Short answer:

You can include setExpanded in the dependency array.

Long answer:

The function passed to useEffect will fire only when at least one of the dependencies changes:

useEffect(() => {
  // runs
  // - on mount
  // - on every render
})

useEffect(() => {
  // runs
  // - on mount only
}, [])

useEffect(() => {
  // runs
  // - on mount
  // - on renders where varA and/or varB change
}, [varA, varB])

You should avoid passing objects as dependencies, because they may trigger unnecessary re-renders. If varA is an object created on every render, it may have the same value but it won't be the same object, so it will be treated as change and fire up the useEffect. See the example below:

const varA = { a : 1 }
const varB = { a : 1 }

varA === varB // false

However, sometimes, certain objects are guaranteed to not produce this behaviour, and this is the case of the setState() function.
According to the React Hooks API docs:

  Note: React guarantees that setState function identity is stable and won’t change on re-renders.

This means that you can include it in the useEffect dependencies with no problem.


public void steppingNumber(int s, int e) {

As described in the problem statement, s is the starting number and e is the ending number.  Why not call them start and end then?  That way we don't have to refer to the problem statement to know what the variables mean.

I would also pick another name for the function.  You are printing the stepping numbers, so call it printSteppingNumbers.  As a general rule, functions should have verb names.  They do things and their names should reflect that.

    String str = String.valueOf(s);

Why a string?  In C, this would make sense as the difference between a letter and a number in C is trivial (char is an integer type).  Java isn't as forgiving.  Even if you do want a string, this is the wrong place to do it.  Call the function with s (or start).

    if ( isSteppingNumber(start) ) {
        System.out.print(start + " ");
    }

I added braces ({}) around the then clause.  This helps avoid a class of error where someone intends to add a new statement to the then clause but actually makes it run whether the if triggers or not.  I also find it easier to read.

List<String> numbers = new ArrayList<>();

while(str.length() >= 3) { // get every 3-digit comma-separated number
    numbers.add(str.substring(str.length()-3));
    str = str.substring(0,str.length()-3);
}

This seems overly complicated.  You don't need to generate a List here.  It's sufficient to check each chunk as you go through.

while ( str.length() > 3 ) {
    if ( ! isSteppingSequence(str.substring(str.length()-3)) ) {
        return false;
    }
    str = str.substring(0,str.length()-3);
}

return isSteppingSequence(str);

You also don't need >= here.  A simple > is better, as you always want there to be one chunk left to test outside the loop.

But we can do better if we keep it as a number at this point.  First, we need a constant.

private final static int CHUNK_SIZE = 1000;

Now we can use it.

    while ( number > CHUNK_SIZE ) {
        if ( ! isSteppingSequence(number % CHUNK_SIZE) ) {
            return false;
        }

        number /= CHUNK_SIZE;
    }

    return isSteppingSequence(number);

Another constant.

private final static int BASE = 10;

Now we just need to define isSteppingSequence and we get:

private final static int BASE = 10;
private final static int CHUNK_SIZE = 1000;

private static void listSteppingNumbers(int start, int end) {
    while ( start <= end ) {
        if ( isSteppingNumber(start) ) {
            System.out.print(start + " ");
        }

        start++;
    }
}

private static boolean isSteppingNumber(int number) {
    if ( number < BASE ) {
        return false;
    }

    while ( number > CHUNK_SIZE ) {
        if ( ! isSteppingSequence(number % CHUNK_SIZE) ) {
            return false;
        }

        number /= CHUNK_SIZE;
    }

    // all the other sequences were stepping, so
    // if this one is, it's a valid stepping number
    // otherwise not
    return isSteppingSequence(number);
}

private static boolean isSteppingSequence(int number) {
    int previous_digit = number % BASE;
    number /= BASE;
    while ( number > 0 ) {
        int current_digit = number % BASE;

        if ( Math.abs(previous_digit - current_digit) != 1 ) {
            return false;
        }

        previous_digit = current_digit;
        number /= BASE;
    }

    // if number was less than BASE, then it skipped the while loop
    // and all single digit numbers are valid stepping sequences
    // so true
    // if it made it through the while loop,
    // all the adjacent digits differed by 1
    // so true
    return true;
}

So we now have a more readable version of your initial algorithm.  Since it doesn't convert to a String and from characters, I suspect that it will be slightly faster.

You also ask if we can do better than stepping through every number in the range and testing to see if it is a stepping number.  Certainly we can.  We can generate the stepping numbers by composition.  We don't have to search for them.  I notice that this is described in more detail on Stack Overflow.


SSO login & authenticate Wordpress users with JWT token

I don't know why an iframe was suggested to you, but I do see some possibilities for vulnerability.

For your platforms, I would validate server-2-server.

Flow:

If client claims to be logged in ( in JS / has token in local storage), send token to the platform itself.

The receiving endpoint (let's say platform1_showProfile.php) sends a curl-request to the SSO platform in order to validate (and or logout/refresh if expired etc)

For performance reasons, you will want to ask yourself whether

JWT is only your SSO authentication method while maintaining state on each platform or if you want to go stateless and use the sso-endpoint on each call.
WordPress is the right solution for this. Consider setting up an authentication server with slimframework or neoan3


I am personally not a fan of the Time pattern, it gets messy quickly. There is an extension in the works, called electrum that allows you to use variables.
Overall your solution seems too detailed. The magic of alloy is that you only have to say what you want to achieve. I.e. the animals should always be safe and and somehow they need to end up on the other side. I.e. you don't care about the crossing itself that much as long as you ensure there is never a lunch happening.
My personal favorite solution for this problem is:
open util/ordering[Crossing]
enum Object { Farmer, Chicken, Grain, Fox }

let eats = Chicken->Grain + Fox->Chicken
let safe[place] = Farmer in place or (no place.eats & place)

sig Crossing {
    near, far : set Object,
    carry :  Object
} {
    near = Object - far
    safe[near]
    safe[far]
}

run {
    first.near = Object
    no first.far
    all c : Crossing - last, c': c.next {
        Farmer in c.near implies {
            c'.far = c.far + c.carry + Farmer
        } else {
            c'.near = c.near + c.carry + Farmer
        }
    }
    some c : Crossing | c.far = Object
} for 8

Peter Kriens @pkriens


Reduce number of operations to get one array value

@Stewie Griffin's answer is good, but I dare say it promotes eval, where dict is safer and more expansive.
The main aim here is to use the same if's as Stewie, as they are definitely good.
As a dictionary contains things and you can't get other things out of it it's safer.
With Stiewies for example you can pass 'get_file_info' as the field and it'll give you '<function get_file_info at 0x03335150>'.
It also means that you can return a dictionary for each and every stream in info.get_video_streams().

To obtain this we will make a variable video_info that will hold the needed information.

video_info = {
    'width': 2,
    'height': 3,
    'name': 'Name of video'
}

field = 'width'
str(video_info[field])
Out[3]: '2'

field = 'name'
str(video_info[field])
Out[5]: 'Name of video'

This means we just need to move all the information into this dictionary.
And so you'll need to change the for-loop to create a dictionary.

video_info = {
    'type': vinfo.get_stream_type_nick(),
    'width': vinfo.get_width(),
    'height': format(vinfo.get_height()),
    'depth': format(vinfo.get_depth()),
    'framerate': 'Frate: {}'.format(vinfo.get_framerate_num()),
    'bitrate': 'Brate: {}'.format(vinfo.get_max_bitrate()),
    'par': vinfo.get_par_num(),
    'fname': vinfo.get_caps().to_string().split(',')[0]
}

I'd also go on to say that you can change the code to return a dictionary and you can then remove all the field stuff from this function.
And you can use a list comprehension to return a dictionary for every info.get_video_streams().

which leads to:

def get_file_info(f, stream):
    discoverer = GstPbutils.Discoverer()
    discoverer.connect('discovered', on_discovered)
    info = discoverer.discover_uri(f)
    duration = convert_time(info.get_duration(), 'hh:mm:ss')
    return [
        {
            'duration': duration,
            'type': vinfo.get_stream_type_nick(),
            'width': vinfo.get_width(),
            'height': format(vinfo.get_height()),
            'depth': format(vinfo.get_depth()),
            'framerate': 'Frate: {}'.format(vinfo.get_framerate_num()),
            'bitrate': 'Brate: {}'.format(vinfo.get_max_bitrate()),
            'par': vinfo.get_par_num(),
            'fname': vinfo.get_caps().to_string().split(',')[0],
        }
        for vinfo in info.get_video_streams()
    ]

def get_file_field(f, stream, field):
    videos = get_file_info(f, stream)
    video_info = videos[-1]
    if stream == 'video':
        return str(video_info[field])


Converting input from a FileReader to JSON and outputting it again

An idea:

private BufferedReader getReader(final String fileUrl) throws IOException {
    final String filename = getFilename(fileUrl) + ".gz";
    final URL url = new URL(fileUrl);
    final InputStream stream;
    if (new File(filename).isFile()) {
        stream = ClassLoader.getSystemResourceAsStream(fileUrl);
        System.out.println("Using tdat header from classes directory");
    } else {
        stream = url.openStream();
    }
    final GZIPInputStream gzipStream = new GZIPInputStream(stream);
    final InputStreamReader gzipStreamReader =
        new InputStreamReader(gzipStream, "UTF-8");
    final BufferedReader reader = new BufferedReader(gzipStreamReader);
    return reader;
}

You don't have to close the GZIPInputStream, Reader.close() does it.

I'd invert the condition inside the while loop:

// start processing
while (reader.ready()) {
    final String line = reader.readLine();
    if (!line.matches("^(.*?\\|)*$")) {
        continue;
    }
    Map<String, String> result = new HashMap<String, String>();
    ...
}

It makes the code flatten which is easier to read.

This code maybe unnecessary, since no one uses the template˛object:

// create a template so I only have to create a map once
final Map<String, String> template =
    new LinkedHashMap<String, String>(catalog.getFieldData().size());
for (final String fieldName : catalog.getFieldData().keySet()) {
    template.put(fieldName, null);
}

You should specify the charset when you call the constructor of the InputStreamReader.

final InputStreamReader gzipStreamReader =
    new InputStreamReader(gzipStream, "UTF-8");

Omitting it could lead to 'interesting' surprises, since it will use the default charset which varies from system to system.

Here is the code after a few more method extractions. Check the comments please and feel free to ask if something isn't clear.

public void importTdatFile(final String fileUrl) throws MyAppException {
    try {
        doImport(fileUrl);
    } catch (final IOException e) {
        // MalformedURLException is a subclass of IOException
        throw new MyAppException("Cannot import", e);
    }
}

private void doImport(final String fileUrl) throws IOException {
    BufferedReader reader = null;
    BufferedWriter writer = null;
    try {
        reader = getReader(fileUrl);
        writer = getWriter();

        while (reader.ready()) {
            final String line = reader.readLine();
            final Map<String, String> results = processLine(line);
            filterResults(results);
            final String jsonLine = getJsonLine(results);
            writer.write(jsonLine);
        }
    } finally {
        closeQuietly(reader);
        writer.close(); // do NOT ignore output errors
    }
}

private BufferedReader getReader(final String fileUrl) throws IOException {
    final InputStream stream = getStream(fileUrl);
    final BufferedReader reader = createGzipReader(stream);
    return reader;
}

private InputStream getStream(final String fileUrl)
    throws MalformedURLException, IOException {
    final InputStream stream;
    // I don't really like this 'if' here
    if (isGzipFile(fileUrl)) {
        // I'm not sure that the condition is correct for classpath loading
        // or not
        stream = ClassLoader.getSystemResourceAsStream(fileUrl);
        // I would put this println to somewhere else (after refactoring the 'if')
        System.out.println("Using tdat header from classes directory");
    } else {
        final URL url = new URL(fileUrl);
        stream = url.openStream();
    }
    return stream;
}

private BufferedReader createGzipReader(final InputStream stream)
        throws IOException, UnsupportedEncodingException {
    final GZIPInputStream gzipStream = new GZIPInputStream(stream);
    final InputStreamReader gzipStreamReader =
        new InputStreamReader(gzipStream, "UTF-8");
    final BufferedReader reader = new BufferedReader(gzipStreamReader);
    return reader;
}

private boolean isGzipFile(final String fileUrl) {
    final String filename = getFilename(fileUrl) + ".gz";
    return new File(filename).isFile();
}

private BufferedWriter getWriter() throws IOException {
    // TODO: FileWriter use the default character encoding (see javadoc),
    // maybe you should use a FileOutputStream with a specified encoding.
    final String outputFilename = getOutputFilename();
    final FileWriter fileWriter = new FileWriter(outputFilename);
    return new BufferedWriter(fileWriter);
}

private String getOutputFilename() {
    return catalog.getName() + ".json";
}

private Map<String, String> processLine(final String line) {
    final Map<String, String> result = new HashMap<String, String>();
    if (!isProcessableLine(line)) {
        return result;
    }
    // It's hard to refactor without the internals of catalog.
    final String[] fieldValues = line.split("\\|");

    for (int i = 0; i < fieldValues.length; i++) {
        // TODO: possible ArrayIndexOutOfBoundsException here?
        final String fieldName = catalog.getFieldName(i);
        final FieldData fieldData = catalog.getFieldData(fieldName);
        if (catalog.fieldDataSetContains(fieldData)) {
            final String fieldValue = fieldValues[i];
            result.put(fieldName, fieldValue);
        }
    }

    return result;
}

private void filterResults(final Map<String, String> results) {
    removeNulls(results);
    // TODO: catalog probably a field, so it should be visible inside these
    // methods without passing them as a parameter
    removeUnwantedFields(results, catalog);
    fixFieldPrefixes(results, catalog);
    fixFieldNames(results, catalog);
}

private boolean isProcessableLine(final String line) {
    // TODO: A precompiled regexp maybe faster but it would be premature
    // optimization, so don't do that without profiling
    return line.matches("^(.*?\\|)*$");
}

private void closeQuietly(final Closeable closeable) {
    if (closeable == null) {
        return;
    }
    try {
        closeable.close();
    } catch (final IOException e) {
        // TODO: log the exception with a logger instead of the
        // printStackTrace();
        e.printStackTrace();
    }
}

Anyway, your streaming approach is fine, you shouldn't read the whole file into the memory.


Deitel Java exercise 6.30: Number-guessing game

Guess Guess = new Guess();

Java's naming convention for variables are in camelCase, so I will suggest writing that as Guess guess = new Guess();.

With that said, the fact that Java being an OOP language doesn't mean that everything must be done object-style. For this relatively trivial exercise, all you need is just a random number:

int randomNumber = getRandomNumber();

And everything can be done within the main() method itself:

public static void main(String[] args) {
    int randomNumber = getRandomNumber();
    try (Scanner scanner = new Scanner(System.in)) {
        for (int guess = prompt(scanner); guess != randomNumber; guess = prompt(scanner)) {
            System.out.println("too " + (guess < randomNumber ? "low" : "high"));
        }
        System.out.println("Congratulations, you win!");
    }
}

I will suggest using try-with-resources on the Scanner instance to handle its underlying I/O resources efficiently. Instead of a 'plain' while loop, I opted to showcase how a similar loop can be done using the for-loop construct: it is somewhat more expressive, and the slight benefit is that it nicely scopes the guess variable within itself.

The implementation for getRandomNumber() and prompt(Scanner) shall be left for the reader... What I can further advise for the latter is that it should safely handle invalid inputs internally and only returns an int value for comparison.

Oh, and one more thing... you current implementation for the random number does not generate it in the range \$[1 ... 1000]\$, assuming that you really intend the range to be bound-inclusive:

(int) (Math.random() * 999 + 1)

Tip: Math.random() will not give you exactly 1.0. In addition the cast to int truncates the precision, so a value like 999.999 is rounded down to 999. You'll need an alternative way of getting 1000. :)


Reading, processing and counting an array setting limits

Here are some things that may help you improve your code.

Eliminate unused variables

Within main, the variables i, BestA and BestB are declared and some of them set, but they are otherwise unused.  They should be omitted from the program.

Don't abuse the comma operator

This line doesn't really need a comma operator:

bestA = A, bestB = B, bestMin = Min;

It should instead be three separate statements, or (if you follow the previous advice) reduced to a single one involving bestMin.

Don't cast the return from malloc

The return value from malloc or calloc is a void * and does not need an explicit cast.  See this question for a thorough discussion of the reasons not to, but for me the most compelling reason is that it's simply not needed.

Use const where practical

In your sum_array routine, the values in the array are never altered, which is just as it should be.  You should indicate that fact by declaring it like this:

int sum_array(const int* array, int cnt)

Use pointers rather than indexing for speed

Pointers are generally a faster way to access elements than using index variables.  Speed may not a particular goal in this program but it's useful to know anyway.  For example, your sum_array routine could be written like this:

int sum_array(const int* array, int cnt)
{
    int res;
    for ( res = 0; cnt; --cnt)
        res += *array++;
    return res;
}

Check return values for errors

The calls fopen, fscanf and malloc can each fail.  You must check the return values to make sure they haven't or your program may crash (or worse) when given malformed input or due to low system resources.  Rigorous error handling is the difference between mostly working versus bug-free software.  You should strive for the latter.

Consider separating I/O from the algorithm

The I/O is done first, and then the input values are processed to find the answer.  Consider separating those into to separate functions which would both make your program cleaner and also allow for better automated testing (such as automatically generating random values and then checking that the algorithm does the right things).

Reconsider your algorithm

Right now, the sums are recalculated many times, but this isn't strictly necessary. As you iterate through the combinations, the partitioning only moves by one value.  So what you could do instead would be to keep the three sums ProfitA, ProfitB and ProfitC and then just add and subtract the particular value that moves from one brother to another.

I've done some reading and it appears to me that the best you can do for complexity is \$\mathcal{O}(N^3)\$
See this question and the many links from it to explain that.

Think about negative numbers

While the problem states that the shop generates profit each day, it doesn't necesarily mean that every time period is profitable.  This suggests that some of the time periods could be associated with negative numbers.  If we use this input:

8
-5 6 1 4 -9 3 1 2

the program reports a max value of 1, which is correct, but you should verify that it is correct for any possible set of numbers.

Consider adding an "early bailout"

If it ever occurs that ProfitA == ProfitB == ProfitC (as with the values in the previous point) this must be the answer (do you see why?) so the program could exit early with that correct answer.

Eliminate return 0

You don't need to explicitly provide a return 0; at the end of main -- it's created implicitly by the compiler.


Keep the sequential nature while updating the UI of the progress of the HTTP request

Good you have a BackgroundWorker. If I understood correctly, let's say you want to update a button, whether to enable it or not. you can use this:

delegate void EnableButton(Button b, bool enable);
public void ActuallyEnableButton(Button b, bool enable)
{
    if (b.InvokeRequired)
    {
        EnableButton del = ActuallyEnableButton;
        b.Invoke(del, new object[] { b, enable });
        //in some cases add "return" statement
    }
    b.Enabled = enable;
}

Call ActuallyEnableButton(btn, true) for example, inside DoWork event of BackgroundWorker.

This applies to Label, TextBox, ComboBox, ListView, ProgressBar, etc. No need to use this code if you want to update ToolStripStatusLabel and ToolStripProgressBar.

Hope this helped.


Yeah, the output looks really Nice :-)

