Optimize code block for LINQ and non LINQ

First - if you are working with DataTables, then you can use Linq to DataSet, which has nice extension methods to get field values.

Now let's review logic of your code. You are not using any data from tblone and tbltwo in your result. Actually you only finding joined categories between these two tables, and for each matched rows pair you are adding all m values from tblthree and tblfour to result. I find this logic pretty strange. Maybe you are expecting only single match here. Then you will need boolean result (match found or not). But basically you need count of joined rows:

var matchedCategoriesCount =
            (from one in tblone.AsEnumerable().Where(r => r.Field<bool>("id"))
             join two in tbltwo.AsEnumerable()
                on one.Field<string>("cate") equals two.Field<string>("category")
             select one).Count();

Same with lambda syntax if you find it more readable:

var matchedCategoriesCount =
            tblone.AsEnumerable().Where(r => r.Field<bool>("id"))
                  .Join(tbltwo.AsEnumerable(),
                        one => one.Field<string>("cate"),
                        two => two.Field<string>("category"),
                        (one, two) => one)
                  .Count();

Then you can select m values from tblthree and tblfour N times and create new DataTable:

// if (matchedCategoriesCount > 0)
var values = tblthree.AsEnumerable().Concat(tblfour.AsEnumerable())
                     .Select(r => r.Field<string>("m")))
                     .ToArray();

You can even use simple loop here:

for(int i = 0; i < matchedCategoriesCount; i++)
   foreach(var value in values)
       datatemp.Rows.Add(value);

And last - don't use variable names like tblone, tbltwo, tblthree etc. These names does not explain what data these variables hold. Use names from domain of your application.


In Java 8 you can more accurately represent the dateOfBirth with a LocalDate.
If the ageAt() method also takes a LocalDate as argument, then the age is easily computed using Period.

public int ageAt(LocalDate ageReferenceDate) {
    return Period.between(dateOfBirth, ageReferenceDate).getYears();
}

It is fairly easy, albeit a bit verbose, to convert a Date instance to a LocalDate :

LocalDate localDate = ZonedDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault()).toLocalDate();

The catch is that you need to interpret it vs. a ZoneId. A Date can be mapped to different LocalDates depending on what ZoneId (TimeZone's successor) it is evaluated against. You should use the ZoneId that was used when the Date was recorded. That is probably ZoneId.systemDefault(), but if your code can run on systems accross time zones, you can have a problem.

This is also the reason why it is a better idea to represent date of birth as a LocalDate, since it does away with that ambiguity.


Setting header color on scroll for each post

jsBin demo

Instead of storing section positions on window onload time, which can be always kind of inaccurate since your images might still load...

get dynamically  the current position / size data of an element using:

element.getBoundingClientRect()

using that JS method you don't even need to calculate the $(window).scrollTop()
 cause the returned value is the element's position respective to the client top (viewport top edge).

To retrieve only the one element that matches a top criteria you can use the jQuery's .filter() method and return the element which...

$section.filter(function(){
    var r = this.getBoundingClientRect();
    return  r.top + r.height - 100  > 0; // ...matches this
})

(100 is the header height in this demo; set as desired or calculate dynamically)

Now, since jQuery filtered more than one element that matches that criteria of (gbcr.top + gbcr.height - headeroffser) > 0 by going directly to chain another method to it like .data(), the value will be respective to the first of elements returned in the .filter() collection:

$header.css({
  color : $section.filter(function(){
    var r = this.getBoundingClientRect();
    return  r.top + r.height - 100 > 0;
  }).data().colour // is the colour data of the first of filtered elements
});

Store that colouring stuff inside a setScrollColors function and use like:

$(function() { // DOM ready shorthand

  var $header  = $("header");  // Cache selectors
  var $section = $("section");

  function setScrollColors() {
    $header.css({
      color : $section.filter(function(){
        var r = this.getBoundingClientRect();
        return  r.top + r.height - 100 > 0;
      }).data().colour
    });
  }

  setScrollColors();                            // Call inside dom ready
  $(window).on("load scroll", setScrollColors); // call also on load and scroll

});
*{margin:0;}
header{
  position:fixed;
  z-index:1;
  top:0;
  width:100%;
  background:#f9f9f9;
  height:100px;
  border-bottom:1px solid currentColor;
}
#content{
  margin-top:100px;
}
section{
  min-height: 1000px;
  min-height: calc(100vh - 100px);
  border-top:1px solid #000;
}

HEADER

black

red

blue

green

fuchsia

orange


I have some suggestion for you.

Use the java.lang.StringBuilder instead of the older java.lang.StringBuffer

The java.lang.StringBuilder is generally faster than the older java.lang.StringBuffer.

Use the same instance of java.util.Scanner

Move the java.util.Scanner of the loop, you can reuse it. you can use the obj instance and use only this instance.

Reuse the same java.lang.StringBuilder instead of creating a new one each time.

You can reuse the same builder by clearing it with the method java.lang.AbstractStringBuilder#setLength and passing zero to the method; this will prevent the object creation to be put on the stack and use less memory than creating lots of instances of the builder.

Extract similar code to methods.

In your code, you can extract some of the code to methods; this will make the code shorter and easier to read. I suggest that you create a method to read the input and revert it as a String.


One variable per line please.

int gess,i=0,found=0,  r = rand()%100;

This makes the code hard to read. There is also one corner case (with pointers) were this will not work as expected for beginners. As a result this is usually banned in most companies coding standards.

You are using found as a boolean variable.
Treat it as such. use TRUE/FALSE.

I would change the while() into a for(;;) loop. Then you can remove all the increments.

while (i<10 && found==0)

--

for(int i = 0; i < 10 && !found; ++i)

White space is your friend:

if (found==1&&gess==1)  // This is hard to read and will get worse with more conditions.

if (found && (guess == 1)) // much more readable
//  ^^^^^  boolean use it as such.

Your "st", "nd", "rd", "th" is not correct.

10-19    => th
x1       => st
x2       => nd
x3       => rd
x[4-9]   => th

Also you print basically the same string every time on success. So we not have one print statement and just separate the logic for getting the ending.
I would change the logic:

if (!found)
{
    printf("\n Never mind try again");
}
else
{
    char const* ext = "th";
    if ((gess < 10) || (gess >= 20))  // 10->19 already set
    {
        int end = gess % 10;
        if      (end == 1) { ext = "st";}
        else if (end == 2) { ext = "nd";}
        else if (end == 3) { ext = "rd";}
    }

    printf("\n Very good the number is %d this is your %d%s gess", gess, i, ext);
}


Create composition instead of inheritance

"... instead of inheritance.." I expected the JobFilterRequest class to encapsulate the TimeFrame object by wrapping the contained TimeFrame object's methods in its own. Thus the client code is not aware of a distinct inner object - the Law of Demeter a.k.a. the least knowledge principle.

That encapsulation implies there is no public getter; and I would prefer a constructor parameter over the public setter.

If we inherit from TimeFrame there is no contained object, so good encapsulation makes composition "feel" the same for the client code. Class types are different of course, but we're still calling the same methods and getting the same behavior.


Using a string instead of division / modulo seems to be a few percent faster than the solution from the question:

    public static int Reverse(int x)
    {
        var str = x.ToString();
        int res = 0;
        int multiplier = 1;
        var negative = str[0] == '-';
        for (int i = negative ? 1 : 0; i < str.Length; i++)
        {
            var num = str[i] - 48;
            if (num > 0 || multiplier > 1)
            {
                res += num * multiplier;
                multiplier *= 10;
            }
        }
        return negative ? -res : res;
    }

However, improving the solutions from the question using System.Math.DivRem (as mistertribs suggested in a comment) will be even faster :):

    public static int Reverse(int x)
    {
        var result = 0;
        var negative = x < 0;
        if (negative) x = -x;

        while (x != 0)
        {
            x = Math.DivRem(x, 10, out var rest);
            result = result * 10 + rest;
        }

        return negative ? -result : result;
    }


Doubly linked std::list simple implementation

Take care to be explicit about compiler generated functions

Effectively your List class violates the Rule of Three/Five/Zero, thus the compiler generated copy/move constructors will create unexpected side effects by implementing a shallow copy mechanism.

Let's suppose you have code like

int main() {
    List l1;
    List l2;

    l1.push_back(5);
    l1.push_back(42);
    l1.push_back(21);

    l2 = l1; // Copy the list
    *l1.begin() = 80; // Change the original list

    for(auto value : l2) {
        std::cout << value << std::endl;
    }
}

The output is

80
42
21

I doubt you really intended that. See the Live Demo please.

Why not making your class a template?

using T = int;

looks strange.

Why not making the List class a template like

template<typename T>
class List {
    // ...
};

Compiles and works the same way here

Prefer smart pointers instead of raw pointers

You should prefer using smart pointers instead of managing new and delete yourself.

I have evolved the demo from above with changing the relevant parts

class Node;
class Node {
public:
    T data;
    std::shared_ptr<Node> next;
    std::shared_ptr<Node> prev;

public:
    explicit Node(std::shared_ptr<Node> next_, std::shared_ptr<Node> prev_) : next(next_), prev(prev_) {}

    explicit Node(const T &_data, std::shared_ptr<Node> next_, std::shared_ptr<Node> prev_) :
            data(_data), next(next_), prev(prev_) {}

    ~Node() {}
};

class Iterator : public std::iterator<std::bidirectional_iterator_tag, T> {
public:
    std::weak_ptr<Node> position;
    std::weak_ptr<Node> tail;

public:
    Iterator(std::shared_ptr<Node> node) : position(node) {}

    Iterator(std::shared_ptr<Node>node, std::shared_ptr<Node>_tail) : position(node), tail(_tail) {
    }

    Iterator &operator++() noexcept {
        position = position.lock()->next;
        return *this;
    }

    Iterator operator++(int) noexcept {
        auto old = *this;
        position = position->next;
        return old;
    }

    Iterator &operator--() noexcept {
        if (position == nullptr) position = tail;
        else
            position = position->prev;
        return *this;
    }

    Iterator operator--(int) noexcept {
        auto old = *this;
        if (position == nullptr) position = tail;
        else
            position = position->prev;
        return old;
    }

    T &operator*() const noexcept {
        return (position.lock()->data);
    }

    bool operator!=(Iterator other) noexcept {
        return position.lock().get() != other.position.lock().get();
    }

    bool operator==(Iterator other) noexcept {
        return position.lock().get() == other.position.lock().get();
    }

    ~Iterator() {}
};

Solve the shallow copy problem

As mentioned in my 1st point you have a problem with The Rule of Three/Five. Your List class will be shallow copied. So you should provide the relevant operations.
This will be a lot easier using smart pointers as mentioned in my previous point

