What you have isn't bad, but I feel like you're creating too many variables. For example, in getAuditID and other methods, you assign an object to a variable and immediately return it. You also have some unnecessary type annotations.
def getAuditID: String = {
    val instant: Instant = Instant.now
    val zoneId: ZoneId = ZoneId.of("Canada/Eastern")
    val auditIdFormatter: DateTimeFormatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS")
    val auditId = ZonedDateTime.ofInstant(instant, zoneId).format(auditIdFormatter)
    auditId
}

After eliminating that, I got this:
abstract class FileSystem(flagFileURI: String) {

  def getRecordCount(properties: Properties): String =
    properties.getProperty("recordCount")

  def getAuditID: String =
    ZonedDateTime
      .ofInstant(Instant.now, ZoneId.of("Canada/Eastern"))
      .format(DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS"))

  def getSourcePath(properties: Properties): Path =
    new Path(properties.getProperty("dataFileURI"))

  def getMetaDataFileURI(properties: Properties): String =
    properties.getProperty("metadataFileURI")

  def getIDPDataDate(properties: Properties): String =
    properties.getProperty("idpDataDate")

  def getDataFileName(srcPath: Path, auditID: String): String =
    srcPath.getName + "_" + getAuditID

  def getDestinationPath(
      properties: Properties,
      metaDataFileURI: String,
      IDPDataDate: String,
      dataFileName: String
  ): Path = {
    val l0DirLocation =
      ConfigFactory.load().getString("sparkFramework.hdfs.l0dirlocation")
    val frameWorkUtils = new FrameworkUtils()
    val sourceSystem =
      frameWorkUtils.getSourceSystem(metaDataFileURI)
    val schemaName = frameWorkUtils.getSchemaName(sourceSystem)
    val tableName = frameWorkUtils.getTableName(sourceSystem)

    new Path(
      l0DirLocation + schemaName + "/" + tableName + "/idp_data_date=" + IDPDataDate + "/" + dataFileName
    )
  }
}

However, your other method, copyFromLocalFile, could also be improved. The return type is a tuple of 5 strings, which to me seems much too complex. Instead of that, I'd suggest making a case class that makes it obvious what each of those strings mean.
case class FileInfo(
    IDPDataDate: String,
    recordCount: String,
    auditId: String,
    metaDataFileURI: String,
    dataFileName: String
)

Then you can define this method in FileSystem to get all the information at once
def getFileInfo(properties: Properties): FileInfo = {
    val auditId = getAuditID
    FileInfo(
      getIPDDataDate(properties),
      getRecordCount(properties),
      auditId,
      getMetaDataFileURI(properties),
      getDataFileName(getSourcePath(properties), auditID)
    )
}

After that, you can turn your method into something like this:
def copyFromLocalFile: FileInfo = {

    val properties: Properties = new Properties()

    properties.load(Source.fromFile(flagFileURI).reader)

    val fileInfo = getFileInfo(properties)

    FileSystem
      .get(new Configuration())
      .copyFromLocalFile(
        true,
        false,
        fileInfo.srcPath,
        getDestinationPath(
          properties,
          fileInfo.metaDataFileURI,
          fileInfo.IDPDataDate,
          fileInfo.dataFileName
        )
      )

    fileInfo
}

You can still destructure the result:
val FileInfo(idpDataDate, count, auditId, metadataFileURI, fileName) =
  hdFileSystem.copyFromLocalFile

Of course, I don't know about the whole structure of your program, so this might not work for you.
Link to Scastie


Dynamic Dispatch replacement for Generic methods

Personally, I would be able to live with your huge if statement if it remains straightforward, is well tested, and hidden in a nice class. I think a parser will often have these types of structures, especially if you are generating it from a grammar using a tool (like ANTLR for example) instead of coding it by hand.

You could slightly improve the huge if statement by factoring out currentNode.getData().getClass() (instead of currentNode.getData()):

final Class<?> dataClass = currentNode.getData().getClass();
if (Number.class.isAssignableFrom(dataClass))
    dxNode = new TreeNode<Double>(0.0);
else if (AddOperator.class.isAssignableFrom(dataClass))
    dxNode = deriveAddContext((Node<AddOperator>) currentNode);
else if (MulOperator.class.isAssignableFrom(dataClass))
    dxNode = deriveMulContext((Node<MulOperator>) currentNode);
else if (SineFunction.class.isAssignableFrom(dataClass))
    dxNode = deriveSineContext((Node<SineFunction>) currentNode);

You could also consider using Java 8 to create an explicit mapping between the class the current node (data) is assignable from and the initialization code for dxNode using lambda expressions. This has the advantage that you should be able to extend the expression types by adding a single line to the map:

public Node deriveAlternative(final Node currentNode, final Node parentNode) {
    Node dxNode = null;

    final Map<Class<?>, Function<Node, Node>> deriveMap = new HashMap<>();
    deriveMap.put(Number.class, n -> new TreeNode<Double>(0.0));
    deriveMap.put(AddOperator.class, n -> deriveAddContext((Node<AddOperator>) n));
    deriveMap.put(MulOperator.class, n -> deriveMulContext((Node<MulOperator>) n));
    deriveMap.put(SineFunction.class, n -> deriveSineContext((Node<SineFunction>) n));

    final Optional<Class<?>> optionalKey = deriveMap.keySet().stream()
            .filter(key -> key.isAssignableFrom(currentNode.getData().getClass()))
            .findFirst();

    if (optionalKey.isPresent()) {
        final Class<?> key = optionalKey.get();
        dxNode = deriveMap.get(key).apply(currentNode);
    }

    if (dxNode != null && parentNode != null)
        dxNode.setParent(parentNode);

    return dxNode;
}


Recording a customer's shopping cart as an order

Using the "try-with-resources" statement should clean up your code significantly. There are two advantages:

It allows you to declare your resources (in this case Connection and Statement objects) in exactly the scope they're going to be used. This means you don't have to first initialize them to null, which is ugly.
It will ensure your resources get closed no matter what.

Also, you should probably print the stack trace (to aid you and others in debugging), and you should print your error messages to stderr instead of stdout.

public long insertOrder(Customer customer, Hashtable<String, CartItem> shoppingCart)
{
    try (Connection connection = MySqlConnection.getConnection();
        Statement statement = connection.createStatement();) {
        connection.setAutoCommit(false);
        long orderId = System.currentTimeMillis();
        OrderPeer.insertOrder(statement, orderId, customer);
        OrderDetailsPeer.insertOrderDetails(statement, orderId, shoppingCart);
        connection.commit();
        return orderId;
    } catch (SQLException e) {
        try {
           connection.rollback();
        } catch (Exception ex) {
            System.err.println("Could not roll back connection: " + ex.getMessage())
            ex.printStackTrace();

        }
        System.err.println("Could not insert order: " + e.getMessage());
        e.printStackTrace()l
        return 0;
    }
}


Am I reconstructing the buffers correctly

This is the wrong way to sue realloc:

returnBuffer = (char*)realloc(returnBuffer, requestedBufferSize);

If it fails you have just leaked the old returnBuffer.
The way realloc should be used is:

char* tmp = (char*)realloc(returnBuffer, requestedBufferSize);
if (tmp != NULL)
{
    returnBuffer = tmp;
}
else { /* Deal with realloc() failure */ }

But why are you dealing with this. I would use a std::vector<char> it deals with all the memory management issues for you (and your post id tagged C++).

TO be honest I have trouble following the rest of your code.


Using Reflection to Initialize Instance Variables

Reflection is not the correct way to do this. You will need Serialization for this. Another option is to use XML marshalling and unmarshalling, but I am not so familiar with that.

For serialization I suggest you to pick up a copy of Effective Java, and read the last couple of items of the book, which are all about Serialization.

You really need to take care of the following, since you are dealing with a game and network:

Check your class invariants, constructors may not violate them.
Make sure that your seriliazation is all safe as attackers can exploit a lot of things to do some quite surprising things.
Take care of the evolvability of your classes, serialization does pose some issues on that.

I would recommend all your classes to implement a static inner classes called ProxyHelper and implement the Proxy Serialization Pattern on the classes.

Some other ad-hoc review points of your current code:

Do not catch Exception, catch the subclass(es) that you actually see happening, currently it will also catch RuntimeExceptions.
Do preferably not throw RuntimeException, but add somewhat more detail, IllegalStateException may be a candidate here.
Follow the coding conventions, you do it quite well in general, but in the switch (type) { } every case (and inherited code lines) need to be indented one more factor.

In general I would never let Reflection do such a task, I would add with the following code, either a public constructor taking all arguments of the object (which you can get from the String[] data), or if there are too many arguments (more than five usually), you can also emply the Builder Pattern.


Yes, it works, but it's slow.

I compared it to this:

bool[] notPrime = new bool[total];
notPrime[0] = true;
notPrime[1] = true;
for (int i = 2; i <= Math.Sqrt(notPrime.Length); i++) {
  if (!notPrime[i]) {
    for (int j = i * 2; j < notPrime.Length; j += i) {
      notPrime[j] = true;
    }
  }
}

(I used Enumerable.Range(2, total - 2) in the Linq code to make it produce the numbers 2 to 99999 rather than 2 to 100001.)

For total = 100000, average for 100 executions:

Linq 27.696966 ms., 0.280000 collections
Array 0.708616 ms., 0.030000 collections

So, it takes a lot of time, and does more garbage collections.


Your original code:

with open(PR_out_path, 'a') as g:
    for name in PR_files:
        with open(PR_path + name, 'r') as f:
            g.write(f.read())

works but, as you found, has problems if the entire file can't be read into memory.  The solution to that problem is to read the input file in chunks:

with open(PR_out_path, 'a') as g:
    for name in PR_files:
        with open(PR_path + name, 'r') as f:
            while True:
                data = f.read(ChunkSize)
                if not data:
                    break
                g.write(data)

where ChunkSize is something like 1GB.

But if speed is your only requirement why not use the tools offered by the operating system, as others have noted?


One big thing we need to do is to sort everything into arrays

I should point out that

db.stack

is the same as

db["stack"]

Firstly, shift GetChecked() and GetText() (sidenote functions names usually start with lowercase) into an array

local get = { maximum = GetChecked, minimum = GetText }

Stuff that needs to be called during min should be given the "minimum" key. Same with "maximum".

Sort everything else out...

local func = { minimum = "cbutton", maximum = "ebox"}
local keys = {"enabled", "value"}
local minmax = {"minimum", "maximum"}
local db = {}
local stuff = {"stack", "duration"}
local minormax = { minimum = "min", maximum = "max" }

Lets take a break for a second, and create the important array

for _, each in ipairs(stuff) do
  db[each] = {}
  for _, it in ipairs(minmax) do
    db[each][it] = {}
  end
end

This creates

db["stack"]["minimum"]
db["stack"]["maximum"]
db["duration"]["minimum"]
db["duration"]["maximum"]

Now first, we iterate over the stack and duration keys

for _, param in ipairs(stuff) do

end

Then we iterate over the min max values

for _, param in ipairs(stuff) do
  for _, min_max in ipairs(minmax) do

