Loop to copy values from one sheet and paste the values 68 times in another, time efficiency

Since no information was available about the size of source range being copied
Following grey area in the question is assumed as follows

Since 191 Rows X 68 copy X 3 columns take around 10 minutes only (with you code), the range is about 191 Rows X 15 Columns in size

since it has been claimed that code is working Correctly. The Cells of the range (irrespective of their row or column positions) is being copied in column A only (below one another). Though it contradicts the statement "automate creation of a data table"

Since the cells of the ranges are being copied and pasted. In test case only formulas are copied.
So the code below will just replicate what your code is doing with some increased efficiency. As I personally don't prefer to keep calculations, event processing and screen updating off (in normal cases) i haven't added that standard lines. However you may use these standard techniques, depending on the working file condition. Make necessary changes regarding Range etc

Code takes only 2-3 seconds to complete with  191 Rows X 15 columns X 68 copies:
Sub test()
Dim SrcWs As Worksheet, DstWs As Worksheet, SrcArr As Variant
Dim Rng As Range, cell As Range, DstArr() As Variant
Dim X As Long, Y As Long, Z As Long, i As Long, LastRow As Long
Dim Chunk60K As Long
Dim tm As Double
tm = Timer
Set SrcWs = ThisWorkbook.Sheets("Input Data")
Set DstWs = ThisWorkbook.Sheets("TrialSheet")

Set Rng = SrcWs.Range("A1:O191")
SrcArr = Rng.Formula

LastRow = DstWs.Cells(Rows.Count, "A").End(xlUp).Row + 1
Chunk60K = 0
Z = 1
    For X = 1 To UBound(SrcArr, 1)
    For Y = 1 To UBound(SrcArr, 2)
    For i = 1 To 68
        ReDim Preserve DstArr(1 To Z)
        DstArr(Z) = SrcArr(X, Y)

        If Z = 60000 Then  ' To Overcome 65K limit of Application.Transpose
        DstWs.Range("A" & Chunk60K * 60000 + LastRow).Resize(UBound(DstArr, 1), 1).Formula = Application.Transpose(DstArr)
        Chunk60K = Chunk60K + 1
        Z = 1
        ReDim DstArr(1 To 1)
        Debug.Print "Chunk: " & Chunk60K & " Seconds Taken: " & Timer - tm
        Else
        Z = Z + 1
        End If

    Next i
    Next Y
    Next X

If Z > 1 Then DstWs.Range("A" & Chunk60K * 60000 + LastRow).Resize(UBound(DstArr, 1), 1).Formula = Application.Transpose(DstArr)

Debug.Print "Seconds Taken: " & Timer - tm
End Sub

Edit: With full credit to @TinMan's brilliant suggestion in his comment, the code has been modified (efficiency improved around 65%). The inherent deficiency in the above code is use of ReDim Preserve within the loop has been removed. This enabled use of 2D array and eliminates necessity of transposing the array. Again with many thanks to TinMan and acknowledging full credit to TinMan, The final simplified code as follows.
Sub test()
Dim SrcWs As Worksheet, DstWs As Worksheet, SrcArr As Variant
Dim Rng As Range, cell As Range, DstArr() As Variant
Dim X As Long, Y As Long, Z As Long, i As Long, Lastrow As Long
Dim Repeat As Long
Dim tm As Double
tm = Timer
Set SrcWs = ThisWorkbook.Sheets("Input Data")
Set DstWs = ThisWorkbook.Sheets("TrialSheet")
Set Rng = SrcWs.Range("A1:O191")
SrcArr = Rng.Formula
Repeat = 68
ReDim DstArr(1 To (Repeat * Rng.Count), 1 To 1)
Lastrow = DstWs.Cells(Rows.Count, "A").End(xlUp).Row + 1
Z = 1

    For X = 1 To UBound(SrcArr, 1)
    For Y = 1 To UBound(SrcArr, 2)
    For i = 1 To Repeat
    DstArr(Z, 1) = SrcArr(X, Y)
    Z = Z + 1
    Next i
    Next Y
    Next X

DstWs.Range("A" & Lastrow).Resize(UBound(DstArr, 1), 1).Formula = DstArr
Debug.Print "Seconds Taken: " & Timer - tm
End Sub


Various nitpicks

range(0, x) is better written as range(x)
print(str(i) + " ", end='') is equivalent to print(i, end=' ') but slower
if matches == 0 reads better as if not matches
You compute len(V) several times, just store its value in a variable.
Given that you don't use sep, and that h should already be a string, P,sep,V = str(h).partition(' ') is better written as P, V = h.split()

Special cases aren't special enough to break the rules

Checking for equality between the patient sub-string and the virus is just a sub-case of counting the differences between them (and finding it is 0). Same for comparing the entire patient string and the virus. All are just sub-cases of:

    for i in range(0,upperlimit):
        Psub = P[i:i+len(V)]
        for j in range(0,len(V)): # If we hit this code then, we're about to see how many characters mismatch in the substring
            if Psub[j] != V[j]:
                mismatches += 1
            if mismatches>=2: # No point checking the substrings alphabet by alphabet any further, more than 1 mismatch present here.
                break

Besides, it is to be expected that there will be much more mismatch or fuzzy-matching when checking the substrings than there will be exact matches. So the exact comparison is just slowing you down.

Moreover, you can abuse the fact that booleans are integers and use the sum builtins to compute the number of differences faster:

    for i in range(upperlimit):
        Psub = P[i:i+len(V)]
        mismatches = sum(Psub[j] != V[j] for j in range(len(V)))

Once again, this can be optimized by using zip instead of retrieving letters with their indices in the string:

    for i in range(upperlimit):
        Psub = P[i:i+len(V)]
        mismatches = sum(p != v for p, v in zip(Psub, V))

The advantage of using zip being that the iteration will stop when reaching the end of the shortest string. We can use that to simplify the writting to:

    for i in range(upperlimit):
        mismatches = sum(p != v for p, v in zip(P[i:], V))

Separation of concerns

As it stand, your code does 3 things at once:

iterate over the input data
compute the index of "matching" substrings
print such indexes

You should make functions to separate concerns and make it easier to re-use/test. A basic layout could look like:

def analyze(patient, virus):
    # build indexes where there is a match

def main():
    # iterate over lines in input
    for line in input_string:
        patient, virus = line.split()
        matches = analyze(patient, virus)
        # print output based on `matches`

It makes it more clear to follow what is going on. You then just have to figure out how to return meaningful values from analyze. First thoughts should be to build a list and return it:

def analyze(patient, virus):
    matches = []
    for i in range(len(patient) - len(virus) + 1):
        if sum(p != v for p, v in zip(patient[i:], virus)) < 2:
            matches.append(i)
    return matches

def main():
    # iterate over lines in input
    for line in input_string:
        patient, virus = line.split()
        matches = analyze(patient, virus)
        if not matches:
            print('No match!')
        else:
            print(' '.join(map(str, matches)))

Or you could turn analyze into a generator and convert its computation into a list when calling it. It let you avoid explicitly calling append:

Proposed improvements

def analyze(patient, virus):
    for begin in range(len(patient) - len(virus) + 1):
        if sum(p != v for p, v in zip(patient[begin:], virus)) < 2:
            yield begin

if __name__ == '__main__':
    T = int(input())

    for _ in range(T):
        patient, virus = input().split()
        matches = list(analyze(patient, virus))
        if not matches:
            print('No Match!')
        else:
            print(' '.join(map(str, matches)))

The advantage of using a generator is that you don't even have to convert it to a list, your original prints work as well:

    for _ in range(T):
        patient, virus = input().split()
        matches = 0
        for index in analyze(patient, virus):
            print(index, end=' ')
            matches += 1
        if not matches:
            print('No match!')
        else:
            print()

Or you can convert the matches on the fly:

    for _ in range(T):
        patient, virus = input().split()
        matches = ' '.join(map(str, analyze(patient, virus)))
        if not matches:
            matches = 'No match!'
        print(matches)


Remove sections of content from Quora.com

Interesting question,

I would place the bulk of your comments on top, they stop the flow of the reading
I would experiment with $.remove() instead of $.hide();, otherwise you might actually run into memory and performance problems. I am thinking that with $.remove() you might not even need the timeouts any more.
Manifest looks fine
Your indenting is off, use something like jsbeautifier
This is shorter and more readable

$("span:contains('Top content on Quora')").closest('.pagedlist_item').hide();

than

var $topContent = jQuery("span:contains('Top content on Quora')").closest('.pagedlist_item');
$topContent.hide();


You cannot change the type of the input field on client side in some or all browsers. I would create a custom hiding method in Javascript and leave the input type in text mode (SingleLine), but maybe this has some drawbacks in security.

Other solution is to remove the original input and create a new one on the fly with Javascipt but i think not all browser will let you to read out the value of a password type input.

Third version is to send the field to the server side and get back the new HTML fields but in this way you may send multiple times the password to the server which can be a security hole.


Which solution of the two is the most efficient? Is there a better one? (IP Address Defang)

If you are in an interview using Python, assume that the interviewer is
reasonable and wants you to write fluent Python code. That means, among
other things, taking advantage of the language's built-in powers:
def defrang(ip):
    return ip.replace('.', '[.]')