List(const List<T>& rhs) {
    copy(rhs);
}

List(List<T>&& rhs) {
    move(std::move(rhs));
}

List& operator=(const List<T>& rhs) {
    copy(rhs);
    return *this;
}

List& operator=(List<T>&& rhs) {
    move(std::move(rhs));
    return *this;
}

void copy(const List<T>& rhs) {
    clear();
    for(auto value : rhs) {
        push_back(value);
    }
}

void move(List<T>&& rhs) {
    head = std::move(rhs.head);
    tail = std::move(rhs.tail);
}

void clear() {
    std::shared_ptr<Node> temp = head;
    std::shared_ptr<Node> next;
    do {
        if(temp) {
            next = temp->next;
        }
        temp = nullptr;
    } while(next);
}

~List() {
}

Output is as expected for the example mentioned in the 1st paragraph:

5
42
21

Again you can check the improved code here.


The code looks like typical code that uses the Google Maps API. Nice work serializing the markers in localstorage.

I did notice that there doesn't appear to be any mechanism to prevent the user from adding one marker multiple times. You may need to change your data structure to one that associates keys with values (e.g. a (hash) Map, or use an object instead of an array).

Related to preventing markers from appearing multiple times in the array, there appears to be a bug: when the user removes a marker, all other markers get duplicated because after removeMarkersFromLocalStorage() is called, the call to renderMarkers() will call generateMarker() for each marker, which in turn adds the marker to the list again.

I would recommend that instead of adding a listener for rightclick to each marker, try to add the listener to the map. It doesn't appear that the callback run on the rightclick event utilizes any properties of the marker - just the latitude and longitude of the event. It may be the case that the Google Maps API and/or modern browsers have handled it but in general, one cause of memory leaks in Javascript is adding an event listener to a DOM element and then having that element removed. For more information on that topic , read 4 Types of Memory Leaks in JavaScript and How to Get Rid Of Them - especially the section under the heading 2: Forgotten timers or callbacks.


On the whole your code seems pretty concise and clean.  I've just got a couple of side points.
Scope creep
This is a real problem in production code, where developers implement stuff that isn't really needed.  Your specification you've posted says 'take an exact string and an exact filename'.  You've allowed a regular expression to be passed.  The original requirements could have been met by just using strstr which would have made the code quite a bit smaller.  You've used extra time and added extra complexity, is there a real benefit?
The scope creep also means that I can't pass the basic string "\n" into your parser and have it find it as the '\n' is interpretted by the regex parser.  So, with grep I can do:

grep -F "\n" someFile.h

And get lines with the text \n:

printf("some text\n");

Whereas running your code:

./a.exe "\n" someFile.h

I get every line that ends in a newline (i.e. every line of the file).
-h -i and arguments
If you're going to implement programs that take in arguments, it's a good idea to give the user some way to find out what the arguments mean.  When I use grep -i, I'm trying to do a case-insensitive search.  Your program advertises a '-i' option, however it doesn't do the same thing as grep.  Instead I get told it can't open a file:

$ ./a.exe -i if someFile.h
if: could not open: No such file or directory


The function check_winner() does not need global move_count.  Using global is code smell, avoid if at all possible, which tends to be always.  But in this case it is completely unnecessary, as move_count, like board, is already accessible in check_winner().

winning_list is constructed every time check_winner() is called.  It does not persist from one call to the next, so new_list = winning_list and the comment immediately above it should be removed.

The statement move = int(input(...)) can crash if the user enters invalid input.  Even if a valid integer is given, the integer could be outside the valid range, like 42, which will cause when board[move] is evaluated.  Place user input in a try ... except statement, inside a loop, and don’t let the program continue until valid input has been given.

You have a game loop that handles two turns (a move by both players) each pass through the loop.  While this does work, it will paint you into a corner in subsequent programs.  3 or more players is going to make writing the game loop much harder.

It is usually simpler to handle one turn (a move by only one player), in each pass through the loop.  At the end of the loop, the “current player” is incremented, wrapping around to the first player when necessary.  With only 2 players, this alternates between them.  More advanced games may require skipping player when a “lose a turn” move is made.  Other games may even reverse the direction of play mid game.  All of these would be horrible to try to write the game loop for if each pass through the loop tried to handle all player moves in one pass.

When the game loop is change to handle only a single move at each pass, it is much easier to handle the “game over” condition.  A while game_is_running loop is all that is required.  Or, for tic-tac-toe, you could use:

for move_count in range(9):
    # moves made here
    # break if someone wins
else:
    print("You Tied")

The else: clause of a for loop only executes if the loop finishes without executing break, so after 9 moves with no winner, it is a tie game.

Using sys.exit() to stop the interpreter on a “game over” condition is a bad idea.  It works here, but it makes test code impossible to write, because the program can kill the interpreter, and the test code can’t stop that.


Write a typo correction program with Levenshtein distance algorithm

I see very little space for improvements.

First, your min3 macro (btw, max is missing a closing bracket) will, in some cases, execute inside branching more than needed (i.e., if c > min2(a,b)). I'd write it directly:

#define min3(a, b, c)   \
((a) < (b) ? ((a) < (c) ? (a) : (c)) : ((b) < (c) ? (b) : (c)))

Second, this part:

for (size_t i = 1UL; i <= nt; ++i) {
    char const cCol = t[i-1];
    d2[0UL]         = i;

can save one subtraction:

for (size_t i = 0UL; i < nt; ) {
    char const cCol = t[i];
    d2[0UL]         = ++i;

Maybe the inside loop can be made faster by using pointer arithmetic instead of indexing, but I'm not sure. So, you can try replacing

    for (size_t j = 1UL; j <= ns; ++j) {
        int    const nCost = s[j-1] != cCol;
        size_t const i1    = d1[j  ] + 1;
        size_t const i2    = d2[j-1] + 1;
        size_t const i3    = d1[j-1] + nCost;
        d2[j] = min3(i1, i2, i3);
    }

with

    size_t *d1j = d1+1, *d2j1 = d2, *d1j1 = d1;
    for (size_t j = 1UL; j <= ns; ++j) {
        int    const nCost = s[j-1] != cCol;
        size_t const i1    = *d1j + 1;
        size_t const i2    = *d2j1 + 1;
        size_t const i3    = *d1j1 + nCost;
        *d2j = min3(i1, i2, i3);
        d1j1 = d1j++;
        d2j1++;
    }


There are two things I see.

Don't store a reference to a time out. I think the count down starts when After() is called.

timeout := time.After(2000 * time.Millisecond)
...
case <- timeout:

Most code I've seen writes it like this.

case <- time.After(2000 * time.Millisecond):

Use a lock when accessing a map from multiple goroutines because maps aren't thread safe.

Better solution:

func Crawl(url string, depth int, fetcher Fetcher) {
    m := map[string]bool{url: true}
    var mx sync.Mutex
    var wg sync.WaitGroup
    var c2 func(string, int)
    c2 = func(url string, depth int) {
        defer wg.Done()
        if depth <= 0 {
            return
        }
        body, urls, err := fetcher.Fetch(url)
        if err != nil {
            fmt.Println(err)
            return
        }
        fmt.Printf("found: %s %q\n", url, body)
        mx.Lock()
        for _, u := range urls {
            if !m[u] {
                m[u] = true
                wg.Add(1)
                go c2(u, depth-1)
            }
        }
        mx.Unlock()
    }
    wg.Add(1)
    c2(url, depth)
    wg.Wait()
}

Useful link:

https://stackoverflow.com/questions/12224962/exercise-web-crawler-concurrency-not-working


You could change count = count + 1 to count += 1 besides that, do you need to repeat messageBox = ctypes.windll.user32.MessageBoxA so much? If it doesn't change, couldn't you just have it once? You could also add variables to shorten repeated lines like making a variable called resetMsgBox and have it be: resetMsgBox = ctypes.windll.user32.MessageBoxA so it's easier to read by having messageBox = resetMsgBox every line instead, I suppose.


Ok, there are a couple of things wrong with your code and your method of organizing the code. I've pointed them out to you in the code below within comments. The comments preceded with # are my comments.

<?php

/* Mysql data */
$MysqlUsername = "root";
$MysqlPassword = "**********";
$MysqlHostname = "localhost";
$MysqlDatabase = "teamgamersnet";

$Username = $_POST['Username'];
$Password = $_POST['Password'];
$Email    = $_POST['Email'];

# Check for empty variables
if (empty($Username) || empty($Password) || empty($Email)) { die("Please fill in all the fields"); }

# We're only using $IP once, so why set it above? Let's do a direct comparison here
// Beta, Restrict users from using it until it's done
#OLD::
#if ($IP != "84.***.***.***") { die(); }

#NEW::
if ($_SERVER['REMOTE_ADDR'] != "84.***.***.**") { die(); }

/* Random Activate code generator */
function GenerateCode() {
    # You're setting 7 variables with like variables, and returning them
    #OLD::
    #$R1 = rand(1,9);
    #$R2 = rand(1,9);
    #$R3 = rand(1,9);
    #$R4 = rand(1,9);
    #$R5 = rand(1,9);
    #$R6 = rand(1,9);
    #$C1 = "$R1$R2$R3$R4$R5$R6";
    #return $C1;

    #NEW::
    return rand(1,9) . rand(1,9) . rand(1,9) . rand(1,9) . rand(1,9) . rand(1,9);
}

/* Encrypt the password */
function Encrypt($Pass) {
    # Again, setting multiple variables in the name of readability over performance
    #OLD::
    #$B64 = base64_encode($Pass);
    #$MD5 = md5($B64);
    #$Hash = base64_encode($MD5);
    #return $Hash;

    #NEW::
    return base64_encode( md5( base64_encode($Pass) ) );
}

# Let's move the Mysql Connection Data to the top, so its easier to modify in the future
#OLD::
/* Mysql data */
#$MysqlUsername = "root";
#$MysqlPassword = "**********";
#$MysqlHostname = "localhost";
#$MysqlDatabase = "teamgamersnet";

#NEW::
# Moved to top

$Sql = new mysqli($MysqlHostname, $MysqlUsername, $MysqlPassword, $MysqlDatabase);
if ($Sql->connect_error){ echo $Sql->connect_error; }

/* Let's add a comment here: Escape the user data */
$sUser = $Sql->real_escape_string($Username);
$sPass = $Sql->real_escape_string($Password);
$sMail = $Sql->real_escape_string($Email);
$xPass = $Sql->real_escape_string(Encrypt($Password));

# Let's move this to the top, right after these are set from _POST, to avoid all the
# prior computation before running into this. Also, use empty() or isset() instead of ! checking
# See: http://www.phpbench.com/
#OLD::
#if (!$Username | !$Password | $Email) { die("Please fill in all the fields"); }

#NEW::
# Moved to top, also - syntax errors fixed: it's || not |

/* Let's add a comment here: Check if the user exists */
$CheckUser = $Sql->query("SELECT Username FROM `users` WHERE `Username` = '".$sUser."'");
$CheckMail = $Sql->query("SELECT `E-Mail` FROM `users` WHERE `E-Mail` = '".$sMail."'");
if ($CheckUser->num_rows == 1) { die("Username allready exist"); }
if ($CheckMail->num_rows == 1) { die("E-Mail allready exist"); }

/* Let's add a comment here: Generate an activation code */
$xCode = GenerateCode();

/* Let's add a comment here: Write out the Insert statement  */
$Insert = "INSERT INTO `teamgamersnet`.`users` (`ID`, `Username`, `Password`, `E-Mail`, `IP`, `Activated`, `ActivateId`)
VALUES (NULL, '".$sUser."', '".$xPass."', '".$sMail."', '".$IP."', 'false', '".$xCode."');";

/* Let's add a comment here: Insert the SQL statement */
$Create = $Sql->query($Insert);
# Why are we echoing? Shouldn't we be dying?
#OLD::
#if (!$Create) { echo "S**t, a error happened D:";}

#NEW::
if ( empty($Create) || !isset($Create) ) { die("Sorry, an error occurred during Create."); }

/* Let's add a comment here: Build the message, and send it to the user. */
$to = $Email;
$subject = 'User account activation | Team Gamers Net';
$message = '

Thank you for registering at Team Gamers Net

Just one more step and that is to activate your account

You registred with username '.$Username.'

And your password you selected (not shown)

To activate and contiune, please click HERE

';
$headers = "From: DoNotReply@TeamGamers.Net \r\n";
$headers .= "Reply-To: Admin@heisteknikk.com \r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
mail($to, $subject, $message, $headers);

header("Location: /?register=true");
?>

Here's the same code, with my comments removed:

<?php

/* Mysql connection data */
$MysqlUsername = "root";
$MysqlPassword = "**********";
$MysqlHostname = "localhost";
$MysqlDatabase = "teamgamersnet";

$Username = $_POST['Username'];
$Password = $_POST['Password'];
$Email    = $_POST['Email'];

/* Check for empty variables */
if (empty($Username) || empty($Password) || empty($Email)) { die("Please fill in all the fields"); }

/* Beta, Restrict users from using it until it's done */
if ($_SERVER['REMOTE_ADDR'] != "84.***.***.**") { die(); }

/* Random Activate code generator */
function GenerateCode() {
    return rand(1,9) . rand(1,9) . rand(1,9) . rand(1,9) . rand(1,9) . rand(1,9);
}

/* Encrypt the password */
function Encrypt($Pass) { return base64_encode( md5( base64_encode($Pass) ) ); }

$Sql = new mysqli($MysqlHostname, $MysqlUsername, $MysqlPassword, $MysqlDatabase);
if ($Sql->connect_error){ echo $Sql->connect_error; }

/* Escape the user data */
$sUser = $Sql->real_escape_string($Username);
$sPass = $Sql->real_escape_string($Password);
$sMail = $Sql->real_escape_string($Email);
$xPass = $Sql->real_escape_string(Encrypt($Password));

/* Check if the user exists */
$CheckUser = $Sql->query("SELECT Username FROM `users` WHERE `Username` = '".$sUser."'");
$CheckMail = $Sql->query("SELECT `E-Mail` FROM `users` WHERE `E-Mail` = '".$sMail."'");
if ($CheckUser->num_rows == 1) { die("Username allready exist"); }
if ($CheckMail->num_rows == 1) { die("E-Mail allready exist"); }

/* Generate an activation code */
$xCode = GenerateCode();

/* Write out the Insert statement  */
$Insert = "INSERT INTO `teamgamersnet`.`users` (`ID`, `Username`, `Password`, `E-Mail`, `IP`, `Activated`, `ActivateId`)
VALUES (NULL, '".$sUser."', '".$xPass."', '".$sMail."', '".$IP."', 'false', '".$xCode."');";

/* Insert the SQL statement */
$Create = $Sql->query($Insert);

/* Check if SQL insert went well, otherwise die */
if ( empty($Create) || !isset($Create) ) { die("Sorry, an error occurred during Create."); }

/* Build the message, and send it to the user. */
$to = $Email;
$subject = 'User account activation | Team Gamers Net';
$message = '

Thank you for registering at Team Gamers Net

Just one more step and that is to activate your account

You registred with username '.$Username.'

And your password you selected (not shown)

To activate and contiune, please click HERE

';
$headers = "From: DoNotReply@TeamGamers.Net \r\n";
$headers .= "Reply-To: Admin@heisteknikk.com \r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
mail($to, $subject, $message, $headers);

header("Location: /?register=true");
?>


Use enumerate rather than range(len(...)) + __getitem__. It is both faster and more readable.
To limit items of the second iteration to be "after the current item" you can use itertools.combinations.
To avoid the need to check for the special case of "is the item already in the dictionary?", use a collections.defaultdict.
You could use a set rather than a list to store the final results and remove yourself the need to check for duplicates
-key + target is better written as target - key

import itertools
from collections import defaultdict

def four_sum(array, target):
    seen = defaultdict(set)
    for (i, first), (j, second) in itertools.combinations(enumerate(array), 2):
        seen[first + second].add((i, j))

    result = set()
    for key, first_indices in seen.items():
        second_indices = seen.get(target - key, set())
        for p, q in second_indices:
            for i, j in first_indices:
                # Not reusing the same number twice
                if not ({i, j} & {p, q}):
                    indices = tuple(sorted(array[x] for x in (i, j, p, q)))
                    result.add(indices)
    return result


Create a new object that excludes specified keys

From a short review;

Naming

standardizeFilter is too specific/specialized, perhaps standardizeObject?
queryParams also seems a very specific name, whereas the functionality is very general, I would just call it keys
inputType is not a type, it's an object, I would propose source

For each key you perform both a indexOf and a [] access, you can drop the indexOf

I would propose something like this:

function standardizeObject(source, keys){

  const o = {};

  for(const key of keys){
    const value = source[key];
    if(value !== undefined){
      o[key] =  this.parseValues(value);
    }
  }

  return o;
}


Nested if-else within a for-loop using np.concatenate to create batches for a neural network

Your code is coupling independent ideas, this is making your code at least twice as long as you need it to be, as you have to duplicate your if statements.
And so I refactored your code in the following way:

Move x.append(np.concatenate(...)) out of the if statements. This is as you're needlessly duplicating this across them all.
Make the array passed to (1) outside the ifs, this is as you always add token_hidden and token_hidden_generator.
Replace once. generated_lemma = generated_lemma.replace('#', '|') and you don't have to call replace again.
Move all the generated_lemma code into a single if-else. Leading to:

generated_lemma = generated_lemma.replace('#', '|')
if generated_lemma in self.lemmas_word2vec_model:
    gen_lemma = self.lemmas_word2vec_model[generated_lemma]
else:
    gen_lemma = self.embedding_unknown_lemma

Cleanup the rest of the ifs.

This got me:

for generated_lemma, classified_lemma, token_hidden, token_hidden_generator in zip(
    tokens_generated,
    tokens_classified,
    token_dnn_output,
    token_generator_output
):
    generated_lemma = generated_lemma.replace('#', '|')
    if generated_lemma in self.lemmas_word2vec_model:
        gen_lemma = self.lemmas_word2vec_model[generated_lemma]
    else:
        gen_lemma = self.embedding_unknown_lemma

    classified_lemma = classified_lemma.replace('#', '|')
    if classified_lemma in self.lemmas_word2vec_model:
        class_lemma = self.lemmas_word2vec_model[classified_lemma]
    elif classified_lemma == '<UNK>':
        class_lemma = self.embedding_unknown_token
    else:
        class_lemma = self.embedding_unknown_lemma

    x.append(np.concatenate([
        gen_lemma,
        class_lemma,
        token_hidden,
        token_hidden_generator
    ]))

This may be faster, due to (3), however, I doubt it'd have any serious speed-ups. I don't really know any of the data types, and so can't comment on whether you need np.concatenate, or a faster way to add to x.


IEnumerable<Registration> all = All(); // <-- this gets all registrations from
                                       //       the database.

This looks like a really bad idea. Why are you getting all data from the database first and not filter it before retrieving?

where r.FirstName.ToLower().StartsWith(voornaam.ToLower().Trim())

Most databases are case insensitive so you wouldn't need this formatting adjustment if you used server side filtering.

On the client it's better to use the StrigComparer.XIgnoreCase where the X is either the InvariantCulture or Ordinal then ToUpper/Lower because on the one hand it better communicates the intention that you are performing a case-insensitive comparison (which is not that obvious if you use ToUpper/Lower - you might be just fixing the case for whatever reason) and on the other hand you don't have to change the case twice which might introduce a new bug if you call ToUpper for the first string and ToLower for the other one or forget it altogether.

If you use EF or any other ORM you should filter the data on the server and not after downloading everything. With large databases this would be such a waste of resources.

If All is backed by Entity Framework then you could return an IQueryable and still take the advantange of a server query.

Why don't you use english variables names? Everything is in english but the parameters. This is not consistant... and it's difficult to get help with local names.


Shift an element in a circular container

Don't get me wrong. The function currently is almost useless, since you are rotating only circular_container. People would like to rotate any container on pair of iterators, as mentioned by @Jerry. But lets put those things aside, and have a look at your code.

Code Review

std::vector<SomeType> circular_container;

Global variable, very bad. Here's why. You could at least write template variable (don't do that!).

void shift(int i, const int j)

OK lets imagine for a minute that someone really filled the global variable and wants to rotate now. But then that someone gets upset, because apparently int is not large enough to hold the index he/she wants to rotate. Always use at least std::size_t defined in <cstddef>, or better use std::vector<SomeType>::size_type. This guarantees you that the type will be large enough to hold the biggest possible index.

if (circular_container.size() < 2) {
    return;
}

You are creating a branch that should be taken care of by the loop (it actually does, I believe). If the size of the container is 1, caller should provide equal i and j (you are not performing range check anyway). If the size of the container is zero, caller shouldn't even call your function at all! So the above if is redundant.

Conclusion:

It does the needed job. Sometimes. In a very clumsy way. I would arguably say that this is better than nothing, but there is a huge room for improvement.

Suggestions on better implementation:

As @Jerry noted, you should create iterator that performs the logic of your next() function. Probably you'll want to provide one version for forward, another for bidirectional, and the last one for random access iterators. The only thing you need to do is to move the logic from next() to the operator++(), for example.

I would also like to have a function that returns me circular iterator range taking pair of begin and end iterators, so that I could pass it into the function which does similar things to your shift function, and then specify by how much I want to shift, like the count of shifts to the right. You can also provide bool parameter that specifies the direction, if iterator supports it. Also, you could harness the power of random access iterators to make count shifts at once, rather than calling the shift in the loop.


Variadic templated method to extract values from a table

Yes, it is a good example

Variadic templates are associated with recursion by similarity to functional programming, where an recursion is a simple method of operating on sequences. Direct expansion is akin to a map or fold, or some other higher-order function.

It can be simplified even more

If you have a similar function

/* find value or return default */
template <typename Arg>
V value_at(Arg const & key) const
{
    auto const it = gate.find(key);
    if (it != gate.end()) {
        return it->second;
    }
    return {};
}

Then you can condense this down into a single expression

return vector<V>({value_at(args)...});

as that expands the parameter pack into multiple calls to value_at, which goes into vector's std::initializer_list<V> constructor.


There may be a more fundamental problem here beyond converting a string to enum.

By adding a fromString(String) into the enum and defining the format specific strings in the enum constructor, you are coupling the enum tightly to the data format and making it an integral part of the input parser. Your enum now has two responsibilities, being clearly in violation of the single responsibility principle

Instead you should implement a format specific converter that converts the string used in transport to the enum used in computing and make the enum as bare as possible.


Construct binary tree from inorder and postorder traversal

Before tackling the algorithmic issues of your code, lets start with a review of your coding style.

Use proper spacing and indentation

When reviewing, or coming back to code, the readability of the code is very valuable in order to understand the code and to correctly change it. Two very important aspects of this readability is how you indent your code and where you your new lines.

Lets review the start of your code:

public class Solution {
public class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int x) { val = x; }
}
public TreeNode buildTree(int[] inorder, int[] postorder) {
    if(inorder==null || inorder.length<1)return null;
    int rootVal=postorder[postorder.length-1];
    TreeNode root= new TreeNode(rootVal);

    int mid=0;
    for(int i=0;i<inorder.length;i++){
        if(inorder[i]==rootVal){
            mid=i;
            i=inorder.length;
        }
        ...
}
}