Consider the following points:

I think you'll have NPE's when you pass null maps
There's a lot of different implementations of Map. If you have a SortedMap, it can pass, even though the sorting is different.
How does the message look, when the maps do not have the same size? Is the message clear enough?
The message "Expected: Maps are equivalent, but" is a bit strange? They are not equivalent, are they?
m_expected: Naming convention: should be mExpected. But to be honest, I'd go with expected.
Sadly, it only works with String...

Hope this helps...


How hard is this to scale?
Sorry but I don't understand what do you mean here. How do you want to scale a method?
What are the downsides to this method?

It does not work with Action

It does not work with Func<T1, T2, TResult>

It does not work with Func<Task>

It does not work with Func<Task<T>>

It blocks the calling thread unnecessary (Thread.Sleep)

You must throw exception to enforce retry (can't use any other condition, like Result != true)

It swallows the exception

in the worst case if all attempts fail then it will return a default instead of the exception

It does not allow to use exponential back-off algorithm

It does not allow infinite retry (performing yet another attempt until it succeeds)

It does not utilize Cancellation concept

It does not provide debug information (like how many times the retry has been performed)

What alternatives are available?

Polly's Retry << The suggested
EnterpriseLibrary.TransientFaultHandling.Core

Is this code easy to understand?
For me, yes.
Not only in final usage, but initial implementation?
Is this a question?
What would a more concise and clear name be for this method?

ExecuteWithRetry
ExecuteAtMostNTimes
RetryFunction
PerformCallWithRetryPolicy
etc.


You have a physical table that has been established for the purpose of managing calendar dates. This is great, but with just a little more work it can be extended to do so much more.

Consider adding a column "DayType", with values like:

0 -> Normal
1 -> Weekend
2 -> Holiday

You could add this easily... right?

Then, you can maintain it with:

update FiscalCalendars
set DayType = case
                  when Holiday is not null then 2
                  when FiscalDayOfWeek in (1, 7) then 1
                  else 0
              end

Now your query becomes quite simple:

select count (*)
from FiscalCalendars
where CalendarDate between @fromDate and @toDate
  and DateType = 0

Index the column with (DateType, CalendarDate)

Maintaining this static data in a function would be a poor use of computational power, and make indexing harder.

Your function would thus become:

create function dbo.WorkWeekDateDiff(@fromDate date, @toDate date)
returns int
as
begin

    /* returns the number of workdays (non-holiday week days) between two dates. */
    declare @result int;

    select @result = (select count(*)
                      from dwd.FiscalCalendars
                      where DateType = 0
                        and CalendarDate between @fromDate and @toDate
    );

    return @result;

end


If you're going to use a list in Haskell, the last thing you want to do is continually modify random elements within it. Luckily, there's a better way.

Start by listing out all of the different things your function is doing.

Drop characters that are not 'a'..'z' or 'A'..'Z'.
Regardless of case, determine a letter's position in the alphabet.
Tally a value that represents a specific letter in the alphabet.
Return a list of alphabet letter frequencies.

By identifying the smallest bits of functionality that still make sense to talk about, we can write or reuse functions that do only one thing, and then compose them using higher order functions into something that does everything we need in one go.

Since this problem is dependent on characters and lists, your first stop as a new Haskell user should be to the Haddock documentation for Data.Char and Data.List to learn about what pre-existing functions you might be able to use for your solutions.

Tackling the first bullet point, dropping some elements of a list conditionally on their values should jump out at you as a filter operation. If we look through the documentation for Data.Char you may realize that Char represents all Unicode characters—not just ASCII values—but we're only interested in the ASCII letters.

Knowing that Char is an instance of Enum (from the Data.Char documentation), we can use list range notation to get just the Char values we care about in a list. I.e., alphabet = ['a'..'z']. Instead of expanding our range to include the uppercase versions of letters, we'll next write a function to lowercase our string using toLower :: Char -> Char from Data.Char.

lower :: String -> String
lower = map toLower

And assuming we have a lowercase string, it's easy to filter to just the characters we're interested in.

alphas :: String -> Char
alphas = filter (`elem` alphabet)

Notice that we're building functions that can be easily composed to produce the functionality our final program requires. Going from an arbitrary string to just one containing valid letters all in lower case is easy, alphas . lower.

Going by the original statement of functionality, we next need to determine a letter's position in the alphabet so that we can then keep a tally of letter frequencies. In writing a functional version though we can be smarter. Instead of picking a letter and then finding the correct tally to increase, we rearrange the order of operations. First we group letters and then we count the number of elements in each group to produce a tally.

Perusing the documentation for Data.List we'll pull out sort and group. sort will rearrange our list of Char, then group will organize them into lists by equality. The last step is to run length encode the groups to produce a tally for each letter.

tally :: (Ord a) => [a] -> [(a, Int)]
tally = map runLength . group . sort
    where
        runLength :: [a] -> (a, Int)
        runLength       [] = error "runLength: Can't run length encode an empty list"
        runLength xs@(x:_) = (x, length xs)

That error case should be unnecessary, group shouldn't return any empty sub-lists, but we include it so that if our understanding is incorrect or future changes to the function ever break things we get a better error than a pattern-match failure (and the compiler stops complaining if we compile with -Wall).

Now one thing to note is that if a letter isn't present at all in a given string, tally won't return a pair for it. In your original computeMaxBeauty that's a problem since it relies on a list of length 26 being returned. Since we have alphabet which encodes letter value by position though we can write another version that is more flexible.

beauty :: (Char, Int) -> Int
beauty (a, n) = n * (fromMaybe 0 (elemIndex a alphabet) + 1)

Here we look up the index of a Char in alphabet, then use a utility function from Data.Maybe in the event that Char wasn't present. Because lists are 0-indexed we have to add 1.

And tying all of our simple single-purpose functions together,

computeMaxBeauty :: String -> Int
computeMaxBeauty = sum . map beauty . tally . alphas . lower

My working version, should be runnable.

import Data.Char (toLower)
import Data.List (group, sort)
import Data.Maybe (fromMaybe)

alphabet :: [Char]
alphabet = ['a'..'z']

lower :: String -> String
lower = map toLower

alphas :: String -> [Char]
alphas = filter (`elem` alphabet)

tally :: [Char] -> [(Char, Int)]
tally = map runLength . group . sort
    where
        runLength :: [a] -> (a, Int)
        runLength       [] = error "runLength: Can't run length encode an empty list"
        runLength xs@(x:_) = (x, length xs)

-- Matches original functionality, unnecessary with changed computeMaxBeauty as below
letterFreqs :: String -> [Int]
letterFreqs = map ((subtract 1) . snd) . tally . (alphabet ++) . alphas . lower

computeMaxBeauty :: String -> Int
computeMaxBeauty = sum . map beauty . tally . alphas . lower
    where
        beauty :: (Char, Int) -> Int
        beauty (a, n) = n * (fromMaybe 0 (elemIndex a alphabet) + 1)


Show all full/partial search matches in the first worksheet from other worksheets

The Find method is pretty quick but has some overhead due to all the find options e.g. whole cells, match case etc.

In this case it would be quicker to put the search data into an array and iterate that to find your value. e.g (written here, untested):

Function MatchCell (ws as Worksheet) as Range

Dim sourceData() as variant
Dim lastRow as long, x as long, y as long

lastRow = ws.Range("A1000000").end(xlUp).row ' you may want to adjust this if you don't know that column A will represent all used rows
sourceData = ws.range("A1:G" & lastRow).value ' again, adjust to suit

for x = 1 to ubound(sourceData) ' loop the first dimension

   for y = 1 to ubound(sourcedata, 2) ' loop the 2nd dimension

      if sourceData(x, y) = myVal then
         MatchCell = ws.Cells(x, y) ' the row is x, the column is y
         Exit Function ' escape the loop/function once the value is found
      End If

   next y

next x

End Function


I think I'd break this up into a few separate routines, each with a single more specific intent. I think the easiest way to do this is probably to start by taking the absolute value of the input (represented as an unsigned type), something like this:

unsigned iabs(int input) {
    if (input >= 0)
        return (unsigned)input;
    return (UINT_MAX - (unsigned)input)+1U;
}

I believe C's requirements for converting a signed to unsigned ensure that this produce correct results for all inputs (including INT_MIN).

With that, nearly everything else can deal with an unsigned number. Personally, I also prefer to generate the result in order instead of generating in reverse, then reversing it. One fairly simple way to do that is with recursion, with each step first generating previous numerals (if any), then adding its own numeral to the end of the string. I'd have the recursive function deal only with an unsigned type (as produced above). Of course, like nearly everything that manipulates data in a buffer in C, you should also pass the maximum buffer length for it to use, to prevent buffer overruns. For the sake of generality, I've also made it accept the base for the conversion as a parameter instead of always assuming base 10.

char *itoa_internal(char *buffer, size_t len, unsigned input, int base) {
    static const char digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    char *pos = buffer;
    if (input >= base)
        pos = itoa_internal(buffer, len, input/base, base);

    if (pos-buffer < len-1)
        *pos++ = digits[input % base];
    return pos;
}

Then I'd have a small wrapper function that puts in a - if the input is negative, invokes the function above with the absolute value of the input, and terminates the string after the internal function returns.

char *itoa(char *buffer, size_t len, int input, int base) {
    char *pos = buffer;

    if (base < 2 || base > 36 || len < 1)
        return NULL;

    if (input < 0)
        *pos++ = '-';

    pos = itoa_internal(pos, len, iabs(input), base);
    *pos = '\0';
    return buffer;
}

This should also make it pretty trivial to write a utoa that handles unsigned inputs -- it would be like itoa without the code to deal with negative numbers. As a minor refinement, I'd probably also make iabs and itoa_internal static functions to minimize the chances of them interfering with other names.


Reading and classifying lines from a file

Code has bug. After free'ing line, set len = 0; line = NULL;

    free(line);
    line = NULL; // add
    len = 0; // add

Further, it would be better to initialize line and move this free();  ... to outside the for()   loop.  Also line = NULL; len = 0; would not be needed there.

size_t len = 0;
char *line = NULL;
...
for(...; ... getline(&line, &len, file) ...; ...) {
  ...
}
free(line);

  Is this way of writing the if statement a good practice? Is it readable? Should I do it differently?

It is not clear that the  { printError(... true; } block is part of if() and not a free standing block.  Consider the below.  The first lacks clarity that the first block is part of the if() and the 2nd block simply a stand-along block

    if (strToSample(line, SEPARATOR, dim, sample) != EXIT_SUCCESS ||
        calibrateLinearSeparator(sample, linearSeparator, dim) != EXIT_SUCCESS)
    {
        printError(TRAINING, "Failed processing line");
        stop = true;
    }
    {
        printError(TRAINING, "Status");
    }
    free(line);
    freeSample(sample);

vs. this form.  The 1st block is part of the if() and the 2nd block is not nested like the first.

    if (strToSample(line, SEPARATOR, dim, sample) != EXIT_SUCCESS ||
        calibrateLinearSeparator(sample, linearSeparator, dim) != EXIT_SUCCESS)
      {
        printError(TRAINING, "Failed processing line");
        stop = true;
      }
    {
        printError(TRAINING, "Status");
    }
    free(line);
    freeSample(sample);

  Is it a good practice in C to write the for condition the way I did?

Why read a line if stop is true?  Certainly this is surprising functionality.  Given 3 stopping conditions, it appears to me that the combination of them occurring in groups, the side effects of getline() , and the short-circuit nature of && led to weak function flow.

for(int i = 0; i < m && getline(&line, &len, file) != -1 && !stop; i++)
// vs.
for(int i = 0; i < m && !stop && getline(&line, &len, file) != -1; i++)

IMO, a for() loop is best as for (initialize_index, index_test; index_delta).  Another other stopping condition belongs in the body.  Example:

for (int i = 0; i < m; i++) {
  if (stop || getline(&line, &len, file) == -1) {
    break;
  }
  ...
}

Notice this form avoid ! in 2 places.  Negation adds to complexity.  Don't you not think it is not so and not so when not done?


HTML parser written in JavaScript that takes in strings and output a DOM tree object

General review points

Use semicolons
Try to avoid Array iterator functions in favor of for of. Generally use array iterators when you want the iteration to be an expression.

Apart from that the code looks good and is an elegant solution to parsing simple markup. It can be used as a base to provide the additional functionality you mention.
Questions

"Right now the HTML string it takes doesn't have any indentation. How can I modify the code so it can allow indentations in the input strings?"

After you split the markup string you can remove white spaces using String.trim
In the example parser (bottom of answer), the first expression uses Array.map and Array.filter to trim white spaces and then remove empty lines.
If you want to only remove white spaces using the same rules as HTML then you can use a RegExp and  String.replace to remove white spaces.
Token validator

"How can I modify the code so it can become easily expandable for other HTML tag body, div, span etc."

"Right now the HTML string it takes has to be valid. How can I modify the code so it can detect invalid HTML"

For the other questions you will need to create an object that can validate tokens. The validators role is to recognize, valid tags, invalid tags, and content.
It does this

by keeping a Set of tag names
providing a function to check a token. If the token is a valid closing tag it returns the token representing the opening tag.
keeps the state of the token tested. If the token is unknown or a tag the semaphore are set appropriately.

Your function has been modified to use the validator and check for various problems related to invalid markup.
The function will return a simple error object containing the error description if the markup is invalid
If the token validator checks a token that is unknown (not in name list and starts or ends with < or >) unknown is set true.
If the token validator checks a known opening tag the semaphore tag is set true.
The semaphore are reset on each token checked.
The Validator
Add the tags you wish to recognize to the names Set.
Call tokenValidator.token to validate a token.
It will return the opening tag as a token or undefined.
If undefined the check the semaphores  tokenValidator.tag and / or tokenValidator.unknown to determine what to do with the current token.
const tokenValidator = (() => {
    const names = new Set(["div", "span", "p"]);
    var unknown = false, tag = false;
    return {
        get unknown() { return unknown },
        get tag() { return tag },
        token(token) {
            tag = unknown = false;
            const hasEnd = token.endsWith(">");
            if (token.startsWith("<")) {
                if (token.startsWith("</") && hasEnd) {
                    const tokenName = token.slice(2,-1);
                    if (names.has(tokenName)) { return "<" + tokenName + ">" }
                    tag = unknown = true;
                } else if (hasEnd) {
                    const tokenName = token.slice(1,-1);
                    unknown = !names.has(tokenName);
                    tag = true;
                    return;
                }
                unknown = true;
            } else if (hasEnd) { tag = unknown = true }
        },
    };
})();

The Parser
The parses is based on your original code.
It will either return the parsed markup or an error.
Usage example
const result = parser(HTML);
if (result.error) { console.log(result.message) }
else { console.log(result) }

To check for hanging tags (eg missing closing tags) the function counts up on opening tags and down on closing tag. The countOpen must be 0 when done or there is an error.
Example Code
function parser(html) {
    const tokens = html.split('\n').map(token => token.trim()).filter(token => token !== "");
    const error = message => ({error: true, message: "Invalid HTML. " + message});
    const stack = [];
    var countOpen = 0;
    for (const token of tokens) {
        const openToken = tokenValidator.token(token);
        if (tokenValidator.unknown) { return error("Unknown tag: " + token) }
        if (openToken) {
            const children = [];
            let stackToken = stack.pop();
            while (stackToken?.value !== openToken) {
                if (!stackToken) { return error("Tag order: " + token) }
                children.unshift(stackToken);
                stackToken = stack.pop();
            }
            stack.push({value: openToken.slice(1, -1), children});
            countOpen--;
        } else if (tokenValidator.tag) {
            stack.push({value: token});
            countOpen ++;
        } else { stack.push(token) }
    }
    return countOpen ? error("Missing tag") : stack.pop();
}

Note that the code does not cover all invalid markup. It is just an example intended to demonstrate how validation can be addressed.


splitting multiple joined words, port from perl to PHP

This should be find_words() php equivalent,
(note perl %words is here $Gwords as perl makes distinction between hashes/dictionaries and arrays)

function find_words() {
    global $Gwords;

    # Print every way $string can be parsed into whole words
    $words = func_get_args();
    $string = array_shift($words);
    $length = strlen($string);

    foreach (range(1, $length) as $i) {

        $word = substr($string, 0, $i);
        $remainder = substr($string, $i, $length - $i);
        # Some dictionaries contain each letter as a word
        if ($i == 1 && ($word !== "a" && $word !== "i")) continue;

        if (isset($Gwords[$word])) {
            $words[]= $word;
            if ($remainder === "") {
                echo join(' ', $words), "\n";
                return;
            }
            else {
                # find_words($remainder, @words);
                call_user_func_array(
                    "find_words",
                    array_merge((array)$remainder, $words)
                );
            }
            array_pop($words);
        }
    }

    return;
}


Finding the differences between two revisions (or objects)

You certainly seem to be going a pretty long detour in some cases.

What worries me most is that you look at stringified JSON. Just look at the objects. If you try to manually parse JSON by splitting on commas, you risk splitting on commas in strings, and all sorts of other nonsense.

You really don't need raw JSON strings for anything here (except perhaps for printing the result in a readable way)

Just iterate the objects with for...in, and use hasOwnProperty to check for properties.

For instance:

var A = {A: 10, B: 20, C: 30, D: 90, BB: 5, CC: 4, AA: 2};
var B = { B: 22, C: 30, L: 4, KK: 444, A:15};

var difference = diff(A, B);
document.write("<pre>"+JSON.stringify(difference, 0, 3)+"</pre>");

function diff(a, b) {
  var result = {
    removed: {},
    changed: {},
    created: {},
    notChanged: {}
  };

  // check for changed/unchanged/removed keys
  for(var aKey in a) {
    if(!a.hasOwnProperty(aKey)) continue; // skip inherited properties

    if(b.hasOwnProperty(aKey)) {
      // check for changed/unchanged values
      if(b[aKey] === a[aKey]) {
        result.notChanged[aKey] = a[aKey]; // no change between a and b
      } else {
        result.changed[aKey] = [a[aKey], b[aKey]]; // get before/after values
      }
    } else {
      result.removed[aKey] = a[aKey]; // key wasn't in b, so it's been removed
    }
  }

  // do the reverse to check for added keys
  for(var bKey in a) {
    if(!b.hasOwnProperty(bKey)) continue;
    if(!a.hasOwnProperty(bKey)) {
      result.created[bKey] = b[bKey];
    }
  }

  return result;
}


Calculate the nth Fibonacci number, mod m

Sorry, I am giving no code (I am on a phone and I don't know Python), but be aware that if m^2 is way lower than n, you could use the fact that your function gets periodical with a period maximally m^2 (as both a[-1] and a[-2] can gain m different values).

You could test in your for loop if/when you reached your period (if a[-2]==0 and a[-1]==1) and if so, variable i would indicate your period. Then you could simply grab a[n%(i-2)] as the answer, if I am not mistaken.

By the way, shouldn't the for loop range begin with 2?


Compute the mean, variance and standard deviation of all pairs, triplets and sets of four

If you want to keep all results, this can be done more efficiently using meshgrid.  You can create N-dimensional grids of values, flatten them, then take the mean of the result.

So for the 2D case, meshgrid is pretty straightforward:

>>> a = np.arange(5)
>>> [a1, a2] = np.meshgrid(a, a)
>>> print(a1)
[[0 1 2 3 4]
 [0 1 2 3 4]
 [0 1 2 3 4]
 [0 1 2 3 4]
 [0 1 2 3 4]]
>>> print(a2)
[[0 0 0 0 0]
 [1 1 1 1 1]
 [2 2 2 2 2]
 [3 3 3 3 3]
 [4 4 4 4 4]]
>>> print(a1.ravel())
[0 1 2 3 4 0 1 2 3 4 0 1 2 3 4 0 1 2 3 4 0 1 2 3 4]
>>> print(a2.ravel())
[0 0 0 0 0 1 1 1 1 1 2 2 2 2 2 3 3 3 3 3 4 4 4 4 4]

As you can see, the flattened versions of a1 and a2 combined provide every possible combination.  This can be extended to higher dimensions just by putting more a values:

>>> a = np.arange(3)
>>> [a1, a2, a3] = np.meshgrid(a, a, a)
>>> b = np.vstack([a1.ravel(), a2.ravel(), a3.ravel()])
>>> print(b)
[[0 0 0 1 1 1 2 2 2 0 0 0 1 1 1 2 2 2 0 0 0 1 1 1 2 2 2]
 [0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2]
 [0 1 2 0 1 2 0 1 2 0 1 2 0 1 2 0 1 2 0 1 2 0 1 2 0 1 2]]

This can be extended to any number of dimensions, allowing of course for memory constraints.

You can generalize the meshgrid function call by using unpacking.  These two function calls are equivalent:

np.meshgrid(a, b, c)
np.meshgrid(*[a, b, c])

The * in this case means "unpack the list as function arguments" (also works with tuples, iteratirs, and many other things).  You can combine this with the [x]*n syntax, where n is a number.  This means "duplicate the contents of list [x] n times".  So [5]*4 is similar to [5, 5, 5, 5] ("similar", not "identical", but the differences are not relevant to what we are doing).

So you can combine this to make calling meshgrid with multiple values easier.  These three lines of code are the same:

np.meshgrid(a, a, a)
np.meshgrid([a, a, a])
np.meshgrid([a]*3)

You can exclude combinations where all the values are equal using logical indexing.  First, you determine whether each element is equal to the value of the first element in that combination.  Then you find combinations where that is True for all values.  Then you get the columns for which that isn't the case.  So something like:

>>> c = b[:, ~(b[0] == b).all(0)]
>>> print(c)
[[0 0 1 1 1 2 2 2 0 0 0 1 1 2 2 2 0 0 0 1 1 1 2 2]
 [0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2]
 [1 2 0 1 2 0 1 2 0 1 2 0 2 0 1 2 0 1 2 0 1 2 0 1]]

If you want to avoid memory issues you can make use of some internal knowledge of how numpy handles arrays.  Arrays are simply continguous (or strided, i.e. continous in steps) blocks of memory.  By working with this sort of memory, numpy can make use of very fast libraries for doing calculations on a block of memory at a time.  But since this is simply a sequence of bytes, there are different ways to look at this block of memory.  The same block could be seen as a 1D array of floats, a 2D array of integers, etc.  Numpy can make use of this to avoid making unnecessary copies.  So arr.ravel(), for example, "flattens" an array by treating the same underlying data as a 1D array.  The catch (or benefit, depending on your use-case) is that changes to a raveled array will affect the original.

meshgrid can make use of this to avoid making unnecessary copies.  Consider this:

>>> a = np.arange(10)
>>> b = np.meshgrid(*[a, a, a, a])
>>> c = np.meshgrid(*[a, a, a, a], copy=False)
>>> b[0].flags['OWNDATA']
True
>>> c[0].flags['OWNDATA']
False

flags['OWNDATA'] tells you whether the array is a view into the data stored in another array or not.  In the case of b, it is, which means each b array takes up memory equal to the size of the array.  In the case of c, however, it isn't, which means c takes almost no additional memory, it is still using the same block of memory as a.  The catch is that any change to any element to any of the arrays in c will change the value in a and any of the values corresponding to that value in any of the c arrays.

If you combine this with ravel, you can get a view as well, but reshape(-1) is more reliable.  Consider this:

>>> c[0].ravel().flags['OWNDATA']
True
>>> c[0].reshape(-1).flags['OWNDATA']
False

Slice of arrays, such as a[5:1000] also return views.  "Fancy" indexing, where you get multiple elements of an array by index or boolean value, return new arrays.  So you can slice out as many values as you want.

Getting the histogram of rows or columns of an array is a bit more difficult.  The np.histogram can't do it.  What you can do is follow the instructions here to get the unique rows (you need unique columns so just transpose), but when they use the unique function add the return_counts=True argument to also get the counts of each unique row.  You will also need to sort each column using d.sort(axis=0) at the beginning so that columns with different orders of the same value are not counted separately.

Note that this doesn't use the highly-optimized numpy array processing libraries, so it will be very slow for large data set.

You can also read all the lines into a numpy array at once using loadtxt

So to implement what you want you can do:

from __future__ import print_function

import numpy as np

n = 4  # This is the number of repetitions
maxn = 10000

data = np.loadtxt('testdata.txt')

vals = np.meshgrid(*[data]*n, copy=False)
vals = np.vstack([val.reshape(-1)[:maxn] for val in vals])
vals = vals[:, ~(vals[0] == vals).all(0)]
p_avg = vals.mean(0)
print(p_avg)

Or as a function:

from __future__ import print_function

import numpy as np

def allmeans(data, n):
    vals = np.meshgrid(*[data]*n)
    vals = np.vstack([val.ravel() for val in vals])
    vals = vals[:, ~(vals[0] == vals).all(0)]
    return vals.mean(0)

data = np.loadtxt('testdata.txt')
print(allmeans(data, 4))

Doing variance or standard deviation just requires replacing mean with var and std, respectively.  You could even pass it as a function:

from __future__ import print_function

import numpy as np

def allagg(data, n, func):
    vals = np.meshgrid(*[data]*n)
    vals = np.vstack([val.ravel() for val in vals])
    vals = vals[:, ~(vals[0] == vals).all(0)]
    return func(vals, 0)

data = np.loadtxt('testdata.txt')
print('Mean: \n', allagg(data, 4, np.mean))
print('Variance: \n', allagg(data, 4, np.var))
print('Standard Deviation: \n', allagg(data, 4, np.std))

NOTE:  The differences between [x, x, x] and [x]*3 come into play when x is itself mutable (a data type that can change, like a list or numpy array).  Consider this example:

>>> a = [[1], [1], [1]]
>>> b = [[1]]*3
>>> a[0][0] = 5
>>> b[0][0] = 5
>>> print(a)
[[5], [1], [1]]
>>> print(b)
[[5], [5], [5]]

This difference happens because in a each [1] is an independent list, while in b each [1] is the same list.  Since you can change lists in-place, changes to a list in one part of your program affect that list everywhere else in the program.  So these are more equivalent:

>>> x = [1]
>>> a = [x, x, x]
>>> b = [x]*3
>>> a[0][0] = 5
>>> print(a)
[[5], [5], [5]]
>>> print(b)
[[5], [5], [5]]

Notice I didn't even have top change b here, changes to a change every x used everywhere.  This can be used to do funny things like create nested infinitely-nested lists:

>>> x = [1, 1]
>>> x[0] = x
>>> x
[[...], 1]

This issue affects lists of numpy arrays as well, but it doesn't matter to use because we aren't changing any of those arrays in-place.

EDIT 1: Change code to exclude duplicated

EDIT 2: Explain unpacking

EDIT 3: Warning about [x]*n syntax

EDIT 4: Added optimization tips and histogram


You can use postwalk:

(defn maybe-square [x]
  (if (number? x)
    (* x x)
    x))

(clojure.walk/postwalk maybe-square [1 [2 [3]]])
=> [1 [4 [9]]]

Which is perhaps against the spirit of learning how to do it, so it is worth looking at the implementation code:

https://github.com/clojure/clojure/blob/2224dbad5534ff23d3653b07d9dc0a60ba076dd7/src/clj/clojure/walk.clj#L35

Which shows the correct way to test for various things you may expect in a tree (There are quite a few different tests you can take advantage of).

lazy-seq and map are cool, but it is probably more common to think of trees as data structures rather than lazy sequences; you will note that postwalk returns datastructures, not lazy sequences. So I recommend you also return datastructures (in your case vectors and lists, rather than a sequence).


Minimum window substring - LeetCode challenge

Performance

The main culprit for exceeding the time limit is here:

while end < s.count { ... }

A Swift string is a Collection but not a RandomAccessCollection, so that the complexity of var count is \$ O(n) \$, where \$ n \$ is the number of characters in the string.

s.count is called on each iteration, so that the total complexity becomes  \$ O(n^2) \$.

Since you already converted the string to an array of characters, you can simply replace the condition by

while end < stringArray.count { ... }

Arrays are RandomAccessCollections and determining their count is a \$ O(1) \$ operation. That should already improve the performance considerably for large strings.

An alternative is to iterate over/keep track of string indices instead, that makes the stringArray obsolete:

var start = s.startIndex // Start of current window
var end = s.startIndex // End of current window
var len = 0 // Length of current window

while end != s.endIndex {
    let curChar = s[end]
    s.formIndex(after: &end)
    len += 1

    // ...
}

Some simplifications

Testing for an empty string can be done with isEmpty:

if s.isEmpty || t.isEmpty || s.count < t.count {
    return ""
}

When building the frequency map you can use the dictionary subscripting with default value:

var freq: [Character : Int] = [:]
for curChar in t {
    freq[curChar, default: 0] += 1
}

and that can be further shorted using reduce(into:):

var freq = t.reduce(into: [:]) { dict, char in
    dict[char, default: 0] += 1
}

Use Optional instead of magic values

Here

var resLen = Int.max

you are using a “magic value”: Int.max indicates that no matching window has been found so far. That works because the given strings are unlikely to have \$ 2^{63} - 1 \$ characters, but it forces you to use exactly the same “magic value” at

if resLen == Int.max { ... }

Also the initial value of

var resStart = 0

is meaningless, it will be overwritten as soon as the first matching window is found.

Magic values are frowned upon in Swift because there is a dedicated language feature for the purpose: the optional values.

var resLen: Int?

clearly indicates an undefined value, and later be tested with optional binding.

A (minor) drawback is that you no longer simply compare

if resLen > end - start { ... }

but I'll come back to that later.

Use structs to combine related properties

Both the current and the best window are described by two properties (

var end = 0
var start = 0

var resStart = 0
var resLen = Int.max

or – with the above suggestion – by three properties

var start = s.startIndex // Start of current window
var end = s.startIndex // End of current window
var len = 0 // Length of current window

// Similar for best window ...

With a

struct StringWindow {
    var startIndex: String.Index
    var endIndex: String.Index
    var length: Int

    // ...
}

these related properties are nicely combined, and it makes the code more self-documenting:

var currentWindow = StringWindow(...)
var bestWindow: StringWindow?

Comparing the length against the optional bestWindow can be put into a method of that type, assigning a new best window is simply done with

bestWindow = currentWindow

and the final result can be determined with optional binding:

if let best = bestWindow {
    return String(s[best.startIndex..<best.endIndex])
} else {
    return ""
}

Putting it together

Putting all the above suggestions together the code could look like this:

func minWindow(_ s: String, _ t: String) -> String {

    struct StringWindow {
        var startIndex: String.Index
        var endIndex: String.Index
        var length: Int

        init(for string: String) {
            self.startIndex = string.startIndex
            self.endIndex = string.startIndex
            self.length = 0
        }

        func shorter(than other: StringWindow?) -> Bool {
            if let other = other {
                return length < other.length
            } else {
                return true
            }
        }
    }

    if s.isEmpty || t.isEmpty || s.count < t.count {
        return ""
    }

    var freq = t.reduce(into: [:]) { dict, char in
        dict[char, default: 0] += 1
    }
    var distinct = freq.count

    var currentWindow = StringWindow(for: s)
    var bestWindow: StringWindow?

    while currentWindow.endIndex != s.endIndex {
        let curChar = s[currentWindow.endIndex]
        s.formIndex(after: &currentWindow.endIndex)
        currentWindow.length += 1

        if let val = freq[curChar] {
            freq[curChar] = val - 1
            if val - 1 == 0 {
                distinct -= 1
            }
        }

        while distinct == 0 {
            if currentWindow.shorter(than: bestWindow) {
                bestWindow = currentWindow
            }

            let curStart = s[currentWindow.startIndex]
            if let val = freq[curStart] {
                freq[curStart] = val + 1
                if val + 1 > 0 {
                    distinct += 1
                }
            }
            s.formIndex(after: &currentWindow.startIndex)
            currentWindow.length -= 1
        }
    }

    if let best = bestWindow {
        return String(s[best.startIndex..<best.endIndex])
    } else {
        return ""
    }
}

Final remarks

Try to use more descriptive variable names (what is var distinct) or at least document their meaning.
Don't abbreviate variable names: use e.g. length instead of len, or startIndex instead of start.
Determining the number of key/value entries in a dictionary can be simplified to

var distinct = freq.count

instead of freq.keys.count.
The parentheses at

while (distinct == 0) { ... }

are not needed.


Refactoring Java transmitter delegate implementation

Why no reflection? Have you considered code generation (compile time or runtime)?

Here's an idea based on proxies and reflection. I haven't actually tried any of this, so the idea might break down at some point, but here goes.

Create an interface for the transmitter that extends all of the interfaces the transmitter will implement:

public interface ITransmitter extends IRecordingView, IView { ... }

Have the transmitter class implement that interface and return the singleton instance as that interface:

public class Transmitter implements ITransmitter {
    public static ITransmitter getInstance() { ... }
}

The instance returned is actually a proxy created using java.lang.reflect.Proxy with an InvocationHandler that will delegate the appropriate method invocations using reflection.


There are a lot of loops in here. I would probably turn at least one of them into a recursive function; actually, refactoring high low and pivotIndex into let constants with recursion should be faster due to optimizations. (I'm not that good of an FP programmer to mock something up for you quickly).

Otherwise, one suggestion I'd make (just my preference), you have two major loops smooshed next to each other, perhaps another empty line could help readability:

            // Partition elements such that:
            //   a[i] <  pivotElement    for low <= i < pivotIndex,
            //   a[i] >= pivotElement    for pivotIndex <= i < high.
            var pivotIndex = low

            while a[pivotIndex] < pivotElement {
                pivotIndex += 1
            }

            for i in pivotIndex+1 ..< high {
                if a[i] < pivotElement {
                    swap(&a[pivotIndex], &a[i])
                    pivotIndex += 1
                }
            }

I would definitely try refactoring some of this to FP, then running it through some measureBlock()s in Xcode to see if it's faster.

Hope this helps!


Fun question;

you should write a function that takes a parameter instead of just writing the code
A chessboard has lots of repetition, take a minute to ponder how String.repeat could make this code much simpler.
Your indentation is not perfect, consider using a site like http://jsbeautifier.org/
I am not a big fan of var within the loop, I would declare var up front.

This is a possible solution that provides the right size of the board:

function createChessboardString(size){

  const line = ' #'.repeat( size ),
        even = line.substring(0,size),
        odd = line.substring(1,size+1);
  let   out = '';

  while(size--){
    out = out + ((size % 2) ? odd: even ) + '\n';
  }

 return out;
}

console.log(createChessboardString(8));

You could consider for very large boards that the board in essence repeats
odd + '\n' + even, so you could repeat that as well. The problem for me is that there are too many corner cases to consider. So personally I would go for the above for any board size < 1000.


Basic calculator that calculates result based on operands using a class

There is no need to manually raise ZeroDivisionError. Python will do it for you anyway.
Rather than inspecting an operand with the bunch of ifs, create a dictionary of operand, lambda:

ops = {
    '+': lambda x,y: x + y,
    ....
}

and calculate the result as

ops[operand](value1, value2)

Such dictionary (initialized in a constructor) is the only justification for making a class. It doesn't feel right to make an operator and values class members. Consider

r = calculator()
r.calculate(1, 2, '+')
r.calculate(3, 4, '*')

etc.


A few things stand out:

The many levels of indentation. Consider putting the contents of one of the loops into a function, and calling that instead. For example, all the printing work could be done in a separate function. I'd suggest a maximum number of four levels of indentation
The amount of comments. Comments are to explain how something works (an algorithm), not what you're doing. The latter should be obvious from the code. And definitely not a comment per line.

For example:

def pattern(count): #created a function here called pattern, and gave it a parameter called count

is an unnecessary comment: Python programmers know def means to create a function, and the parameter (I think Pythoneers tend to use the term argument instead) is obvious as well.
The lengthy lines. The suggested maximum line length is 79 characters, though preferences and local standards may differ. A situation like here provides a good example about a limited line length: you have put code in a code block on a web site, which has set a limited viewing width. And you can immediately see why long lines can be bad, in particular: hard to read. (Hint: other than removing all those comments, consider putting comment lines on the line preceding the code).
If a user enters something that can't be converted to an int, they'll get presented with a traceback. That is not very user friendly. Consider testing this appropriately (error checking is, for some code at least, > 50% of the actual code).
You have if run < count / 2:, and below that if run >= count / 2:. Since run and count don't change in between, an else instead of the second if-statement is probably clearer.


Displaying information about an order when selection changes

Architecture
One thing that jumps forward is that you're going straight from the UI to your datasource. In a three-layer design (UI, Model, Persistence) or MVC (Model, View, Controller) there is always a layer between the UI and your datasource.
A samplesetup would be this:
interface IOrderRepository {
    IEnumerable<OrderInfo> GetOrderById(int id);
}

class OrderRepository : IOrderRepository {
    public IEnumerable<OrderInfo> GetOrderById(int id){
        using(var context = new MyDataContext()){
            return context.OrderInfo.Include("Item").Where(x => x.OrderID == ID).ToList();
        }
    }
}

class UIController {
    private IOrderRepository _orderRepository;

    public void OnOrdersSelectionChanged(DataGridView view){
        _orderRepository.GetOrderById(Convert.ToInt32(dgv["ID", dgv.SelectedRows[0].Index].Value));
    }
}

Now your view is coupled loose from your datasource through the intermediate repository. You might be interested in reading up on the repository pattern, for example here.
Resources
I don't see a using statement in your code so I assume that your DataContext is held as a private field. This context class is explicitly made to be disposed after using it once so you should use it as such.
In the MSDN blog I linked just before the repository is disposed instead which is also an option although I have found that wrapping all calls to the DataContext is more often used.
Braces
Always add your braces to your if statements, even when it's just one line. It's simply too easy to make mistakes.
Inline declaration
This snippet
List<OrderInfo> OrderInfo = new List<OrderInfo>();
OrderInfo = c.OrderInfo.Include("Item").Where(x => x.OrderID == ID).ToList();

is an elaborate way of writing
var orderInfo = c.OrderInfo.Include("Item").Where(x => x.OrderID == ID).ToList();

Notice also how I made orderInfo lowercase. Keep naming conventions in mind!


This code is pretty good, and there's very little to improve.  The two-line fold expression did benefit from the explanatory comment in the description, so perhaps it could get a summary in the code?

I found a couple of very minor simplifications:

We can declare count as

    static const auto count = sizeof...(PredsT);

Instead of duplicating ++begin in a for loop, we can transform to a simpler while loop:

    while (++begin != end) {

Instead of indexing selected, we might choose to iterate (and avoid a no-op assignment, and avoid the need to remember precedence of comma operator):

    auto p = selected.begin();
    ((preds(**p, *begin) ? *p++ : *p++ = begin), ...);


Your bottleneck is probably that you write the file to disk first and then read it again (I/O).
If the file does not exceed your machines random access memory, decompressing the file on the fly in memory might be a faster option:

from gzip import decompress
from json import loads

from requests import get

def get_gzipped_json(url):
    return loads(decompress(get(url).content))

if __name__ == '__main__':
    print(get_gzipped_json("https://xxxxx.auth0.com/1537150574"))

Also note, that I put the running code into an if __name__ == '__main__': guard.


Sum of two elements of a list equaling a target

Since the task is about using arrays, I would suggest to use OCaml arrays and not list. Because of lists, you need to use List.nth and that is quite costly.


Proper way of using the MVC concept - update

I'll skip MVC for now, as I see a whole review for formatting and the such. Perhaps someone else could break down the pattern for you. Right now, let's focus on each individual class.

Model

public!? What's your logic behind that!? Are we programming object-oriented code here? Part of OOP is designing with encapsulation in mind. Encapsulation is using those getters and setters. So in your case, we might find:

protected $site_url;

public function getSiteURL() {
    return $this->site_url;
}

Here are some benefits of doing this:

  By keeping data private and providing public well-defined service
  methods the role of the object becomes clear to other objects. This
  increases usability.

Source

  The shielding of the data means that should the format of the private
  data need to change for some reason the objects invoking methods on
  the object whose data has changed will not need to change the format
  they send their messages in.

Source

  Encapsulation is used to hide the values or state of a structured data
  object inside a class, preventing unauthorized parties' direct access
  to them.

Source
You should type hint $global with array.
In general, it seems strange to be passing this type of configuration data as an array in the constructor. If you had a configuration class, then you could pass that, and then the model would have to worry less about the information it's handling. It will only get the information it wants, yet it's expandable so you can later add more information.

View

You could improve the constructor to something like:

__construct(Model $model, Controller $controller)

This way you know exactly what's being thrown at you.
You raised the scope of $this->content, which is unnecessary. Keep it local.
'{' . $key . '}': it would make more sense to do this as you replace, not store.
$key and $value aren't very meaningful names.
For both createParam and replaceParams, don't be afraid to type out the whole word. It helps no one to shorten it like you have.
pageExists has no business living in the view.
And probably the biggest issue I see is the lack of support. Right now, this class replaces static values on static pages. What if we need a conditional on the view? ("If the user's logged in, show this. If not, show that") Or maybe a you want to show all the blog posts you stored, well you'll need to build the HTML in your PHP, and then send it all as one parameter! Think about what you can do to support these types of edge cases.

Controller

It's not uncommon to see child controllers, so private may want to be protected for $model.
Type hint Model in the constructor.
Any type of "handler" or "manager" is a bad sign. So either handlePageLoad needs a new name, or the contents need to be broken down. Let's have a look...
Well, it looks like the method "handles" to much! Perhaps pageExists should be a controller function, and that way you can work in the path.
$this->path should be local to the method. You're reducing the class scope's clarity by not having proper local variables.
Normally there's a space after ifs.
file_exists returns a boolean only, so the type comparison is overkill. A simple == would suffice.

Global

classes is a horrible directory name. I highly suggest you change that. Perhaps break apart the classes by responsibility.
Here's anything fuzzy variable name, $global.
I don't see the connection between 'theme' and 'v1'. Is "theme" not the best word?


Resources:
You should start using try-with-resources. This statment does some work for you with resources that implement AutoCloseable. It closes these resources for you, so you don't have to worry about file-locks and remaining database connections:
File file = new File("C:/text.txt");
try(Scanner scanner = new Scanner(file, "utf-8")){
    //your code here ;)
}

You also shouldn't throw Exception in the main method of your program. This can be very confusing to users. Instead you main-method should handle all exceptions "gracefully" by being wrapped into a try-catch-block.
Conditionals:

if(!Character.isLetter(c)){
   continue;
}

This is an early return statement for the purpose of following conditions, meaning you don't have to write else if in your next condition.
Naming
hashMap is not a good name. The map you use is not a Hash-Map, and treeMap would also not explain what the map does, what it contains.
You might want to rename it to characterMap
all else equal, your naming is nice and consistent, and tells exactly what the variables do. You nicely follow camelCase-conventions. Keep it up!
Summary:
Your code reads nicely and is easily understandable. You follow naming conventions and have descriptive and understandable variable names. You should work on your exception handling and the use of resources.


Overview
There is an issue (Bug) here in that yytext points at the beginning of the lexeme. But the lexeme is not null ('\0') terminated. You need to pass a length if you want to pass the current token into vec
   vec.push_back(yytext);

   // should be:
   vec.emplace_back(yytext, yytext + yylen);

You had a bug in your call to the underlying base class.
    FileLexer(std::istream& in, std::ostream& out) :
        yyFlexLexer{&in, &out},
        out{out}
    {}

Sorry I fixed it before any answers. But you need to pass the address of the streams to yyFlexLexer.

Normally I would return a value for each lexeme (and move any complex processing into methods of FileLexer. BUT this is such a simple class I don't see any issue with your current implementation of putting all the code in the lexer directly (though I would remove the return 1; from the end of line marker to make it consistent with field processing).

This seems to be correct.
std::copy(vec.begin(), vec.end(), std::experimental::make_ostream_joiner(out, ","));
out << '\n';

But it is not obvious how it achieves it. Would be nice to have a comment that points out that field 10/11 are not added to the end but rather to a point not at the end of the end of the vector.


The minRectangle is doing what it should but could be improved by storing the value of area() in a variable. Assume you have 1.000.000 rectangles to check then the calculation would happen 2.000.000 times.

public static Rectangle minRectangle(Rectangle[] rect) {

    Rectangle min = rect[0];
    double minArea = min.area();

    for (int i = 0; i < rect.length; i++) {
        double currentArea = rect[i].area();
        if (currentArea < minArea) {
            min = rect[i];
            minArea = currentArea;
        }
    }
    return min;
}

The selectRectangles() method is doing too much work as well. By using an List<Rectangle> to add the rectangles with the desired color and returning the list as array will speed this up.

Please don't omit braces {} although they might be optional. Omitting braces can lead to hidden and therfor hard to track bugs.

public static Rectangle[] selectRectangles(Rectangle[] rect, String color) {
    List<Rectangle> rectangles = new ArrayList<>();
    int countRect = 0;
    for (int i = 0; i < rect.length; i++) {
        if (rect[i].getColor().equals(color)) {
            rectangles.add(rect[i]);
        }
    }

    Rectangle[] results = new Rectangle[rectangles.size()];

    return rectangles.toArray(results);
}

The last task in question isn't solved correctly. You should first get the yellow rectangles in the array and then detect the smallest of these.


Check this method. Pass value as minus 18 (-18)

-(NSDate *)offsetYear:(int)numOfYears date:(NSDate*)date {
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
    [offsetComponents setYear:numOfYears];

    return [gregorian dateByAddingComponents:offsetComponents
                                  toDate:date options:0];
}


Sort three numbers using only if-statements

I will try to take several things into account but to keep things simple. A few remarks:

First, it seems that you have a typo here:

if ((num1 < num2) && (num3 << num1))

I think that you meant num3 < num1 instead of num3 << num1 in your second condition.
As @Josay says, you better write small functions. I would add that you better separate the input/output operations (that you can keep in main) and the sorting function. In my opinion, this would be a good enough signature for the sorting function:

void sort3(int& a, int& b, int& c);

You would give three variables to it and it would sort them in-place so that you end up with \$ a \le b \le c \$.
Now, let's choose an algorithm. For three values, the easiest is to implement a bubble sort which shouldn't be really slower than other algorithms (when you want to sort more values, it becomes horribly slower though).

void sort3(int& a, int& b, int& c)
{
    if (a > b)
    {
        std::swap(a, b);
    }
    if (b > c)
    {
        std::swap(b, c);
    }
    if (a > b)
    {
        std::swap(a, b);
    }
}

Most sorting algorithms heavily rely on swapping values. The one I just implemented sorts your values with only three comparisons and at most three swaps and is, in my opinion, far simpler to understand than what you had.

Note that there are more efficient algorithms but I deliberately chose to present one that is not that bad while easy to understand.
This is not a problem in your case, but we can't stress out enough that using namespace std; is often considered bad practice. It is the case when used in a header file, especially in a library header file since it will pollute the global namespace of every file including it. That's not a problem for you since you're probably doing everything in a .cpp file but it's better to keep that in mind.
You don't need to return 0; at the end of main. If the compiler reaches the end of the main function without having encountered a return statement, it automagically adds a return 0; for you. Note that it only works with main though. Dropping this line is an interesting way to document that your program cannot return error codes and that it will only ever return 0.


How to turn this working A/B optimization program into more pythonic code?

There is massive code duplication in your script. Basically you are doing the same things for A through E, so you could just put them in a list of dictionaries and use loops. Also, by using defaultdict you do not have to initialize them per hand (and even if not you could use a loop for this, too). Also, I'd recommend removing the code for transforming the URL to a 2D array from the function, and using just split() without '\t' the code works as well, and is somewhat more robust to other input formats.

from urllib.request import urlopen
from collections import defaultdict

def getBestDesign(data):
    # this list holds all your A, B, C, ... dicts, with defaultvalues
    ABCDE = [defaultdict(int) for i in range(5)]
    for row in data:
        if row[5] == '1':
            for i in range(5):
                ABCDE[i][row[i]] += 1
    for i in range(5):
        maxclicks = max(ABCDE[i].values())
        for k, v in ABCDE[i].items():
            if v == maxclicks:
                print('ABCDE'[i], ": ", k) # note the ''!
                # break # optional, stop after first "max" value

if __name__ == "__main__":
    url = input('Url: ')
    lines = urlopen(url).readlines()
    data = [line.decode(encoding='UTF-8').split() for line in lines]
    getBestDesign(data)

The algorithms is still basically the same as yours, and I think that it can still be improved. Probably you could use numpy to treat the input data as a matrix and do all sorts of useful matrix operations on the data. Further, you could probably use collections.Counter or itertools.groupby for counting the good combinations, reducing the whole thing to two or three lines.

Here's another version, even shorter, doing some preprocessing and using collections.Counter:

def getBestDesign(data):
    filtered = [d[:-1] for d in data if d[5] == '1']
    for i, d in enumerate(zip(*filtered)):
        key, maxclicks = Counter(d).most_common(1)[0]
        print("{0}: {1} ({2})".format("ABCDE"[i], key, maxclicks))

Let's explain this line by line:

the filtered list comprehension holds just the lines from data where the user has clicked; as this is already filtered, we can drop the last column with [:-1]
in the loop, we iterate the data columns -- zip(*...) basically transposes the matrix -- using enumerate, which yields the index i and the actual data d at that index
the Counter class is used to count each variant and to return the most_common one
finally, we print the result using string.format, using the index i to get the respective letter from the string "ABCDE"


Create variable and use in one stored procedure

You can make it shorter by having a single query, thus avoiding the extra variable @SiteIDOriginal and possibly make it a little faster:

ALTER FUNCTION [dbo].[GetImage]
(
    -- Add the parameters for the function here
    @SiteID varchar(100)
)
-- It is required as it specifies return value type
RETURNS varchar(100)
AS
BEGIN
    DECLARE @SiteImage varchar(100) = (
        SELECT ImageName
        FROM TblImages Img
            JOIN TblPropertyDetails PD ON PD.ClientsSiteID = Img.SiteID
        WHERE PD.ClientsSiteID = @SiteID
    )

    RETURN @SiteImage
END
GO

Other than that, something more of aesthetics:

try to have uniform formatting (blanks between variables and operators etc.)
use indentation (I usually treat SQL as Java or C# code where every "begin"
and "end" trigger a new level of indentation). This is particularly useful when reading rather large objects.


There are a couple issues with this code:

You don't define a function in Javascript with ajaxRequest(function() { ... }); What you're doing there is calling function ajaxRequest and passing an anonymous function into it as the only parameter. It will throw a JS error as it is now, because ajaxRequest isn't defined.

To define an ajaxRequest function, you would do either function ajaxRequest() { ... } or var ajaxRequest = function() { ... };.
This code snippet:

activexmodes = ['Msxm12.XMLHTTP', 'Microsoft.XMLHTTP'];
_ref = activexmodes.length;

for (_i = 0, _len = _ref.length; _i < _len; _i++) {
    i = _ref[_i];

will also throw a JS error because you're treating _ref like an Array when it's actually a Number. I'm guessing you meant to use activexmodes instead. _ref is completely unnecessary.
Why do you declare all your variables at the very top of the function? It's bad practice because declaring your variables when you first need them tells anyone who reads your code that "this is the first time I'm using this variable." If you declare them all at the top, anyone else who reads it has to search through to make sure it's not used or modified anywhere else. (In this case it's harmless, but in larger functions it can become and issue.)
To use the function, you should call it directly instead of using new:

var get_request = ajaxRequest();   // probably should be named getX(),
                                   // like getAJAXRequest()

I would be careful about returning false from the function. If that's a known return value and you're going to check for it everywhere you use it, then that's okay. But if you forget to support that rare case, the user will get some cryptic JS error somewhere down the line when you try to call get_request.open() or some other function.


Iterator<SelectionKey> keyIterator = selectedKeys.iterator();

            while (keyIterator.hasNext()) {

                SelectionKey key = (SelectionKey) keyIterator.next();

This cast here is not needed; you already know that you're going to get SelectionKey out of the keyiterator.

Looking up a bit, you declare Set<SelectionKey> selectedKeys = selector.selectedKeys();, but only use it for the iterator. The variable name doesn't add anything to understanding the code, and you might just want to say Iterator<SelectionKey> keyIterator = selector.selectedKeys().iterator();

(key.readyOps() & SelectionKey.OP_ACCEPT) == SelectionKey.OP_ACCEPT

This sort of statement, I'd wrap in a function. Bit manipulation tends to be very low level stuff and looks out of place in a function responsible for doing high level stuff.


Your "clear" button

To get your clear button to work, you just need to add the event listener to each button as its created, rather than at page load.  To do that, take out your .forEach() function and add this line to the end of your addField function:

remove[remove.length - 1].addEventListener('click', removeField);

You'll also want to change the remove declaration so that instead of using querySelectorAll() (not a live list) it uses .getElementsByClassName() (a live list):

var remove = document.getElementsByClassName('remove');

Optimization suggestions

In addField, the field variable is only used once. You can make the code a little more concise by removing that variable and changing your declaration of clone to this:

var clone = document.getElementsByClassName("input-container")[0].cloneNode(true);

You can condense it even further by changing the clone declaration to:

var clone = input[0].cloneNode(true);

In removeField, if you want to reduce the number of variables (and lines) you can replace these lines inside your if statement:

var parent = this.parentElement.parentElement.parentElement;
var child = this.parentElement.parentElement;
parent.removeChild(child);

with these:

var child = this.parentElement.parentElement;
child.parentNode.removeChild(child);

Enhancement suggestion

If you want to add autofocus to each newly-cloned element, so that as it's added it automatically has focus, you could do so easily by adding this line to addField:

latestInput.childNodes[1].focus();

and adding this line to the bottom of your code, to run on load:

input[0].childNodes[1].focus();

Here's what your code looks like with all of the changes mentioned above:

var add = document.getElementById('add');
var input = document.getElementsByClassName("input-container");
var remove = document.getElementsByClassName('remove');

var addField = function() {
  var clone = input[0].cloneNode(true);
  var latestInput = document.getElementById("list-container").appendChild(clone);
  latestInput.childNodes[1].value = '';
  latestInput.childNodes[1].focus();
  remove[remove.length - 1].addEventListener('click', removeField);
};

var removeField = function() {
  if (input.length > 1) {
    var child = this.parentElement.parentElement;
    child.parentNode.removeChild(child);
  }
};

add.addEventListener('click', addField);
remove[0].addEventListener('click', removeField);

input[0].childNodes[1].focus();
@import url('https://fonts.googleapis.com/css?family=Quicksand:300,400,500,700');
@import url('https://fonts.googleapis.com/css?family=Chewy');
* {
  box-sizing: border-box;
  font-family: 'quicksand', 'sans-serif';
}

html,
body {
  background: #E0E6ED;
  width: 100%;
  height: 100%;
  font-family: 'quicksand', 'sans-serif';
}

h1 {
  font-size: 50px;
  color: #E85D75;
  font-family: 'Chewy', cursive;
}

.main-container h1 {
  margin-bottom: 20px;
}

.text-center {
  text-align: center;
}

.text-input {
  width: 100%;
  border: none;
  border-radius: 4px;
  padding: 10px;
  font-size: 12px;
}

.input-container {
  position: relative;
  margin-top: 8px;
}

.input-container:first-child {
  margin-top: 0;
}

.remove-container {
  position: absolute;
  right: -22px;
  top: 0;
  line-height: 35px;
}

input:focus {
  outline: none;
}

.main-container {
  width: 200px;
  position: relative;
  top: 50%;
  margin-left: auto;
  margin-right: auto;
  transform: perspective(1px) translateY(-50%);
}

.plus-container {
  display: block;
  margin-top: 10px;
}

.fa.fa-plus,
.fa.fa-close {
  color: #C0C8D2;
  cursor: pointer;
}

.fa.fa-plus:hover,
.fa.fa-close:hover {
  color: #E85D75;
}

To-Do List

      <input class="text-input" type="text" placeholder="Type something">


You say you got a hundred of these? And possibly longer?

I suggest you invest on learning these tools:

A client-side MV* framework like Backbone. That way, your code will be modular and structured.
As for your UI, I suggest you go with Mustache for a logicless templating solution.
An automation tool like Grunt, which runs for you the most repetitive tasks like merging files, moving files unit tests etc.

I also suggest you watch this video from Nicholas Zakas regarding scalability and architecture. Though not all points will be applicable, at least you get the idea how to loosely couple your code.

As for the questions:

  In an MVC environment, should the Ajax data part be in the url?

If you were to use MVC, that would be handled in the Models and Routers. Depending on the framework, some handle it for you. Just give them the proper routing and parameters, and you are good to go. No "low-level" code.

  I will be splitting up the functions into different files an the production environment.

It's only in development that you actually split them so they make sense. In production, you actually merge and minify them. Check out jQuery. Their source is split into parts during development, but end up with a squished file during deployment.

The usual procedure (via Grunt tasks) is:

jsbeautifier - Beautify code, so that the linter will be happy
JShint - Checks for syntax errors, readability issues, possible break areas.
Qunit - Unit testing for all your functions. to check if it works as expected.
concat - Join all files into one. Lessens HTTP requests.
minify - shrinks your concatenated scripts, to lessen download size.

And you end up with one power-packed nKB file (where n is the size of course).

  The main problem I'm having with this is that it just looks like it's hanging loosely together, and doesn't fit my structured MVC environment/code.

I really suggest you invest your time in your toolset. I gave suggestions above based on experience and taste. There are other tools out there, like other MV* frameworks, other template engines. You might even want to learn SASS or LESS for CSS.

Although I encourage you to learn the tools, which will lead you to ultimately abandon your old code, here are a few tips though:

The index.php/ part of the url can be removed via url-rewriting on the server. As far as I know, there's a solution posted somewhere in the CodeIgniter forums, which can be searched. That way, your code will always start right after the first / of the domain.
The data parameter of $.ajax() can accept objects:

data: {
  username : username,
  password : password
}

These could be avoided using templating:

$("#login-window-inner-message").html("The credentials provided were not found. Please try again.");


Extracting the classpath entries from a jar file's manifest

I would create the trap for cleanup before an action is done that needs cleanup, so change the sequence of commands. Also I would prefer signal names instead of numbers. If you add EXIT to the signal list then cleanup is called when the shell is exited, so you can remove the last line of your script (cleanup)

trap 'cleanup' EXIT SIGHUP SIGINT SIGQUIT SIGTERM
mkdir -p "$workdir"

If the script is called without argument or with-? a usage message should be displayed.

Warnings and error messages should be written to stderr(2) and not to stdout(1). This is Unix standard behaviour for a program. Otherwise you will not see the error message if you pipe the output through a grep command.


Loop through products and return first product that matches criteria

Clean, readable code. But why not use more of PHP's standard array functions? Use the array_search or in_array functions. Or -even more fancy- the array_filter function.


There's probably much that can be done, but I'll give it a quick review:

Are only integer grades allowed?  They can be decimals in real life, and that would make for a more robust grading system.
Consider renaming UserNumber to something like numericalGrade.  The former sounds like it's for an ID number, not a grade.
Do not "list" variables at the top of a function in C++, unless it's absolutely necessary.  Here, you can declare UserNumber between the std::cout and std::cin.
There's no need for a Z case here.  Use a default case instead, which will be reached if no other case is reached.
You don't need an explicit return 0 at the end.  The compiler will do this return for you at the end of main() as successful termination is always implied here.


As suggested by rolfl you should do Benchmarks on different approaches. This is the only way to tell, if you actually improved on your function.

There are a few points you can improve (or check if they actually improve your case) that I can share from experience:

1) currently you are converting the bytes to string and then you are creating an integer from them. Since you already know there will be integers, use the binary package to do the transformation from bytes directly to integer:

order := binary.LittleEndian
myint := int(order.Uint64(mybyteslice))

Note: this is about 10 times faster than any string/scan operation you can do.

2) Have you checked ReadBytes function of the inputreader? That could probably eliminate your for loop and thus also eliminate the memory allocations you have each time you add an item to mybyteslice.

3) This probably should be the first point because it is the most important: check out the pprof tool to investigate your code. For this you definitly need to write Benchmarks or generate load for your code another way. Then check what takes time in your code and minimize your allocations. Good places to start with pprof are this video and the very good article Debugging performance issues in go making a lot of suggestions.


Detecting properly nested parenthesis using functional programming

The algorithm is overly complicated, and incorrect: for example, it will fail on the input (())().

  I feel like it could ... use a more functional approach to solving the problem.

There is a more functional approach, maintaining a count of how many parentheses are open.

Let's start with the function signature

let rec isNested' (parens : char list) (openParens : int) : bool =

And fill in the cases. If there are no parentheses left to process, and no open parentheses, they are properly nested.

    match parens, openParens with
    | [], 0 -> true

If we are processing a (, we increase the open parentheses count

    | '(' :: rest, _ -> isNested' rest (openParens + 1)

I'll leave the other two cases up to you.

For convenience, we add a wrapper for this function

let isNested (parens : string) = isNested' (List.ofSeq parens) 0


This loop looks odd...

static void *demod_thread_fn(void *arg)
{
    while (!do_exit)
    {
        if (do_exit)
        {
            return 0;
        }

        ...
    }

    return 0;
}

Looks to me like you can get rid of the if. If do_exit can change
between the first check and the second, and that's important, then you have
a race condition -- it could change after the second check as well.  No
amount of rechecking can provide you any assurances.
Consider using a semaphore rather than busy-waiting for o_buffer_count to change.
Decide whether this is to be C or C++. :P  If it is supposed to be C++, then you should be using new and delete rather than malloc and free. If it's not, then you ought to either typedef your struct types or actually say struct output_buffer etc.