Trabb Pardo – Knuth - Algorithm in streams

Instead of generating an array of \$N\$ elements and then reversing it, I'd find it more natural to push values onto a stack and pop off one by one.

It would seem that the "standard" and "traditional" elements would be good as constants, defined near the top of the file:

the number 11
the function to apply
the limit

So that you can play with them easily without making edits inside the main, unchanging part of the code.

Lastly, you have an unnecessary ; in the try statement.

The ability to unit test would be nice, though in this simple example it might take substantial refactoring and lead to over-engineering, and so might not be worth it. Just a thought anyway.


pulling specific data from XML from inside 3rd party application

Joined declaration & assignment
This isn't necessarily a bad use of the : instruction separator, but it did surprise me. Actually, I'd even give you a star on that one:

Dim Age : Set Age = Parameters.Item( Bookmark , "Age" )

Pretty much any other use I can think of of the : instruction separator is hindering readability. Here I find it's a clever way of joining declaration with assignment.
However this:

Dim oNodes
Dim oNode

Set oNodes = XmlDoc.SelectNodes("Record/CelloXml/Integration/Case/ServiceEvent")

Should then be written like this:
Dim xPath : xPath = "Record/CelloXml/Integration/Case/ServiceEvent"
Dim ServiceEventNodes : Set ServiceEventNodes = XmlDoc.SelectNodes(xPath)

I'm not going to mention I'm allergic to things like an "o" prefix to object variables' names (oops just did), but I think you'll agree with me that ServiceEventNodes is a much more descriptive name than oNodes can ever dream to be.
I've skipped oNode here because.. I'll get there in a moment.

