Number-guessing game in Python with a single level of abstraction

When too many parameters are being passed around, object-oriented programming can help.  But I don't think that that is your problem here.  I think you have divided the work into functions suboptimally.  Some advice:

Document each function's purpose in a docstring.

If you can't write a good docstring, then perhaps the function is poorly conceived.  Can you tell me what the displayHotHotterCooler() function does?  If you had to write a docstring for it, it might say:

  Assuming that a guess is hot, and that it is not the player's first guess, print 'HOT!!', 'HOTTER!!!', or 'COOLER' depending on how it rates relative to the previous guess.

That's too complicated, I think.  The function already has two preconditions on its applicability.  Any attempt to describe it better would end up being more verbose than the code itself.  Furthermore, the name displayHotHotterCooler doesn't really summarize the function's purpose.  All these problems suggest that this is not a worthwhile function to define, because its purpose is not clear.

In contrast, my display_hint() function below does have a clear summarizable purpose:

  Print a message hinting at the player's progress towards guessing the target number.

Delegate, don't micromanage.

promptGuess() could be smarter.  It already knows what the valid range is, so why can't it perform the validation for you too?  That would relieve main() from having to call validGuess(), and would eliminate one level of indentation from main().

Part of not micromanaging is to let each function figure out what information it needs.  Instead of passing three parameters newDistance, oldDistance, and firstGuess, consider passing the entire history of guesses instead, as a list.  The called function can infer whether it's the first guess based on the length of the array.  It can easily extract the last two elements, as needed.  (Drawbacks are that you end up storing more state than is strictly necessary, and that you have to trust the called function not to mutate the list.  But I think it's a worthwhile tradeoff for simplicity.)

Suggested solution

from random import randrange

def user_guesses(lo, hi):
    """
    Yield prompted guesses from the user, all verified to be integers
    between lo and hi (inclusive).
    """
    while True:
        guess = int(input('Enter a number ({}-{}): '.format(lo, hi)))
        if lo <= guess <= hi:
            yield guess

def display_win(diffs):
    """
    Print a congratulatory message for winning.
    """
    if len(diffs) == 1:
        print('WOW!! You got it on your first try!')
    else:
        print('GOOD JOB! You got it in {} tries.'.format(len(diffs)))

def display_hint(diffs, hot_distance):
    """
    Print a message hinting at the player's progress towards guessing
    the target number.

    diffs is a sequence of absolute differences between the guesses
    and the target number.  hot_distance is the threshold distance
    for considering a guess to be "hot".
    """
    is_hot = diffs[-1] <= hot_distance
    was_hot = diffs[-2] <= hot_distance if len(diffs) > 1 else None
    if was_hot is None:
        print('HOT!' if is_hot else 'Cold')
    elif diffs[-1] == diffs[-2]:
        print('Same temperature!')
    elif is_hot:
        print('HOT!!' if not was_hot else
              'HOTTER!!!' if diffs[-1] < diffs[-2] else
              'COOLER')
    else:
        print('COLD' if was_hot else
              'Warmer!' if diffs[-1] < diffs[-2] else
              'Colder')

def main(lo=1, hi=100):
    """
    Pick a random number between lo and hi (inclusive), and let the
    player guess the number.  Temperature hints are printed until
    the player guesses correctly.
    """
    hot_distance = (hi - lo + 1) // 10      # 10% of the range
    answer = randrange(lo, hi + 1)
    diffs = []
    for guess in user_guesses(lo, hi):
        diffs.append(abs(guess - answer))
        if guess == answer:
            display_win(diffs)
            return
        display_hint(diffs, hot_distance)

main()

Other remarks:

Using the is operator to test for numeric equality is incorrect.  It only happens to work for some smaller numbers.

>>> 5 is -(-5)
True
>>> 1024 is -(-1024)
False
>>> 5 == -(-5)
True
>>> 1024 == -(-1024)
True

PEP 8, the official Python style guide, discourages extra spaces for the sake of aligning = signs.  It also recommends lower_case_with_underscores instead of interCaps naming.
Python support double-ended inequalities (lo <= num <= hi).
Instead of sprinkling references everywhere to hard-coded constants, I often prefer to define default parameters.
Flag variables, like won and isFirstTry, are almost always a sign that you can devise a better control structure.  Just eliminate them from your code.


Preventing XSS attacks in a Spring MVC application controller

Don't use RegEx to prevent XSS attacks!
Why?

Regex is not a tool that can be used to correctly parse HTML.

There are much better ways to prevent XSS attacks.

An example, using your code, modified to use Spring HtmlUtils.
Please note that I changed names s to input and ret to isHtml, as these names indicate what the variable is intended for, rather than just what kind it is.
import org.springframework.web.util.HtmlUtils;

public class HtmlUtils {
    /**
     * Verify if a string contains any HTML characters by comparing its
     * HTML-escaped version with the original.
     * @param String input  the input String
     * @return boolean  True if the String contains HTML characters
     */
    public static boolean isHtml(String input) {
        boolean isHtml = false;
        if (input != null) {
            if (!input.equals(HtmlUtils.htmlEscape(input))) {
                isHtml = true;
            }
        }
        return isHtml;
    }
}

I'm sure there are other things to say about your code, but this is very important.
There is much more to truly preventing XSS attacks, depending on how critical your use case is. This page has a tremendous amount of useful information you may want to consider: XSS (Cross Site Scripting) Prevention Cheat Sheet


Let's analyze what the problem is saying.

Let's say we start out with the array:

0, 1, 2, 3, 4, 5, 6, 7, 8, 9

We then reverse the elements of the array starting at element 0:

9, 8, 7, 6, 5, 4, 3, 2, 1, 0

Then, we reverse all elements except the 0th element:

9, 0, 1, 2, 3, 4, 5, 6, 7, 8

Then we reverse all elements except 0th and 1st element:

9, 0, 8, 7, 6, 5, 4, 3, 2, 1

And so on like so:

9, 0, 8, 1, 2, 3, 4, 5, 6, 7
9, 0, 8, 1, 7, 6, 5, 4, 3, 2
9, 0, 8, 1, 7, 2, 3, 4, 5, 6
9, 0, 8, 1, 7, 2, 6, 5, 4, 3
9, 0, 8, 1, 7, 2, 6, 3, 4, 5

To get the final result:

9, 0, 8, 1, 7, 2, 6, 3, 5, 4

The key thing to note here is that if take every odd-indexed element we get:

9, 8, 7, 6, 5

While every even-indexed element is:

0, 1, 2, 3, 4

So it looks like the final sequence is constructed like this:

Split elements into lower half and upper half
Reverse the order of the upper half
Merge them by taking 1 element from upper half and 1 element from lower half and so on

This is an \$O(n)\$ process with the right implementation

All that remains is to then search the list for the given element (which is \$O(n)\$ in the worst case with a standard implementation), yielding a final computational time complexity of \$O(n)\$. That's it, right? Well it would be, if not for some interesting math.

If we apply some mathematical logic we can get an even faster solution:

Decide if element is in lower half (which will have even indices) or the upper half (which will have odd indices) with a simple comparison to half the length of the array
If element is in lower half: final index will be 1 + 2 * K (as 0 will be in 1st index, 1 will be in 3rd, 2 will be in 5th and so on)
If element is in upper half: final index will be 2 * (N - 1 - K) (as N - 1 will be at 0, N - 2 will be at 2, N - 3 will be at 4 and so on)

This yields an \$O(1)\$ solution! Hurray for Math!

You can also simplify the logic a bit by noticing an interesting fact:

If you wrongly put an element from the upper half into the formula for the lower half and vice versa, an interesting thing happens: the final index will be out of the bounds of the array, and most importantly is greater than the index calculated from the other formula. The proof is left as an exercise, but this allows your entire program to boil down to:

min(1 + 2 * K, 2 * (N - 1 - K)) for every N, K pair

Note: this code ran in .05 sec for each trial under Python3.

Implementations are left as an exercise to the reader.


Trying multiple regexes against a single string

I think it's a neat idea, because you're indeed using well-tested code, which reduces the chance of errors.
Looking at the re API, you do need to retrieve all possibles matches using groupdict().
Even that one is not a gotcha since you're naming your groups yourself. Right? I can't think of anything else.

Other comments:

You have a small bug in your last loop where text and hit need to be exchanged.
There's no easy to way to be sure that the DFA version will be faster than the normal version. Since you're not producing a factorized DFA but a sum of DFAs, naive code could be as slow as testing each regex one by one. Of course it's possible that it's much faster, but measure it if this is what you want to achieve!
You don't need uuids, a simple counter would be enough. Eg ?P<g1> instead of ?P<fd897214dd9d4dd28f591a412ef5d3ea>.


When it comes to iteration in Python, there is often an itertools recipe or function that come close to the needs.

Here, I’m thinking about pairwise which is defined as:

def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = itertools.tee(iterable)
    next(b, None)
    return itertools.izip(a, b)

If you’re interested in cycling back to the beginnig, you should consider itertools.cycle too:

def get_line_coordinates(iterable, close=False):
    """s -> (s0,s1), (s1,s2), (s2, s3), ...
    ends with (sN, s0) if close is True else (sN-1, sN)
    """
    a, b = itertools.tee(iterable)
    if close:
        b = itertools.cycle(b)
    next(b, None)
    return itertools.izip(a, b)

Lastly, itertools.izip_longest will let you fill that last value by consumming less memory than cycle:

def get_line_coordinates(iterable, close=False):
    """s -> (s0,s1), (s1,s2), (s2, s3), ...
    ends with (sN, s0) if close is True else (sN-1, sN)
    """
    a, b = itertools.tee(iterable)
    beginning = next(b, None)
    if close:
        return itertools.izip_longest(a, b, fillvalue=beginning)
    return itertools.izip(a, b)


Convert generic class into XML string of specific structure

Take a look at  How to: Specify an Alternate Element Name for an XML Stream.
Although it is more code, I would use the mentioned XmlAttributeOverrides like so

public static string GetXml<T>(T instance, string sourceName = "InnerObject") where T : class
{
    var wrapper = new DocumentElement<T>(instance);
    var writer = new StringWriter();
    var overrides = CreateOverrides(typeof(DocumentElement<T>), instance.GetType().Name, sourceName);

    var serializer = new XmlSerializer(typeof(DocumentElement<T>), overrides);
    serializer.Serialize(writer, wrapper);
    return writer.ToString();
}
private static XmlAttributeOverrides CreateOverrides(Type type, string destinationName, string sourceName)
{
    var elementAttribute = new XmlElementAttribute() { ElementName = destinationName };
    var attributes = new XmlAttributes();
    attributes.XmlElements.Add(elementAttribute);
    var overrides = new XmlAttributeOverrides();
    overrides.Add(type, sourceName, attributes);
    return overrides;
}


Infix to postfix Converter implementation

The intent of your preced function is completely unclear. I can't make heads or tails of what it's supposed to be doing as a whole. It appears to return 1 for two operators of equal precedence, but it also returns 1 for some cases when they're not equal--but it's not at all clear what those cases are supposed to be.

