Checking if numbers in array are sorted or reverse sorted

Your version is slightly misnamed.  It's actually isNonincreasingOrNondecreasing.  It returns true for arrays where all the entries are the same value, which is neither increasing nor decreasing.

If you don't want to duplicate the checks, you can add a bit more logic.

public static boolean isNonincreasingOrNondecreasing(int[] sequence) {
    // clear out equal entries from the beginning
    int i = 1;
    while (i < sequence.length && sequence[i - 1] == sequence[i]) {
        i++;
    }

    // if there are no entries left, then it is nonincreasing and nondecreasing
    if (i >= sequence.length) {
        return true;
    }

    int previous = sequence[i - 1];
    if (i < sequence.length && previous > sequence[i]) {
        for (; i < sequence.length; i++) {
            if (previous < sequence[i]) {
                return false;
            }

            previous = sequence[i];
        }

        return true;
    }

    for (; i < sequence.length; i++) {
        if (previous > sequence[i]) {
            return false;
        }

        previous = sequence[i];
    }

    return true;
}

This version only loops once, although it has three loops coded.  It only runs one loop over any section of the array.

It also gets rid of the Boolean variables.  It can return immediately since it only gets to the loops once it already knows which one to test.


You cannot use double quotes in a string literal like this:

cout << "Enter some text. Type "***" to end." << endl;

(The syntax-highlighting even changes the color of the ***.)

In order to print them out, you have to escape them as such:

cout << "Enter some text. Type \"***\" to end." << endl;

I suppose your compiler ignored the original, as I got an error when I tried it.

See this for more info on escape sequences in C++.


Making CSS rules for links in header more DRY

The worst aspect of your code is the markup, not the CSS.  Unless you need the div as an actual styling hook, you can safely discard it.  After all, you're not styling it in any meaningful way (what you do have can just as easily be applied to the descendant tags).

    BruxZir
    &equiv;

However, the inclusion of semantic tags might be a better way to go:

BruxZir

        &equiv;


I do know nothing about WordPress, so I will not be able to answer if the loop is a proper method for using order by.

Converting and comparing time

The DateTime class has great utilities for exactly this kind of thing. You have DateTime::createFromFormat to use your custom format, DateTime->format for formatting, and DateTime->sub and DateTime->diff for comparing.

Timestamp

For very simple comparing like "is this date bigger than that date," you could use timestamps (AKA time()) and compare them with <> as a timestamp is just a big number (seconds from 1970 until now). This will be more reliable than comparing date strings.


save the registers we intend to alter, failure to do so causes problems when gcc -O3 is used

It should be possible to avoid the pushes and pops.  If you are changing the values of the constraints, you cannot have them as just "inputs" (which is where this code currently has them).  Quoting the docs:

  Do not modify the contents of input-only operands (except for inputs tied to outputs). The compiler assumes that on exit from the asm statement these operands contain the same values as they had before executing the statement.

There are a variety of ways to deal with this.  Simply moving the ones you actually change to the "outputs" section and changing them to "+r" might be sufficient.  Note that this will indeed change the values, which might affect your "remaining bytes" code.

  [rem]"d" (rem)

Is there some reason you need this value in that specific register?  Letting the optimizers pick the registers tends to be a better plan.

  let alone the AT&T syntax