  end
end

Then we iterate over enabled and value

for _, param in ipairs(stuff) do
  for _, min_max in ipairs(minmax) do
    for _, key in ipairs(keys) do

    end
  end
end

To recap, for both the stack and duration, we are checking min and max, and for both min and max, we are checking enabled and value. So your function looks something like this:

db[param][min_max][key] = _G[minormax[min_max]..param][func[min_max]]:get[min_max]()

Finally, we iterate over all the min entries to tonumber them

for _, each in ipairs(db) do
  for _, it in ipairs(db[each]["minimum"]) do
    db[each]["minimum"] = tonumber[each]["minimum"]
  end
end

Let's consolidate everything:

local func = { minimum = "cbutton", maximum = "ebox"}
local get = { maximum = GetChecked, minimum = GetText }
local keys = {"enabled", "value"}
local minmax = {"minimum", "maximum"}
local db = {}
local stuff = {"stack", "duration"}
local minormax = { minimum = "min", maximum = "max" }

for _, each in ipairs(stuff) do --Create the multidimensional array
  db[each] = {}
  for _, it in ipairs(minmax) do
    db[each][it] = {}
  end
end

for _, param in ipairs(stuff) do --The important function
  for _, min_max in ipairs(minmax) do
    for _, key in ipairs(keys) do
      db[param][min_max][key] = _G[minormax[min_max]..param][func[min_max]]:get[min_max]()
    end
  end
end

for _, each in ipairs(db) do --Tonumber all the min entries
  for _, it in ipairs(db[each]["minimum"]) do
    db[each]["minimum"] = tonumber([each]["minimum"])
  end
end

Sorry for the long answer. Hopefully it works, because with such a complicated program my poor brain had to work it out slowly and methodically. The different steps should help you understand my train of thought and help you flush out any bugs (if there are any)

I cannot guarantee this solution will work (I may have messed up somewhere), and it looks really repetitive in itself but here you go.

EDIT: I noticed some of the code is missing. I'll fill in the rest when I have time

EDIT 2: I changed some of the code after reviewing it again.

EDIT 3: Thank you Etan Reisner for pointing out the mistakes I made. I've edited the code.

EDIT 4: You can actually combine the array creation loop and the main body loop if you want:

for _, param in ipairs(stuff) do --The important function
  db[param] = {}
  for _, min_max in ipairs(minmax) do
    db[param][min_max] = {}
    for _, key in ipairs(keys) do
      db[param][min_max][key] = _G[minormax[min_max]..param][func[min_max]]:get[min_max]()
    end
  end
end


Should I use atexit to close db connection?

Firstly, an alternative:

import MySQLdb, contextlib

def main():
    db = MySQLdb.connect( .. )
    with contextlib.closing(db):
         do_thingy()

The database connection will be closed after the with block even in the case of exceptions.

The primary problem created by atexit is in any attempt to reuse that code in question. It will only release the database connection when the entire program exits. That's fine in the case where this function is your entire program. But at some later point that my cease to be the case.

If you really want the database connection to be closed at the end of the function, its clearest if you write code that does that rather then assuming that this is the only function called in the program.

There really is not much of saving to use the atexit route. I think the clarity in the "with" method is worth the extra level of indentation. Additionally, you can use this same technique anywhere in code not just in a main function.


Always check the argument which is reffered by this in an extension method against null to early throw and return. Sure one could say it doesn't matter, because it will throw an ArgumentNullException but that would be thrown from the Regex.Split() method.
You don't check for args == null either.
The optional argument ignoreCase isn't used anywhere in that method so it can safely removed.
if by accident the property of the anonymous object isn't spelled exactly like in the string, the call to argsType.GetProperty() will return null and an NullReferenceException is thrown. Maybe it would be better for such a case to just assume it isn't a property. I will come back to this later.
if the passed in text only contains { the code will throw an IndexOutOfRange exception. This can be prevented by returning early if the length of text is < 3.
if the Length of substrings will be < 3 we can return early by returning text.
the regex pattern does not allow single letter variables being passed. So a text like {i} won't be matched.

Implementing the mentioned points will lead to

public static string FormatFrom(this string text, object args)
{
    if (text == null) { throw new ArgumentNullException("text"); }

    if (text.Length < 3 || string.IsNullOrWhiteSpace(text) || args==null) { return text; }

    var substrings = Regex.Split(text, "({{?)([A-Za-z_][A-Za-z0-9_]+)(}}?)")
                          .Where(s => s != string.Empty).ToArray();

    if (substrings.Length < 3) { return text; }

    var argsType = args.GetType();
    var result = new StringBuilder(text.Length);

    const int propertyNameOffset = 1;
    const int rightBraceOffset = 2;

    var bindingFlags = BindingFlags.Instance | BindingFlags.Public;

    for (int i = 0; i < substrings.Length; i++)
    {

        var possibleLeftBraces = substrings[i];
        var possibleRightBraces = substrings[i + rightBraceOffset];
        var propertyName = substrings[i + propertyNameOffset];

        var isPropertyName = possibleLeftBraces == "{" && possibleRightBraces == "}";
        if (isPropertyName)
        {
            var property = argsType.GetProperty(propertyName, bindingFlags);
            if (property == null)
            {
                result.Append("{").Append(propertyName).Append("}");
            }
            else
            {
                result.Append(property.GetValue(args, null));
            }
            i += 2;
            continue;
        }

        var isEscapedPropertyName = possibleLeftBraces == "{{" && possibleRightBraces == "}}";
        if (isEscapedPropertyName)
        {
            result.Append("{").Append(propertyName).Append("}");
            i += 2;
            continue;
        }

        result.Append(substrings[i]);
    }

    return result.ToString();
}

which will pass all of these tests

[TestMethod()]
public void FormatFromTestStringEmptyShouldPass()
{
    string expected = string.Empty;
    string actual = string.Empty.FormatFrom(null);

    Assert.AreEqual(expected, actual);

}
[TestMethod(),ExpectedException(typeof(ArgumentNullException))]
public void FormatFromTestStrinNullShouldPass()
{

    string actual = ((string)null).FormatFrom(null);

    Assert.Inconclusive("Shouldn't happen !");

}
[TestMethod()]
public void FormatFromTestArgsNullShouldPass()
{
    string expected = "lala";
    string actual = "lala".FormatFrom(null);

    Assert.AreEqual(expected, actual);

}
[TestMethod()]
public void FormatFromTestParamsButArgsNullShouldPass()
{
    string expected = "{land}";
    string actual = "{land}".FormatFrom(null);

    Assert.AreEqual(expected, actual);

}
[TestMethod()]
public void FormatFromTestArgsNotNullShouldPass()
{
    string expected = "germany";
    string actual = "{land}".FormatFrom(new { land = "germany" });
    Assert.AreEqual(expected, actual);

}
[TestMethod()]
public void FormatFromTestArgsNotNullButWrongShouldPass()
{
    string expected = "{land}"; // TODO: Passenden Wert initialisieren
    string actual;
    actual = "{land}".FormatFrom(new { lan = "germany" });
    Assert.AreEqual(expected, actual);
}


Median Calculation of List of Integers without using heap

Performance
I instrumented your code differently:
def main():
    m, n = 1000, 15000000
    start_time = time.time()
    data = [random.randrange(m) for i in range(n)]
    print("--- %s seconds to generate" % (time.time() - start_time))
    # print("Random Data: ", data)
    start_time = time.time()
    result = SortedList(data)
    print("--- %s seconds to sort" % (time.time() - start_time))
    start_time = time.time()
    result = list(Median(data))
    print("Result: ", result)
    print("--- %s seconds ---" % (time.time() - start_time))

For me, the results were:
--- 7.407598257064819 seconds to generate
--- 4.535749673843384 seconds to sort
Result:  [500]
--- 5.01109504699707 seconds ---

This shows that the generation of the random input takes longer than finding the median, and that 90% of Median() is spent sorting (probably most of the rest is caused by converting between lists and iterators).  You're unlikely to get large gains through modifications to your own part of the code.
I got better results by using Python's built-in sorted().  We don't need any of the extra functionality of SortedList (maintaining the invariant through adds and deletes), and a single sort (mostly in native code) gives these results:
def median(values):
    sortedlist = sorted(values)
    length = len(sortedlist)
    half = length // 2
    # return not yield; see "General review"
    if length % 2 == 0:
        return (sortedlist[half] + sortedlist[half - 1]) // 2
    else:
        return sortedlist[half]

def main():
    m, n = 1000, 15000000
    start_time = time.time()
    data = [random.randrange(m) for i in range(n)]
    print("--- %s seconds to generate" % (time.time() - start_time))
    # print("Random Data: ", data)
    start_time = time.time()
    result = sorted(data)
    print("--- %s seconds to sort" % (time.time() - start_time))
    start_time = time.time()
    result = median(data)
    print("Result: ", result)
    print("--- %s seconds ---" % (time.time() - start_time))

--- 7.638948202133179 seconds to generate
--- 3.118924617767334 seconds to sort
Result:  500
--- 3.3397886753082275 seconds ---

General review
I don't see why you yield a single value, rather than simply returning.  Is there a need for Median() to be iterable?
Given that length is an integer, if length % 2 is not 0, it must be 1 - so the elif could easily be else.


Creating new CSS element everytime database updates

Set the return datatype to html and update the DOM in the success callback:

function updatestatus()
{
    $.ajax({
        type: "POST",
        url: "statusupdate.php",
        data: $('#statusupdater').serialize(),
        dataType: "html",
        success: function(data, status, xhrObj){
            $('#statuscontainer').prepend($('<div id="stat">').html(data));
            $("#statusupdater")[0].reset();
            $('.statuspop').fadeOut(300);
            $('#opacify').hide();
        }
    });
}

You could also update the DOM using the error and statusCode callbacks if it fails.


A couple of simplifications are possible that will make this code more Pythonic.

Instead of declaring an empty number = [] and then appending elements,
use a list comprehension:

number = [int(i) for i in reversed(n)]

Notice that I used reversed(...) instead of number[::-1],
which seems a bit more intuitive to me.

Instead of this:

if n[0] == '-':
    n = n.replace('-', '')

I'd find it more clear:

if n.startswith('-'):
    n = n[1:]

At this point it's also clear that n is not a good name.
n is usually used as a number,
but here it's a string.
Maybe "string" or "numString" would be better.

number is also not a good name.
Since it's a list, making the name plural would be more natural.

Instead of this:

        number[i] = number[i] * -1
        number[i] = number[i] * (base ** i)

You could write in a shorter, more natural way:

        number[i] *= base ** i * -1

Similar to the previous point, this can be shortened:

        n = abs(n)
        n //= base
        n = -n

To this:

        n = abs(n) // base * -1

  Basically this program can convert any number from any base to another base including negative bases as long as the input is coherent.

For input arguments 255 10 16 it gives me:

You entered 255 in base 10.
Your number in base 16 is 165.

Normally it should be ff, or at least (15, 15) or something...


Design of class hierarchy for a object formatter API forces derivatives to know too much

This one is screaming for an enum. What you want is what you get:

public enum FormatType {
    XML, JSON, //maybe further support later
}

And your constructor then becomes:

public Formatter (Object object, FormatType formatType) {
    switch (formatType) {
        case XML:
            output = getXMLFormat(object);
            break;
        case JSON:
            output = getJSONFormat(object);
            break;
    }
}

In addition to that a small nitpick on naming:
Your get...Format() methods break the camelCase you kept until then. I suggest you ignore that these formats are acronyms and instead use following method names:

getXmlFormat (Object object);
getJsonFormat (Object object);

But I'd say that's personal preference. All else you didn't give us much to review :(


File uploads with image previews and remove link using Array and readAsDataURL

Welcome to Code Review! Good on you for opening up to constructive criticism.
Buckle up, this will be a long one ;)