As a general rule, my immediate reaction would be to encode operator precedence into a table, and then have a little bit of logic to deal directly with precedence it found for them. So, I'd probably start with some code just to get the precedence:

int get_precedence(char ch) {

    char const *operators[] = {
        "^",
        "+-",
        "*/%"
    };
    int i;

    for (i=0; i<3; i++)
        if (strchr(operators[i], ch) != NULL)
            return i;
    return -1;
}

Using this, the "return 1 if they're equal" part could look something like this:

int preced(char ch1, char ch2) {
    if (get_precedence(ch1) == get_precedence(ch2))
        return 1;
}

I'm not quite sure about the rest of the logic, so I won't try to deal with that right now, but I'd almost be surprised if it didn't come out rather clearer after treatment like this as well.

That brings up an obvious second point: preced isn't a particularly great name for the function. It hints at the fact that it's somehow related to precedence, but that's about all we get from the name. Something more descriptive of the real intent would clearly help a lot here.

Use of NULL

NULL is intended to be a null pointer constant--not anything else. It should never be assigned to anything other than a pointer. Right now, you have places where you use it as a char instead, such as:

 Symbol[j-1]=NULL;

Although it's possible for a compiler to define NULL in a way that allows this, it's also possible to define NULL so you'd have to add a cast for this to work, so this affects both style/readability and portability.

Avoid arbitrary limits

If at all reasonable, and I think it probably is, it's generally best to avoid having entirely arbitrary limits on things like the size of the input. If you are going to have an arbitrary limit, at least try to make it large enough that it's unlikely to ever arise in practice (e.g., set it to 8 kilobytes instead of 10 bytes).

Enforce the limits you do have

Any time you see scanf("%s", somestring); you should cringe in fear, bordering on horror. You've just used scanf to re-create gets, a function so terrible it's been removed from recent versions of the standard.

The problem here is that although your string is (in this case) only 10 bytes long, you haven't informed scanf of that fact, so if the user types in more than 9 characters (remember, the string needs a NUL terminator) you'll get undefined behavior. Any time you use the %s conversion with scanf (or cousins like fscanf) you need to include a maximum size allowed:

char buffer[1025];

scanf("%1024s", buffer);

So here we've specified a maximum length of 1024, with a buffer length of 1025, so we have room for the NUL terminator. Result: the code is nice and safe. No matter how much data the user enters, scanf will never write past the end of our buffer.


If you had ran simulation or loaded onto FPGA, you would noticed you didn't get the expected behavior. Run simulation and look at waveforms before loading to FPGA.

You have hcnt <= hcnt + 1; at the bottom of your always block, this will override hcnt <= 0; which is not what you want. <= is a non-blocking assignment which means it will be evaluated immediately but the value will not be updated until the end of the timestep. Order matters.

The simplest solution is to move hcnt <= hcnt + 1; above the case statement.

Be aware that your hcnt are counting from 0 to 800 which is 801 clocks. You may want to consider subtracting 1 from each case condition or initiating/resetting hcnt (and vcnt) as 1 instead of 0.

Your vcnt will only be 525 for one clock, which don't look intentional. Consider moving it inside the case(hcnt)'s condition 800.

I will recommend adding a reset input. And also recommend using an ANSI header Non-ANSI is required for Verilog-95 and pre IEEE1364. Since Verilog-2001, ANSI style is preferred mostly because it reduces the amount of typing.

Below is my suggestion. Note I haven't tested that all functional requirements are met (that should be done in your testbench).

module sync (
  input clk, rst_n,                       // <-- ANSI header
  output reg hblank, hsync, vblank, vsync
);
  reg [9:0] hcnt, vcnt;

  always @(posedge clk) begin
    if (!rst_n) begin // <-- synchronous reset logic
      hblank <= 1'b0;
      hsync <= 1'b1;
      vblank <= 1'b0;
      vsync <= 1'b1;
      hcnt <= 10'h001;  // <-- init as 1 so case index doesn't need to change
      vcnt <= 10'h001;  // <-- same as vcnt
    end
    else begin
      hcnt <= hcnt + 10'h001; // <-- default assignment, will be updated after the clock
      case (hcnt) // <-- uses the sampled value, not the result of the above line
        10'd640: hblank <= 1'b1;
        10'd656: hsync <= 1'b0;
        10'd752: hsync <= 1'b1;
        10'd800: begin
          hblank <= 1'b0;
          hcnt <= 10'h001; // <-- reset as 1, last assignment wins
          vcnt <= vcnt + 10'h001;
          case (vcnt)
            10'd480: vblank <= 1'b1;
            10'd490: vsync <= 1'b0;
            10'd492: vsync <= 1'b1;
            10'd525: begin
              vblank <= 1'b0;
              vcnt <= 10'h001; // <-- reset as 1, last assignment wins
            end
          endcase
        end
      endcase
    end
  end
endmodule

You may want to consider using the 2-alway block coding style. It does require more lines of code small designs (usually reduces lines of code for large/complex desings). The main benefit is you can access to the present state and next state of a flop.

// sequential logic (uses non-blocking assignment and is synchronous)
always @(posedge clk) begin
  if (!rst_n) begin
    hblank <= 1'b0;
    hsync <= 1'b1;
    vblank <= 1'b0;
    vsync <= 1'b1;
    hcnt <= 10'h001;
    vcnt <= 10'h001;
  end
  else begin
    hblank <= next_hblank;
    hsync <= next_hsync;
    vblank <= next_vblank;
    vsync <= next_vsync;
    hcnt <= next_hcnt;
    vcnt <= next_vcnt;
  end
end

// combinational logic (uses blocking assignment and is asynchronous)
always @* begin
  next_hblank = hblank; // <-- default keep previous
  next_hsync = hsync;
  next_vblank = vblank;
  next_vsync = vsync;
  next_hcnt = hcnt + 10'h001; // <-- default increment
  next_vcnt = vcnt;

  // calc next values, update as needed
  case (hcnt)
    10'd640: next_hblank = 1'b1;
    10'd656: next_hsync = 1'b0;
    10'd752: next_hsync = 1'b1;
    10'd800: begin
      next_hblank = 1'b0;
      next_hcnt = 10'h001;
      next_vcnt = vcnt + 10'h001;
      case (vcnt)
        10'd480: next_vblank = 1'b1;
        10'd490: next_vsync = 1'b0;
        10'd492: next_vsync = 1'b1;
        10'd525: begin
          next_vblank = 1'b0;
          next_vcnt = 10'h001;
        end
      endcase
    end
  endcase
end


Your fields size and queue have package access, they need to be private so only your class can control them.

private final int size;
private final T[] queue;

And because their values are known at initialization, its good practice to declare them final.

your isempty method is not Camelcase, use isEmpty instead.
Some validation on the size parameter is needed as well.

 if(size<=0){
  throw new IllegalArgumentException("Size cannot be less than or equal to zero");
 }

Something I love about the this keyword is that it helps you finding a name for your variables

 public Queue(int size) { // size is more relevant than inSize
   if(size<=0){
       throw new IllegalArgumentException("Size cannot be less than or equal to zero");
    }
    this.size = size;
    queue = (T[]) new Object[size];
    front = -1;
    rear = -1;
}


Do not select elements that contain data attributes

Very good question. I'm pretty sure this can't be done within the selector.

However, instead of checking the data every time it's clicked, filter the collection before applying the event listener:

$('a[href^="#"]').filter(function () {
    return $.isEmptyObject( $(this).data() );
}).click(function (event) {
    // Your code here...
});

If you don't care about IE, you can check the dataset property directly, which is much faster and much more reliable, since $(this).data() also contains any arbitrary data that might have been set (possibly by a plugin):

$('a[href^="#"]').filter(function () {
    return $.isEmptyObject( this.dataset );
})

If you find that you have to do this a lot, you can abstract it into a custom filter, which you can then use in your selectors:

jQuery.expr[':']['has-data'] = function (el) {
    return ! $.isEmptyObject( $(el).data() );
    // If you don't care about IE:
    // return ! $.isEmptyObject( el.dataset );
};

Then just use it throughout your code:

$('a[href^="#"]:not(:has-data)').click(function (event) {
    // Your code here...
});


The solution above shows some very old coding practices that are no longer valid. In addition the code has some level of complexity that is not required - almost like a Rube Goldberg approach!

The use of Option Explicit is to be applauded. Same as the lack of On Error [Resume Next]!

Main

Some broad comments:

The use of "Main" as a function name is not required and hides what
the real intent is.
You use a 2-D array when a single dimension will do.
You juggle values through different variables without any real reason.
Why not show the code you will use to extract the IDs from the Excel file?
You call CloseConnection but you have not opened one.

Refactored code below

Private Sub Main()
    ' Assuming I've already read values from column into an array
    'Dim customerIDs(1 To 3) As Long
    'customerIDs(1) = 1
    'customerIDs(2) = 2
    'customerIDs(3) = 3
    Dim customerIDs as Variant
    customerIDs = Range("NamedRangeHoldingColumnOfIDs") ' this will return an array

    Dim i As Long
    Dim customer As String

    ' For each ID run a query, retrieve and display a customer name
    OpenConnection ' should Open and Close in the same scope
    For i = 1 To UBound(customerIDs)
        If IsNum(customerIDs(i)) then  ' doesn't hurt to add a bit of error checking
            customer = GetCustomer(CLng(customerIDs(i)))
            Debug.Print customer
        End If
    Next i
    CloseConnection
End Sub

Helper functions

You have fractured your helper functions too much, you are probably confusing yourself with your logic.

Your ReadRecord function reads all records in the recordset, which you have set with your GetCustomer, QueryDB and ExecuteCmd routines.
Perhaps breaking them apart would make sense if you were to re-use
them, but your calls (parameters) and returns are not set up to allow
this. Your use of globals would make re-use fraught with danger
(particular in overlapping or older calls, and race conditions)

Refactoring all this into one function makes it cleaner.

Private Function GetCustomer(ID As Long) As String
    Dim sqlQuery As String
    Dim readResult as String
    sqlQuery = "SELECT Customer FROM Customers WHERE Customers.ID = " & ID
    If (pDb Is Nothing) Then
        OpenConnection  ' could consider opening and closing connection only in this scope - could be expensive but safer.
    End If

    ' Return
    pDbCmd.CommandText = sqlQuery  ' Assumes pDbCmd is valid
    pDbCmd.CommandType = adCmdText
    Set pDbRecordset = pDbCmd.Execute
    Do While Not (pDbRecordset.EOF)
        readResult = pDbRecordset.Fields("Customer").value
        pDbRecordset.MoveNext
    Loop
    GetCustomer = readResult
End Function

Connections

Having done this, you rely on globals to manage your connections. All fine if you have a single purpose - but if you are going to make this more complex it will introduce problems.
You can fix this by treating your Open and Close as parameterised routines.

Private Sub CloseConnection(Db as ADODB.Connection, DBRecordSet as ADODB.Recordset, DbCmd As ADODB.Command)
    Db.Close
    Set DbRecordset = Nothing
    Set DbCmd = Nothing
    Set Db = Nothing
End Sub

Similarly for OpenConnection