But let's suppose that the interviewer explicitly directs you to ignore
built-ins and write your own implementation that does the work
character-by-character. Your current implementation is reasonable, but I would
suggest a few things. (1) Especially at interface points (for example, a
function's signature) use substantive variable names when they make sense. (2)
Don't make the caller re-assemble the IP address. (3) There is no need to
use concatenation to create a literal: just use '[.]' directly. (4) The logic is
simple enough for a compact if-else expression (this is a stylistic judgment, not a firm opinion).
def defang(ip_address):
    chars = []
    for c in ip_address:
        chars.append('[.]' if c == '.' else c)
    return ''.join(chars)

A final possibility is to distill further and just use a comprehension.
def defang(ip_address):
    return ''.join(
        '[.]' if c == '.' else c
        for c in ip_address
    )


User defined string literals and namespace use

I would follow the way user-defined literals are used in the C++14 standard library: put them in a literals subnamespace that can be imported by the user. This subnamespace would be inline so that it can be imported alone, or automatically imorted when the namescape net is imported:

namespace net {
    class uri { ... }; // contains decomposed URI (path, parameters, etc)

    uri parse_uri(const std::string& uri_str); // parse string and return uri instance

    inline namespace literals
    {
        uri operator "" _uri(const char*str, const unsigned long size)
        {
            return net::parse_uri(std::string{str, str + size});
        }
    }
}

Then, a client code could use your literal with the following code:

int main()
{
    // Import only the literal, not the rest of net
    using namespace net::literals;

    auto x = "/static/path/here/image.jpg"_uri;
}

I actually slightly simplified the way user-defined literals are used in the standard library for your example: there are actually nested inline namespaces in namespace literals so that a more precise selection of related literals can be done if needed (for example, import only the std::chrono-related literals). Since you have only one literal, you don't need to have so many nested namespaces, but you can still add them later if needed.


Checking the difference between old and new XML

Your code seems simple and how it works is clear enough. I only have a few remarks:

This line seems a little bit off:

#include "include/pugixml.hpp"

Generally speaking, in C and C++, libraries provide an include dir that has to be added to the search directories so that we can write:

#include "pugixml.hpp"

While it certainly does not make your code invalid, it makes it feel a bit less pedantic.
Your code currently does not handle parsing errors. See pugi's documentation for more information about that.
Now, let's have a look at your set operations. We will use the following diagram to simplify the explanation:

You are currently computing \$A \setminus B\$ and \$B \setminus A\$, then \$A \cap B\$ (where \$A \setminus B\$ represents the difference between \$A\$ and \$B\$). Technically speaking, it would be faster to compute \$A \cap B\$ first then to compute \$A \setminus (A \cap B)\$ and \$B \setminus (A \cap B)\$ since it would mean fewer elements to compare in the sets (there are fewer elements in \$(A \cap B)\$ than there are in \$A\$ or in \$B\$).

In other words, your code should be:

str_set a_and_b;
std::set_intersection(a.begin(), a.end(), b.begin(), b.end()
    , std::inserter(a_and_b, a_and_b.begin()));

str_set b_from_a;
std::set_difference(a.begin(), a.end(), a_and_b.begin(), a_and_b.end()
    , std::inserter(b_from_a, b_from_a.begin()));

str_set a_from_b;
std::set_difference(b.begin(), b.end(), a_and_b.begin(), a_and_b.end()
    , std::inserter(a_from_b, a_from_b.begin()));


Point distance program written without a framework

It's an interesting idea to write Windows code in Objective-C. If you were using NeXTStep frameworks (or GNUStep) it would make a little more sense. I don't understand your desire to avoid frameworks,  which tend to be force multipliers saving you time and effort. (And of course, you are using OpenGL and GLFW, so this seems like an arbitrary choice.) Regardless, given those constraints, here are my thoughts.
Language
In my opinion Objective-C is the wrong choice for this particular project. I say that as someone who makes a living programming largely in Objective-C. The problem, as I see it, is that you lose 2 important things that you would get from other languages:

The ability to use objects or structs for doing your work and passing them directly to OpenGL/GLFW.
The ability to use operator overloading.

OpenGL expects to receive geometry as an array of vertex attributes (or several different arrays – one for each attribute). That's going to be impossible using the class as you've written it. Each Objective-C object is its own entity on the heap. If  you have an array of them, it's really just an array of pointers to the objects, which may or may not be contiguous in memory. You won't be able to just call glVertexAttribPointer() or other similar functions and pass a pointer to the array since the array will just be an array of other pointers. In C you'd have an array of Point structs either on the stack or the heap and could just pass the address of the first element to the above function. Likewise with something like a C++ std::vector<Point> you'd be able to pass the address of the first element (assuming Point had no v-table). In addition to  making it harder to send  the data to the GPU, it also makes processing the data on the CPU slower because you lose cache coherency when the data isn't contiguous.
You'll also want to do math on your Point objects. While you can write methods on your Objective-C class to add, subtract, etc., it's not as natural as using a language that allows you to overload operators. In particular, C++ and Swift both allow this and it makes writing graphics code feel much more natural.
Class
This class is rather thin. It doesn't do very much that's useful. What it does do, it appears to do correctly. It might be useful to swap the sqrt() call with a call to hypot(x,y) instead.
At a minimum, if you're doing 2D graphics, you'll probably want to add the following methods:
- (void)add:(Point*)p;
- (void)subtract:(Point*)p;
- (float)dotProduct:(Point*)p;
- (void)normalize;
- (void)multiplyScalar:(float)s;
- (void)multiplyVector:(Point*)p;
- (void)divideScalar:(float)s;
- (void)divideVector:(Point*)p;

And eventually, you'll probably want a Matrix class for things like scaling and rotation operations.


Should I write my fadeTo function differently?

Well written animation functions typically use a tweening algorithm that checks the system clock to see how much time is actually remaining in the originally specified time allotment and then adjusts the animation increment to put things back on time, even if the timer events weren't coming in exactly on time or the browser was super busy and you weren't getting all the cycles you might want or the host CPU just isn't very fast.  Done well, this can even allow you to adjust the step value for smoother animations on more capable computers and coarser steps on less capable computers.

As you have it, you have a hard coded step function in time of 1/10th the time and thus 1/10th the total opacity change.  On capable computers, you can run much, much smoother than this.

Here's an example:

function now() {
    return new Date().getTime();
}

function fadeTo(obj, time, to, doneFn){

    // sanitize optional arguments
    if ( typeof time === "undefined" )
        time = 1000;
    if ( typeof to === "undefined" )
        to = 1;

    if ( time <= 0 )
        return true;

    var objSt = obj.style,
        originalOpacity = parseFloat(getComputedStyle(obj, null).getPropertyValue("opacity")),
        deltaOpacity = to - originalOpacity,
        sanitizeOpacity,
        minT = 30,
        startTime = now();

    // based on whether we're going up or down, set our santize function
    if (deltaOpacity > 0) {
        sanitizeOpacity = function(x) {
            // not more than 1
            return Math.min(x, 1);
        }
    } else {
        sanitizeOpacity = function(x) {
            // not less than zero
            return Math.max(x, 0);
        }
    }

    function step() {
        // calculate how much time has elapsed since start
        // and then calculate what the opacity should be set
        // to for the animation to be perfectly on time
        var elapsed = now() - startTime, completion;

        // if all our time has elapsed, then just set to final opacity
        if (elapsed >= time) {
            objSt.opacity = to;
            // we're done, call the completion function
            // with the this pointer set to the object that was animating
            if (doneFn) {
                doneFn.apply(obj);
            }
        } else {
            // still some time remaining
            // calculate ideal opacity value to be "on time"
            completion = elapsed/time;
            objSt.opacity = sanitizeOpacity((deltaOpacity * completion) + originalOpacity);
            // schedule next step
            setTimeout(step, minT);
        }

    }
    // start the animation
    setTimeout(step, minT);
}

Working demo: http://jsfiddle.net/jfriend00/hG3Wj/

In other comments:

You MUST use var in front of variables that should be local variables.
You need to be getting the original opacity as the computedStyle, not just reading opacity directly because you need to include style sheet opacity, if nothing is set directly on the object.
If you want to know if an argument is truly undefined, you need to use === to test for it so there can be no automatic type conversions.
I find it more efficient to define an inner function that is called repeatedly because then all of our argument sanitization and what/not only has to happen once, not on each iteration and we can have state variables in the outer closure.


You are not overloading the new operator correctly.
See: How should I write ISO C++ Standard conformant custom new and delete operators?
But you should not be overloading new at all.
All the work you are doing here is stuff that goes in the constructor.
The sole job of the new operator is to allocate memory (not initialize it).
As a side note:
Though you can actually add parameters to new.
Doing so is not a good idea.
As it is not normal, and thus makes it harder to maintain.
The code above will be called if you do:
// Note: The first parameter (ie size) will be auto inserted as the first parameter.
Info* data = new ("File Name", 12) Info;


Passing an entity to use it's fields to update method is ok to do?

The second one seams to me a better approach but you say that the ManID is a primary key, so why are you handling it as a non primary key and using the query result as a sequance?

public DbResult Update(int idToLookFor, string newName)
{
    return Update(_MyDBEntities.Men.Single(p => p.ManID == idToLookFor), newName);
}

public DbResult Update(Man person, string newName)
{
    try
    {
        person.Name = newName;
        //saving missing?
        return DbResult.Success("Record updated");
    }
    catch (Exception e)
    {
        return DbResult.Failed(e.ToString());
    }
}

And the real saving missing or it's placed to elsewhere so why are you setting here the DbResult?


Your code looping over string functions doesn't seem like something SQL Server is optimized for.

Database systems are optimized for set based operations, not looping. I understand the confusion coming from procedural/Object Oriented languages, but in the end SQL isn't a programming language in it's classical form but a way to instruct an RDBMS what data you need.

Also, UDF's do all sort of weird things with execution plans, like hiding the actual cost in a plan, and often removing the option to choose a parallel plan for the optimizer.

I wouldn't try to roll my own UDF for something like this.

The best way IMO would be to figure out a way to do it inline or set based.
I don't have any sample data and expected output to work with but I could imagine a

UPDATE [table]
SET [url] = REPLACE([url], 'base_url', 'new_url')
WHERE [url] LIKE '%<regex>%';

kind of construct

You might even do it in the application code (such as retrieving a datatable, fixing the data and saving the datatable again).

If you insist on doing it in a function I'd just either write a SQLCLR function or go and download the sqlsharp library and use that.

If you are worried about performance then read the article posted by the creator of the library comparing performance.

I highly doubt your implementation will work better or faster than a .NET regex solution.


Regex to match several slightly different strings

This isn't so much a Python question as it is a RegEx question.  The Python tag is almost irrelevant.
'+' -vs- '*'
You regex includes two alternates:

(?:20\d\d#\d{1,3}(?:,\d{1,3})+)
(?:20\d\d#\d{1,3})

The difference in these expressions is the first one include one or more repeats of ,\d{1,3}, where as the second does not include any repeats of that ...
... in other words, you have 20\d\d#\d{1,3} followed by 0 or more repeats of ,\d{1,3}.
So we can replace the + modifier with the * modifier, and the pair of alternates becomes simply
(?:20\d\d#\d{1,3}(?:,\d{1,3})*)
Common prefix
All three (or rather, both now that the last two have been combined into one) regex's start with 20\d\d#.  You can factor this out of both patterns.
20\d\d# (?: (?: \d{1,3}-\d{1,3} | \d{1,3}(?:,\d{1,3})* ) )
Capture Groups
There is no point creating a capture group for the entire regex expression.  The entire match is always captured, as group 0.
Reworked Regex & Example
The regex can be rewritten as:
r"20\d\d#(?:(?:\d{1,3}-\d{1,3}|\d{1,3}(?:,\d{1,3})*))"
which is shorter, but is still quite unreadable.  It is better for future programmers at the charity (as well as for yourself) to document the regex using the re.VERBOSE option.  I find it clearer than comments below the regular expression that try to document the parts of the regular expression through vertically lined up notes.
Note: Since comments follow the octothorpe (#) character in re.VERBOSE mode, we need to escape it (\#) to indicate that it is actually a character we want matched, and not the start of a comment.
import re

JOB_PATTERN = re.compile(r"""
                          20\d\d                     # A 4-digit year
                          \#                         # followed by a hash mark
                          (?:                        # followed by either ...
                             (?:\d{1,3}-\d{1,3})        # a range of serial #'s
                             |                          # or
                             (?:\d{1,3}(?:,\d{1,3})*)   # a list of serial #'s
                          )""", re.VERBOSE)

test_cases = ["junk2021#123-45bar",
              "baz2021#003,5,07,89,131foo"]

for test_case in test_cases:
    m = JOB_PATTERN.search(test_case)
    if m:
        print("Found:", m[0])

Output:
Found: 2021#123-45
Found: 2021#003,5,07,89,131

Update
Based on the OP's response to RootTwo's comment, named capturing groups are actually desired.  Here is an updated example with RootTwo's enhancement:
import re

JOB_PATTERN = re.compile(
    r"""(?P<year>              # Capturedas "year" ...
           20\d\d                 # a 4-digit year
        )
        \#                     # followed by a hash mark
        (?:                    # followed by either ...
           (?P<range>             # captured as "range" ...
              \d{1,3}-\d{1,3}        # a range of serial #'s
           )
           |                      # or
           (?P<list>              # captured as "list" ...
               \d{1,3}               # a serial number
               (?:,\d{1,3})*         # or list of comma-seperated serial #'s
           )
        )
        """, re.VERBOSE)

test_cases = ["junk2021#123-45bar",
              "baz2021#003,5,07,89,131foo"]

for test_case in test_cases:
    m = JOB_PATTERN.search(test_case)
    if m:
        if m.lastgroup == "range":
            start, end = m['range'].split('-')
            print("Year:", m['year'], " from", start, "to", end)
        else:
            serial_numbers = m['list'].split(',')
            print("Year:", m['year'], " serial #':", serial_numbers)

Output:
Year: 2021  from 123 to 45
Year: 2021  serial #': ['003', '5', '07', '89', '131']


Is there a better SQLite update / insert pattern than this?

The second code block is the clunky one, it has repetition which the first one doesn't. If you wanted to refactor the first example you would need to go higher up and do the check for existing record before you make the call to save or update then have a method for save and one for update, but this would lead to some duplicate code.

From what you have posted I'd stick with the first one.


First of all it is a pretty wide-spread convention in ruby to use 2 spaces for indendation not 4. Personally I don't care, but there are some ruby developers who will complain when seeing code indented with 4 spaces, so you'll have an easier time just going with the stream.

file = ARGV.shift

Unless there is a good reason to mutate ARGV (which in this case doesn't seem to be the case), I'd recommend not using mutating operations. file = ARGV[0] will work perfectly fine here.

match = l[pattern]
if match
    list = split_file[$1]
    list = [] if list == nil
    list << l
    split_file[$1] = list
end

First of all you should avoid using magic variables. Using MatchData objects is more robust than using magic variables. As an example consider this scenario:

Assume that you decide you want to do some processing on the line before storing it in split_file. For this you decide to use gsub. Now your code looks like this:

match = l[pattern]
if match
    list = split_file[$1]
    list = [] if list == nil
    list << l.gsub( /some_regex/, "some replacement")
    split_file[$1] = list
end

However this code is broken. Since gsub also sets $1, $1 now no longer contains what you think it does and split_file[$1] will not work as expected. This kind of bug can't happen if you use [1] on a match data object instead.

Further the whole code can be simplified by using a very useful feature of ruby hashes: default blocks. Hashes in ruby allow you to specify a block which is executed when a key is not found. This way you can create hash of arrays which you can just append to without having to make sure the array exists.

For this you need to change the initialization of split_file from split_file = {} to split_file = Hash.new {|h,k| h[k] = [] }. Then you can replace the above code with:

match = l.match(pattern)
if match
  split_file[ match[1] ] << l
end

  One thing I noticed is that the new files are created in the same directory as the original file, not at the current working directory (so ./logsplitter.rb ../log.log creates files in the .. directory).

If you want to avoid that use File.basename to extract only the name of the file without the directory from the given path and then build the path of the file to be created from that. I.e.:

File.open("#{ File.basename(file) }.#{k}", "a+") do |f|

Speaking of this line: I don't see why you use "a+" instead of just "a" as the opening mode - you never read from it.


Using sed regular expression to extract domain name from file

When processing tabular data in columns, awk is often a more appropriate tool to use.  The equivalent command would be

awk '{ sub("\.$", "", $NF); print $NF }' test

… which I think is more readable.

Explanation:

NF is the number of fields: for this text, 5.
$NF is the content of the last (5th) field.
sub("\.$", "", $NF) strips the trailing dot from the last field.
{ commands } executes the commands for every line in the file.


First off I have to say I found this code very hard to understand. It took me quite some time to finally understand what this code actually does.

First off the function takes 6 arguments. That's way too many. Clearly the positionX and positionY should be combined into one Point object.

But the larger problem is, that you seem to be working at the wrong level of abstraction. The function is supposed to deal with one single row of a FT_Bitmap, but because there is no abstraction of such a single row, it ends up dealing with the whole FT_Bitmap, doing confusing offset calculations all over the place.

What I would do first, is to create a separate GlyphRow class:

public class GlyphRow
{
    private FT_Bitmap bitmap;
    private int offset;

    public int Width;

    public GlyphRow(FT_Bitmap bitmap, int rowIndex)
    {
        this.bitmap = bitmap;
        this.offset = rowIndex * bitmap.Width;
        this.Width = bitmap.Width;
    }

    // Returns the transparency value of a point in position x of our row
    public byte Alpha(x)
    {
        return bitmap.Buffer[offset + x];
    }

}

This will allow us to work with a single row at a time.

Now our function can take just the following arguments:

private static void drawGlyphRowToGraphics(
    GlyphRow row, Graphics graphics, Point position, SolidBrush brush)

And when calling it, we initialize Point and GlyphRow objects:

GlyphRow row = new GlyphRow(glyphBitmap, rowIndex);
Point position = new Point(positionX, rowIndex + positionY);
drawGlyphRowToGraphics(row, graphics, position, brush);

Note that the position is now exactly the position where this GlyphRow should be painted, already offset with rowIndex.

So here's the new simplified drawGlyphRowToGraphics:

private static void drawGlyphRowToGraphics(
    GlyphRow row, Graphics graphics, Point position, SolidBrush brush)
{
    int i = 0;
    while (i < row.Width)
    {
        int length = sameAlphaLength(row, i);
        brush.Color = cloneColorWithAlpha(brush.Color, row.Alpha(i));
        graphics.FillRectangle(brush, position.X + i, position.Y, length, 1);
        i += length;
    }
}

I found the algorithm in original implementation very hard to grasp, so using divide-and-conquer strategy, I created a separate function to calculate the length of a section that has the same transparency value:

private static int sameAlphaLength(GlyphRow row, int start)
{
    byte alpha = row.Alpha(start);
    int length = 1;
    while (start + length < row.Width)
    {
        if (alpha != row.Alpha(start + length))
        {
            return length;
        }
        length++;
    }
    return length;
}

In the original code, at first the gray value was calculated with (255 - alpha), and then passed to updateAlpha, where it was again transformed with (255 - gray). Pretty redundant IMHO. So I'm skipping this whole double-conversion. I also find it better to work with functions without side-effects, so I replaced updateAlpha with a function that creates a new color value from an existing one, which I can then assign to brush:

private static Color cloneColorWithAlpha(Color color, byte alpha)
{
    return Color.FromArgb(alpha, color.R, color.G, color.B);
}

Disclaimer: I've never written a single line of C# before. It probably doesn't compile, not to mention other possible bugs. But hoping to get the general point across.


I would tend to agree with Adrian's comment that you might be better off finding some lightweight / micro ORM to start from, if bigger things such as EF or NHibernate aren't options for you.

Still, if you really want to go all the way long your own route with generics, then, FWIW, I'd probably put it along the lines of something like:

(just a rough, compilable sketch; untested, clearly not thread-safe, with no provisions or hints on how to go from the DataTables to your DB engine's SQL, etc)

public interface IStore<TItem>
{
    TPersistent Deserialize<TPersistent>(TItem item)
        where TPersistent : class, new();

    TItem Serialize<TPersistent>(TPersistent instance)
        //if only for consistency with Deserialize:
        where TPersistent : class, new();
}

public interface IPersistence<TStore, TItem>
    where TStore : IStore<TItem>
{
    void Add<TPersistent>(TPersistent instance)
        //if only for consistency with GetById, or other various
        //Getters/Finders/Selectors:
        where TPersistent : class, new();

    TPersistent GetById<TPersistent>(long id)
        where TPersistent : class, new();
}

public abstract class Persistence<TStore, TItem> : IPersistence<TStore, TItem>
    where TStore : IStore<TItem>
{
    protected abstract TItem Get<TPersistent>(long id);

    protected abstract void Insert(TItem item);

    // Useful to use TStore here (and not just IStore<TItem>) to allow for
    // type-safe internal friendship between the store and persistence implementations later on,
    // if needed
    protected TStore Store { get; private set; }

    protected Persistence(IStore<TItem> store)
    {
        // Note we *want* this to barf at construction time,
        // if it turns out that store (the parameter)
        // does not conform to TStore
        Store = (TStore)store;
    }

    void IPersistence<TStore, TItem>.Add<TPersistent>(TPersistent instance)
    {
        Insert(Store.Serialize(instance));
    }

    TPersistent IPersistence<TStore, TItem>.GetById<TPersistent>(long id)
    {
        return Store.Deserialize<TPersistent>(Get<TPersistent>(id));
    }
}

/// <summary>
/// Friend of DataTablePersistence (via its internal DataSet)
/// </summary>
public class DataTableStore : IStore<DataRow>
{
    internal readonly DataSet DataSet;

    internal DataTable EnsureTable(Type instanceType)
    {
        var tableName = instanceType.Name;
        DataTable table;
        if (!DataSet.Tables.Contains(tableName))
        {
            table = new DataTable(tableName);
            //(left to-do) also define the table schema (columns),
            //after what instanceType tells us
            DataSet.Tables.Add(tableName);
        }
        else
        {
            table = DataSet.Tables[tableName];
        }
        return table;
    }

    public DataTableStore()
    {
        DataSet = new DataSet();
    }

    TPersistent IStore<DataRow>.Deserialize<TPersistent>(DataRow item)
    {
        var instance = new TPersistent();
        //e.g., use System.Reflection to hydrate instance (from item)
        return instance;
    }

    DataRow IStore<DataRow>.Serialize<TPersistent>(TPersistent instance)
    {
        var table = EnsureTable(instance.GetType());
        var item = table.NewRow();
        //e.g., use System.Reflection to dehydrate instance (into item)
        return item;
    }
}

/// <summary>
/// Friend of DataTableStore (via DataTableStore's internal DataSet)
/// </summary>
public class DataTablePersistence : Persistence<DataTableStore, DataRow>
{
    protected override DataRow Get<TPersistent>(long id)
    {
        var table = Store.EnsureTable(typeof(TPersistent));
        return table.Rows.Find(id);
    }

    protected override void Insert(DataRow item)
    {
        // presumably, item was created by some DataSet[<table name>].NewRow(),
        // so, it already knows the table in which it ought to be inserted
        item.Table.Rows.Add(item);
    }

    public DataTablePersistence()
        : base(new DataTableStore())
    {
    }
}

public class Program
{
    public class Person
    {
        public long Id { get; set; }

        public string First { get; set; }

        public string Last { get; set; }
    }

    public class Asset
    {
        public long Id { get; set; }

        public string Category { get; set; }

        public string Name { get; set; }
    }

    public static void Main(string[] args)
    {
        IPersistence<DataTableStore, DataRow> persistence = new DataTablePersistence();

        persistence.Add(new Person { First = "John", Last = "Smith" });

        persistence.Add(new Asset { Category = "Vehicle", Name = "Cadillac" });

        var john = persistence.GetById<Person>(1);

        var asset = persistence.GetById<Asset>(1);

        //etc, etc
    }
}

Finally, it'll get more interesting (challenging) if you want to support dehydrating (i.e., emitting SQL insert/update/delete) arbitrary object graphs where some instances are transient/freshly created, while others come with their existing keys from your underlying DB, etc)

'Hope this helps.


Using an instance of PDO class as global variable inside 'query' methods

Use global scope for as little as possible. EVER.

Explicitly passing the connection it into the method is always the safe and happy.  It allows for better testing by adhering to dependancy inversion principles.

You could also do it inside of the constructor if the the connection doesn't change during the life of the object, but I'm not a fan of this--I'd prefer a intitial() method to be called after instantiation or explicitly setting it with a set_connection() method.


Outputting all possible words which fit a string of letters

I would have used patterns and pattern in main instead of words and word to avoid confusion with the words of vocabulary.


Limiting the number of text fields created

Bored, so I made a few improvements as I mentioned (in the comments that have vanished when this was moved to Code Review):

Use the jQuery shortcut DOM-ready handler

A handy short-cut for your DOM ready, with locally scoped $ is just jQuery(function($){...});

Store templates in HTML, not JavaScript strings:

and access like this:

var box_html = $('#template').html().replace(/{n}/g, n).replace(/{-1}/g, n-1);
var $box = $(box_html);

Count the current items when you need them

var n = $('.text-box').length + 1;
if (n <= max_fields) {

Restrict to the current "group" of inputs:

var $form = $(this).closest('.my-form');
$('p.text-box:last', $form).after($box);

This also means it can now handle multiple sets of inputs, each with different name/id prefixes.

Combine operations when you can:

$box.hide().fadeIn('slow');

Putting it all together:

JSFiddle: http://jsfiddle.net/TrueBlueAussie/q2emvzdd/4/

Notes:

A prefix was needs to be supplied by the parent form (e.g. a data attribute) so that each set of inputs has unique IDs and names. This is not applied to the first entry yet, but I have to go now, so something for you to finish :)


First, don't call it gets_s as the signature and behavior differs in some subtle and not-so-subtle ways, that just leads to confusion and frustration. Anyway, you really wouldn't want the gets_s-contract.
Call it something descriptive like getline_truncated.

Do you know that n <= 0 is UB in your implementation?

if (temp == EOF || temp = '\n')
                        ^

I'm sure your compiler warns you about the typo above.
Or don't you ask it for all warnings (-Wall -Wextra -std=...)?

I suggest re-defining and re-naming your return-codes to allow better result-testing:

#define GETS_S_TRUNCATED 1
// Because truncation is not neccessarily an error
#define GETS_S_OK 0
#define GETS_S_ERROR EOF
// Because we already have an appropriate negative constant

This way you can test for ==0 or >=0 depending on what you decide is "success", respectively !=0 or <0 for "failure".


Calculating frequency of a note from a string

Overall this is pretty readable code. It's straightforward to understand, so it would be fairly easy to maintain or debug if there were found to be problems.
Table-driven Development
If you look at the various case statements within your switch you'll notice that they all take the same form, just with different values. This indicates that it might be a good idea to use a table of values to reduce the amount of code. I would build a table of the number of semitone change for each note like this:
int kSemitoneOffsets[] = { -2, 0, 2, 4, 5, 7, 9 };

In the natural case where there are no accidentals (sharps or flats) applied, every case from your switch statements breaks down to this:
frequency = a4Frequency / pow(2, (kSemitoneOffsets [ index ]  / 12));

Here index is calculated from the key character. If we don't mind rearranging the above table so it progresses from A up to G, it ends up looking like this:
int kSemitoneOffsets[] = { 0, -2, 9, 7, 5, 4, 2 };

Now you can calculate the index like this:
int index = key - 'A';

Next, we can handle accidentals by adding or subtracting 1 from the lookup. Putting it all together, it looks like this:
int kSemitoneOffsets[] = { 0, -2, 9, 7, 5, 4, 2 };
int index = key - 'A';
int numOfSemitones = kSemitoneOffsets [ index ];
if (flat)
{
    numOfSemitones--;
}
else if (sharp)
{
    numOfSemitones++;
}
frequency = a4Frequency / pow(2, (numOfSemitones / 12));

Notice that I changed the calculation for B from a multiplication to a division so it was the same form as the other calculations. This is possible because raising a number to a negative power is the same as dividing by that number raised to the positive power.
We can use this same trick to calculate final without the if statement, like this:
final = round(frequency * pow(2, octave - 4));

When octave is less than 4, we get a negative number and end up dividing. When it's 0, we get 1 so the multiplication does nothing.
Remove Unnecessary Code
In addition to switching to using a table, you can also remove unnecessary code. For example the if statement you use to check if the user specifically entered A4. That code is unnecessary because you will correctly calculate the value using the rest of your code. Unless this function is being called inside some tight inner loop, its speed isn't a concern, so that optimization is not very helpful.
Avoid Magic Numbers
Your code also has a bunch of magic numbers. These are hard-coded values in the code that have no indication what their purpose is. You should create named constants for these. You have one for 440Hz, but the values of the semitone offsets are a bit mysterious. In my code I put them in a table with a name so it's more obvious what they are. But in general, values other than 0 or 1 should have a name. I would also comment the relationship of 2^(numSemitones / 12) as it would be non-obvious to people who haven't studied the physics of Western music.
Nitpicks
One other thing I noticed is that in your code you didn't handle the cases of Fb, Cb, E#, or B#. These are valid notes that you'll want to handle. They don't come up often, and they are synonyms (at least in equal temperament) for E, B, F, and C, but they are legit, so I'd recommend handling them. (And if you want to get really technical, you could handle double sharps (Ax4, for example), and double flats (Bbb3, for example).)


I'm not going to comment on the algorithm or functionality, however, there are several aspects in this code that make it very hard to read and understand.

Strange variable naming:

Most programmers associate names in ALL_CAPS with macros and constants (Windows programmers might also like that notation for typedefs), which makes them very unsuited for variable and parameter names. X_OFFSET, STRING, and the others would be much better as x_offset, string, and so on.

Unused parameter:

BYTE CLRSPACE[][3] is not used by the function. Should be removed or at least referenced with a (void) to suppress compiler warnings:

{
    (void)CLRSPACE;
    ...

Too many things in a line:

You have no idea how these lines combining several statements can hurt readability. A few instances:

char *buffer = STRING, *font; int xo = X_OFFSET, yo = Y_OFFSET;
...
fseek(fp, EOF, SEEK_END); fontsize = ftell(fp); font = malloc(fontsize); rewind(fp);

A much clearer layout:

char *buffer = STRING, *font;
int xo = X_OFFSET, yo = Y_OFFSET;
...
fseek(fp, EOF, SEEK_END);
fontsize = ftell(fp);
font = malloc(fontsize);
rewind(fp);

Inconsistent statement layout:

You have different ways of indenting and positioning your control statements.
This one in particular is very awkward:

if
(font[chrOffset+linep] == '#') { colp++; line = 0; }
else if
(font[chrOffset+(linep+1)] != '#')  // if not NL and w/o ending supplement:
{
    ...
}

Re-arrange that to a more natural way an be consistent with all your code:

if (font[chrOffset+linep] == '#')
{
    colp++;
    line = 0;
}
else if (font[chrOffset+(linep+1)] != '#')  // if not NL and w/o ending supplement:
{
    ...
}

Here, at the end of the function, another strange arrangement:

    } free(font);
    return;
}

free(font) should be in its own line. The return is not necessary, as this is a void function.

Mysterious statement:

It seems that in here:

int chrOffset, chr = 32; _ = chrOffset;

You have declared (or re-assigned) a variable named _. I have no idea what that is supposed to mean, as there are no further references to _. A variable named _ is already pretty bad by itself. This code here, I'm not even sure if it would compile...

There are probably more aspects to consider, but that's all I can tell you for now. Hope the advices are useful.


Building a profile image with a fly-out menu in the header

I've reviewed your code and I can make the following remarks:

CSS rules

I dont find your css particularly bad its just you need to think how the rules can fit each other logically with the css class names you assign to. Lets go in depth:

.header {
  width: 1000px;

Why did you hardcode 1000 px here? If you don't know the width sizes of the screen you want to target its better if you give it full width like width: 100% and if you want some minimum widths so things will not collapse you can add a rule like min-width: 700px

.animation-fade-out{
  animation-duration: 333ms;

.fly-over ul li {
  transition: color, background-color 333ms;

I would certainty reduce the animation duration of those 2 to be no more than 0.2s.If you notice the transitions are too fancy and they don't look appealing to the eye. Use a smaller duration to make them smoother.

.fly-over{
  display: none;
  width: 300px;
  border-radius: 5px;
  box-shadow: 1px 1px 10px 1px rgba(0,0,0,.3);
  text-align: left;

  position: absolute;
  right: 36px;
  top: 80px;
}

My main concern on this class is the last 3 rules  about positioning. Why did you choose to mix positions with decorations in the same class? It makes it more difficult to reuse its a one off. It may not be bad for small apps but for larger ones this really counts.

If I were to took they fly-over class and use it on another element I would have to override the positioning with a new class which would add too much bloat. A better solution is to make this class a little more generic and name it like fly-over-menu and add another class a little more specific named profile-menu with the positioning rules. That way I can reuse the fly-over-menu in other places.

background-color: #888888;
color: white;

I don't like mixing color code names with hex values. Pick one preferred representation and stick with it. That way the code will be more consistent.

Now lets focus on the Javascript:

Global state pollution

var menuState = {
  visible: false
};

Why did you choose to save state here? As you will read bellow the state actually is saved in the element classlist. If the element has a class show its visible otherwise its hidden provided that it has display:none by default.

And one other thing What are you saying here is hey I want to save this object to the global namespace and add one property visible to it. You will literally have window.menuState = {visible: false}; Why do you want to save something so specific in a global object?

You really don't want to do that. What if you had 10 of those menus? You had to change the representation of the state object every time. And if you wanted more variations of it like poping-menu or something you would have to add more objects. State management in Javascript is still behind so try to be a little bit more resourceful with what you have.

DOM manipulation

el.addEventListener('click', function(){
  var flyOverEl = document.getElementsByClassName("fly-over")[0];
  function onFadeInAnimationEnd(){
    this.classList.add('show');
    this.classList.remove('animation-fade-in');
    menuState.visible = true;
    this.removeEventListener('animationend', onFadeInAnimationEnd);
  }

  function onFadeOutAnimationEnd(){
    this.classList.remove('animation-fade-out');
    menuState.visible = false;
    this.removeEventListener('animationend', onFadeOutAnimationEnd);
  }

 if(menuState.visible){
    flyOverEl.classList.remove("show");
    flyOverEl.addEventListener("animationend", onFadeOutAnimationEnd)
    flyOverEl.classList.add("animation-fade-out");
 }
 else{
    flyOverEl.addEventListener("animationend", onFadeInAnimationEnd)
    flyOverEl.classList.add("animation-fade-in");
 }

})

Oh boy. I don't mind using plain javascript for simple things but did you notice while typing this code that you are repeating yourself? I did just by reading it. What you are really doing here is this. You just toggling class names of the fly-over element depending if the element is visible or not. You also hook the animationend events that are getting fired once the animation is completed to just clean up the event listeners.

I don't think its too bad but to be honest I believe its too low level. You want something more abstract and simplified when dealing with DOM events and callbacks. so to have time to work on more interesting things. If were you I would use jQuery to handle all of this staff don't get me wrong but also I think its safer.Its more of a personal preference this one so you can ignore it.

However check out this line:

var flyOverEl = document.getElementsByClassName("fly-over")[0];

You are lucky here that you have only one element with that class in the document. If you were to add more than one you would see flying ponies.

Also note that the query selector for the fly-over is the only specific thing here and its better if its passed as a parameter using bind or wrap the function in a wrapper and apply the callback with the arguments. That way you can pass whatever class you like in the event callBack. I will leave that as an exercise.

In general I think you are working it well its just some peculiarities of the front-end development you need to understand better.


This problem is much easier looking it backwards: Instead of processing the input in the order given, process it in reverse order. You know the last number in your answer will be 1, because no numbers follow it. Now the previous one could be a 2 if the sign is different with the last one or a 1 if its the same sign.

So basically, each step back can either add 1 to the list of consecutive numbers with alternating signs or reset the count to 1.

The code:

    length=(raw_input())
    st = map(int,reversed(raw_input().split()))

    answ = []
    count = 0
    for i, num in enumerate(st):
         count += 1
         if i > 0 and (num < 0) == (st[i - 1] < 0):
            count = 1
        answ.append(str(count))

    print " ".join(reversed(answ))


My question is simple: is this secure?

It's safe from SQL injection attacks.

  If many people buy at the same time can I have problems?

Since you insert the order and the cart contents in a transaction, the table will be locked until you have inserted everything, preventing other users from placing their orders. So the transaction can become a bottleneck. However, this is the right way of doing it, if it's important for you to avoid partial orders.

  Is there a possibility of a product being directed to the wrong customer?

One thing is not clear, what happens if the first query fails. You didn't check for errors, though I would guess that in that case you won't get a meaningful insert ID (would have to check the docs). In any case, you should check for errors after all insert operations and handle gracefully.

Other than that, the transaction guarantees that order IDs won't get mixed up. Even without the transaction, probably it wouldn't happen, but I'd have to dig into the docs for that.

  Can I trust in this method?

Yes, keeping in mind the potential bottleneck and other considerations above.


It depends what do you mean by "streamlined"? There is not much you can do to, for example, reduce the complexity of your algorithm. What you can do is to increase the clarity of your algorithm, which falls into the domain of code review or improvement.

Maybe there is some math trick that can do the job faster, or with fewer lines of code. However there is also a good chance that such a trick will not make your algorithm look more "streamlined". It might even go the opposite direction and make it harder for the code to reveal its intention.

That being said, the problem you solved can be generalized to the problem of converting number to an arbitrary base, and then encode the number-in-new-base using a set of arbitrary symbols. In your case, the base is 26. The symbols are ["A", "B", ..., "Z"].
How a number is encoded or represented in a new base is independent of the base-convertion itself.

Looking at it this way, the only improvement I can think of is "do not limit the convertion to only one or two characters". Such a constraint does not bring much simplicity. But this probably is still implementation level improvement.

Your algorithm (or api) could eventually look like: number.convertToBase(26).encodeIn (["A", "B", ... , "Z"]). Is this more "streamlined"?


Horridly Inefficient Project Euler #14 in Python - Collatz Sequences

You should use memoization. It can be as simple as:

def next(n):
    if n % 2 == 0:
        return n // 2
    else:
        return 3 * n + 1

lengths = {}  # n -> length of sequence starting from n
lengths[1] = 1

def length(n):
    if not n in lengths:
        lengths[n] = 1 + length(next(n))
    return lengths[n]

max = 0
for n in range(1,1000000):
    l = length(n)
    if l>max:
        max = l
        print n, max


Welcome to Rust.  Here's some suggestions to get you started:
Creating idiomatic use declarations
It is not common in Rust to bring a function into scope directly via a use declaration.  Instead, io::stdin and io::stdout are preferred.  See the section Creating Idiomatic use Paths in the book for more information.
Using structs to self-document code
You included this sentence in your explanation of the code:

To store letters already guessed, I use an u128 and flag the
corresponding bit. It should be ok since all ASCII letters are
represented by u8 < 128.

It is preferable to include this information in the code itself.  In this case, we can introduce a struct:
#[derive(Clone, Copy, Debug, Default)]
struct AsciiSet {
    flag: u128,
}

impl AsciiSet {
    fn new() -> Self {
        Self { flag: 0 }
    }

    fn push(&mut self, letter: u8) {
        self.flag |= (1 << letter);
    }

    fn contains(&self, letter: u8) -> bool {
        (self.flag & (1 << letter)) != 0
    }
}

and modify the code accordingly:
let mut letters = AsciiSet::new();

loop {
    // ...
    if letters.contains(letter) { /* ... /* }

    // ...
    letters.push(letter);
}

Checking for ASCII
letter as u8 truncates the character if !letter.is_ascii().  Check for this case and prompt the user accordingly.


Pick a two different random elements from a given closed range

Naming

Swift naming conventions are listed in the API Design Guidelines. With respect to “Omit needless words” and “Strive for Fluent Usage” I would suggest to call the function

func randomPair(from range: ClosedRange<Int>) -> (Int, Int)?

Simplify the code

Your method is fine, but can be simplified a bit. First, the return values from randomElement() can safely be forced-unwrapped because it is guaranteed at that point that the range is not empty. That makes the final optional binding obsolete:

func randomPair(from range: ClosedRange<Int>) -> (Int, Int)? {
    guard range.count >= 2 else { return nil }

    let firstElement = range.randomElement()!
    var secondElement = range.randomElement()!

    while firstElement == secondElement {
        secondElement = range.randomElement()!
    }
    return (firstElement, secondElement)
}

Alternatively one can use a repeat-loop, so that the second element is assigned only at one place, that is a matter of personal preference:

func randomPair(from range: ClosedRange<Int>) -> (Int, Int)? {
    guard range.count >= 2 else { return nil }

    let firstElement = range.randomElement()!
    var secondElement: Int
    repeat {
        secondElement = range.randomElement()!
    } while firstElement == secondElement

    return (firstElement, secondElement)
}

But actually the same can be achieved without a loop, if we pick the second element from a reduced range and adjust it if necessary:

func randomPair(from range: ClosedRange<Int>) -> (Int, Int)? {
    guard range.count >= 2 else { return nil }

    let firstElement = range.randomElement()!
    var secondElement = range.dropLast().randomElement()!
    if secondElement >= firstElement {
        secondElement += 1
    }

    return  (firstElement, secondElement)
}

Generalizations

Now we have a function to get a random pair from a closed range. But what about open ranges? What about ranges of other types? In fact it is not difficult to implement the same algorithm for arbitrary (random access) collections. The only difference is that we pick random indices first:

func randomPair<C>(from collection: C) -> (C.Element, C.Element)? where C: RandomAccessCollection {
    guard collection.count >= 2 else { return nil }

    let firstIndex = collection.indices.randomElement()!
    var secondIndex = collection.indices.dropLast().randomElement()!

    if secondIndex >= firstIndex {
        collection.formIndex(after: &secondIndex)
    }

    return (collection[firstIndex], collection[secondIndex])
}

This covers closed ranges, open ranges, arrays etc:

randomPair(from: 0...10)
randomPair(from: 0..<10)
randomPair(from: ["a", "b", "c", "d"])

Alternatively one can implement this as an extension method for RandomAccessCollection so that it closely resembles the existing randomElement() method:

extension RandomAccessCollection {
    func randomPair() -> (Element, Element)? {
        guard count >= 2 else { return nil }

        let firstIndex = indices.randomElement()!
        var secondIndex = indices.dropLast().randomElement()!
        if secondIndex >= firstIndex {
            formIndex(after: &secondIndex)
        }
        return (self[firstIndex], self[secondIndex])
    }
}

(0...10).randomPair()
(0..<10).randomPair()
["a", "b", "c", "d"].randomPair()


Cut excess whitespace from input and print to output

A few suggestions:

Extract the space removal to a function of its own.  It a repeatable task and despite this being a short program it's still good practice. Then all you have to do in main() is just pass in the input string. Here's a function I came up with:

void removeSpaces(char* source)
{
    for (char *i = source, *j = source; *j != 0;)
    {
        *i = *j++;
        if(*i != ' ') i++;
    }
    *i = 0;
}

Keep in mind that this method modifies the original string.
Change how you get input from the user.  I'd recommend either getting input via command line arguments, or using fgets().  It's safer those ways and easier to do in my opinion.
If you decide to not use command line arguments, declare your function as:

int main(void)

Put the variable declarations to separate lines and initialize them to some value. From Code Complete, 2d Edition, p. 759:

  With statements on their own lines, the code reads from top to bottom,
  instead of top to bottom and left to right. When you’re looking for a
  specific line of code, your eye should be able to follow the left
  margin of the code. It shouldn’t have to dip into each and every line
  just because a single line might contain two statements.

You don't have to return 0 at the end of main(), just like you wouldn't bother putting return; at the end of a void-returning function. The C standard  knows how frequently this is used, and lets you not bother.

  C99 & C11 §5.1.2.2(3)

  ...reaching the } that terminates the main() function returns a
  value of 0.


Seems fine. However, depending on the context and the rest of the program, you can relax pattern's type:

pattern :: Int -> a -> a -> [[a]]

Also, since every putStrLn is basically hPutStrLn stdout, you could first glue all lines together with unlines and then print them with a single action:

main = putStr (unlines (pattern 48 '.' '+'))


Mapping uint to value within min/max set

I would recommend considering this using more explicitly the Two-Point Equation of a Line. Your code is basically doing the same thing, but thinking more explicitly in terms of the underlying mathematics would help avoid errors or extra complication.

Here is how I would implement this:

public static uint LinearTransform(uint x, uint x1, uint y1, uint x2, uint y2) {
    ulong a = (ulong)(y2 - y1)*(x - x1);
    uint b = (x2 - x1);
    return (uint)(a/b) + (a%b*2 >= b)?1:0 + y2;
}

I don't actually know C#, so it is likely that the code is not syntactically correct, or breaks the style rules of the language, but it should get the point across.

The (a%b*2 >= b)?1:0 term is to compensate for the way integer division always truncates to zero. This will make it instead round up if the fractional part would be 1/2 or more, so we don't need to do any floating point computations.

This function can then be used to perform your original task by calling it as LinearTransform(input, 0, min, uint.MaxValue, max).


The block should return the user's current_active_role

You never want to combine select with a first. Instead, use detect.

def current_active_role
  user_roles.detect(&:is_active_role)
end


Comments are not by any order of significance.

Which operating system standard?

A platform supporting C++ does not necessarily have an execve() call; that depends on <unistd.h>. Are you sure you're not making assumptions about what it contains?

Perhaps you aren't, but you need to double-check and document this.

Wrapping a single operating system call is questionable

If you've written this for your own use, since you execve() all the time like there's no tomorrow :-) ... then ok. Otherwise, developers would probably be hesitant to incorporate a idiosyncratic piece of code which handles exactly one out of dozens of system calls.

Also, even focusing on exec'ing another program, we have:

int execl(const char *path, const char *arg, ...);
int execlp(const char *file, const char *arg, ...);
int execle(const char *path, const char *arg, ...);
int execv(const char *path, char *const argv[]);
int execvp(const char *file, char *const argv[]);
int execvpe(const char *file, char *const argv[], char *const envp[]);

I'm not saying you need to implement a "Cpp-ified" version of all of these - on the contrary, it would probably be a bad idea - but you chose the less-general version.

Don't add utility/library functions to the global namespace

Application code uses (or rather, may use) the global namespace; library code uses a dedicated namespace. What you've written is supposed to be used repeatedly, not just once - so it's essentially library code, right? Put it in some namespace (e.g. util or unix etc.) A benefit of that is that you don't have to append the artificial name extension, i.e. unix::exec sounds nicer than execve_cpp.

Confusing parameters in your second variant

If I look at your second variant:

int execv_cpp(const std::vector<std::string> &argv);

It would not be clear to me whether the element of that vector should be the name of the binary I wish to execute. You may think you're making things more convenient for the client code, but people would rather type a few more characters than have to contend with semantic ambiguity.

If you're Cpp'ifying - do so for errors as well

In C++, passing invalid arguments typically causes an exception to be thrown; and you don't need to return anything, since you never return (as opposed to throwing an exception). Thus, for example:

void execv_cpp(const std::vector<std::string> &argv)
{
    if (argv.size() == 0) {
        throw std::invalid_argument(
            "At least one argument must be provided, being the path of "
            "the binary to execute");
    execv_cpp(argv[0], argv);
}

but of course, you're making it easy for the calling code to get it wrong by being willing to take an empty argv in the first place.

Don't force people to use std::vector's

A vector is just one specific container. There's no reason to assume the calling code is using vectors; and you're not even actually using the vector - you're converting it into a C-style array.

  in C++ you normally want to use vectors... instead of arrays.

Not true. You sometimes want to use them.

Don't force people to use std::strings

  of course in C++ you normally want to use... strings...

Sometimes, sometimes not. An std::string is just one way - albeit the default way - to represent strings. Remember, it's in the library - it's not int he langue. And std::string involves memory allocation policy (stack & heap etc.) which might not be appropriate to everyone. You should be more flexible, e.g. by templating on the string type:

template<typename S>
void execv_cpp(const std::vector<S> &argv);

or by using string views (C++17, experimental in C++14).

Consider a C++'ish interface for a bounded number of arguments

If you know the number of arguments at compile time, you can just have the following:

template <typename Args...>
void execv_cpp(std::string_view binary, Args&&... arguments);

and use std::to_string(), or operator<< into a stringstream, on each of the arguments in a loop. That gives maximum flexibility to the calling code, and makes exec() ing a binary basically the same as calling an arbitrary function:

execv_cpp(my_binary, 1, "two", std::optional<int>(3), 4.0);

Now, true, in this case you would be using up memory for string conversion results, but in the fixed-number-of-arguments case it's acceptable, I would say.

No need to duplicate strings

In the answer you linked to, it specifically says it's safe to const_cast the char pointers. So no need for the strdup().


Tracking the stability of a website using ping monitor

In reality, people just use third-party services for that. For instance, uptime website monitoring can be done StatusCake. If you own the target site, you install infrastructure tools like New Relic. Cloud services these days also provide uptime data and tools out of the box.

The only reason I would write my own uptime monitor is if  you're doing this for a small project or doing it for fun.

Now the problem with the uptime monitor you wrote is that it contributes to the site traffic. To the website, you're just another client trying to connect to the site. Together with your traffic are other sources of traffic, like legitimate users, web crawlers, malicious site scanners, DDOS bots, etc.

The reason you get the Request Timeout (HTTP 504) is because the site is already overloaded. It can be worse though. The site may choose to ignore you, block you temporarily, or even permanently. If you've seen a captcha appear when doing a Google search, that's one example.

So, what I recommend is to:

Reduce the rate you ping. Every 5, 15, or 60 minutes is reasonable. You're probably not going to need it every 6 seconds.
Hit a static asset on the domain instead, like the favicon. Hitting actual pages will cause 504s since it requires logic and probably database calls to generate the page. Just make sure it's not cached or served from a CDN.

This only tells you if the static server/caching proxy is up, not the actual server with the logic.

If the website has an API for uptime or a status page that you can scrape, use that instead. Those are usually served by a separate server so they can still tell you the status even if the main site is down.
If you own the website, monitor the infrastructure instead.


I'd change the color scheme,  the colors are a retinal burning  :)   Also, it would make the colors easier to read.   Also you have the sub menu over to the left irregardless of what choice is selected.  I'm a fan of the choices being under the selection I mouse over myself.   Other than that, it looks good!


Is there a more efficient way of doing function 'which' in R?

Try:

1-sum(ftable==1L)/sum(ftable)

Test on larger data:

n <- 1000000
set.seed(21)
ftable <- data.frame(replicate(3, sample.int(4, n, replace = T))-1L)

start.time=Sys.time()
1-length(which(ftable==1))/sum(ftable)
end.time=Sys.time()
end.time-start.time
# Time difference of 0.1981359 secs

start.time=Sys.time()
1-sum(ftable==1L)/sum(ftable)
end.time=Sys.time()
end.time-start.time
# Time difference of 0.06704712 secs

bechmarks:

n <- 1000000
set.seed(21)
ftable <- data.frame(replicate(3, sample.int(4, n, replace = T))-1L)

jz <- function() 1-length(which(ftable==1))/sum(ftable)
minem <- function() 1-sum(ftable==1L)/sum(ftable)

br <- bench::mark(jz(), minem(), iterations = 50)
br[, 1:7]
# A tibble: 2 x 7
#   expression      min     mean   median      max `itr/sec` mem_alloc
#   <chr>      <bch:tm> <bch:tm> <bch:tm> <bch:tm>     <dbl> <bch:byt>
# 1 jz()         51.2ms   53.8ms   52.6ms   66.3ms      18.6    60.1MB
# 2 minem()      37.7ms   39.9ms   38.5ms     67ms      25.1    45.8MB
# only around 36 % faster


I think your suspicion that the code is a "wet" is correct.  I would start moving these predicates into the model whenever they are:

Used more than once, or
Can make the code clearer by having a named predicate.

Consider replacing this:

helper_method :profile_type_from_user
  def profile_type_from_user(user)
    return profile = user.trucker ? :trucker : :owner_trucker
  end

With this:

class User
  ...
  def profile_type
    trucker ? :trucker : :owner_trucker
  end
  ...
end

Similarly, consider replacing this:

@profile = current_user.trucker ? current_user.trucker : current_user.owner_trucker

with:

class User
  ...
  def profile
    trucker || owner_trucker
  end
  ...
end

@profile = current_user.profile


Plotting terrain pixels with PyGame based on random NumPy array

If you have a lot of data in a rectangle, and you need to go fast, the answer is always the same: import numpy as np

Pygame has added some functions that support numpy arrays for exactly this reason. So you can fairly painlessly convert from an appropriately sized numpy array to a surface. You could even go back again, if you wanted.

Here's some code that does something similar to what you appear to be doing. I stripped out the stuff that you didn't provide source for, and focused on just doing the high/low/mid cutoff you seem to want. Also note, I'm using python 3, so there will likely be some slight gotchas in the syntax:

# https://codereview.stackexchange.com/questions/215575/plotting-terrain-pixels-with-pygame-based-on-random-numpy-array
"""

This file holds functions that modify pyGame surfaces.

"""

import numpy as np
import pygame

screen_size = (180, 320)

def display_map(noise):  # NOTE: I expect noise to be a 2-d np.ndarray
    ''' Return a surface with terrain mapped onto it. '''

    CHANNELS = 3  # use 4 for alpha, I guess
    RED = 0
    GREEN = 1
    BLUE = 2
    WATER_LEVEL = 0.20
    MOUNTAIN_LEVEL = 0.75

    # NOTE: numpy automagically "vectorizes" things like this.
    # array times scalar means a[i,j] * scalar, for all i,j
    shade = (noise * 255).astype(np.ubyte)

    # NOTE: dstack "stacks" however-many 2d arrays along the "depth" axis
    # producing a 3d array where each [i,j] is (X,X,X)
    rgb = np.dstack([shade] * 3)

    # NOTE: (WATER_LEVEL <= noise) produces a 2d boolean array, where
    # result[i,j] = (WATER_LEVEL <= noise[i,j]), kind of like the scalar
    # multiply above. The '&' operator is overloaded for boolean 'and'.
    # The upshot is that this assignment only happens where the boolean
    # array is 'True'
    rgb[(WATER_LEVEL <= noise) & (noise <= MOUNTAIN_LEVEL), GREEN] = 255
    rgb[(noise < WATER_LEVEL), BLUE] = 255

    # NOTE: pygame.surfarray was added mainly to talk to numpy, I believe.
    surf = pygame.surfarray.make_surface(rgb)
    return surf

pygame.init()
running = True
display = pygame.display.set_mode(screen_size)

noise = np.random.random_sample(screen_size)
terrain = display_map(noise)

while running:
    for ev in pygame.event.get():
        if ev.type == pygame.QUIT:
            running = False

    display.blit(terrain, (0, 0))
    pygame.display.update()


I did test it, it is working well. Well,

    System.out.println(Arrays.toString(
        new HeapSort(new int[] {3, 2, 1}).heapSort()));

isn't working.

document/comment your code.
You commented (all public method) members, see above for standard tool support.
For every non-trivial piece of code, what is the reason it is there, in the first place?
Starting at the class-, if not package-level:

/** HeapSort as a java.util.function.UnaryOperator<T>.
 * Java & coding beginner's exercise
 *  in type design and algorithm implementation.
 * The general idea is to turn the array into a max-heap
 *  and repeatedly move the max item
 *  from the shrinking heap to its current end.
 */
class HeapSort<T> implements In_placeSorter<T> {
    @Override
    public T sort(T toBeSorted) {
        if (!(toBeSorted instanceof int[]))
            throw new IllegalArgumentException("int[] only, for now");
        comparables = (int[]) toBeSorted;
        return (T) sort();
    } …

(note sort() not (doc)commented here: inherits from In_placeSorter<T>)
name things for what use they are. arr is horribly unspecific (used comparables instead).
don't make things more visible than they need to be. When in doubt, start with default/not specifying visibility:
int comparables[];
pay attention to boundaries:
neither the loop in makeHeap() nor the one in heapSort() need to handle index 0.
More importantly, while it is true that a right child needs to exist to be handled: what about left?
trying to implement "the general idea" without looking what&how others have done is a great step in learning —
please precede it by considering how do I know/check the specification is met?
asking how to improve the procedure is another great step in programming
(professionals prefix a when and). Start with algorithm;
Just don't try to force it - if nothing suggests itself, turn to something else temporarily, sleep on it, or now look what others have done and how, for heap-sort:

why do heapify()s start at the middle of the array?
what is to be gained from not comparing the item to be (re-)inserted while there are two children?

Continue with coding: e.g., there are several instances where you exchange/swap elements: "factor out" a method/procedure
handle petty concerns last, if at all:
Java arrays & java.util.Arrays don't come with a swap()? Use java.util.Collections.swap(java.util.List, int, int) as a template
using a for-loop:
for (int index = i, parent ; index != 0 ; index = parent) {…

Just in case:

/** Rearranges items in ascending "natural" order. */
interface In_placeSorter<T> extends java.util.function.UnaryOperator<T> {
    /** Rearranges items in ascending "natural" order.
     * @param toBeSorted items to be sorted
     * @return toBeSorted */
    T sort(T toBeSorted);
    @Override
    default T apply(T t) { return sort(t); }
}


Better multithreading with network IO and database queries

Take a look at the eventlet library. It'll let you write code that fetches all the web pages in parallel without ever explicitly implementing threads or locking.

import cStringIO, threading, MySQLdb.cursors, pycurl

NUM_THREADS = 100
lock_list = threading.Lock()
lock_query = threading.Lock()

The purist that I am, I wouldn't make this locks globals.

db = MySQLdb.connect(host = "...", user = "...", passwd = "...", db = "...", cursorclass=MySQLdb.cursors.DictCursor)
cur = db.cursor()
cur.execute("SELECT...")
rows = cur.fetchall()
rows = [x for x in rows]  # convert to a list so it's editable

It would make more sense to do this sort of thing after you've define your classes. At least that would be python's convention.

class MyThread(threading.Thread):
    def run(self):
        """ initialize a StringIO object and a pycurl object """

that's pretty much the most terrible description of this function I could have come up with. (You seem to be thinking of that as a comment, but by convention this should be a docstring, and describe the function)

        while True:
            lock_list.acquire()  # acquire the lock to extract a url
            if not rows:  # list is empty, no more url to process
                lock_list.release()
                break
            row = rows.pop()
            lock_list.release()

It'd be a lot simpler to use a queue. It'd basically do all of that part for you.

            """ download the page with pycurl and do some check """

            """ WARNING: possible bottleneck if all the pycurl
                connections are waiting for the timeout """

            lock_query.acquire()
            cur.execute("INSERT INTO ...")  # insert the full page into the database
            db.commit()
            lock_query.release()

It'd be better to put this data in another queue and have a database thread take care of it. This works, but I think the multi-queue approach would be cleaner.

            """do some parse with BeautifulSoup using the StringIO object"""

            if something is not None:
                lock_query.acquire()
                cur.execute("INSERT INTO ...")  # insert the result of parsing into the database
                db.commit()
                lock_query.release()

Same here. Note that there is no point in python of trying to split up processing using threads. The GIL means you'll get no advatange.

# create and start all the threads
threads = []
for i in range(NUM_THREADS):
    t = MyThread()
    t.start()
    threads.append(t)

# wait for threads to finish
for t in threads:
    t.join()


Side-scrolling

Don't make do it. If a line of code doesn't fit comfortably inside the code pane of the IDE with a reasonable window size, it's too long. If the code line actually has to be that long, take advantage of VBA's line continuation operator (_) and break it up so you can see the whole line at once. The If tests are especially problematic, given that by the time I've scrolled right far enough to see the last condition I can't see what gets executed if it's true.

Naming

Although the actual naming convention you use is a question of taste, it is good to be consistent. I typically follow a convention similar to the one outlined over on the SO documentation page for Naming Conventions. You have a mix of Pascal and lower snake case for (what appear to be) local variables - i.e. Start_Row and double_actuals_support.

More important is the variables named *_Row. You have Start_Row, Last_Row, and Finish_Row,  These are frankly confusing as to what they are referring to. All of those names imply that they are more or less constant values, but all of them change.  I think of a start row as the first row on a sheet and last row as the last row on the sheet.  Since Start_Row is the holding your loop counter, I'd suggest something more like workingRow or currentRow. Last_Row appears to refer to the last row of each node (it is always offset by 6), so it would be more appropriately named something like nodeEndRow.  Finally Finish_Row appears to be set to the last row of the previous node, so something like previousNodeEnd would be appropriate.

Best Practices

Indentation isn't consistent, but it's hard to tell whether that's an artifact of copying and pasting or not.  You can fix it with Rubberduck's SmartIndenter feature (full disclosure, I'm a contributor).

You should qualify all of your Range and Cells calls to avoid using the global collections (if the code isn't in a worksheet module). Wrap the whole thing in With ActiveSheet (or even better, a worksheet code name like With Sheet1) if it's anywhere other than a worksheet module, otherwise wrap the whole thing in With Me.

Use the String returning versions of functions (they end with $) instead of Variant returning functions when they are available to avoid implicit casts. You can find a list of them here.

Declare your variables and add Option Explicit to your modules.  Otherwise they are implicitly Variant, and this can cause a host of issues. If they are declared somewhere above the code that was posted, they should be moved closer to where they are being used.  For example, double_actuals_support and adjust_delete are what appear to be throw-away loop counters. There's no reason you should need to go somewhere else to see how they're defined.

It's not clear why you call Application.Wait Now + TimeValue("00:00:02") at the start.  If there's a reason you need to do that, comment it.  Also, while updating the status bar is useful, you should immediately call DoEvents after updating it so that the screen can refresh.  Although, it's possible you wont' need it once the row delete issue is addressed, which leads me to...

Skip the row delete gymnastics

I literally had to stare at this section of code for about 5 minutes before I could determine that it probably wasn't actually a bug (and I can still only make an educated guess as to why it's there):

'Delete actual and support nodes, loop twice to remove R value rollups
For double_actuals_support = 0 To lastRow_das_delete
range("B" & (Start_Row + 1)).Formula = "=CONCATENATE(""~ "" & INDEX('Complete Database Pull'!B:B,MATCH(B" & Start_Row & ",'Complete  Database Pull'!C:C,0)))"
If Right(range("B" & Start_Row).Value, 19) = "- Actuals & Support" Then
    For adjust_delete = 0 To 5
        Rows(Start_Row).EntireRow.Delete
    Next adjust_delete
End If
Next double_actuals_support

First, the comment is extremely misleading - this doesn't loop twice, it loops through the every row of the worksheet. As it looks like you found out, deleting rows while you're looping through them alters the row index.  From the above section of code, it appears that you are just reloading the the worksheet from that point down if you have to delete something. This is incredibly inefficient.

There are 3 much easier and much faster ways to handle this.  Either loop through the rows backwards, accumulate the rows that need to be deleted and delete them all at once when you're done, or conditionally increment your row counter.  If I'm misunderstanding the purpose of this code, you do have a bug, because there isn't anything else in your code that adjusts the indexing for deleted rows.

Note that this is the only thing I could find that indicated "recursion" in the code you posted.  There aren't any function calls and I wouldn't know the name of the posted function anyway.

Avoid repeated function call and Worksheet accesses

If the return value of a function call or property is guaranteed to be identical over multiple calls, you should cache the value in a local variable instead of repeatedly requesting it.  This line is a perfect example (line continuations added for clarity):

 If (Right(range("B" & Start_Row).Value, 10) = "- Overhead" Or _
     Right(range("B" & Start_Row).Value, 14) = "- Non Overhead" Or _
     Right(range("B" & Start_Row).Value, 4) = "- WG") Then

The value of Range("B" & Start_Row).Value is going to be exactly the same for the 3 times you're requesting it. This would be much better:

Dim pulled As String
pulled = Range("B", workingRow).Value

If (Right(pulled, 10) = "- Overhead" Or Right(pulled, 14) = "- Non Overhead" Or _
    Right(pulled, 4) = "- WG") Then

Note that your lines are getting shorter now too.

Repeated code

There's a consistent pattern that you repeat over and over again.  Going back to the same line of code as above, you make multiple tests to see if a given string ends with another string similar to this:

If (Right(range("B" & Start_Row).Value, 10) = "- Overhead" ...

I'd throw in a couple simple utility functions called EndsWith and StartsWith and use those instead (StartsWith would be similar):

'Tests to see if a string ends with any of the passed candidates.
Public Function EndsWith(test As String, ParamArray candidates() As Variant) As Boolean
    Dim candidate As Variant
    For Each candidate In candidates
        Dim chars As Long
        chars = Len(candidate)
        If Len(candidate) <= test Then
            If Right$(test, chars) = candidate Then
                EndsWith = True
                Exit Function
            End If
        End If
    Next
End Function

This has several advantages:

It makes the code much clearer as to the intent.
It gets rid of all of the hard coded string lengths that are prone to errors.
It almost completely solves the side scrolling issue.
It short-circuits on the first match (If x Or y Or z doesn't).

The line referenced above can now be something like:

If EndsWith(pulled, "- Overhead", "- Non Overhead", "- WG") Then

Use numeric column indexes and constants

The only reason that Excel has letters for column identifiers is because they are easier for humans to read - it ultimately treats column indexes as a numbers internally. So, it's a (albeit small) performance improvement to use numeric range indexing rather than string indexing because Excel just has to parse it.  Also, for individual cells, using .Cells is much better than using the .Range because Excel doesn't have to do any parsing.

'Good
Range("B", workingRow).Value
'Better
Cells(workingRow, 2).Value

While it's easier to see "B" than to have to mentally calculate that it would be column 2 , it's important to remember that "B" is just as much of a "magic letter" as 2 is a magic number.  You can make code much more readable by defining and using constants for them. This also makes the code tremendously easier to maintain - think about how many places you would need to make changes if your columns all shifted one to the right.  If it's in a constant, you only need to change it in one place:

'Module level
Private Const ROW_INDEX_COLUMN As Long = 1
Private Const DATA_ID_COLUMN As Long = 2
Private Const END_COLUMN As Long = 25
'...
'Best
Cells(workingRow, DATA_ID_COLUMN).Value

Another perfect candidate for a constant would be NODE_LENGTH As Long = 6.

Extract methods for common code

The code used for formatting the cells is pretty much identical other than the colors being used.  Instead of repeating the code twice here...

'Color WG rows/columns
If (Right(range("B" & Start_Row).Value, 10) = "- Overhead" Or Right(range("B" & Start_Row).Value, 14) = "- Non Overhead") Then
    range("B" & Start_Row & ":Y" & (Start_Row + 3)).Interior.Color = 15853276
    range("B" & Start_Row & ":B" & (Start_Row + 5)).Interior.Color = 15853276
End If

If Right(range("B" & Start_Row).Value, 4) = "- WG" Then
    range("B" & Start_Row & ":Y" & (Start_Row + 3)).Interior.Color = 15523812
    range("B" & Start_Row & ":B" & (Start_Row + 5)).Interior.Color = 15523812
    Last_Row = Start_Row + 6
End If

...it would be more readable and maintainable if you made a separate Sub that performed the formatting.  Something like this:

Private Sub FormatDataNode(anchor As Range, colorIndex As Long)
    Dim r As Long, c As Long
    r = anchor.Row
    c = anchor.Column
    With anchor.Parent
        .Range(.Cells(r, c), .Cells(r + 3, END_COLUMN)).Interior.Color = colorIndex
        .Range(.Cells(r, c), .Cells(r + 5, c)).Interior.Color = colorIndex
    End With
End Sub

Then you can simplify the code in the loop to something more like this:

Private Const WG_COLOR As Long = 15523812
Private Const NON_WG_COLOR As Long = 15853276
'...
'Color WG rows/columns
If EndsWith(pulled, "- Overhead", "- Non Overhead") Then
    FormatDataNode Cells(workingRow, DATA_ID_COLUMN), NON_WG_COLOR
ElseIf EndsWith(pulled, "- WG") Then
    FormatDataNode Cells(workingRow, DATA_ID_COLUMN), WG_COLOR
    nodeEndRow = workingRow + NODE_LENGTH
End If

Conclusion

Overall nothing horrible - the suggestions above will make it much more readable.  My guess is that taking a different strategy to deleting rows will have a huge impact in both performance and correctness.  After that's sorted out, my guess is that this code can be simplified tremendously - feel free to post a follow-up question after your first refactoring round.


Which is a better style to write default return case in if-else

I'd remove both elses:

private String getFacilityName(String facilityHexId) {
    if (FACILITY_AIRCON_HEX_ID.equals(facilityHexId)) {
       return FACILITY_AIRCON_NAME;
    }
    if (FACILITY_FAN_HEX_ID.equals(facilityHexId)) {
       return FACILITY_FAN_NAME;
    }
    return facilityHexId;
}

I think it's easier to follow. (It's called Guard Clause.)

Some other notes:

I've switched the equals to CONSTANT.equals(inputParameter). Now it handles null inputs too and does not throw NullPointerException.
I've renamed the method to camelCase. It's more common in Java to start method names with small letters.  (Code Conventions for the Java Programming Language, 9 - Naming Conventions)
I've changed ID to Id in the variable names. I prefer camelCase here too because it's usually easier to read. From Effective Java, 2nd edition, Item 56: Adhere to generally accepted naming conventions:

  While uppercase may be more common,
  a strong argument can made in favor of capitalizing only the first
  letter: even if multiple acronyms occur back-to-back, you can still
  tell where one word starts and the next word ends.
  Which class name would you rather see, HTTPURL or HttpUrl?


What if you changed the algorithm to do the following steps?

Remove all Spaces
If String Length is Odd, delete middle character
Split string in half
Reverse one of the halves
Compare the two halves

Rationale: In your case, you reverse the entire string, even when it's very large, when you really only need to reverse the first half of the string.


I guess from efficiency point of view this is fine, even that last line. Efficiency points:

You create player variable as list and then keep converting to set over and over again, why not have it as set from beginning?

From readability and maintenance point of view, you are having lots of duplicities.

Player moves are exactly same except for message and variable, you can extract that to function.
Same goes for checking if a player won.
I don't like variable w. Why not make variable winner instead and save name of winner into it? Related to extracting if player won to separate function.

And for your last line - you can put all possible winning combinations into array or tupple and then check that in cycle (you get the idea):

winning_combinations = [
[1, 2, 3],
[4, 5, 6],
...
]


It seems that you could use a little C++11 in order to improve your code:

You can abstract away the operating system you are using by replacing the platform-dependent sleep functions by std::this_thread::sleep_for. If you can use C++14, you can even benefit from the added readability gained with the standard user-defined literals in <chrono>:

using namespace std::chrono_literals;
std::this_thread::sleep_for(3s);

You can avoid using most of the this-> you are using. Generally speaking, you don't need to prepend this->: it just makes the code longer and the compiler should warn you anyway if a local variable shadows a class member (-Wshadow with GCC for example).
Declaring all the variables at the beginning of a function is very C-like and makes it hard to know where a variable is used exactly. Generally speaking, you should only declare variables when you need them, in the tightest possible scope. Have a look at this piece of your code:

if (this->oTerminal->MenueSavePw() == true)
{
    this->oTerminal->Print("The password has been saved in a file.");
    oFstream.open("PasswordGenerator.txt", std::fstream::app);
    oFstream << "\r\n[" << (timePtr->tm_year + 1900) << "." << (timePtr->tm_mon+1) << "." << timePtr->tm_mday << " " << timePtr->tm_hour << ":" << timePtr->tm_min << ":" << timePtr->tm_sec << "] " << this->oSecurity->GetPw();
    oFstream.close();
}

Here, you can clearly declare oFstream in the if block since it isn't used before nor after. Moreover, it allows you to open the stream at construction and to let the end of the scope call the destructor, which will call close for you:

if (oTerminal->MenueSavePw() == true)
{
    oTerminal->Print("The password has been saved in a file.");
    std::ofstream oFstream("PasswordGenerator.txt", std::fstream::app);
    oFstream << "\r\n[" << (timePtr->tm_year + 1900) << "." << (timePtr->tm_mon+1) << "." << timePtr->tm_mday << " " << timePtr->tm_hour << ":" << timePtr->tm_min << ":" << timePtr->tm_sec << "] " << oSecurity->GetPw();
}

By the way, it is considered bad practice to compare conditions against true. You should simply change it to:

if (oTerminal->MenueSavePw())

Your lines are quite long too. You could split them into several lines to make your code more readable. Consider the following and compare it to your one-liner:

    oFstream << "\r\n["
             << (timePtr->tm_year + 1900) << "."
             << (timePtr->tm_mon+1) << "."
             << timePtr->tm_mday << " "
             << timePtr->tm_hour << ":"
             << timePtr->tm_min << ":"
             << timePtr->tm_sec << "] "
             << oSecurity->GetPw();

Sometimes, when printing things that have a structure (like printing XML data), you can even use fancier indentation in order to reflect the structure of the data you're printing.
There are too many useless pointers and dynamic allocation in your code. In C++, whenever possible, you should use automatic variables instead of dynamically allocated ones. Here is what your main should look like:

void main()
{
    Controller::PwGenerator oController;
    oController.Run();
}

Terser, safer and even probably faster (unnoticeable in this case though). Whenever you use new, your program may throw an std::bad_alloc, and dynamically allocated memory doesn't free itself when an exception occurs while automatic variables are correctly destructed when an exception is thrown. Bottom line: use pointers when you have to and regular variables whenever you can.
I said that this is what main should look like, but it's actually not true: your main has a void return type, which makes the program ill-formed in regards to the standard. While most compilers will accept it, you better have an int return type for your main to be standard-compliant. You don't have to return anything from it though since it is guaranteed that the compiler will add a return 0; at the end of it if it didn't encounter any return statement.
std::random_shuffle has been deprecated in C++14 and will be removed from the standard library in C++17 because it might be unsafe. You should consider using std::shuffle instead, with a random number generator from the C++11 header <random>:

std::random_device rd;
std::mt19937 g(rd());

std::shuffle(sPassword.begin(), sPassword.end(), g);


Repetition

I would write only one function to locate zeros:

def locate_zeros(matrix: IntegerMatrix) -> Iterable[Position]:
    """Given an NxM matrix find the positions that contain a zero."""
    for row_num, row in enumerate(matrix):
        for col_num, element in enumerate(row):
            if element == 0:
                yield (col_num, row_num)

And use it in zero_out like this:

    if row_num in (x[1] for x in zeros_positions) or col_num in (x[0] for x in zeros_positions):
        matrix[row_num][col_num] = 0

Type hints

Given that you specifically mentioned Python 3.5 and that you already have something like type hints on your functions, I suggest you go all the way with mypy compatible type hints.

from typing import List, Any,  Iterable, Tuple

Position = Tuple(int, int)
IntegerMatrix = List[List[int]]

def locate_zeros(matrix: IntegerMatrix) -> Iterable[Position]:

def zero_out(matrix: IntegerMatrix) -> IntegerMatrix:

This way you can statically check your code has the correct types like in natively statically types languages and give the user much more detailed information on the types.