 The Question
Let us start with your question:

[...] I don't know if the code is robust or not. Any advice to improve the code is welcome.

I hope you would agree with me when I say that this is not really a proper question. Code "robustness" is a rather subjective matter, so one couldn't objectively answer that. If you would like my opinion: any code that does what it needs to do, everytime you run it, is robust.
I could direct you to the guide on posting a proper question, but I find that is often unnecessary, since I understand what you would want from me so you can improve this code.
Another problem with your question is that you have a bug in your code. Fixing bugs is not really something we do at Code Review, but the way I see it, we can both improve your code and fix the bug in one swoop!
I'm going to review your code nonetheless, because it's perfectly possible, it's fun and people who come here to get their code reviewed can get easily discouraged with all these rules.
The way I measure code improvement in my day-to-day reviews, is by how much smaller you can make a file or function, while maintaining full functionality and  maintaining or improving readability. I'm not really interested in code speed, so you'd have to look elsewhere for tips on that. Let's get to work.

 The problem
The (in my opinion) most valuable advice one could give to a beginning programmer is the following:
Before you start on any given programming problem, you must first understand the problem, and the sub-problems that make up the larger problem, ad infinitum.
In your case it would require you to state and disect the problem as follows:

Create a File upload with image previews and removal functionality

How does one upload a file?

What does it mean to "upload" a file?

How does one remove an uploaded file?

What does it mean to "remove" an uploaded file?

How does one show a thumbnail for an uploaded file?

What is a thumbnail?
How do you get a thumbnail from an uploaded file?
How do you link the remove functionality to a thumbnail?

Thence we can figure out how to write code that solves these sub-problems, and combine those solutions into one big solution.

 How does one upload a file?
This is a part of the problem you've understood. To upload a file with HTML, you use the input tag with type=file. The interesting part here is the next step: what does it mean to "upload" a file?
According to the html specification for <input type="file"/>, an input tag keeps track of what items have been uploaded, known as "the selected files", under a property called files. So for a file to "be uploaded", it must be in the files property of the input. It would seem your mental model does not match the actual implementation of the input tag! That's where the bug comes from.
When you upload a file in your snippet, it overwrites the last selection of uploaded files. You probably thought you fixed it using the multiple attribute, but that attribute only specifically allows multiple files to be uploaded at once. This means that everytime you select any file(s), you lose reference to the previously uploaded files.
Now that we know what we want and understand the problems, we can define a bit of code to do what we want.

<input type="file" multiple onchange="upload(this)"/>

There we go. That's all we needed: an array to store our uploaded files and a function to add to that array any file we upload.
A couple of quick notes about this solution:

input.files is a FileList, not an array -- you knew and understood this. One could transform it to an array and use array methods on it, but I chose to use the ... spread operator. In this context, to spread a FileList means to take every File in the FileList, and provide it as an argument to files.push(...). Other solutions like for (const file of input.files) would also work, with the benefit that these methods don't create an array which we never directly use for anything but looping over.

❌ How does one "remove" an uploaded file?
The way you remove a file in your current code is not actually removing the file. You are just removing the thumbnail from the DOM (that is indeed the right term).
But then what does it mean to "remove" an uploaded file? Well, simply put: if "uploading" means that we add a File to an array, "removing" should just mean to take that File out of the array again:

<input type="file" multiple onchange="upload(this)"/>

A couple of quick notes about this solution:

To remove an element from an array in JavaScript you need to use Array.splice, which requires an index from where to start removing elements, and the number of items to delete from there. files.splice(index, 1) means to remove 1 item at index index.
To know which file we want to delete from the list, we need a way to differentiate between files. The File API defines a property "name" which we can use.
To know the index of the file we differentiated, we need to use Array.findIndex, which takes a function as a parameter and returns either the index of that file, or -1 (meaning the file was not found in the array).
In case we try to remove a non-existing file, we return. This should in theory never happen, but you should always cover your non-happy flows. That's just good software etiquette.

 How does one show a thumbnail for an uploaded file?
This is not a simple question. To show a thumbnail, we must first understand what a thumbnail is.
 What is a thumbnail?
Simply put, if a given file is an image, we want to show a small representation of that image. There's already a problem: your input accepts files of any type. If you upload a pdf or an illustrator file, your code will not work. Again, if you think about the problem and define what you do and do not want, you can create a solution.
The simplest approach is to allow any image, and nothing else. One could make custom rendering logic for all sorts of files; a fun exercise for the reader ;).
HTML has got us covered: you can specify what type of file your input will accept. You can read the entire page (which is quite interesting so why not), but the main takeaway here is that you can use the accept attribute with a value of "image/*" to accept only files that are images:

<input type="file" multiple accept="image/*" onchange="upload(this)"/>

A couple of quick notes about this solution:

An added benefit is that the HTML specification allows user agents to use this constraint to display only images in the file picker dialog.
As mentioned in the spec, there is still no guarantee that uploaded files will really, really be images. We will keep this in mind for the last step.

➡ How do you get a thumbnail from an uploaded file?
Now that we allow only images, we need a way to display uploaded files as thumbnails. You did a good job discovering that you can use the FileReader API to transform a File to an img in the DOM. The method itself is solid, but the approach could be a bit more tactical. This will be the largest code chunk of this answer, so I'm going to annotate it using comments.

<input type="file" multiple accept="image/*" onchange="upload(this)"/>

It works!
A couple of quick notes about this solution:

Like I said in the first comment, you're going to need a solid understanding of Promises. If I were to go into detail here this answer would become far too large.
A thumbnail typically is a version of an image with a much smaller resolution to save data. This solution just loads the entire image into memory, which could be troublesome in case of many uploaded files.

❌ How do you link the remove functionality to a thumbnail?
Now that we have thumbnails and know what it means to remove a file, we can link these together. This is now an easy step.

<input id="files" type="file" multiple accept="image/*" onchange="upload(this)"/>

A couple of quick notes about this solution:

Since some files may share the same name, upon removing an image, it will remove the first image from the array with that name. We can't do much about that using the native API, but you could assign some id to every file upon "uploading" them. That shouldn't be too hard.
All this work really only gives us a DOM representation of our input, but if you would like to upload these files using a <form> you're out of luck. You would need to define custom logic in order to upload the const files array upon form submission -- but since we're already heavy into JavaScript-land here, you might just want to do that. In that case, have a look at the Fetch API which allows you to post blob data (Files implement the Blob interface).

 Conclusion
We've done it -- through blood, sweat and tears perhaps.
Hopefully you learned a thing or two, otherwise this was probably really boring... :)
So how did we do according to my metric of

how much smaller you can make a file or function, while maintaining full functionality and maintaining or improving readability

Well we increased the size of the code... We went from 34 lines to 50. However, there's an important reason: we only care for less code while maintaining full functionality and maintaining or improving readability. We increased functionality, and also made sure the code is actually always correct in a happy flow.
To link that to your inquiry about "robustness": we defined what it means for your code to work, and we made sure it works in every case we want it to. That's robust code in my opinion.
I would also argue that, since we've neatly packed our functionality into reasonably small functions, it's crystal clear what each part of the code does. Your snippet was clear to me as well, so it's not an improvement per se, but that's quite the achievement when you change a large part of the code.
The main takeaways are:

Define the problem, then define the problem, then define the problem...
Think about what the code should do, but also about what it shouldn't do (and make sure it doesn't).
Whenever asynchronous code will run, such as events, you could probably use a Promise to streamline the interface.
I would personally like it better if you would use only one way of defining functions. There are subtle differences in implementation between function and () => {} but you're not leveraging those differences. You could just use either notation to be consistent and reduce the amount of "WTF?!"'s coming from the review room.

You're already quite proficient with JavaScript; you're using fancy syntax such as const and () => body, you have researched and understood intricate concepts of the browser environment and you're using as much vanilla JS and HTML as possible. Very nice!
Here's the final snippet:

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>

  <input type="file" id="files" multiple accept="image/*" onchange="upload(this)"/>


Function queue for synchronous execution

With this in mind, it also allows to execute them with a defined delay, to prevent them from blocking the browser.

This is a common misconception of how the timers work. Currently executing code doesn't stop when a timer expires. That callback waits until the currently running code finishes.

You can think of JS as having 3 internal data structures:

The execution stack, where the currently running code is.
The callback queue, where all callbacks for async operations are stored
The callback ready queue, where all callbacks for competed async operations are stored.

When you call a timer function, that callback is stored in the callback queue until the timer expires. When it does, it moves to the ready queue, but it doesn't execute just yet. The current code in the stack will continue until it exhausts the stack. Only then will the engine pick from the ready queue and execute it. This is what they call the "event loop" which is basically code taking turns, one after the other.