Private Sub OpenConnection(ByVal DbName, [ByRef] Db as ADODB.Connection, [ByRef] DbCmd As ADODB.Command ) 'As Boolean - perhaps indicate if successful?
    Set Db = New ADODB.Connection
    Set DbCmd = New ADODB.Command
    Dim dataSource As String
    dataSource = ThisWorkbook.Path & DbName '"\db.accdb"
    Dim connectionString As String
    connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & dataSource & ";Persist Security Info=False;"
    Db.Open(connectionString)
    DbCmd.ActiveConnection = Db
End Sub

Additional thoughts

Having gone through the above process, the key DB element is the DBCmd object. Your Open/Close could simply pass that as a result with all other workings to get there encapsulated within the relevant function.

You don't do any error checking.

What happens if you cannot open the database?
What happens if you cannot open the query?
What happens if you cannot find a relevant record?


That was a fun little challenge to code against, although my solution was very different from yours!

With those kinds of challenges, it can be tempting to just write throw-away code. I would suggest though, if you are serious about coding, to just try to write the most professional code you can, even if it's just to solve this one challenge.

In particular, I find your code is not very expressive. There's no functions/methods/classes, there's really not anything telling me (or future you) what this code is for at all, so I'm having to actually read the code from beginning to end to even get an idea what it's supposed to do (let alone if it's doing it correctly). This also makes it much less reusable.

We can start by organizing input handling separately from program logic. In fact, I think __main__ would be a perfect place to handle getting input. You'll notice my code is somewhat more verbose, I personally prefer to make it obvious when doing "breaky" things like reading raw text input.

if __name__ == "__main__":
    num_cases = int(input())
    for case in range(num_cases):
        no_of_cubes = int(input())
        side_lengths = list(map(int, input().strip().split()))

I don't think it would be unreasonable to create a function to handle text input, but that may be a bit much for this. So, we have our input, now we just need to handle it.

One data structure to consider, and for which it seems like this challenge was written, is the deque...

  Deques are a generalization of stacks and queues (the name is pronounced “deck” and is short for “double-ended queue”). Deques support thread-safe, memory efficient appends and pops from either side of the deque with approximately the same O(1) performance in either direction.

However, you found a shorter, less literal way to pass the test cases, which, in the end, is the goal. So if you wanted to keep it at that, I'd just move the logic into a function and return a bool, and call it a day.

def can_be_piled(no_of_cubes: int, side_lengths: List) -> bool:
    if max(side_lengths) not in (side_lengths[0], side_lengths[-1]):
        return False
    return True

I also made a few other utility functions, one to split up the side lengths, the other to display the output. Note that I used Python 3 type hints in each function signature, in case that looks unfamiliar.

from typing import List

def can_be_piled(no_of_cubes: int, side_lengths: List) -> bool:
    if max(side_lengths) not in (side_lengths[0], side_lengths[-1]):
        return False
    return True

def get_side_lengths(raw_input: str) -> List:
    return list(map(int, raw_input.strip().split()))

def display_output(truthy: bool) -> None:
    if truthy:
        print("Yes")
    else:
        print("No")

if __name__ == "__main__":
    num_cases = int(input())
    for case in range(num_cases):
        no_of_cubes = int(input())
        side_lengths = get_side_lengths(input())
        display_output(can_be_piled(no_of_cubes, side_lengths))


I haven't been following this thread from the beginning, so I'm more confused than you expect readers to be by this point. It would be a good idea for you to provide a complete compilable example each time — even just as a Godbolt link, if you want to keep the question's focus on some little piece of the code.
In fact, I prefer to see a Godbolt link (in addition to seeing the code in the question as you correctly have done), as it saves me the trouble of pasting your code into Godbolt myself. :) Here's a link to your code: Godbolt.

std::variant<double> testNumber = 1;

This doesn't compile in C++20. Did it use to? If so, yikes, that's a pretty big API break for C++... but not your problem. Anyway, change it to 1.0 and recompile.

template<typename T_variant, typename T>
static inline auto

Lose the static inline. Templates are effectively inline by definition, and you don't want this template to be static — you don't want to force each translation unit to keep its own unique copy (in the case that it's not optimized away by the inliner).
I'm not a fan of Giraffe_case. Template parameter names should be short and CamelCase; here I recommend V.
Your std::visit lambda has a useless return arg;. In fact, this entire function should look more like
template<class V, class T>
auto get_from_variant(V input) {
    return std::visit([&](auto&& arg) {
        return static_cast<T>(arg);
    }, input);
}

With the cruft removed, we have brain cells free to focus on the next level of pedantry: You're taking arg by forwarding reference (auto&&), but you're not actually forwarding it to the static_cast. Maybe we should use static_cast<T>(static_cast<decltype(arg)>(arg)) here, so that if arg is an rvalue reference, it'll get moved into T's constructor?
But wait; arg will never be an rvalue reference, because we're visiting an lvalue input! So maybe we shouldn't expect to modify the arg we visit — we could take it as const auto& arg. But if we don't expect to modify input, maybe it should be taken by— yeah, wait a minute, why are we making a copy of input here? Just take it by const reference to begin with!
template<class V, class T>
auto get_from_variant(const V& input) {
    return std::visit([](const auto& arg) {
        return static_cast<T>(arg);
    }, input);
}

I've dropped the [&] from the lambda, since it doesn't require any captures.
We should also look at the template parameters to get_from_variant. V can be deduced and T can't; it always always always makes sense to put non-deducible parameters first.
template<class T, class V>
auto get_from_variant(const V& input) {
    return std::visit([](const auto& arg) {
        return static_cast<T>(arg);
    }, input);
}

Now our main driver looks like this:
std::variant<double> testNumber = 1.0;
std::cout << get_from_variant<double>(testNumber);

std::vector testVector1 = {
    std::variant<double>(3.14),
    std::variant<double>(3.14),
    std::variant<double>(3.14),
};
std::cout << get_from_variant<double>(
    recursive_transform(testVector1, [](const auto& x){
        return get_from_variant<double>(x) + 1;
    }).at(0)
) << std::endl;

Meanwhile, in recursive_transform, you have a typo: const T input when you meant const T& input. You can mechanically grep for these typos, and you should!

Again, remove static inline from templates.

The name _Fn is reserved for the implementation; just use F.

Copying func into the lambda isn't necessary; you should use [&] as your default for every lambda you write (unless, as above, you can get away with plain []).

Honestly, unless you are rabid about following STL idioms, just pass the callback F by const reference and avoid ever copying it. There is a place in C++ for stateful, mutable callbacks, but transform is not that place.

Your base case is more complicated than it needs to be. Let's fix that.

Putting it all together:
template<class T, class F>
T recursive_transform(const T& input, const F& f) {
    return f(input);
}

template<class T, class F> requires is_iterable<T>
T recursive_transform(const T& input, const F& f) {
    T returnObject = input;
    std::transform(input.begin(), input.end(), returnObject.begin(),
        [&](const auto& element) {
            return recursive_transform(element, f);
        }
    );
    return returnObject;
}

And then, it really seems to me that using std::transform here is overkill: it reads from input twice, once to make the copy and again to do the transform. Suppose we just open-coded it, like this?
template<class T, class F> requires is_iterable<T>
T recursive_transform(const T& input, const F& f) {
    T output = input;
    for (auto&& elt : output) {
        elt = recursive_transform(elt, f);
    }
    return output;
}

Of course we could use C++20 Ranges to do something like this:
template<class T, class F> requires is_iterable<T>
T recursive_transform(const T& input, const F& f) {
    auto transformed = input | std::views::transform([&](auto&& x) {
        return recursive_transform(x, f);
    });
    return T(transformed.begin(), transformed.end());
}

That's slower to compile and generates bigger code — but it might indeed be faster at runtime, if T::value_type is expensive to copy, because we're eliminating the copy-assignments on T::value_type — we're just constructing directly in place.


var parts = _.filter(parts, (_, i) => i % 2 === 1) this looks like a habit from python. I do not recommend shadowing lodash in any part of the code, it is harder to read.


Access an associative array value given an array of keys in PHP

This seems alright, but you could use foreach, and checking and returning can be simpler:

class Config
{
    protected static $values;

    ...

    public static function get()
    {
        $val = &self::$values;
        foreach(func_get_args() as $argument)
        {
          $val = &$val[$argument];
          if(empty($val)) return "";
        }
        return $val;
    }
}

I would call this more elegant, but it's not more efficient. (I did not test the code.)


A package for outer-package communications

The below code would be cleaner with object literal notation :

    // a basic registry pattern with get/set and getMany/setMany
    $P.Reg = (function () {
        var publik = {},
            register = {};
        publik.get = function (key) {
            return register[key];
        };
        publik.set = function (key, value) {
            register[key] = value;
        };
        publik.setMany = function (o) {
            $A.someKey(o, function (val, key) {
                register[key] = val;
            });
        };
        publik.getMany = function () {
            return register;
        };
        return publik;
    }());

would be

    // a basic registry pattern with get/set and getMany/setMany
    $P.Reg = (function () {
        var register = {};
        return {
            get : function (key) {
                return register[key];
            },
            set : function (key, value) {
                register[key] = value;
            },
            setMany : function (o) {
                $A.someKey(o, function (val, key) {
                    register[key] = val;
                });
            },
            getMany : function () {
                return register;
            }
        };
    }());

I also note that

getMany is wrongly named, getAll perhaps ?
not sure what someKey does, is it any different from for( var key in o) ?


Any better way to solve Project Euler Problem #5?

You are recomputing the list of prime numbers for each iteration. Do it just once and reuse it. There are also better ways of computing them other than trial division, the sieve of Eratosthenes is very simple yet effective, and will get you a long way in Project Euler. Also, the factors of n are all smaller than n**0.5, so you can break out earlier from your checks.

So add this before the num for loop:

prime_numbers = list_of_primes(int(end**0.5))

And replace prime_gen with :

prime_gen =(each_prime for each_prime in prime_numbers if each_prime <= int(num**0.5))

The list_of_primes function could be like this using trial division :

def list_of_primes(n)
    """Returns a list of all the primes below n"""
    ret = []
    for j in xrange(2, n + 1) :
        for k in xrange(2, int(j**0.5) + 1) :
            if j % k == 0 :
                break
        else :
            ret.append(j)
    return ret

But you are better off with a very basic sieve of Erathostenes:

def list_of_primes(n) :
    sieve = [True for j in xrange(2, n + 1)]
    for j in xrange(2, int(sqrt(n)) + 1) :
        i = j - 2
        if sieve[j - 2]:
            for k in range(j * j, n + 1, j) :
                sieve[k - 2] = False
    return [j for j in xrange(2, n + 1) if sieve[j - 2]]

There is an alternative, better for most cases, definitely for Project Euler #5, way of going about calculating the least common multiple, using the greatest common divisor and Euclid's algorithm:

def gcd(a, b) :
    while b != 0 :
        a, b = b, a % b
    return a

def lcm(a, b) :
    return a // gcd(a, b) * b

reduce(lcm, xrange(start, end + 1))

On my netbook this gets Project Euler's correct result lightning fast:

In [2]: %timeit reduce(lcm, xrange(1, 21))
10000 loops, best of 3: 69.4 us per loop


Improving speed of word search algorithm

widht is misspelled; it should be width. :-)
Some generalities regarding naming convention:

Variables and functions should start with a lowercase letter:

// "camel case"
int camelCaseVariable;
void camelCaseFunction() {}

// "snake case"
int snake_case_variable;
void snake_case_function() {}

Custom types should start with a capital letter:

class Class;

Macros should be uppercase:

#define MACRO 0

Check()'s body can be simplified as such:

return Letter == Matrix; // already returns true or false

Its parameters should also be passed by constant reference since they're not being modified:

bool Check(string const& Letter, string const& Matrix) {}

You should make sure the input file is open before proceeding.  If not, terminate from main() by returning 1 or EXIT_FAILURE.
You could vastly improve readability by using more functions.  Putting everything in main() is not always a good idea, especially with a lot of nesting.  Define the functions to perform one important task, and call them in main() or wherever else as needed.  Function call overhead shouldn't hurt you here, making the readability aspect more important.

In its current state, more comments may help others follow the code.  That, in turn, could help flesh out any optimization issues.  However, this isn't a substitute for writing readable code.


I'm always a fan of using interfaces wherever possible so that unit tests can mock out my component easily. So let's create a couple of interfaces:

public interface IFolder
{
    IEnumerable<IFolder> Folders { get; }

    IEnumerable<IFolder> AllFolders { get; }

    IEnumerable<string> Files { get; }

    IEnumerable<string> AllFiles { get; }

    IFolder Up();

    IFolder Down(string folderName);

    void Create();

    void Empty();

    void CopyTo(IFolder destination);

    void CopyTo(IFolder destination, Func<string, bool> filter);

    void Run(string exe, string args = "");
}

and

internal interface IFolders
{
    IFolder Bin { get; }

    IFolder App { get; }

    IFolder Docs { get; }

    IFolder Temp { get; }
}

I also like to re-use constants. And I added another implicit operator to go with your new constructor:

public class Folder : IFolder
{
    private const string DirectoryWildcard = "*";

    private const string FileWildcard = "*.*";

    private readonly string _Path;

    public Folder(Assembly assembly)
        : this(Path.GetDirectoryName(assembly.Location))
    {
    }

    public Folder(string path)
    {
        this._Path = path;
    }

    public override string ToString() => this._Path;

    public static implicit operator string(Folder folder) => folder.ToString();

    public static implicit operator Folder(string path) => new Folder(path);

    public static implicit operator Folder(Assembly assembly) => new Folder(assembly);

    public IEnumerable<IFolder> Folders => Directory
        .GetDirectories(this, DirectoryWildcard, SearchOption.TopDirectoryOnly)
        .Select(path => new Folder(path));

    public IEnumerable<IFolder> AllFolders => Directory
        .GetDirectories(this, DirectoryWildcard, SearchOption.AllDirectories)
        .Select(path => new Folder(path));

    public IEnumerable<string> Files => Directory.GetFiles(this, FileWildcard, SearchOption.TopDirectoryOnly);

    public IEnumerable<string> AllFiles => Directory.GetFiles(this, FileWildcard, SearchOption.AllDirectories);

    public IFolder Up() => new Folder(new DirectoryInfo(this).Parent.FullName);

    public IFolder Down(string folderName) => new Folder(Path.Combine(this, folderName));

    public void Create() => Directory.CreateDirectory(this);

    public void Empty()
    {
        var directoryInfo = new DirectoryInfo(this);

        if (!directoryInfo.Exists)
        {
            return;
        }

        foreach (var file in AllFiles)
        {
            File.Delete(file);
        }

        foreach (var folder in Folders)
        {
            Directory.Delete(folder.ToString(), true);
        }
    }

    public void CopyTo(IFolder destination) => this.CopyTo(destination, file => true);

    public void CopyTo(IFolder destination, Func<string, bool> filter)
    {
        // Create directories
        foreach (var folder in this.AllFolders)
        {
            Directory.CreateDirectory(folder.ToString().Replace(this, destination.ToString()));
        }

        // Copy all the files & replaces any files with the same name
        foreach (var filePath in this.AllFiles.Where(filter))
        {
            File.Copy(filePath, filePath.Replace(this, destination.ToString()), true);
        }
    }

    public void Run(string exe, string args = "")
    {
        var defaultCurrentDirectory = Environment.CurrentDirectory;

        Environment.CurrentDirectory = this;
        try
        {
            var process = new Process { StartInfo = { FileName = exe, Arguments = args } };

            process.Start();
            process.WaitForExit();
            if (process.ExitCode != 0)
            {
                throw new InvalidOperationException(
                    $"{exe} process failed with exit code {process.ExitCode}.");
            }
        }
        finally
        {
            Environment.CurrentDirectory = defaultCurrentDirectory;
        }
    }
}

And finally, the Folders.cs implementation:

internal class Folders : IFolders
{
    private readonly Assembly _Assembly;

    public Folders(Assembly assembly = null)
    {
        this._Assembly = assembly ?? Assembly.GetExecutingAssembly();
    }

    public static IFolders Default => new Folders();

    public IFolder Bin => new Folder(this._Assembly);

    public IFolder App => this.Bin.Up();

    public IFolder Docs => this.App.Down("Docs");

    public IFolder Temp => this.App.Down("Temp");
}

Now that it's not static, you'll either have to create a new one with a particular assembly, or Folders.Default will have the current assembly as per original design.


1. Comments on your code

There's no documentation. What does your program do and how should it be used?
Your program is not split up into functions. This makes it hard to test it from the interactive interpreter.
The name data.csv seems arbitrary. Surely this should be an argument to the program? Similarly for 'part_%03d.txt' and block_size = 200000.
You read the whole of the input file into memory and then use .decode, .split and so on. It would be more efficient to read and write one line at a time, thus using no more memory than is needed to store the longest line in the input.
In Python, a file object is also an iterator that yields the lines of the file. It's often simplest to process the lines in a file using for line in file: loop or line = next(file).
When you have an infinite loop incrementing a counter, like this:

counter = 0
while True:
    counter += 1

consider using itertools.count, like this:

for counter in itertools.count(1):

(But you'll see below that it's actually more convenient here to use enumerate.)
Since your data is encoded in UTF-8, and only character you actually look for in the input is the newline character (\n), there is no need for you to decode the input or encode the output: you could work with bytes throughout. (But if you insist on decoding the input and encoding the output, then you should  pass the encoding='utf-8' keyword argument to open.)

2. Revised code

Here's how I'd implement your program. The only tricky aspect to it is that I have two different loops that iterate over the same iterator f (the first one using enumerate, the second one using itertools.chain). This works because the iterator state is stored in the object f, so the two loops can independently fetch lines from the iterator and the lines still come out in the right order.

from itertools import chain

def split_file(filename, pattern, size):
    """Split a file into multiple output files.

    The first line read from 'filename' is a header line that is copied to
    every output file. The remaining lines are split into blocks of at
    least 'size' characters and written to output files whose names
    are pattern.format(1), pattern.format(2), and so on. The last
    output file may be short.

    """
    with open(filename, 'rb') as f:
        header = next(f)
        for index, line in enumerate(f, start=1):
            with open(pattern.format(index), 'wb') as out:
                out.write(header)
                n = 0
                for line in chain([line], f):
                    out.write(line)
                    n += len(line)
                    if n >= size:
                        break

if __name__ == '__main__':
    split_file('data.csv', 'part_{0:03d}.txt', 200000)

3. Generating the output blocks instead

Do you really want to process a CSV file in chunks? I can't imagine why you would want to do that. Surely either you have to process the whole file at once, or else you can process it one line at a time?

Processing a file one line at a time is easy:

with open(filename, encoding='utf-8') as f:
    header = next(f)
    for line in f:
        # process line

But given that this is apparently a CSV file, why not use Python's built-in csv module to do whatever you need to do? Like this:

import csv
with open(filename, encoding='utf-8', newline='') as f:
    reader = csv.reader(f)
    header = next(reader)
    for row in reader:
        # row[0] is the first field in this row, and so on.


Simpler Methods.

the code:

public string removeSpaces(string plainIn)
{
    plainIn = plainIn.Replace(" ", string.Empty);
    return plainIn;
}

Could be:

public string removeSpaces(string plainIn)
{
    return plainIn.Replace(" ", string.Empty);
}

Which begs the question... why have the removeSpaces method at all?

The same is true with toUCase()

Simpler Conversion

Why use Convert.ToInt32(....); and Convert.ToChar(...) when (int) and (char) will do?

Simpler Math

This line here (the crux of the problem), can be simplified using modulo and removing the Magic Numbers:

int Num = Convert.ToInt32(charArray[i]) + shift;
readOut += Convert.ToChar(Num > 90 ? Num -= 26 : (Num < 65 ? Num += 26: Num));

can be:

// Constants....
private const int LETTERA = (int)'A';
private const int LETTERCOUNT = (int)'Z' - LETTERA + 1;

// actual code.
 readOut += (char)(LETTERA + (((int)charArray[i] + shift - LETTERA + LETTERCOUNT) % LETTERCOUNT));

(See ideone here)

Without the conditional / ternary operator it is more likely to be tighter/faster code as well.

Comments

You have used magic numbers, so you attempted to document them with a comment:

public string shift(string plainIn, int shift)
{// 65=a 90=z in ASCII

But, the comments are wrong, and misleading (wrong case character).

 {// 65=A 90=Z in ASCII

Symmetry

When you have methods that do symmetrical work (they are closely related), then you should ensure the parameter names are the same.... For example, you have:

public string Encrypt(string ReadIn, int Shift)

and

public string Decrypt(string ReadIn, int amountShift)

The second should have the parameter name Shift


It is a matter of taste, so there is no 'better'. But more common seams to be time.getHours(); because often the conventions of JavaBean are used.

If you work in a team, I would discuss the naming conventions to use with them.


display:none instead of .hide()

Instead of hiding them like this:

 $(".ServicesSectionWrapper,.ServicesSectionWrapper .Selector,.ServicesS...hide()

Add a class common to each (on the HTML) and with that class, use display:none.

.commonClass{display:none}

Sequential Animation

Well, I haven't found anything elegant for sequential jQuery animation (or haven't looked that hard). However, I have made this which executes functions sequentially. It isn't a generic solution for animation, only for this situation.

function animateQueue(q){

    // Get the next item
    var next = q.shift();

    // Remove from the array the selector (or jquery object) and function name
    var obj = $(next.shift());
    var functionName = next.shift();

    // Add in the callback that runs after the animation
    next.push(function(){
       if(!q.length) return; // When done, don't continue
       animateQueue(q);      // otherwise, pass on the queue
    });

    // Run the animation
    jQuery.fn[functionName].apply(obj,next);
}

All you need to do is write the queue like so:

[selector OR jQuery object, animation function, params except the callback]
animateQueue([
    ['#red','fadeIn',400],
    ['#blue','fadeIn',400],
    ['#green','fadeIn',400],
    [$('#red'),'fadeOut',400],
    [$('#blue'),'fadeOut',400],
    [$('#green'),'fadeOut',400]
]);

Added for a jQuery object since...

Cache objects

to avoid fetching them from the DOM everytime

var red = $('#red');
var blue = $('#blue');
var green = $('#green');

animateQueue([
    [red,'fadeIn',400],
    [blue,'fadeIn',400],
    [green,'fadeIn',400]
]);

Taking it further

Since the only vital function for the pageLoader with respect to this functionality is selecting what to animate, we can move out everything but the selection. Further, we can store the animation queues into an array, and have pageIndex select them instead. pageIndex should be 0-indexed, so we subtract 1:

var queues = [
  first : [...],
  second : [...],
  third : [...]
];

function animateQueue(q){...}

function pageLoader(pageIndex) {
  animateQueue(queues[pageIndex-1]);
}


Displaying IP addresses in Go using Stringer interface

Your first variant is unnecessary detailed and hard to read:

an IPv4 address consists of exactly 4 digit groups
4 is a small number, maybe it's worth to inline the for loop
the for loop treats the case k == 0 specially
the += operator for strings allocates a new string each time
the code is much longer than the description in the task "join the four numbers with dots"

Your second variant is short, easy to grasp and probably efficient enough for all practical cases.

func (ip IPAddr) String() string {
    return fmt.Sprintf("%v.%v.%v.%v", ip[0], ip[1], ip[2], ip[3])
}

You can replace the %v with %d to make it more specific, since the arguments are integer values.

The main reason for choosing this variant is readability. The format string shows at a glance how the formatted string will look like.

If you want to write the fastest possible code, you should probably allocate a byte array of size 3+1+3+1+3+1+3 and append each number and dot individually, without using a loop at all.


Compare two ArrayList in a two way comparison?

How about streams API?

public boolean compare(List<Task> source, List<Task> actual) {
    Set<Task> sourceDifference = source.stream()
          .filter(t->!actual.contains(t))
          .collect(Collectors.toSet());
    for (Task t: sourceDifference) {
        System.out.println(String.format("Task %s not present in actual", t));
    }

    Set<Task> actualDifference = actual.stream()
          .filter(t->!source.contains(t))
          .collect(Collectors.toSet());
    for (Task t: actualDifference) {
        System.out.println(String.format("Task %s not present in source", t));
    }

    return sourceDifference.isEmpty() && actualDifference.isEmpty();
}


Implementing The Proper Undead's Cave Generator


Checks if user is part of Active Directory group

OnAuthorization()

If the possibility exists that HttpContext.Current.User.Identity.Name dosn't contain \ the call to alias.Substring() will fail. Instead of calling two times alias.IndexOf("\\") you could use string.Split().

This

if (CheckAccess(accessLevel, alias, domain))
{
    return;
}

is a little bit useless. You don't rellay care about the returned value of CheckAccess() hence you could remove it. But I guess thats not what you want. Instead you should e.g throw an AuthenticationException.

CheckAccess

PrincipalContext, GroupPrincipal and UserPrincipal are implementing the IDisposable interface, hence its best practice to enclose the usage in a using block.

Local variables should, based on the .NET Naming Guidelines, be named using camelCase casing and shouldn't use abbreviations. Hence AdUser should be activeDirectoryUser and AdGroup should be activeDirectoryGroup.

You should validate group and userDomain wether you really need to do the loop and you could store the result in a bool as well like so

bool userDomainIsInDomain1 = userDomain.ToLower().Contains("domain1");
bool userDomainIsInDomain2 = userDomain.ToLower().Contains("domain2");
bool groupCanWrite = group == "WRITE";

if(!userDomainIsInDomain && !userDomainIsInDomain2 && !groupCanWrite)
{
    return false;
}

We can now use the introduced bool variables in the loop like so

foreach (Domain domain in forest.Domains)
{
    if (domain.Name.Contains("domain1"))
    {
        using (var ctx = new PrincipalContext(ContextType.Domain, domain.Name, null, ContextOptions.Negotiate | ContextOptions.SecureSocketLayer, "username", "password"))
        {
            if (groupCanWrite)
            {
                activeDirectoryGroup = GroupPrincipal.FindByIdentity(ctx, "group1");
            }

            if (userDomainIsInDomain1)
            {
                activeDirectoryUser = UserPrincipal.FindByIdentity(ctx, user);
            }
        }
    }
    else if (domain.Name.Contains("domain2"))
    {
        if (userDomainIsInDomain2)
        {
            using(var ctx = new PrincipalContext(ContextType.Domain, domain.Name, null, ContextOptions.Negotiate | ContextOptions.SecureSocketLayer, "username", "password"))
            {
                activeDirectoryUser = UserPrincipal.FindByIdentity(ctx, user);
            }
        }
    }
}

but wait we can do better than that. We should extract two methods, one to get the an UserPrincipal and one to get a GroupPrincipal.

private UserPrincipal FetchUserPrincipal(string domainName, string userName, string password, string user)
{
    using (var ctx = new PrincipalContext(ContextType.Domain, domainName, null, ContextOptions.Negotiate | ContextOptions.SecureSocketLayer, userName, password))
    {
        return UserPrincipal.FindByIdentity(ctx, user);
    }
}

I am unsure about the user variable because I don't know if user is the same as "username".

private GroupPrincipal FetchGroupPrincipal(string domainName, string userName, string password, string groupName)
{
    using (var ctx = new PrincipalContext(ContextType.Domain, domainName, null, ContextOptions.Negotiate | ContextOptions.SecureSocketLayer, userName, password))
    {
        return GroupPrincipal.FindByIdentity(ctx, groupName);
    }
}

After implementing these methods the former CheckAccess() method will look like this

private bool CheckAccess(string group, string user, string userDomain)
{
    bool userDomainIsInDomain1 = userDomain.ToLower().Contains("domain1");
    bool userDomainIsInDomain2 = userDomain.ToLower().Contains("domain2");
    bool groupCanWrite = group == "WRITE";

    if(!userDomainIsInDomain && !userDomainIsInDomain2 && !groupCanWrite)
    {
        return false;
    }

    GroupPrincipal activeDirectoryGroup = null;
    UserPrincipal activeDirectoryUser = null;
    using (Forest forest = Forest.GetCurrentForest())
    {
        foreach (Domain domain in forest.Domains)
        {
            if (domain.Name.Contains("domain1"))
            {
                if (groupCanWrite)
                {
                    activeDirectoryGroup = FetchGroupPrincipal(domain.Name, "username", "password", "group1");
                }

                if (userDomainIsInDomain1)
                {
                    activeDirectoryUser = FetchUserPrincipal(domain.Name, "username", "password", user);
                }
            }
            else if (userDomainIsInDomain2 && domain.Name.Contains("domain2"))
            {
                activeDirectoryUser = FetchUserPrincipal(domain.Name, "username", "password", user);
            }
        }

        if (AdGroup != null && AdUser != null)
        {
            return AdUser.IsMemberOf(AdGroup);
        }
        return false;
     }
}

As you can see, I have simplified the if..else at the bottom as well.


Answerifying what Joseph the Dreamer commented on,

there is really not enough code to build a general routine out of, the code is fine as is. Though ideally you could add comments.


Creating a 2-D array whose first elements come from a 1-D array

For the most part, what you are doing is fine (like @Ashwin commented on your question).

About the only thing I really don't like is the name of the function getResult. That name is just really useless. How about convert2D or something? Your other variable names are well put together, and make sense.

Another issue you may run in to is if someone specifies bad input values. Your code will fail with a NoSuchElementException if someone sets a rowSize of 0.

From a performance perspective, I expect that your code is pretty much as fast as it can be too - in a single-threaded process.

Using a Java 8 stream you can possibly make the process a bit more parallel, but it would be more complicated to read. Still, I thought it would be an interesting thing to see..... though, in a production system, I would be happy to see your code instead (i.e. the following code is just a thought, not a recommendation):

public static double[][] convert2D(double[] data, int rowSize) {
    return IntStream.range(0, data.length)
        .parallel()
        .mapToObj(i -> {
            double[] row = new double[rowSize];
            row[0] = data[i];
            return row;
        })
        .toArray(s -> new double[s][]);
}

The above has the advantage that each row may be created in a different thread, and "all CPUs" on your system will be creating rows. I did some performance benchmarks, and, if the rowSize is small (10 or so) then your code is faster. If the row size starts getting larger (like 1000 or so) then the parallel code starts getting faster.

Even though the stream code can sometimes be faster, I would still probably prefer to use your code.

If you want raw numbers (Note the unit for the 10-size row is MicroSeconds, and for 1000 size row is MilliSeconds), this is the timing for row-size of 10 for 1000 rows, run 1000 times:

Task 1d2d -> Single: (Unit: MICROSECONDS)
  Count    :      1000      Average  :   62.9370
  Fastest  :   41.4460      Slowest  : 1383.5230
  95Pctile :   95.9190      99Pctile :  124.3400
  TimeBlock : 91.553 72.914 55.230 65.829 66.551 48.998 60.405 49.428 63.745 54.717
  Histogram :   887   109     3     0     0     1

Task 1d2d -> Stream: (Unit: MICROSECONDS)
  Count    :       1000      Average  :   145.3900
  Fastest  :    20.9210      Slowest  : 85596.0480
  95Pctile :   115.2600      99Pctile :   317.3620
  TimeBlock : 983.900 101.962 61.807 49.069 57.070 36.698 32.841 34.045 45.761 50.754
  Histogram :   519   339   116    17     4     0     4     0     0     0     0     1

This is the timing for row-size 1000 for 1000 rows run 1000 times:

Task 1d2d -> Single: (Unit: MILLISECONDS)
  Count    :     1000      Average  :   1.3570
  Fastest  :   1.1601      Slowest  :   7.7698
  95Pctile :   2.5799      99Pctile :   4.2958
  TimeBlock : 2.175 1.387 1.284 1.225 1.217 1.244 1.253 1.314 1.260 1.211
  Histogram :   948    44     8

Task 1d2d -> Stream: (Unit: MILLISECONDS)
  Count    :     1000      Average  :   0.9919
  Fastest  :   0.5680      Slowest  :  92.7422
  95Pctile :   2.2405      99Pctile :   4.0231
  TimeBlock : 2.672 1.074 0.742 0.811 0.763 0.773 0.762 0.733 0.772 0.817
  Histogram :   932    19    45     3     0     0     0     1


Every function needs to be called to run. If you have 30 functions you need to call them all but if you want to call them only once you can do something like this:

            var callThemAll = function() {
                function1();
                function2();
                // call them all like this
            }

But there is also a 'lazy way' if I could call it like that. We create an object and these functions will become it's methods and we can iterate over them:

         var objWithFunctions = {
            myFirstFunction: function() {
                // code here
            }
            // rest of your functions
        }

        for(fn in objWithFunctions) {
            objWithFunctions[fn].call();
        }
        // all methods are being called

I wrote a full example here: http://jsbin.com/gaseti/1/

Edit:
After seeing your code(you posted it somewhere) the difference bettwen your function are just 2 strings.
You can make only one function with 2 parameters:

You can insert this into your code

            function updateDisplay(param1, param2) {

              var statElem = document.getElementById(param1);

              if (statElem) {

                statElem.innerHTML = stats[param2];

              }

            }

Call like this:

            updateDisplay("stat_ht", "ht");

Now, to call them all we could do this. Save all parameters into 2 separated arrays

var param1s = ["stat_ht","stat_ht","stat_ht"], param2s = ["ht","ht","ht"];

Call updateDisplay for each of this

            if(param1s.length == param2s.length) {
                for(var i = 0; i <= params1.length; i++) {
                    updateDisplay(param1s[i], param2s[i]);
                }
            }


Concisely adding values in a loop to a column

It would be better to make a list of the parameters,
and then use a loop to perform the assignments.
That will reduce the duplication of logic,
for example in the long grep(...).

params <- list(
  c("/comp-a/", "a: spont-conv"),
  c("/comp-b/", "b: interv-ler-nl"),
  c("/comp-(c|d)/", "c/d: telefoon"),
  c("/comp-e/", "e: onderhandeling"),
  c("/comp-f/", "f: interv-radio-tv"),
  c("/comp-g/", "g: debat"),
  c("/comp-h/", "h: les"),
  c("/comp-i/", "i: spont-comm-radio-tv"),
  c("/comp-j/", "j: reportage-radio-tv"),
  c("/comp-k/", "k: nieuws-radio-tv"),
  c("/comp-l/", "l: comm-radio-tv"),
  c("/comp-m/", "m: misviering"),
  c("/comp-n/", "n: college"),
  c("/comp-o/", "o: voorgelezen")
)

placeholder <- "PLACEHOLDER"
d$Register <- placeholder

for (i in 1:length(params)) {
  pattern.i <- params[[i]][1]
  label.i <- params[[i]][2]
  d$Register[grep(pattern.i, d$Source)] <- label.i
}

if (nrow(d[d$Register == placeholder]) > 0) stop('Register is not assigned in some rows')

Some other minor improvements:

Simplified the regular expressions: pattern will match the same things as .*pattern.*
No need for the perl = T parameter in grep


In your use case, where the constants are private and only ever used in one place, they are pretty much boilerplate. One could argue that the constants group the keys into one condense place where they can be referred to easily when reading code.


Calculating distance and time between waypoints for large files

This line looks like trouble:

        chunk = chunk.append(l)

The docs say it will "append rows of other to the end of this frame, returning a new object." If the new object were to be small, containing a reference to the old object, then you would win, but here I think we're looking at quadratic copying behavior. Consider using .concat() instead, with copy=False. Or perhaps you can preallocate. Verify that the columns of l always match those of the existing chunk.

I recommend adding periodic progress reports that mention throughput and chunk size, to see where performance falls off a cliff. Do a timing run with the call to output.append commented out. Verifying that expected group sizes are passed into distance() would be helpful, too.  And definitely use cProfile, as Graipher suggests.


Javascript split array into n subarrays, size of chunks don't matter

First: Since you already know how many chunks you want, there's no point in checking if the chunk exists and otherwise declare it. In general terms, you should not need to check for objects you can define deterministically.
So instead of doing this check on each loop:
if (typeof result[i] == 'undefined'){
  result[i] = [];
}

create an array of N empty arrays beforehand.
const result = Array.from(Array(chunks),item=>[]);

Second: Albeit the performance difference is negligible, checking for i's value and conditionally reassigning it is less efficient than using the modulo operator on its value regardless
So instead of
results[i].push(...)
i++
i = (i == chunks) ? 0 : i;

You can do
results[i % chunks].push(...)
i++

With the above, your function could be expressed as
function usingShift(myArray, chunks=5){
  const copiedArray = myArray.slice(),
        result=Array.from(Array(chunks),item=>[]);
  let i=0;
  while(copiedArray.length){
    result[i % chunks].push(copiedArray.shift());
    i++;
  }
  return result;
}

Third: As you've been told, shifting from an array is expensive. I understand you're doing it because you want to populate the chunks in the same order of the original array. However you can achieve the same popping from the a reversed array:
If you declare
const a = myArray.slice().reverse();

You can replace the usage of shift with
result[i].push(a.pop());

The function would be something like:
function usingPop(myArray, chunks=5){
  const reversedArr = myArray.slice().reverse(),
        result=Array.from(Array(chunks),item=>[]);
  let i=0;
  while(reversedArr.length){
    result[i % chunks].push(reversedArr.pop());
    i++;
  }
  return result;
}

However... you'd still be copying the array and performing a mutation on the copy.  @Miklós Mátyás solution has the advantage of populating the result without copying nor extracting items from the source array. Now, you haven't said the source array will be always the same (9 elements from 1 to 9). It could as well have repeated/unsorted items, so his solution should take into account not the item itself but its index, which can be expressed as:
function filterByModulo(myArray, chunks=5){
  return Array.from(Array(chunks),(_,modulo)=>{
    return myArray.filter((item,index) =>  index % chunks === modulo);
  });
}

That's pretty clean, but it's filtering on the original array as many times as chunks you want, so it's performance degrades according to the source array length AND the chunk quantity.
Personally I believe this is a case in which reduce would be more appropiate and pretty concise, while avoiding the copying or mutation of the source array.
function usingReduce(myArray,chunks=5) {
   const result=Array.from(Array(chunks),i=>[]);

   return myArray.reduce( (accum,item,index)=>{
      accum[index%chunks].push(item);
      return accum;
   }, result);
}

Finally there's the classic for loop
function classicFor(sourceArr, chunks=5) {
  const lengthOfArray=sourceArr.length;
  const result=Array.from(Array(chunks),i=>[]);

  for(let index=0; index<lengthOfArray ; index++) {
     result[index % chunks ].push(sourceArr[index]);
  }
  return result;
}

I made a test case at JSPerf in which it shows that the for loop is the most efficient. (I threw in forEach and for..of implementations too).
Running with a source array of 5000 items and 5 chunks shows that using pop on the source is more efficient than using shift by a 2.89x factor. It even looks more efficient that reduce. The classic for loop is the fastest whereas filtering N times comes up last by a ratio of 9x the modulo filtering.
If you use a source of 100000 items and 15 chunks the classic for is still the most efficient (still 9x modulo filtering) but the other implementations do scale a bit better than modulo filtering.


Code style

Definitely make the helper methods private;
There is no need to specify the class name when calling a static method in the same call. Instead of AlphanumericPalindromeValidator.isNumericCharacterPair(), just call isNumericCharacterPair();
Do a static import of the static methods of Character;
There is no need for the variables oppositeCharacter and character. Only keep them if it helps you make the code easier to read.
it's possible to make the inner while loop a one liner with a for, but I actually think the while better expresses what is the intent in this case.

If condition

I don't see the point of the first check: i < j. At ths point you know that i<=j. If i == j, the comparison will succeed. This is the case of palindromes with an odd length.

You don't need to check if the char is alphabetic to use Character.toLowerCase(). The method will simply return the same char if there is no mapping to lower case for a given char.

You can also use Character.isLetterOrDigit instead of your isAlphanumeric, unless you care about the subtle differences between "alphatetic" and "letter".

Suggested solution

No helper methods are needed.

public static boolean isValid(String value) {
  char[] chars = value.toCharArray();
  int i = 0;
  int j = value.length() - 1;

  while (i < j) {
    while (!isLetterOrDigit(chars[i]) && i < j) {
      i++;
    }
    while (!isLetterOrDigit(chars[j]) && i < j) {
      j--;
    }

    if (Character.toLowerCase(chars[i]) != toLowerCase(chars[j])) {
      return false;
    }

    i++;
    j--;
  }
  return true;
}


Reducing memory footprint with queue of classes

As @Lstor mentions in the comments, clean up your formatting and indentation.  There should be plenty of resources online, and you can also look at other highly-developed code for ideas.  Above all, keep it clear and consistent.

Naming

This isn't a very descriptive typedef:

typedef vector<double> Vec;

There's no point in using a typedef here if you're just going to name it what it already it.  Name it based on how this type is used in your program, otherwise don't bother renaming it.
Why is this all uppercase?

typedef queue< Subcube>  SUBQUEUE;

It's a type, not a macro.  Just like you have with Vec, have it start with an uppercase, but don't use all uppercase.

Functions

I'm not sure what this is:

for(int j=0;j<n;j++)
{
    nw.e.at(j) = f.e.at(j) +(f.hside/2)*v.at(j);
    }
  }

For one thing, the second closing curly brace is for the function.  But the poor indentation makes it appear to belong to the loop.

Put some whitespace between the operators and operands within the loop statement.  This should be done everywhere for clarity.

Consider adding comments explaining what the loop is doing.  I'm not even sure what is going on inside.  Even if something seems obvious to you, it won't be obvious for everyone.  Now, if something is too obvious, then it doesn't warrant commenting.  But this does.
Many things from main() and below is very unclear.  Not only should everything inside main() be indented, but it appears that you're missing a closing brace (the one above class looks like it belongs to the while loop).

That's an odd place to declare the class.  It should be put into a separate header file, with this file including the header.  If you're going to have main() defined after everything else (which is good), make sure it is the last thing in the file.

Subcube

I'm not sure if you already have the implementation elsewhere and haven't included it here, but make sure you have something for it.  It would be helpful to see how those data members are used and how those member functions perform.
Everything is crammed into public, and there are some things that shouldn't be there.  The data members (k, hside, and e) should be under private.  The functions and constructor should stay public, unless some shouldn't be used by outside code.  If you're not using protected, just get rid of it.  It doesn't need to be there for nothing.
In printvector() and Subcubeset(), you don't need to pass the ints by const&.  Passing an int is relatively cheap, so just pass them by value.
printvector() should be const as it shouldn't be modifying any data members:

void printvector(const int& n) const;

Subcubeset() should use camelCase naming as it's a function.


Reading input from console in F# (as a sequence of lines)

What you have there is a value, but you probably want it to be a function:

let rec readlines () = seq {
    let line = Console.ReadLine()
    if line <> null then
        yield line
        yield! readlines ()
}


Busy waiting on an empty queue is doubleplusungood. Add a condition variable to the queue, let the threads to pthread_cond_wait on it, and pthread_cond_signal it when adding the task to the queue.
The functions you don't want to export (those with the leading underscores) shall be static.
sizeof(type) may lead to a double maintenance problem. Prefer sizeof(var), as in

thread_pool *pool = malloc(sizeof(*pool));


Simple code that checks if you're old enough to drive

class EfficientCode could be improved by naming the class by the purpose of the code. Otherwise your naming is good.
static int age = 0; should be a local variable in Start()
Thread.Sleep(8000); // adds a 8 second delay so that the user could first read the introduction shouldn't be needed because you aren't clearing the Console hence the user could still read it.
Instead of try..catch you could take advantage of the int.TryParse() method which returns a bool indicating the success of "converting" the string to an int. If you would use int.TryParse like below you could omit the restarting in case of an error. If the call succeeds age holds the integer.

while(!int.TryParse(Console.ReadLine(), out age))
{
    Console.WriteLine("ERROR: The entered AGE must be a number!");
    Console.WriteLine("Enter your age");
}

ConfirmInformation() is doing a little bit to much. You should split it into 2 methods. One composing the output and one printing the output and asking for confirmation.

private static string ComposeOutput(String firstName, String middleName, String lastName, int age)
{
    StringBuilder sb = new StringBuilder(100);
    sb.AppendLine("======================================")
      .AppendLine("INFORMATION CHECK:")
      .AppendLine()
      .AppendLine($"FIRST NAME: {firstName}")
      .AppendLine($"MIDDLE NAME: {middleName}")
      .AppendLine($"LAST NAME: {lastName}")
      .AppendLine($"AGE: {age}")
      .AppendLine()
      .AppendLine("Are all those information correct? (Y/N)")
      .AppendLine("======================================");

    return sb.ToString();
}

This method uses the StringBuilder class. The AppendLine() method is returning the StringBuilder itself hence we can use the method calls fluently. It uses $-string interpolation as well.

The former ConfirmInformation() method could then look like so

private static bool ConfirmInformation(string information)
{
    Console.Write(output);

    while (true)
    {
        string input = Console.ReadLine().ToLowerInvariant();
        if (input == "y" || input == "yes")
        {
            return true;
        }
        if (input == "n" || input == "no")
        {
            return false;
        }

        Console.WriteLine("ERROR: Input must be either YES or NO.");
        Console.WriteLine();
        Console.Write(output);
    }
}

I have made a while(true) loop here because your user wouldn't want to restart the whole process if they made a mistake.
As a sidenode, the variable String booleanInput = Console.ReadLine(); is misleading. If Sam the maintainer would read this method the purpose of that variable wouldn't be seen at first glance.


is this a graph?

Yes

Am I missing anything?

In terms of a graph: No.
You have chosen to make your edges uni-directional (thus two edges are required to mark routes between cities). Not an issue in itself but you could have helper functions that create two edges automatically.
In terms of good coding: Yes
You have completely missed out encapsulation.

I think I have a decent understanding of them conceptually, so at least for a basic graph I think this suffices.

Your understanding of a graph is fine. Your understanding of implementing them needs some work. The whole point of a class and encapsulation is to make sure the object keeps and maintains state. Access to the state is controlled so that it can not be manipulated incorrectly.
Unfortunately this is not the case in your implementation. You have leaked the state of the object outside the class thus expose yourself to it be manipulated without the graphs consent (this can make maintaining other information very hard).
Also the state used by the graph may not be scoped in the same way as the graph and thus you can potentially loose state (ie objects dying) thus making the graph invalid.
Additionally you use pointers very poorly. It is very rare to pass pointers across an interface boundaries as there is not associated concept of ownership. Using pointers internally is perfectly fine (i.e. don't pass pointers through public methods).

are the pointers necessary?

Probably not.
Also they are probably not a good idea.

Is there a better way I could be implementing them?

Yes.
If you encapsulate your vertices inside the graph then you can give them 'ids' (probably just the index into a vector of vertices). This ids can be universal and need not change. Or you could use the name as the 'id' it all depends on implementation.

It was my understanding that an Edge is supposed to just contains pointers to vertices.

Rather than use the word 'contains pointers to' just use the term 'refer' (so as not to get us confused with the term references).
An edge has a source and a destination vertex with a value (representing the distance (or cost)) to transfer between them along the edge. How the edge manages that information will depend on implementation.
Code Analysis
Don't do this:
using namespace std;

See https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice
I would not expose Edge publicly.
They are an internal state of the graph. If you expose them you will be unable to change the internal represent of an edge which binds you to this form (i.e. you will not be able to update your class with improvements later).
class Edge

Do not pass pointers over a public interface:
public:
    Edge(Vertex *org, Vertex *dest, int dist)

Here you are passing pointers (in a very C like form).

Are you giving ownership of the objects to the edge (unlikely)?
Are the vertices going to be NULL (unlikely)?

So here I would suggest passing them by reference. BUT I also know that we will storing the vertices internally as well I would refer change the graph to hold a vector of the vertex and then you only need to pass their index in the vector as a reference.
BUT then if we consider that a graph may be huge. We don't want to scan through all the edges when we know a start node. So personally I would have each vertex hold a vector of edges. Since we now know the start node you only need to pass the destination node and cost.
Same thing for Vertex. No need for it to be public (same reason).
class Vertex

No problem with a method printEdges() but output is usually done via operator<<.
void printEdges()

Don't pass pointer through a public interface.
Personally I would copy the method used by the standard containers and pass a const reference and copy it into the object (or with C++ pass a r-value reference that can be moved into the object).
void insert(Vertex *v)

Again with printing. Prefer operator<<
void printGraph()

This is how I would expect the graph to work:
Graph  g;
// Type one: Add vertices (if they don't exist) and add
//           two edges (one for each way).
g.addEdges("Seattle", "Portland", 100);
g.addEdges("Seattle", "Bellevue",  20);

// Type two: Add vertices (if they don't exist) and add
//           one edges
g.addEdge("Everett",  "Seattle", 30);

// Type three: Add new Vertix.
//             Use the id to add edges.
int id1 = g.addVertix("Everett");
int id2 = g.addVertix("Lynnwood");
g.addEdge(id1, id2, 10);


Refactoring digital clock - JavaScript ES5 Functional Programming

You have almost everything in a single function, displayTime.

I'd start by refactoring the date-to-string manipulations into separate functions and leaving only DOM manipulation code in displayTime:

// qs :: String -> Element
// formatTime :: Date -> String
// formatYearMonth :: Date -> String
function displayTime() {
  let date = new Date();
  // handle weekdays here
  qs('.clock-time').textContent = formatTime(date);
  qs('.clock-date').textContent = formatYearMonth(date);
}

formatTime would be more readable IMO if we named your checkTime function zeroPad and used mm/ss for double-digit strings:

function formatTime(date) {
  let zeroPad = (i) => ((i < 10) ? "0" : "") + i; // I know you said no arrow functions, but I can't resist

  let h = date.getHours();
  let mm = zeroPad(date.getMinutes());
  let ss = zeroPad(date.getSeconds());
  return `${h}:${mm}:${ss}`;
}

The weekday indicators can be created once and only get updated as necessary. This makes it obvious what part is dynamic:

let weekdayLIs = Array.from(qs('.clock-weekdays').children);
// I'm no fond of using the index here, can be changed to inspect the

function isCurrentWeekday(idx) { return idx === date.getDay(); }

weekdayLIs.forEach((li, idx) => {
  li.classList.toggle('active', isCurrentWeekday(idx));
});

I'm not sure what's the point of displaying the current weekday in two places, but if you insist:

qs('.clock-day').textContent = weekdayLIs.find((li,idx) => isCurrentWeekday(idx)).textContent;

As for creating the
s corresponding to the weekdays, you can simply list them in HTML; this has the benefit of having all the structure defined in one place:

Sun

Mon

Tue

Wed

Thu

Fri

Sat

https://codepen.io/anon/pen/zpyRjm?editors=1010


As you have read it is usually preferred to exit a loop via its condition(s) as supposed to force exiting via commands like break, exit and continue. Those commands do have their place but your loop and logic could do without them. You are only executing the code inside the if once. Why bother keeping it inside the loop? Lets update the while condition and move the if clause outside.

$maximumAttempts = 60
$attemptIndex = 0

do {
    # Wait between checks.
    $attemptIndex++
    Start-Sleep -Seconds 10
} While (Test-path "\\$server\c$" -and $attemptIndex -le $maximumAttempts)

# Check if the loop ran for its maximumAttempts
if($attemptIndex -ge $maximumAttempts){

  [PsCustomObject]@{
      "Server" =  $server
      "Status" = "FailedToReboot!"
      "LastRebootTime" = "$LastReboot"
      "CurrentRebootTime" = "FailedToReboot!"
   }

   Send-MailMessage <Details>
}

You will also see that I have used more meaningful variable names. I have also used standardized indentation. Doing that removes the need for comments like }#while loop. The indentation makes it clear where the brackets start and stop and make reading the code easier.


Your switch statements will run through until they find a break statement.  Having the braces {} only defines a block of code and has no effect on breaking out of the case.

switch (1)
{
case 1: {
   echo 'One';
}
case 2: {
   echo 'Two';
}
default: {
   echo 'Also default';
      }
}

The one above prints out "OneTwoAlso default" whereas the following prints out "One".

switch (1)
{
case 1:
   echo 'One';
   break;
case 2:
   echo 'Two';
   break;
default:
   echo 'Also default';
}

I think your testing would be cleaner if you didn't use then and when methods.  Normally I create an array of test data and expected results and loop over them.  As you are writing the test for the isId method I would have something like this:

public function test_isID()
{
   $object = new Object_That_You_Are_Testing();

   $tests = array(
      array('Data'            => 123,
            'Expected_Result' => true,
            'Test_Name'       => 'Positive Integer'),
      array('Data'            => -123,
            'Expected_Result' => false,
            'Test_Name'       => 'Negative Integer'));

   foreach ($tests as $test)
   {
      $this->assertEquals($test['Expected_Result'],
                          $object->isID($test['Data']),
                          $test['Test_Name'] . ' Failed');
   }
}

You could do more clever things than this.  Also a test will not always be so simple.  Normally I find that I have mocked objects and am ensuring that they get called appropriately.


Django model with methods to register various kinds of events

One way would be keep a map of these method names and related action_type. Now we can override __getattribute__ to check if one of these methods were accessed and return the partial function with related action_type.

from functools import partial

from django.db import models

register_map = {
    'register_adhoc_created': 'ADHOC_CREATED',
    'register_adhoc_deleted': 'ADHOC_DELETED',
    'register_broadcast_created': 'BROADCAST_CREATED',
}

class RegisterUserAction(models.Manager):

    def __getattribute__(self, attr):
        if attr in register_map:
            return partial(self.create, action_type=register_map[attr])
        return super(RegisterUserAction, self).__getattribute__(attr)

Personally I would do something like this only when the number of such methods are huge and are polluting the code base. Because simplicity in this case greater than being DRY and other devs will have to spend some understanding it. Also because of this custom implementation the code editors won't allow developers to jump into respective code because such method(s) actually doesn't exist.


Auto filter data from worksheet and create vlookup using a different worksheet

ooh wee Because of the below statement, I'll do this in little steps which may not be the best approach, but should be easy to follow.

  I don't understand the syntax of index match, otherwise I could have eliminated ...

let me drop an article from my website right here

I'm not bashing you for not knowing index/match, but you might as well learn it! use it to look up to the left

VBA and worksheet functions

All right, so you're using VBA - you don't need to use worksheet functions at all. If you need the function to exist because the audience needs to see the functions rather than the results, then that's another issue.

ActiveWorkbook.Sheets("Bulk Sheet").Range("H3:K3" & LrowBlk).SpecialCells(xlCellTypeVisible).Copy

Is this essentially .Range("H3:K3" 130) (using 130 arbitrarily)? How does that work?

You also sort based on H3:I3 but then copy H3:K3 and P - are columns J through P filtered when you filter based on column I?

That's pretty confusing. Essentially you have a range (like "H3:P400") that you want to get elements from only if columns 2 matches a string ("adGroup")?

So what? Arrays.

There are a lot of ways to do this, but let's start with the way you've done it, but instead use an array -

bulksheet.Range("H3:P" & lastRow).AutoFilter field:=2, Crteria1:="AdGroup"
Dim bulkData As Variant
bulkData = bulksheet.Range("H3:K" & lastRow).SpecialCells(xlCellTypeVisible)

Right now you have all your data in a variant where you can do your thing instead of on the sheet. Essentially, it's the same advice as

  Be sure to avoid things like .Select - it just slows the code down
  by needing to fiddle with the spreadsheet while doing everything else
  behind the scenes. There's a good question on StackOverflow
  addressing
  this.

So now you have a variant where there are 9 columns and you need 4 of them on a new sheet. You could just put them on the new sheet like this -

For i = LBound(bulkData) To UBound(bulkData)
    adGroupSheet.Cells(i, 1) = bulkData(i, 1)
    adGroupSheet.Cells(i, 2) = bulkData(i, 2)
    adGroupSheet.Cells(i, 3) = bulkData(i, 3)
    adGroupSheet.Cells(i, 1) = bulkData(i, 9)
Next

But maybe there's a better way to do all of that (I'm not 100%, I might have read somewhere that autofilter is faster than a loop, but I digress). Simply -