If you prefer the intel format for writing asm (and what rational person doesn't?), gcc has the -masm=intel option.

And lastly, have you tried writing this in C using intrinsics?  There are a couple of places in your code where I wonder if a different arrangement of instructions might give better results, but I can't say without trying it or running an analysis tool.

It's hard for humans to optimally arrange assembler instructions for modern processors.


Sum of switch-triggered integers in VHDL

This is some old question, but lets answer it.

Synthesis software is not that dumb. It will evaluate the potential outcomes of a function and generate reduced logic from that. Often you have to aid the synthesis software somewhat. You could do that by writing a function which internally resolves the things you want.

N.B. constraining the range of your integers keep the resource usage low. Else everything will be implemented as a 32-bit value

library ieee;
use ieee.std_logic_1164.all;

entity light is
  port(
        SW : in std_logic_vector(0 to 9); -- why 'to' and not 'downto'??
        KEY : in std_logic_vector(0 to 3); -- downto is normally used
        HEX0 : out std_logic_vector(0 to 6);
        HEX1 : out std_logic_vector(0 to 6);
        HEX2 : out std_logic_vector(0 to 6);
        HEX3 : out std_logic_vector(0 to 6);
        LEDR : out std_logic_vector(0 to 9);
        LEDG : out std_logic_vector(0 to 7)
  );
end light;

architecture arch of light is
    function hex_decode(x:integer)
        return std_logic_vector is
    begin
        case x is
            when 0 => return "0000001";
            when 1 => return "1001111";
            when 2 => return "0010010";
            when 3 => return "0000110";
            when 4 => return "1001100";
            when 5 => return "0100100";
            when 6 => return "0100000";
            when 7 => return "0001111";
            when 8 => return "0000000";
            when 9 => return "0000100";
            when others => return "1111111";
        end case;
    end hex_decode;

    function add_input(input : std_logic_vector(0 to 9))
        return natural is
        variable sum : natural range 0 to 45 := 0;
    begin
        for i in 1 to 9 loop
            if input(i)='1' then
                sum := sum + i;
            end if;
        end loop;
        return sum;
    end function add_input;

    function select_decimal(input : natural; sel: natural)
        return natural is
        variable output : natural range 0 to 9;
    begin
        output := (input / (10**sel)) mod 10;
        return output;
    end function select_decimal;

    signal switch_value : natural range 0 to 45;
begin

    switch_value <= add_input(sw);

    hex0 <= hex_decode(select_decimal(switch_value, 0));
    hex1 <= hex_decode(select_decimal(switch_value, 1));
    hex2 <= hex_decode(select_decimal(switch_value, 2));
    hex3 <= hex_decode(select_decimal(switch_value, 3));
end arch;

Result in Vivado:

---------------------------------------------------------------------------------
Start RTL Component Statistics
---------------------------------------------------------------------------------
Detailed RTL Component Info :
+---Adders :
       8 Input      6 Bit       Adders := 1
+---Muxes :
      11 Input      7 Bit        Muxes := 2
       2 Input      6 Bit        Muxes := 1
---------------------------------------------------------------------------------
Finished RTL Component Statistics
---------------------------------------------------------------------------------
Report Cell Usage:
+------+-------+------+
|      |Cell   |Count |
+------+-------+------+
|1     |CARRY4 |     2|
|2     |LUT2   |     2|
|3     |LUT3   |     1|
|4     |LUT4   |     4|
|5     |LUT5   |     7|
|6     |LUT6   |    15|
|7     |IBUF   |     9|
|8     |OBUF   |    28|
|9     |OBUFT  |    18|
+------+-------+------+

Report Instance Areas:
+------+---------+-------+------+
|      |Instance |Module |Cells |
+------+---------+-------+------+
|1     |top      |       |    86|
+------+---------+-------+------+


Some minor observations:

It's a good idea to check your html projects with a validator of some sort (for example: https://validator.w3.org/). There are some slight mistakes in your file which can easily be caught by any validator.
Usually you want to keep content, presentation and behavior separated from another. This means you put scripts, CSS etc. into their own files instead of having them all in your html file.
From a usability perspective I think it would be nicer to have explicit control over when the conversion takes place. E.g. via a button or something similiar.


Use the force library Luke!

Your code does use std::vector, but for reasons I don't understand, it also uses new to allocate a manually managed dynamic array as well. You don't seem to gain anything from this, so I'd advise using std::vector throughout.

I'd also look at the standard library's algorithms. Some of them (e.g., std::remove_copy_if) could be put to excellent use for this task.

Avoid std::endl

std::endl not only writes a new-line to a stream (which is what you usually want) but also flushes the stream (which you usually don't want). If you do that very often, it can slow a program significantly.

In your case, you using it when writing to std::cerr, which automatically flushes in any case, so the flushing done by std::endl is unnecessary in any case.

Random generator seeding

When you're using <random> (a good idea) the generally accepted way of seeding a generator is by using std::random_device. This is usually a truly random device (e.g., reading from /dev/random) so it normally does a substantially better job of seeding than using the system time.

As @1201ProgramAlarm already pointed out, you normally want to seed a generator exactly once, then just generate numbers from it.

Unfortunately, doing a good job of seeding a random number generator is a somewhat nontrivial task. I posted some code that demonstrates what I believe is one reasonable possibility in a previous answer. The short summary is that regardless of whether you use time(nullptr) or std::random_device, if you only use a 32-bit seed, you're limiting yourself to only \$2^{32}-1\$ possible sequences that you can generate, which is a huge limitation compared to the full capabilities of MT19377.

Single Responsibility Principle

It seems to me that your LineEditor does more than I'd like a single class to do. For most practical purpose, the entire program is embodied in that one class. That doesn't strike me as entirely ideal. I'd rather see individual pieces responsible for the individual parts of doing the job.

This also fits better with having clearly defined layers of abstraction. For example, you might have one layer that deals with the file name, and a separate one that deals with the actual content of the file.

Convenient Interface

For most uses, I'd rather run the program something like removeLines foo.txt 10, rather than doing removeLines, then having to separately walk through a questionairre (so to speak) to tell it the name of the file and number of lines to remove. Of course, depending on the situation, that might be better as something like removeLines -f foo.txt -n 10 (especially if this were part of a larger program that might have more/other command line arguments as well.

If you are going to ask questions interactively, I'd ask for the filename first, then read in the file, then ask for the number of lines to remove. This will allow you to check how many lines you've actually read, which (in turn) you can use to advise the user as to the maximum number of lines they can have removed (e.g., "Please enter the number of lines to remove (1-723): ").

Constructor Definition

You've currently defined your constructor with no member initializer list and nothing in the body. It's not clear what you're hoping to accomplish by defining it explicitly rather than just accepting what the compiler would define if you didn't define one at all. Until/unless your ctor will actually accomplish something, it's probably better not to define it explicitly.

Possible Code

#include <iostream>
#include <vector>
#include <string>
#include <set>
#include <fstream>
#include <iterator>
#include "rand.h"

struct InputSpec {
    std::string filename;
    std::size_t count;

    InputSpec(int argc, char **argv) {
        if (argc != 3)
            throw std::runtime_error("Usage: removeLines <filename> <count>");

        filename = argv[1];
        count = std::atoi(argv[2]);

        if (count == 0)
            throw std::runtime_error("numbers of lines to remove can't equal 0");
    }
};

int main(int argc, char **argv) {
    InputSpec input{argc, argv};

    std::ifstream infile(input.filename);
    std::vector<std::string> lines;
    std::string line;
    while (std::getline(infile, line))
        lines.push_back(line);

    int maxLines = std::min(input.count, lines.size());

    generator g(maxLines);
    std::set<int> removals;

    while (removals.size() < maxLines)
        removals.insert(g());

    int current_line = 0;
    std::remove_copy_if(lines.begin(), lines.end(),
        std::ostream_iterator<std::string>(std::cout, "\n"),
        [&](std::string const &) { return removals.find(++current_line) != removals.end(); });
}

Note that for the moment, this presumes that the number of lines to be removed from the file is small compared to the number of lines in the file. If there's a significant chance that won't be true, you may want to see the selection algorithm in yet another old answer.


Generating random numbers and decks of cards

First off, your code is borderline unreadable. Use proper indentation. Add whitespace (horizontal and vertical). Follow conventional guidelines (lowercase camelCase names for most things). And give your variables actual names - bytes are cheap.

If you want really compact code, use a minifier - after writing the code in readable, sane manner. This looks like a text dump of a fiendish Excel spreadsheet or something.

For the few things that I could read, and which stand out:

You Rand [sic] function is doing a bunch of unnecessary stuff. You parseFloat something that's guaranteed to be an integer, because you called Math.floor() on it. You parseFloat on min when adding it at the end, but you don't do it when you subtract it from max.

And it's broken (which makes it technically off-topic for CodeReview, by the way).

Firstly, it doesn't even run because you've got one close-parenthesis too many, so there's a syntax error.

Secondly, you're not paying attention to operator precedence: Multiplication precedes addition and subtract. So your code is saying Math.random() * max then subtracting min and finally adding 1. Hence, if you call Rand(9, 10), you're liable to get any number from 1-10, rather than a number from 9-10.

Just say:

function rand(min, max) {
  var span = max - min;
  return Math.round(Math.random() * span) + min;
}

As for Choose [sic], you can use the bitwise-floor trick:

function choose(arr) {
  return arr[Math.random() * arr.length | 0];
}

When appending to and array, use push. Don't just assign to an index. E.g.

spades.push(values[i] + " of Spades");
hearts.push(values[i] + " of Hearts");
clubs.push(values[i] + " of Clubs");
diamonds.push(values[i] + " of Diamonds");

As for "better RNG", that's a StackOverflow question if anything. JavaScript has Math.random() and that's it.


JavaScript - Difference between two dates in days or less

Your code looks good to me. I think 1000 * 60 * 60 * 24 would be more intuitive than the scientific notation, but either way gets the job done.

The script doesn't actually take localization into account because Date's getTime method is not localized. To account for time zone, you'd want to get the "timezone offset" of the user's location. (Note that getTimezoneOffset returns a number of minutes, and that number isn't a property of the date object but just an indication of what timezone the code is running in.)

As for the other methods
 - getTime returns the actual "timestamp", a big integer showing how many milliseconds have passed since the 60s ended in London
 - getUTCMilliseconds is just the last three digits of that timestamp (ie how many milliseconds it's been since the last full second since the "epoch", as it's called.)
 - Leaving out the UTC bit (as in getMilliseconds,  or in any of the similar get methods, excepting getTime) makes javascript calculate the local version for you (and in the case of milliseconds, I'd be pretty surprised if it were different from the universal version.)

...You can see the whole buffet on MDN:
   https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#Date.prototype_Methods


Program to print the number as a sum of consecutives

Your algorithm, being \$O(\sqrt n)\$, is pretty efficient.  I just think that your code could just a bit of cleanup.

Your print() function does all kinds of things, mostly unrelated to printing.  You should separate the code for the user interaction from the calculation.  (Since each result is a pair of numbers, and there will be an indeterminate number of results, I'd use a callback.)  You should also extract the loop the prints each series into a helper function.  (Executing many System.out.print() statements can be surprisingly slow, as each one is a separate I/O operation.)

Your mathematical reasoning was not clear to me at first.  I would have preferred a comment that more clearly explained the nomenclature and used fewer words.

// n = a + (a+1) + ... + (a+i-1) (Given n, find all a>0 and i>=2)
//
// 2n = i(2a + (i-1))            (arithmetic series formula)
//
// a = (2n - i(i-1)) / 2i
//
// 2n > i(i-1)                   (because a>0 and i>0)
//
// 2 <= i < (1+sqrt(1+8n))/2     (quadratic formula)

Since this is supposed to be an exercise in integer arithmetic, you should avoid using doubles.  Use either int or long.  Note that I have avoided your a = n/i - (i-1)/2, which involves non-integer division.

Actually, you don't need to calculate max_i.  You don't really trust that bound, and you test for a > 0 anyway.

Suggested solution

import java.util.Scanner;
import java.util.function.BiConsumer;
import java.util.stream.Collectors;
import java.util.stream.LongStream;

public class Consecutives {
    /**
     * Find integers a>0 and i>=2 such that n = a + (a+1) + ... + (a+i-1).
     *
     * @param n        The target sum.
     * @param callback A function that will be called with parameters a and i
     *                 for each solution found.
     */
    public static void findSeries(long n, BiConsumer<Long, Long> callback) {
        // n = a + (a+1) + ... + (a+i-1) (Given n, find all a>0 and i>=2)
        //
        // 2n = i(2a + (i-1))            (arithmetic series formula)
        //
        // a = (2n - i(i-1)) / 2i

        for (long i = 2; ; i++) {
            long aNumer = 2 * n - i * (i - 1);
            long aDenom = 2 * i;
            if (aNumer <= 0) break;
            if (aNumer % aDenom == 0) {
                callback.accept(aNumer / aDenom, i);
            }
        }
    }

    /**
     * Form a string of all integers in the range [a, a+i), separated by space.
     */
    private static String spaceDelimitedRange(long a, long i) {
        return LongStream.range(a, a+i)
                         .mapToObj(String::valueOf)
                         .collect(Collectors.joining(" "));
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter number: ");
        findSeries(
            scanner.nextLong(),
            (a, i) -> System.out.println(spaceDelimitedRange(a, i))
        );
    }
}


Multiplying a numeric string with the "vedic method"

Code organization: main does too much. Actual calculations, that is everything between gets and puts shall be a standalone function (multiply). Zero-filling loop shall be factored out into a function (see below). main declares many unused variables (value, u, v, j, mulVal - do you need them?).
Globals: globals are bad. Try to get rid of them.
Input: Don't use gets. Also, input shall be validated.
Magic number: 48 is ASCII for zero. Subtracting '0' would be much more clear. BTW, you do a lot of extra work: it is enough to convert just once as soon as the string lengths are calculated.

Other notes:

Don't be shy on spaces. Things like for(i=0,j=length-1;i<length/2;i++,j--){ are very hard to read.

An if (i != j) condition in mulIndices may only happen upon loop termination. There's no need to test it at every iteration. Similarly, in the length fitting loop, the condition is tested at every iteration. Swapping ifs and while results in better code:

if (length2 < length1) {
    while (diffOfLen--)
        str2[i++] = '0';
    str2[i] = 0;
} else {
    while (diffOfLen--)
        str1[i++] = '0';
    str1[i] = 0;
}

BTW, now it is obvious that the loops are functions. I'd prefer just memset.


Solving Project Euler Problem 1 using extension methods

This is not so much of a code answer as a mathematical answer.

We can calculate directly the number of multiples \$m\$ of a natural number \$n\$ that are below the limit \$x\$.  It's simply \$\lceil x/n\rceil\$.  The sum of those multiples is:
$$n\sum_{i=1}^{\lceil x/n\rceil}= n\left(\frac{1}{2}(\lceil x/n \rceil)(\lceil x/n\rceil+1)\right)$$
So for \$n=3\$ and \$x=999\$, we get $$3\left(\frac{1}{2}(333)(333+1)\right)= 166833$$
And for \$n=5\$ and \$x=999\$, we get $$5\left(\frac{1}{2}(200)(200+1)\right)=99500$$
So we could calculate the answer is $$166833 + 99500 = 266333$$  However the problem here (hat tip to @MartinR !) is that we have double-counted multiples of 15.  To fix that, we need to subtract that count:

$$ 15\left(\frac{1}{2}(66)(66+1)\right) = 33165$$
So the correct final answer is $$266333 - 33165 = 233168$$


Stock picker that tells when to buy and when to sell

The code is a pretty sensible solution for this problem.

Never put $ before a variable in Ruby, it becomes global and may be modified from anywhere.

I think that function programming is more apt to algorithmic problems than imperative. I solved it like this:

def stock(prices)
  ((0...prices.length).to_a)
    .repeated_permutation(2)
    .select {|start, finish| finish > start}
    .max_by {|start, finish| prices[finish] - prices[start]}
end

It is more close to how you would describe the problem, anyway you may be intersted in PBRTM, the main programming style supported by Ruby. (Programming By Reading The Manual) Ruby gives you many many library functions and you may enjoy scrolling through them to find the ones that help you shorten your code.

Getting to the real meat, both yours and my approach run in O(N^2) time complexity. That means that for a million (10^6) stock prices, the code must make (10^12) operations, that is not feasible.

I suggest something like this:

I find min and max of array. Is max after min? If so I am done. Otherwise I delete the least far from average and start again.

This is almost linear, but may not be optimal.

OR

You may sort the data O(N log N) and try first and last, if in the array the index of last is after the index of first, done. Otherwise delete the least far from average between first and last and repeat. Also this may fail to provide the optimal result in edge cases.

All in all, a quadratic solution is easy but slow but a quasilinear one is hard but fast.


Test if a network is online by using urllib2

I would use Python's socket library instead of urllib. Then, you could test like this:

import socket
REMOTE_SERVER = "www.google.com"
def is_connected():
  try:
    host = socket.gethostbyname(REMOTE_SERVER)
    s = socket.create_connection((host, 80), 2)
    return True
  except:
     pass
  return False
print is_connected()

Borrowed from here

I think the most obvious thing to point out is this:

if response:
    return True
else:
    return False

You can actually just return the variable, so just return response would replace all those lines.

There's not really any reason to use .format for one variable.

'Sending request to {}'.format(url)

Plain string concatenation is fine, for one variable.

Anyway, what's the point of printing out that you're requesting google.com?

'Request to {} failed'.format(url)

The level of abstraction that you put into this, is that it'll return whether you're connected or not.

Printing out anything other than: 'Net is up' or 'Net down' (Which could better be: 'Net is down, retrying connection') seems superfluous.

kwargs.setdefault('timeout', 0.30)

I would avoid the magic numbers (undefined numbers: 0.30), define it as a constant (in all caps) to improve readability.

  Is this code Pythonic?

I'd recommend reading PEP8, Python's official style guide. It has many guidelines to follow on just about everything; it should really be a Python programmer's Bible. There's also a nice little Online PEP8 checker to help/show you where your code doesn't meet the standards of PEP8.

The term 'Pythonic' is not so easily defined, so I'm not really going to give you a 'Yes or No' answer, but, I'd just really recommend reading over PEP8.

  Is this code practical?

Yes, it's practical.

However, one thing more to point out; While you keep retrying and retrying:

Put a some kind of wait in between network connection tests.
Every time you call is_online, when the Net is down, you redo the url setup, consider keeping that seperate so you can only do the bare minimum for the continual tests:

kwargs.setdefault('timeout', 0.30)
kwargs.setdefault('url', 'http://www.google.com')
timeout = kwargs.get('timeout')
url = kwargs.get('url')


My first advice would be to reformat your code with a linter.  I won't go into this in more detail because I assume you're mostly after implementation advice, but as it is it's quite jarring to read, similar to text written in your own language but with foreign capitalization and punctuation.
Some of your functions could use destructuring to make their bodies more terse.
For instance, this:
document.addEventListener(`keyup`, function (e) {
  if (e.code === `ArrowRight` || e.code === `ArrowLeft`) {
    resetFunc()
  }
})

Could be rewritten as this, since you're only using the code property of the argument:
document.addEventListener(`keyup`, function ({ code }) {
  if (code === `ArrowRight` || code === `ArrowLeft`) {
    resetFunc()
  }
})

A more controversial bit of advice might be to write this at the top of your script:
const $ = document.querySelector.bind(document);

This allows you to replace this:
const getNumber = document.getElementById(`number`)
const incrButton = document.getElementById(`incr`)
const decrButton = document.getElementById(`decr`)
const resetButton = document.getElementById(`reset`)

With something much less verbose:
const getNumber = $(`#number`)
const incrButton = $(`#incr`)
const decrButton = $(`#decr`)
const resetButton = $(`#reset`)


There is no need to store all lines from the input file in memory.
For each line read from the input you can append the string and write the
result to the output file. This would save memory for large input files.

You should also check if opening the input and output file was
successful, otherwise your program will silently do nothing if the
files could not be opened/created.

std::ifstream in_file(argv[1]);
if (!in_file) {
    std::cerr << "Could not open input file\n";
    return EXIT_FAILURE;
}
std::ofstream out_file(argv[2]);
if (!out_file) {
    std::cerr << "Could not create output file\n";
    return EXIT_FAILURE;
}
const char * add_string = argv[3];

std::string str;
while (std::getline(in_file, str)) {
    out_file << str << add_string << "\n";
}


Another alternative (very similar to Matt's) is to use the synthetic field property (which is set for default class properties, but not for your own defined props):

class Baz {
  String foo = "foo2"
  int bar = 2

  public Map asMap() {
    this.class.declaredFields.findAll { !it.synthetic }.collectEntries {
      [ (it.name):this."$it.name" ]
    }
  }
}


Use diagonals. The idea is to have only one pixel check, compared to two you have now:

find the first occupied pixel on a diagonal
skip to an unoccupied one
fill with 0.1 while unoccupied
repeat 1-3 until out of bounds

Considering everything should be inlined, the code would be like this:

var x, y, index, index0,
    len = width * height * 4,
    stride = width * 4;
    strideDia = stride + 4; // distance to the sibling pixel towards bottom-right

// walk diagonals from the bottom-left corner to the top-left corner
for (x = 0, y = height, index0 = (y * width + x)*4 + 3; --y >= 0; ) {
    index = index0 -= stride;

    while (index < len && x < width) {
        // find an occupied pixel
        while (index < len && x < width && !data[index])
            index += strideDia, x++;
        // skip to an unoccupied
        while (index < len && x < width && data[index])
            index += strideDia, x++;
        // fill with 0.1 all unoccupied
        while (index < len && x < width && !data[index]) {
            data[index] = 25; // 0.1 * 256
            index += strideDia;
            x++;
        }
    }

    x = 0;
}

// walk diagonals from the top-left corner to the top-right corner
// (0,0) is skipped as it was processed in the previous walk block
for (x = 0, y = 0, index0 = (y * width + x)*4 + 3; ++x < width; ) {
    index = index0 += 4;
    var x0 = x;

    while (index < len && x < width) {
        // find an occupied pixel
        while (index < len && x < width && !data[index])
            index += strideDia, x++;
        // skip to an unoccupied
        while (index < len && x < width && data[index])
            index += strideDia, x++;
        // fill with 0.1 all unoccupied
        while (index < len && x < width && !data[index]) {
            data[index] = 25; // 0.1 * 256
            index += strideDia;
            x++;
        }
    }

    x = x0;
}

Another potentially promising idea would be to use asm.js.


Improve speed of object-to-html transform in javascript?

If this is on an intranet, with similar machines running this JS, then 2 seconds is fairly ok for 4,200 records...but if its on the internet, you might want to think about doing this server side and just ajax'ing the server generated table code via js...someone running this on an iPad would probably take considerably longer to generate 4,200 records vs someone running an overclocked i7 machine for instance. Just food for thought.

As for actual improvements to the code, I don't really see any glaring items...although someone else might want to pipe in. Seems someone already piped in :)


Mutually exclusive expandable panels (needs to work in IE9 and above)

Overall, the code looks pretty good. Definitely much better than many other JS examples in CodeReview. A few minor points can be made though.

DRY - Don't repeat yourself

At the very minimum, you can reuse some code by encapsulating it into a function.

You can define setPanelVisibilityState which will be responsible for the details of showing/hiding a section. The decision on whether a button/panel should be visible or not remains in the control of the caller...

Variable naming

Similarly, I'm unsure if the selectors '.panels-button' and '.panels-content' more than in one place...

I personally am a big enemy of variables like i, j, c, and so on. It's not so difficult to spell it out: panelIndex.

IE is a beast

As far as IE page renderer goes, I can't provide much feedback because I don't deal with it.

function togglePanel() {
    const showContent = content.getAttribute('aria-hidden') === 'true';
    reset();
    setPanelVisibilityState(false, button, content);
}

function reset() {
    for (var panelIndex = 0; panelIndex < panel.length; panelIndex++)
        setPanelVisibilityState(false, button[panelIndex], content[panelIndex]);
}

function setPanelVisibilityState(isVisible, button, content) {
    button.setAttribute('aria-expanded', isVisible);
    content.setAttribute('aria-hidden', !isVisible);
    content.className = isVisible ? 'panels-content' : 'panels-content js-hidden';
}


Call method if child implements interface vs override

I think the classes that have a calculateStatus method should have it called in the end of their doSomeThing()

Or, if you wish to reuse more code, create a  AbstractRequestStatusUpdatableWs, like this:

abstract class AbstractRequestStatusUpdatableWs implements StatusUpdatable
{
     abstract void calculateStatus();
     abstract void doSomeRealWork();

     public final void doSomeThing()
     {
           doSomeRealWork();
           calculateStatus();
     }
}


You can improve the efficiency by reversing the numbers as integers instead of converting to strings and back.

Modifying the list and returning it is redundant since the list is passed by reference and your changes will persist to the original list.

Simplified your code could look like this:

public static void ReverseIntegerList_Array(List<int> intList)
{
    if(intList == null)
    {
        return;
    }
    int limit = intList.Count;
    for(int i = 0; i < limit;++i)
    {
        intList[i] = ReverseNum(intList[i]);
    }
}

public static int ReverseNum(int num)
{
    int retVal = 0;
    while(num > 0)
    {
        retVal = (retVal * 10) + num % 10;
        num /= 10;
    }
    return retVal;
}


Simple object oriented console calculator

Exception handling

try {
    ...
} catch (InputMismatchException ime) {
     System.out.println("invalid input");
} finally {
     if (operator != '+' & operator != '-' & operator != '*' & operator != '/') {
         throw new InputMismatchException();
     }
     Calculator calculator = new Calculator(firstNum, secondNum,    operator);
     ...
}

That's pretty weird.

It makes no sense to continue the computation if the Scanner throws. What is the point of having a finally block that throws the same exception? I would rather let the exception pass through instead of catching and rethrowing (the original exception is likely to contain a more meaningful message, too).

Variable scope

Try and use the narrowest possible scope. For instance, here:

Calculator calc = new Calculator(6.0, 2.0, '+');

@Test
void addsTwoNumbers() {
     assertEquals(8.0, calc.makeCalculation());
}

there's no point in making calc a field. It can (and should) be just a local variable in the addsTwoNumbers() method. The same is true for other calc's and test methods.

Class design

I don't think that the Calculator is a good name for your class. I would expect a calculator to be able to be instantiated once and then evaluate results of different expression. Something like this:

Calculator calculator = new Calculator();
double sum = calculator.evaluateExpression(x, y, '+');
double difference = caclulator.evaluateExpression(x, y, '-');

I'd change it this way or rename this class to Expression.

Object reuse

Creating four new objects for each operation per each expression evaluation can be costly and is unreasonable because the operation are stateless.

You can use a static factory to reuse the same Operation objects in different expressions.


For now, let's ignore the fact that there are easier ways to add binary numbers. There are other issues with this code.

Inherits System.Web.UI.Page

Why is code that adds binary numbers inheriting from a UI class? There's no need for this. Separate the concerns and create a module for this code instead.

carry is scoped to the class level. This is a symptom of problems in this code.

Protected Sub Button1_Click(sender As Object, e As System.EventArgs) Handles Button1.Click
    Dim binary1 As String = TextBox1.Text 'First binary number
    Dim binary2 As String = TextBox2.Text 'Second binary number
    Dim result As String = "" 'to store the result
    For i As Integer = Len(binary1 ) - 1 To 0 Step -1
        result = bin_add(getbyte(binary1 , i), getbyte(binary1, i)) & result ' calling function
    Next
    If carry = True Then
        result = "1" & result 'if a carry remains add it to the MSB
    End If
    MsgBox(rslt) 'Display the result
End Sub

Getting the values from the UI makes sense, but then you loop over bin_add, which obviously doesn't actually add anything, or you wouldn't need to loop or have a class variable. All of this logic should happen inside of bin_add.

bin_add should take in two strings, handle all of the logic, and return a single string representing the output. While I'm at it, methods should have PascalCased verb-noun names. This method should be called AddBinary and I will refer to it as such for the rest of the review.

As I said earlier, I wouldn't expect a Function that adds binary numbers to take in Boolean values. I would rather it actually take in a byte and overload the method to handle string representation, but I'm lazy and you don't seem to need all that.

Putting it all together, the signature line

Public Function bin_add(b1 As Boolean, b2 As Boolean) As String

Should look like this.

Public Function AddBinary(value1 as String, value2 as String) As String

Implementing this change will be left as an exercise for the reader.


Style

At the moment, this is C with iostream. The style obliterates the point in using C++ at all.

Code Review

Almost complete absence of standard library

The code does not leverage the functionality standard library provides. On top of that, the code is not better in any ways than standard library functionality
Using int for size of objects in memory

Indexable memory is very big nowadays. int is guaranteed to be only 16 bits, so it might not be enough to index all of the available memory on the system. Use std::size_t for that.
C style swapping

C++ has std::swap() located in <utility>. It will probably be as good as your version, if not better (it might invoke some assembly).
Using std::endl

std::endl does not only put a newline, but also flushes the buffer. Flushing is a very expensive operation, and can hinder performance of the code in tight loops.

What is done right

No using namespace std

This is good step forward. Do not use it, in any IDE/text editor code highlighting and completion will be available, if not, find a plugin for your text editor. By grabbing everything in std, you will overwhelm the ability of the IDE/text editor to give you real-time code completion suggestions.
Uniform initialization

Using uniform initialization avoids all of the vexing parse issues. Do note though, that sometimes they might invoke std::initializer_list constructor, which might not be what you need.

tl;dr

Use Standard library. Use concepts and idioms. Any decent C++ programmer knows that to reimplement standard library one must have a very good reason to do so.


Here are my main recommendations:

use recursion
use names instead of list indices, for example node$data$reply$data$children reads much better than node[[2]][[5]][[2]][[2]] and it is also more robust to data changes.
use well-named variables so you code reads easily

Now for the code:

url       <- "http://www.reddit.com/r/funny/comments/2eerfs/fifa_glitch_cosplay/.json"
rawdat    <- fromJSON(readLines(url, warn = FALSE))
main.node <- rawdat[[2]]$data$children

get.comments <- function(node) {
   comment     <- node$data$body
   replies     <- node$data$replies
   reply.nodes <- if (is.list(replies)) replies$data$children else NULL
   return(list(comment, lapply(reply.nodes, get.comments)))
}

txt <- unlist(lapply(main.node, get.comments))
length(txt)
# [1] 199


Security of the login code on the website

The devil is in the details, and you are omitting a lot of details from your code that usually go wrong. That said, I at least saw the following issues in your code:
session_regenerate_id regenerates the... id... of the session. I am not sure why you do this, but it is not necessary and will likely cause issues where people are logged out unexpectedly on unstable networks where a page might not load for any reason. Your logged in session is also valid indefinitely. If an attacker can get their hands on a session identifier, they can keep their session alive indefinitely. You might want to add an expires_on timestamp to your session that is checked to limit the lifetime of any session.
While not wrong perse, unset($_POST['submit']); does not add anything either. It does not do anything for you security-wise at least.
Your check in_array('', $_POST) is a bit convoluted. It uses that in_array checks values, even if you pass it an array with key-value pairs instead of one with numeric indexes. It is probably the reason why you unset the submit button, but at least in the documentation it is only used with numeric indexed arrays. You might want to check if password and email are set instead with empty($_POST['password']) || empty($_POST['email']). This also guards against warnings when password is not set. A second quirk of in_array is that your check will return true with the following array due to type conversion: [ 'remember_me' => 0 ].
I am not sure why you use filter_var($_POST['email'], FILTER_VALIDATE_EMAIL), since the email is already in the database and you should be using prepared queries that are resistent against sql injection through any user input. FILTER_VALIDATE_EMAIL lets through a lot more than you expect, and if you are relying on that function to prevent sql injection, you might be vulnerable. Since you didn't share that part of the code I cannot comment on if your code is vulnerable in that regard.
The second argument of password_verify($_POST['password'], Password field in db) is a hash, not a database field name. If you meant that you retrieve it from the database, it is fine.
You do not store who is logged in and instead only set if someone is logged in $_SESSION['loggedin'] = 1;. If you do not care who is logged in, the email part of the login is redundant and you should just remove it. It does not really add any security.
All else-es in your code should be combined into one message. You do not want to give a would-be attacked any information on what part they should improve to get into your website. Just give a generic message "your email or password is incorrect".

That said, the functions that you do use do not return anything else than the expected booleans as far as I know. You correctly exit after sending your location header. I also don't see a way to set being logged in outside sending a username and password through the login page.


Just some generic notes since I'm not too familiar with C#:

rtn should be StringBuilder
I'd change the preprocessor and ParserRounds variables to fields and pass their values to the constructor of the class. It makes testing easier (you can test only one parser at a time, you can test with a mocked preprocessor etc.) and it results looser coupling.
Using SourceTemplate.Top and SourceTemplate.Bottom also tight coupling, pass these values to the constructor too, store them in a field and use these fields in the Compile method. (Maybe it's worth creating a SourceTemplate interface with GetTop() and GetBottom() methods and passing a proper instance to the Compiler class.)
I'm really missing the input validation. For example, if the Compile method get a null as a value of TextReader you should throw an exception immediately. It helps debugging a lot. Why would you do any compiling if it will throw an exception later since the TextReader is null?

The Start method also should check the input values.
Some variable naming ideas:

src -> sourceReader or srcReader
com -> compiler
target -> targetFileName
rtn -> result
wsrc -> targetWriter


Singletons

There are several ways to make something a singleton. You are doing it by removing the public constructor, and forcing users to get an instance through a static member function. That works, but there are alternatives. You can create a regular class, and provide a global instance of that class. Just like so:

class Log {
    ...
};

Log logInstance;

You then just refer to logInstance instead of SingletonLog::instance().

Proper naming

Your class has a function log(), however that function does not log anything. Instead, it just returns a std::ostream reference. A more appropriate name for the function would then be get_stream().

If you intend to always use it as SingletonLog::instance().log() << "some string", then it might be better to just add an operator <<() overload to your logging class. This has several advantages:

It's less typing: SingletonLog::instance() << "some string", or when using the alternative way of making a singleton: logInstance << "some string".
You can actually read the contents of the string in your class, and check whether it ends with a newline or not.

Flushing

Whether or not to flush depends on what you want to log. If you log a lot of information, flushing adds considerable overhead. However, if you want to be sure that any errors that are logged are not lost when your program terminates abnormally, then it might be prudent to flush the output stream after every write to the log.

Other suggestions

Do you really want to use the << operator? If you rather like to use the printf() style, then consider making use of fmtlib, which provides a type-safe way to format strings the printf() or Python .format() way. Your logging class could look like:

#include <fmt/format.h>

class Log {
    template <typename... Args>
    void log(const std::string &format, const Args &... args) {
        std::cout << fmt::format(format, args...);
    }
};

Log logInstance;

And use it like:

logInstance.log("First line: {}\nSecond line: {}\n", "first entry", "second entry");


Which loop to use for multiple if statements which serialize objects

The solution I propose to you is to create an array or another ordered structure where you could create all the 20 club objects and just select the right one base on the index of the club.

ClubInfo [] clubs =  new ClubInfo[20];
clubs[0] = new ClubInfo("Arsneal" , "Emirates" , "Premier League" , 11122333 , 60000);

Then you can do :

ClubInfo club = clubs[passed_choice - 1];
tryWriteClub(club);

You could find a better way to deal with the index problem. Small problem is now the ClubInfo objects will either be created everytime the method is called or you could create it one time as a static array or something similar.

Naming

You do not follow the naming standard for the Java language. Method name should be nameLikeThis() and variable should be nameLikeThisToo. So your  int passed_choice should be int passedChoice and the method public void Serialize() should be public void serialize().

Comments

I recommend that you get rid of comments like // end if 2. It is just noise that serve nothing. Comments should be use to explain why you have this particular piece of code.


Implementing boost::upgrade_mutex using only standard locks

I think it actually is valid.

Here's all of the possible states of the two mutexes.

/* u: unlocked, s: shared locked, g: upgrade locked, x: exclusive locked
   (state): of which upgrade_mutex state, the states are as this line
   (inter-state): in the middle of these transitions, the states might be as this line
                  Xab means the original state is of symbol X,
                      and the thread is doing the lock/unlock of a->b
   symbol xmutex smutex (state) (inter-state)
     A      u      u       u
     B      x      u             Aux Axu Aug Agu Agx Axg Axs Dgu Dgx Exu Exg Exs
     C      u      s       s     Cs
     D      x      s       g     Axs Bs Cux Cug Ds Dgu Dgx Exs
     E      x      x       x
*/

The 10 lock/unlock methods all behave reasonably good in all of the states
Given the prior-method state is in the set, the during-/post-method state is in the set


Actually, this can be more generic.

Instead of hard-coding your map; fill it from your properties file.
So change your prop file to :

#db.id=a
#db.user=testa
#db.password=testa

db.id=b
db.user=testb
db.password=testb

Fill your map like this :

private Map<String, String> schemaMap = new HashMap<String, String>();

public void fillMap() throws FileNotFoundException, IOException {
    String line;
    String key = null;
    String value = null;
    try (BufferedReader file = new BufferedReader(new FileReader("test.properties"))){
        while ((line = file.readLine()) != null) {

            if (line.contains("db.id")) {
                key = line.substring(line.indexOf('='));// could be you have to do an + 1
            }
            if (line.contains("db.user")) {
                value = line.substring(line.indexOf('='));
            }
            if (key!=null && value != null) {
                schemaMap.put(key, value);
                key = null;
                value = null;
            }
        }
    } catch (IOException ex) {
         // report with Logger or System.out what happend.
    }
}

Secondly : In your main you use the args.
You do not check for how many args you have, you just take the last arg.
Maybe a check for how many args you have is appropriate here, and make the program do what you want then. (like quitting with error message or taking default arg).

Third : Always close your resources(reader/writer in this case).
Here it is done with a Try-with-resources available from java 7, otherwise you will need a finally block where you close it in.


I see a number of things that may help you improve your program.

Understand const

In a number of places in the code we have function declarations like this:

const int8_t getRoundedBits(int8_t bits)

The const is ignored by the compiler in this case, so it's merely confusing to the reader.  One can't have type qualifiers (such as const) on a return type, which makes sense if one thinks about it.  It makes no sense to return an int8_t value that can't be altered.  It's like going to the market and buying an egg, and being told, "You may have this egg, but you are not allowed to alter it."

Think carefully about data types

The code currently contains this function:

long double negLog2(uint64_t num)
{
    long double negLogVal = 0.0f;
    negLogVal = (num < 0) ? (sizeof(num) * BYTE) : (log2l(1.0L) - log2l(num));
    return isNumInMaxRange(num) ?  fabs(negLogVal) + 1 : negLogVal;
}

Since num is an unsigned type, the test for num < 0 will never return true, so this, too is useless code that the compiler easily ignores, but is confusing to a human reader of the code.

Simplify your code

The code contains this peculiar function:

bool isNumInMaxRange(uint64_t num)
{
    return ((num == (UINT8_MAX  + 1U) || num == (UINT16_MAX  + 1U) || num == (UINT32_MAX  + 1ULL))) ?  true : false;
}

First, the function uses the trinary operator (?:) where it isn't needed and simply clutters the code.  Second, there are a number of parentheses that aren't needed.

Avoid global variables

By the context, it appears that the binaryArrayLen variable is global.  It's generally better to explicitly pass variables into and out of your functions rather than using the vague implicit linkage of a global variable.  Not least, the current implementation would seem to preclude the possibility of ever having more than one BinaryArray.  In this case, it seems to me that a BinaryArray should be a struct containing both the data and the length.

Avoid conversions to and from floating point

We have a function getEncodingBits() which appears to be intending to return the number of bits required to encode the given number.  It looks like this:

int8_t getEncodingBits(uint64_t num)
{
    return getRoundedBits((int8_t)fabs(floor(negLog2(num) - 1) + 1));
}

The other functions have still more floating point mathematics in them, none of which is not really needed and will slow down your program.  Here's an alternative approach that is much simpler and uses no floating point:

int8_t getEncodingBits(uint64_t num)
{
    int8_t bits = 8;
    for (num >>= 8; num; num >>= 8) {
        bits += 8;
    }
    return bits;
}

Understand the standard library

The code currently includes these lines:

uint8_t *binaryArray = (uint8_t *)malloc(binaryArrayLen);
memset(binaryArray,0x0,binaryArrayLen);

First, memory allocation can fail, so the value of binaryArray must be checked before using it.  Second, if you really need the memory cleared, simply use calloc instead.

General comments

Handling this one bit at a time in the manner that this program does is a very inefficient mechanism.  For speed, it's better to handle as much data at one time as possible.  So instead of extracting and writing one bit at a time, it would make more sense to write the data in uint64_t sized chunks where possible.  Allocating memory in small chunks is also time-consuming.  In this case, the maximum data size is apparently uint64_t, so it would make sense to me to simply use uint64_t everywhere that you're currently using a BinaryArray.  Example:

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

typedef uint64_t BitArray;

int printBitArray(BitArray n) {
    const int len = sizeof(BitArray) * 8;
    char string[len + 1];
    char *ptr = &string[len];
    *ptr-- = ‘\0’;
    if (n == 0) {
        *ptr-- = '0';
    } else {
        for (*ptr = '0'; n; n >>= 1) {
            *ptr-- = '0' + (n & 1);
        }
    }
    return printf("%s\n", ptr+1);
}
BitArray setBit(BitArray n, int bitnum) {
    const BitArray mask = 1 << bitnum;
    return n | mask;
}
BitArray clrBit(BitArray n, int bitnum) {
    const BitArray mask = 1 << bitnum;
    return n & ~mask;
}

int main() {
    // set to 10101101 binary
    BitArray bits = 173u;
    printBitArray(bits);
    bits = setBit(bits, 14);
    printBitArray(bits);
    bits = clrBit(bits, 14);
    printBitArray(bits);
    bits = clrBit(bits, 0);
    printBitArray(bits);
}


Complexity is (26)(maxPassLength).

You know that the password is only lower-case alpha characters?

  Would you recommend threading to reduce the search space?

It's possible that threads wouldn't help. The doc.open2000 will be more expensive than anything else, and your communication with Word may (I don't know) be effectively single-threaded (i.e. talking to a single Word process/task).

You might get better performance from a Word emulator which is designed to run on a server, e.g. from http://www.aspose.com/


Finding an element without pair in a list O(n**2)

This is not a review, but an extended comment.
The linear time/constant space solution is too well known to be spelled out again. However, here it goes.
XOR of two equal numbers is 0, and XOR of a number and 0 leaves the number unchanged. XOR is commutative and associative operation; we may perform it in any order we wish, and arrive to the same result. In other words, if we XOR all of them, each pair of numbers would cancel to 0, and the final result would be the number without a pair, the one we are looking for.


Selecting currencies on a form using Selenium

You don't have to recreate the Select instances, define once and reuse:

currency = Select(self.driver.find_element_by_id("currencyid"))
excur = Select(self.driver.find_element_by_id("excur"))

currency.select_by_visible_text("AUD")
excur.select_by_visible_text("AUD")

assert currency.first_selected_option.text == "USD"  # should not be "AUD"?
assert excur.first_selected_option.text == "CAD"  # should not be "AUD"?

If you have more select elements, this approach would not scale well, you can further improve the code and put the logic into a loop, something like:

values = [("currencyid", "AUD"), ("excur", "AUD")]
for id, value in values:
    select = Select(self.driver.find_element_by_id(id))
    select.select_by_visible_text(value)

    assert select.first_selected_option.text == value


Find the sum of all digits that match the following digit in a circular list

foldIndexed -> fold

The foldIndexed line can be replaced with:

.fold(Carry(-1, -1, 0)) { (first, last, total), value ->

This is because the indexed part is unused

Using a data class

A data class can be used to make the values passed along the fold operation more obvious.


Let's imagine this problem as building a histogram. We draw out an X axis of 100 (0 <= x < 100, as given by the problem). For each element that we're given, we move the bar up by one in the histogram.

For something like this we have Data.Array. We can build an Array Int Frequency that will map each number to the frequency of the number. Each insertion into the array will be O(1). Initializing the array will also be O(1) since the size of the array is fixed. We'll just have the computer set aside 100 slots of memory for us up top, every time. This should lead to a running time of initialization + n * insertion = O(n), which indeed beats O(n lg n).

Our function will have this type:

count :: [Int] -> Array Int Int
count input = _

The best way to build an array is to ... uh ... I never remember. So we consult the docs, specifically the array construction section. There's a function here called accumArray that folds over a list of (index, value) tuples – that is, it walks each tuple and uses it to accumulate into a value into the array that is returned back to us. In our case, each tuple will be (number, 1): we'll have it so that each tuple represents a single count of the number. Our job is then to convert  a bunch of tuples like this

(2, 1) (5, 1) (5, 1) (3, 1)

to a histogram like this

0: 0
1: 0
2: 1
3: 1
4: 0
5: 2

Back to our code:

count :: [Int] -> Array Int Int
count input = accumArray _ _ (0, 99) (zip input (repeat 1))

The trick here is that repeat 1 is an infinite array, but we know input is finite and zip terminates when either argument terminates.

It remains to specify the accumulating function, which takes two arguments (the frequency of the number thus far and then second value of our tuple, which is always the number 1) and is supposed to return the new frequency. This is as simple as incrementing the old number, or just adding one.

count :: [Int] -> Array Int Int
count input = accumArray (\old one -> old + one) _ (0, 99) (zip input (repeat 1))

This being Haskell, we can simplify this to

count :: [Int] -> Array Int Int
count input = accumArray (+) _ (0, 99) (zip input (repeat 1))

For the greater good. And we're done! Oh, and we need to specify a default frequency for values that we didn't encounter in the list. For us, that's a simple zero.

Combining this with your IO code that reads from stdin, we get:

import Data.Array
import Data.List

main :: IO ()
main = do
  _ <- getLine
  numbers <- getLine
  (putStr . unwords . map show . elems . count . map read . words) numbers

count :: [Int] -> Array Int Int
count input =
  accumArray (+) 0 (0, 99) (zip input (repeat 1))

And if we wanted to be a smart-ass we could golf the solution into a one-liner:

import Data.Array
import Data.List

main :: IO ()
main = getLine >> getLine >>= (putStr . unwords . map show . elems . accumArray (+) 0 (0, 99) . flip zip (repeat 1) . map read . words)

I think that last line even fits into a tweet.


Consider replacing this:

Student(std::string name) {
    this->name = name;
}

with one of these two:

Student(std::string n)
: name{ std::move(n) } // assign here, not in function body
{
}

Student(const std::string& n)
: name(n) // assign here, not in function body
{
}

They are more efficient and more idiomatic.

The first takes the argument by value (constructs a string copy when it receives an argument) , then moves the constructed value into Student::name.

The second is marginally faster than the first (but this speed difference should not matter in most use cases, so which you choose is a matter of style), but it doesn't express as well as the first, the idea that Student gets it's own copy of the string (passing by value means "the function gets it's own copy of the value", or "the function takes ownership of the argument").


Python function to find all integers between two numbers whose sum of squared divisors is a perfect square

There is no need to go up to the number to know its factor, going up to the sqrt is enough:

def D(x):
    return sum(i**2 + int(((x / i) ** 2 if i * i != x else 0))  for i in range(1, floor(x ** 0.5) + 1) if not x%i)

That should speed up quite a bit the computation if you are dealing with big numbers


Compiler warnings

Always compile with warnings turned on.  Your compiler should have warned you that offset is an unused variable.  My compiler also complained about passing an unsigned int as an argument to printf("%*") with height - (i < ARRSZ(angel) ? ARRSZ(angel) : i + 1).

Error handling

The output should either be a Christmas tree or nothing at all.  Printing an error message in place of a tree is just mean.

If you must print an error message, print it to stderr!

Code formatting

Why not make the angel look like an angel in your code?  Granted, the double backslashes interfere with the alignment, but at least you could try.

const char * const angel[] = { " ._.",
                              "(\\o/)",
                               ")/|\\(",
                               "/_*_\\", };

Looping

With those conditional expressions within the loop, you might as well split it into two loops:

for (i = 0; i < ARRSZ(angel); ++i) {
    printf("%*s%s\n", height - (int)ARRSZ(angel), "", angel[i]);
}
for (; i < height; ++i) {
    printf("%*s%s\n", height - i - 1, "", stars + ARRSZ(stars) - 2*i);
}

Here, I've also rewritten &stars[ARRSZ(stars) - 2*i] using the more idiomatic pointer arithmetic.

Alternate solution

If you ensure that each line of the angel has the same length, then you could also write the printf() calls as

const char * const angel[] = { " ._. ",
                              "(\\o/)",
                               ")/|\\(",
                               "/_*_\\", };

for (i = 0; i < ARRSZ(angel); ++i) {
    printf(" %*s\n", (int)(height - ARRSZ(angel) + ARRSZ(angel[0]) / 2), angel[i]);
}
for (; i < height; ++i) {
    printf("%*.*s\n", height + i - 2, 2 * i - 1, stars);
}


Most frequent word in an array of strings - Java

As you noticed, searching for your entries is adding to your time complexity, because you have to run down your queue. Priority queues are very good at polling the top element, but not optimized for searching for specific entries.

You can optimize for searching by using a Map<String, Integer> for counting frequency, and then use a NavigableMap<Integer, Set<String>> for maintaining order (1). Adding an entry will look like this:

NavigableMap<Integer, Set<String>> ordered;
Map<String, Integer> frequency;

void add(String word) {
  int count = frequency.getOrDefault(word, 0);
  if ( count > 0 ) {
    ordered.get(count).remove(word);
  }
  ordered.computeIfAbsent(count + 1, HashSet::new).add(word);
  frequency.put(word, count + 1);
}

(1) If you're confident about your data being densely distributed and bounded, you can replace this with an array for quicker access—approaching O(1) i.o. O(log N)—but it's going to make your code messier dealing with edge cases.

I do have two recommendations for your code.

When searching for an element in the queue, you can abort once it's found. On average, this will halve your time spent searching:

Iterator<MyWord> itr = queue.iterator();
while (itr.hasNext()) {
   MyWord next = itr.next();
   if (next.getWord().equals(word)) {
       oldWord = next;
       break;  // <-- found, abort search
   }
}

And a nitpick from an 'elegance' point of view: consider adding a method to MyWord that creates a new, incremented instance. Right now, outside code is accessing the fields and creating new instances with it. This is something MyWord can handle internally.

public MyWord incremented() {
    return new MyWord(count + 1, word);
}


Making sequence unique with removal records

Generally, this seems to be readable code.  I would just note a few possible improvements:

Use a std::vector instead of a std::map

The std::map may be appropriate if you plan on doing frequent lookups of the key values, but a std::vector might be a less expensive storage mechanism than std::map otherwise.

Prefer for to while loop

The while loop may be more intuitively written as a for loop, as shown in the code below the next suggestion.

Consolidate loops

As you've asked in your question, yes, the separate loop can be eliminated.  Once the pair of iterators (it1 and it2) are found, simply use erase with those as parameters:

template <typename SequenceType>
std::map<std::size_t, std::size_t> collapse(SequenceType& sequence, char c)
{
    std::map<std::size_t, std::size_t> result {};

    std::size_t position {}, num_removed {};
    auto last = std::end(sequence);

    for(auto first = std::begin(sequence); first != last; last = std::end(sequence) ) {
        auto it1 = std::adjacent_find(first, last, [c] (char lhs, char rhs) { return lhs == c && lhs == rhs; });

        if (it1 == last) break;

        auto it2 = std::find_if_not(it1, last, [c] (char b) { return b == c; });

        position    += std::distance(first, it1);
        num_removed += std::distance(++it1, it2);

        result.emplace(position, num_removed);
        first = sequence.erase(it1, it2);
    }

    return result;
}

Because std::erase returns an iterator following the last erased value, this also provides a handy way to update first.  Also, by incrementing it1 within the num_removed update, we eliminate the need to subtract one and automatically correct the first iterator so that we eliminate only duplicate Ns and not all of them.

Consider the use of std::regex

It occurs to me that rather than use compress at all, perhaps std::regex might be better suited to solving this particular problem by eliminating the need to do preprocessing at all.  That is, with the proper regex, the notion of "one or more N's" is very quickly and easily represented.  Naturally, this assumes a more restrictive possibility range than a generic sequence object, but if your sequences are already std::string types, this may work very well.


Your getLocation can be improved a little:

For a start, the call parameter should be const (although if you were happy
modifying the string you could avoid the memory allocation).

Moving on:

const char *p1 = strstr(source, "Location:")+10;

This is ok, except that p1 is cryptic and it is better to avoid embedded constants such as 10. Since this is the length of "Location:", we can extract that:

#define LOC "Location:"
const char *loc = strstr(source, LOC) - 1 + sizeof LOC;

Note the -1 for the \0 at the end of LOC. But it is now uglier still.  And of
course it might fail, returning NULL.  So we need to protect the next line:

const char *p2 = strstr(p1, "\n");

in which you are looking for just one character; strchr is more appropriate and eol is a more descriptive name:

if (loc) {
    const char *eol = strchr(loc, '\n');
}

So next you get the length

size_t len = p2-p1;

which needs a cast to avoid a sign-conversion warning:

size_t len = (size_t) (eol - loc);

You allocate memory next:

char *res = (char*)malloc(sizeof(char)*(len+1));

but you should omit the cast and note that sizeof(char) is 1 by definition,
so:

char *res = malloc(len + 1);

and of course allocation could also fail, so you must check before copying the
address into it.  You copy the address thus:

strncpy(res, p1, len);
res[len] = '\0';

but as you already know the length of the string, memcpy would be better, as
strncpy must check each char in the input string for \0

if (res) {
    memcpy(res, loc, len);
    res[len] = '\0';
}

Putting it all together, we get:

static char* getLocation(const char* source)
{
#define LOC "Location:"
    size_t len = 0;
    char *eol = NULL;
    const char *loc = strstr(source, LOC) - 1 + sizeof LOC;
    if (loc) {
        eol = strchr(loc, '\n');
    }
    if (eol && loc) {
        len = (size_t) (eol - loc);
    }
    if (len) {
        char *res = malloc(len + 1);
        if (res) {
            memcpy(res, loc, len);
            res[len] = '\0';
        }
        return res;
    }
    return NULL;
}

Yes, string handling in C is ugly.

My conclusion from this ugliness is that another approach is needed.  Why not
modify the input string by putting a \0 at eol and returning loc?  Then
you could extract the address and port directly from that:

static char* getLocation(char* source)
{
#define LOC "Location:"
    char *loc = strstr(source, LOC) - 1 + sizeof LOC;
    if (loc) {
        char *eol = strchr(loc, '\n');
        if (eol) {
            *eol = '\0';
        }
    }
    return loc;
}


Nesting Branches

You were worried your code might be a bit ugly. I consider deeply nested branches ugly aka a penalty in readability when they can easily be avoided. For example, your function indents the entire while-loop body to perform this little branch at the end:

if (byte xor IFM_FRAME_HEADER == BYTE_ZERO) {
    // branch body ..
} else {
    index++
}

You could invert the branch condition, use an early continue and avoid nesting branches.

if (byte xor IFM_FRAME_HEADER != BYTE_ZERO) {
    index++
    continue
}
// other code in while-loop no longer needs indentation ..

Shifting the input

You have 3 occasions where you shift the input array to the next index index++. 2 of these have conditions that guard when to shift, the 3th is an exception handler for type IllegalArgumentException. Consider refactoring the code to have only a single connection point in the code where you perform the shift index++. This increases maintainability of the code. You can do this be either (1) trying to avoid the exception and using a condition instead, and use a single flag shouldShift marked true on any of the conditions or (2) throw exceptions for all conditions that require shifting and have a single exception handler performing the shift.

Flow Integrity

The callback invocation  emitter.onNext(canFrame) sits within the try-catch block. This means that if the callback would throw an IllegalArgumentException you'd be shifting the input index++ while you shouldn't have. Ensure callback invocation does not trigger such shifting.


Fraction or percentage regular expression

Your regex accepts (20/) as valid input, and I suspect that you didn't intend to consider it valid.

Your regex rejects one-digit numbers.  If that is intentional, you might want to write a comment about it in the code.

As you suspected, this is a very "noisy" regex — nearly unreadable.  This expression would do the job:

String regex = "\\( *(\\d{2}) *(?:/ *(\\d{2}) *)?\\)";

There is no need to wrap everything in [ ].  In this particular problem, there aren't even any character classes to speak of.  The only place where the square brackets might be justified is as a hack to formulate the expression with fewer backslashes:

String regex = "[(] *(\\d{2}) *(?:/ *(\\d{2}) *)?[)]";

In (?:[ ]*)?, the square brackets are pointless.  The ? is redundant with *.  So, you can just write a space followed by *.

In ([\d][\d]), the square brackets are pointless, and I would slightly prefer seeing (\d{2}) to (\d\d), since it can more easily be modified to accommodate different numbers of digits.

You might want to consider naming the capture groups for clarity:

String regex = "\\( *(?<numerator>\\d{2}) *(?:/ *(?<denominator>\\d{2}) *)?\\)";


You allocate a memory block:

char * str_c = malloc(str_c_len);

and then pass it to the strlen():

if (strlen(str_c) == 0)
    ....

Apart from the str_c == NULL condition, described by @sanecz, you can not expect any meaningfull result from that test. It can even cause a crash!
That's because malloc() is not defined to initialize the allocated block of memory in any way. It can contain a zero byte at any position, which will cause strlen() to return any value less than the requested size of the block str_c_len; or it can contain no NUL byte at all, which will cause strlen() to scan past the allocated block and trigger an Undefined Behavior.

Additionally, you do not need the allocated block. If you want only to make an interleaved output, just do that: print characters in appropriate order.

int main(int argc, char const *argv[])
{
    // Expecting: exe name, str_a, str_b
    if (argc != 3)
    {
        return EXIT_FAILURE;
    }

    size_t str_a_len = strlen(argv[1]);
    size_t str_b_len = strlen(argv[2]);
    if (str_a_len != str_b_len)
    {
        return EXIT_FAILURE;
    }

    for (int i = 0; i < str_a_len; ++i)
    {
        putchar( argv[1][i] );
        putchar( argv[2][i] );
    }

    putchar('\n');

    return EXIT_SUCCESS;
}

EDIT

As for the comment 'this was mainly an exercise in string
manipulation': if you want to improve your programming skills, and string
manipulation among them, then I'd recommend to organize your program
into separate functions. For example:

let main() fetch input data and pass it to some processing routine,
then print the output;
let some MakeInterleavedString() validate input and prepare output
buffer;
and let some InterleaveTwoStrings() do actual processing.

For example:

char *InterleaveTwoStrings(const char *l, const char *r, char *sum)
{
    // assume input strings l, r of equal length
    // and output buffer sum twice that long

    char *out = sum;      // the place where output goes
    while(*l != 0)        // input not exhausted yet
    {
        *out ++ = *l ++;  // copy one char and advance input
        *out ++ = *r ++;  // and output positions
    }
    *out = 0;             // terminate the output string

    return sum;           // return the filled buffer
}

char *MakeInterleavedString(const char *l, const char *r)
{
    // test if strings l, r are equal length,
    // prepare a buffer to accomodate l,r contents
    // interleave data into a buffer and return it;
    // return NULL on error

    int llen = strlen(l), rlen = strlen(r);
    if(llen == rlen)
    {
        if(char *sum = malloc(2*llen + 1))    // +1 for terminating NUL char
            return InterleaveTwoStrings(l, r, sum);
    }

    return NULL;   // on (llen != rlen) or malloc() failure
}

int main(int argc, char const *argv[])
{
    // Expecting: exe name, str_a, str_b
    if (argc == 3)
    {
        const char *str_a = argv[1];
        const char *str_b = argv[2];

        if (const char *str_c = MakeInterleavedString(str_a,str_b))
        {
            printf("%s\n", str_c);
            free(str_c);
            return EXIT_SUCCESS;
        }
    }
    return EXIT_FAILURE;
}

Please note the call to free() function – it's not that important in such simple program, as all the allocated memory goes back to the operating system on the program termination. However, in library functions we should always release temporary buffers as soon as they are no longer used. Otherwise we may forget to release them later, and we may cause so called 'memory leaks', when long running process consumes more and more memory for no reason.


Identifying indices of non-delimited characters in a string, supporting greater than 1 length of delimiters

Some off the cuff comments:
It would help if you provided a compilable class rather than a somewhat misleading snippet.
Your search would be better as a separate method.
I don't see why you search in this way when String.indexof(String) and String.substring(int) exist.
Have you a clear understanding of how you would handle overlapping delimiters? If your delimiter is "!!", how is "abc!!!def" to be interpreted?


In my opinion using the repository pattern is absolutely fine, for a number of reasons, not limited to:

It enables unit testing
Allows you to change EF for a another DB technology

The detail that you have to be careful of using the base class is that you make sure that you declare properties/variables via the interface and not via the base class. So consider this:

Good

public class Test{
    private IRepository<MyClass> _repo;
}

Bad

public class Test{
    private BaseRepository<MyClass> _repo;
}

With the actual code, I would suggest a number of changes:

The interface should have full CRUD operations
Try and use the same name for fetching a record (Consider Get() and Get(id) vs All() and Get(1). It makes it more natural to consumers)
The class Repository should be marked as abstract to stop you using it directly
The class Repository should probably be named EFBaseRepository

Typically, when I implement the pattern I create the interface followed by a class called BaseRepository that implements all the methods. The methods no nothing more than throw a NotSupportedException/NotImplementedException. This is because I might only want consumers to have read/update but not create. It does depend on the context of the application.


How can I convert this to a generic method?

You could receive a lambda that adds parameters.

public static DataTable GetData(string connString, string sqlStatement, Action<iDB2ParameterCollection> addParameters)
{
    DataTable dt = new DataTable();

    using (iDB2Connection conn = new iDB2Connection(connString))
    {
        using (iDB2Command cmd = new iDB2Command(sqlStatement, conn))
        {
            conn.Open();
            if(addParameters != null) {
                addParameters(cmd.Parameters);
            }
            using (iDB2DataAdapter da = new iDB2DataAdapter(cmd)) { da.Fill(dt); }
            conn.Close();
         }
    }

    return dt;
}

//...
GetData(connStr, sqlStatement, parameters => {
        parameters.Add("@custnumber1", iDB2DbType.iDB2Decimal).Value = id;
        parameters.Add("@custnumber2", iDB2DbType.iDB2Decimal).Value = id;
    });

Edit: I suggest reading about the different delegates: Action; Func; Predicate.
https://stackoverflow.com/questions/566860/delegates-predicate-action-func

In a nutshell:

Action does something;
Func is the same as an Action, but with a return value;
Predicate<T> is the same as Func<T, bool> but a bit more semantically significant.


As you guessed, you can make your code much more performant/robust by using % instead of for loops to convert the distances.

An example with just yards you would do something like:

m = 0;
y = 1761;
m += (y / 1760); // add the number of whole miles
y = (y % 1760);  // set to the number of remaining yards

At the end of that you'll see that:

m == 1
y == 1


The C standard does not guarantee that an int is 32 bits.  Even though the problem guarantees that 0 ≤ n ≤ 31, your code fails if run on a machine with a 64-bit int.  One way to resolve that problem is to be explicit about the size of your inputs:

#include <stdint.h>

int32_t logicalShift(int32_t x, int n) {
    …
}

The C standard says (C99 §6.5.7):

  The result of E1 >> E2 is E1 right-shifted E2 bit positions. If E1 has an unsigned type or if E1 has a signed type and a nonnegative value, the value of the result is the integral part of the quotient of \$\dfrac{\mathrm{E1}}{2 ^ \mathrm{E2}}\$. If E1 has a signed type and a negative value, the resulting value is implementation-defined.

Therefore, your best bet is to treat x as an unsigned type:

int logicalShift(int x, int n) {
    return (unsigned int)x >> n;
}


Spawning futures as an alternative to multithreading

I see some things that may help you improve your code.

Simplify your code using literals

There is nothing intrinsically wrong with std::chrono::milliseconds(0) but I would prefer to read (and to write) 0ms instead.  This can be done by adding this line to within main:

using namespace std::literals::chrono_literals;

Use more meaningful variable names

I understand that it's just a toy program, but I really think we can do better than varI and varJ!  Since it's just a freerunning counter, why not just call it count?

Understand the threading model

It's important to realize that std::future was designed to hold not only the future value (or exception) but also a flag for the future_status.  This renders the current code's flag unnecessary.  Here's a more concise rewrite of main:

int main()
{
    using namespace std::literals::chrono_literals;
    int count = 0;
    std::future<int> future = std::async(std::launch::async, thread, count);
    while(1) {
        if (future.wait_for(0ms) == std::future_status::ready) {
            std::cout << "\t result is " << future.get() << '\n';
            future = std::async(std::launch::async, thread, count);
        }
        ++count;
    }
}

Beware of sharing unsynchronized variables

Right now, both the thread running main and the thread running the function write to std::cout.  The way the code is currently structured (both in the original and in the rewrite above), they do not contend for that same variable but they could because there currently is no synchronization.  The effect is that the output of the two threads could easily be interleaved.  The easiest way to prevent this is to only access cout from a single thread.


Is there a more succinct way of writing this simple JavaScript loop?

I think at the very least I'd rearrange the cases to make the dichotomy between Array.isArray and !Array.isArray more direct and apparent:

while (i < x) {
    if (typeof arr[i] === 'string') {
        text = arr[i];
    }
    else if (typeof arr[i] === 'object') {
        if (Array.isArray(arr[i])) {
            child = arr[i];
        }
        else {
            attr = arr[i];
        }
    }
    i++;
}

That's not really a lot shorter but I think it makes the intent rather more clear (at least assuming I've divined the real intent correctly).


Other, similar libraries don't require you to pass everything to the constructor. What if you want to send an email to more than one person? You should be able to call $mailer->setTo() more than once.

For now, I would suggest getting rid of the constructor entirely, and calling the setters manually as needed. After all, if you're planning on doing the entire operation in one call then you might as well write a function instead of a class.

If you're going to implement setter methods then you should make your properties private or protected so they can't be changed manually by whoever is using your class. Usually, the setters are implemented so you can validate input before setting them, for example,

public method setTo($email){
    if(filter_var($email, FILTER_VALIDATE_EMAIL)) $this->toEmail = $email;
    else $this->lastError = "Invalid to email: {$email}.";
}

Now you can prevent the user from manually setting $mail->toEmail by marking it as private, thus, forcing the input to be validated by your setter.

You're not using your toName parameter and you're only allowing a single receiver. Check out the manual and you'll notice that you can have multiple recievers and you can specify a name for each one in the following format:

  User <user@example.com>, Another User <anotheruser@example.com>

Therefore, you should have an array for your toNames and another array for your toEmails.

public method setTo($email, $name=""){
    if(filter_var($email, FILTER_VALIDATE_EMAIL)){
        $this->toEmail[] = $email;
        $this->toName[] = $name;
    }else $this->lastError = "Invalid to email: {$email}.";
}

Then, in your send function...

$to = "";
foreach($this->toEmail as $k=>$v){
    if(!empty($this->toName[$k])) $to .= "{$this->toName[$k]}<$v>,";
    else $to .= "$v,";
}
$to = rtrim($to, ","); // trim off trailing comma

If you're not sending an HTML email you should wordwrap your $message parameter at 70 chars. (You can create a variable to determine if the email will contain HTML).

if(!$this->isHTML) $message = wordwrap($message, 70, "\r\n");

If it is HTML you have to let the client know by adding these headers:

$headers .= 'MIME-Version: 1.0'."\r\n".
    'Content-type: text/html; charset=iso-8859-1';

You can also carbon copy someone with this header:

'Cc: birthdayarchive@example.com'

Anyway, you're on the right track, but make sure you read the manual to see what other cool stuff you could be doing.


Find an order with the minimum total price

Your prezzo() function is very inefficient: for every line, you scan every line in OR to for a matching o, which makes your algorithm O(n2).  To make it worse, you call it from twice from ordine_min(), doubling the work!  Ideally, the calculations should be done in one single pass through OR.

Your code is also very hard to read and understand, due to cryptic naming — OR, i, OR[k][2] * OR[k][3].  Using destructuring assignments can help improve readability.

from collections import Counter

def ordine_min(ordini):
    prezzi_neg = Counter()
    for ordine, articolo, quantità, prezzo in ordini:
        # The Counter can efficiently find the maximum total.  We calculate
        # negative prices to trick it into finding the minimum instead.
        prezzi_neg[ordine] -= quantità * prezzo
    for ordine, prezzi_neg in prezzi_neg.most_common(1):
        return -prezzi_neg, ordine


Choosing a CSS class based on an HTTP status code

One very important principle of modern software design is that mutability should be minimised. The first case needlessly introduces mutability by potentially modifying the value of statusCodeCssClass. Thus I'd argue it's bad practice to write code like this, regardless of whether it's easier to read (which is a completely subjective claim as both are simple and easy-to-read).

However, the second approach ignores the fact that JavaScript supports an idiomatic solution to to a "test a value and return one of two results based on that test" problem: the ternary operator. This can be used in this situation to yield a third solution that makes better use of language features:

function getCssClass(options) {
    var statusCode = parseInt(options.statuscode, 10);
    return (statusCode >= 100 && statusCode < 200) || statusCode >= 400) ? 'text-danger' : '';
}

However, the code could be further improved by respecting the single responsibility principle. The function should only have one responsibility. Currently, it has two: it extracts the status code from options and it returns a CSS value based on that code. By splitting out obtaining the status code into another function, this one becomes more focused.


Naming things
Avoid single-character variable names, unless it's something that is very commonly used, like i for a loop index. Consider r and c, even if you guess it has something to do with coordinates, are those positions or sizes? I would personally use width and height here as unambiguous names for the size of the grid.
Note that in the constructor's initializer list, you can use the same name for the parameter as for the member variable, like so:
int width;
int height;

public:
Connect4(int width, int height): width(width), height(height) {...}

Not everyone likes this style; some people want to disambiguate between parameter and member variable by writing:
Connect4(int width_, int height_): width(width_), height(height_) {...}

And you also see projects where all member variables are prefixed with m_, so it will look like:
int m_width;
int m_height;

public:
Connect4(int width, int height): m_width(width), m_height(height) {...}

Other variable names that could be improved:

cnt -> count
itr -> it (the latter is more idiomatic)
diag -> diagonal
verify -> line

Create an enum class for the possibly contents of a grid cell
An enum, and even better an enum class, allow you to specify the possible values of a grid cell up front, with names instead of integer values. I suggest you write the following:
class Connect4 {
    enum class Cell: char {
       EMPTY,
       PLAYER1,
       PLAYER2,
    };
};

The above also explicitly sets the type to char, so only one byte is necessary to store it.
Storing the grid
There are several things wrong with how you store the grid. The data structure you are using is very inefficient, both for large and small grids, and for checking for a winning condition. The best way is to use a single vector to store all the grid cells:
std::vector<Cell> grid;

This ensures things are laid out very compactly in memory, and to look up an arbitrary grid cell, the CPU only has to do one multiplication and two additions, which is very cheap on contemporary processors, and as Toby Speight already mentioned, to check horizontal, vertical and diagonal lines is very easy as well; just calculate the start point, end point and stride to use, and then every step along the line only a single addition has to be done to find out the grid cell to check.
I would add a function to get a reference to a grid cell given its coordinates, like so:
Cell &at(int row, int col) {
    return grid[row * c + col];
}

Handling huge grids
The first thing to consider when dealing with huge grids/arrays/matrices is whether the data structure is going to be densely or sparsely populated. It's easy to think that it should be sparse, after all you start with the grid being completely empty. But consider that during the end game of connect 4, you will probably have used more than half of the grid cells, so a dense grid is likely the best way to store the state.
With the above Cell type, you use one byte per grid cell. Since a cell only has three possible states, you could pack up to five cells in a byte (since 3⁵ = 243) relatively easily, at the cost of some extra calculations when reading/writing a given cell. With this, a 100,000 by 50,000 grid fits in a little less than a gigabyte.
You might also think about compressing the grid somehow, but again consider what a connect 4 game looks like near the end. For sure there won't be runs of more than 3 cells with the same color in a row, otherwise there would already have been a winner. And you rarely see a repetitive pattern appearing. So it basically looks like noise, which is not compressible. Perhaps predictive coding could be used to compress the sequence of moves made by the players, but the compressed data would most likely not be in a form suitable for displaying the grid and checking winning conditions.
The only option I see for significantly reducing the amount of data is to consider that the bulk of the grid cells where players have already played will never be part of the 4 connected cells of the same color. For example, you could mark all cells that are more than 3 positions away (both horizontally and vertically) from any empty cells as being "dead". This way, that in principle, instead of having to store \$\mathcal{O}(W \cdot H)\$, you only have to store \$\mathcal{O}(W + H)\$ grid cells. But that would mean that you cannot show exactly all the moves made so far anymore.
Checking for a winning condition
Your idea of keeping a per-line score is unfortunately not really helpful. It is quite easy to create a line where the total score would be four, but there are no 4 consecutive cells with the same player, for example, representing players 1 and 2 with O and X respectively:
X O O X O O X O O X O O

There are 8 pieces of player 1, and 4 of player 2, so your way of counting score would result in 4 or -4, but clearly no player has won yet. However, if player 1 adds two more O's to this line:
X O O X O O X O O X O O O O

Then player 1 has 4 in a row, but the "line score" would be 6 or -6. So the line score is not useful.
The simple solution is to just always check the 9x9 area surrounding the latest move for a horizontal, vertical or diagonal line with 4 in a row. This might seem a bit wasteful in the very early game when only few moves have been made, it doesn't really matter in the long run.


Image upload and thumbnail creation script using PHP GD

It's considered better to omit the closing ?> of the PHP file.

If you're wondering why, there are a few rare situations in which you can accidentally have whitespace trailing the closing tag and issues will result. Since PHP doesn't require the closing tag anyway, it's safer to just always omit it.

I'm a bit skeptical of validate.php. What exactly is it doing? Is it processing user input, or bootstrapping, or what? I suspect it's doing way too many things (processing user input and bootstrapping). It's a bit uncomfortable to me that $hash_query likely has some kind of user input going into it, yet it cascades through another file.

It would be a lot cleaner and cleaner to instead have a getSpeakerByHash() function.

Why is the mysql_fetch_assoc in a loop? It seems it's only actually operating on one row.

Since you don't use most of the variables that come from the hash_query stuff, I wouldn't bother even defining them. They're just clutter.

Also, instead of pulling the values out into independent variables, I would instead give $hq a more meaningful name (perhaps $speaker or something). That makes it a lot clearer that the variables are related, and it makes it a bit easier to see where they came from.

What happens if the mysql_fetch_assoc call doesn't return anything? You should handle that situation. (Although it might not actually be possible for there to not be a result since I have no idea where hash_query is coming from.)

Once again, with the $_FILES stuff, I would defined a $file = $_FILES['file'] and then access into that array. Not only does it cut down on the clutter of defining 5 variables only to use each one once or twice, it makes it clearer that everything is related in one group.

$errors   = $_FILES['file']['error']; is prone to emit a warning if a request is submitted without a file field. This means that you should be checking if the field exists:

if (isset($_FILES['file'])) {
    $file = $_FILES['file'];
} else {
    // Error
}

$extension = pathinfo($filename, PATHINFO_EXTENSION);

Should be a little cleaner than exploding and accessing the last array element.

Since the filetype comes from the client side, you can't trust it at all. I wouldn't even bother checking it. I would just check the extension, and then if the extension is allowed, check if it can actually be opened as a jpg.

You should pull 10485760 into some kind of configuration management. That way, if you want to change it to something else later, you don't have to go digging around for it. Also, it might be clearer to have it as 10*1024*1024 since that's immediately clear to be 10MB.

Since $timestamp is only used once, I would just do the date call inline instead of having it out in a variable.

Instead of a deeply nested if-tree, I would use an if-else flow to keep things flatter:

if (!blah) {
    closeCon(x, "...", "...");
} else if (!bleh) {
    closeCon(y, "...", "...");
} else {
    // Do actual work
}

Don't use $errors == 0. UPLOAD_ERR_OK is much clearer.

You should make sure move_uploaded_file doesn't fail. If it does, you'll end up with a DB record that has no matching file with it. This can be fixed by either using a transaction and rolling back if the move fails, or more simply, just do the insert after the file moving. (Technically you can then have a file without a DB record, but that will likely be less bad.)

Don't reuse variable names ($filename). It's confusing to others reading your code, and it's prone to error.

I've cut out the irrelevant code, but consider this:

if ((($filetype == "image/jpg") ||
    ($filetype == "image/jpeg")) && in_array($extension, $extensions)) {
    $filename = $speaker_id . "_" . $timestamp . "_photo." . $extension;
    $md = explode(".", $filename);
    if (end($md) != "eps") {

$md can't be eps. md will always be a value that's in $extensions.

With regards to the Location header, technically it's supposed to have a full url (i.e. http://.../... rather than a relative url). No browser actually requires this, and all of them act as expected, but it's worth knowing that they're not technically required to, nor is there a guarantee that future browsers will.

It would be cleaner for closeCon to take an array as the third parameter and build the query string internally with http_build_query. It also means that callers to closeCon don't have to handle potential URL escaping.

Resizing an image seems a pretty clear cut requirement that might be nice to push into a function rather than embedding in the upload functionality. resizeImageToMaxWidth is also clear enough that it's understandable at a glance rather than having to either comment it or read 10 lines of code.

Rather than using "uploads/" . $filename twice, I would create a $filepath variable that contains the entire relative path. This means that you can avoid the potential bug of changing one of the uploads and not the other.

It might also be nice to make uploads configurable.

With your insert queries, you should be checking that they succeed. The query never should feasibly fail, but you'll very much want to know if it ever does for some weird reason.

And, if you're not going to check that they succeed, there's no point in assigning them to variables.

I tried not to harp on this since you already seem aware of it, but PDO's exception throwing is a rather nice way of having errors crop up from queries when you don't actually expect them to happen, but you really should know if they do, as in this case.

With regards to the first parameters of closeCon, it would be nice to pull those numbers into constants. I have no idea what any of them mean, and you likely won't either 3 months from now.

Unfortunately my knowledge of image processing is very limited, but I can tell you that I tend to prefer imagemagick over GD. I have no proof of this, but in the few situations I've used both, IM seems to perform the same functionality a bit snappier than GD.

The only other thing I can tell you is that image processing is surprisingly memory intensive and you might just need to crank up the amount of memory script executions can use. GD at some point probably represents the image as a matrix of pixels. This means that the amount of memory required isn't the size of the image but rather the resolution multiplied by colors per pixel. That means that a simple 8 megapixel picture could be 32MB of memory whereas the JPG compressed version would likely only be 5MB.

This SO question seems to have had a similar problem to you and might be worth looking into.