So adding a delay isn't really needed. You can even put a delay of 0 and it won't block the UI.

What does block the UI is when operations in the stack take too long - regardless where they came from. If you happen to call a function that iterates through 10 billion items, that's the problem. Your stack won't exhaust fast enough to let other code run.

(window.console.error || window.console.log).call(window.console, data);

This is a problem, because some browsers don't even have a console object (I'm looking at you IE8). You'll probably get a "Accessing property error of undefined) when you run this piece of code. Check for console first to be safe.

try {
  //sometimes, when it is to stop, it's already here
  if(!stop){
    queue.shift();//remove it from the queue
    fn.fn();
  }
}

There are 2 problems in this piece of code. First is why are you even trying to use try-catch. Whenever I see a try-catch, it's an indicator that the developer is unsure of what will happen with the code. Solve the root problem of why the code can be unpredictable and make it predictable, before resorting to a try-catch.

The next is optimization. Engines like V8 optimize code heavily (and which is why Chrome is fast). However, code inside a try-catch doesn't get optimized because it is deemed unpredictable.

So what you can do is place all of your code in the try-catch inside a function and call that function in the try-catch instead. That way, the engine can optimize the function, while what doesn't get optimized is the call.

setTimeout(runNext, 1);

I assume your function queue isn't sensitive to when it gets called due to this. Anyways, the problem with this code is that it's calling setTimeout all the time. The problem here is that, as explained in the first section of the answer, you are scheduling when you call a timer.

A better solution for this is to schedule once, using setInterval. Each iteration will call the function next in line. Once the queue is done, you can clear the interval using clearInterval.

Function('return this')()