I have the following issue with this segment of code:

The classes Solution and TreeNode are at same indentation – This indicates that this classes are defined side by side, which is not unnatural, but then the Solution class seems to miss its implementation. So given they are not defined side-by-side it seems like a compilation error, until you scan a lot more code and realizes that TreeNode is actually an internal class of Solution.
TreeNode seems to only have 4 members – The way it is written it seems like it has 4 members, and no constructor or methods. Yet again closer inspection reveals that the last parameter isn't a parameter, but actually a constructor with single inline code block.
The buildTree appears at same level as class definitions – This kind of seems like you have a third class, next to Solution and TreeNode, but it misses the class keyword and has parameters? Oh shoot, it's a method belonging to TreeNode? No, it belongs to Solution but returns a TreeNode.
Confusing start of buildTree – Ordinarily a method starts with some declaration of local variables, but your first variable is an if statement hiding an early return. This block uses neither braces nor newlines to indicate this block, and is disguised if you don't have a trained eye.
Inline statements are too compressed – Adding spaces around operators, and after commas can open up your statements a lot. Compare for(int i=0;i<inorder.length;i++){ to for (int i = 0; i < inorder.length; i++) {. Try to think of the statements as sentences where the different parts are words. ItIsNotVeryEasyToReadWithoutSpaces!

Correcting for all of the above you'll end up with this code:

public class Solution {

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }
    }

    public TreeNode buildTree(int[] inorder, int[] postorder) {
        if (inorder == null || inorder.length < 1) {
            return null;
        }

        int rootVal = postorder[postorder.length - 1];
        TreeNode root = new TreeNode(rootVal);
        int mid=0;

        for(int i = 0; i < inorder.length; i++){
            if (inorder[i] == rootVal) {
                mid = i;
                i = inorder.length;
            }
        }
        ...
    }
}

This still has some issues, like it doesn't actually check if postorder is not null or has values. But it shows the increase of readability where the only change I've made is to add spaces, correct indentation and add one set of braces.

Algorithmic considerations

In the text of your question you state that Java would pass the entire array by value, which is not correct. If you read Is Java “pass-by-reference” or “pass-by-value”?, you'll see that when passing arrays it's actually the value of the reference to the array which is passed. This allows for the array to be internally dereferenced (and possibly have the array values changed) within the method it is passed to. (It also allows for you to overwrite the array internally, without affecting the external array, but that is another history. Read the accepted answer to the link carefully, and you'll see the difference)

In other words, your suggestion of passing indices will be a much better solution, than the current one. The current one creates loads of extra arrays which it shuffles around making the space requirement of your code grow exponentially (doubling for each recursion). If you passed indices, you would only require space for the extra tree nodes.

So I would rewrite the buildTree into two separate functions something like:

public TreeNode buildTree(int[] inorder, int[] postorder) {
    return buildTree(inorder, postorder, 0, inorder.length);
}

private TreeNode buildTree(int[] inorder, int[] postorder, int left, int right) {
    ... your revised code here ...
}

I would also strongly consider adding some documentation and comments here and there to further enhance and explain what your code is supposed to do!


It's not necessary to name your methods as below. Someone may reference to it further.

Form.prototype.submit = function submit(data) {
...
}

You can just simply define it as follows

Form.prototype.submit = function (data) {
...
}

ES6 style ;)

Form.prototype.submit = (data) => {
...
}

Form.prototype.init looks as moot method. This is exact what constructor has to do.

I take into account that you are developing a plugin so you're going to reuse it. Right? Thus your CSS classes such as "error", "info", etc. have to be configurable as well as other stuff. Or at least add unique prefix to it.


Best way to construct a semantic HTML table?

I can't fault your tags at all. The only problem is that due to your table being quite complex, assistive technology may not be able to figure out the structure of your table.

I was going to recommend using scope but according to W3C there are some inconsistency issues.

  The row and col values of the scope attribute are currently supported
  to a large extent by most current versions of JAWS. However, there are
  still some problems and WindowEyes support for scope is inconsistent.
  The same is true for Japanese versions of these screen readers.
  Versions of JAWS prior to version 5 and older versions of Window-Eyes
  have inconsistent support for scope.

Using scope would look like this, with scope="col" in all  elements in the first row and scope="row" for all other  elements.

            th 1
            th 2
            th 3
            th 4

            th 5
            th 6
            th 7
            td 1
            td 2
            td 3

            td 4
            td 5
            td 6

            th 8
            td 7
            td 8
            td 9

            td 10
            td 11
            td 12

            th 9
            th 10
            td 13
            td 14
            td 15

            td 16
            td 17
            td 18

            th 11
            td 19
            td 20
            td 21

            td 22
            td 23
            td 24

JSFiddle for scope method

This is W3C's recommendation:

  At the current time, those who want to ensure consistent support
  across Assistive Technologies for tables where the headers are not in
  the first row/column may want to use the technique for complex tables
  H43: Using id and headers attributes to associate data cells with
  header cells in data tables. For simple tables that have headers in
  the first column or row we recommend the use of the th and td
  elements.

Let me just start off by saying this is a complete pain in order to be completely accessibly and scope will probably be fine in most cases. Here is the table using the id/header method (shudder):

            th 1
            th 2
            th 3
            th 4

            th 5
            th 6
            th 7
            td 1
            td 2
            td 3

            td 4
            td 5
            td 6

            th 8
            td 7
            td 8
            td 9

            td 10
            td 11
            td 12

            th 9
            th 10
            td 13
            td 14
            td 15

            td 16
            td 17
            td 18

            th 11
            td 19
            td 20
            td 21

            td 22
            td 23
            td 24

JSFiddle for id/headers

What is comes down to in the end in my opinion is an accessible solution that is also maintainable in the back end. Realistically JAWS and WindowEyes will eventually fix up their bugs and using scope will be fine even for tables as complex as this. Unless you expect many users to use assistive technologies and require strict adherence to WCAG, go with scope. Markup needs to be beautiful too :)

There is also the <colgroup> element which is relevant but support for it isn't great currently.


Exception handling with null check in java

Your business logic is getting muddled with your error-checking logic. I would recommend extracting your "null-to-Exception" conversions into different methods, so they don't appear here.

Ideally, PEParser.parse() and PE.getSignature() would not return null values, and would instead throw an exception directly if they encountered an issue. If you have the option to change these methods, I would do so. Otherwise, I would recommend wrapping them in methods that will convert null return values to exceptions, like so:

PE GetPEFromPath(String path)
{
    PE pe = PEParser.parse(path);
    if (pe == null)
    {
        throw new IOException();
    }
    return pe;
}

PESignature GetSignatureFromPE(PE pe)
{
    PESignature ps = pe.getSignature();
    if (ps == null || !ps.isValid())
    {
        throw new IOException();
    }
    return ps;
}

These methods should return a valid object, or throw an exception - no other options. This way, we can write our business logic in a try block with no null-check interruptions, and if something fails, we will move gracefully to the catch block.

Now, we can transform your given code snippet into something more readable:

//not an elf file. try PE parser
try
{
    PE pe = GetPEFromPath(path);
    PESignature ps = GetSignatureFromPE(pe);
}
catch (IOException e)
{
    Toast.makeText(this, "The file seems that it is neither an Elf file or PE file!", 3).show();
    throw e;
}


Stopwatch class without using System.Diagnostics in C#

public static void RunProgram()
{
   ....
}

Why do you run the application as a method on the Stopwatch class it self?

You have made all the methods (StartTimer(), StopTimer()) private. This means that they only can be run from your RunProgram method, which occupy the main thread of the program and measures nothing. This set up makes the entire effort rather useless. I would expect a stopwatch being able to measure something in a way like:

  Stopwatch stopwatch = Stopwatch.StartNew();

  // TODO: execute something you want to measure
  Thread.Sleep(5000);

  stopwatch.Stop();

  Console.WriteLine($"Duration: {stopwatch.Duration}");

    private static bool isStarted = false;
    private static bool isStopped = false;

These flags can be combined into one isRunning, used like:

    private static void StartTimer(DateTime start)
    {
        if (isRunning)
        {
            throw new InvalidOperationException("Unable to start a stopwatch twice in a row.");
        }
        else
        {
            isRunning = true;
            TimeStart = start;
        }
    }