Dim bulkData As Variant
Dim bulkLastRow As Long
bulkLastRow = bulksheet.Cells(bulksheet.Rows.Count, 8).End(xlUp).Row
bulkData = bulksheet.Range(bulksheet.Cells(1, 8), bulksheet.Cells(lastrow, 16))
Dim sortedData As Variant
ReDim sortedData(1 To bulkLastRow, 1 To 4)
Dim bulkIndex As Long
Dim sortedIndex As Long
sortedIndex = 1
For bulkIndex = LBound(bulkData) To UBound(bulkData)
    If bulkData(bullkindex, 2) = "AdGroup" Then
        sortedData(sortedIndex, 1) = bulkData(bulkIndex, 1)
        sortedData(sortedIndex, 2) = bulkData(bulkIndex, 2)
        sortedData(sortedIndex, 3) = bulkData(bulkIndex, 3)
        sortedData(sortedIndex, 4) = bulkData(bulkIndex, 9)
        sortedIndex = sortedIndex + 1
    End If
Next

Right, now you have your sorted data in a variant and could easily just

 sortedsheet.Range(sortedsheet.Cells(1, 1), sortedsheet(sortedIndex, 4)) = sortedData

Now you can write your formulas.

But wait

But, I see now that you moved column 3 to column 4 -