'''stop here and look around

I'll skip the Stop keyword and hope this isn't production code. This isn't a necessary comment, but it's well-placed - stop right here and look below, you've got If...For...If...For...If blocks nicely (!) nested here. I'd say stop here and fill up your lungs with that horrible smell, you've got two blocks of code that are rigorously identical, except for one tiny little thing; how about first deciding what the child nodes are, and then iterate them, regardless of Age.Value?
Dim ChildNodes
Select Case Age.Value
    Case "OLD":
        Set ChildNodes = ServiceEventNodes(0).childNodes
    Case "NEW":
        Set ChildNodes = ServiceEventNodes(ServiceEventNodes.length - 1).childNodes
    Case Else:
        Err.Raise 5 'invalid procedure call or argument
End Select

Notice this is not allowing the code to run any further if there's an invalid input. Returning " Hit the Else Statement " is a dangerous thing to do, because it's a valid value that your function will return just as if everything went normal, and I don't know what that's used for, but I'm sure " Hit the Else Statement " doesn't quite belong in production data.
That's why I'd rather throw an error and blow up than return a string that's actually an error message.

That being settled, I believe both loops could be completely eliminated with a little XPath (untested; I think this would do it):
Dim CommentNodes : Set CommentNodes = ChildNodes.SelectNodes("Service/Comment")

Now that you've got the nodes you're after, you can iterate them:
Dim CommentNode
For Each CommentNode In CommentNodes
    ReturnData = ReturnData & CommentNode.Text & MD
Next

I left out the & "" part, because that's concatenating an empty string, which does strictly nothing but add confusing clutter to your code.
The last part:

If Len(ReturnData) > 0 Then
    ReturnData = Left(ReturnData, Len(ReturnData) - Len(MD))
Else
    ReturnData = ""
End If

Looks like it's working around the fact that you haven't properly declared and initialized ReturnData in the first place. If you put Dim ReturnData : ReturnData = vbNullString somewhere before the loop, then you don't need to assign it to an empty string if the loop resulted in a no-op.


Finding number of number pairs with given difference

Current complexity is \$O(n^2)\$, you can accomplish this with \$O(n \space log \space n)\$ instead by sorting the array first and then loop through the elements.

Let's say that you know that the array is sorted, and the array is for example 4 8 15 16 23 42 and you want to find the diff 7:

Let's initialize two variables, lowIndex, highIndex to both 0.

Now we compare index 0 to index 0, i.e. 4 and 4. It's less than the diff value (7) so we increase highIndex
Compare index 0 to index 1, 4 vs. 8, still less than 7, so highIndex++
Compare index 0 to index 2, 4 vs. 15, that's more than 7, so lowIndex++
Compare index 1 to index 2, 8 vs. 15, that's exactly 7, so we have a match and we do highIndex++
Compare index 1 to index 3, 8 vs. 16, that's more than 7, so lowIndex++
Compare index 2 to index 3, 15 vs. 16, that's less than 7, so highIndex++
Compare index 2 to index 4, 15 vs. 23, that's more than 7, so lowIndex++
Compare index 3 to index 4, 16 vs. 23, that's exactly 7, so we have a match and we do highIndex++
Compare index 3 to index 5, 16 vs. 42, that's more than 7, so lowIndex++
Compare index 4 to index 5, 23 vs. 42, that's more than 7, so lowIndex++
Compare index 5 to index 5, 42 vs. 42, that's less than 7, so highIndex++
highIndex has reached the end of the array, return the number of matches found.


The first thing that came to mind was further encapsulation of the fight mechanics. One thing I did have to change was how success was handled; now it's a member of each action subclass and is given a new value each time Controller.fight is called.

The other part necessary to this approach was the implementation of a action mode (offensive or defensive) so that actions like Dodge would know what to do.

import random

OFFENSIVE = 0
DEFENSIVE = 1

class Action(object):

    def __init__(self):
        super(Action, self).__init__()
        self.health = 100
        self.success = 0
        self.nextSuccess()

    def nextSuccess(self):
        self.success = random.randint(-2, 3)

    def performOn(self, subject, success):
        pass

class Dodge(Action):

    def __init__(self):
        super(Dodge, self).__init__()

    def performOn(self, subject):
        if mode == DEFENSIVE and subject.success > self.success:
            subject.performOn(subject, success=subject.success)

class Attack(Action):

    def __init__(self):
        super(Attack, self).__init__()

    def performOn(self, subject, mode):
        if self.success < 0 and subject.success < 0:
            return
        if mode == OFFENSIVE and self.success >= subject.success:
            subject.health -= 5 if success > 1 else 3
        elif mode == DEFENSIVE and self.success > subject.success:
            subject.health -= 3

class Manoeuvre(Action):

    def __init__(self):
        super(Attack, self).__init__()

class Controller:

    def fight(offense, defense):
        offensive = offense.nextSuccess()
        defensive = defense.nextSuccess()
        offense.performOn(defense, OFFENSIVE)
        defense.performOn(offense, DEFENSIVE)

As far as I can tell this does what the original script did. If there are any tweaks that need to be made, let me know!


Tarjan's Algorithm Python Implementation

Multi-statement lines

This:

stack = []; result = []
lowlinks = {}; index = {}
# ...
if successor == node: break

is generally discouraged; just use two lines.

snake_case

This:

lowlinks

is usually spelled out, i.e. low_links.

Bare except

    try:
        successors = graph[node]
    except:
        successors = []

has an except statement that's too broad. If you expect a KeyError from this, then except KeyError.


Find a triangle in a graph represented as an adjacency list

Algorithm looks correct to me. The code is mostly okay, but I have a few suggestions below.

Improving the algorithm

For better algorithms, you could look at algorithms for finding triangle-free graphs. Wikipedia mentions an algorithm that’s O(n^35/27), where n is the number of vertices. However, most of that research is for undirected graphs only – the directed case is probably more complicated.

(Although you should clarify what you mean by a triangle in a directed graph. Consider the two graphs below: do they both contain a triangle, or is the first one disqualified because the triangle does not form a cycle?

If it’s the former, then I don’t see any different from the undirected case.

If it’s the latter, then I’m not sure your current implementation will spot the difference.)

Some alternative approaches that might be worth investigating:

In the undirected case, Turán’s theorem tells us that a triangle-free graph with n vertices can have at most n^2/4 edges. By counting edges, you might be able to very quickly prove that a graph is not triangle-free.
Vertices of lower degree are less likely to be in a triangle. (Vertices of degree 1 are never in a triangle.) You could work through the vertices in increasing order of degree. Once you’ve proved that a vertex of low degree isn’t in a triangle, you can delete it and ignore it for further calculations.

The complexity will probably be less than O(n^4), although I’m not sure exactly what it would be (or indeed whether we could find the complexity of this approach).
You might be able to do something clever with Ramsey numbers, although that’s only a half-baked thought – I’m not entirely sure if there’s something sensible or useful there, it’s just an inkling that there might be.

It’s worth noting that all of these approaches are quite complicated, and likely to add significant complexity to your code. It may that the simplicity of the code is more valuable than the speed increase – that depends on how and when this code will be used.

Improving the code.

Here are my thoughts:

There are lots of repeated function calls. For example, g.get_nodes() is going to be called n(n-1) times. I hope these results are fast and/or cached – otherwise those repeated calls are going to be a big drain on your code. (But also probably some low-hanging fruit for improved performance.)
I don’t know why is_an_edge isn’t defined as simply

def is_an_edge(u, v):
    return v in u.get_adjacent_nodes()

although note that this is going to make lots of calls to u.get_adjacent_nodes(), and you will call it with the same arguments multiple times.

I’d do it something like this:

already_checked_nodes = set()

for u in g.nodes():
    for v in u.neighbors - already_checked_nodes:
        if any(u.neighbors & v.neighbors):
            return True
    already_checked_nodes.add(u)

return False

These are the changes I’ve made:

g.nodes() is only looked up once. I don’t know how it’s implemented in your code, but it should probably be a generator.
.neighbors is a property of a node that is precomputed – there shouldn’t be any processing going on to retrieve this information.
Once I’ve looked at a vertex and found that it doesn’t have a triangle with any of its neighbours, I put it in already_checked_nodes and discard it from future processing. That will save a lot of repeat lookup operations.
I’ve done away with is_an_edge entirely, and am simply looking for anything in the set intersection of u and v’s neighbours. Using any() gets you the same short-circuit evaluation behaviour as before, but it’s Python doing it: as soon as it finds any element in that intersection, it returns True and goes to the next line.

You could probably make this faster by sorting the list of nodes from g. I suspect it might be better to start with nodes of high degree, which are more likely to be in triangles, and work your way down, but I’m guessing a bit there.


In general visitor patterns in other languages are manage with tables, maps or any other struct/object type, here is the improvement that you can make on your code

class TaxVisitor(CostVisitor):

    def cost(self,node):
        if isinstance(node, Milk):
            return 150
        if isinstance(node, Sugar):
            return 100
        if isinstance(node, Plain_Coffee):
            return 10

Can be changed to

class TaxVisitor(CostVisitor):
    self.__table = { "Milk" : 150, "Sugar" : 100, ...}

    def cost(self,node):
        if node.__class__.__name__ in self.__table:
            return self.__table[node.__class__.__name__]

This will make it easy to extender the number of instances by just update the table variable, hope is clear.


Function to check that two objects have "equivalent" values

Personally, I think your naming is just fine. However, the only thing I'd change is equality. That name is very general.

Luckily, since we are talking about races, we can use information about races to name the variables. As you probably know, in a race, when two or more teams end with the same exact score, it is called a tie. Therefore, you should rename that variable to tie.

And, now that I think about it, your function could use some renaming too. isGoodWinner doesn't really tell you what the function is doing; what is a "good winner"? I would name it to isWinningBet. That name tells you if the bet (not the winner) was on the winning team.

You have a few extra variables here. The ones in question are teamAWins and teamBWins, and betOnTeamA and betOnTeamB.

These can be simplified. If someone did not be on team A, they bet on team B (ties don't matter because the variable holding the tie will handle that). And, if team A did not win, then team B win. Both of these apply visa-versa, too.

That being said, we can reduce the variables you need:

var teamAWins = match.scoreTeamA > match.scoreTeamB;
var equality = match.scoreTeamA === match.scoreTeamB;

var betOnTeamA = bet.scoreTeamA > bet.scoreTeamB;
var betEquality = bet.scoreTeamA === bet.scoreTeamB;

Good job writing documentation for your function. I don't often see JavaScript code with documentation, even thought it should.

And, good job using the === operator. Most of the time, people will use the == operator in JavaScript which is a bad idea on a few levels.

Your design is a little confusing.

Judging by these variables:

var betOnTeamA = bet.scoreTeamA > bet.scoreTeamB;
var betOnTeamB = bet.scoreTeamA < bet.scoreTeamB;
var betEquality = bet.scoreTeamA === bet.scoreTeamB;

a person can bet different amounts on both teams. However, your function declares that, if they bet more on, say, team A, then their full bet is on team A.

Now, I don't know what the rest of your code is supposed to do, but I assume you are going to have some payback for winning bets. Well, if a user bets (for example) 10 on team A and 5 on team B, then team B wins, how are you supposed to know which amount to payback?

You wouldn't want to payback based on a 15 bet because the person bet 15 in total, you'd want to payback based on a 5 bet because that bet was on the winning team.

There are two ways you could fix this:

Have the function return an object, saying if the bet was on a winning team and if so, which team the bet was on.
Change your bet design so a bet can only be placed on a single team.

Personally, I'd go with the second option. This "aligns" your objects more, so one object isn't doing the work or holding the information of another. And, it makes more sense in real life: at a real race, you could place a single bet that applied to multiple teams; you place multiple bets, one for each team.


The only other way that I could see this can be done in POSIX would be to use popen() rather than using raw pipes.  It also returns a stream pointer that can be used with the C standard I/O functions like fprintf(), fgets(), etc. to read and/or write to the process on the other-side of the pipe created by popen().  According to the POSIX specification, with popen(),

  The environment of the executed
  command shall be as if a child process
  were created within the popen() call
  using the fork() function, and the
  child invoked the sh utility using the
  call:

  execl(shell path, "sh", "-c", command,
  (char *)0);

  where shell path is an unspecified
  pathname for the sh utility.

So it's basically an easier, more straight-forward way to work with pipes rather than having to fork child processes yourself and close the un-used portions of the pipe so that you don't end up with accidental blocking reads or lost writes because there are still active file-descriptors on each end of the pipe that you've accidentally forgotten to close in either the parent or child process.

With your example, using popen() would look like the following:

#include <stdio.h>
#define BUFFERSIZE 128

FILE *ls_proc, *grep_proc;
ls_proc = popen("ls -l", "r");
grep_proc = popen("grep .bashrc", "w");

char buffer[BUFFERSIZE];

//read from one child process and write to the other
while (fgets(buffer, BUFFERSIZE, ls_proc) != NULL)
    fprintf(grep_proc, "%s", buffer);

pclose(ls_proc);
pclose(grep_proc);


Creating abstraction to validate complex objects

So If I understand correctly, clients get an instance of Validator from the factory, call validate() and get an instance of ValidationStatus and then call process() and get an exception (or nothing). so you replaced an if...else block with a try...catch one. the client still have to check the return value to figure out what to fix. and if you ask me, it is more clear to ask
if (result == ValidationFailureCause.MISSING_MANDATORY_FIELDS)
then
} catch (MandatoryElementsMissing mem) {

in addition, Validator interface contains a method that returns a boolean. how do you plan to prevent clients from calling it?

If we go along with your solution: the whole ValidationStatus class tree seems redundat to me.  It is just a wrappper over throwing a user defined Exception.  It doesn't provide extra capabilities beyond translate an enum into an Exception (considering that exceptions can also have String message). So I believe a design where validate() throws an Exception provides the same functionality.  If you don't want to throw the Exception super class, you can create a ValidationException super class and have all your custom exceptions extend it (much like Java's ReflectiveOperationException)
Your design determines that for a given type, there can only be one Validator.  This may be fine for user-defined types like FlightProposalRequest but it may be too restrictive for JDK types like String.  I imagine that you want to validate that getDepartureDate() is a valid date, and perhaps validate getDepartureAirport() against predefined list of airports (perhaps an SQL query) and so on.  You should assocaite a Validator with a String name (perhaps an enum).
lastly, regartding the validation of the attributes, I believe you can write it like this:

return requestValidator.isValid(request.getArrivalAirport())
&& requestValidator.isValid(request.getDepartureAirport())
&& requestValidator.isValid(request.getDepartureDate())
&& requestValidator.isValid(request.getReturnDate());

this has the same (if not more) level of readability as the original.


<?PHP

Normally it's all lower case, just saying.

//Turn off error reporting (Not Necessary)
error_reporting(E_ALL ^ E_NOTICE);

This is one prime example of confusing and not helpful commenting. If this call is not necessary, why is it there at all?

if (!@mysql_connect('localhost', 'user', '') or !@mysql_select_db('comments')) {

Stop using the mysql_* functions, seriously.

$guest_name = htmlentities(str_replace(' ', '',$_POST['guest_name']));

Why are you replacing entities here? You should not replace stuff when saving it into your database. Ideally the data in your database would be as unbiased as possible. Only replace entities if you need to, f.e. you display it on a webpage.

$time = date('g:i A', time());
$date = date('n/j/Y');
$query = "INSERT INTO `user_comments` VALUES(
    '".mysql_real_escape_string('')."',
    '".mysql_real_escape_string($guest_name)."',
    '".mysql_real_escape_string($comment)."',
    '".mysql_real_escape_string($date)."',
    '".mysql_real_escape_string($time)."'
    )";

From this query I can tell you a few things:

Your database layout is sub-optimal, it uses VARCHAR fields if it should use a DATETIME field.
You like to copy and paste code, that's bad.
You don't do things explicitly, consider adding a fields list to your queries.

First, you should be using a DATETIME type if you're gonna save date and time. MySQL supports also a 'pure' DATE and TIME format, there's absolutely no reason and no excuse to use use a VARCHAR field for that.

And then there's your missing fields list, I made a habit out of adding a fields list to my queries for two reasons:

It let's the reader know exactly what is getting set to where.
It makes your code more robust, the query will not fail if you add a field. Removing a field is also easier, as a simple grep for the field will yield all queries that use it.

So, your query should look like this:

$query = "
    INSERT INTO
        user_comments
    SET
        name = :name,
        comment = :comment;
";

It's easy to read and you know exactly what ends where. Additionally the date/time stuff is here completely missing, because I changed the database layout:

CREATE TABLE user_comments
    name VARCHAR,
    comment VARCHAR,
    timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP;

The TIMESTAMP type is optimal for this kind of operation, as it is able to save automatically the time when the row is created.

$array_query = mysql_query("SELECT * FROM `comments` ORDER BY `ID` DESC");

Same here, your usage of the * makes it easily broken by adding new fields. Additionally you don't know what fields are fetched until you look at the table declaration.

header('Location: index.php');

I'm 99% sure that this should not work. Headers can not be changed after data was send, you set the header in the middle of the file, but your php script should be moved to the top of the file. Additionally if you want to redirect people, it would be good to die() afterwards to make sure that your script stops executing at this point:

<?php
    if (condition) {
        header("Location: othersite.php");
        die("Redirect: <full address here>");
    }
?>

    ...

This will also allow everyone who is not automatically redirected to see where to go to now.

echo '*Please enter a Guest Name*
';

You're outputting stuff while inside the , that's bad practice, content should go into the .

What is this?!

And just to make sure:

Stop using the mysql_* functions and start using prepared queries!


How could I make this PHP $_POST more secure? -Or is it secure already?

I recommend getting yourself a simple, simple function that uses PDO and parameterizing of queries by default behind the scenes.

Here are sample use cases for query functions that use PDO in the background that I use all the time:

$iterable_resultset = query('select * from users where email = :email and username ~* :username or user_id = :user_id', array(':email'=>$email, ':username'=>$username, ':user_id'=>(int)$user_id));
// Results a resultset that is able to be foreached over.

$multidimensional_array = query_array('select * from users where email = :email and username ~* :username or user_id = :user_id', array(':email'=>$email, ':username'=>$username, ':user_id'=>(int)$user_id));
// Results in a multidimensional array with each subarray corresponding to a database row, or null.

$row_of_data = query_row('select * from users limit 1');
//Results in a single dimensional array or null.

$item = query_item("select max(score) from players where username ~* :username", array(':username'=>$username));
// Returns a single piece of information, or null.

There's a lot of advantage from a refactoring viewpoint to having simple function-based parameterizing of sql queries.  PDO is often verbose, and sometimes when you're securing bad code you need simple, terse functions to fit in the place of old mysql_query() calls and the like.

In your specific case, I think that you are making the mistake of escaping before it's time, which can often introduce weird bugs.

$untrusted_input = @$_REQUEST['password'];

is all that you should do when getting the input.  Don't strip tags, don't do anything until it comes time to -use- that untrusted input in sql or in html:

In the sql, parameterize it while using the sql, filter/modify the data based on the circumstances.
When outputting to html, escape it then, e.g. via .htmlentities($example). or using a templating engine.

Here's an example of your code turning a non-existent get/post variable (that would normally result in null) into an empty string, for just the first of many subtle things that happen when you escape too early: http://ideone.com/r7bSr

In general, when you're first getting used to the security issues that php can throw your way, I really recommend using a template engine (e.g. smarty) to help you keep your business logic and your display templates separate.  A lot of people will argue about whether you need a templating engine with php because php is a templateable system already.  Engine or not doesn't matter, but a template-based approach to separate your manipulation logic from your display logic is very necessary, which most programmers would probably agree on.  And personally, I found it easier to learn how that separation benefits php when I was first starting out by just learning how a templating engine does things, before I could understand how to apply those principles to native php without a templating engine.

TL;DR; - Set up a templating engine, it'll get you using best practices faster.


Can I shorten this assembly code to test if a number is even?

As was helpfully pointed out by G. Sliepen in a comment, you can flip the bottom bit using xor.
That enables the above code to be rewritten in one fewer instruction:
isEven:
  andi $t0, $a0, 1
  xori $v0, $t0, 1
  jr   $ra

This takes advantages of the properties:
A xor 1 = !A
A xor 0 = A


Program to retrieve key/message from a multiple times used one time pad

List comprehensions

You use list comprehensions sometimes, and sometimes you use for ...: someList.append(...). This is not consistent. Use list comprehensions as much as you can since you are already building lists (and list comprehensions are slightly faster than for loops):

cribList = [hex(ord(letter)[2:] for letter in crib]

cipherHashList = [int(ciphers[i],16)^int(ciphers[i+1],16) for i in range(len(ciphers)-1)]

hexList = [hashResultString[i:i+cribLength] for hashResultString in hashResultList for i in range(len(hashResultString) - cribLength + 1)]

You can speed things up a little more (maybe at the cost of readability) by using more complex expressions in the list comprehension to avoid creating intermediate lists:

hashResultList = [hex(int(ciphers[i],16)^int(ciphers[i+1],16))[2:] for i in range(len(ciphers)-1)]

Naming

Check PEP 8 for the rationale but you’d better use UPPERCASE names for constants such as FORBIDDEN_SIGNS or CRIB and lower_snake_case for variables such as hex_list or crib_length.

Some of the variable are named thingList and might be improved using things.

Reusability

Make functions to ease testing into the interpreter and/or reusability:

def get_crib_hash():
    return ''.join(hex(ord(letter))[2:] for letter in CRIB)

change the value of CRIB in the interpreter and voilà, every time you (or any function) use get_crib_hash() the value is easily updated without having to recompute everything.

For efficiency reasons I recommend using a generator function for file reading.

Flaws

On my computer, instead of returning b'test':

>>> codecs.decode("74657374","hex")
Traceback (most recent call last):
  File "<pyshell#39>", line 1, in <module>
    codecs.decode("74657374","hex")
LookupError: unknown encoding: hex

You can use a more robust approach in the name of binascii.unhexlify which is doing exactly what you want.

For your issue with “real ciphers”, you might want to print the clear text first instead of trying to lookup words through a web API. It’ll help understand what is happening.

Small improvements

forbiddenSigns = ['{', '}', '[', ']', '(', ')', '?', '=', '%', '_', ';', '-', '^', ':', '<', '>', '|', '!', '`', '´', "'", '\\']

is better written (more resource friendly) as:

FORBIDDEN_SIGNS = '{}[]()?=%_;-^:<>|!`´\'\\'

and you will still be able to iterate over each symbol.
range() does not need a 0 as first argument (unless you want to specify a step); similarly a step of 1 is the default.
compute once if you can; e.g: str(clearText, "ASCII").
consider using an if __name__ == '__main__': construct to emphasize on reusability and improve testing in the interactive interpreter.
format is often more efficient for building strings; it can even replace hex for your use case.

Proposed improvements

import binascii

FORBIDDEN_SIGNS = '{}[]()?=%_;-^:<>|!`´\'\\'
CRIB = 'the'

def get_crib_hash():
    return ''.join(format(ord(letter), '02x') for letter in CRIB)

def hash_file(filename):
    with open(filename) as f:
        previous = None
        for line in f:
            line = line.strip()
            try:
                yield format(int(previous, 16) ^ int(line, 16), 'x')
            except TypeError: # for int(None, 16) at first pass
                pass
            previous = line # Yeah, I’ll compute int(this_thing, 16) a second time…
            # Avoiding it is left as an exercise for the reader.

def decipher_file(filename):
    crib_hash = get_crib_hash()
    crib_length = len(crib_hash)
    crib_hash = int(crib_hash, 16)

    for hash_result in hash_file(filename):
        for i in range(len(hash_result) - crib_length + 1):
            attempt = crib_hash ^ int(hash_result[i:i+crib_length], 16)
            attempt = '{0:0{fill}x}'.format(attempt, fill=crib_length)
            yield str(binascii.unhexlify(attempt), 'ASCII')

if __name__ == '__main__':
    from urllib.error import URLError
    from urllib.request import urlopen

    for clear_text in decipher_file('testCiphers.txt'):
        # or just print(clear_text)…
        if '\\x' not in clear_text and any(s not in clear_text
                                           for s in FORBIDDEN_SIGNS):
            url = 'http://www.morewords.com/contains/{}'.format(clear_text)
            try:
                response = str(urlopen(url).read())
                if 'words found.
' in response:
                    print(clear_text)
            except URLError :
                'error getting webpage'


Style

Spaces and punctuation

if array.is_empty(){

should be

if array.is_empty() {

(likewise match key.cmp(&middle_element){ → match key.cmp(&middle_element) {, etc.)

Ordering::Equal => {return Some(start+middle as usize);} ,

should be

Ordering::Equal => return Some(start + middle as usize),

although really, the comma at the end isn't necessary; you can remove that too.

And there should only be one new line below use std::cmp::Ordering and none above.

Scope

middle isn't used outside the loop, so you can replace:

let mut middle;

loop {
    middle = (end - start) / 2;

with:

loop {
    let middle = (end - start) / 2;

Note how the mut can go away, because the value of middle is only set once (per loop).

Unnecessary cast (as)

Ordering::Equal => {
    return Some(start + middle as usize);
},

The as usize is unnecessary; Rust already knows that you're returning Option<usize>. In fact, both start and middle are already usize, as is start + middle, so Rust isn't even doing anything fancy to get this to work. However, writing as usize makes it seem like those aren't usize, which could end up confusing your reader quite a lot.

(Same with start as usize → start and end as usize → end.)

Misleading comments

This comment:

//The slicing syntax produces an unborrowed slice
//(type: [i32]) which we must then borrow (to give a &[i32]),
//even if we are slicing a borrowed slice.//More can be read at
//https://github.com/nrc/r4cppp/blob/master/arrays.md
if end - start <= 1 {

is misleading, for two reasons:

It's right above (hence attached to) the wrong piece of code.
You don't use the slicing syntax (array[4..6]) anywhere in your code; you use the indexing syntax.

Just remove it; perhaps replace it with

let middle_element = array[start + middle];
// cmp requires a reference
match key.cmp(&middle_element) {

or something if you think it would be helpful. Though be aware that let middle_element = array[start + middle] makes a copy of middle_element, so the reference is to middle_element on the stack, not array[start + middle] wherever array is stored.

loop with if and break

if end - start <= 1 {
    break;
};

You're trying to make a do while loop here. However, if end - start <= 1 already, you don't need to enter this loop in the first place. This means you can just use a regular while:

while end - start > 1 {
    let middle = (end - start) / 2;
    let middle_element = array[start + middle];
    // cmp requires a reference
    match key.cmp(&middle_element) {
        Ordering::Less => end -= middle,
        Ordering::Greater => start += middle,
        Ordering::Equal => return Some(start + middle),
    }
}

And now cargo fmt doesn't change the code, and cargo clippy doesn't give any suggestions. Hooray!

Implementation

middle

In my mind, middle should be the index of the middle element – not the difference between start and the middle element. You might want to calculate this as (start + end) / 2 but that risks overflow; fortunately, start + (end - start) / 2 works fine.

So this:

let middle = (end - start) / 2;
let middle_element = array[start + middle];
// cmp requires a reference
match key.cmp(&middle_element) {
    Ordering::Less => end -= middle,
    Ordering::Greater => start += middle,
    Ordering::Equal => return Some(start + middle)
}

becomes:

while end - start > 1 {
    let middle = start + (end - start) / 2;
    let middle_element = array[middle];
    // cmp requires a reference
    match key.cmp(&middle_element) {
        Ordering::Less => end = middle,
        Ordering::Greater => start = middle,
        Ordering::Equal => return Some(middle)
    }
}

Unnecessary variable

Now we've made that change, I think array[middle] is obviously the middle element; so much so that we can remove middle_element entirely and get clearer code:

let middle = start + (end - start) / 2;
// cmp requires a reference
match key.cmp(&array[middle]) {

Ordering ordering

I actually think it'd be clearer if these were in Less, Equal, Greater order:

match key.cmp(&array[middle]) {
    Ordering::Less => end = middle,
    Ordering::Equal => return Some(middle),
    Ordering::Greater => start = middle
}

Implicit return

At the end, it might be clearer to use the implicit return form:

if array[start] == key {
    Some(start)
} else if array[end] == key {
    Some(end)
} else {
    None
}

Addendum: Tests

To make sure I didn't break your code while making these changes, I wrote a test. Tests are good to have (not that this is a particularly good test).

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_find() {
        assert_eq!(find(&[2, 4, 5, 7, 11, 12, 17], 5), Some(2));
        assert_eq!(find(&[], 5), None);
        assert_eq!(find(&[2, 4, 5, 7, 11, 12, 17], 6), None);
        assert_eq!(find(&[-63, -42, 1, 2, 4, 5, 7, 11, 12, 17, 17, 18], 12), Some(8));

        call_find(&[-10, -7, 0, 2, 4, 4, 5, 16, 27, 37, 38, 40, 40, 40, 40, 63, 628, 844, 10000000, 41230456]);
    }

    fn call_find(array: &[i32]) {
        for i in 0..array.len() {
            assert_eq!(array[find(array, array[i]).unwrap()], array[i]);
        }
    }
}


C++ custom exception handling using std::error_category and std::system_error

Here are some things that may help you improve your code.
Separate interface from implementation
The interface goes into a header file and the implementation (that is, everything that actually emits bytes including all functions and data) should be in a separate .cpp file.  The reason is that you might have multiple source files including the .h file but only one instance of the corresponding .cpp file.  In other words, split your existing CustomException namespace into into a .h file and a .cpp file.
Correctly override functions
The code currently contains this as part of class ErrorC:
bool equivalent(int const code, std::error_condition const &condition) const noexcept
override {
    (void) code;
    (void) condition;
    return false;
}

This is not right for several reasons.  First, the standard says that this should return true if the error is equivalent, but this does not do that.  Instead, I'd write:
return default_error_condition(code) == condition;

Better still, omit it, since this is not a pure virtual method in std::error_category.
Don't create pointless classes
The CustomException class is doing very little here and I would strongly recommend omitting it and just deriving directly from std::error_category.  See C.120 for further guidance.
Don't use all caps for enum name
ALL CAPS have been traditionally used for macros.  To avoid misleading the reader, don't use them if it's not a macro.  See ES.9.
Fix the spelling
If the machine has "breaks" it is broken.  If it has "brakes" it has the ability to slow down.  These homonyms are easily confused, but it's important to make sure you don't have spelling errors, especially in interface code, so that you don't confuse users of your code.
Consider combining error codes
It appears that you are intending to have non-overlapping and unique error codes for each type of error, but that is not assured because the errors are in three different enum classes.  I'd suggest combining them.
Reconsider your classes
If the error codes were combined, as suggested above, then the differentiation among them would be by the error code.  Having different classes doing exactly the same thing makes little sense to me.  I'd suggest a single error class derived from std::error_category would be sufficient.


The main issue I see is that the code opens the XML file six times to
read a single value each time.  Edit:  With a bit more a work I have a
now a rather nice solution for this.  The original minified version is
below.

So the point here is to only read the file once, then filter the tree in
two stages, once for the top-level coordinate and once for the "parent"
node below.  By combining the two stages with &&& and handling the
edge-cases of missing values, the output is same (I hope) and
performance, as well as the number of lines is improved significantly.
(There is still potential for reduction in at least the coordinate
function, but I'll leave that to a kind editor for now.)

import Control.Lens ((&))
import Text.XML.HXT.Core
import System.Environment (getArgs)
import Text.XML.HXT.Arrow.XmlArrow
import Control.Monad (liftM)
import Data.Maybe
import Control.Applicative

type Coordinate = (String, String, String)

main = do
  (filename:_) <- getArgs
  (coordinate, parentCoordinate):_ <- runX (readFileDoc filename >>> coordinatesFilter)
  print coordinate
  print parentCoordinate

readFileDoc = readDocument [withValidate no]

coordinatesFilter :: ArrowXml a => a XmlTree (Maybe Coordinate, Maybe Coordinate)
coordinatesFilter =
  project >>>
  maybeSelector coordinate &&&
  maybeSelector (parent >>> coordinate)

maybeSelector :: ArrowList a => a b c -> a b (Maybe c)
maybeSelector selector = withDefault (selector >>> arr Just) Nothing

namedChildren :: ArrowXml a => String -> a XmlTree XmlTree
namedChildren name = getChildren >>> hasName name

project :: ArrowXml a => a XmlTree XmlTree
project = namedChildren "project"

parent :: ArrowXml a => a XmlTree XmlTree
parent = namedChildren "parent"

field :: ArrowXml a => String -> a XmlTree String
field name = namedChildren name >>> getChildren >>> getText

threeAndSelector :: Arrow a => (t -> a b c) -> t -> t -> t -> a b (c, c, c)
threeAndSelector f a b c = (f a &&& f b &&& f c) >>> arr (\(x, (y, z)) -> (x, y, z))

coordinate :: ArrowXml a => a XmlTree Coordinate
coordinate = threeAndSelector field "groupId" "artifactId" "version"


Checking if all possible combinations of any two array elements in an array contains 0-9 atleast once

static int winningLotteryTicket(String[] tickets,int n)
 // tickets = array of all strings

 {

Please don't put comments in between a function declaration and the function body (which starts with {).

The standard way to write this in Java is

// tickets = array of all strings
static int winningLotteryTicket(String[] tickets, int n) {

This is shorter and easier to read.

Some people prefer to put the { on a separate line.  That's not standard in Java.  But if you do do that, please put the { on the line immediately after the function declaration.  Put comments either before the function declaration or inside the function body.

In Java, unlike C, you do not need to pass the length of the array separately.  Instead of n, you can just use tickets.length.  So

    for (int i = 0; i < tickets.length; i++) {
        for (int j = i + 1; j < tickets.length; j++) {

This also has the advantage of being clearer than n.  I can immediately see that it is the length of the array that is the limitation.  And this avoids bugs where n is passed as something other than the length of the array.

     if(i!=j)

This line is unnecessary.  The way that the inner for loop is declared, j is always greater than i.

         b=check.contains(r);

This is inefficient.  It does a linear time search for each digit.  We can do a single linear time search that covers all the digits.  Consider

public static final int RADIX = 10;

static boolean hasAllDigits(String ticketPair) {
    boolean[] found = new boolean[RADIX];
    for (char digit : ticketPair.toCharArray()) {
        found[digit - '0'] = true;
    }

    for (boolean digitFound : found) {
        if (!digitFound) {
            return false;
        }
    }

    return true;
}

So the original method could be just

static int winningLotteryTicket(String[] tickets) {
    int count = 0;

    // the i and j loop are to create all possible combinations
    for (int i = 0; i < tickets.length; i++) {
        for (int j = i + 1; j < tickets.length; j++) {
            if (hasAllDigits(tickets[i] + tickets[j])) {
                count++;
            }
        }
    }

    return count;
}

If this still isn't fast enough, consider storing the digits found in each string.  E.g. instead of "129300455" store "0123459".  Then you can just use merge logic to check if two strings contain all the digits.


1) is a Value Object "better" than a Domain Service?

This is certainly subjective, but i'll offer this pragmatic view point. Evaluate how often this code will be actively referenced and debugged by other developers. If this code is located in an easily reusable utility assembly, and it is a realistic expectation that it will be reused, then Value Object wins for me every time. It offers more self documentation than your initial attempt which is important because you have not implemented code comments at all.
At the end of the day you have to justify the time and effort required to get the code into production, code that is reused a lot, especially by other developers is worth the effort to get it right, but you have increased you code surface and will have to increase you unit test coverage to match.
Value objects like this i find are much easier to unit test, and like you have said with validation, the object now has additional options for expressing it's state without blocking execution with exceptions and we can more easily inherit this structure and when we need to override specific functionality, such as validation when we as developers do reuse your code.

  2) Is it wise to have a property called Currency.DecimalPlaces

Absolutely, especially with currency where rounding errors can have a real world monetary impact on the user, this seems like a useful thing to know, and it is natural to expect that Currency would already have this attribute.

  3) Should I go with option 2?

See my response to question 1  from a purist point of view your Value Object is a complete package, it has a dependency on Currency, but is easier to lock down with unit tests and to distribute in a utility assembly for reuse. It's up to you to evaluate the cost of developing this solution and refactoring existing code to use it.

Certainly follow the advice from @t3chb0t, you've gone to this much effort, implement your own contract definition for the response from CalculateDenominations, a key value pair response is too ambiguous for users know how to use the response, it's the missing bit of "self" documentation.

  How do i approach validation with option 1?

Throwing exceptions from the calculation routine is an acceptable method for validation, if this was a Mutable type (not readonly) then I would argue that it would be better than throwing exceptions from the constructor which can lead to other interesting and less than satisfactory implementation patterns.

  UPDATE: Moving validation to an explicit method called Validate() further helps to self document your class, and makes it easier to maintain long term. You still call validation from either your calculation method or the constructor. As a bonus when validation fails, the stack trace will now show DenominationsRequired.Validate() which further describes why the exception was raised for future debuggers.

For mutable types it's only at the point of execution that the validation matters, the code that interacts with the instances of this class should be free to instantiate the object and react to its state at a later point in the execution. It is hard for example to check the state of a Value object if we failed to create the object in the first place.

  Here your Value type is an Immutable Type, that is to say that it's value over time will not change, and cannot because you have marked the fields as readonly. This is a special case where it is more appropriate to validate in the constructor rather than in the calculation because there will not be any opportunity to change the value if it is not valid.

A quick note about your validation, you hardcoded 2 as the comparison, rather than Currency.DecimalPlaces, so it should be:

if (decimal.Round(cost, currency.DecimalPlaces) != cost)
        throw new ArgumentException(string.Concat("Cost has too many decimal places.  It should only have: ", currency.DecimalPlaces), "Cost");


Sum of all paths between all pairs of nodes in a tree

\$O(n^2)\$ time complexity

Your current algorithm has \$O(n^2)\$ time complexity because for each edge, you count the number of vertices on one side of the edge, which is a linear time operation.

However, the program is pretty fast.  I ran it on three large test cases.  The first was 10000 nodes arranged in a line, the second was 10000 nodes arranged in a star, and the third was 10000 nodes arranged in a star, but with the edges listed with reverse direction.  Here were the results:

Line : 1.15 sec
Star : 0.01 sec
Star2: 2.30 sec

The first star was quick because the program always counted the outside (i.e. 1 node always).  The second star was slow because the program always counted the inside (n-1 nodes always).  So you could consider these the best and worst possible test cases.

Alternative strategy

The problem can be solved in \$O(n)\$ time.  Instead of picking a random edge and having to count one side, if you picked an edge connected to a leaf node, you automatically know that the count on the leaf side is 1.  There is always at least 1 leaf node in the graph, because the graph is a spanning tree with no cycles.  If you then remove the leaf node from the graph, there must still be at least 1 leaf node, so you can keep finding a leaf node and removing it until there are no nodes left.

A small complication arises after you find the first leaf node and remove it from the tree.  The node it was attached to must now remember that it was connected to the leaf, in order to keep the distance calculations correct.  In other words, if leaf A is attached to node B and leaf A is removed, then node B must now count as 2 nodes.  If node B is later removed, it must add its 2 nodes to some other node, etc.

So the pseudocode is this:

Find a node with 1 edge only.  Call this node A and the node it is attached to B.
Add to the total distance this amount: A.count * (totalNodes - A.count) * edge.weight.
Add A.count to B.count.
Remove the edge from A and B.
Go back to step 1.  If B only has 1 edge, use B as the next node.

You can find all the leaf nodes in \$O(n)\$ time because:

In the beginning there are a fixed number of leaf nodes.
If you scan the nodes array from beginning to end, you will find these initial leaf nodes in \$O(n)\$ time.
Any other nodes that become leaf nodes are found in step 5 above and can be handled without scanning.

Similarly, finding and removing edges can be done in amortized \$O(n)\$ time if you handle the edge lists correctly.  One key point is that even though you need to search through edge lists, there are only \$n\$ total edges, so that total time spent searching through edge lists is limited to \$O(n)\$.

Sample \$O(n)\$ program

Here is the program I wrote in C with the alternative strategy.  It solved all three test cases in 0.01 seconds.

Note: I did edge removal in a somewhat nonstandard way, where I marked the edge invalid instead of removing it from the edge list.  I wrote another version where I kept the edges in a doubly linked circular list and I actually removed the edge from the list when needed.  Both versions are just as fast, so if anyone wants to see the other version, just ask.

#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>

const int MOD = 1300031;

typedef struct Edge {
    struct Edge *next;
    int          to;
    int          weight;
} Edge;

typedef struct Node {
    int         numConnected;
    int         numEdges;
    Edge       *edges;
} Node;

int main(void)
{
    int   numTests = 0;
    Node *nodes    = NULL;
    Edge *edges    = NULL;

    scanf("%d", &numTests);
    for (int i=0; i<numTests; i++) {
        int numNodes = 0;
        int e        = 0;

        scanf("%d", &numNodes);
        nodes = (Node *) calloc(numNodes, sizeof(*nodes));
        edges = (Edge *) calloc(2*numNodes, sizeof(*edges));

        // Read in list of edges.  For each edge, we create two Edge
        // structures and add one to each endpoint Node.
        for (int j = numNodes - 1; j > 0; j--) {
            int from   = 0;
            int to     = 0;
            int weight = 0;
            scanf("%d %d %d", &from, &to, &weight);
            from--;
            to--;

            edges[e].to       = to;
            edges[e].next     = nodes[from].edges;
            edges[e].weight   = weight;
            nodes[from].edges = &edges[e];
            nodes[from].numEdges++;
            e++;

            edges[e].to       = from;
            edges[e].next     = nodes[to].edges;
            edges[e].weight   = weight;
            nodes[to].edges   = &edges[e];
            nodes[to].numEdges++;
            e++;
        }

        int      search = 0;
        int      cur    = -1;
        uint64_t dist   = 0;

        for (int nodesLeft = numNodes-1; nodesLeft > 0; nodesLeft--) {
            Edge *edge;

            // Either use the node known to have 1 edge, or find the next
            // node that has 1 edge.
            if (cur == -1) {
                while (nodes[search].numEdges != 1) {
                    search++;
                    if (search >= numNodes) {
                        printf("ERROR, reached end of nodes\n");
                        exit(1);
                    }
                }
                cur = search++;
            }

            // Find the one valid edge in the list of edges.
            for (edge = nodes[cur].edges; edge != NULL; edge = edge->next) {
                if (edge->to != -1)
                    break;
            }
            if (edge == NULL) {
                printf("ERROR, reached end of edges\n");
                exit(1);
            }

            // The edge is going from cur <-> to, where cur is a leaf node.
            // We can calculate the distance used by the edge because we know
            // how many nodes are attached to cur.  That number is 1 for cur
            // itself plus nodes[cur].numConnected which is the number of
            // previous leaf nodes that we removed that are connected to cur.
            int to       = edge->to;
            int curNodes = nodes[cur].numConnected + 1;

            dist += (numNodes - curNodes) * curNodes * edge->weight;

            // Since we are removing the leaf node cur, we add its nodes
            // to the node it is attached to.
            nodes[to].numConnected += curNodes;

            // If the new node has 1 edge, use it, otherwise set cur to
            // negative to search for another node with 1 edge.
            if (--nodes[to].numEdges == 1)
                cur = to;
            else
                cur = -1;
            nodes[cur].numEdges = 0;

            // Delete other side of edge by marking its to field as -1.
            // This is needed so that when we search through the other
            // node's edges for its one remaining edge, we will skip this one.
            // We can find the paired edge by looking at its array index
            // because always created edges in consecutive pairs.
            int edgePairIndex = (edge - &edges[0]) ^ 0x1;
            edges[edgePairIndex].to = -1;
        }

        // printf("%lld\n", dist);
        printf("%lld\n", dist % MOD);
        free(edges);
        free(nodes);
    }
}


Should I design my enumeration in some way that indicates what the highest value is?

I think you should add a numeric field indicating the order of a card relative to the other cards. You do not need to use it for anything other than sorting.

Also, instead of taking the identifier of the enum value and doing uppercase and lowercase tricks with it in order to turn it into something presentable to the user, you should just store the name, too, as a separate string in the enum.

So, it would look like this: ACE( "A", "Ace", 0 ) (where 0 indicates lowest order for sorting.)

Furthermore you can also add one more number, the 'weight' of a card, to use in calculations which determine whether a card beats another. In general, enums in java are very powerful, so powerful that you pretty much end up not having to use the switch statement with enums anymore, because you can include a big part of an enum's functionality within the enum itself.


Count elements in a collection based on a condition [Java 8]

The code looks very nice! However, here my small complaints:
Tests
The tests are good, but you're testing the Behaviours implicitly, when you test the Counter. The Counter itself does only the following things: stream, filter with the given predicate, and count. The static methods im Behaviours should be tested separately, as should the logic of the Counter. The problem is, if the test fails, you don't know if the problem is the Counter or the Behaviours. The more "implicit" things you test, the harder is it to find the bug.
You're testing with too many values. The logic itself should be the same with two values (one is a palindrome, one is not) as with four values (two palindromes, two not). If the behaviour for two or four values is different, then it's two different test cases.
The lists to count/filter can have a better name.
To make a test case more readable, it's usually split in the three blocks given/when/then, separated by an empty line. Setup the test data / perform the action / assertion.
Also, I recommend, but that's personal preference, to static import static methods, at least the assertion methods, so it looks a bit more clean.
What's missing (at least what I couldn't find):

You're missing the test for even numbers.
You're missing the test for 0/1 number in testCountingPrimeNumbers.
What happens for an empty String (or string with length 1 or 2) in the palindrome count?

Other

check-prefix: The convention is to use a is prefix, if a method returns a boolean, it's more clear than "check".
test-prefix in test methods: That was the convention for JUnit3 (I think), when annotations weren't a thing. It's not needed anymore, when you use the @Test annotation, so instead of testCountingPrimeNumbers, you can go with countPrimeNumbers.
The JavaDocs for the test methods are obsolete, the method names are clear.
I'd get rid of the System.outs, too, you get enough information in the junit test report.
Instead of naming stuff actual, I'd give it the proper name, e.g. amountOfPalindromes. And maybe not declare the expected variable.

Hope this helps...


Calculating the total daily amount of confirmed cases of Coronavirus

So it seams like you have a Pandas dataframe you are working with.
At the moment it looks like this section of code does the following

worldCases = []

for i in range(0,len(dd)):               #iterate through all dates
    count = 0                            #setup a counter
    for j in range(0,len(dd)):           #iterate through all dates
        if dd[j]==dd[i]:
            count+=dc[i]                 #add one to counter if inner date == outer date
    worldCases.append(count)             #track number of times a unique date occurs

You are effectively binning your data, getting a count of the number of times each unique date occurs. Pandas offers you more efficient and convenient tools for doing this. Specifically look into the groupby method.

A much faster way to get the same output for worldCases would be to do the following:

# group the daily cases data by the date and then compute
# the sum of cases within each date group

dc = 'Daily confirmed cases (cases)'
worldCases = cases.loc[:, dc].groupby(cases['Date']).sum()

Also, if you find yourself writing lots of loops like the above, you may want to check out the user guide for "group by" operations in the pandas documentation. It is a very powerful way of handling situations like this, and more, but can take a bit of getting used to. It can feel like a whole different way of thinking about your data.


For a beginner script there are some There might be more to cover but there are a few things here that could improve the script.

Variable and function naming

In general functions and cmdlets should follow the Verb-Noun naming convention. You have the verb and noun part down but the hyphens are not there. Not a must but I would expect you to see those on other scripts.

Variables generally follow camelCase (with first work in lower) or PascalCase. I use camelCase myself. In either case PowerShell were prefer if you use one of those over the joined by underscore method.

Parameter in functions / cmdlets you will always see use PascalCase.

PowerShell script help

You have a multiline command block that contains some information about the script and its creation. I used the same sort of thing for my old VBS scripts. PowerShell has a robust help system you could(should?) be using for this information.. Stealing the simple example from TechNet

<#
.SYNOPSIS

The synopsis goes here. This can be one line, or many.
.DESCRIPTION

The description is usually a longer, more detailed explanation of what the script or function does. Take as many lines as you need.
.PARAMETER computername

Here, the dotted keyword is followed by a single parameter name. Don't precede that with a hyphen. The following lines describe the purpose of the parameter:
.PARAMETER filePath

Provide a PARAMETER section for each parameter that your script or function accepts.
.EXAMPLE

There's no need to number your examples.
.EXAMPLE
PowerShell will number them for you when it displays your help text to a user.
#>

This way you can give more explanation to what your script is doing to the users that might be running it. (I realize this is a personal script). Also is an easy way to explain how each parameter works and give some examples.

The power this gives you is using Get-Help in the shell against your script.

Single line comments

# You can also just use the number sign for single line comments instead of <##>

Too many ifs

If you find yourself with several if blocks there is probably a better way. You should be using a switch for this.

switch ($action){
    {$_ -eq "e" -or $_ -eq "echo"}{
        "Do Something."
    }
    {"s","set" -contains $_}{
        "Do Something Else."
    }
    default {
        "You typed '$_' and it is has no associated action"
    }
}

The above covers a couple of ways that you can work with multiple values of $action that result in the same code being executed. There is more you can do with switches so I encourage to read up on them. You can use regex as well for your cases but I opted not to include it here for brevity.

Remember that

  If the value matches multiple conditions, the action for each condition is executed. To change this behavior, use the Break or Continue keywords.

So it would not be uncommon to see break being used in examples on the web.

Advanced function parameters

This is another large topic that is covered in about_functions_advanced_parameters but one example to call out would be your $action parameter. You only support 10 values and the script will do nothing if the one of those values was not entered.

Param
(
    [parameter(Mandatory=$true)]
    [ValidateSet("e", "echo","s","set","a","add","l","list","r","remove")]
    [String]$Action
    # Continue with other params
)

So now if you don't provide one of those values for $action PowerShell will throw an error stating just that.

  Cannot validate argument on parameter 'Action'. The argument "bagel" does not belong to the set "e,echo,s,set,a,add,l,list,r,remove" specified by the ValidateSet attribute. Supply an argument that
  is in the set and then try the command again.

Parameter Sets

A continuation of advanced functions... Your $action is looking one of a set of mutually exclusive choices. Why not convert those actions into parameter switches? Then, using parameter sets, you can define their use with the $key $value parameters. Ensuring that nothing will be called or used if the combination was not meant to be. Consider the following (ignore the name. I had to call it something) function:

function Set-JavaHome{
    [CmdletBinding(DefaultParametersetName="List")]
    Param
    (
        [Parameter(ParameterSetName="Echo")]
        [switch]$Echo,
        [Parameter(ParameterSetName="Set")]
        [switch]$Set,
        [Parameter(ParameterSetName="Add")]
        [switch]$Add,
        [Parameter(ParameterSetName="List")]
        [switch]$List,
        [Parameter(ParameterSetName="Remove")]
        [switch]$Remove,
        [Parameter(ParameterSetName="Add",Mandatory=$true)]
        [Parameter(ParameterSetName="Remove",Mandatory=$true)]
        [Parameter(ParameterSetName="Set",Mandatory=$true)]
        [string]$Key,
        [Parameter(ParameterSetName="Add",Mandatory=$true)]
        [string]$Value
    )

    switch($pscmdlet.ParameterSetName){
        "Echo" {"Echo echo echo...."}
        "List" {"Show me the list!"}
        "Remove" {"Removing $key"}
        "Set"{"Setting the value to $key"}
        "Add"{"The new key:-$key- will be set to -$value-"}
    }
}

This gives better control over what is used when calling the function (or script). Running Get-Command against this function will help explain.

PS C:\Windows\system32> Get-Command Set-JavaHome -Syntax

Set-JavaHome [-List] [<CommonParameters>]

Set-JavaHome [-Echo] [<CommonParameters>]

Set-JavaHome -Key <string> [-Set] [<CommonParameters>]

Set-JavaHome -Key <string> -Value <string> [-Add] [<CommonParameters>]

Set-JavaHome -Key <string> [-Remove] [<CommonParameters>]

This shows the acceptable ways to call this function. There is no need to check, for example, if $key has been populated with calling -Add since the cmdlet would throw an error or prompt the user otherwise. $key is now mandatory for the parameter sets it is assigned to. PowerShell now pro

PS C:\Windows\system32> Set-JavaHome -Add -Value "C:\bagel"
cmdlet Set-JavaHome at command pipeline position 1
Supply values for the following parameters:
Key:

This is not a feature of parameter sets but since we have each "action" as its own parameter we also can take advantage of calling the parameters by their shortest unambiguous string. In your care that would accept the first letter.

Set-JavaHome -l

Depending on your function this could collide with common cmdlet parameters () e.g. verbose, whatif. In this case I do not think there is any worry.

Test-Path

You are adding paths to your environment. It might be worth testing them before the get used. A simple code block might help prevent hair pulling down the line

If (Test-Path $value){
   "Valid Path"
} else {
   "Not Valid Path"
}

Hopefully that will give you a little something to work with.


Here is my approach:

First some imports:

 {-# LANGUAGE BangPatterns #-}

 module Euler50
 where

 import Math.NumberTheory.Primes
 import qualified Data.IntSet as Set
 import Data.List
 import Debug.Trace

We use the arithmoi library to get the primes:

 myPrimes :: [Int]
 myPrimes = map fromIntegral $ takeWhile (< 1000000) primes

 myPrimeSet :: Set.IntSet
 myPrimeSet = Set.fromList myPrimes

 myIsPrime :: Int -> Bool
 myIsPrime p = Set.member p myPrimeSet

To solve the problem, let's first define a function to produce consecutive sums of a list:

 consecutiveSums0 :: [Int] -> [(Int,Int)]
 consecutiveSums0 ps = scanl step (0,0) ps
   where step (!n,!total) p = (n+1, total+p)

For example, consecutiveSums0 [2,3,5,7] will produce the list:

[ (0,0), (1,2), (2,5), (3,10), (4,17) ]

It will be useful to be able to specify a starting value for the
accumulator, so we'll define:

 consecutiveSums :: (Int,Int) -> [Int] -> [(Int,Int)]
 consecutiveSums start ps = scanl step start ps
   where step (!n,!total) p = (n+1, total+p)

Next, we filter out only the prime sums
which are less than 1000000:

 primeSums :: (Int,Int) -> [Int] -> [ (Int,Int) ]
 primeSums start ps = filter (myIsPrime . snd ) $ takeWhile ( (<1000000) . snd ) $ consecutiveSums start ps

A naive solution to the problem involves repeatedly calling primeSums on the tails of
our list of primes:

 solve0 = maximum $ concat $ map (primeSums (0,0)) (tails myPrimes)

However, there are 78498 primes less than 1000000 and this will examine
approximate 78498^2/2 sums which will take too long.

A better solution involves keeping track of the best solution found so far
and using that to enforce the minimal size of any better solution.
We can stop once the minimal size constraint forces the total of any better
solution to be greater than 1000000.

Our loop will have this structure:

 loop :: [Int]        -- current list of primes
      -> (Int,Int)    -- best solution so far (n, total)
      -> (Int,Int)    -- best solution

The idea is that loop ps b1 will compute a new best solution b2
and then call loop (tail ps) b2 which will compute a new best b3
and call loop (tail (tail ps)) b3 etc. The iteration will stop
when either the primes list is exhausted or the above stopping condition
holds.

An easy case:

 loop [] best = best  -- prime list has been exhausted

We include this just to trace the execution of the function
- it has no effect on the computation:

 loop (p:_) best | trace msg False = undefined
   where msg = "--- p = " ++ show p ++ "  best: " ++ show best

The main definition is:

 loop ps best@(n,total) =
   let (as, bs) = splitAt (n+1) ps -- better solution must have at least n+1 primes
       total0 = sum as
   in
   if total0 >= 1000000
      then best
      else let best' = maximum $ [best] ++ primeSums (n+1, total0) bs
           in
           loop (tail ps) best'

To kick everything off:

 solution = loop myPrimes (0,0)

which results in the followin output:

*Euler50> solution
--- p = 2  best: (0,0)
--- p = 3  best: (536,958577)
--- p = 5  best: (536,958577)
--- p = 7  best: (539,978037)
--- p = 11  best: (543,997651)
(543,997651)

So the longest sum begins at 7 and has length 543 and has sum 997651.
Solving the problem only involves looking at sums which start from the first
five primes.


Sum Square Difference, which way is more Pythonic?

I would do something like:

def sum_of_squares(n):
    return sum(i ** 2 for i in range(1, n+1))

def square_of_sum(n):
    return sum(range(1, n+1)) ** 2

def sum_square_difference(n):
    return sum_of_squares(n) - square_of_sum(n)

Notice the use of a generator expression in sum, where I have omitted the square brackets.


Since $_POST['vname'] is not escaped, your mail script is vulnerable to a header-splitting attack like this.  A cleverly crafted name could be used to make your script CC any arbitrary recipient and thus send spam.


Loading template file and replacing placeholders

I would say suggest writing your input like so:

function replace_tags($template, $placeholders){
    $placeholders = array_merge($placeholders, array('<?'=>'', '?>'=>''));
    return str_replace(array_keys($placeholders), $placeholders, $template);
}

$vars = array('{{NAME}}'=>'Bob', '{{USERNAME}}'=>'user_name');
$template = file_get_contents('template.tmpl', true);

echo replace_tags($template, $vars);

So that you can define the constant changes, and the changes you want to build depending on user, etc.


Your code is in pretty much good shape but there are still several issues apart from what mentioned by ChrisW:

There are many cases in input arguments and return types of functions where you are not particularly careful about const/non-const and value vs. reference.
This code won't work for built-in arrays, hence neither for C-style strings. One way is to decay the type of the input argument before storage; built-in arrays are decayed to pointers in this case (which means array elements are not really copied).
The default constructor shouldn't allocate anything; initialize the data pointer to nullptr and provide member functions empty() and clear() to control the state of having/not having data.
Your assignment operators are unnecessarily complex, inefficient (by self-tests) and not exception-safe (if new throws, the current object is already destroyed). The most elegant solution to all these issues is the copy-swap idiom, where all actual work is done by constructors alone.
You don't need typeid to test for type equality; a lightweight (but low-level) solution without RTTI is here.
Type identification should be kept as an internal detail; the minimal required functionality is type equality by is(); don't expose type(), rather keep it as private as possible.
Type checking is a good thing, but for performance you should also provide unchecked access.
Casting is from a base to a derived class, so need not (and should not) be done with reinterpret_cast; rather, dynamic_cast / static_cast for checked / unchecked access. dynamic_cast to a reference type will automatically throw an std::bad_cast if the object is not of the right type, so there is not need to manually check with is(). This does need RTTI but is more elegant.
Storing empty objects (like function objects) is currently inefficient, as it does need extra space on top of the virtual function table. This can be solved by the empty base optimization, which is done automatically by using std::tuple.
Implicit conversion operators are a possible source for ambiguities and confusion; you may keep them if you need their convenience, but use carefully (e.g. try to explicitly initialize an object of the right type).
Comparison operators are a clear overkill (if you have them, why not also have arithmetic operators, and so on?). If you still want them, define them as non-member functions, using public members is and cast to implement them.
There are no move semantics.
There is no specialized binary (non-member) function swap. Defaulting to std::swap is not as efficient as it involves three move operations; without move semantics, things are even worse as it involves three copy operations.

I took the liberty to re-factor your code to a great extent, and here is the result, resolving all issues above:

class some
{
    using id = size_t;

    template<typename T>
    struct type { static void id() { } };

    template<typename T>
    static id type_id() { return reinterpret_cast<id>(&type<T>::id); }

    template<typename T>
    using decay = typename std::decay<T>::type;

    template<typename T>
    using none = typename std::enable_if<!std::is_same<some, T>::value>::type;

    struct base
    {
        virtual ~base() { }
        virtual bool is(id) const = 0;
        virtual base *copy() const = 0;
    } *p = nullptr;

    template<typename T>
    struct data : base, std::tuple<T>
    {
        using std::tuple<T>::tuple;

        T       &get()      & { return std::get<0>(*this); }
        T const &get() const& { return std::get<0>(*this); }

        bool is(id i) const override { return i == type_id<T>(); }
        base *copy()  const override { return new data{get()}; }
    };

    template<typename T>
    T &stat() { return static_cast<data<T>&>(*p).get(); }

    template<typename T>
    T const &stat() const { return static_cast<data<T> const&>(*p).get(); }

    template<typename T>
    T &dyn() { return dynamic_cast<data<T>&>(*p).get(); }

    template<typename T>
    T const &dyn() const { return dynamic_cast<data<T> const&>(*p).get(); }

public:
     some() { }
    ~some() { delete p; }

    some(some &&s)      : p{s.p} { s.p = nullptr; }
    some(some const &s) : p{s.p->copy()} { }

    template<typename T, typename U = decay<T>, typename = none<U>>
    some(T &&x) : p{new data<U>{std::forward<T>(x)}} { }

    some &operator=(some s) { swap(*this, s); return *this; }

    friend void swap(some &s, some &r) { std::swap(s.p, r.p); }

    void clear() { delete p; p = nullptr; }

    bool empty() const { return p; }

    template<typename T>
    bool is() const { return p ? p->is(type_id<T>()) : false; }

    template<typename T> T      &&_()     && { return std::move(stat<T>()); }
    template<typename T> T       &_()      & { return stat<T>(); }
    template<typename T> T const &_() const& { return stat<T>(); }

    template<typename T> T      &&cast()     && { return std::move(dyn<T>()); }
    template<typename T> T       &cast()      & { return dyn<T>(); }
    template<typename T> T const &cast() const& { return dyn<T>(); }

    template<typename T> operator T     &&()     && { return std::move(_<T>()); }
    template<typename T> operator T      &()      & { return _<T>(); }
    template<typename T> operator T const&() const& { return _<T>(); }
};

I call it some instead of any because I prefer to hold something rather than anything :-) Plus, any is a common name for a function (like all), which is not the case for some.

Members cast() provide type-checked access, while members _() (shortest notation) provide unchecked access. I have chosen to give conversion operators unchecked access for performance but you are free to change that or remove them altogether.

I've also made a live example, including an extensive series of tests to demonstrate (almost) all possible uses.

Note that base (your dummy) now has a virtual destructor.

There is one more issue: using the free store is serious performance bottleneck when it comes to small types. What you can do is define a particular size to be allocated on stack, and only use the free store for larger objects, similar to short (or small) string optimization.

More generally, it is a good idea to parametrize the implementation with respect to how memory management (allocation, deallocation) is done by providing a kind of allocator object. any is really a container, even if of at most one object.

I have extended the implementation towards this direction but I will probably post this as a separate answer.


The code is overcommented. Most of the comments do not add any value. They explain what the code is doing, which is obvious; the good comment shall explain why and how the code is doing what it is doing. Some of them are outright wrong, e.g.
   #the middle number is equal to the first num divided by the last number

Say what? Nothing is divided by the last number!
In any case, try to avoid comments. A presence of an explanatory comment means the failure to express yourself in the code.

As mentioned in the comment (no pun intended), the code implements a binary search.
  (fir + las) // 2

is all right in Python with its arbitrarily long integers; in most other languages, which deal with the native integers, computing fir + (las - fir) / 2 is indeed preferable.

Testing for i == -1 looks smelly. Most of the times i remains -1, and it only gets the meaningful value when the target number is found. When the condition
  list[mid] == num

is satisfied, it is a time to break the loop, or even return i right away.

Detour.
Returning -1 when the target number is not there is not right. All the work your function have done is suddenly discarded. Don't be discouraged: you are in the good company. bsearch from the standard C library makes the same blunder.
It is very helpful to return an insertion point instead: where the target number would have been. See how bisect.bisect_left()  does it right (ditto for C++ std::lower_bound).


You have some repeat id tags which aren't good. Using class names instead is much better.

Home

|

About Us

|

Contact Us

And in the CSS it becomes:

.noUD {
  text-decoration: none;
}

You also have standard HTML elements for headers, footers, navigations, and articles:

 becomes

 becomes

 becomes

You are still able to keep classes and ids with this. It just adds extra readability for systems (and humans) and it makes it better in case your CSS fails because browsers apply their own styling to some standard elements.

position: relative; bottom: 0 does nothing in terms of positioning because it sets the element 0 up from where it was before.

Other than that the code looks pretty good.


General way to add persistence to a class in Python

No time to do a proper review, but some quick notes:

There are no docstrings! How am I supposed to use your code?
Doesn't follow the Python style guide (PEP8): in particular, line lengths are too long, so we have to scroll horizontally to read it here.
You should use super to call superclass methods, otherwise your code won't play nicely with multiple inheritance.
This relies on original_class.__init__ taking one optional argument which is copied to self. This seems rather inflexible: it works for some built-in constructors like list but it is not very general. It would be better to leave __init__ alone and use a factory function to do the construction.
It seems clumsy to have to specify the names of all the methods that you need. Python has the tools (dir, __getattribute__, etc.) to avoid this.
Copying attributes from one object to another works for methods but not for properties.
It would be better to actually use the context manager protocol (__enter__ and __exit__) and not contextlib.closing, which requires the object to have a close method which might conflict with original_class.close.
Consider using three-argument type instead of making a class with the wrong name and then rewriting its __name__ attribute.
At the moment you write the object to disk after every change, which is costly. Better to postpone this until the object is finished with.
Consider saving the object via the __del__ method.
Test cases should be organized into unit tests so they are runnable via the unittest module.
Consider catching FileNotFoundError instead of catching IOError and then re-raising if the error code is not ENOENT.


Synchronous and asynchronous motor movement

My suggestion would be to create a special result value (similar to Future) that would represent an asynchronous computation:

class Future(object):
  def result(self):
    raise NotImplementedError()

where result waits until the underlying computation finishes and returns the reuslt.

Then let all your methods return instances of Future asynchronously. If you want a synchronous invocation, just call

motor.move_to(position).result()

The actual implementation in Motor would depend on your needs, in particular:

When calling two subsequent asynchronous computations, should the second block or should it be queued?
Should result() block only until its corresponding call has finished, or until the motor is idle? The former makes more sense, but would require something different than block_until_idle.
Should the class be thread-safe? (Your example code isn't.)


Determining possible triangle from lengths of line segments

As has been pointed out, you must do several things to ensure you get the maximum marks.

Ensure that negative numbers are checked for.
Handle the MAX_INT overflow issue which could arise.

  You know 4 + 5 > 7 is same as 5 > (7 - 4). Yes I know you are grinning ;)

This suggested solution is correct for this.

These two individual points should allow you to achieve the maximum score. Now I would just like to quickly go over some theory behind why this solution works.

Time complexities

It seems people keep asking you to address the "consecutive elements". You have already done this through the use of Arrays.sort(). This Java sort algorithm is referred to as a "tuned Quicksort" ( See http://docs.oracle.com/javase/6/docs/api/java/util/Arrays.html#sort(int[]) ).

  The sorting algorithm is a tuned quicksort, adapted from Jon L. Bentley and M. Douglas McIlroy's "Engineering a Sort Function", Software-Practice and Experience, Vol. 23(11) P. 1249-1265 (November 1993). This algorithm offers n*log(n) performance on many data sets that cause other quicksorts to degrade to quadratic performance.
  Quicksort is well known for its O( n log n ) time complexity (excluding extreme cases).

After this you do a single iteration over the array, which is considered O(n). When we add the two time complexities together we are given O( 2n log n) where constants are considered insignificant for Big-O notation. So to clarify this simplifies down to O(n log n) which was the upper bound of the problem.

How sorting solves non-consecutive elements

Once the array is sorted it is true that only consecutive triples need to be considered.

Consider the following array: {1,2,6,6,8}

Whilst it may be true that (1, 6, 6) is triangular, and is non-consecutive. It can also be proven that if that value is triangular then any number which lies between the initial 1, and 6 will also be triangular.

From this we can see that in the sort array, for each non-consecutive triangular triples which exists there also exists an consecutive triple.

Simplification from sorting

The sort operation allows you to simplify you checks later, and decrease execution time. When checking for negative number, you only need check the lowest number in the triple, as if this is >= 0 it is given the follow values must be >= that initial value.

This mean you only need check one value for negativity, not three.

This can be extended further into the actual triangular checks. If it is true that the smallest two numbers in the triple are larger than the largest number when summed, then all three statements are true.

  1) A[P] + A[Q] > A[R]

  2) A[Q] + A[R] > A[P]

  3) A[R] + A[P] > A[Q]

Remembering the algorithm change to this, so these would be evaluated as

A[P] > (A[R] - A[Q])

Because we can guarantee that A[P] < A[Q] < A[R] due to A being sorted, we only need perform the one check above.


possible multiple enumerations of IENuemerable
Should I change it to a List or leave it the way it is?

This depends on the situation. If there is an EF query behind the IEnumerable and you have never called .ToList() on it (not even once), then every time you enumerate it, the query will be executed against the database. If this is your case then you need to call .ToList() so your query can be executed and the results can be stored in a list on the application side. Whenever you want to get a fresh copy from the database, then you can run your query again or run a query which gets you the delta.
If you are doing everything in memory and there are no database calls, then if items are added to the underlying list, you will not get them. Consider this snippet:
IEnumerable<int> list = new List<int> { 1, 2 };
list.Count(); // returns 2

list.ToList().Add(3);
list.ToList().Add(4);

list.Count(); // it still returns 2


Hexadecimal to decimal converter in C (htoi.c)

#define LIMIT 1024: magic constants should be named well. What is the limit for? You are also storing the result in an unsigned long and contain much less than 1021 hex digits (the last 3 are for 0x and the null terminator).

Operators should be spaced for better readability: int i = 0; and for (int

I'm a bit rusty with C, but I think fgets can be used instead of rolling your own getc loop

Inside htoi, a single tolower or toupper removes the need to check lowercase and capitals

if(s[i] >= 'a' && s[i] <= 'z'): hex digits only contain 0-9 and a-f (not a-z)

pow(16, power): in this case, pow(16, power) = 1 << (4 * power) (see bitshifts). I would split the 4 * power so that it is more clear what it represents (digit position)

Some changes to the algorithm are necessary: input of 1z00x000 gives 53477376 and kibe gives 86718. I would check if there is a leading 0x and if there is, to skip it (if not, return an error code)

if not, then we assume it is an upper case char and And should it be unsigned as well if I know it won't be negative: with your code, I can get currdigit to underflow by choosing (for example) a plus sign as input.


if(head == NULL)  // is there more elegant way of dealing with this? any idiom?
{
head=newp;
return;
}

head is a local variable in this function. Modifying it will not change the variable that was passed into the function. As a result, the new node you create isn't attached to anything that the caller can access. If you want to modify a variable being passed in you need to use a pointer. If you want to modify a pointer, you need to use a pointer to a pointer.

Here is a version which reduces the amount of code, but for those who don't think in pointers naturally it may be hard to follow.

// I take a pointer to a pointer so that I can modify it if need be.
void insertattail(struct node **head,int data)
{
    // advance the pointer until it reaches NULL
    // because its a pointer to a pointer I can modify it
    while(*head != NULL) head = &(*head)->next;

    // replace that NULL with a new node
    *head = malloc(sizeof(struct node));
    // fill up the node
    (*head)->data = data;
    (*head)->next = NULL;
}


Rails view to list users in a zebra-striped table

Rails has a built in method, cycle, which will cycle between two more more options for you, so you don't have to manage the "Even"/"Odd" selection.

<% @patients.each do |patient| %>
  <%= content_tag :tr, :class => cycle('Even', 'Odd') do %>
    <%= content_tag :td, link_to(patient.id, patient) %>
    <% [:username, :first_name, :last_name, :email, :active, :disabled].each do |property| %>
      <%= content_tag :td, patient.user.send(property) %>
    <% end %>

        <%= content_tag :li, link_to('Detail', patient) %>

  <% end %>
<% end %>

If you happen to use Haml, it looks quite nice. :)

- @patients.each do |patient|
  %tr{:class => cycle('Even', 'Odd')}
    %td= link_to(patient.id, patient)
    - [:username, :first_name, :last_name, :email, :active, :disabled].each do |property|
      %td= patient.user.send(property)
    %td
      %ul.Horizlist
        %li= link_to('Detail', patient)


Avoid branching code for degenerate cases in Fibonacci generator

Consider breaking it up into two methods: one, Fibonacci(), that represents the infinite* Fibonacci sequence, and another, Fibonacci(int), that just returns Fibonacci().Take(n). This removes the branching.

An implementation might look like this:

static IEnumerable<int> Fibonacci(int n)
{
    return Fibonacci().Take(n);
}

static IEnumerable<int> Fibonacci()
{
    int a = 0;
    int b = 1;
    while (true)
    {
        yield return a;
        int c = a + b;
        a = b;
        b = c;
    }
}

* Well, the first 47 values that fit in an int.


This is overall well-thought-out, well-organized, and well-written.
There's at least one bug, and one oversight that I would consider a bug:

In traverse your recursive call is passing the wrong second parameter:
} else if (mode == Node.Traversal.DepthFirst) {
    callback(this);
    this.children.forEach(n => n.traverse(callback, false));
}
should read
} else if (mode == Node.Traversal.DepthFirst) {
    callback(this);
    this.children.forEach(n => n.traverse(callback, Node.Traversal.DepthFirst));
}

in add you don't declare child.  Presumably is should read for (let child of children)

As to design decisions, there are several things you might want to consider.

add might be improved with return this.

I think a clone method might be a more common choice here than a static from function.

You might find the ES6 class syntax slightly more explicit.  I wasn't a big fan of it when it was proposed, and I'm still not; I don't like the implication it suggests that JS OOP is particularly similar to Java/C# style OOP.  But it does carry a bit less cruft than the constant repetition of Node.prototype.

Rather than use an enumeration of traversal types, you might want to consider simply using functions instead.  That is,
Node.Traversal = {
    BreadthFirst: function(callback) {
        let nodes = [this];
        while (nodes.length > 0) {
            const current = nodes.shift();
            callback(current);
            nodes = nodes.concat(current.children);
        }
    },
    DepthFirst: function(callback) {
        callback(this);
        this.children.forEach(n => n.traverse(callback,  Node.Traversal.DepthFirst));
    }
};

Node.prototype.traverse = function(callback, traversal = Node.Traversal.BreadthFirst)
{
    traversal.call(this, callback);
    return this;
};

This would make it easier for you to add another traversal, since you only have to do it in one place, and it lets users supply their own instead.

Perhaps most importantly, you might want to drop the parent property.  You do not use it anywhere except in building or cloning a tree, and it can lead to real problems.  For instance, if you cloned a tree with from (and therefore ended up with non-empty parent nodes), you will not be able to call JSON.stringify on it due to the cyclic nature.

Putting this all together, here's an alternate version:

console.clear()

class Node {
  constructor (value = 0, children = []) {
    this.value = value;
    this.children = children;
  }

  static Traversal = {
    BreadthFirst: function(callback) {
        let nodes = [this];
        while (nodes.length > 0) {
            const current = nodes.shift();
            callback(current);
            nodes = nodes.concat(current.children);
        }
    },
    DepthFirst: function(callback) {
        callback(this);
        this.children.forEach(n => n.traverse(callback,  Node.Traversal.DepthFirst));
    }
  }

  clone () {
    let that = Object.assign(new Node(), this);
    that.children = this.children.map(n => n.clone());
    return that;
  }

  add (...children) {
    for (let child of children) {
      this.children.push(child);
    }
    return this;
  }

  traverse (callback, traversal = Node.Traversal.BreadthFirst) {
    traversal.call(this, callback);
    return this;
  }

  reduce (callback, initial, mode) {
    let acc = initial;
    this.traverse(n => acc = callback(acc, n), mode);
    return acc;
  }

  every (callback) {
    return this.reduce((a, n) => a && callback(n), true);
  }

  some (callback) {
    return this.reduce((a, n) => a || callback(n), false);
  }

  find (callback, mode) {
    return this.reduce((a, n) => a || (callback(n)? n: false), false, mode);
  }

  includes (value) {
    return this.some(n => n.value === value);
  }
}

const tree = new Node ('A', [
  new Node('  B', [
    new Node('    D'),
    new Node('    E', [
      new Node('      G'),
    ]),
    new Node('    F')
  ]),
  new Node('  C')
])

tree.children[0].children[2].add(new Node('      H')).add(new Node('      I'))

const log = ({value}) => console.log(value)
console.log('===============================')
console.log('Breadth-first')
console.log('===============================')
tree.traverse(log)
console.log('===============================')
console.log('Depth-first')
console.log('===============================')
tree.traverse(log, Node.Traversal.DepthFirst)
console.log('===============================')
console.log('Clone, Breadth-first')
console.log('===============================')
tree.clone().traverse(log)
console.log('===============================')
console.log('Clone, Depth-first')
console.log('===============================')
tree.clone().traverse(log, Node.Traversal.DepthFirst)


C++ program to swap links of a Linked List

This works as long as 2 conditions are met.

val1 and val2 are in the list.
Neither are in the head node.

Otherwise you access stuff via null pointers:

  void swapLinks(T val1, T val2)
  {
    Node* prevNode1 = nullptr;
    Node* prevNode2 = nullptr;
    Node* nextNode1 = nullptr;
    Node* nextNode2 = nullptr;
    Node* node      = head;
    Node* node1     = search(val1);
    Node* node2     = search(val2);

    // This will not find values in the "head node"
    // If the value is in head the you will not find a previous node.
    // You need to take into account this special case at the bottom.
    while(node->next != node1)
    {
      node = node->next;
    }
    if(node->next == node1)
    {
      prevNode1 = node;
      nextNode1 = node1->next;
    }

    node = head;

    // This will not find values in the "head node"
    // If the value is in head the you will not find a previous node.
    // You need to take into account this special case at the bottom.
    while(node-> next != node2)
    {
      node = node->next;
    }
    if(node->next == node2)
    {
      prevNode2 = node;
      nextNode2 = node2->next;
    }

    // HERE YOU HAVE some issues.
    // prevNode1 or prevNode2 or node1 or node2 may be nullptr
    // If any of these values are null the code below will be UB.
    prevNode1->next = node2;
    Node* tmp       = node2->next;
    node2->next     = node1->next;
    prevNode2->next = node1;
    node1->next     = tmp;
  }