While this relatively looks safe (because the string isn't arbitrary), you will run into issues when using this piece of code in environments with very strict CSP rules. This includes mobile devices, browser extensions and some websites who lock down these things for security.

getQueue: function(){
  return queue;
},

I wouldn't want one to manipulate the queue outside if I were you. It could mess up your code. I suggest you return a copy of the queue, and not the queue array itself. Use slice to return a copy of the queue.

clear: function(){
  queue = [];
  return window.FnQueue;
},

A better way to clear an array without creating another array is to just set the length to zero.

If I understood the code correctly and following my suggestions, the following should be a simple replication:

;(function(ns){

  var queue = [];
  var isRunning = false;
  var runner = null;

  ns.add = function(fn){
    queue.push(fn);
    if(!isRunning) ns.resume();
    return ns;
  };

  ns.clear = function(){
    queue.length = 0;
    return ns;
  };

  ns.stop = function(){
    clearInterval(runner);
    runner = null;
    isRunning = false;
    return ns;
  };

  ns.resume = function(){
    if(!isRunning && !runner){
      isRunning = true;
      runner = setInterval(function(){
        // Here, I intentionally set the context to null. This makes the
        // callbacks have a `this` value of null, instead of `window`.
        queue.shift().call(null);
        if(!queue.length) ns.stop();
      }, 0);
    }
    return ns;
  };

  ns.getQueue = function(){
    return queue.slice(0);
  };

  ns.isRunning = function(){
    return isRunning;
  };

}(this.FnQueue = this.FnQueue || {}));

// Sample usage

alert('Let us start. This is your first alert in the stack');

FnQueue.add(function(){
  alert('First scheduled item');
});

alert('This should fire second, we are still in the stack');

FnQueue.add(function(){
  alert('Second scheduled item');
});

FnQueue.add(function(){
  alert('Third scheduled item');
});

FnQueue.add(function(){
  alert('Fourth scheduled item');
});

alert('After this alert, the stack is empty. All callbacks should fire in sequence');


Building a report of DNA sites and chunks

nbchunks = nbsites/nbsitesPerChunk
if nbchunks%1 != 0:
    print("\n\nThe number of sites per chunk for WCFst is not a divisor of the number of sites per locus.\nProcess is aborted!\n\n")
    sys.exit(1)
nbchunks = int(nbchunks)

This chunk of code is not good because:

nbchunks = nbsites / nbsitesPerChunk

In python-2 is already int for sure, in Python-3 you can write:

nbchunks = nbsites // nbsitesPerChunk

and it will be int for sure, so you can remove

nbchunks = int(nbchunks)

to avoid clutter.

The line:

if nbchunks%1 != 0

(minor) should be spaced like if nbchunks % 1 != 0
(SERIOUS) is always false as the remainder between a natural number and one is always zero!

Also the error message:

print("\n\nThe number of sites per chunk for WCFst is not a divisor of the number of sites per locus.\nProcess is aborted!\n\n")

is not connected to the if statement...

Exiting explicit like sys.exit(1) should be avoided, you should instead:

raise AdequateException(message)


First of all, a client-server relationship is kind of a 1:1 relation. That means that the client should probably have a connection to a server (or, if abstracted, a server) to talk with. Currently you are using a server parameter, but I would argue that this should be a field. This will also free one parameter of every method. Furthermore, currently it seems allowed to call just any server from the client class. First register and then call a totally different server.

Furthermore, if such a generic & relatively static parameter is present then it should probably be the first parameter. Currently the location of the server parameter seems to change per function, and that makes reading the functions harder.

The dispatchFollowEvent seems to be used to "follow a user", but that's only clear to me after reading the code. Similarly we have an upload method that seemingly uploads an image. Why not just followUser or uploadImage? It's a client, we expect it to "dispatch" and that it creates an "event" at the server.

I'm not sure why you would use a factory in above code. The makePacket code is really just an intermediate to the specific packets that you need anyway. So now you go: "packet specific method -> packet enum -> packet specific method". Sure you can do that, but why should you?

A more grievous thing is that your factory method seems to create partial packets without a payload. That means that packets are initially in an invalid state. The whole idea is that you manufacture concrete products inside a factory.

Another minor issue is the send part of the sendToServer method. A send method generally doesn't receive any data back. If you have a callback handler, why not call it call instead? You can leave the server part out of it maybe, that a client calls a server seems kind of logical.

Unfortunately I have to leave it at this, not just because it is late, but also because I don't think I've seen enough of your code / architecture to refactor the given code. It's not terrible code or anything, but it seems rather over-engineered and especially the naming suffers from it.


Please take a look at this library for inspiration on how to state machine could be defined:
https://projects.spring.io/spring-statemachine/

Should I change locking system to "fair"? => Could you please clarify what you are trying to achieve
Will it work smoothly with 2 threads? (There's no possibility that the start()/stop() can be accessed at the same time by more than 2 threads) => Yes. You have declared the only monitor object (lock) and configured corePoolSize = 1, maximumPoolSize = 1.
Does the code have any bugs I can't see? => I do not understand what is the purpose of this exercise
Any way to write it much simpler? => I think yes. Work is a singleton. the synchronized keyword could be used directly on Work's methods. And without clarification, it looks like that the whole solution could be replaced with ThreadPoolExecutor, cause it is not clear why do we need RUNNING, FINALIZING states.


Maybe it's a matter of preference, but IMO Exceptions shouldn't be used for validation errors (see:Don't Use Exceptions For Flow Control). First, it's not that exceptional and second, you should still handle user friendly response: re-display form with error messages (or error list only in case of ajax request). Insetad exception one-liner you should build (View)Model that gets messages from validator and (invalid) $_POST data.

Other Exceptions (league/country/insert) are ok. They're thrown when user have done something illegal (bypassed GUI). On the other hand it doesn't deserve any specified message then (serve debugging purpose only).

The thing that looks smelly is collaborating with league and country mappers. I wouldn't use them at all in this context. I would either handle it with db constraints (foreign keys) that would throw me db exception* or (if I wanted to decide details later) handle it within $this->teamMapper->insert() method.
If you intend to use ORM there are propably some sophisticated methods for such constraints too, but can't tell for sure - got allergy to ORM.

*) The downside of using key constraints only is relying on something that is hidden outside the sourcecode. Db schema might be messed up (during migration for example) and vulnerability might pass unnoticed. Unless you have full controll over your code it's better to make checks anyway (preferably using transactions).


The original code is fine IMO, but technically it's possible to flatten using a complete regexp

var isTagName = /^[A-Za-z]([A-Za-z0-9-]*[A-Za-z0-9])?$/

plus dubious/stinky value fallbacks and ES2015 arrow function:

  create: context => ({
    CallExpression: node => {
      if ((node.callee.object || {}).name !== 'by' ||
          (node.callee.property || {}).name !== 'tagName') {
        return
      }
      var tagName = ((node.arguments || [])[0] || {}).value
      if (tagName && !tagName.match(isTagName)) {
        context.report({
          node,
          message: `Invalid tag name: "${tagName}"`
        })
      }
    }
  })


Class definition
There is no need to explicitly inherit from object; that is a Python 2.x anachronism.
Instead of class Node(object):, simply write class Node:.
Similarly, class Queue(): can simply be class Queue:.
Default Parameters
Every Node should have a value; there is little reason to provide a default of 0 for the val parameter.  By forcing the caller to provide the value, you are less likely to accidentally have a node with the default integer 0 value when all the other nodes are created with (say) strings.
Unnecessary returns
There is no need for the return statements in preorder_print, postorder_print, and inorder_print.
Visitor pattern
You have defined several methods for traversing the tree.  All of them print the values.  If you wanted to do anything else with the values, you're stuck writing another (set of 4?) function.
Instead, you should separate the traversal from the operation.  Visit each node, in some order, and do something at that node.
class Node:

    ...

    def preorder(self, visitor):
        visitor(self.val)
        if self.left:
            self.left.preorder(visitor)
        if self.right:
            self.preorder(visitor)

    ...

# Do a pre-order traversal the tree, starting at the root, printing each values.
root.preorder(print)

Breadth First Traversal
First, the function should probably be called breadth_traversal_print, not bread_traversal_print.
Second, there is no need to use recursion during a breadth first traversal.  You have a Queue which keeps track of the nodes you need to visit.  You just need to loop while the queue is not empty.  The recursion is doing a loop in a resource-intensive fashion.  If Python had tail-call-optimization, the inefficiency could be removed automatically; but Python doesn't, so looping this way is wrong.
    def breadth_traversal_print(self):
        q = Queue()
        q.push(self)

        while q:
            node = q.pop()
            if node:
                if node.left:
                    q.push(node.left)
                if node.right:
                    q.push(node.right)
                print(node.val)

PEP-8
The PEP 8 -- Style Guide for Python enumerates many style guidelines all programs should follow.
White Space
There should be a space around binary operators, like =.  You violate this with q=Queue().  Note that = used with keyword arguments is not an operator, so doesn't shouldn't be surrounded by white space; therefore def __init__(self, val=0, left=None, right=None): is correct.
There should be a space after commas.  You violate this in def push(self,elt):
No-op code
This string ...
    """          1
            2       3
        4     5    6  7

    [1 2 4 5 3 6 7]

    """

... is a statement which does nothing, and has no side-effect.  Perhaps you meant this to be a comment?
NOTE: This is different from """docstrings""".  A string statement which immediately follows a class or def statement is treated as a docstring, removed from the program code, and stored in the __doc__ member of the class or function by the Python interpreter.  There, it can be extracted by help(...) and other documentation generation programs.


On a side note, is there a difference betwen "routing" and "URL rewriting"? The terminology isn't all that clear to me.

Yes. Generally, "routing" describes the process of mapping URLs to code in some form. The standard example would be mapping a URL to a method of a controller.

On the other hand, "rewriting" doesn't map a URL to code, but maps a URL to a different URL.

[But both terms are often not 100% clearly defined, and are sometimes used interchangably]

Security: DOS

If I visit your index.php directly, without giving any parameters, I get an infinite loop in getPageName.

You shouldn't need a while loop here, replacing the script path without the index.php file name in the request parameter should do the same thing.

Security: Directory Traversal

Your index.php file is likely open to directory traversal and LFI in Windows (I don't have a Windows machine to test right now, but using \ should work). With current PHP versions, it is restricted to PHP files, but it should probably still be fixed.

Correctness: URL encoding

Because you use REQUEST_URI, the values you get will be URL encoded. So if I visit /users/foo"bar, I would get Displaying user #foo%22bar. instead of the expected result. For the example this may be fine, but it will likely cause bugs in the future.

Do note though that the URL encoding is currently all that protects you from XSS (and that the encoding happens client-side, so you should not necessarily trust it).

Approach

If it's just about mapping /page/subpage to ?p=page&s=subpage, I would probably use Apache URL rewriting exclusively (I'm no expert, but it should certainly be possible).

If you want the URL routing functionality, I would probably go with a more extended approach, which lets me define a whitelist of allowed URLs, and maps them to a controller method.


You're essentially copying copy_if with some additional debug messages. One can rewrite your code with

std::copy_if(all_items.begin(), all_items.end(), std::back_inserter(filter_items),
             [&bad_ids](const mystruct& item)
{
     return std::find(bad_ids.begin(), bad_ids.end(), item.id) == bad_ids.end();
});

But that's not necessarily more efficient, because copy_if and remove_copy_if are usually implemented as

for(; first != last; ++first) {
    if(predicate(*first)){     // copy if; remove_copy_if would negate
        *result = *first;
        result++;
    }
}

A more efficient way would be a faster predicate, e.g. instead of find(bad_ids…) you could use

for(const auto & item : all_items) {
    if(item.id < 151 || 152 < item.id) {
        filtered_items.push_back(item);
    }
}

But that's not as flexible anymore. That being said, we're talking about a small code snippet. As always, you should measure the time your code needs. And in this case, the output by cout will most likely take the most time.

For now, use the variant that you understand best. Your code is fine, there's not much one can improve at that point without resorting to personal preference because it's too short.

By the way, I would call filter_items filtered_items instead, since it doesn't actually filter items. It is a std::vector of items that have been filtered.


Using the StringBuilder class will typically be better for looped string building.

string keys = "";
foreach (KeyValuePair<string, string> entry in core.errorLogger())
{
    keys += entry.Key + ":       " + entry.Value + "
";
}

turns into

StringBuilder keys = new StringBuilder();
foreach (KeyValuePair<string, string> entry in core.errorLogger())
{
    keys.AppendFormat("{0}:&nbsp;{1}
", entry.Key, entry.Value);
}

Then you take errorSpan.InnerHtml = (keys); and change it to errorSpan.InnerHtml = (keys.ToString());

Alternatively, you could use this to replace the dictionary as CharlesNRice suggests.

StringBuilder keys = new StringBuilder();

 public void errorLogger(string key, string err)
    {
        if(!String.IsNullOrEmpty(err))
        keys.AppendFormat("{0}:&nbsp;{1}
", key,err);
    }


This is a tricky problem to solve.  In the general case, the change-making-problem requires dynamic-programming to solve.  It is possible to write a simpler algorithm that works for $20 and $50 only, but yours is buggy:

This machine only dispense in $20 and $50 bills only
Enter in the amount to be withdraw :
30
remE : 10

(2) Number of $50 bills : -1
(2) Number of $20 bills : 4
(2) Number of bills dispensed is 3

Furthermore, if (remE >= 10 || remE >= 20 ) in the second solution looks wrong.

If I had to write a quick-and-dirty non-generalized solution for $50 and $20, I would write it this way:

#include <cassert>
#include <iostream>
#include <iomanip>

/**
 * Composes the given amount as a number of 50-dollar bills and 20-dollar
 * bills (as out-parameters).  Returns the total number of bills needed, or -1
 * if the amount cannot be formed.
 */
int split_50_20_bills(int amount, int *num_50, int *num_20) {
    if (amount < 0 || amount == 10 || amount == 30 || amount % 10) {
        return -1;
    } else {
        *num_50 = (amount % 20) ? ((amount - 50) / 100) * 2 + 1 :
                                  (amount / 100) * 2;
        *num_20 = (amount - 50 * *num_50) / 20;
        assert(amount == 50 * *num_50 + 20 * *num_20);
        return *num_50 + *num_20;
    }
}

int main()
{
    for (int amt = 0; amt <= 1000; amt += 10) {
        int num_50, num_20;
        int total = split_50_20_bills(amt, &num_50, &num_20);
        std::cout << std::setw(4) << amt;
        if (total < 0) {
            std::cout << " cannot be formed\n";
        } else {
            std::cout << " = " << std::setw(2) << num_50 << " x $50 + "
                               << std::setw(2) << num_20 << " x $20 ("
                               << std::setw(2) << total << " bills)\n";
        }
    }
}

Note that one function passes back four pieces of information:

Whether it's possible to form the amount
If so, how many bills it will take altogether
How many $50 bills
How many $20 bills


A few things:

Squares don't have width and height, those are rectangles
You check to see that your values are not strings, what if they are lists (or other types of objects)?
Your check functions error if their title is true, this is unintuitive. Something like ensure_value_is_positive would be a better name.


In Java, and in Code Review, the preference is for creating both highly readable, and highly efficient code.

It is an almost bizarre fact, that one leads to the other.

your code has one efficiency, and that is space-on-disk.... it is neither readable, nor high-performance.

System.out.println(new StringBuilder(new Integer(new Scanner(System.in).nextInt()).toString()).reverse().toString());

For a start, having to scroll off the page means you have to read with your mouse, not with your eyes.
Secondly, it is very hard to evaluate what parenthesis match when they are all clumped together.

Breaking your code down (which should not be necessary), we have:

int valinput = new Scanner(System.in).nextInt();
String stringinput = new Integer(valinput).toString();
String reversed = new StringBuilder(stringinput).reverse().toString();
System.out.println(reversed);

Now, you need error handling on the Scanner, and it needs to be closed as well. Without that, you have a program that is ugly when a user types in 123.0.

Since you have no error handling, you may as well just junk the lines with the Integer...

And, there is no reason to convert the StringBuilder to a String directly...

Without error handling, you can:

System.out.println(new StringBuilder().append(scanner.nextInt()).reverse());

That is, effectively equivalent to your code, but it has different error-condition characteristics..

Also, it is, suprisingly, quite readable, and fast.

Now, all you need is the try/catch for the scanner, and you are sorted.


Write strings to a file while downloading new one simultaneous

You have a lot of interesting things going on in your code. There are many ways to solve your problem, here is an approach utilizing an ActionBlock. I used .NET Core 3.1 to build the sample, but ActionBlock is available in the System.Threading.Tasks.Dataflow NuGet Package if it isn't included in your framework by default.

1) Change your entry point from static void Main(string[] args to static async Task Main(string[] args async main has been available since C#7.1 (https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-7-1). If you can't use C#7.1 or greater, you can still do it with something like DoAsyncWork().GetAwaiter().GetResult()

2) List is not guaranteed to be thread safe and I noticed you add to your list outside your lock. I elected to use a ConcurrentDictionary instead since that is guaranteed thread safe. I try to avoid my own locks whenever I can and in this case, if you get rid of the Console writes, you could dump your lock altogether.

3) I elected to use Interlocked.Increment(ref requestDid) instead of {requestDid++} and then read it with an Interlocked.Read. Interlocked operations are thread safe, so you would be okay to use these even if you removed lock (ConsoleLock) (although you are only using those variables to write to the Console anyway)

4) In an async/await world, Thread.Sleep is almost always wrong. You usually want to await Task.Delay instead. https://stackoverflow.com/questions/20082221/when-to-use-task-delay-when-to-use-thread-sleep

5) I didn't Dispose the httpclient or handler because of https://stackoverflow.com/questions/15705092/do-httpclient-and-httpclienthandler-have-to-be-disposed (although since the program is terminating anyway, it doesn't really matter in this case)

6) As far as the ActionBlock goes, there are a lot of articles out there on it, but here is an ok start https://docs.microsoft.com/en-us/dotnet/standard/parallel-programming/dataflow-task-parallel-library. Note how I set EnsureOrdered to false. If you don't need the items to be processed in order, I find it best to set it to false. In this case, since you are writing the file after you have retrieved ALL the results, you could simply sort the values coming out of the ConcurrentDictionary

I set SingleProducerConstrained to true, because in this case post is not being called concurrently. This allows the ActionBlock to make some optimizations. https://docs.microsoft.com/en-us/dotnet/api/system.threading.tasks.dataflow.executiondataflowblockoptions.singleproducerconstrained?view=netcore-3.1

MaxDegreesOfParallelism can be a tough choice. I sometimes cringe when I see a hardcode for that in real world applications because the optimal value for this will likely vary based on what hardware or virtualization platform you are running on. However, the optimal value can be hard to come by, especially when running a container. This is a great example of how nuanced the choice can be. https://github.com/dotnet/runtime/issues/622

7) Finally, I have found when testing performance like this, to make sure you do so WITHOUT a debugger attached. Attached debuggers can really slow things down. I built this code in release mode and then ran it from the command line.

