Instead of calculating two sums, you could just calculate one: the sum of all elements. Then, the min sum is the sum minus the maximum element, and max sum is the sum minus the minimum element.
Note that sorting just to find the minimum and maximum elements is inefficient, because sorting is generally an \$O(n \log n)\$ operation,
and finding the minimum and maximum (and the sum) is possible in a single pass, which would be \$O(n)\$.

Hard-coding the number 4 makes the solution very rigid, applicable to only this specific problem. In your implementation you could use the length of the array instead in a way to make that number 4 unnecessary, and easily make your implementation applicable to a more general set of problems. The number 4 is an artificial restriction; it's wise to get rid of it.


Conditional statements with doctor and patient information

First things first: while this obviously comes from real code, the way you "anonymized" your code doesn't work, eg. sys.argve doesn't exist.

  I'm trying to make this code easy for someone to read and add more cases.

If you want Python developers to be able to read your code easily, please follow PEP 8 (using a tool such as pep8). That includes sticking to 80 columns, using underscored_names and using ALL_CAPS variables for constant strings.

  Most of this code in the if else statements are very similar. I feel like I might be able to use a lambda to clean this code up but I'm not sure that will work. What is the best way of avoiding a lot of the repetition in this code?

Without having tried to improve your code yet, using list comprehensions and lambdas is a good way to shorten code, but short code != readable code.


Input data from file, calculating average by a function

I would think about breaking this up into more functions that do specific things. For example, I would break out the reading of the header information (the number of tests passed and the number returned) into one function, and the reading of the actual test data into another function:

void readHeader (FILE* inputbestand, float* uitgereikt, float* ingeleverd)
{
    fscanf(inputbestand, "%f", uitgereikt);
    fscanf(inputbestand, "%f", ingeleverd);
}

This brings up a question I have for you - why is ingeleverd a global variable? In fact, why do you have any global variables? They all look like they belong inside the main() function to me.

In any event, reading the table of data would then look something like this:

void readTable (FILE* inputbestand, int invoer[RIJ][KOLOM])
{
    //------- overige data inlezen in een array van 5 bij 6.
    int rij, kolom;
    for (rij = 0; rij < RIJ; rij++)
    {
        for (kolom = 0; kolom < KOLOM; kolom++)
        {
            fscanf(inputbestand, "%d", &invoer[rij][kolom]);
        }
    }
}

For what it's worth, I like to put spaces around operators (like comparison operators - <, >, etc.), as I find it much easier to read. That's just a style decision and might not suit you, but that's what I prefer.

I would also move the output into various functions. The introductory text could go into a function like this:

#define RESULT_OK 1    // <- These can go at the top of the file
#define RESULT_ERROR 0 // <- with the others
int printIntro (FILE** inputbestand, char bestandpad[100])
{
    int result = RESULT_OK;
    printf("Dit programma verwerkt de data uit verschillende enquetes.\n");
    printf("\n");
    printf("Voer de locatie van het bestand in.\n");
    scanf("%s", bestandpad);
    *inputbestand = fopen(bestandpad, "r" );

    if (*inputbestand == NULL)
    {
        printf("Bestand niet gevonden.");
        result = RESULT_ERROR;
    }
    else
    {
        result = RESULT_OK;
    }

    return result;
}

Although, perhaps a better function name would be getFileName() (or would it be getBestandpad()? I don't know Dutch for "get").

Since you were originally returning 0 from main() when the file could not be read, you need to return any errors from the above function and use that in main() to decide what to return. Which reminds me - you aren't returning a value on success in your main() function. So let's look at that next. After breaking out the various functions, it will look something like this:

int main (void)
{
    FILE* inputbestand;
    int invoer[RIJ][KOLOM];
    char bestandpad[100];

    int result = printIntro(&inputbestand, bestandpad);
    if (result == RESULT_OK)
    {
        float uitgereikt;
        float ingeleverd;
        readHeader(inputbestand, &uitgereikt, &ingeleverd);
        readTable(inputbestand, invoer);
        fclose(inputbestand);

        printStatistics(uitgereikt, ingeleverd);
        printResults(invoer, ingeleverd);
    }

    return result;
}

The function printStatistics() should print out the information about how many tests were passed and how many were returned:

void printStatistics (const float uitgereikt, const float ingeleverd)
{
    printf("Aantal uitgereikte evaluaties: %0.f\n" , uitgereikt);
    printf("Aantal ingeleverde evaluaties: %0.f\n" , ingeleverd);

    float percentage = (ingeleverd/uitgereikt) *100 ;
    printf("Response is: %.1f %% \n\n" , percentage);
}

Likewise, printResults() should print out the resulting table:

void printResults(int invoer[RIJ][KOLOM], const float ingeleverd)
{
    printf("   \t  A\t B \t C \t D \t E \t cijfer \t opmerking\n\n");
    int rij, kolom;
    for (rij=0; rij<RIJ; rij++)
    {
        printf("vraag %d   " ,rij+1);

        for (kolom=0; kolom<KOLOM ; kolom++)
        {
            printf("%d       ", invoer[rij][kolom]);
            if (kolom==KOLOM-1)
            {
                printf("%c \n", functie(invoer[rij], ingeleverd));
            }
        }
    }
}

It's not clear to me what the functie() function is doing. It looks like it's supposed to calculate an average, but it doesn't look to me like it's actually doing that. Also, it returns a float, but it's being used as a character in the printf() statement where it's called. That's almost certainly incorrect. And you've listed 3.0 and 3.5 as the breakpoints between fail, warning, and pass, but in the example, all the grades are 2.4, but marked as "pass". So I'd double-check to make sure you understand the requirement there.

In addition to the above, you should know that there are various ways that reading from the file could fail. You could have truncated data, or there might be the wrong kind of data in the file. I'm not sure if your teacher wants you to worry about that yet, or not. If you want to, you can check the return value of fscanf() and make sure that it read the argument you expected.


TweetResolver class, to be used in a graphql project

If all your catch is doing is re-throwing the error, there is no reason to have the try/catch in the first place.
If you find yourself using export default {}; to export an object, it is a huge sign that you should be using named exports instead, since you're essentially emulating them. This means you'll want to do import * as Foo from instead of import Foo from on these "bag of functions" modules.
You can make a wrapper function to remove the repetitive requireAuth call.
A wrapper function also allows you to remove the params you don't care about in the implementation, like the first and third parameters to these functions.

To update your code with these, I'd do

import Tweet from '../../models/Tweet';
import { requireAuth } from '../../services/auth';

let withAuth = callback => async (_, args, data) => {
    await requireAuth(data.user);
    return callback(args);
};

export const getTweet = withAuth(({ _id }) => Tweet.findById(_id));
export const getTweets = withAuth(() => Tweet.find({}).sort({ createdAt: -1 }));
export const createTweet = withAuth((args) => Tweet.create(args));
export const updateTweet = withAuth(({ _id, ...rest }) => Tweet.findByIdAndUpdate(_id, rest, { new: true }));
export const deleteTweet = withAuth(async ({_id}) => {
    await Tweet.findByIdAndRemove(_id);
    return {
        message: 'Tweet has been deleted'
    };
});

with

import GraphQLDate from 'graphql-date';
import * as TweetResolvers from './tweet-resolvers';
import UserResolvers from './user-resolvers';

export const Date = GraphQLDate;
export const Query = {
    getTweet: TweetResolvers.getTweet,
    getTweets: TweetResolvers.getTweets,
};
export const Mutation = {
    createTweet: TweetResolvers.createTweet,
    updateTweet: TweetResolvers.updateTweet,
    deleteTweet: TweetResolvers.deleteTweet,
    signup: UserResolvers.signup,
    login: UserResolvers.login,
};


Toggling element class according checked radio input V2.0

Let's start with a dry review:

Underscores in JavaScript hurt the eyes. The absolute naming convention of JavaScript is to use camelCase. Your underscore notation, while consistent, hurts the eyes of other JavaScript developers.
Using event delegation is great, but since you've queried the DOM once when you instantiated the element, you can only use the elements which existed in the DOM when you instantiated the object. Boo.
This line

  this.radio_set = document.querySelector('radio-set'),

selects the first <radio-set></radio-set> element.
You're selecting all of the radio buttons on init, what happens if you have other radio elements which aren't related to your module? You'll process them too, which is undesirable.

Now a bit on the approach, I prefer the Revealing Module Pattern for making self-contained modules. It allows you to have public and private properties and methods, and only reveal what you want.

My Take

jsFiddle

 <form id="module">
    <input type="radio" name="color" value="yellow" checked/>Yellow
    <input type="radio" name="color" value="brown"/>Brown
    <input type="radio" name="color" value="orange"/>Orange
    <input type="radio" name="color" value="purple"/>Purple

    <input type="text" class="radio-condition visible" placeholder="Which yellow?" data-value="yellow"/>
    <input type="text" class="radio-condition" placeholder="Which brown?" data-value="brown" disabled/>
    <input type="text" class="radio-condition" placeholder="Which Orange?" data-value="orange" disabled/>
    <input type="text" class="radio-condition" placeholder="Which Purple?" data-value="purple" disabled/>
</form>


You are checking much more than you need to. Consider the first two cases:

if weight <= 2:
    # A
elif weight > 2 and weight <= 5:
    # B

If weight <= 2, we fall into case A. If we're not in case A, only then do we continue onto the next condition checks (because we're using elif and not if). As such, if we're even in the path that checks the condition which leads to B, we already know that weight > 2. Thus, that check is redundant and can be reduced to simply weight <= 5.

The whole body can become:

if weight <= 2:
    rate += 1.25
elif weight <= 5:
    rate += 2.35
elif weight <= 10:
    rate += 4.05
else:
    rate += 5.55

Which isn't just less code, it's easier to reason about since all your bounds are visually in the same column.


Unfortunately, you haven't included enough code for me to give a proper review. Essentially what your looking for is called "eager loading." MSDN and stack overflow have some examples.

When you're building the query for entities.LOGs do something like this:

entities.LOGs.
    Include (log => log.TAG).
    Include (log => log.TAG.GROUP).
    Include (log => log.TAG.GROUP.GROUPNAMEs).
    Include (log => log.TAG.TAGNAMEs).
    Select ( /* your select here */);


Calculate the number of moves requires for a knight chess piece

\$O(1)\$ Discussion

  Is it possible to calculate the distance in \$O(1)\$ time complexity?

Yes, it is.

This problem is called the "Knight's distance" problem, and googling it find a number of references.

This problem was posed as part of the South African "Computer Olympiad" in 2007 for high-school students to solve.... (I know, kids these days.... :) ). The specification was such that some input values for the programs were large enough that \$O(n)\$ solutions would fail to compute in the required time limits, so to get full marks you needed to (devise, and) compute the \$O(1)\$ system.