With Sheets("Adgroup List")
    .Columns("C:C").Cut
    .Columns("E:E").Insert Shift:=xlToRight
 End With

This could easily be fixed by just putting it there in the first place with something like

 ReDim sortedData(1 To bulkLastRow, 1 To 5)
 sortedData(sortedIndex, 1) = bulkData(bulkIndex, 1)
 sortedData(sortedIndex, 2) = bulkData(bulkIndex, 2)
 sortedData(sortedIndex, 4) = bulkData(bulkIndex, 3)
 sortedData(sortedIndex, 5) = bulkData(bulkIndex, 9)

And you have a blank column.

All right, so?

But, why stop there? Assuming you don't need the formulas to be present on the sheet, you can get your data from your variant. But let's examine what you're doing first -

LrowSTR = termSheet.Cells(termSheet.Rows.Count, 8).End(xlUp).Row
Dim termData As Variant
ReDim termData(1 To 3)
termData(1) = "=VLOOKUP($K4,'Adgroup List'!$C:$D,2,0)"
termData(2) = "=VLOOKUP($K4,'Adgroup List'!$C:$E,3,0)"

You make a 1 dimensional array, look up a single value to populate 2 of the 3 items and never use your LrowSTR. Then

.Range("AJ4:AK4").Formula = Strformulas
.Range("AJ4:AK" & LrowSTR).FillDown