using System;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Threading.Tasks.Dataflow;

namespace RequestTest
{
    static class Program
    {
        static async Task Main(string[] args)
        {
            var startTime = Stopwatch.GetTimestamp();
            //DECLARATION
            int start = 1000;
            int end = 2000;
            long requestDid = 0;
            var requestToDo = end - start;

            object ConsoleLock = new object();
            ConcurrentDictionary<string, string> jsonResponses = new ConcurrentDictionary<string, string>();
            var baseAddress = new Uri("https://localhost:5001/");
            var cookieContainer = new CookieContainer();
            cookieContainer.Add(baseAddress, new Cookie("JSESSIONID", "xxx"));
            var handler = new HttpClientHandler() { CookieContainer = cookieContainer };
            var client = new HttpClient(handler) { BaseAddress = baseAddress };
            var actionBlock = new ActionBlock<string>(async x =>
            {
                var response = await client.GetStringAsync(new Uri(baseAddress + x));
                jsonResponses.TryAdd(x, response); //note this actually returns a bool to indictate if it was added successfully, as long as x is unqiue, I can't imagine a scenario where this would return false
                lock (ConsoleLock)
                {
                    Console.SetCursorPosition(0, 0);
                    Interlocked.Increment(ref requestDid);
                    Console.Write($"Progress {Interlocked.Read(ref requestDid)}/{requestToDo}     ");
                }

            }, new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = 8, EnsureOrdered = false, SingleProducerConstrained = true });

            for (var counter = start; counter<end; counter++)
            {
                actionBlock.Post("api/test?requestid="+counter.ToString());
            }
            actionBlock.Complete();
            await actionBlock.Completion;
            var endRequestTime = Stopwatch.GetTimestamp();
            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine($"Executed Requests in {(endRequestTime - startTime)} ticks");
            Console.WriteLine("Writing to file");

            using (var streamWriter = new StreamWriter("C:\\temp\\sctest.txt"))
            {
                foreach (var sc in jsonResponses.Values)
                {
                    streamWriter.WriteLine(sc);
                }
            }

            var endFileTime = Stopwatch.GetTimestamp();
            Console.WriteLine($"Completed File write in {(endFileTime - endRequestTime)} ticks");
        }
    }
}