and

    private static void StopTimer(DateTime stop)
    {
        if (!isRunning)
        {
            throw new InvalidOperationException("Unable to stop the stopwatch because it is not running.");
        }
        else
        {
            isRunning = false;
            TimeStop = stop;
        }
    }

    private static void Begin()
    {
        StartTimer(DateTime.Now);
        System.Console.WriteLine(" - Stopwatch has begun.");
    }

You shouldn't write to the console in class methods of any object, unless it's explicitly meant to be a console application. The above message is useless in a WinForm application.

  private static void StartTimer(DateTime start)

I don't se why you have a start time as argument to StartTimer. Why not just call DateTime.Now inside it? And likewise in StopTimer.

You were told to provide the result as a TimeSpan, but you actually return a string:

  private static string ElapsedTimer() => (TimeStop - TimeStart).ToString();

  public static class Stopwatch

The major problem with your implementation is though, that you make it static. That means that you only can run one "instance" at a time. In this way you aren't able to measure on two treads at the same time - or have nested measurements.

I would remove all the static stuff and only have one static method - starting a new Stopwatch instance, that then can be stopped by calling Stop() on the returned object like I showed above. So the public interface of the object would be:

  public class Stopwatch
  {
    public TimeSpan Duration { get; }

    public void Start() { }
    public void Stop() { }
    public static Stopwatch StartNew() { }
  }

I think you have misunderstood the concepts of "encapsulation and information hiding" slightly. An object must have a public interface through which clients can communicate with it, but they shouldn't be allowed to manipulate the objects internal state (for instance the StartTime member of your watch) - only through the public interface. The client shouldn't know about how you measure the time internally, they are only interested in the final result, when they stop the watch by calling Stop().


Concurrency Strategy

In general, using volatile is complicated, partially because the meaning of volatile changed in Java 1.4, and also because it is hard to spot. I recommend against using it at all. Instead, you should use a more visible concurrency mechanism like synchronization, java.util.concurrent.* classes, java.util.concurrent.locks.*, or java.util.concurrent.atomics.*

So, while I recommend against volatile, what's a real problem is using multiple different locking schemes in the same code, and you use both volatile and synchronized.

The use of synchronization as your concurrency strategy should be fine all on its own in this case.

General

The private final Object lock = new Object() is great. Good to be final, and I prefer that to locking on the instance itself (like synchronized(this)). Makes it more clear.
Println in a synchronized block is almost never a good idea:

synchronized(lock) {
  System.out.println("Received ack Event: " + state);
  state = State.READY;
}

A better solution would be:

State copy = null;
synchronized(lock) {
  copy = state;
  state = State.READY;
}
System.out.println("Received ack Event: " + copy);

Timed sleeps while waiting for a lock are a horrible solution:

Thread.sleep(1);

Better algorithm

The right way to solve this problem, though is to used timed-waits on the lock:

private void handleAck(Event event) {
    State copy = null;
    synchronized(lock) {
      copy = state;
      state = State.READY;
      // tell any waiting threads the state has changed.
      lock.notifyAll();
    }
    System.out.println("Received ack Event: " + copy);
}

/* THIS IS THE IMPORTANT BIT */
private void ensureAck() {
  // how long to wait... 10 milliseconds
  try {
      synchronized(lock) {
          if (state == State.NEW) {
              long waited = 0; // milliseconds
              long start = System.currentTimeMillis();
              while (state == State.NEW && waited < 10) {
                  lock.wait(10 - waited);
                  waited = System.currentTimeMillis() - start;
              }
          }
      }
  } catch (InterruptedException e) {
      // do more than nothing.....
  }
}

The above strategy does not need anything to be volatile, and it does not 'poll' the state, it returns immediately when the state changes....


Endless stream: stream a range and return default value if the range is exhausted

Design

Iterator categories: You try to make sure to support InputIterator, but then expose current_position(). Since callers of that function can do anything with the returned iterator, including dereferencing and/or advancing it, for pure InputIterators this can invalidate first.
To support this, you'd need at least ForwardIterators, since they have to provide a multipass guarantee. As a side effect, it would fix the std::vector<bool> issue, since its iterator isn't complying to one of the ForwardIterator requirements: reference must be equal to value_type& or const value_type&.

Note: Just removing current_position wouldn't fix this, you'd also need to disable copying (same issue).