The problem description, and enough of the description of the \$O(1)\$ solution are available. In case the .za net goes dead, here's the description of the solution:

  4 The Knights Who Say Ni

  The (x, y)-coordinates in the 50% constraints are small enough to
  generate a full grid of the minimum number of moves required to get
  from any point to (0,0). The grid can be generated by a breadth-first
  search (BFS).

  We know that getting to (0,0) requires 0 moves. We therefore know that
  the points (1,2), (2,1) and the other six movements each require 1
  move. From each of those points with a shortest distance of 1, we can
  take another step in each direction for a shortest path of 2. However,
  some moves will bring us back to a point we have already found a
  shorter distance for and we therefore discard such moves. We continue
  this until the grid is full and then use the grid to find the
  distances for each knight.

  To get 100%, a lot of scribbling on paper is required to make some key
  observations and work out some formulae. The first thing to note is
  that the grid is symetrical along the x, y axis and the lines y = ±x.
  You can therefore convert all points (x, y) into an equivalent
  point such that the new 0 ≤ y ≤ x.

  The magic formula is:

  $$
f(x, y) = \left\{
 \begin{array}{ll}
  2 \left\lfloor \frac{y - \delta}{3} \right\rfloor  + \delta & \mbox{if } y > \delta \\
  \delta - 2 \left\lfloor \frac{\delta - y}{4} \right\rfloor & \mbox{otherwise}
 \end{array}
\right.
$$

  where \$δ = x − y\$.

Are there mistakes

Yes.... All squares are accessible to the knight. Why do you have a restriction?

I put your code in to an Ideone that loops through the 100 targets in positions (0,0) through (9,9).... and its results are disappointing... Does your code work?

NO. it does not. It produces wildly wrong values.....

Now, the algorithm I referenced above does not seem to be producing good values either (at least a short range....), but seriously? Your code hardly works at all :(

Lots, and lots of -1 distances, and lots and lots of 0.....


Organizing JavaScript code for a website

One problem in your code is that the "modules" aren't standalone. You'd be adding the "modules" for calling into the init every time a new on is made.

To avoid doing so, each module should register itself for init. You can do this by adding a "register" functionality in your singleton.

(function(exports){

    var registry = []; //collection of module

    //adds module to collection
    exports.register = function(moduleDeclaration){
        registry.push(moduleDeclaration);
    }

    //executes every module
    exports.init = function(){
        var registryLength,i;

        registryLength = registry.length

        //loop through each module and execute
        for(i=0;i<registry.length;i++){
            registry[i].call(this);
        }
    }

//use existing namespace or make a new object of that namespace
}(window.Lib = window.Lib || {}));

//To register a module
Lib.register(function(){
    //do what you have to do here
});

//executing the init
Lib.init();

See? The modules register themselves and don't need to be added manually for init. A developer can create a module on a separate file, add it into the page without editing the main Lib singleton.

Also, you'd have to consider what you'd do if you include a module dynamically after init is called. You should have some internal flag to indicate that init was already called, and that dynamically added module should register and execute immediately.

A vaguely known library called KernelJS already does this and contains many more features like core abstraction, pub-sub inter-module communication, register-remove modules, loose coupling pattern and so on. I suggest you try it or base from it.

As an answer to your add-on question of exposing modules, sure you can. However, according to scalability principles, modules or "widgets" as they call them, should not know each exists. This is to prevent tight-coupling and avoid breakage when, for example, you take out a certain module out.

Also, naming modules isn't good for portability as you are setting a fixed name for a set of code. What if you changed it's name? You'd have to look for all code that depends on that module and change the name.

However, if you want to have named modules and fetching badly, you could expose another function to retrieve a module and return that module if it exists, or undefined or a custom error if it doesn't. Here's modified code for Lib. Since we are using named modules, instead of an array, registry is now an object.

var registry = {}

exports.register = function(name,declaration){
    registry[name] = declaration;
}

exports.init = function(){
    var module,i;

    registryLength = registry.length

    //loop through each module and execute
    for(name in registry){
        if(registry.hasOwnProperty(name)){
            registry[name].call(this);
        }
    }
}

exports.getModule = function(moduleName){

    //default to undefined
    var module;

    //if module exists, assign
    if(registry.hasOwnProperty('moduleName')){
        module = registry[moduleName];
    }

    return module
}

//to register a module
Lib.register('moduleName',function(){
    //module code
});

Additionally, you can call each module's init from Lib's init. Just make sure each module exposes an init function.


Change

var code = $(this).text();

to

var code = $(this).val();


Full code

import (...)

Please include your full code next time. This should instead be:

import (
    "database/sql"
    "errors"
    "fmt"
    "io/ioutil"
    "log"
    "net/http"
    "os"
    "path/filepath"
    "sync"
    "time"
)

You also have item.toString(), but this is nowhere defined. I changed it to:

fmt.Println(item)

Scope

connectionString doesn't need to be in the global scope, whether it's const or not. The same could be argued about wg, ch, and errItems -- but moving those to a lower scope would involve adding more function arguments, which is a choice you can make.

In terms of security, I recommend against hard-coding the connection string in the source code. Instead, as one of many options, you can have the connection credentials as a separate file that you read.

Simplify query

You use named arguments in your query. But here, the query is so short that it's clear from the context. You can split the query across multiple lines to make it easier to read. You also have some keywords in all uppercase and some in all lowercase.

q := `
SELECT [ImageID],
       [AccommodationlID],
       [Link],
       [FileName]
FROM [dbo]. [AccomodationImage]
WHERE AccommodationlID BETWEEN ? AND ?
      AND FileName NOT LIKE '%NoHotel.png%'`

rows, err := db.Query(q, from, to)

(Notice that you also have a misspelling in AccomodationImage.)

This kind of formatting for query strings is also how the Go documentation does it.

Vertical spacing

All of the code is compressed together and has no room to breathe. I recommend adding the occasional empty lines, such as between if-statements, for loops, goroutines, etc.

Validate os.Args

Your code assumes the program will always have three arguments. While this makes sense if only you plan to use it, it's generally not good practice.

Without bounds checking, you will get a runtime panic "index out of range" -- no a particularly useful message for those running the program.

if len(os.Args) < 4 {
    log.Fatal("missing arguments")
}

You can also use short variable declaration when declaring basePath, from, and to.

basePath := os.Args[1]
from, to := os.Args[2], os.Args[3]

Default values

var item = item{}

This is redundant. You should be able to simply use var item -- please correct my if I'm wrong here and Rows.Scan() produces an error if item is nil. Since we do not need to initialize item, we can combine our declarations. Notice I rename the variable item to avoid confusion with the type item.

var (
    i     item
    accID string
    name  string
)

Conclusion

Here's the code I ended up with:

package main

import (
    "database/sql"
    "errors"
    "fmt"
    "io/ioutil"
    "log"
    "net/http"
    "os"
    "path/filepath"
    "sync"
    "time"
)

type item struct {
    id      int
    url     string
    path    string
    content []byte
    err     error
}

var wg sync.WaitGroup
var ch = make(chan *item)       // For success items
var errItems = make(chan *item) // For error items

func main() {
    const connectionString = "connectionString"

    if len(os.Args) < 4 {
        log.Fatal("missing arguments")
    }

    start := time.Now()

    basePath := os.Args[1]
    from, to := os.Args[2], os.Args[3]

    db, err := sql.Open("sqlserver", connectionString)

    if err != nil {
        log.Fatal(err.Error())
    }

    q := `
SELECT [ImageID],
       [AccommodationlID],
       [Link],
       [FileName]
FROM [dbo]. [AccomodationImage]
WHERE AccommodationlID BETWEEN ? AND ?
      AND FileName NOT LIKE '%NoHotel.png%'`

    rows, err := db.Query(q, from, to)

    if err != nil {
        log.Fatal(err.Error())
    }

    defer db.Close()

    for rows.Next() {
        var (
            i     item
            accID string
            name  string
        )

        _ = rows.Scan(&i.id, &accID, &i.url, &name)

        i.path = fmt.Sprintf("%s\\%s\\%s", basePath, accID, name)

        wg.Add(1)

        go downloadFile(&i)

        go func() {
            select {
            case done := <-ch:
                wg.Add(1)
                go saveAndUpdateFile(db, done)
            case errorItem := <-errItems:
                wg.Add(1)
                go printResult(errorItem)
            }
        }()
    }

    wg.Wait()

    fmt.Printf("%.2fs elapsed\n", time.Since(start).Seconds())
}

func downloadFile(i *item) {
    defer wg.Done()

    resp, err := http.Get(i.url)

    if err != nil {
        i.content, i.err = nil, err
    } else if resp.StatusCode != http.StatusOK {
        i.content, i.err = nil, errors.New(resp.Status)
    } else {
        i.content, i.err = ioutil.ReadAll(resp.Body)
    }

    if i.err != nil {
        errItems <- i
    } else {
        ch <- i
    }
}

func saveAndUpdateFile(db *sql.DB, i *item) {
    defer wg.Done()

    if i.content == nil {
        i.err = errors.New("Content is empty.")
    } else {
        dir := filepath.Dir(i.path)
        err := os.MkdirAll(dir, os.ModePerm)

        if err != nil {
            i.err = err
        } else {
            i.err = ioutil.WriteFile(i.path, i.content, 0644)
        }
    }

    q := `
UPDATE [dbo].[AccomodationImage]
SET    IsRead = 1
WHERE  ImageID = ?`

    if i.err == nil {
        result, err := db.Exec(q, i.id)

        if rows, _ := result.RowsAffected(); rows <= 0 || err != nil {
            i.err = errors.New("Update status failed.")
        }
    }

    if i.err != nil {
        errItems <- i
    }
}

func printResult(i *item) {
    defer wg.Done()

    fmt.Println(i)
}

Unfortunately I cannot test this code and suggest algorithmic or more in-depth changes.

Hope this helps!


Automatic condensing of whitespace in HTML

I don't see much reason to use (*F) instead of the somewhat more understandable (*FAIL).
Consider using single-quoted (') strings for regular expressions to avoid \\1.
There's a big assumption here that the HTML will be well-formed. I assume (ha!) that this is okay.
Whitespace is significant in <input> tags.


Finding prime divisors with wheel factorization

Work with larger integers than what int allows

Here, you seem to be asking for templates, so that your code works with any integer (and actually, any type which properly acts like an integer). I will convert the checkdivisor function for you so that you can analyze it, then templating the rest of the code will be left as an exercice:

template<typename Integer>
Integer checkdivisor(Integer n, Integer p) {
  while (n % p == 0) {
    std::cout << p << std::endl;
    n /= p;
  }
  return n;
}

Actually, it should even work with any type for which the operations %, / and == have the desired semantics.

Catch errors arising from command-line arguments that cannot be parsed as ints

That one is easy if you look at the documentation of std::stoi: it says that std::stoi throws an std::invalid_argument exception if the string does not represent an integer and an std::out_of_range exception if the string to parse represents an integer too big for the type to hold. Knowing that, you can set up a simple try/catch to handle the errors:

int main(int argc, char* argv[]) {
  for (int i = 1; i < argc; i++) {
    try {
      primedivisors(std::stoi(argv[i]));
    }
    catch (const std::invalid_argument& err) {
      std::cerr << "the input is not an integer\n";
    }
    catch (const std::out_of_range& err) {
      std::cerr << "the input is too big\n";
    }
  }
}


Implementing a Scheduler(something that implements a given schedule)

Your code is super-comlicated for such simple logic. I'm also pretty sure it deadlocks in pretty much any use case.

class Scheduler : IDisposable
{
    private readonly object scheduleLock = new object();
    private int[] schedule = null;
    private int scheduleIndex = 0;
    private readonly ManualResetEvent collectionResetEvent = new ManualResetEvent(false);
    private readonly AutoResetEvent delayEvent = new AutoResetEvent(false);
    private volatile bool working;

    private Thread th;

    public Dispose()
    {
        Offline();
    }

    public void RunSchedule()
    {
        while (true)
        {
            collectionResetEvent.WaitOne();
            if (!working) return;

            lock (scheduleLock)
            {
               if (schedule == null || scheduleIndex >= shedule.Count)
               {
                   collectionResetEvent.Reset();
                   if (!working) return;
               }
               else
               {
                   var nextSchedule = schedule[scheduleIndex++];
                   //execute,
                   //probably can be done outside the lock
               }
            }

            delayEvent.WaitOne(120 * 1000);
        }
    }

    public void Offline()
    {
        if (!working) return;
        working = false;
        delayEvent.Set();
        collectionResetEvent.Set();
        th.Join();
        th = null;
    }

    public void Online()
    {
        if (working) return;
        working = true;
        th = new Thread(RunSchedule);
        th.Start();
    }

    public void OfflineTooLong()
    {
        ScheduleReady(null);
    }

    public void ScheduleReady(int[] schedule)
    {
        lock (scheduleLock)
        {
            schedule = schedule;
            scheduleIndex = 0;
            collectionResetEvent.Set();
            delayEvent.Set();
        }
    }
}

This is just an example of how it can be refactored, to give you an idea. It can still potentially deadlock (for example if you call offline and dispose at the same time from different threads) so it requires some tweaking depending on your requirements. RunSchedule() method is somewhat hard to read, it should be splitted into sub-methods. BartoszKP makes a perfectly valid points as well, check his answer, if you haven't already.


If you want to dynamically insert the Google Map, instead of simply linking to an href, you can do as follows:

In your HTML, have the basic outline for the colorbox ready:

Then, when you invoke your colorbox, invoke it with an html option:

$("#farm_on_google_maps").colorbox({
            inline: true,
            width:700,
            height:450,
            html : $("#box").html()
            });

This will setup your colorbox with the basic HTML structure. We then want to insert the google map dynamically into the colorbox as follows:

var googleMap = $("#cboxLoadedContent").find("div.google-map")[0];
var latlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = { zoom: 8, center: latlng, mapTypeId: google.maps.MapTypeId.ROADMAP };
var map = new google.maps.Map(googleMap, myOptions);

The cboxLoadedContent div is created by the colorbox when it's invoked, so it's simply a matter of grabbing that, and using it to setup the Google Map.


Prefer C++ headers (such as <cstdio>) to the C compatibility headers (<stdio.h>).  The C++ headers define identifiers in the std namespace where we want them.
It seems that this header isn't even used here, so we can omit it completely.

std::size_t is misspellt throughout as size_t.  This commonly happens when writing on a platform that declares it in the global namespace as well as in std, but that's not a portable assumption.

We only use PI as a double, so we can declare it as a constant rather than as a macro:
constexpr double pi = 3.14159265358979323846;

Or to make it more obviously correct:
const double pi = std::acos(-1.0);

We can avoid naked new[] and delete[] using std::vector.  If we use std::vector::reserve before adding any elements, there should be no performance impact, only improved code safety.
Using a vector saves having to pass the array size explicitly, too.

A helpful technique to determine whether a number is a power of two is that bitwise-and of the number and its arithmetic predecessor is zero for powers of two:
constexpr bool is_power_of_two(unsigned n)
{
    return n && (n & (n-1) == 0);
}

A single value of N is probably not very useful in general.  We could make it a template parameter, or a simple function argument, to make our code useful for other sizes of input.

Modified version
I split FFT() into a simple public function that ensures arguments are valid and the internal recursive implementation.  I've used a requires to constrain the complex type we accept (integer types aren't useful here), but that can be omitted for plain C++17.
#include <complex>
#include <vector>

namespace internal
{
    /*
      Creating the table of all N'th roots of unity.
      We use notation ω_i = e^(-2πi/n).
    */
    template<typename U>
    constexpr auto rootsOfUnity(std::size_t n)
    {
        constexpr auto pi = std::acos(U{-1.0});
        std::vector<std::complex<U>> table;
        table.reserve(n);

        for (std::size_t i = 0;  i < n;  ++i) {
            table.emplace_back(std::cos(-2.0 * pi * i / n), std::sin(-2.0 * pi * i / n));
        }

        return table;
    }

    template<typename V>        // V is vector of complex
    void FFT(V& input, const V& table, std::size_t total_size)
    {
        if (input.size() <= 1) {
            // The Fourier transform on one element does not do
            // anything, so nothing needed here.
            return;
        }

        const auto n2 = input.size() / 2;

        // Split up the input in even and odd components
        V evenComponents;  evenComponents.reserve(n2);
        V oddComponents;   oddComponents.reserve(n2);

        for (std::size_t i = 0;  i < input.size();  ) {
            evenComponents.push_back(input[i++]);
            oddComponents.push_back(input[i++]);
        }

        // Transform the even and odd input
        FFT(evenComponents, table, total_size);
        FFT(oddComponents, table, total_size);

        // Use the algorithm from Danielson and Lanczos
        for (std::size_t i = 0;  i < n2;  ++i) {
             // ω_n^i = (ω_N^(N/n))^i = ω_N^(Nk/n)
            auto const plusMinus = table[total_size / n2 * i] * oddComponents[i];
            input[i] = evenComponents[i] + plusMinus;
            input[i + n2] = evenComponents[i] - plusMinus;
        }
    }
}

/*
  Fast Fourier transform
  T is the precision level: float, double, long double.
  Overwrites the input.
  Only works for input sizes that are a power of 2.
*/
template<typename T>
    requires std::is_floating_point<T>
void FFT(std::vector<std::complex<T>>& input)
{
    if (input.size() == 0) {
        throw std::invalid_argument("input is empty");
    }
    if (input.size() & (input.size() - 1)) {
        throw std::invalid_argument("input length is not a power of two");
    }

    auto const table = internal::rootsOfUnity<T>(input.size());
    internal::FFT(input, table, input.size());
}

// Test program
#include <iostream>

int main()
{
    static constexpr size_t n = 1048576;
    std::vector<std::complex<double>> input;
    for (std::size_t i = 0;  i < n;  ++i) {
        input.emplace_back(i);
    }

    // Overwrite input with its Fourier transform
    FFT<double>(input);

    // use the result, to avoid optimising out
    std::cout << input[0] << '\n';
}


Calling a button's OnClick method elsewhere - Good Practice?

I'd suggest something like the following which is simple enough for even a novice like me to understand. Is there a real need to simulate button click? You're not testing buttons, are you?

// OnClick="ThisButton_OnClick" for ThisButton
protected void ThisButton_OnClick(object sender, EventArgs e)
{
    // do stuff
    if(condition)
        DoStuffThatButtonWouldDo(arg);
    else
        // do stuff
}

// OnClick="ThatButton_OnClick" for ThatButton
protected void ThatButton_OnClick(object sender, EventArgs e)
{
    DoStuffThatButtonWouldDo(arg);
}

private static DoStuffThatButtonWouldDo(fancy arguments)
{
    //TODO: do all the stuff that the that button would do
}


You have:

direction: Direction = {self.position + d: d for d in Direction}[path_to_destination[1]]

The dict is just mapping each key to key - self.position (I don't know your exact data models, but I'm going to assume that these are some kind of vector and that + and - behave in intuitive ways).  Hence:

direction = path_to_destination[1] - self.position

and maybe:

assert abs(direction) == 1

if you want to require that direction is a unit vector (again, I'm assuming your vector representation is reasonable and implements __abs__ to return the magnitude).


Public Function GetFilteredTableRange(ByRef targetTable As ListObject, Optional ByVal includeHeaders As Boolean = False)
    '/ given a table, return a range object that contains only those rows which are visible
    '/ Do this by looping through tableRows, adding all visible rows to a unionRange

Newlines
are
cheap.

In Python, you always aim to keep your lines shorter than 80 characters long. I personally think it's a good practice to keep that size as a guideline in other languages as well. Your first line is 120, 1.5x my proposed maximum.

Added benefit of trying to stick with a maximum is it keeps you sharp. You're forced to think whether it's absolutely necessary for that line to be that long. Long lines are not fun to read, so try not to make them longer than necessary.

Public Function GetFilteredTableRange( _
    ByRef targetTable As ListObject, _
    Optional ByVal includeHeaders As Boolean = False _
)
    '/ Given a table, return a range object with only the visible rows.
    '/ Do this by looping through tableRows,
    '/ adding all visible rows to a unionRange.

That's how I'd do it, but I'm not up to par with VBA coding standards.


Magic values
Your code compares to "1" and "2". What are these values supposed to convey? Use constants to signify what they mean.
Data structure
Your data structure is not great for the task you are trying to accomplish. Why not use a list containing car types? Why not at least split the data based on cars and trucks, so you can get away with just using Object.keys(data.cars).length or even a simple reduce?
{
    "cars" : {
         "car1": "2",
         "car2": "0"
    },
    "trucks" : {
         "truck1": "0",
         "truck2": "1"
    }
}

or
{
    "cars": [
        {
            "type": "car1",
            "status": "broken"
        },
        {
            "type": "car2",
            "status": "contains 4 wheels"
        }
    ],
    "trucks": [
        //you get the point
    ]
}


Rigidness and verbose nature of XML parsing

In your code I do agree there more redundancy than I like to see. I would suggest writing some helper functions, and perhaps leveraging exceptions instead of return codes (I won't show that here).

const char* FirstChildElementText(tinyxml2::XMLElement *parent, const char *child_name)
{
    auto child = parent->FirstChildElement(child_name);
    return (child != nullptr) ? child->GetText() : nullptr;
}
: : :
for (child = root->FirstChildElement(); child != nullptr; child = child->NextSiblingElement()) {
    auto game_name = FirstChildElementText(child, "name");
    auto game_system = FirstChildElementText(child, "system");
    auto game_status = FirstChildElementText(child, "status");

    if (game_name == nullptr || ...)
    : : :
}

This helps a bit. Always be on the lookout for a good refactoring. Even if you already found a better XML library for your needs.

(I have things I dislike about both DOM and SAX style XML parsing, either being too lenient or too much work. Really, all in all, I suspect that directly working with XML is approaching things from the wrong level. But I don't have a great solution, so I'll get off my soap box.)


Product of 2 numbers equals sum of numbers between them

Some notes:

Use 2 spaces for indentation.
mul = 0 No need to define variables in Ruby.
@x = x. @name is a instance variable, but there is no class here. Use only local variables.
(1..n).reject {|n| n == x || n == y}.inject(&:+). That's very slow, you should pre-compute the sum before, and just subtract the two elements in every loop.
last_arr << (@x,@y = @y,@x). Only the last pair is reversed?
Make functions/methods return something.
You can use the simple formula n * (n + 1) / 2 for the sum of (1..n).
Your code is very, very imperative. For mathematical problems (if not for all), favor a functional style (immutable data-structures)

I'd write:

def get_pairs(n)
  range_sum = (n * (n + 1)) / 2
  pairs = (1..n).to_a.combination(2)
  matching_pairs = pairs.select { |x, y| x * y == range_sum - x - y }
  matching_pairs.flat_map { |x, y| [[x, y], [y, x]] }
end

p get_pairs(26) #=> [[15, 21], [21, 15]]

With n = 500 it takes ~0.1s in my machine. If this is not still fast enough, you can still filter out pair values on the range that are too small to possibly match the sum range.


Ajax request URL with the Google Maps API

You may want to put your query string into the data property of your XHR request in order to clean up your request as well.

$.ajax({
  url: "https://maps.googleapis.com/maps/api/distancematrix/json",
  type: "GET",
  data: {
    origins: $("#origin").val(),
    destination: $("#destinations").val(),
    mode: "driving",
    key: "AIzaSyASanevdiCI4t1h8LMf5FgWHMD52K3QeB0"
  },
  success: function(data) {
    console.log(data);
  }
});


I don't know Kivy, so here are a few general style tips.

First, order you imports. Don't also import everything directly; it's OK to use namespaces. I would probably import as so:

import random

from kivy import app
from kivy.uix import boxlayout, button, popup, textinput
from kivy.core.window import Window

A minor point is that the class name would read much better as IsPrimeApp.

Your get_font is misnamed; it should be get_font_size. The equation is also rather strange; it's infinitely large at size 10, negatively sized at size 11 and you end up very negative sizes to get small fonts. It's also advisable to use formatting over concatenation.

I would suggest something like:

def font_size(size):
    return "{}sp".format(avg(Window.size) / 32 * 1.5 ** size)

I really suggest against wrapping lines like:

number_input = textinput.TextInput(
    text=str(random.randint(5, 10 ** 10)), font_size=font_size(3))

This seems immensely more readable:

number_input = textinput.TextInput(
    text=str(random.randint(5, 10 ** 10)),
    font_size=font_size(3)
)

or any other semantic equivalent (take your pick).

It's potentially better to just reorganize so you don't have to:

default_input = str(random.randint(5, 10 ** 10))
number_input = textinput.TextInput(text=default_input, font_size=font_size(3))

Please don't go naming things parent or btn; give them semantically useful, even if more verbose names.

parent → root
btn → is_prime_btn
callback → check_primality

Move things into separate methods. build does not need to contain a lot.

It seems buttons don't need a bind call; you can just add an on_press in the constructor.

I would consider explicitly making phases where you declare what boxes are where and what contains what.

Your isprime is a "confused" function, and its name doesn't really explain its functionality. I would separate the actual core behaviour (which is buggy for negative numbers) from generating a response. This is more reusable than just adding CONSTANTS, and it's cleaner.

Here's a cleaned up version:

import random

from kivy import app
from kivy.uix import boxlayout, button, popup, textinput
from kivy.core.window import Window

def is_prime(n):
    if n == 2:
        return True

    if n < 2 or not n % 2:
        return False

    sqrt_n = int((n ** 0.5) + 1)

    return all(n % i for i in range(3, sqrt_n, 2))

class IsPrimeApp(app.App):
    def font_size(self, size):
        return "{}sp".format(sum(Window.size) / 64 * 1.5 ** size)

    def check_primality(self, instance):
        def response():
            try:
                n = int(self.number_input.text)
            except:
                 return "Enter a number"

            if n > 10 ** 17:
                return "The number must be less than 10^17"

            elif is_prime(n):
                return "Yes, {} is prime".format(n)

            else:
                return "No, {} is not prime".format(n)

        content = boxlayout.BoxLayout(orientation="vertical")

        response = button.Label(
            text=response(),
            font_size=self.font_size(0)
        )

        question = popup.Popup(
            title='Is the number prime?',
            content=content,
            size_hint=(1, 1),
            font_size=self.font_size(2)
        )

        dismiss = button.Button(
            text="OK",
            font_size=self.font_size(2),
            on_press=question.dismiss
        )

        content.add_widget(response)
        content.add_widget(dismiss)

        question.open()

    def build(self):
        root = boxlayout.BoxLayout(orientation="vertical")

        self.number_input = textinput.TextInput(
            text=str(random.randint(5, 10 ** 10)),
            font_size=self.font_size(3)
        )

        is_prime_btn = button.Button(
            text='Is prime?',
            font_size=self.font_size(3),
            on_press=self.check_primality
        )

        root.add_widget(self.number_input)
        root.add_widget(is_prime_btn)

        return root

if __name__ in ('__main__', '__android__'):
    IsPrimeApp().run()

It's not markedly different, but I would argue that without using a declarative approach to layout there isn't much more you can do. 61 SLOC isn't a lot, and most are dedicated to declaring properties about the buttons, such as strings.


Usually Python is not terribly fast when it comes to "hand-written" loops. So my prediction (also supported by some preliminary profiling using timeit, see below) would be that a "hand-written" loop is slower than the C loop used in the implementation of set.intersection. The effect should/will become more significant for larger lists.

A quick non-performance related note: you can substitute l[i+1:len(l)] by l[i+1:]. This is because the end of a slice defaults to the end of the sequence.

import timeit

SETUP = """
l = [10, 7, 11, 3, 5, 11]
k = 22

diff = {k-x for i, x in enumerate(l) if k != 2*x or x in l[i+1:]}
"""
print(
    sum(timeit.repeat("bool(diff.intersection(l))", setup=SETUP,
                      repeat=10, number=100000)) / 10
)
print(
    sum(timeit.repeat("bool([i for i in l if i in diff])", setup=SETUP,
                      repeat=10, number=100000)) / 10
)


Asp.Net Custom Server Control: PostBack handling

You can just expose hiddenField.Value in the property.

public bool Property
{
    get
    {
        EnsureChildControls();
        return Convert.ToBoolean(hiddenField.Value);
    }
    set
    {
        EnsureChildControls();
        hiddenField.Value = value.ToString();
    }
}

Property will expose the current value on postback by it self.

You could also expose an event on your control that you refire in the ValueChanged event of the hidden field.

public event EventHandler PropertyChanged;

...

void hiddenField_ValueChanged(object sender, EventArgs e)
{
    ContentPanel.Visible = Property;
    if (PropertyChanged != null) PropertyChanged(this, EventArgs.Empty);
}

I moved the visibility here since it's more related to the value changing than the property itself.


There are no tests. That means that all of the changes I show compile, but may not do what I say. Rust makes is very easy to write basic tests, so I'd encourage you to write them. Especially as you are learning a new language and especially when you ask for feedback or refactor the code.
You should never ignore Results. If you don't believe it's possible for an error to occur, use unwrap to cause the program to abort on error. Even better would be to use try! to return an error in case of error.
Result::Ok(()) is duplicated at the end of each method; move it after the match.
Result::Ok is imported via the prelude, you can just say Ok.
Multiple consecutive fmt calls can be combined with the write! macro and a format string.
Instead of using to_string, embed the write! call inside the match arms. Then there are no additional heap allocations.
Consider dealing with the middle commas in a different way. Pop off the first element, then unconditionally add the comma for all subsequent ones. Theres a possibility of performance difference here, so you should test.
Consider using an Option instead of creating a Null type. Option is a pervasive type from the standard library and people innately know how to use it.
I think you will have a bug if a string contains embedded quotes, as there's no escaping happening.

use std::fmt;

pub enum Json {
    Obj(Vec<(String, JsonVal)>),
    Arr(Vec<JsonVal>),
}

pub enum JsonVal {
    Str(String),
    Num(f64),
    Composite(Json),
    Bool(bool),
    Null,
}

impl fmt::Display for Json {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            Json::Obj(ref obj) => {
                try!("{".fmt(f));
                let mut props = obj.iter();
                if let Some(prop) = props.next() {
                    try!(write!(f, r#""{}":{}"#, prop.0, prop.1));
                }
                for prop in props {
                    try!(write!(f, r#","{}":{}"#, prop.0, prop.1));
                }
                try!("}".fmt(f));
            }
            Json::Arr(ref arr) => {
                try!("[".fmt(f));
                let mut items = arr.iter();
                if let Some(item) = items.next() {
                    try!(item.fmt(f));
                }
                for item in items {
                    try!(write!(f, ",{}", item));
                }
                try!("]".fmt(f));
            }
        }

        Ok(())
    }
}

impl fmt::Display for JsonVal {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            JsonVal::Str(ref string) => write!(f, r#""{}""#, string),
            JsonVal::Num(number) => number.fmt(f),
            JsonVal::Composite(ref json) => json.fmt(f),
            JsonVal::Bool(boolean) => boolean.fmt(f),
            JsonVal::Null => "null".fmt(f),
        }
    }
}

fn main() {

}

  the warning suppression before the implementation of the Display trait

We mentioned this one already; good call on thinking that something was wonky here.

  In the Display implementation of JsonVal I use the format! macro to basically make a copy of the string
  In the Display implementation of JsonVal I use the String::from associated function to return the value of JSON's null.

Again, good call on both of these points. Creating an allocated object is sometimes the right thing, but in this case we can just delegate to the existing Display implementations of various types. In case you weren't aware, the {} corresponds to items that implement Display. That's what makes it possible to just call out to those.

  I put all the refs because the compiler hinted me to do so and I understand more or less that it has to do with the fact that I'm just borrowing what's inside the struct to use it

Yes, this is the right intuition. When formatting something, you don't have ownership of the item, only a reference. That means you can't take ownership of a struct member, only further references. The ref keyword in a pattern match is conceptually equivalent to taking another reference on the right side:

struct Foo(String);
let f = Foo("hello".to_string());

let String(ref s) = f;
let s = &f.0; // equivalent

The problem is that you can't always write code like the second case, like in a multi-way pattern match or in one arm of a match, so the ref keyword is needed.


Without re-writing all your code I do have a few suggestions for you:

Don't use inline javascript (onMouseeOut, onMouseOver) always use event listeners (I'll show you how the code example below).  The reason for this is twofold: first it separates your javascript from your HTML second it makes your code even more maintainable if you change a listener you have one place to look.
Use classes instead of inline styles (for the same reasons mentioned above)

this means replace the style=xxx with a css classname (again i'll have an example in the code below)

A lot of your code can be condensed into small reuseable functions since a lot of it is repetitive.

Since you are new to JavaScript I'll avoid some of of the intermediate patterns that I think may apply here such as wrapping this entire functionality in an instantly invoked function expression (IIFE) but you really should read this article by Ben Alman http://benalman.com/news/2010/11/immediately-invoked-function-expression/

So lets look at how it can be improved with some psudo code.  First Lets create one wrapper function that will encapsulate all your functionality.  First set some function variables to your links and radios.  Then we attach events for most browsers and older versions of IE, then we create two generic functions to handle your mouseenter and mouseleave. These functions will handle the duplicated logic of checking

function overOut(){
 //these variables will be accessable by all the inner functions so we only declare them once
  var fbLinks = document.links.fb,
      twLinks = document.links.tw
      fbLink = document.getElementById('fb_link'),
      twLink = document.getElementById('tw_link');

  //check for standard event listener
  if(fbLink.addEventListener){
    //here i'm assuming that fblinks are the links you want to highlight
    fbLink.addEventListener("mouseover",radioOverFunction(this,fbLinks));
  }
  //ie events
  else if(fbLink.attachEvent){
    //here i'm assuming that fblinks are the links you want to highlight
    fbLink.attachEvent("mouseover",radioOverFunction(this,fbLinks));
  }

  /***************************************************
  *  repeat the above code but for mouseout events   *
  ***************************************************/

  var radioOverFunction = function(radio,target){
      //in here you would set check the radio and set the classname on the target
      target.className = 'mouseOverClassName';
  };

  var radioLeaveFunction = function(radio,target){
      //in here you would set check the radio and set the classname on the target
      target.className = 'standardClassName';
  }

}


Yes dirty, buggy, and bad.

There are several problems with your code. You have undeclared variables, do not protect against iterating over unintended enumerable array properties, redundant code, inappropriate object types, and unneeded iteration.

Undeclared variable.

You use the variable obj without declaring it. It is thus created in global scope and available to any function. This can result in difficult to spot bugs and unexpected behaviour.

Always on the first use of a variable declare it with one of JavaScript's variable types var, let, or const. In this case I will not say which type to use as the variable obj is badly used and inappropriate for the situation.

Use strict

To save you from ever make this mistake again you should add to the first line of any javascript file or script tag the line

"use strict";

this will enforce some stricter parsing standards and help you avoid making mistakes such as "forgetting to declare". It also has the benefit of running your code quicker.

Which way to iterate.

There are many ways in javascript to iterate over a set of items in arrays, objects, iterable objects, and array like objects. Using built in statements for, for...in, for...of, while, do...while, and more

The one you use is about the worst for the situation. The problem with for...in is that it will iterate over all the arr/object enumerable properties, including properties that are inherited via the object's prototype.

This means you can get almost anything for each iteration, and thus need to check every item to see if it is what you intend to be handling, and if it belongs to the object or has it be inherited from another. This is just a pain, so much so I never use it.

For your code you should have used

for(const el of arr){

Which does what you intended without the risk of getting unknown properties.

Dont burn cycles

Good code is efficient code, with every instruction the computer executes in your code, you burn power, sucked from batteries, the grid, You chew the clients time and you extract a little more from the environment we share as a comunity.

Yes your code is trivial in the scheme of things, immeasurable, but combined millions of programmes, or with fortune on your side an app you write  may end up on billions of devices, and particular parts of your code may execute trillions of times a minute. Then it matters.

Always (I digress, no rant... :P) code for efficiency, even the little bits combined matter.

Your code could have exited early as the problem states that there is only one set of odd numbers in the array. So as soon as you find the odd set, the job is over and you should exit. On average you will do a quarter as much processing overall. On average you could do up to a quarter less processing overall.

Use appropriate Objects.

You are using obj as a map, for each unique key (number) you create an entry and use the associated value to count the number of keys. Though technically not wrong javascript provides a object Map that is better suited (see rewrite)

The rewrite

If the array of numbers was known to be sorted or numbers were grouped then a different solution could be used that is more efficient, But as there is no mention of the array being sorted or numbers grouped apart from the sample data the best is to play safe and assume unsorted data.

Some may opt to sort the array to take advantage of the better solution, but the sort is expensive and would offset any benefits the more efficient method would give.

UPDATE I miss read the question and thought that counts of one were to be excluded. I have changed the code via commenting out the incorrect behaviour.

function findOdd( arr ) {
    const counts = new Map();
    // find each unique number and count the entries
    for (const num of arr) {
        const item = counts.get(num); // get entry with key = num
        if (item !== undefined) {     // does it exist
            counts.set(num, item + 1);          // yes count one more
        } else {
            counts.set(num, 1);       // no so add and set count at 1
        }
    }
    // all items in the array have been checked so find the first with odd count
    for (const [num, count] of counts) {
        if (/*count > 2 &&*/ count % 2) { // See update in answer re comment
            return num; // we have found what we are looking for
        }
    }
    // the problem suggests that there is always an odd set so this
    // line will never be reached.
}

Sorted version

Just for the exercise I have included the more efficient code that assumes the array of numbers is sorted or that numbers are in groups.

function findOdd (arr) {
    var i = arr.length - 1;
    var count = 1;
    var prev = arr[i];
    while (i--) {
        const current = arr[i];
        if (current !== prev) {
            if (count % 2) { return prev }  // Update remove test for count > 2
            count = 1;
        } else { count += 1 }
        prev = current;
    }
}

Which on average executes in 1/3rd the time of the other method


If the script works fine for you the points about robustness below won't
matter too much.

The way PATH is defined is a bit unusual since in most cases I want
to be able to invoke the script from any directory, but this default
forces it to the directory of the script.  I'd almost say that the
normal default argument of os.listdir, namely "." is way better.
os.listdir is called too often, the result can just be reused.
Don't use list when you can have literal list syntax instead.
The output is fine I guess, except for passing it to other scripts
you'd usually want a more "standard" format, i.e. a single file per
line without quotes.

For the record missing_pages should look more like this (filtering
filenames and directories is left as an exercise though):

def missing_pages(directory="."):
    """
    Lists all the pending links of the html pages of the `directory`.
    """
    files = os.listdir(directory)
    all_pages = sorted(set(flatten(destinations(read(i)) for i in files)))
    return [i for i in all_pages if i not in files]

Otherwise looks good, test does what it says, docstrings where needed
and the script even has a top-level description.

Robustness

I ran the script on a random directory just to see what happens.  With
Python 3 I get a UnicodeDecodeError; with Python 2 it errors out on a
directory - it wouldn't hurt to skip them.  It probably should only read
files with the correct ending as well.

Next is that the regular expression to match is quite limited; it also
will not really deal with the situation where a file is mentioned, but
not linked to.  The docstring to destinations implies that the
function does more than what it can - so you could just leave out all
the HTML fluff and just mention the filenames separated by spaces; or,
actually document the corner cases, meaning I'd like to have a docstring
saying something like "Finds mentions of HTML files in a string.  Only lowercase filenames with underscores are returned." or something similar.


C++ vector that uses expression templates technique to increase performance of mathematical expressions

Generally speaking, it's pretty good. However, there are still a few things that I would have done differently:

typedef becomes kind of ugly now that we have type aliases. Always using type aliases generally tends to produce more readable and more consistent code:

using size_type = typename std::vector<T>::size_type;

Loop only when you have to. In your std::initializer_list constructor, you don't need to loop; you can use std::vector's constructor taking a pair of iterators instead:

Vec(const std::initializer_list<T>& elements):
    data(std::begin(elements), std::end(elements))
{
}

By the way std::initializer_list tends to be no more than a pair of pointers. You can take it directly by value instead of taking it by const reference.
In operator+ and operator-, I would have placed the return type into the function signature and then used the list initialization syntax in the return statement:

template<typename T1, typename T2>
auto operator+(const T1& t1, const T2& t2)
    -> VecSum<T1, T2>
{
    return { t1, t2 };
}

Whether it is better or not is debatable but when the return type is fixed, rather meaningful and arguably simple, I prefer to expose it in the signature.


You can avoid appending to vectors (which can cause re-allocation of space and can considerably slow things down in principle; though in your case of only a length 10 vector that shouldn't be noticeable) if you allocate them to the needed size initially and then assign within them.

result <- vector("numeric", 10)
# or even: result <- numeric(10)
n <- vector("numeric", 10)

for (i in 2:10)
{
  avg <- kf.nnet(data, 5, i)
  result[i] <- avg
  n[i] <- i
  cat("!!!!!!!", i, avg, "\n")
}

I'm not clear what you are asking about combing function; you can add an additional argument which is a character vector which then the code just has a series of if/elseif's checking that parameter to see which algorithm to use, if that is what you mean.


Showing activity indicator (loading image) while processing in background

There are a few things I would recommend to do.

Usually, instead of disabling the interaction events there is an extra layer on top of all views that contains the activity indicator. So, instead of adding the activity indicator directly into the viewController's view, add it in another view first with clear background color and with 0.4 alpha.
Right now the startLoading() function also sets up the activity indicator, what i would rather separate into a different function, like setupLoading()
If you want to reuse the solution on other viewControllers, create a class or a protocol at least ecapsulating the logic. Also, it is better to present it on the UIApplication's keyWindow property, than just simply adding it to viewContollers view's.
Prepare for the stopLoading() and startLoading() functions to be called from a background thread.

Finally, there are plenty of very good solutions already on the interwebs, that you could integrate into your project, like SwiftSpinner.

If you need further help, code examples, let me know and I will edit my answer.


Initializing immutable objects with a nested builder

When I think of immutable object I think of get only properties backed with readonly fields.

  public string Bar { get; private set; }

That's not a fully immutable instance you still have the private set but removing the set completely will cause problems in your implementation, because your nested Builder class relies on the fact that it can set them.

What I think is better in this case is to have a private constructor to initalize your get only properties and instead of saving some private instance of the Foo object in the Builder you can save values :

public class Foo
{
    public string Bar { get; }

    public IDictionary<string, string> Corge { get; }

    private Foo(string bar, IDictionary<string, string> corge)
    {
        Bar = bar;
        Corge = corge;
    }

    public class Builder
    {
        private string _bar;
        private readonly IDictionary<string, string> _corge = new Dictionary<string, string>();

        public Builder Bar(string bar)
        {
            _bar = bar;
            return this;
        }

        public Builder AddCorge(string key, string value)
        {
            _corge.Add(key, value);
            return this;
        }

        public Foo Build()
        {
            return new Foo(_bar, _corge);
        }
    }
}

Usage :

Foo foo = new Foo.Builder().Bar("bar").AddCorge("key", "value").Build();

The action delegate doesn't quite fit in my solution so I just removed it.

You can add the public empty constructor if you want to. I personally wouldn't  like to have static methods to create an immutable object, I prefer everything to be instance based.

One builder to rule them all..

One thing that I really don't like about your code is this

var fooBuilder = Foo.Builder.Create();
fooBuilder.Bar("baz");
var foo = fooBuilder.ToFoo();
fooBuilder.Bar("QUUX"); // bam!

You can't use the same builder to create multiple objects and it's not obvious that it will crash unless you check how the Builder class is implemented.

My solution fixes that

var fooBuilder = new Foo.Builder();
fooBuilder.Bar("baz");
var foo1 = fooBuilder.Build();
fooBuilder.Bar("QUUX"); // no bam!
var foo2 = fooBuilder.Build();


Is this a proper way to check a viewstate of type int?

I usually do like this:

return (int)(ViewState["CurrentCom"] ?? 0);


What you have here is, IMHO, excellent.

Couple nitpicks:

I don't get why RemoveAll is returning the original content instead of void - also I'm expecting an exception to be thrown in GetQueue if the specified key doesn't exist.
This part (in the Pop(string) method):

var queue = GetQueue(key);
string result = "";

Would look more consistent if written like this:

var queue = GetQueue(key);
var result = string.Empty;

Or, since it's used as an out parameter value on the next line (and therefore is compiler-enforced to be initialized after the call to TryDequeue(out string)), simply like this:

var queue = GetQueue(key);
string result;

As for the Clear extension method, there's a potential tiny little issue here - see this MSDN thread:

  ConcurrentQueue<T>'s implementation is based on a particular lock-free algorithm that doesn't permit atomically clearing of the collection, hence why no Clear method is exposed.  As such, you have two primary options.

  The first is simply to create a new ConcurrentQueue<T> instead of clearing the original, and then swap in the new for the original.

  The second is to continually remove from the collection until it's empty, e.g. T ignored; while(cq.TryDequeue(out ignored));. Which you choose is largely dependent on the needs of your application.

  The former will be faster, but you also run the risk of losing some items you didn't intend to lose (then again, if the whole point is to empty the collection, that might not matter), and it only works if you have access to all of the variables holding references to the queue.

  The latter is effective, but it runs the risk of running indefinitely if other threads are concurrently appending; it's also more expensive that simply allocating a new queue.


There are several things that I would change in your code:

Use functions

This is a good example of spaghetti code where everything is meshed together.
You should provide functions to load the mutation list, one to execute one mutation and one that executes a list of mutations.

Printing the results should also be an extra function.

Use a better mutation representation

Your internal representation for the replacements is too leaky (and maybe too easy).

What if the requirements change and you want to replace multiple character strings?

Instead you should use a structure that already does the separation of the search term, the counter and replace term.

Another problem here is that you will not be able to pass replacement indices bigger than 9 because you only take one character instead of matching a regex for the number in the middle and taking the whole number as index.

Missing error handling

Talking of indices, your program will fail when the given index is out of bounds for the input string.

Unclear input

Neither you nor the OP on SO state what the first element in the mutation string is for. I don't see it being used. It seems to duplicate some of the information of the replacement index.

Code formatting

Please improve the code formatting. Take for example this:

temp_string=temp_string[:int(index)-1]+letter+temp_string[int(index):]

I had a hard time finding the boundaries of the [] because everything is so close together. Instead try to leave space around operators/operands:

temp_string = temp_string[:int(index) - 1] + letter + temp_string[int(index):]

Misused collection

I don't see why you are using a Counter in your code. You don't seem to count anything with it and use it like an ordinary dict.

The line

for j in i:
        c[j[1]]=j[2].lower()

Looks dubious, what is it for? If there are several mutation strings with the same offset only the last one will be recorded (because it overwrites the previous ones). Is this the intended behavior?

If you do not want this behavior then why use the dict (or rather Counter) at all? You could have iterated through the mutations and directly applied them with the same result.


Perhaps you should mention that your code takes advantage of the Rearrangement inequality which states
that the scalar product of any permutation of the vectors
\$ (x_1,x_2,...,x_n) \$ and \$ (y_1,y_2,...,y_n) \$ is minimal if the elements of one vector
are in increasing order and the elements of the other in decreasing order.

I see two possible simplifications: First, instead of reading the second
vector into a temporary vector, sorting it and then reversing it "manually", you can sort in decreasing order by supplying a comparator to the sort:

for (std::size_t y_index = 0; y_index < n; ++y_index) {
    std::cin >> y[y_index];
}
sort(y.begin(),y.end(), std::greater<int>());

Second, the scalar product can be computed with

#include <numeric>

int product = std::inner_product(x.begin(), x.end(), y.begin(), 0);


There are various methods to generate a random n-word text. Markov chain is one of them.

Basic idea how to do this is described in Centennial of Markov Chains (by Oleksandr Pavlyk) under "Text Generation" - you generate n-grams carry info,  encode transitions and define a function to walk the graph (in a non-brute force manner).

Result will heavily depend on word corpus and their connections rather then algorithm implementation itself.

The real problem is actually to generate the word corpus and connections from random text. In order to do this well you need to work out the grammatical structure of sentences. Because, you do not want to be doing this manually.

For example, consider the text:

  The strongest rain ever recorded in India shut down the financial hub
  of Mumbai, snapped communication lines, closed airports and forced
  thousands of people to sleep in their offices or walk home during the
  night, officials said today.

You want to tag word grammatical structure

  The/DT strongest/JJS rain/NN ever/RB recorded/VBN in/IN India/NNP
  shut/VBD down/RP the/DT financial/JJ hub/NN of/IN Mumbai/NNP ,/,
  snapped/VBD communication/NN lines/NNS ,/, closed/VBD airports/NNS
  and/CC forced/VBD thousands/NNS of/IN people/NNS to/TO sleep/VB in/IN
  their/PRP$ offices/NNS or/CC walk/VB home/NN during/IN the/DT night/NN
  ,/, officials/NNS said/VBD today/NN ./.

To do this you can use The Stanford Parser (ruby wrapper).


As mentioned in the comments the or part of your "xor_gate" prevents it from actually working as an xor gate to calculate bit parity.

Instead your paro signal will be '0' when a=b  and '1' when a/=b (the 16 bit vectors, not the bits within xor_gate). If that was your intended functionality, then paro <= '0' when a=b else '1'; would be simpler.

Finally, it would be much clearer and cleaner to not have a whole component for such a simple operation. The following does an xor of all the bits (a typical parity calculation) and is shorter and easier to read. If I was only going to use this calculation in one or two places, I'd absorb this whole block into those as well, as it is only 6 additional lines.

library ieee;
use ieee.std_logic_1164.all;
entity parity_2 is
  port(a: in std_logic_vector (0 to 15);
       b: in std_logic_vector (0 to 15);
       paro: out std_logic
      );
end parity_2;

architecture behavior of parity_2 is
  signal parry: std_logic_vector (0 to 15);
begin

parry(0) <= a(0) xor b(0);
c: for i in 1 to 15 generate
  parry(i) <= parry(i-1) xor a(i) xor b(i);
end generate;

paro <= parry(15);

end behavior;


Maximize a traveling employee's vacation over k weeks

With this kind of problems it is important to build good mathematical model. After that, the best algorithm known to science can be easily found.

The problem in question seems to be Longest path problem, which if we build a graph properly has linear time solution.

Lets consider a graph (V, E), where V are week-offices (for example, H1, A1, B1, H2, A2, B2, ... - where H1 means home office at first week, B2 - office B at week two, and so on).

Edges are possible flights. For the example in the question we have the following edges:

H1 -> H2, H1 -> A2, H1 -> B2, H2 -> H3, A2 -> H3, B2 -> H3, H2 -> A3, H2 -> B3 (note, that there is never An -> Bn direct flights).

Here is the flights graph, which is an input, (on the left) and corresponding unrolled space-time one, for which a linear time algorithm can be found. Each node has a given weight.

Then a somewhat lengthy quotation from wikipedia:

"For instance, for each vertex v in a given DAG, the length of the longest path ending at v may be obtained by the following steps:

Find a topological ordering of the given DAG.
For each vertex v of the DAG, in the topological ordering, compute the length of the longest path ending at v by looking at its incoming neighbors and adding one to the maximum length recorded for those neighbors. If v has no incoming neighbors, set the length of the longest path ending at v to zero. In either case, record this number so that later steps of the algorithm can access it.

Once this has been done, the longest path in the whole DAG may be obtained by starting at the vertex v with the largest recorded value, then repeatedly stepping backwards to its incoming neighbor with the largest recorded value, and reversing the sequence of vertices found in this way."

Please, note, that our graph has been already topologically sorted - we know where it starts and where it ends.

A recursive algorithm can be elegant, but it's not really needed here.

This is maybe a bit unusual answer for a code review, but I strongly believe it is appropriate to point out at the possibility of a better algorithm while doing code review. I hope this is useful not only as a specific answer, but also as a good approach to apply math where it's due.

Please also note it is not necessary to memorize all possible graph and theory algorithms: At first I only had a vague idea, which became clear after some thinking and finding right terms.


This is my personal opinion, but I'd say the following:

The code should be formatted, I'd personally look at PSR-12 as this standard should be followed when possible.
move_uploaded_file doesn't protect against directory traversal. You should use basename on $_FILES['fileToUpload']['tmp_name'] and some other forms of validation
Checking the file extension with if(in_array($file_ext,$extensions)=== false) doesn't prevent a user from uploading a malicious file they could for instance use a magic byte to trick the server into thinking it's a certain type of file. You should take a look at finfo and the first example on file upload
You're create an array of errors, currently that's being checked in an if statement and is then thrown away. If you aren't planning on using it you might be better just returning out of the function early rather than continuing execution.
Depending on how unique the filename should be you might want to use something like uniqid(mt_rand(), true)
move_uploaded_file will replace a file if it already exists, you might want to check that this exists before you overwrite an existing file. Depending on your naming solution it's very unlikely to occur but under high load for long periods of time this could happen more often than you think.
You're using UPDATE users SET profile_pic = ? WHERE username = ? I'd assume that this value exists in the database as the user needs to be logged in. However, if you aren't sure if the field exists or not (I haven't seen the database) I'd personally use: INSERT INTO users (profile_pic, username) VALUES (?,?) ON DUPLICATE KEY UPDATE profile_pic=?, username=? this will insert into the table if the row doesn't exist but will update it if it does.
You've set a local variable called width and height and are comparing them to the same value. I assume this was meant to check the actual file dimensions?

I hope this helps in some way :)


Synchronization

pushMutex_ and popMutex_ aren't needed. Even worse, they prevent other threads from waiting on a condition variable! Just lock queueMutex_ instead (that also prevents having to re-lock queueMutex_).

Assume that the queue is full, and thread 1 and 2 both want to push an item into the queue. Thread 1 was faster and got the lock on pushMutex_, so it proceeds to wait on pushCV_. Thread 2 in the meanwhile spins trying to lock pushMutex_ - which is still held by thread 1!

Avoid using std::condition_variable::notifiy_one() while still holding the corresponding lock! The notified thread will wake up, and the first action it has to do is reacquiring the lock that is still hold by the caller of notify_one(), so it will instantly block again (this time on acquiring the lock though, not wait()).

Implementation

The outer scopedLock in push() and pop() get shadowed by the inner scopedLock. This can lead to extra confusion in an already complex code!

Since MAX_SIZE isn't supposed to change once the object is initialized, consider marking it as const. (It can still be set with the initialization list of the constructor, but not changed afterwards.)

Further considerations

Maybe add fast returning bool try_push(const T&) and bool try_pop(T&) member functions, so users of the queue don't have to wait if they don't need to?


The main thing that I feel you should change is the heap allocations inside the processBlock(). With realtime processing like this audio application you never want to call new/delete within time critical code, either yourself (or indirectly like adding a vector, vector.resize() etc. etc.) The reason it's unpredictable how long a new/delete will take.

You have two lines that call new either directly/indirectly

Complex *copy = new Complex[inFramesToProcess];
CArray data(copy, inFramesToProcess); // indirect call of new

The solution is to create work areas beforehand as a member variable. This is created to be the right size at setup time before playback then the processBlock() can write to it as it wants.

So data (now renamed fftData) is outside as a member variable...

Edit: better solution below!

#include <complex>
#include <valarray>

typedef std::complex<double> Complex;
typedef std::valarray<Complex> CArray;

class FrequencyShifter {

float sampleRate;
const int guessInFramesToProcess;
CArray fftData;

public:
    FrequencyShifter()
        : guessInFramesToProcess {512}, // best guess at what the num samples per block will be
                                        // or is there a prepareToPlay function that you can
                                        // send in the blocksize before user hits play?
          fftData {Complex(0.0, 0.0), inFramesToProcess}
    {
    }
    void setSampleRate(float inSampleRate) { // something like this but for blocksize???
        sampleRate = inSampleRate;
    }
    void fft(CArray& x)
    {
        const size_t N = x.size();
        if (N <= 1) return;

        // divide
        CArray even = x[std::slice(0, N/2, 2)];
        CArray  odd = x[std::slice(1, N/2, 2)];

        // conquer
        fft(even);
        fft(odd);

        // combine
        for (size_t k = 0; k < N/2; ++k)
        {
            Complex t = std::polar(1.0, -2 * PI * k / N) * odd[k];
            x[k    ] = even[k] + t;
            x[k+N/2] = even[k] - t;
        }
    }
    void processBlock(float *inBlock, const int inFramesToProcess, float scale) {

        /* now there are no heap allocations in the time-critical processBlock */

        fillFftData(inBlock, inFramesToProcess, fftData);       // function that declares intent

        fft(fftData);

        const float freqoffsets = 2.0 * PI/ inFramesToProcess;  // below is quite hard to figure out
        const float normfactor  = 2.0 / inFramesToProcess;      // your intent. maybe functions
                                                                // like below?
        for (int frame = 0; frame<inFramesToProcess; frame++) {
            inBlock[frame] = 0.5 * fftData[0].real();
            for (int x = 1; x < fftData.size() / 2; x++) {
                float arg = freqoffsets * x *frame*scale;
                inBlock[frame] += fftData[x].real()*cos(arg) - fftData[x].imag()*sin(arg);
            }
            inBlock[frame] *= normfactor;
        }
    }
private:
    // probably good to make little functions like this in your processBlock
    // so you can easier debug later. here's an example
    void fillFftData(float* inBlock, const int inFramesToProcess, CArray& data) {
        for (int frame = 0; frame<inFramesToProcess; frame++) {
            data[frame] = Complex(static_cast<double> (inBlock[frame]), 0.0);
        }                       // static cast ugly but preferred to c-style casts
    }                           // for better compiler checking
};

Now the issue is with how do you tell in advance what the blocksize is going to be i.e. inFramesToProcess ?

The way the code stands now, it may not work because we need some way to let the host tell us the blocksize before we actually start processing the audio in processBlock().

We need this because now the fftData needs to be fully resized the same as the blocksize (and filled with zeros) before during the setup time.

Is there a function that you can hook into that will tell your plugin what the expected blocksize will be?

(Sorry I'm a JUCE user I don't know the specifics of what framework you're using but for example in JUCE there's a function called prepareToPlay(int sampleRate, int expectedBlockSize) that gets called before processing the audio with processBlock(), this would be a perfect place to resize and zero fftData).

Hopefully you can figure this bit out!

Some smaller points

Not sure you need to copy into the buffer then into the fftData? Seems unnecessary. (If you need it, again, allocate the buffer beforehand).
If you split your code into small functions with good names that state the purpose, then it's easier to come back to your code in a few months time :)
Try and avoid C-style casts in C++ as the compiler 'knows' what's going on better with a static_cast.

The main point is really the heap allocations in the processBlock(). Only after it might be time to look at implementing and benchmarking the FFT performance vs. Apple Accelerate vDSP :)

There are other things you should avoid in time critical code too, for more info see this section of this talk...

CppCon 2015: Timur Doumler “C++ in the Audio Industry”

EDIT: Just overcompensate the FFT data buffer.

Sorry I wasn't thinking clearly about the issue previously! The simplest way around this issue is to make fftData larger than you could possibly need i.e. larger than the largest possible block size, then if a smaller block size is actually dealt with in processBlock(), it will only access the start of the buffer. Note how we are now sending the block size through to fft() and now iterating over currentInFramesToProcess (since fftData.size() is overcompensated).

#include <complex>
#include <valarray>

typedef std::complex<double> Complex;
typedef std::valarray<Complex> CArray;

class FrequencyShifter {

float sampleRate;
const int largestPossibleInFramesToProcess;
CArray fftData;

public:
    FrequencyShifter()
        : largestPossibleInFramesToProcess {2048}, // best guess, could add more for safety
          fftData {Complex(0.0, 0.0), largestPossibleInFramesToProcess}
    {
    }
    void setSampleRate(float inSampleRate) {
        sampleRate = inSampleRate;
    }
    void fft(CArray& x, int currentInFramesToProcess)
    {
        const size_t N = currentInFramesToProcess;
        if (N <= 1) return;

        // divide
        CArray even = x[std::slice(0, N/2, 2)];
        CArray  odd = x[std::slice(1, N/2, 2)];

        // conquer
        fft(even);
        fft(odd);

        // combine
        for (size_t k = 0; k < N/2; ++k)
        {
            Complex t = std::polar(1.0, -2 * PI * k / N) * odd[k];
            x[k    ] = even[k] + t;
            x[k+N/2] = even[k] - t;
        }
    }
    void processBlock(float *inBlock, const int inFramesToProcess, float scale) {

        /* now there are no heap allocations in the time-critical processBlock */

        fillFftData(inBlock, inFramesToProcess, fftData);       // function that declares intent

        fft(fftData, inFramesToProcess);

        const float freqoffsets = 2.0 * PI/ inFramesToProcess;  // below is quite hard to figure out
        const float normfactor  = 2.0 / inFramesToProcess;      // your intent. maybe functions
                                                                // like below?
        for (int frame = 0; frame < inFramesToProcess; frame++) {
            inBlock[frame] = 0.5 * fftData[0].real();
            for (int x = 1; x < inFramesToProcess / 2; x++) {
                float arg = freqoffsets * x * frame * scale;
                inBlock[frame] += fftData[x].real()*cos(arg) - fftData[x].imag()*sin(arg);
            }
            inBlock[frame] *= normfactor;
        }
    }
private:
    // probably good to make little functions like this in your processBlock
    // so you can easier debug later. here's an example
    void fillFftData(float* inBlock, const int inFramesToProcess, CArray& data) {
        for (int frame = 0; frame < inFramesToProcess; frame++) {
            data[frame] = Complex(static_cast<double> (inBlock[frame]), 0.0);
        }                       // static cast ugly but preferred to c-style casts
    }                           // for better compiler checking
};

This would get you by for now.

The 'best practise' would be to make your FFT size independent of whatever the processBlock() size is. That way if the user changes the soundcard block settings, they will still hear the same thing. i.e. lock FFT to size 1024, soundcard block size processBlock() variable 64-512

This is accomplished with a circular buffer of size 1024, you fill this up sample by sample with input, then when it's full you call fft() on those 1024 samples.

Hope these are all helpful tips to get started!


Print the string equivalents of a phone number

You're working way too hard:

itertools.product() produces cartesian products.
You don't need to convert strings to lists; you can iterate over strings directly.
Lookups are better done using a dictionary than a chain of if statements.

from itertools import product

KEYPAD = {
                 '2': 'abc',  '3': 'def',
    '4': 'ghi',  '5': 'jkl',  '6': 'mno',
    '7': 'pqrs', '8': 'tuv',  '9': 'wxyz',
}

def convert_num(number):
    letters = [KEYPAD[c] for c in number]
    return [''.join(combo) for combo in product(*letters)]

print(convert_num('234'))


Report for a restaurant showing hourly sales information for a given timespan

Style

First, I like the compact style of the CTEs, and putting the closing
parentheses on the same line. I would say, though, that I find the
select statements a bit hard to read.  Especially the main one.

Use prefix aliases for columns

This is not standard SQL, but t-sql can do this: prefix aliases.
In general, when writing long expressions, it gets harder to read
the query and to find what you are looking for.  So:

SELECT DATEPART(hour, OrderCloseTime) AS Hour,
       OrderType,
       SUM(OrderGuests) AS GuestCount,
       ROUND(CASE WHEN SUM(OrderGuests) = 0 THEN 0 ELSE SUM(OrderSubTotal) / SUM(OrderGuests) END, 2) AS AvgPerGuest,
       SUM(OrderSubTotal) AS Subtotal,
       ISNULL(SUM(Coupons), 0) * - 1 AS Coupons,

can be more clear when you write it as

SELECT Hour = DATEPART(hour, OrderCloseTime)
     , OrderType
     , GuestCount = SUM(OrderGuests)
     , AvgPerGuest = ROUND(CASE WHEN SUM(OrderGuests) = 0 THEN 0 ELSE SUM(OrderSubTotal) / SUM(OrderGuests) END, 2)
     , Subtotal = SUM(OrderSubTotal)
     , Coupons = ISNULL(SUM(Coupons), 0) * - 1

You can even make it a bit more fancy and align the = signs, which
could improve readability if the expressions are much alike
(differences stand out more clearly), but would be harder to maintain.

Order columns consistently

Not just in the GROUP BY, but also in the SELECT list.  This
especially makes sense when you join on them: list the primary
key(s) in a consistent order.  This may be a minor pick, but it
helps when reviewing; when you see them at the top, you won't miss
them.  For now, I'm guessing that OrderTrackDate is a combined
key with OrderNum and that neither of them is unique by itself.

   WITH TempGiftCard AS
(SELECT OrderTrackDate
      , OrderNum
      , GiftCardsSold = SUM(ItemPrice)
   FROM RMArchive.dbo.OrderItems
  WHERE ItemName = 'GIFT CARD'
    AND OrderTrackDate BETWEEN '12/7/2015' AND '12/8/2015'
  GROUP BY OrderTrackDate, OrderNum)
      , TempPayment AS
(SELECT OrderTrackDate
      , OrderNum
      , Coupons = SUM(CASE WHEN PaymentCoupon = - 1 THEN PaymentAmount ELSE 0 END)
      , Promo   = SUM(CASE WHEN PaymentPromo  = - 1 THEN PaymentAmount ELSE 0 END)
   FROM RMArchive.dbo.Payment
  WHERE OrderTrackDate BETWEEN '12/7/2015' AND '12/8/2015'
  GROUP BY OrderTrackDate, OrderNum)

Use the ISO 8601 date format

At first when I read the query, I thought you accidentally queried
data for a whole month, but I guess I am used to the DD-MM-YYYY
format.  You might want to check whether the date format settings
of the database are correct, so that SQL interprets the strings
correctly.

If that setting may vary, you can always fall back on the ISO
notation, which will be interpreted correctly.

AND OrderTrackDate BETWEEN '2015-12-07' AND '2015-12-08'

If, for whatever reason, the OrderTrackDate column is
a char(10) instead of a date, you will certainly have queried a
whole month.  In that case, you would probably need to do something
with convert.  And as that does not index well, you might need to
SELECT the result of that convert into another table, first.

Use variables as constants or parameters

Both dates are specified three times.  If you declare two variables
at the top, you need to change them only in one place.  You could
also more easily use them as parameters if you go and implement the
query as a stored procedure or as a script you call from another
client (a client application you might write or maintain later).

DECLARE @startDate date = '2015-12-07';
DECLARE @endDate date = '2015-12-08';
-- ...
   AND OrderTrackDate BETWEEN @startDate AND @endDate

CTEs are not per definition more efficient

See also this excellent answer.  Syntactically, it looks so much
nicer to write a CTE instead of a temp table (which also needs
cleanup), but they are quite different to the SQL Server that has to
execute them.

In this case, it would probably help to rewrite both of the CTEs to
temp tables first, then join on them in the final query.

IF OBJECT_ID(N'tempdb..#TempGiftCard') IS NOT NULL DROP TABLE #TempGiftCard;
SELECT OrderTrackDate
     , OrderNum
     , GiftCardsSold = SUM(ItemPrice)
  INTO #TempGiftCard
  FROM RMArchive.dbo.OrderItems
-- ...

I cannot test this without table definitions, but I would not be
surprised if this helped performance.


Function that enables fields based on checkbox state

It's difficult to answer accurately without seeing your markup, but maybe you can use a multiple selector to alleviate code redundancy. You can also use prop() to enable or disable your elements more easily:

$(function() {
    var $elements = $("#amount, #period, #key");
    $elements.prop("disabled", true);
    $("#api").change(function() {
        $elements.prop("disabled", !$("#apiEnabled").is(":checked"));
    });
});


Spreadsheet to calculate how to cut pipes

You didn't declare y or x.

Always turn on Option Explicit. You can have it automatically by going to Tools -> Options in the VBE and checking the Require Variable Declaration option. This way if you have any variables not defined, the compiler will let you know.

When you don't define your variable, VBA will declare it as a Variant type that can hold any type of data. While this may be more flexible, it adds processing time to your macro as VBA decides or tests for the type.

Additionally, since a Variant can be any type of data, you may miss out on valuable troubleshooting information on Type Mismatch

By not declaring variables, you could possibly be paying a penalty.

It's good practice to indent all of your code that way Labels will stick out as obvious. You also have a ton of unneeded white space. To begin, it might look like this:

Option Explicit

Sub CalcPipe()
    Dim StartPipeLng As Long, LastLng As Long, TotalLng As Long, PipeName As Long
    StartPipeLng = Cells(2, 4).Value
    LastLng = ActiveSheet.UsedRange.Rows(ActiveSheet.UsedRange.Rows.Count).Row
    TotalLng = Application.WorksheetFunction.SumProduct(Range("A2:A" & LastLng), Range("B2:B" & LastLng))
    TotalLng = Application.WorksheetFunction.RoundUp(TotalLng / StartPipeLng, 0)
    Cells(5, 4).Value = TotalLng
    PipeName = 1
    Dim y As Long
    Dim x As Long
        For y = 6 To TotalLng + 5
            Cells(1, y).Value = "Pipe " & PipeName
            PipeName = PipeName + 1
            StartPipeLng = Cells(2, 4).Value
            For x = 2 To LastLng
                If StartPipeLng - Cells(x, 1).Value >= 0 And Cells(x, 2).Value <> Cells(x, 3).Value Then
                    StartPipeLng = StartPipeLng - Cells(x, 1).Value
                    Cells(x, 3).Value = Cells(x, 3).Value + 1
                    Cells(x, y).Value = Cells(x, y).Value + 1
                    x = x - 1
                End If
            Next x
        Next y
    Columns(3).Clear
End Sub

Variable names - give your variables meaningful names.
Standard VBA naming conventions have camelCase for local variables and PascalCase for other variables and names.

Dim initialPipeLength As Long
Dim lastPipeRow As Long
Dim totalPipes As Long
Dim pipeNumber As Long
Dim rowCounter As Long
Dim y As Long

A loop like this -

For x = 2 To lastPipeRow
    If firstPipeRow -  Then
        x = x - 1
    End If
 Next x

Could probably just be

For x = lastPipeRow to 2 Step -1
Next

But, since it's not a standard loop and that won't work, you should use variable names to make it more obvious what is happening there.

There is a standard way to find lastRow and lastColumn. That post explains why.

lastPipeRow = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Row

Also, since you reuse your range, I'd add something to catch if you're accidentally overwriting data

Dim result As VbMsgBoxResult
If Not IsEmpty(ActiveSheet.Cells(1, 6)) Then
    result = MsgBox("There is still data on this sheet, do you want to overwrite it?", VbMsgBoxStyle:=vbYesNo)
    If result = vbNo Then Exit Sub
End If

I'd also clear out old data

If Not IsEmpty(ActiveSheet.Cells(1, 6)) Then
    result = MsgBox("There is still data on this sheet, do you want to overwrite it?", vbYesNo)
    If result = vbNo Then Exit Sub
    Dim lastColumn As Long
    lastColumn = ActiveSheet.Cells(1, Columns.Count).End(xlToLeft).Column
    ActiveSheet.Range(Columns(6), Columns(lastColumn)).Clear
End If

To avoid using column 3, use an array. But, I'd say since you want to use an array, you could optimize your solution to the cutting stock problem with the Greedy algorithm.


Simple calculator implemented with lambdas

Don't use String labels of GUI elements in flow control

It's not good to use the String labels of GUI elements to make decisions.
It would be slightly better if you made "Sum", "Difference", ... global constants, but only slightly.

An enum would be better for this purpose:

enum Operation {
    Sum("Sum", (x, y) -> x + y),
    Difference("Difference", (x, y) -> x - y),
    Product("Product", (x, y) -> x * y),
    Quotient("Quotient", (x, y) -> x / y),
    Exponent("Exponent", Math::pow)
    ;

    private final String label;
    private final Equation equation;

    private Operation(String label, Equation equation) {
        this.label = label;
        this.equation = equation;
    }

    @Override
    public String toString() {
        return label;
    }
}

With this, you could create the JComboBox with Operation items instead of String:

    JComboBox<Operation> calculate = new JComboBox<>();

    calculate.addItem(Operation.Sum);
    calculate.addItem(Operation.Difference);
    calculate.addItem(Operation.Product);
    calculate.addItem(Operation.Quotient);
    calculate.addItem(Operation.Exponent);

Change the call to calculate to this:

    calculate(
            ((Operation) calculate.getSelectedItem()).equation,
            Double.parseDouble(first.getText()),
            Double.parseDouble(second.getText())
    ),

And simplify calculate itself to this:

public static double calculate(Equation operation, double val1, double val2) {
    return operation.compute(val1, val2);
}

Avoid pointless evaluations

In calculate, you declare all the equation types at the top but only use one of them.
This is pointless and wasteful.

Simplify lambdas with method references

These lambdas can be replaced with method references:

    SwingUtilities.invokeLater(() -> new EquationCalculator());
    // ...
    Equation exponentiate = (alpha, beta) -> Math.pow(alpha, beta);

Like this:

    SwingUtilities.invokeLater(EquationCalculator::new);
    // ...
    Equation exponentiate = Math::pow;

Pointless to print stack trace in main

If an exception is thrown in main,
a stack trace will be printed on the console.
There's no need to catch an exception and do the same manually.

Also beware,
it's not a good practice to catch Exception.
It's recommended to catch specific exceptions,
both to signal to readers the things that can possibly go wrong,
and also to avoid truly unexpected exceptions getting caught by the blanket catch.