```


add_const or remove_const based on another type

I don't see any obvious omissions or bugs.

The naming and inner struct are neatly expressive (and remind me of some testing frameworks' precondition/assertion chaining).  It's not something that's done by the standard library, but I don't think it should be hugely controversial.

I might go with a naming like copy_const<foo>::from<bar> - or perhaps even the other way around: copy_const<bar>::to<foo>.  Or even both!  (Actually, I now wish std::is_assignable worked like that - it would be easier to remember which parameter is which!)

None of the above is a concrete suggestion - intended merely as food for thought!


Refactor multiple if-else conditions when condition is a minor change

This is a common problem. Sometimes it's tricky to generalise a process even when its iterative in nature.
By keeping track of both:

the location of the user's cursor (cursor_position), and
an iterable data structure storing which characters are shown (pinNumbers),

it is possible to implement this behaviour without so much repeated code. This gave the desired behaviour after some thorough testing (in my imagination).
public string PinCode { get; set; } = string.Empty;

private int cursor_position = -1;
private string[] pinNumbers = new string[] {"_", "_", "_", "_"};

    private async Task<bool> SelectedButton(Button button)
    {
        //If button is a number then
        if (button.Text != null)
        {
            if ( cursor_position < 3 )
            {
                PinCode = PinCode + button.Text;

                if ( cursor_position > 0 )
                {
                    pinNumbers[cursor_position] = "*";
                }

                cursor_position += 1;
                pinNumbers[cursor_position] = button.Text;
            }
        } else { // apparently backspace?
            if ( cursor_position >= 0 )
            {
                PinCode = PinCode.Remove(PinCode.Length - 1);
                pin_numbers[cursor_position] = "_";
                cursor_position -= 1;
            }
        }

        pinNumberOne   = pinNumbers[0]; // update actual shown values with array
        pinNumberTwo   = pinNumbers[1]; // you could probably take out the "pinNumberX" middleman
        pinNumberThree = pinNumbers[2]; // but I dont know what relation these variables have to
        pinNumberFour  = pinNumbers[3]; // the rest of your code

        return true;
    }

Depending on how you are assigning values to the actual rendered characters you may be able to remove the first four of the last five lines. You likely could just refer the rendered components directly to the values in the pinNumbers array.


Finding the most popular element with C# given O(1) space complexity requirement

You don't have \$O(1)\$ space complexity at the moment, OrderBy and OrderByDescending (used wrong as pointed out in the other answer(s)) will have a non-constant space complexity.

Since runtime is not the problem here, we can make this a space complexity of \$O(1)\$ pretty easily:

Tuple<int, int> GetItemWithMaxCount(int[] items)
{
    var maxCount = 0;
    var maxItem = 0;

    for (int i = 0; i < items.Length; i++)
    {
        var currentCount = 1;
        var currentItem = items[i];

        foreach (var item in items.Skip(i + 1))
        {
            if (item == currentItem)
            {
                currentCount++;
            }
        }

        if (currentCount > maxCount)
        {
            maxCount = currentCount;
            maxItem = currentItem;
        }
        else if (currentCount == maxCount)
        {
            if (currentItem < maxItem)
            {
                maxItem = currentItem;
            }
        }
    }

    return new Tuple<int, int>(maxItem, maxCount);
}

Return an actual class if you like.

The downside of this? Time complexity is \$O(n^2)\$ (I think), but it's guaranteed to use constant space. We also cannot build a lookup of previous iterations, as that would use more than constant space.

Essentially, we just loop through all the items n times, then loop from that item on. This is a trick to help us prevent iterating the same item multiple times. We know that each index can only have a specific value in it so we can skip the that value (and all previous ones) in the inner loop.

There's no complex LINQ here, no additional arrays, no sorting. Just go through them all and add them up then compare to the current max. The .Skip(i + 1) method is part of LINQ, but you can get around that pretty easily by changing that iteration up (swap the foreach out):

for (int j = i + 1; j < items.Length; j++)
{
    if (items[j] == currentItem)
    {
        currentCount++;
    }
}

This can be ordered, unordered, whatever. It meets all your criteria: return item with most counts and count or lowest value item with most counts and count if a tie.

This solution is similar (has the same general effect) to the solution presented in this answer by Peter Taylor, but the key advantage here is that we can optimize it for our requirements. We've already made one optimization: skilling the first i elements. Just as well, that answer will not use constant space because of Select, which appears to use a significant amount of space.

As an example, you can increase speed (slightly) by skipping duplicates as we can with our constant space requirement:

for (int i = 0; i < items.Length; i++)
{
    var currentCount = 1;
    var currentItem = items[i];

    if (currentItem == maxItem)
    {
        continue;
    }

    foreach (var item in items.Skip(i + 1))

Basically, that if will mean that if we are iterating a value again (mind you, it can change, so we can still check the same value twice, but if it's the current max we'll skip it to maintain our space complexity) we can skip it for the moment.

If you read about LINQ-to-objects (which is what we're using) it uses a Stable Quicksort to do it's sorting.

One thing we know about quicksort is that worst-case space complexity is \$O(n)\$ for a naive implementation, and \$O(log(n))\$ for an optimized implementation.

This means that any solution presented that uses LINQ to order the elements is going to use \$O(log(n))\$ space complexity.

And of course, I have to prove that this uses \$O(1)\$ space (or, at least, less space than the OP) so I ran BenchmarkDotNet against my code and OP code:

            Method |            Mean |      StdDev |   Gen 0 | Allocated |
------------------ |---------------- |------------ |-------- |---------- |
      OriginalCode |   1,718.1155 us |   7.6080 us |       - | 327.31 kB |
      EBrownAnswer |  28,547.8824 us |  48.4272 us |       - |     512 B |

Mine took 130 times as long (expected) but ran in 0.15% of the space. So, how do the other answers stack up?

Well, once we put all the answers together (the one by Peter Taylor doesn't return the correct object, but let's just try that one out as well anyway) we get the following:

            Method |            Mean |      StdDev |   Gen 0 | Allocated |
------------------ |---------------- |------------ |-------- |---------- |
      OriginalCode |   1,718.1155 us |   7.6080 us |       - | 327.31 kB |
      EBrownAnswer |  28,547.8824 us |  48.4272 us |       - |     512 B |
  RubberDuckAnswer |   1,183.3647 us |   3.5244 us | 20.3125 | 302.64 kB |
 PeterTaylorAnswer | 255,862.3770 us | 201.6448 us |       - | 760.33 kB |
   HeslacherAnswer |      62.5081 us |   0.3105 us |       - |   8.23 kB |
   PaparazziAnswer |     882.7228 us |   2.9597 us |       - | 157.98 kB |

So there we have it. Looks like the only version that actually had \$O(1)\$ space complexity was the version I posted here. If you can relax that requirement slightly then the version Heslacher posted is the most superior version to use.

If you want a truly optimal solution based off of both metrics of each method (we'll define best as the lowest of time * memoryInBytes), we have the following:

           Method |          Weighted Result |
----------------- |------------------------- |
     OriginalCode |     575,852,937.5283 usB |
     EBrownAnswer |      14,616,515.7888 usB |
 RubberDuckAnswer |     366,728,696.6354 usB |
PeterTaylorAnswer | 199,208,797,290.9158 usB |
  HeslacherAnswer |         526,728.4275 usB |
   PaparazziAnswer|     142,799,409.0947 usB |

The answer posted by Heslacher comes in first, again.

Do note, however, that method is not without it's flaws. As the range between integers grows bigger, the method uses more space. If we're using unbounded int ranges, Heslacher's answer will not work at all. (It will crash on negatives and on extremely large ranges.)

Do note: list generation is not measured for each of these methods and is defined as:

const int _integerCount = 10000;

private static int[] GetItems()
{
    var list = new int[_integerCount];
    var rand = new Random(0);

    for (int i = 0; i < _integerCount; i++)
    {
        list[i] = rand.Next(0, 2048);
    }

    return list;
}

So, if we adjust our integer range to fall within 0 and short.MaxValue (32767), we get the following results:

          Method |           Mean |     StdDev |   Gen 0 |   Gen 1 |   Gen 2 | Allocated |     Result Weighted |
---------------- |--------------- |----------- |-------- |-------- |-------- |---------- |-------------------- |
    EBrownAnswer | 28,408.5030 us | 34.7946 us |       - |       - |       - |     512 B | 14,545,153.5360 usB |
 HeslacherAnswer |    119.7295 us |  0.4404 us | 36.8164 | 36.8164 | 36.8164 | 131.42 kB | 16,112,487.3114 usB |

As this shows, our fastest answer is not always the best. For large ranges of integers (or anything above ~500m, or any values below 0) that solution will fail, sadly. :(

And believe it or not, for small, highly-variable data-sets this algorithm is the fastest (number count = 100, vary from 0 to short.MaxValue):

            Method |       Mean |    StdDev | Scaled | Scaled-StdDev |   Gen 0 |   Gen 1 |   Gen 2 | Allocated |
------------------ |----------- |---------- |------- |-------------- |-------- |-------- |-------- |---------- |
      OriginalCode | 39.0327 us | 0.1790 us |   1.00 |          0.00 |  0.5615 |       - |       - |   9.91 kB |
      EBrownAnswer |  4.6140 us | 0.3984 us |   0.12 |          0.01 |       - |       - |       - |      16 B |
  RubberDuckAnswer | 25.2577 us | 0.0717 us |   0.65 |          0.00 |  0.3499 |       - |       - |   8.39 kB |
 PeterTaylorAnswer | 34.0133 us | 0.1991 us |   0.87 |          0.01 |  0.0651 |       - |       - |   7.76 kB |
   HeslacherAnswer | 30.2370 us | 0.0269 us |   0.77 |          0.00 | 40.3239 | 40.3239 | 40.3239 | 131.42 kB |
   PaparazziAnswer | 17.5162 us | 0.0507 us |   0.45 |          0.00 |  0.5412 |       - |       - |   6.09 kB |


Conditionally replacing an input field when submitting a form

You mention the changes in scope as though they're a problem. But you actually want them here, since that's how jQuery operates, and using => would be counterproductive. Anyway here are some notes

CoffeeScript has a do keyword for IIFEs. So do -> ... is equivalent to (-> ...)() without the need for all those parentheses
It seems your IIFE isn't returning something you'll need later; it's just encapsulating some code. In that case, don't bother giving it a name. Just invoke it.
You don't need to cache $form - you only use it once
Don't call the UL id $ulId - that is, don't use a $ in the name. It's not a jQuery object, it's just a string
You can use a switch statement instead of the if... else, which helps a bit (but read on for a better solution)

Here's the code with these tweaks:

do ->
  $('form.simple_form').submit ->
    $(this).find('.fake-input').each ->   # don't bother caching $form
      $fakeInput = $ this
      return unless $fakeInput.children().length is 1 # return early instead of a big if-block

      $fakeInput.empty()

      switch $fakeInput.closest('ul').attr('id')
        when 'primary_diagnosis_select'
          $fakeInput.append emptyListArrayHTML('primary_icd9_codes')
        when 'secondary_diagnosis_select'
          $fakeInput.append emptyListArrayHTML('secondary_icd9_codes')
        else
          $fakeInput.append emptyListArrayHTML('med_names')

However, I'd make the relationships explicit in the markup. For instance, give the UL element a data-codes attribute or something:

...

...

Then you can shorten the code like so:

do ->
  $('form.simple_form').submit ->
    $(this).find('.fake-input').each ->
      $fakeInput = $ this
      return unless $fakeInput.children().length is 1
      $fakeInput.empty()
      codes = $fakeInput.closest('ul').data("codes") or "med_names"
      $fakeInput.append emptyListArrayHTML(codes)

Now the CoffeeScript handles only logic while the data and relationships are declared in the markup. You can add the single line from emptyListArrayHTML back into the function with complicating things too much, though.

p.s. CoffeeScript also has a triple-quote Python-like heredoc syntax, if you want to use double quotes in a string without escaping them. So your emptyListArrayHTML function could be written as

emptyListArrayHTML = (list_type) ->
  """<input type="text" name="#{nameWithListType list_type}" value="">"""

It looks a little strange at first (and the syntax highlighting is messed up here), but I like to use it, because I prefer to always use double quotes for HTML attributes (just personal preference).


public class CSMRReducer extends Reducer<IntWritable, DocumentWritable ,Text,
        VectorArrayWritable> {

    private ArrayList<DocumentWritable> al;
    private VectorWritable[] val;
    private VectorArrayWritable vaw;

    @Override
    public void reduce(IntWritable key, Iterable<DocumentWritable> values,
            Context context) throws IOException, InterruptedException{
        al = new ArrayList();
        vaw = new VectorArrayWritable();

        /* Storing each key-value pair (document) in a java.util.ArrayList */
        for (DocumentWritable v : values){
            al.add(new DocumentWritable(v.getKey(),v.getValue()));
        }

        /* Generating all the possible combinations of documents */
        if (al.size()>0){
            for (int i=0;i<al.size();++i){
                for (int j=i+1;j<al.size();++j){
                    val = new VectorWritable[2];

                    /* Generating the key for the current document pair with
                        the format "doci_name@docj_name" */
                    String k = al.get(i).getKey().toString()+
                            "@"+al.get(j).getKey().toString();

                    //First Document (doci)
                    val[0] = new VectorWritable(al.get(i).getValue().get());
                    //Second Document (docj)
                    val[1] = new VectorWritable(al.get(j).getValue().get());
                    vaw.set(val);

                    context.write(new Text(k), vaw);
                }
            }
        }
    }

}

You can remove the fields and just declare the variables in the function. There's no need for class variables here.

You can also remove the al.size()>0 check, because that's automatically checked by the for loop.

On the performance end, you could prepare al.get(i) and al.get(i).getKey().toString()+"@" before going into the j loop.


You don't need an exhaustive search: \$2*3*5*7*11*13*17*19*23*29 = 6469693230 > 2^{32}\$, so it is safe to allocate 9 slots.

primeExponents does too much and shall be split into three functions, one to factorize a number, another to validate factorization, and yet another to print it.

The factorization logic is extremely hard to follow. Consider instead

void factorize(int num, factors_t * factors, int * primes)
{
  for (; num > 1; ++primes) {
    factors->prime = *primes;
    factors.exponent = 0;

    while (num % *primes == 0) {
      factors->exponent++;
      num /= **primes; // Edit: shame on me.
    }

    if (factors->exponent > 0) {
      factors++;
    }
  }
}


I don't think there is any other way to solve it. By using the  SelectedIndexChanged event and initializing a TabPage you do it just the way it should/can be done.

You may however consider renaming the interface to IInitializable and the method to Initialize which more clearly describes what you are doing. You don't create any tabs, you initialize them so name the interface and the method accordingly.

Internally you can use a boolean field _isInitialized so that the Initialize method checks it and doesn't initialize your tab-page multiple times. Then you just do:

private void OnSelectedIndexChanged(object sender, EventArgs e)
{
    var initializableTabPage = (sender as TabControl).SelectedTab as IInitializable;

    // In case you have other tab-pages.
    if (initializableTabPage != null)
    {
        initializableTabPage.Initialize();
    }
}

and the tap-page with its interface:

interface IInitializable
{
    void Initialize();
}

class MyTabPage : TabPage, IInitializable
{
    private bool _isInitialized;

    public void Initialize()
    {
        if (_isInitialized) { return ; }

        ...initialize

        _isInitialized = true;
    }
}

  I find it hard to believe that TabPage does not know when it's selected.
  It looks like it really doesn't:
  TabPage Class Events

You could experimet with GotFocus but it can be tricky. I wouldn't


Wow, that is slow! Those array concatenations will completely kill performance. The canonical solution is to make a dictionary of each possible combination of y=z/2 values, then check every combination of z-y values against the dictionary. This has complexity of (K choose (z+1)/2)).


Javascript Minesweeper (with Stack Snippets!)

thisButton.attr('data-x')

You can use jQuery's .data(). It uses an internal cache for storing key-value pairs, but if it doesn't find it there, it looks up the data-* attributes of the associated element. This means you can do thisButton.data('x'). Note that dash-space becomes camelCase.

Number(thisButton.attr('data-x'))

If you use jQuery's .data(), it automatically converts the type for you. If it finds "2", then it converts it to a number.

Also, you can use the unary + to convert strings to numbers. It's close to parseFloat(). Something like:

+"2" === 2

  Is it a good idea to use data-* attributes to store the data?

For a regular audience, maybe. For advanced users, you might want to do something else (unless they're just bored and want to play :P)

Use jQuery .data(). The data is stored in an internal cache rather than written as a data-* attribute. However, if you have reference to the element and call .data() against it, it could reveal the value. Also, afaik, the cache is accessible via jQuery._cache.
Use an internal mapping, and have the buttons only carry an index/coordinates. You can create a 2x2 array inside a closure which only your code can access. On click, you can announce the coordinates freely.

Also, any determined dev/skid can peek through using dev tools, so the best you can do is just make it harder to pick on.

  Am I using the features of JQuery in a good way?

Nothing wrong with it :D


all of your functions seem to do the same thing with a different message, so why not condense them and take the message as a parameter?

def get_num(msg):
    num = None
    while num is None:
        try:
            num = float(raw_input(msg))
        except ValueError:
            print("Use a number, silly!")

    return num

and then

def output():
    x = get_num('Please give your weight (pounds): ')
    y = get_num('what is your current body fat percentage? (>1): ')
    z = get_num('What is your desired body fat percentage? (>1): ')
    A = (x*(y/100-z/100))/(1-z/100)
    B = x - A
    print("Your necessary weight loss is %.1f pounds, and \
your final weight will be %.1f pounds" % (A,B))
    more()

in your more function you can condense your ifs with the in operator

def more():
    again = raw_input("Calculate again? ")

    if again.lower() in ["yes", "y", "sure" , "ok", "", "okay"]:
        output()
    elif again.lower() in ["no", "n", "nah", "nope"]:
        end()
    else:
        more()


Do you need to iterate?

There is a lot of room for improvement..

Use one loop if possible.

You have many loops where you iterate the same number of times. Rather than doing each loop in turn do as much as possible in one loop.

Eg.

while (!(9 * slots >= n)) {
  slots += 1;
}
while (slotsArray.length != slots) {
  slotsArray.push(9);
}

Can be done in one

// Note new solution does not require extra item
while (!(9 * slots >= n)) {
    slots += 1;
    slotsArray.push(9);
}

Simple conditions

Make the condition statement as simple as possible. You had !(9*slots >= n) the additional not clause is extra work (if not optimised) 9*slots < n is the same

Use variables

Some javascript engines (V8) are not as quick handling literal numbers. eg x *= 10 is slower than x *= ten but you must take into account the declaration and assignment of the variable. If you use the number once or twice there is no advantage, but if you do it many time there is.

Math rather than Loops

Alway check to see if there is a way to directly calculate the result rather than use iteration.

You do not actually need any loops

Use memory

Memory is cheap and fast, CPU cycles are not. So rather than iterate have a predefined object that can be used to create a result

You have

  while (finalOutput[1].length != n) {
    finalOutput[1] += '1';
  }

but the following is quicker (note it should be defined outside the function but in this case you may only have the function's scope)

  // long enough for all possible results?
  var ones = "111111111111111111111111111111111111111111111111111111111";
  finalOutput[1] = ones.substr(0,n);

There are many other optimisations that I have not included as the resulting optimised code is very simple and most of what you had is not needed.

Testing

To ensure I got it correct I wrote a test that compares your function to the new one. Making sure the results are the same, then running each version 100,000 times to get the performance.

There results are

// calls to function oneTwoThree Ori is the original and New is the optimised version
// time in ms (1/1000);

-- Test value : (19) -------------------
Ori : 191.53ms Mean : 0.00192
New : 22.38ms Mean : 0.00022
-- Test value : (1) -------------------
Ori : 8.78ms Mean : 0.00009
New : 6.61ms Mean : 0.00007
-- Test value : (7) -------------------
Ori : 62.03ms Mean : 0.00062
New : 6.02ms Mean : 0.00006
-- Test value : (36) -------------------
Ori : 208.12ms Mean : 0.00208
New : 18.57ms Mean : 0.00019
-- Test value : (0) -------------------
Ori : 8.47ms Mean : 0.00008
New : 4.00ms Mean : 0.00004

For the results of n < 10 the improvement is not that great but near 25%-50% is worth the effort. The improvement for n >= 10 are well worth the effort.

The new code

No loops needed. Warning longStr1s may need to be larger as I have not tested all possible inputs.

function oneTwoThree_Q(n) {
    var nine = 9; // variable = 9 is quicker than litteral value
    var slots;
    var longStr1s = "11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111";
    var longStr9s = "999999999999999999999999999999999999999999999999999999999";
    if (n < 10) {
        return ['' + n, n === 0 ? '' + n : longStr1s.substr(0,n)];
    }
    slots = Math.ceil(n / nine);
    nine += n - slots * 9;
    return [longStr9s.substr(0,slots-1) + nine, longStr1s.substr(0,n)];
}


High Level Notes

My most substantial suggestion is to avoid mixing data logic and view code.  Transform your data, as pure data, into the form you would like it to be so that your view code can treat it uniformly.  Then your view will be more like a "dumb" mail-merge template, even if you decide to keep using jquery to build it up programmatically.  A rewrite should clarify what I mean:

This will take each event that the ajax returns and transform it into data for both of the row cells:

function eventToRowData(event) {
    var nullCell = {"Name": '', "Sport":null, "Events": null},
        isRun = event.Sport == 'Run';
    return {
        "Date": event.Date,
        "RunCell": isRun ? event : nullCell,
        "SwimCell": isRun ? nullCell : event
    };
}

Now all the if...else logic vanishes from your view code:

function buildTable(data) {
    var rowData = data.map(eventToRowData),
        tableBody = document.createElement("tbody");

    rowData.forEach(makeRow);
    $("#my_events").append(tableBody);

    function makeRow(rowDatum) {
        var row = tableBody.insertRow();
        row.insertCell().appendChild(document.createTextNode(rowDatum.Date));
        addEventCell(rowDatum.RunCell);
        addEventCell(rowDatum.SwimCell);

        function addEventCell(cellData) {
            var cell = row.insertCell();
            cell.className = cellData.Sport ? 'Event' : '';
            cell.Events = cellData.Events;
            cell.appendChild(document.createTextNode(cellData.Name));
        }
    }
}

See below for full working snippet.

Other Notes

To mitigate nesting, avoid defining things like success callbacks inline, unless they are so short they can fit on a single line.  This will make both the callback itself and whatever is calling it (in your case, an ajax options object) more readable.
Table row striping and hover highlighting belong in css.  As a rule, most view things that can be done in css should.
Consider ditching jquery.  The only good reason to have it in this code is simplifying your ajax call.  You could use zepto instead, or do it raw, and save some KB. See this link for more.
Consider using a light template library to clean up the view code which builds the table.
Consider using mithril.js (an extremely light library with the same philosophy as React) if this becomes more complex, or if you are interested in taking the separation of data view even further.
I didn't fix all the trivial things like naming conventions.  js is camelCase, css is dash-case by convention.
Finally, this may not be relevant, since I get the sense you are just doing this to learn, but unless you have more complex, interactive features, I think server side code rendering a static site is more appropriate for this use case.

var sampleData = [{
    "Date": "MM/DD/YYYY",
    "Name": "Some Event",
    "Sport": "Run",
    "Events": [1, 2]
}, {
    "Date": "MM/DD/YYYY",
    "Name": "Some Other Event",
    "Sport": "Swim",
    "Events": [1, 2]
}, {
    "Date": "MM/DD/YYYY",
    "Name": "Another Event",
    "Sport": "Swim",
    "Events": [1, 2]
}, ]

// Rather than work with data in an inconvenient format, change
// it to a format that suits our view code.
function eventToRowData(event) {
    var nullCell = {"Name": '', "Sport":null, "Events": null},
        isRun = event.Sport == 'Run';
    return {
        "Date": event.Date,
        "RunCell": isRun ? event : nullCell,
        "SwimCell": isRun ? nullCell : event
    };
}

function buildTable(data) {
    var rowData = data.map(eventToRowData),
     tableBody = document.createElement("tbody");

    rowData.forEach(makeRow);
    $("#my_events").append(tableBody);

    function makeRow(rowDatum) {
        var row = tableBody.insertRow();
        row.insertCell().appendChild(document.createTextNode(rowDatum.Date));
        addEventCell(rowDatum.RunCell);
        addEventCell(rowDatum.SwimCell);

        function addEventCell(cellData) {
         var cell = row.insertCell();
         cell.className = cellData.Sport ? 'Event' : '';
            cell.Events = cellData.Events;
            cell.appendChild(document.createTextNode(cellData.Name));
     }
    }
}

$(document).ready(buildTable(sampleData))
table, th, td {
    border: 1px solid black;
}
td {
    text-align: center;
    vertical-align: middle;
    padding: 5px;
}
#my_events tbody tr:nth-child(even) {
   background-color: #ccc;
}
td.Event:hover { background: lime }

            Date
            Run
            Swim


Naming:

λ is not a standard Python function name ([a-z] followed by [a-z0-9_]+) and will require figuring out some magic sequence in non-Greek keyboard layouts.
s0, s1, s2, lead and cd should be renamed to be more intuitive. For example, based on your documentation s1 could be named something like assignments.

General:

Rather than adding strings and newlines together I'd use format() and join(). It's easier to follow the construction of the string that way.
I would not recommend using this in production code. Treating strings as code is going to result in many more runtime errors which will be harder to debug than the corresponding named function.
λ does not accept functions without parameters - λ('print("value")')() for example results in IndexError.
Code construction and execution should be split up for easier debugging. I should be able to run construct_code(my_code_string) and see what would be executed for debugging.
I don't have the time to test this myself, but you should be able to get rid of the global rtrn by constructing an actual function and running that instead of creating global code.


Probably not the right forum.

In java f(x) the method f will never change the variable x to another value; it cannot be make it null or true or whatever. (A rule to prevent a category of errors.)

So you want a result:

public static class Decision {
    String destination;
    boolean conditionFound;
}

As in java null's should in normal code not be valid, I did not test them.
A test however would not need:

if (null != decisionTree) { // Typical C style.

but can be

if (decisionTree != null) {

As the following is not legal java:

if (decisionTree = null) { // *** Illegal java. // Run-time error in C (assignment).

Searching the code entry result results in an Optional<Decision>.

public static Optional<Decision> doAction(List<Map<String, String>> decisionTree,
            String code) {
    decisionTree.stream()
        .findAny(decisionMap -> code.equalsIgnoreCase(decisionMap.get("code")))
        .map(decisionMap -> {
            Decision decision = new Decision();

            String success = decisionMap.get("is_success");
            String action = decisionMap.get("action");
            BiPredicate<String, String> isApplicable = (s, a) ->
                    "N".equalsIgnoreCase(s) && "Z".equalsIgnoreCase(a);

            if (isApplicable.test(success, action)) {
                decision.destination = decisionMap.get("destination");
                decision.conditionFound = true;
            }
            return decision
        });
}

Optional<Decision> optionalDecision = doAction(decisionTree, code);
optionalDecision.ifPresent(decision -> {
    if (decision.conditionFound) {
        System.out.println(destination);
    }
});

A BiPredicate is not really needed, but not bad.

Instead of a result object, one could also pass an in-out parameter:

public static class DecisionParameter {
    boolean decisionFound;
    StringBuilder destination;
    boolean conditionFound;
}


Determine whether an integer is a palindrome

Your second solution is awfully complicated for something simple.

You start out alright.  No negative number can be a palindrome, so we can discount those. However, 0 is always a palindrome, so you're discounting that while you shouldn't.

You do a lot of complicated math and use an array. You could use either, but shouldn't use both. There are a couple of mathematical approaches to solve this, but you should be able to use those without iterating over the individual numbers or splitting it up at all. The most obvious solution however, is using an array and direct comparisons, without any math.

Say we got 1221. Split it up. [1, 2, 2, 1]. Iterate over the array, comparing every nth character to the last-nth character. 0th to 3rd. 1st to 2nd.

Say we got 92429. Split it up. [9, 2, 4, 2, 9]. Ignore the middle character. Handle the rest like it's an even-length number.

Based on those 2 cases, you should be able to figure out a much simpler algorithm.

Note: This answers the explicit question. Implicitly, you should wonder whether arrays should be allowed for this challenge. After all, iterating over a string or an array, it's not that different. I strongly suspect they want you to use the math-only approach.

Another approach, which is somewhat math-based and you should beware of overflows, is simply reversing the number.
In pseudo-code, that would look something like this:

reverse = 0
while (number != 0) {
  reverse = reverse * 10 + number % 10;
  number /= 10;
}

Check the input versus its reversed number. If they are the same, it's a palindrome.

But this still uses extra memory to hold the additional integer we just created.

Can it be done without? Absolutely. But I'll leave that as an exercise for you.