endless_stream interface: This is neither a range (doesn't contain begin() and end() member functions) nor an iterator. Instead, it looks like some range-like construct (maybe inspired from other languages?). As mentioned, this doesn't fit in well with usual standard library constructs.
Is there any specific reason this implementation doesn't orient itself on usual iterator semantics?

Is there any specific reason for allowing output operations, i.e. allowing modification of default_value? I'd think it wouldn't be too much of a restriction to only return const ValueType& from next (basically adhering to const_iterator semantics).

Implementation

Most member functions can be made conditionally noexcept.

Some names are off:

has_next: I'd expect that one to always return true for an infinte range. From the implementation, I guess something like end_reached or fully_traversed was meant.

end suggests there should be an begin, which there isn't (usually expected iterator semantics). I'd suggest renaming to end_iterator (or maybe last_iterator), or removing this function entirely.

current_position: The position irks me a bit, as an iterator doesn't always conceptually represent a position (e.g. in a generator). current_iterator might be better.

endless_stream isn't a stream as it would usually be understood in C++. Maybe it could be reworked into an infinite_filler_range (when matching the range criteria)?

There is no way to get the same value multiple times (since next always advances first, if possible). I'd suggest splitting this operation into two parts: advance() and value() (or current_value()).

member initializer list: The general advice is to prefer aggregate initialization (using {}) over direct initialization (using ()), unless the latter is absolutely required. So, first and last can and should use aggregate initialization, and default_value can go either way (though I prefer direct initialization in this case).

Usage example
I don't think an implementation detail like endless_stream should leak into the interface. Instead, it might be better to create those endless_stream instances inside of add_digit_lists, taking either iterators or const std::list<int>& as parameters.
Also, the output is in normal order, whereas the inputs are reversed. This might not be intended.


You can't really call a difference of 1% slower or faster. You should consider that both codes have exactly the same performance.

The only explanation for a speed difference between those two applications comes from the malloc (which is slightly slower than an array).

IMO, first code is better than second; the second one is quite hard to get (you are basically reversing a string, then comparing the reversed string with the normal one). I actually had to read the code 3 times to understand what was done.

About code review in itself:

First code sample:

You should indent your code in a consistent manner.

int c,flag = 0;
char *ch, *h;

Those variables are poorly named; flag could be replaced by is_palindromic, h could be string_start/str_start/str, and ch string_from_end/string_reverse etc....

while((c=getchar())!=EOF){

It's usually a good idea to separate comparators and equal sign from their operands, so it'd be something like this:

while((c = getchar()) != EOF){

Second code sample:

char a[100],b[1000];
int n,i,j=0,f=0;

Same as before, you should also avoid declaring 4 variables on the same line (especially considering you have both initialized and non-initialized variables).


Standard C requires that main() return int:

int main(void)

There's no need (for 20 years now) to write all local declarations before the code.  Introduce variables as you need them, so they can be initialised immediately:

{
    char line[MAXLEN];

    int i = 0;

There's no need for the extra storage rev in reverse().  We can reverse the string in place, by swapping first and last characters, then the second and second-last, and so on.

Use the Standard Library - it provides functions such as scanf(), getline(), strcpy() and strlen().  Don't write your own code to do these things - it makes your code much less clear, and causes readers to wonder what's being done that's different to the standard.


Creating a searchable collection of rooms

There are some issues here:

  auto room = rooms.GetRoom(0);

Here you do copy the Room because auto does not imitate the 'reference part'. To bind a reference to the internal map entry, you need to both return by reference and assign to a reference type. Based on your gist, I assume you would think that if you then call room.OnEnter, the Room is also updated in the RoomList. This is not the case, because it is a copy. Therefore you would want to use:

  auto& room = rooms.GetRoom(0);

instead. But for that to work, RoomList::GetRoom should return a non-const reference, so that you can actually modify it. In turn there should also be a const RoomList::GetRoom that also returns a const reference.

However, there should also be a non-const RoomList::GetRoom that returns a non-const reference, so that you can actually call non-const methods on the returned rooms.

To avoid running into that issue - you might want to delete the copy constructors and assignment operators of Room. If you further wanted to enforce that all Room objects are owned only by RoomList you could even make the Room constructor private and friend RoomList.

  I'm not initializing the m_rooms map - will it be default initialized to live as long as the rooms variable in main.cpp is in scope?

Yes

  I have a map of Rooms, but I want to return Room references. Will returning a Room have any negative side effects? (e.g., is there some automatic creation of a wrapper object or even a copy of Room going on?)

Not for std::map. You can delete the copy constructor and assignment operator or Room, that will ensure you make no copies somewhere else in the code also.

See https://stackoverflow.com/a/6442829/620382 for a listing of iterator/reference invalidations in standard containers.

  Is result->second even still valid after a return? result is a local variable that should die when the function ends, but I'm returning what second points to, so that should be good?

Yes. result points to the internal value_type of the map.

  Would I need to implement ~RoomList to make sure all the Rooms are freed? Or does std::map::emplace own the constructed Room?

RoomList::m_rooms own the constructed Rooms. More technically speaking:

m_rooms.emplace(0, Room(0, "Start Room"));

Here a temporary Room object is created, which is then moved into the std::pair<int, Room> that is construed inside of the map. In C++14 you can use std::piecewise_construct to even skip the temporary Room object. But as long as you have a move constructor, which you have by default, you are fine.

  If I wanted to return something by value, how would I need to allocate it? For example, imagine I've added this to Room, wouldn't I return a stack-allocated variable?

If you do not declare the return value to be a reference (which you do not in your example), then it is returned by copy. But the C++ rules and compilers are good so that you will either get a move (cheaper than actual copy) or even omitting it alltogether when possible.

  // Considering Optional

If you document it properly, it would be actually fine to return a raw pointer here, with nullptr meaning that it is not available. The raw pointer (similar to the raw reference) does not imply ownership. You just need to make sure the caller does never reference it without checking. optional (also available in boost and soon in the standard).

The funny thing about your code is, that you have randomly written proper and safe code. IMHO this is a nice property especially about modern C++. There is actually no explicit resource allocation (like new) in your code - when you allocate resources implicitly, through member variables, C++ will behave nicely by default and also implicitly release the resources.

  std::string m_name; // should this be const?
  int m_id; // should this be const?

Yes, it would be a good idea to make those const.

const int& GetEnterCount() const { return m_enterCount; };

I would consider it a uncommon to return an int by const reference here (as opposed to a simple copy). I don't have a strong argument for or against, but lets just take note that std::vector::size doesn't return an const int& either.

  RoomList& operator=(RoomList const&) = delete;

You should put the const before RoomList for consistency.
You also might want to explicitly default or delete the move constructor and assignment operators. I would say neither would hurt.

In Room, you list m_id and m_name in a different order in the initializer list. This can lead to confusion because the initialization order follows the order from member declaration (m_name then m_id). Therefore this is a compiler warning.

So the tip is, compile with maximal warnings, e.g. -Wall -pedantic for gcc. Also it can be helpful to run your code with valgrind to check for any leaks.


Using readonly field instead of private setters in struct

Thought I'd chime in:

You've stated that this should be an immutable struct. With that in mind, the solution you want is the one with the backed readonly fields.

I feel explicitly stating intent in code is good. You say that you want immutability, then write the code so.

If you were to opt for the property only solution then consider what would happen if some other developer came along and misunderstood your original intent (because this time it wasn't fully explicit)

With the properties you are stating - The public consumers of my struct may not mutate it but the struct itself can.

With the readonly fields you are stating - The public consumers of my struct may not mutate it and neither may the struct itself.

The latter is correct in regards to your spec.

To briefly summarise:

"Does it make a difference?" Yes, your intent is different between the two. Yes, one allows mutation after the point of declaration, one does not.

"In case it does, which one is preferrable, regarding immutability (and also other characteristics)?"
For immutability, the readonly option.


I don't know if this is more idiomatic, but ever since I've seen an infinite list construction for the Fibonacci numbers, I've been in love with it, so here goes nothing.

pascalTriangle :: [[Integer]]
pascalTriangle = [1] : map newRow pascalTriangle
    where newRow y = 1 : zipWith (+) y (tail y) ++ [1]

To understand this, perhaps first you should look at simpler examples, e.g. an infinite list of zeros,

zeros = 0 : zeros

or the list of natural numbers,

nats = 0 : map (+1) nats

or my favourite, the list of fibonacci numbers,

fibs = 1 : 1 : zipWith (+) fibs (tail fibs)

That being said...

The line

pascalList 1 = [[1], [1, 1]]

is unnecessary, because you've already specified pascalList 0. The line

[([1] ++ pascalCoeff (last pList) ++ [1])]

is equivalent to

[[1] ++ pascalCoeff (last pList) ++ [1]]

which is equivalent to

[ 1 : pascalCoeff (last pList) ++ [1]]

Whenever possible, I try to use functions from the standard library instead of rolling my own using recursion, so for example instead of

pascalCoeff (x:y:ys) = (x+y) : pascalCoeff (y:ys)
pascalCoeff (x:[]) = []

I'd say that this function takes a list e.g. [1,2,3,4] and does the following:

  [1, 2, 3]
  [2, 3, 4]
+ ---------
  [3, 5, 7]

so it takes the tail (all but the first element) of the list, and the init (all but the last element) of the list, and adds them together element-wise.

There are built-in functions tail, and init that yield you these parts from a list, and luckily the function

zipWith (+)

does the adding part, so you can simply say

pascalCoeff y = zipWith (+) (init y) (tail y)

which is, due to the way zipWith works, the same as

pascalCoeff y = zipWith (+) y (tail y)

Similarly,

listtoString [] = []
listtoString [x] = show x
listtoString (x:xs) = show x ++ " " ++ listtoString xs

could simply be

listToString = unwords . map show

And

justify :: Int -> [String] -> [String]
justify n (x:xs) = (concat (replicate n " ") ++ x) : justify (n-1) xs
justify _ [] = []

could be

justify n ss = zipWith (++) padding ss
    where padding = [ replicate k ' ' | k <- [n, n-1 .. 1]]

or equivalently, after eta-reduction

justify n = zipWith (++) padding
    where padding = [ replicate k ' ' | k <- [n, n-1 .. 1]]

Due to the fact that lists are linked lists, appending to a list is expensive, while prepending to it is cheap. So if you do decide to construct a list element-by-element, then I'd say you should prepend the new elements, and perhaps after the list is built, use a reverse.

By the same logic, head is cheap, last is expensive.

Here's a possible implementation that uses what I've just said.

pascalList = reverse . pascalList'
pascalList' 0 = [[1]]
pascalList' n = new : old
    where new = 1 : pascalCoeff (head old) ++ [1]
          old = pascalList' (n-1)

In my opinion it is a good idea to

separate pure and impure code,
keep your code as modular as possible,
write type signatures,
use a linter like hlint,
use functions from the standard library instead of writing explicit recursions.

Keeping this in mind, here's how I'd write the printing part.

listToString :: (Show a) => [a] -> String
listToString = unwords . map show

leftPadStrings :: [String] -> [String]
leftPadStrings ss = map leftPad ss
    where maxlen = maximum $ map length ss
          leftPad s = replicate (div (maxlen - length s) 2) ' ' ++ s

paddedPascalTriangle :: Int -> [String]
paddedPascalTriangle n = leftPadStrings
                       . map listToString
                       . take n
                       $ pascalTriangle

printPascalTriangle :: Int -> IO ()
printPascalTriangle = mapM_ putStrLn . paddedPascalTriangle

Running this, you should get something like the following:

*Main> printPascalTriangle 10
             1
            1 1
           1 2 1
          1 3 3 1
         1 4 6 4 1
       1 5 10 10 5 1
     1 6 15 20 15 6 1
    1 7 21 35 35 21 7 1
  1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1


Simulating pod racing over a 2D map : am I implementing OOP in a GO-like fashion?

As per request in the comment, here's an implementation of the rotate function in a more idiomatic golang way (ie using a pointer receiver):

// let's use constants so code becomes self-documenting
const (
    maxRotation float64 = 18 // max rotation as typed constant
    fullCircle  int     = 360 // just like all hard-coded values, let's use constants
    semiCircle  int     = fullCirle/2 // do this for all hard-coded values
)

// note the receiver is a pointer, and there's no return value
func (pod *Pod) rotate(p Dot) {
    a := pod.diffAngle(p)

    if a > maxRotation {
        a = maxRotation
    } else if a < -maxRotation {
        a = -maxRotation
    }

    pod.angle += int(math.Round(a))

    var add int // add this value, defaults to 0
    // you are comparing pod.angle (an int) to a float64 (360.0)
    // that shouldn't be happening. I'd say angle should be a float64
    // but keeping the fields in pod the types they are for now
    if pod.angle >= fullCircle {
        add -= fullCircle
    } else if pod.angle < 0 {
        add = fullCircle
    }
    pod.angle += add // adds 0, 360, or -360 depending on the new value for pod.angle
}

That's all there is to it, really. Instead of calling it like this:

pod.angle = pod.rotate(p)

You simply call it like this:

pod.rotate(p)

The value of pod.angle will be updated. If you start doing this stuff concurrently, you'll need to ensure that pod.rotate() is "thread-safe" (ignoring the fact that goroutines aren't really threads for a second). The easiest way to do this is using a sync.Mutex (or sync.RWMutex), to make sure that you're not accidentally updating pod.angle in 2 routines etc...

I might revisit this stuff to give a more detailed review, so stay tuned for updates.


Is anything unclear about this code?

The purpose of this code is unclear.

  Do I break any good-programming rules?

Some bad practices that immediately jump into the eye:

Formatting is horrible
The parameterless constructor of Warrior is pointless and can be safely omitted
Methods with empty bodies, such as fight and levelUp in Human should at least have a comment explaining why the implementation is left empty
showAbility is poorly named:

None of the attributes are abilities: name is certainly not an ability, and the other fields are questionable too
"show" is a bit ambiguous. Show where? In a pop-up, maybe? I'd use the word "print" instead.

Maybe printStats would be better.
It's probably not a big concern for your programming exercise, but for the record, print statements inside a program are generally frowned upon. The preferred way is to use a logging framework instead. (Again, this is just for the record, since you asked about bad practices.)

Instead of Warrior inheriting from Human,
consider using interfaces.
For example you could have Warrior and Mage interfaces,
so that you can have mighty mage-warriors.
With inheritance this would be impossible.
Using interfaces will lead to a more extensible design.


Finding pairs of numbers with a given difference

You don't need to use a map here. A set will work just as well, since you can recreate the original value by adding the difference again.

I'm not sure if it's possible to do it in one line (which of course is not necessarily the most readable solution), but you can get close by converting the input array into a set and then using streams:

static int[][] findPairsWithGivenDifference(final int[] values, final int difference) {

    Collection<Integer> valuesSet = Arrays.stream(values).boxed().collect(Collectors.toSet());

    return valuesSet.stream()
            .map(v -> v - difference)
            .filter(valuesSet::contains)
            .map(v -> new int[] { v, v + difference })
            .toArray(size -> new int[size][2]);
}


Javascript Object Placement / String Parsing Method

Here is what's wrong with your code:

Do not use variable names like _o. Get an editor with good auto-completion.
typeof _o != 'object' does not do what you think it does: typeof([1,2]) // "object".
In general, doing those kinds of checks is a code smell.
if (!isNaN(parseInt(loc))) loc = parseInt(loc);. Confusing and not needed.
JavaScript: ['a', 'b']["1"] // 'b'. Same goes for the other isNaN
in. Do not do that check. null is a value, but what you want to return is the lack of value. It is undefined in JavaScript, and it is what will be returned if there is no value.
Consider using split instead of indexOf and substring. It is much faster and makes the code more readable.

So, here is a neat version for you:

function chained(obj, chain, value){
    var assigning = (value !== undefined);
    // split chain on array and property accessors
    chain = chain.split(/[.\[\]]+/);
    // remove trailing ']' from split
    if (!chain[chain.length - 1]) chain.pop();
    // traverse 1 level less when assigning
    var n = chain.length - assigning;
    for (var i = 0, data = obj; i < n; i++) {
        data = data[chain[i]];
        // if (data === undefined) return; // uncomment to handle bad chain keys
    }

    if (assigning) {
        data[chain[n]] = value;
        return obj;
    } else {
        return data;
    }
}

Blogged: http://glebm.blogspot.com/2011/01/javascript-chained-nested-assignment.html

Please come up with further improvements :)


My first impression:

The implementation looks long and complicated for something that sounds simple
You've provided some example cases to verify correctness, which is a very good thing

My first reaction is to embody the example test cases in proper unit tests, and then replace the implementation with a different approach, and make the tests I broke work again.

The unit tests, straightforward from your examples:

@Test
public void testCamelCased() {
    assertEquals(Arrays.asList("I", "Some", "Camel", "Cased", "String"), split("ISomeCamelCasedString"));
}

@Test
public void testSnakeCased() {
    assertEquals(Arrays.asList("UNDERSCORED", "STRING"), split("UNDERSCORED_STRING"));
}

@Test
public void testMixed() {
    assertEquals(Arrays.asList("camel", "Cased", "and", "UNDERSCORED"), split("camelCased_and_UNDERSCORED"));
}

Next, I was thinking that this can be simplified by splitting on some clever regex. I'm no regex wiz, but there are a lot of those on Stack Overflow, and I found a suitable thread about splitting camelCase to its words, here. Adapting it to also split on underscores was relatively easy, though probably not perfect, resulting in this:

private static final String RE_CAMELCASE_OR_UNDERSCORE =
        "(?<!(^|[A-Z]))(?=[A-Z])|(?<!^)(?=[A-Z][a-z])|_";

public static List<String> split(String string) {
    List<String> words = new ArrayList<String>();
    for (String word : string.split(RE_CAMELCASE_OR_UNDERSCORE)) {
        if (!word.isEmpty()) {
            words.add(word);
        }
    }
    return words;
}

This is probably not perfect, but a lot shorter than the original, and easier to understand how it works. If somebody can figure out how to get RE_CAMELCASE_OR_UNDERSCORE so that it doesn't produce empty elements, then the method can be shortened to simply:

return Arrays.asList(string.split(RE_CAMELCASE_OR_UNDERSCORE));

PS: this_is_usually_called_snake_cased, not "underscored".


Yes, chunk is the way to go. I'd write it differently, though, using a list-comphehension approach (in Ruby: map+if+compact. Or with a custom method.) and taking in account the edge case (no elements item in the array):

def longest_item_only_subsequence_len(xs, item)
  xs.chunk(&:itself).map { |y, ys| ys.size if y == item }.compact.max || 0
end


Not sure if that's going to improve the maintainability index, but

You're misimplementing Inversion of Control. IoC is when your dependency (namely, IReportHandler) is given to you from outside the class. It isn't the case here. It defeats the whole purpose of having an abstract dependency instead of a concrete one.

Read up on Inversion of Control and Dependency Injection and how they can improve code maintainability and testability. Don't use them unless it is an educated choice to do so.
You're using a Factory where it has no benefit.

Read up on the different kinds of factories (Factory from DDD, Factory method and Abstract Factory from Go4). Don't use Factories except where there's a clear advantage to doing so.
The code is too complicated for what it does.

Why the factoryId, switch statement and magic value 1?

The url parameter is never used.

Why the intermediate variables documentsDataJSON when you could just return <expression> and save one line of code for more clarity?
Naming is awkward and violates the Principle of Least Surprise.

Why would you expect a ReportHandler to Create a report, while ReportFactory creates a... ReportHandler?

Why does FetchDocuments() not return a list of Documents, but a list of DocumentMappers?

Don't try to mimic code samples or game a maintainability analysis tool. Learn about the philosophy behind the big design principles/patterns and decide for yourself if, where and how to apply them.


Python OOP Whac-A-Mole program using turtle

Terminology

  one [class] for Game which is the super class

What you probably mean is that it is the class that controls everything and such is on top of the logical class hierarchy. But when talking about super classes, you usually mean classes from which other classes inherit and thus are on top of (or further up) the inheritance hierarchy. In your code for example, Sprite is a super class of Mole.

White space

To make your code more readible, you should add blank lines appropriately, to separate logically related blocks of code. For example, add a blank line between methods, and two blank lines between classes. Inside of methods you can add single blank lines wherever it seems appropriate, for example around loops.

You should add spaces around operators (like self.pointsDisplay = Points() instead of self.pointsDisplay=Points()) and after commas (e. g. def update_score(self, x, y): instead of def update_score(self,x,y):), however not before commas, as you did here random.randint(leftbound , rightbound).

Refer to PEP 8, which is the Python style guide.

Naming

Your naming scheme is inconsistent. Python uses snake_case, not camelCase, for member names (see also PEP 8). You mixed both schemes, for both methods and member variables. It is always better to be consistent with one naming scheme, and prefered to follow the conventions of the language.

You are using x and y as parameter names. It is better to use speaking names that tell you what they are for or what they contain, e. g. position_x, position_y. In some cases x and y can be sufficient if the method name is explicit enough, like move_to_position(self, x, y), but I wouldn't say this is the case with update_score. Furthermore, you aren't even using the parameters in update_score and decrease_score.

update_score and decrease_score seems a bit confusing. Isn't decreasing also a kind of updating? Shouldn't the opposite be called increase_score? Maybe you can use just one method update_score for both cases, and control the amount how much it is increased or decreased with a parameter.

Logic

Your method callDisplayScore does not do anything, because all that happens when you call it is that a local variable is assigned a value, but it is not used afterwards. After the method had been called, the local variable does not exist anymore. So you could remove that method alltogether, and remove the calls to it from the methods update_score and decrease_score. Then all that remains in those two methods can basically be done without methods, because you can simply change the value of the score and then print it, which is hardly worth a method. Not using a method there will probably also make the code more readible, because it is hard to find a method name that describes well what these two lones of code do.

This is redundant:

crash =False
self.crash=crash

You can just write self.crash = False instead.

This expression is way too long to understand what it means:

if turtle1Pos == turtle2Pos or turtle1X < turtle2X - 50 and \
    turtle1Y > turtle2Y - 50 and  turtle1X < turtle2X - 50 and\
    turtle1Y > turtle2Y + 50:
    self.crash = True

Better save the result in a variable with a speaking name, or define a method that returns the result of the expression, again with a speaking name. Such a name could be is_colliding. Also using parantheses to group parts of the expression (even if they are technically not needed) can improve readability a lot.

This method also contains a lot of redundant logic, and also has not a very good name:

def collisionCheck(self,turtle1, turtle2):
    self.crash = False
    turtle1X = turtle1.xcor()
    turtle1Y = turtle1.ycor()
    turtle2X = turtle2.xcor()
    turtle2Y = turtle2.ycor()
    turtle1Pos = (int(turtle1X), int(turtle1Y))
    turtle2Pos = (int(turtle2X), int(turtle2Y))
    if turtle1Pos == turtle2Pos or turtle1X < turtle2X - 50 and \
        turtle1Y > turtle2Y - 50 and  turtle1X < turtle2X - 50 and\
        turtle1Y > turtle2Y + 50:
        self.crash = True
    return self.crash

Method names should be verbs (in most cases), so check_collision is better than collisionCheck. Even better: is_colliding or is_collision, because check_collision is not explicit about what a result of True means.

All of these variables you assign in the first 7 lines of the method are not needed. Your self.crash is not even used anywhere else, so a local variable (without self.) would be enough even if you needed the variable at all. In some cases it can be good to save values from method calls into variables in order to not have to call the methods multiple times, but if the method is just an accessor to a member variable, like turtle1.xcor(), the overhead from the method call is negligible, and readability is much more important as long as performance is not an issue. And instead of returning a boolean value depending in the result of a logical expression, just return the result of the expression instead.

Checking whether the position is the same (turtle1Pos == turtle2Pos) is obsolete if you then check with a threshold anyway. By the way, you have a bug here: turtle1X < turtle2X - 50 occures twice in the expression, perhaps on of the minuses should be a plus. And since turtle1Y > turtle2Y - 50 and turtle1Y > turtle2Y + 50 are combined with and I assume that you have another bug leading to false collisions in some cases. Here one of the > should be a <. You can simplify your collision detection logic by just checking whether the absolute distance is lower than your threshold. Optionally you could define the threshold somewhere as a variable or inject it as a parameter.

Simplifying the method, I get this:

def is_collision(self, turtle1, turtle2):
    return abs(turtle1.xcor() - turtle2.xcor()) < 50 and \
           abs(turtle1.ycor() - turtle2.ycor()) < 50


Moving elements satisfying a predicate from one container to another

Sorting the source is not specified as a requirement, so it seems that std::partition would do the necessary job more efficiently. As a perk benefit, std::partition returns the partition point, eliminating the need to std::find_if.

If you still want to follow the sorting path, consider std::lower_bound instead of find_if.


Randomly generate a Hex Colour code and its contrasting colour using JavaScript

There is a similar question that you may want to take a look at for some extra insight, even thought it doesn't have the contrasting color feature:

JavaScript Random Color Generator

Now lets get to the review.

Naming

The common naming convection in JS for methods is camelCase which you didn't follow in general.
Most of the variable and function names aren't clear or descriptive of what they do/hold. This is a lot more important than it may seem at first, and not naming properly makes your code difficult to read and understand.

As a side note Uncle Bob has a full chapter on this topic on his Clean Code book.
Be consistent in the names. If you look closely you'll see that in some places you used color:

var color = "#";

While in others colour:

function contrastcolour(colour) {

This is at best confusing if not mysterious. Leaves one wondering if it is a different thing or if it has a different meaning.

For this review i went with colour which was the one you used more often.

Functions

Now an overall review of the functions you presented:

startcolour

Better than using an array of elements is using a string with all possible characters:

var values = '123456789ABCDEF';

You can still use the index operator to fetch a character as you do in a normal array.

There is no need to separate the '#' in a single variable and then add only
the color part to a different one, and the += operator is also more idiomatic
and still easy to read.

Don't use variables without declaring them, as you have in the for:

for (i = 0; i < 6; i++) {
//---^

i wasn't declared at all which makes it global, and may be the source of some hard to find bugs.

Taking all this into consideration the function could be rewritten to:

function randomColour(){
  const chars = '123456789ABCDEF';
  let colour = '#';

  for (let i = 0; i < 6; i++) {
    const randomIndex = Math.floor(Math.random() * chars.length);
    colour += chars[randomIndex];
  }
  return colour;
}

Or you can take a totally different approach, the one mentioned in the related question:

function randomColour(){
  const randNum = Math.floor(Math.random() * 16777216); //from 0 to ffffff
  return '#' + randNum.toString(16).padStart(6,"0");
}

This generates a number between 0 and 16777215, or ffffff in hexa, and outputs it with hexadecimal formatting, by calling toString(16). It is then padded with zeros to a length of 6.
padZero

There is no need to create a padding function, because there is one already, called padStart or padEnd. It even has a polyfill if you need to support some old browsers.

Using it in your code would look like so:

r.toString().padStart(2,"0")

Note that it's a method on string therefore if i have a number i must first transform it to string.
colourRun

The name on this one is also not very obvious to what it does. If the function returns a random color and it's contrast a better name would be baseContrastColours.

Its important to mention that push supports any number of elements, so there is no need to make two separate pushes. Also in this specific case its easier to just return the array literal with the respective elements instead of creating the array, pushing the elements and returning at the end.

Like this:

function baseContrastColours() {
  const base = randomColour();
  const contrast = contrastColour(base);
  return [base, contrast];
}

While it has the same functionality, its simpler and easier to read.
contrastcolour

All the r, g, b variables are created up top and only set below:

function contrastcolour(colour) {
  var r;
  var g;
  var b;
  ...

  r = (255 - parseInt(colour.substring(0,2), 16)).toString(16);
  g = (255 - parseInt(colour.substring(2,4), 16)).toString(16);
  b = (255 - parseInt(colour.substring(4,6), 16)).toString(16);
  ...
}

You want to create variables and set the values directly if there is nothing else to do in between both actions:

var r = (255 - parseInt(colour.substring(0,2), 16)).toString(16);

Considering the variables were declared with var they are even hoisted. Also in general you want to declare the variables as close as possible to were you use them.

The arrayLength and comp variables aren't used. Always remove unused variables to keep the code as clean as possible.

Also important is that you are repeating the inverse logic 3 times, one for each color channel. So while simple you may want to consider abstracting that logic to a separate function.

So this function could be rewritten as follows:

function inverseChannelColour(channelColour){
  return (255 - parseInt(channelColour, 16)).toString(16);
}

function contrastColour(colour) {
  if (colour.charAt(0) == '#') {
    colour = colour.slice(1);
  }

  const r = inverseChannelColour(colour.substring(0,2));
  const g = inverseChannelColour(colour.substring(2,4));
  const b = inverseChannelColour(colour.substring(4,6));
  const contrast = '#' + r.toString().padStart(2,"0")
                       + g.toString().padStart(2,"0")
                       + b.toString().padStart(2,"0");
  return contrast;
}

As pointed out by @Zeta in the comments if the color to be inverted is a gray very close to the middle, the inversion will generate a similar color which may not be easy to read.

You can try to avoid this by manually checking the difference of all channels to their inverted versions, and if all of them are bellow a certain threshold generate a different color. A simple approach to this would be to generate black if all channels are closer to white and white otherwise.

There are also some libraries/micro-libraries that generate colors and their complementary versions with other approaches, such as using HSL. These may be interesting for you to take a look.

Here are some of them for reference:

invert-color
Colors.js
complementary-colors


First of all, it seems like you never change the MarkovMap in your States. So, why don't you take it out of MarkovState and change the type of, say, transition, to MarkovMap -> State MarkovState Char?

Try to use more combinators and less pattern-matching. For example, the generate function is something like sequence . repeat.


Selector targets overly obtuse - recommendations?

You can certainly cache the lookups, abusing of the scopes.

$(".button").each(function(){
  var $btn = $(this);
  var $box = $btn.parent().children(".innerBox");
  $btn.toggle(function(){
    $box.fadeIn();
  }, function(){
    $box.fadeOut();
  });
});

Using .fadeToggle() instead of .fadeIn() and .fadeOut().

$(".button").each(function(){
  var $btn = $(this);
  var $box = $btn.parent().children(".innerBox");
  $btn.click(function(){
    $box.fadeToggle();
  });
});

And last but not least, .siblings().

$(".button").each(function(){
  var $btn = $(this);
  var $box = $btn.siblings(".innerBox");
  $btn.click(function(){
    $box.fadeToggle();
  });
});


Project Euler Problem #50 Consecutive Prime Sums

I'll try to focus on the performance of the code provided, and what can be done to improve it. One key observation that I found is that it is more efficient to start searching for larger consecutive sums, and move towards shorter until we find a valid candidate.

Then the obvious question is: where do we start? To find this, simply check the cumulative sums for the first n primes. As n increases, so does the sum. When the sum is above 1000000, it would not be possible to find a sum of n primes which is in the list of primes below 1000000. With this, it can be deduced that the sum can contain 546 elements at most. You should verify this on your own.

Another observation is that 2 is the only even prime. With the knowledge that odd + odd = even, even + odd = odd + even = odd, and even + even = even, we can deduce that if and only if 2 is a part of the consecutive sum, the sum must contain an even number of elements. Thus, we must only check the very first consecutive sum (the one starting with 2) when the sum has an even number of elements.

With all of this in place, the speed of the search is improved considerably.

n = 1000000
found = False
primes = sieve(n)
primes_set = set(primes)

for test_len in range(545, 1, -2):
    for i in range(0, len(primes)-test_len):
        s = sum(primes[i:i+test_len])
        if s in primes_set:
            print("found", test_len, s)
            found = True
            break
    if found:
        break

This is of course only a small snippet, and not the full program. For example, this does not test for even length consecutive sums, but that should be trivial with the information provided above. However, the execution time for the loop is less than a second, with the majority of the runtime now being used by the prime sieve. However, optimizing that is outside the scope of this answer.


Code Organization
Code should be organized in such a way that someone reading the code doesn't have to scroll up and down in order to understand the code.  For instance, you should not have:
mainline code
function definitions
mainline code

Instead, the mainline code should all be together at the bottom:
function definitions
mainline code

Naming
The PEP 8 -- Style Guide for Python Code lists a number of rules guidelines that should be followed throughout Python code.  One such guideline is:

function and variable names should be in snake_case; MixedCase is reserved for class names.

So BewijsN and List1 should become bewijs_n and list_1.  Similarly, IsEven, IsPrime and BigFactorCheck should be is_even, is_prime, and big_factor_check.
List1 is especially ugly.  There is no List2, List3 and so on, so why is there a 1 in that name?  number_chain might make a better name.
Boolean Test
def IsEven(n):
    if n % 2 == 0:
        return True

    else:
        return False

The function body reads approximately:
    if something is True:
        return True
    else:
        return False

Since something will be True in the "then" clause, instead of returning the literal True, we could return something.  Similarly, when something is False, in the "else" clause, instead of returning the literal False, we could also return something:
    if something is True:
        return something
    else:
        return something

At this point, we can see the if ... else is irrelevant; in both cases, we return something.  So we can optimize this to:
    return something

specifically:
def is_even(n):
    return n % 2 == 0

Range
The IsPrime function has this code:
    for x in range(n - 2):
        x += 2

This is confusing and inefficient.  Confusing because the loop variable x starts at 0, and is modified inside the loop, increasing it to 2; what is it on the next iteration?  Of course, the modification inside the loop body is lost when the next iteration begins, but that will often confuse a newcomer to Python.
It is inefficient, since because adding 2 each time through the loop is an unnecessary operation, which takes time.  Numbers are objects, and every time a computation changes a number, the old number object is dereferenced (and possibly destroyed), and a new number object may be created.  It is far faster to simply loop over the correct range: range(2, n).
def is_prime(n):
    for x in range(2, n):
        if n % x == 0:
            return False
    return True

This loop can actually be simplified and sped up, using the all(...) function and a generator expression:
def is_prime(n):
    return all(n % x != 0 for x in range(2, n))

There are many things you can do to further speed up this is_prime function.  If the number would be divisible by an even number larger than 2, it would have already been divisible by 2, so you can call that out as a special case, and then only consider odd numbers 3 and up, using range(3, n, 2):
def is_prime(n):
    if n > 2 and n % 2 == 0:
        return False

    return all(n % x != 0 for x in range(3, n, 2))

Also, looking for factors larger than \$sqrt(n)\$ is inefficient, since if \$x > sqrt(n)\$ was a factor, then \$n / sqrt(n) < sqrt(n)\$ would also be a factor, and you would have already encountered it:
from math import isqrt

def is_prime(n):
    if n > 2 and n % 2 == 0:
        return False

    return all(n % x != 0 for x in range(3, isqrt(n) + 1, 2))

Due to isqrt(n), this will crash if called with a negative value.  Crashing is bad.  What did your function do?  IsPrime(-10) returned True, which is incorrect, which is arguably worse than crashing.  At least if you crash, you know something went wrong, and get a stack trace you can debug.  A wrong result is harder to debug, since you don't know where it went wrong.  While we're at it, neither 0 nor 1 should return True:
from math import isqrt

def is_prime(n):
    if n < 2 or (n > 2 and n % 2 == 0):
        return False

    return all(n % x != 0 for x in range(3, isqrt(n) + 1, 2))

This is faster and more correct.  You could improve it even further, with more advanced prime checking, such as the sieve-of-eratosthenes.
Big Factor Check
def BigFactorCheck(n):
    for x in range(n):
        x += 1

        if n % (n - x) == 0:
            return n - x

On the last iteration, x initially is n-1, but you add 1 to it, so x actually would be n.  Then n % (n - x) would be n % (n - n), or n % 0, which is a division by zero!  Eek.  Fortunately, you never reach the last iteration; the previous iteration would test n % 1 == 0, which should always be true.  Still, dangerous code.
Again, for x in range(n) and x += 1 could simply become for x in range(1, n+1).  But you don't simply want x; you want n - x.  Why not just loop starting a n-1, and go down until you reach n - (n-1)?  You don't even need to try the n % 1 == 0 iteration; you could stop before reaching 1, and simply return 1 if you get to the end of the for loop:
def big_factor_check(n):
    for x in range(n - 1, 1, -1):
        if n % x == 0:
            return x
    return 1

Main function
Your mainline code is complex enough to warrant its own function.  You could even add a main-guard, so you can import this function into other programs if you want to use it, without executing the mainline code.
def addition_chain(n):
    number_chain = []
    while n > 1:
        # your computations here

    number_chain.sort()
    return number_chain

if __name__ == '__main__':
    n = int(input())
    bewijs_n = (n + 1) / 2
    chain = addition_chain(n)
    print(len(chain), chain)
    if len(chain) - 1 <= bewijs_n:
        print(True, len(chain) - 1, "<=", bewijs_n)


Shifting event times to and from time zones

You can add an argument of type:

BiFunction<LocalDateTime, Integer, LocalDateTime>

To your function that will reflect your need: LocalDateTime (initial date), offset, LocalDateTime (date that will be returned after applying the function).
The method will look like this:

private void shiftEventDateTime(EventDto event, BiFunction<LocalDateTime, Integer, LocalDateTime> f){}

To apply the function inside the method you can write it this way:

f.apply(event.getStartDateTime(), getOffsetSeconds(event.getStartDateTime(), event.getStartDateTimeZone()));
f.apply(event.getEndDateTime(), getOffsetSeconds(event.getEndDateTime(), event.getEndDateTimeZone()));

And when you invoke your method you need to specify the operation itself:

shiftEventDateTime(event, LocalDateTime::minusSeconds);
shiftEventDateTime(event, LocalDateTime::plusSeconds);

You can choose whatever name for the BiFunction that you like and the one that fits your case the most.