Yikes - of course that will hang up. Even without really changing your code it would be easier to just

For i = LBound(termData) To UBound(termData)
    termData(i, 1) = "=VLOOKUP($K4,'Adgroup List'!$C:$D,2,0)"
    termData(i, 2) = "=VLOOKUP($K&" & i + 3 & ",'Adgroup List'!$C:$E,3,0)"
Next

And then paste it all at once, no need to autofill (which is definitely slow). You're also searching column "C" when you already moved it and it's empty. Why not just look in D and E? I digress

Regardless, you might just

Dim termData As Variant
termData = termsheet.Range(termsheet.Cells(4, 11), termsheet(LrowSTR, 11))
ReDim Preserve termData(1 To UBound(termData), 1 To 3)
'find things in sortedData and populate termData with values
'print to termSheet

Misc

Other things to note -

You've declared all of your variables, that's great! Your naming could be improved a bit and Standard VBA naming conventions have camelCase for local variables and PascalCase for other variables and names. So LrowBlk would be bulkLastRow or something. And ws would be a terrible name, but
Worksheets have a CodeName property - View Properties window (F4) and the (Name) field (the one at the top) can be used as the worksheet name. This way you can avoid Sheets("mySheet") and instead just use mySheet.
Always turn on Option Explicit. You can have it automatically by going to Tools -> Options in the VBE and checking the Require Variable Declaration option. This way if you have any variables not defined, the compiler will let you know. This isn't a problem for you, but it's good practice - I have it on.
It's good practice to indent all of your code that way Labels will stick out as obvious. VBE standard is 4 spaces between levels


That's definitely an interesting approach. However, I would say that this interface is trying to accomplish too much. That is, average should just be responsible for calculating the average value over some range [first, last) and not worry about any indirection. E.g., only provide the signature

template< class InputIterator >
double average( InputIterator first, InputIterator last );

Note that I've changed your RandomIt to an InputIterator since I think this is a better choice.

Any indirection should instead be handled with iterator transformation. I.e., an adapter which wraps the raw QMap::iterator and overrides operator *() to either return the key or the value. Boost has the boost::transform_iterator which does exactly that. Even more concretely, there is also the boost::indirect_iterator which is very similar to your Dereference class.

Again, the motivation is to divide up the responsibility into separate classes so that each such class is as simple as possible. Complex tasks are then accomplished by combining these separate classes.

All that being said, let me review the code that you already have written. Because, like I said, it is still an interesting approach!

Use InputIterator instead of RandomIterator as the template parameter for average. InputIterator is more generic and is all you need to compute the average value of a range. When C++ gets ConceptsLite, this will make even more sense.
average always returns double. What about float ranges? Use a trailing return type together with iterator_traits to get the value type of the iterator instead. E.g.,

template< class InputIterator>
auto average( InputIterator first, InputIterator last )
    -> typename iterator_traits<InputIterator>::value_type;

In C++14 this is even simpler as you can simply drop the trailing return type.
Prefer using over typedef. They accomplish the same thing but using is more powerful.

Besides that, the code looks fine to me. Good job! Please also consider the alternative I wrote in the first part of this post.

Edit: I recently read D4128: Ranges for the Standard Library: Revision 1 by Eric Niebler which proposes to overload all algorithms with Projection callables exactly as you did. Note that the very same proposal also includes Range Transform View which is an analogue to the iterator transforms I mentioned. That is, Projections and Range Transform Views coexist and serve slightly different purposes. You can read the proposal to get all the details.

In short, a future C++ standard may include a feature which is very similar to your suggestion. It may even come sooner than C++17 in the shape of a TS.


Fill a pandas dataframe (of predetermined size) with results from a similar dataframe (of size less than or equivalent to the original)

You can create the index directly:
pd.MultiIndex.from_product(
    (shop_ids, range(max_timebins + 1)), names=("shop", "timebin")
)

Here is how you can achieve the same result (including the full index even if there is no data) in a simpler way:
import pandas as pd

# Specify the complete list of possible time bins
max_timebins = 3

# Specify the complete list of shops
shop_ids = ["A", "B", "C", "D"]

target_index = pd.MultiIndex.from_product(
    (shop_ids, range(max_timebins + 1)), names=("shop", "timebin")
)

# Example of a result of a query
dfq = pd.DataFrame(
    {
        "shop": ["A", "A", "A", "A", "B", "B", "C", "C", "C", "D"],
        "time_bins": [0, 1, 2, 3, 0, 3, 0, 2, 3, 2],
        "counts": [100, 220, 300, 440, 500, 660, 120, 340, 90, 400],
    }
).set_index(["shop", "time_bins"])

result_df = dfq.reindex(target_index, fill_value=pd.NA)

print(result_df)

Output:
             counts
shop timebin
A    0          100
     1          220
     2          300
     3          440
B    0          500
     1         <NA>
     2         <NA>
     3          660
C    0          120
     1         <NA>
     2          340
     3           90
D    0         <NA>
     1         <NA>
     2          400
     3         <NA>

There might be a better solution, but that would require knowing a bit more context.


Move as a classname sounds really weird. It's a verb. Verbs don't make good class names.

Try a noun like MoveAction instead.

Location also seems to be suffering from "Feature Envy" of sorts... you ask the Land about the Unit's location? And you ask the Land about the Unit's orientation too! And then when you need to reposition a Unit, you ask the Land to do this!

Here, take a look at your own move command.

public void evaluate() {
    Location oldLocation = land.getUnitLocation(unit);
    Orientation oldOrientation = land.getUnitOrientation(unit);
    Location newLocation = new Location(oldLocation.getX() + oldOrientation.getX(), oldLocation.getY() + oldOrientation.getY());
    land.positionUnit(unit, newLocation, oldOrientation);
}

You need to get the Location from the Land, then you need to get the Orientation from the Land, and then you need to make the Land reposition a Unit... in order to move it.

I don't have the source for Land or Orientation or Location but I assume the following:

Orientation is an Enum of NORTH, WEST, EAST, SOUTH with two Maps x and y that map an Orientation to a int value of -1, 0 or 1
Land has a 2D int[] array
Location has 2 ints, x and y
Unit is implemented by Tractor

So lets alter this so it makes sense again. Right now, you've simulated what a human does. Look at the board, get the position of the object, look at in what way it's going... Then pick it up, hit each tile it passes, and place it on the last tile it needs to be.

Welcome to the magical world of programming, where board pieces can move on their own.

Unit should contain a move function. I'm not sure how the game works, since there's no instructions anywhere, but I assume it's a game where you give a series of Actions that would do stuff (like moving a unit some place). moveForwards in the original source code reveals this to me.

So a tractor would only move forward.

I suggest a radically different design from what you've suggested.

Assign responsibilities to each class.

Land manages the Locations.

Location is a value class, it contains x, y. These can't be altered.

Unit has a Location and Orientation.

With this new design, if you want to move, you ask the Unit and give it the Land to do so.
Unit then queries the Land in regards to obstacles and such. Then it moves by requesting a new Location FROM Land.

So why is this important?

Because right now, you've defined Move to be a pretty rigid Action. There's only one way to move. And that way ignores all obstacles (I have the feeling it even ignores the Land's size!). If you were to add obstacles later this code would come crashing down as you have to ask the Land for ALL it's units, iterate over their locations (and possibly orientations, if they're moving at the same time), and somehow calculate if it's possible, and then do the move. And you have to do this for each move, because you can't store state in between.