This is fairly tight; I don't think there's much more performance to pull out without dropping into C. That said:
possible_directions
First, I would rename this to neighbors or successors; it's not really about direction but about the nodes in the graph that come next or are adjacent to your current node.
Second, you can reduce the number of branches and arithmetic operations a little:
for xx in range(max(0, x - 1), min(x + 1, len(grid)):
    for yy in range(max(0, y - 1), min(y + 1, len(grid[x])):
        if xx == x and yy = y: continue
        yield xx, yy

Third, you can prevent many no-op calls of dfs by doing your seen check in this function rather than in the dfs base case. That is, pass seen to this function and modify your yield line to something like
if (xx, yy) not in seen: yield xx, yy

dfs
You compute word + grid[x][y] many times (once + once per neighbor). You should memoize this before yielding it (Python may already perform this optimization for you but I doubt it).
I don't think a set of tuples is the best implementation for seen.  You can't really avoid the copy of seen that I can see, and the lookups are not as fast as they could be. You already implicitly require that every row is the same length (0 <= y + yy < len(grid[x]), not 0 <= y + yy < len(grid[x + xx])) and that seems like a sensible restriction in any case. I suggest a bit array of some sort (e.g. bitarray, which I've never used but seems to fit the bill), which will allow fast setting, checking, and copying of seen (instead of seen[x][y], check and set seen[y * len(grid) + x]).
Best practice here would probably be to have a wrapper function that does not take a seen or word argument, but initializes them for a call to your recursive helper, something like
def dfs(x, y):
    return dfs_recursive(x, y, set(), '')


The many approaches in main and firstNumberFrom can be unified:

main = print . fibonacci' . maybe 10 read . listToMaybe =<< getArgs

The explicit recursion in fibbonacci' is captured by iterate:

fibbonacci' n = fst $ iterate (\(a,b) -> (b, a+b)) (0,1) !! n


Prime factoring function using recursion

+1 for stopping your isPrime search at the SqRt(n). That's a nice little optimization.
+1 for incrementing by 2. It's nice to see you realized that since it wasn't possibly even by this point, that you could optimize.
Next, consider a sieve or memento implementation for further performance improvements on isPrime.
Consider renaming root to limit.
+1 for extracting an isEven method.
-1 for neglecting to use it in your isPrime method.
Instead of having prfact and factor, Rename prfact to factor, overloading the latter. Make it private scoped to hide the implementation details from the outside world.

Sorry for the mostly non-algo review. Not my strong suit & short on time.


identifying pairwise groups from dictionary

Indentation

You should use four (4) spaces for indentation, not eight (8).

Logic

This

if len(list1) == 0:
    pass
else:

should be changed to

if list:
    ... code here ...

This removes the need for the else, as you instead check if the list contains anything. Check out the Python Docs on Truth Testing.

Enumerate

This

for mainkey in masterdict:
    if len(masterdict[mainkey]) > 1:
        for i in range(len(masterdict[mainkey])):
            p1 = masterdict[mainkey][i]
            recursive_finder(p1,masterdict[mainkey][i+1:],masterdict,[mainkey,p1],ans)

can be changed to this

for mainkey in masterdict:
    if len(masterdict[mainkey]) > 1:
        for i, value in enumerate(masterdict[mainkey]):
            p1 = value
            recursive_finder(p1,masterdict[mainkey][i+1:],masterdict,[mainkey,p1],ans)

Use enumerate since you are using both the index and the value.


Prologue

  I have a DateTime class (my own, not System.DateTime)

You could have just pasted the code for that class. Since you are asking a question about sorting, and your DateTime class implements IComparable, its content could have been pivotal for a proper review.

Parodos

  Here is a method that takes a List<DateTime> and sorts it:

You have just told us your class implements IComparable, but you don't show us how you'd use its functionality. I would have expected to to see dateTimes[i].CompareTo(dateTimes[j]) but instead we get dateTimes[i] < dateTimes[j]. This means you have created an operator overload on < and are not sharing this crucial code with us.

Furthermore, why would you roll out your own sorting algorithm if built-in functionality is available? As suggested in the comments by VisualMelon, you could just call dateTimes.Sort();

Exodus

  I believe using foreach loops instead of for is suitable here, but having the following variable names drives me crazy

To get things even more confusing, you ask about a syntactic change to the algorithm rather than going about how to properly sort or how to correctly implement IComparable.

Finishing off, in the for (dateTime1 in dateTimes) approach, you cannot change dateTimes[i] = dateTimes[j]; as it will throw System.InvalidOperationException: Collection was modified; enumeration operation may not execute. rendering your suggested approach unusable.

Cliffhanger

As a challenge, I let you search how to prevent this exception.


Parse output of Google Cloud command into PHP associative array

This code is complicated, and likely buggy.

If a line does not end in a space character, then the last word on that line will be ignored.
The output of gcloud compute instances list is a table.  For example:

NAME                                             ZONE          MACHINE_TYPE   PREEMPTIBLE  INTERNAL_IP  EXTERNAL_IP     STATUS
gke-cluster-asia-eas-default-pool-dc8f484c-knbs  asia-east1-a  n1-standard-1               10.140.0.2   104.155.227.25  RUNNING
gke-cluster-asia-eas-default-pool-dc8f484c-x8cv  asia-east1-a  n1-standard-1               10.140.0.3   104.199.226.16  RUNNING
gke-cluster-asia-eas-default-pool-dc8f484c-z5wv  asia-east1-a  n1-standard-1               10.140.0.4   104.199.134.9   RUNNING

If the table contains an empty value (such as for the "PREEMPTIBLE" column above), then the turn_linux_row_to_array() function will ignore it, resulting in a mismatch between the headers and the values.

I don't recommend trying to improve this code.  Instead, noting that all Google Cloud commands accept a --format option, you should choose a format that is easy to parse.  I would recommend replacing the entire code with:

$servers = json_decode(shell_exec('gcloud compute instances list --format=json'), true);

… to take advantage of json_decode().  That's it — you're done!


2 suggestions..

Condense all that duplicated code.
Don't concat your strings like that. Every time you do that that string has to be re-loaded into memory all over again. It's more efficient to put your string pieces into an array and then join them later.

completeAdress: computed({
    let address = [];
    const address_components = ['title', 'number', 'street', 'city', 'region', 'state', 'country', 'zipcode', 'phone'];
    for(var i=0; i<address_components.length; i++)
        if (get(this, address_components[i]))
            address.push(get(this, address_components[i]).toString());
    address = address.join(',');
    if (address.length)
        address = address.substring(1, address.length);
    return address;
}),

(For some reason the markdown parser didn't want to format this as code unless i also formatted it as a quote.)


I re-wrote your solution to use more typical Clojure features.  When you are looping over data and need to keep track of accumulated state, it is hard to beat loop/recur.  A first example:
(ns tst.demo.core
  (:use clojure.test))

(defn breaking-records
  [scores]
  ; this loop has 5 variables. Init all of them
  (loop [low         (first scores)
         high        (first scores)
         nworse      0
         nbetter     0
         score-pairs (partition 2 1 scores)]
    (if (empty? score-pairs)
      {:nbetter nbetter :nworse nworse}
      (let [curr-score-pair (first score-pairs)
            new-score       (second curr-score-pair)]
        ; start the next iteration with modified versions of the 5 loop vars
        (recur
          (min new-score low)
          (max new-score high)
          (if (< new-score low)
            (inc nworse)
            nworse)
          (if (< high new-score)
            (inc nbetter)
            nbetter)
          (rest score-pairs))))))

and unit tests:
(deftest test-records
  (testing "edge cases"
    (is (= (breaking-records []) {:nbetter 0 :nworse 0}) "no games played yet")
    (is (= (breaking-records [5]) {:nbetter 0 :nworse 0}) "single game"))
  (testing "hackerrank examples"
    (is (= (breaking-records [10 5 20 20 4 5 2 25 1]) {:nbetter 2 :nworse 4}))
    (is (= (breaking-records [3 4 21 36 10 28 35 5 24 42]) {:nbetter 4 :nworse 0}))))

; ***** NOTE: it's much easier to use vectors like [1 2 3] instead of a quoted list `(1 2 3)

Please see this list of documentation, esp. the Clojure CheatSheet. Also, the template project as a whole shows how I like to structure things.  :)
The function that helps the most is partition.  See the docs.

Slight refactoring
You can simplify it a small amount and make it a bit more compact by using more specialized functions like reduce and cond->.  This version uses a map to hold state and reduce to perform the looping:
(defn breaking-records
  [scores]
  (let [state-init     {:low     (first scores)
                        :high    (first scores)
                        :nworse  0
                        :nbetter 0}
        accum-stats-fn (fn [state score-pair]
                         ; Use map destructuring to pull out the 4 state variables
                         (let [{:keys [low high nworse nbetter]} state
                               new-score (second score-pair)
                               state-new {:low     (min new-score low)
                                          :high    (max new-score high)
                                          :nworse  (cond-> nworse
                                                     (< new-score low) (inc))
                                          :nbetter (cond-> nbetter
                                                     (< high new-score) (inc))}]
                           state-new))
        state-final    (reduce accum-stats-fn
                         state-init
                         (partition 2 1 scores))
        result         (select-keys state-final [:nworse :nbetter])]
    result))


Complex data structure organization in javascript?

While there's nothing completely wrong with what you did, if I were the programmer coming in behind you - I would certainly curse your name.  Writing "good" code (to me of course) requires more than meeting the objectives.  Readability and maintainability are just as important.

My concern with your design didn't set in until I saw the sample code to build the menu. Seeing all those brackets and indexes just about melted my brain.  I think if you would use object literals rather than straight arrays then my problems go away as it should then be much more readable and straight forward.


First, regarding your initial question: the code you have right here is definitely safe against SQL injection.  Using prepared queries (which you are doing) will protect you from the majority of SQL injection vulnerabilities.  It's worth doing some reading on SQL injection in general, but otherwise the biggest concern you have is for those queries that cannot use prepared queries.  This is typically the case if you need a column name to change based on user input, in which case you need to apply a white-list.  However, that isn't an issue here, so no need to over complicate things.  So while you are immediately protected against SQL injection, there are still some potential concerns here, and some general room for improvement:

You store the raw user data in the session.  In particular, the username is stored without any filtering.  This can result in a second-order SQL injection vulnerability.  In effect, you are using prepared queries here, but unsanitized data is being stored in the session.  Later on when that data is retrieved from the session and used (for instance, to verify the user when they return to the site), you can't see that it is dirty data and may forget to use proper prepared queries.  As a result, you may accidentally introduce an SQL injection vulnerability that is hard to see.  So remember to abide by two very important rules: 1) Always clean user input before storing and 2) Always use prepared queries.  The latter could very well be true already, but make sure and do #1 as well.
In this particular case though it is better not to worry about cleaning the username so much as halting all processing if you find invalid input.  In an ideal situation this would be part of a check_login function and you would return false as soon as you determined that the login was invalid.  So before you even do anything with the username you first check if it is valid (probably by making sure it doesn't contain any special characters) and return false if you find any problems.  This way there is no chance of getting dangerous input into the session in the first place.  It is much easier if people login with an email instead of a username, because you can use filter_var to make sure an actual email address was given, and return false if not.  Email addresses, of course, cannot be used for SQL injection.
Don't use crypt.  Use password_hash, and let it pick the salt for you.
Don't compare the password in the database.  Password hash comparisons are actually difficult to do right, and (while difficult to execute), a direct comparison like you are doing can leave your application vulnerable to timing attacks and other subtle weaknesses.  Select the hashed password out of the database and use password_verify to check if it matches the user input.
It is probably a bit to soon for you yet, but if you are just learning then now is a good time to start reading about and learning about dependency injection and test automation.  Those two will substantially improve the quality of your code in the long run, but obviously aren't being used here.
Your spacing is very inconsistent.  Following good coding conventions is a surprisingly important way of minimizing bugs in the long run and making maintenance easier.  Pick a coding convention and stick to it.  PSR is the standard in the PHP world, but sticking to any standard is better than being inconsistent.

Code organization is also very important to keep bugs at a minimum in the long run, but since only part of your code is posted here, there isn't much I can say about that at the moment.

Edit to add more about input filtering

I think it is worth a few more minutes to expand upon my discussion about input filtering.  The issue is that there are more vulnerabilities to be concerned about than just SQL Injection.  When you store user input directly in the application (i.e. $_SESSION['valid_user'] = $_POST['userid']) you leave a lot of room for security holes to leak in.  In this case, because you are checking that the username exists in the database, you are effectively checking the username against a whitelist.  Validating against a white-list is the typically the best approach to security, and in this particular case it is unlikely to cause you any specific trouble, but most security vulnerabilities are the more subtle kind that come from failures to properly validate user input at every step of the process.

The concept you want to go for is defense-in-depth.  In this case your login code is implicitly relying upon the fact that the registration form performs proper user-input validation.  As a result, a simple failure in validation logic on the registration page can potentially open up additional avenues for attack when the login page doesn't do any validation of its own.  When each area of the system practices proper security for all data relevant to itself, it becomes much more difficult for an attacker to find an exploitable security bug.  As a result, the most secure way to handle user input is:

Validate user input as strictly as you can, and reject any requests with invalid data
Always use prepared queries


How can I make this WHERE clause more readable?

Add comments, they're the usual way of making complicated source code easier to understand.

There's not a lot to add in your case because the meaning of the code is simple even if the implementation isn't easy to take in at a glance, but adding a few short comments may make it much more readable, especially for someone who's reading through the whole thing trying to understand the flow of logic. I would just do this:

where
    -- optional category
    (@Category = 'all' or
    (@Category = 'omitted' and Category is null) or
    (@Category = Category and (
        -- optional subcategory
        @SubCategory = 'all' or
        (@SubCategory is null and SubCategory is null) or
        (@SubCategory = SubCategory and (
            -- optional subsubcategory
            @SubSubCategory = 'all' or
            (@SubSubCategory is null and SubSubCategory is null) or
            @SubSubCategory = SubSubCategory
        ))
    ))
)

Now I can quickly see the purpose of the code, and even if the detailed logic is awkward to follow it may not matter at all because I may not need to change it, just understand what it's doing. If I do need to modify it, I'll have no choice but to work through it in detail anyway, in which case the comments will help to point me in the right direction.

You didn't mention if you're using SQL Server or Sybase, but if it's SQL Server and if you haven't read it already, this article is well worth reading. I wouldn't be too dogmatic about avoiding dynamic SQL, it certainly has its issues but it has its uses too.


Just a few things from me:

Check the way you name variables.  Local variables by defacto standard are lower case camel.  See here for more details Microsoft naming conventions.

GridViewItems becomes gridViewItems
I personally try to use implicit local variables where the type is obvious.  This is more a personal preference but Microsoft do recommend as well.  See C# coding conventions for more details.
If gridViewItems is going to be assigned to stockrooms immediately, why not just do straight off the cuff?

var gridViewItems = StockRooms.ToList();

I would convert this method into a bunch of smaller functions.  Perhaps something like (excuse any compile options as I could not fully test this code):

void FilterValues()
{
    dgvCompanyProfileDetails.DataSource = null;
    dgvCompanyProfileDetails.Rows.Clear();
    dgvCompanyProfileDetails.DataSource = Filter(StockRooms).ToList();
}

private IEnumerable<SecondaryStockRoomDefenition> Filter(IEnumerable<SecondaryStockRoomDefenition> stockRooms)
{
    // filter the stock rooms on each function call
    stockRooms = FilterStockRooms(stockRooms, cboPrimaryStockRoom, p => p.PrimaryStockroomCode);
    stockRooms = FilterStockRooms(stockRooms, txtSecondaryStockRoomCode.Text, p => p.SecondaryStockroomCode);
    stockRooms = FilterStockRooms(stockRooms, txtSecondaryStockRoomName.Text, (p, v) => p.SecondaryStockroomDescription.Contains(v));
    stockRooms = FilterStockRooms(stockRooms, txtStockRoomLocationCode.Text, p => p.SecondaryStockroomLocationCode);
    // .. etc

    return stockRooms;
}

private IEnumerable<SecondaryStockRoomDefenition> FilterStockRooms(IEnumerable<SecondaryStockRoomDefenition> rooms, ComboBox combo, Func<SecondaryStockRoomDefenition, string> filter)
{
    var value = combo.SelectedValue.ToString();

    return HasValue(value, "0") ? FilterStockRooms(rooms, v => filter(v).Equals(value, StringComparison.InvariantCultureIgnoreCase)) : rooms;
}

private IEnumerable<SecondaryStockRoomDefenition> FilterStockRooms(IEnumerable<SecondaryStockRoomDefenition> rooms, string text, Func<SecondaryStockRoomDefenition, string> filter)
{
    return HasValue(text) ? FilterStockRooms(rooms, v => filter(v).Equals(text, StringComparison.InvariantCultureIgnoreCase)) : rooms;
}

private IEnumerable<SecondaryStockRoomDefenition> FilterStockRooms(IEnumerable<SecondaryStockRoomDefenition> rooms, string text, Func<SecondaryStockRoomDefenition, string, bool> filter)
{
    return HasValue(text) ? FilterStockRooms(rooms, v => filter(v, text)) : rooms;
}

// The question marks are because I wasn't sure of the StockRooms type
private IEnumerable<SecondaryStockRoomDefenition> FilterStockRooms(IEnumerable<SecondaryStockRoomDefenition> rooms, Func<SecondaryStockRoomDefenition, bool> filter)
{
    return rooms.Where(p => p.DeletedSecondaryStockRoom == false && filter(p));
}

private bool HasValue(string value)
{
    return !string.IsNullOrWhiteSpace(value);
}

private bool HasValue(string value, string compareTo)
{
    return HasValue(value) && value.Trim() != compareTo;
}


Assigned a System resource to an image based on variable

this should be written once like this:

private sub whatever(byref res As Bitmap)
  If CurrentRecord(iStatusCol) = "Scheduled" Then
      MapIcon = New Bitmap(res)
  ElseIf CurrentRecord(iStatusCol) = "Tentatively Scheduled" Then
      MapIcon = New Bitmap(res)
  End If
end sub

and

Select Case CurrentRecord(iAssignedToCol)
    Case "Al B. Connor"
         whatever(My.Resources.Scheduled_ABC)
    Case "Donald E. Firestone"
         whatever(My.Resources.Scheduled_DEF)
    Case....

Hope you get my point..


On the face of it, what you're suggesting seems like it should work (although it may be implementation dependant since it depends on the OS socket API).  It also depends on what you mean by 'stripped down'.  Obviously, if you're doing something with the received packets that might throw an error you'll need to handle that as well.  Your catch would be better written as:

except socket.error:
    print ('Oops!')

As far as testing goes, you're sending to the same IP address so should be pretty safe but some things to try are:

Pull out / reconnect network cables
Turn off / reenable Wi-Fi
Disable / reenable network adapters
Send unexpectedly large packets (over your 4096 buffer size)
Try running multiple clients in constant send loops to see how your app handles large demand.


I'm not sure that I trust Codility's detected time complexity. As far as I know, it's not possible to programmatically calculate time complexity, but it is possible to plot out a performance curve over various sized datasets and make an estimation.

That being said, there are a number of unnecessary overhead in your code and so it is possible that Codility is interpreting that overhead as a larger time complexity.

As for your code, Python is all about brevity and readability and generally speaking, premature optimization is the devil.

Some of your variable names are not in proper snake case (str2num, char2digit_dict).
List memory allocation increases by a power of 2 each time it surpasses capacity, so you really don't have to pre-allocate the memory for it, it's marginal.
You convert your string into a list of digits, but then only ever use it in a way that could be fulfilled with your original dict. The list of digits is not really needed since you are already computing a list of prefix sums.
In the C solution it was important to calculate the len of the P/Q list first so that it's not recalculated every time, but in Python, range (xrange in Python2) is evaluated for i exactly once.
It's not necessary to deepcopy cur_count as it only contains integers, which are immutable. You can copy the list by just slicing itself, list[:]
Instead of constantly making references to count_appearances (up to 4x each iteration), you could just make the reference once and store it. This will also make it easier to update your references if the structure of P and Q were to change in any way.

Cleaning up your code in the ways I mentioned gives me:

def solution(S, P, Q):
    cost_dict = {'A':1, 'C':2, 'G':3, 'T':4}

    curr_counts = [0,0,0,0]
    counts = [curr_counts[:]]
    for s in S:
        curr_counts[cost_dict[s]-1] += 1
        counts.append(curr_counts[:])

    results = []
    for i in range(len(Q)):
        counts_q = counts[Q[i] + 1]
        counts_p = counts[P[i]]

        if Q[i] == P[i]:
            results.append(cost_dict[S[Q[i]]])
        elif counts_q[0] > counts_p[0]:
            results.append(1)
        elif counts_q[1] > counts_p[1]:
            results.append(2)
        elif counts_q[2] > counts_p[2]:
            results.append(3)
        elif counts_q[3] > counts_p[3]:
            results.append(4)

    return results

which gets a perfect score on Codility.


Logger to syslog with error_log fallback

You need a SysLog interface and a SysLogImpl implementation class.

public interface SysLog {
    public bool openlog(string $ident, int $option ,int $facility);
    public bool syslog (int $priority, string $message);
    public bool closelog (void);
}

SysLogImpl just delegate the calls to the openlog, syslog and closelog PHP functions.

public class SysLogImpl implements SysLog {
    public bool openlog(string $ident, int $option, int $facility) {
        return openlog($ident, $option, $facility);
    }

    public bool syslog(int $priority, string $message) {
        return syslog($priority, $message);
    }

    public bool closelog (void) {
        return closelog();
    }
}

It's important that this class should be just a thin facade without any logic since this class usually doesn't have any test or just has a few integration tests.

In production code pass a SysLogImpl instance to the constructor of your SystemLogger class and use this SysLogImpl instance instead of direct PHP calls.

In test code pass a mocked or a custom object which implements the SysLog interface to the SystemLogger class. The passed object should be able to store function calls and emulate responses (as mock objects do).

Maybe you'll need an ErrorLog interface and an ErrorLogImpl implementation class which logs with error_log PHP calls.

Another solution is a Test-Specific Subclass. You can extract out the openlog call from the constructor to a separate function and create a subclass of the SystemLogger which overrides this method and returns false.

A better and generic design would be creating a common Logger interface and a SyslogLogger and an ErrorLogLogger implementation classes. Both implements Logger. Then the SystemLogger class get one or more Logger instances and try calling their open functions and use that implementation whose open function returns true first.

If you use this the SystemLogger has only one responsibility: managing loggers, while SyslogLogger cares only about syslog and ErrorLogLogger cares only about error_log logging.


Exception handling: you handle some exceptions but you print them to the console, where they can get lost/unnoticed. It would be better to use the logger module to record them to a file. What I like to do when writing classes is to attach to the logger routine of the main module. This way, all messages go to the console AND get written to the same log file
The code would be along these lines:

import logging

def __init__(self, file, logger=None):
    self.dbfile = file

    # acquire existing logger - https://fangpenlin.com/posts/2012/08/26/good-logging-practice-in-python/
    self.logger = logger or logging.getLogger(__name__)
    self.logger.debug('Running __init__')

See the section 'Use name as the logger name' in the link above.

Redundant code:

assert os.path.exists(self.dbfile)
assert os.path.isfile(self.dbfile)

isfile is sufficient.

  os.path.isfile(path)

  Return True if path is an existing regular file. This follows symbolic links, so both islink() and isfile() can be true for the same
  path.

Source: os.path.isfile(path)

But your code will fail if the DB file does not exist. By default SQLite connect will create the file if it doesn't already exist. So I think you should preferably make that check after the call to connect to determine that the file is indeed present.

Return codes: your procedures return either 0 or -1, I wonder why you made that arbitrary choice. You could simply return a boolean value, also in your except blocks if you want, so that there is a return value on all paths.

Your read procedure returns a tuple (note that fetchall returns a list):

return 0, rows;

Personally I would only return the rows, but in case of error I would return None instead, so I know that the operation failed. If you don't look at the error code, the (empty) returned list is still iterable.
The return code doesn't matter here because it doesn't give any additional information. If I need details, I will look at the error log.

I would make the call to close optional (it's going to be forgotten sometimes anyway). Simply register a cleanup routine for your class:

import atexit

def __init__(self, iface, logger=None):
    ...
    # run cleanup routine when class terminates
    atexit.register(self.cleanup)

def cleanup(self):
    """To perform cleanup tasks when class instance is shutting down
    """
    self.logger.debug('Closing DB')
    if hasattr(self, '_dbconn'):
        self._dbconn.close()

And in fact the open method is not required either:

res = db.open()

Just move the code to the __init__ function. No need to do open & close.

Your write routine only allows certain operations:

assert any(map(lambda s: query.upper().strip().startswith(s), ('CREATE TABLE', 'ALTER TABLE', 'INSERT', 'UPDATE', 'DELETE')))

Therefore no PRAGMAs allowed but this is your choice.

One possible enhancement would be to take an existing connection as a class argument, in case you want to do something special on an open DB (like a PRAGMA), that your class does not easily allow. Although I can imagine this code is sufficient for your needs.


Java to Beanshell: validate an attribute for each record of a spreadsheet

A few things come to mind:

In Java 9 one can use Set.of("X", "Y", ...).
Or could simplify to private static final Set<String> VALID_DEPARTMENTS = new HashSet<>(Arrays.asList("A", "B"));
Could modify validate(dep) to return set.contains(dep) ? dep : null;
It would be nice to return "" instead of null if at all possible.  This is so that a project won't end up with tons of if (x != null) all over the place.
Recommend renaming Test to something more descriptive.  Maybe DepartmentValidator might be a step in the right direction.
Probably refactor dep to department.  Eventually the meaning may become less obvious as time passes and the code base grows larger.
Note: the validation is currently quite strict (exact match), so I'm assuming the incoming data is pretty exact (no misspellings or different capitalization, etc.)


Compare JS files and pick according to requirement

Since your post is a little unclear to me, I'm just going to point out a few small things that could be improved quiet a bit.

The program logic could be separated out into different functions. This allows for easy re-usability.
You should flesh out this program with comments for clarity. There are two types of comments, regular comments, and docstrings. Regular comments start with a # character, followed by a description. Docstrings describe functions and classes, like so.

def my_function(args):
    """
    This is a docstring. Put a description
    of your function here.
    """
    ...

class MyClass(object):
    """
    Put a description of your class here.
    """
    ...

You have some bad variable names, like ii, or tmp. Variable names should generally describe what the variable's purpose is.

There's not much for me to review, but if you want me to cover anything else, just mention it in the comments, and I'll see if I can cover it.


Some thoughts:

Don't continually re-query the DOM. Cache your control and slide elements in a variable so you don't need to spend time re-querying for them.
You don't need to maintain state around clickedSlider condition.  Consider using clearInterval() instead as more "proper" way to manage interval functionality.
Consider breaking apart your autoSlide() function into it's key parts - one function for managing the current slide index and another for actually performing the action of making slide at given index "active".  This gives you more code re-use in giving the capability to jump directly to a slide at a given index as is needed in your control click handler.
Do you really need data properties for your controls and slides?  If there is a 1-to-1 relationship between the slides and the controls and their ordering in DOM is the same, you should be able to know the control at index X relates to the slide at index X.

This might give you code more like:

$(document).ready(function(){
    var $testimonialSlides = $('.testimonial-slider-slides a');
    var $testimonialControls = $('.testimonial-slider-controls a');
    var slideCount = $testimonialSlides.length;
    var slideIndex = 0;

    function activateSlide(idx) {
        $testimonialSlides
            .removeClass('active')
            .eq(idx).addClass('active');
        $testimonialControls
            .removeClass('active')
            .eq(idx).addClass('active');
    }

    function autoSlide(){
        slideIndex++;
        if (slideIndex === slideCount) {
            slideIndex = 0;
        }
        activateSlide(slideIndex);
    }

    var autoSlideInterval = window.setInterval(autoSlide, 2000);

    $testimonialControls.click(function(e){
        e.preventDefault();
        window.clearInterval(autoSlideInterval);
        slideIndex = $testimonialControls.index(this);
        activateSlide(slideIndex);
    });
});

You may also consider building this as a proper jQuery plug-in or class (though not shown in my example above).  This would allow you to better encapsulate state of the slider functionality, such that state would not need to be held in main $(document).ready() scope. This also potentially makes this simple functionality re-usable in the future - just pass in config for DOM selectors, class name(s) to apply (i.e. active), interval time, etc.  I would rather see a usage pattern like:

$(document).ready(function() {
    // Perhaps not all of the configurations shown below need to be passed
    // if there are default settings.
    // This assumes autoslider() code is already included in document
    $('.testimonial-slider-slides a').autoslider(
        {
            controls: '.testimonial-slider-controls a',
            activeSlideClass: 'active',
            interval: 2000,
            startIndex: 0
        }
    );

    // other application code that needs to execute on ready()
    // perhaps even another autoslider with it's own encapsulated state
});

Why have superfluous comments?  If your code is well-written with meaningful function and variable names (I think you do a good job of this), then you should not need such comments.


Reducing duplicated code when using many Netlogo Link Breeds

As far as breeds go, I don't know of any other way to build up the amount other than by copying and pasting. Of course, you can automate the creation in another language and then copy that into NetLogo, but in NetLogo itself I don't think there's any way.

As far as instantiation goes, you can trim down to the more generic links-own and all breeds will inherit those variables:

links-own [
  activity-size
  activity-history
]

For the different getter functions, I wonder if you could make use of dictionaries with the table extension. For example, using your get-activity [layer] reporter as a guide, build an example dictionary that has the key-value pairs defined in your if statements. Assuming this header info:

extensions [ table ]

globals [
  layer-activity-dict
  layer-color-dict
]

undirected-link-breed [infection-activities infect-activity]
undirected-link-breed [exposure-activities exposure-activity]
undirected-link-breed [watch-activities watch-activity]

Start by building the toy dictionary and creating some turtles and a link:

to setup
  ca
  ; build the activity dictionary
  set layer-activity-dict table:make
  let keys [ "infection" "exposure" "watch" ]
  let vals [ "infection-activities" "exposure-activities" "watch-activities" ]
  ( foreach keys vals [ [ k v ] ->
    table:put layer-activity-dict k v
    ] )

  ; build turtles and some links
  crt 10 [ setxy random-xcor random-ycor ]
  ask n-of 5 turtles [
    create-watch-activity-with one-of other turtles
  ]
  ask n-of 5 turtles [
    create-infect-activity-with one-of other turtles
  ]
  reset-ticks
end

To make use of the dictionary, try something like this reporter, which uses runresult to parse the text from the dictionary entry:

to-report get-activity [layer] ; link-reporter
  report runresult ( table:get layer-activity-dict layer )
end

Testing:

to go
  print get-activity "infection"
  print "Does get-activity return a string?"
  print is-string? get-activity "infection"
  print "Does get-activity return an agentset?"
  print is-agentset? get-activity "infection"

  ask get-activity "infection" [
    set color red
  ]
  ask get-activity "watch" [
    set color blue
  ]
end

Note that the reporter structure will vary depending on what your dictionary actually contains. For example, for color there is no runresult needed:

to setup-2
  ca
  ; build the color dictionary
  set layer-color-dict table:make
  let keys [ "infection" "exposure" "watch" ]
  let vals [ blue 113 brown ]
  ( foreach keys vals [ [ k v ] ->
    table:put layer-color-dict k v
    ] )

  print get-color "infection"
end

to-report get-color [layer] ; link-reporter
  report table:get layer-color-dict layer
end


Calculate 8 hours business day in a weekdays only

You can throw an error if someone is trying to set a work day to a day that should be a day off. Then you just need to handle this error.


Binary tree inorder traversal without stack or recursion

Comparison

I don't think this approach offers any benefits compared to Morris traversal, a stack-based or a recursive approach:

Both this and Morris are modifying the given tree, which I consider to be a negative thing. You're not rearranging nodes like Morris does, but those counter fields still prevent simultaneous traversals. A recursive or stack-based approach does not have that limitation.
Adding an additional field to your Node class is 'intrusive', and it increases memory use even when you never traverse a tree.
Unlike the other approaches, yours requires nodes to have a reference to their parent.
In all the tests I've done (using trees of 100 - 100K nodes) this was consistently slower than Morris, which itself was slower than a recursive or stack-based approach.
In terms of how easy the code is to understand, I'd say it's similar to Morris, but both are more complicated than a recursive and stack-based approach.

I don't know why you don't like the idea of using recursion. It's actually a very natural approach when working with tree-like structures. It's easy to implement, fast, and doesn't modify the tree or require structural changes.

public void Traverse(Node node, Action<Node> visit)
{
    visit(node);
    if (node.Left != null)
        Traverse(node.Left, visit);
    if (node.Right != null)
        Traverse(node.Right, visit);
}

With recursion there's always a risk of stack overflow, but that should only be a concern when working with highly imbalanced trees.

Improved approach

Your approach can be modified so it no longer needs those counter fields. You've got the following states:

node.Counter == 0: Move to the left child.
node.Counter == 1: Move to the right child.
node.Counter == 2: Move back to the parent.

But you can also distinguish between these states if you only keep track of the previously visited node:

previous == current.Parent: Move to the left child.
previous == current.Left: Move to the right child.
previous == current.Right: Move back to the parent.

In terms of performance it's somewhere in-between recursive and Morris. It can also be generalized for nodes with a variable number of children. Still, it remains a relatively complicated approach.

Other notes

The root node should be passed to Traverse as an argument, not via a 'global' variable.
Get is a very undescriptive name. GetNextNode sounds better, except that it sometimes returns the same node (in a different state), so that name is slightly misleading. Maybe ContinueTraversal?
Get is only useful within the context of Traverse, so it can be made a local function.
Those counter values indicate specific states, so I'd use an enum instead of 'magic numbers'. Alternately, you could rename it to something like visitedChildNodeCount.
Hardcoding System.Console.WriteLine(node) isn't very flexible. Consider passing in the action to be performed as an Action<Node> argument.
Instead of writing if (condition) { ... } else { return null; }, I'd invert that to if (!condition) return null; ... to reduce nesting.


Another DataGrid (ObservableCollection) Filtering Method

You can refactor this into LINQ query for (arguably) better readability.

AllCompanies.Where(c => CompanyMatchesFilters(c))
            .Where(c => CleanseText(company.Name).Contains(searchText)
                     || CleanseText(company.Town).Contains(searchText)
                     || CleanseText(company.Postcode).Contains(searchText))
            .Take(25);

As for performance - nothing in the code you've shown strikes me as potential performance bottleneck. You will probably have to run a profiler to pinpoint it. One thing in particular you might want to look at is what triggers the search and how often it is executed. For example, if I enter 10 chars in search box, do I search 1 or 10 times? While the filtering logic looks fairly lightweight, the performance implications of recreating 25 item templates in UI on every keystroke can be severe (depending on how complex the DataTemplate is). Rx has some nice extensions that might help in throttling UI events.

P.S. Whats the point of removing all meaningful characters in CleanseText? What characters are you interested in then? This is extremely unclear, you should document that portion of your code.


What would be preferred aesthetically and performance wise?

I agree mostly with @Vogel612's answer, the second version is more concise and there is no need to litter variables all over the place as is done in the first version.

Another point is that code should be self-documenting, which @Vogel612 also suggests, but else you can still add a comment behind the code lines.

My review

I wanted to talk about a more interesting point, as this question seems to be a subproblem of a bigger question of yours, which involves creating a high throughput program that does something with tweets.
Perhaps this is a premature optimization given that I do not know how well your program performs, but your program may very well hit a threshold limit because of the way you handle regexes.

You should consider what a String.replaceAll does:

public String replaceAll(String regex, String replacement) {
    return Pattern.compile(regex).matcher(this).replaceAll(replacement);
}

For every provided regex it creates a pattern and matches and replaces the occurences with the replacement.
It is also important to look into Pattern.replaceAll now:

public String replaceAll(String replacement) {
    reset();
    boolean result = find();
    if (result) {
        StringBuffer sb = new StringBuffer();
        do {
            appendReplacement(sb, replacement);
            result = find();
        } while (result);
        appendTail(sb);
        return sb.toString();
    }
    return text.toString();
}

Here you can see, that because of four regex replaces, you create four times a StringBuffer, which is synchronized, and a String object, which can count up if you are processing tons of tweets.

There are two things you can do:

Create a single regex that captures what you want to do, thus needing only one replaceAll call.
Go really into micro-optimizing and get rid of the regexes in a whole, operate on a char[] and only store the resulting character array.


Refactor a legacy application to a less-unwieldy state

I would put:

var ListItems = new List<ListItem>();
//Yes this is silly since statusReturn is never used
var statusReturn = _Permissions.GetReportsForUserGroupName(userGroup, ref ListItems);

in a method that just returns the list. So you are isolating the madness a bit.

I'm not a C# programmer, but wouldn't listItems be better than ListItems?

I honestly did not understand what the code is doing.  Maybe you could explain it a little bit in your post.

It seems that you have a tree structure in there.  So why transform a list which originally seems to contain a tree to another list, which should also be a tree?


A PDO connection classto initiate multiple connection and easy access

You have some issues in code design and codestyle:

All class names must be Capitalized
Never use self::$field if $field is protected, use static::$field instead. If you use self child classes won't have access to redefine field!
Never use die() you have exceptions for this!
Save process time use if ($con = database::getConnections())
Class containing only static fields is useless and fully procedural-style, create Singleton or Registry instead.


Determine the roots of a Quadratic Equation

int main(void) is preferable, as that's clear about the number of arguments.
I don't understand why the coefficients must be integers - surely a quadratic equation can have any real coefficients?
We don't test whether the scanf() actually converted all three inputs.  If we are given something that's not an integer (perhaps a different kind of number, perhaps just garbage input), then the program will proceed with incorrect data, and produce output that might be plausible, instead of a sensible error message.  We need something more like:
double a, b, c;
if (scanf("%lf %lf %lf", &a, &b, &c) != 3) {
   fputs("Invalid input\n", stderr);
   return 1;
}

There is another case of invalid input that's not checked - if a is zero, we don't want to divide by it.
You seem to have got confused which part is real and which imaginary here:
    root1_complex = -b / (2 * a); root1_i = sqrt(-d) / (2 * a);
    root2_complex = -b / (2 * a); root2_i = sqrt(-d) / (2 * a);

If we use better variable names, and reduce their scope a bit, we can make that simpler:
    double real = -b / (2 * a);
    double imag = sqrt(-d) / (2 * a);

And we can do all the printing in a single call to printf:
    printf("First root : %.2f + i%.2lf\n"
           "Second root : %.2lf + i%.2lf\n"
           "There are TWO COMPLEX SOLUTIONS\n",
           real, -imag,   real, imag);

When we know d is zero, there's really no point computing its square root:
 } else { // Zero
    root_zero = -b / (2*a);

As suggested in a comment, it might also be worth computing that common part of the three expressions to outside the if/else:
const double real =  -b / a / 2;
if (d > 0) { // Positive
    double root = sqrt(d) / a / 2;
    ⋮
} else if (d < 0) { // Negative
    double imag = sqrt(-d) / a / 2;
    ⋮
} else { // Zero
    ⋮
}

Here's a lightly modified version with my suggestions applied:
#include <stdio.h>
#include <math.h>

int main(void)
{
    printf("Enter a, b and c where ax² + bx + c = 0\n");
    double a, b, c;
    if (scanf("%lf%lf%lf", &a, &b, &c) != 3) {
        fputs("Invalid input\n", stderr);
        return 1;
    }
    if (!a) {
        fputs("Quadratic term must not be zero\n", stderr);
        return 1;
    }

    const double d = b * b - 4 * a * c;

    printf("Finding the roots of %gx² + %gb + %g = 0\n", a, b, c);

    const double real =  -b / a / 2;
    if (d > 0) {
        double root = sqrt(d) / a / 2;
        printf("First Root: %.4g\n"
               "Second Root: %.4g\n"
               "There are TWO REAL SOLUTIONS\n",
               real - root,   real + root);
    } else if (d < 0) {
        double imag = sqrt(-d) / a / 2;
        printf("First root: %.4g + %.4gi\n"
               "Second root: %.4g + %.4gi\n"
               "There are TWO COMPLEX SOLUTIONS\n",
               real, -imag,   real, imag);
    } else { // d == 0
        printf("Root: %.4g\n"
               "There is ONLY ONE REAL SOLUTION\n",
               real);
    }
}


Very nice script!

I suggest you put this into a function, that takes n as an input argument instead of hardcoding it. It requires very little alterations, and will make the function a lot easier to use. You can skip all the clearing in the beginning and substitute it with:

function [] = koch_snowflake(iterations)  % or

and add an end at the bottom of your script.

length = 1; % Original side length of triangle

This is a no no. I strongly recommend you not to use length as a variable name as it's a very commonly used builtin function. This can cause a lot of errors that are hard to find. Note that you should always use the function numel instead of length, but it's still not a good idea to overload it.

theta = 60*pi/180; % Angle of the equilateral triangle in radians

I guess you think 60*pi/180 is easier to read than pi/3, but I disagree. If you want to use the number of degrees, and convert it to radians, you might want to use deg2rad.

I suggest substituting the iterator i to for instance ii if you ever work with complex numbers, to avoid potential errors and confusion. i is by default the imaginary unit in MATLAB (so is j, 1i, 1j). This is a matter of preference though.

Also, personal preference again, but I like it when comments are aligned (if possible):

length = 1;                   % Original side length of triangle
theta = 60*pi/180;            % Angle of the equilateral triangle in radians

% Points of the original equilateral triangle
p1 = [0,0];
p2 = [1/2*length,length*sin(theta)];
p3 = [length,0];

flake_points = [p1; p2; p3];  % Vertices of the snowflake

for iteration = 1:7
    n_points = size(flake_points,1);          % No. points currently in data
    new_triangle_points = nan(n_points*3,2);  % New points to be added
...
...


docker-machine provides a simple way to get the IP of the host machine

mongo --host `docker-machine ip default` --port 27017

I'm using default here, since that's the name of the machine I'm using.


Your query looks OK, for the most part. There are two things you could do better.

C and O don't make for very good aliases. Picture if you had 20 tables instead of just 2. In programming it's better to give aliases, variables, etc. meaningful names. Aliases are useful for shortening long table names, but should not be short to the point it obfuscates your code. In your case something like Cust and Ord would be better.

You are using old-style join syntax which is deprecated and should be avoided. In your case, inner join would work good, so instead of this:

FROM   Customer C , Order O
WHERE  C.customer_id = O.customer_id
AND    C.customer_id = 12345;

You should do this:
FROM   Customer C
INNER JOIN Order O
  ON C.customer_id = O.customer_id
WHERE C.customer_id = 12345;

Cross join
Chances are, if you think you need a cross join, you probably don't need a cross join. First, they are insanely slow. Second, the cross join gives you a Cartesian product which is almost never what you want, and in your case your results would be way off. (Try it!)
Here is some more information about cross join in SQL, for further reading.


Splitting text into lines from a max width value for CANVAS

The first thing I notice is an excessive use of measureText, which I am inclined to assume is a relatively expensive operation.  At a minimum, every word is measured twice - once to verify it fits within the maxWidth constraint, and once again to verify it fits on the current line. Of course, as the line grows, all previous words are measured again by virtue of the current line being measured on each loop.

Second, when a word doesn't fit on the current line, it must be processed again (it isn't shifted off the array in this condition).

With this kind of problem, I prefer to separate tasks - that is, measure first (no need to measure twice), build second. I would prefer to loop through the word list a couple of times to minimize the calls to measureText. I have rewritten the function with this in mind. The function is much longer now, but I feel it is easier to follow and to maintain when edge cases arise.

var emmeasure = ctx.measureText("M").width;
var spacemeasure = ctx.measureText(" ").width;

/* takes a string and a maxWidth and splits the text into lines */
 // ctx is available in the parent scope.
function fragmentText(text, maxWidth) {
    if (maxWidth < emmeasure) // To prevent weird looping anamolies farther on.
        throw "Can't fragment less than one character.";

    if (ctx.measureText(text).width < maxWidth) {
        return [text];
    }

    var words = text.split(' '),
        metawords = [],
        lines = [];

    // measure first.
    for (var w in words) {
        var word = words[w];
        var measure = ctx.measureText(word).width;

        // Edge case - If the current word is too long for one line, break it into maximized pieces.
        if (measure > maxWidth) {
            // TODO - a divide and conquer method might be nicer.
            var edgewords = (function(word, maxWidth) {
                var wlen = word.length;
                if (wlen == 0) return [];
                if (wlen == 1) return [word];

                var awords = [], cword = "", cmeasure = 0, letters = [];

                // Measure each letter.
                for (var l = 0; l < wlen; l++)
                    letters.push({"letter":word[l], "measure":ctx.measureText(word[l]).width});

                // Assemble the letters into words of maximized length.
                for (var ml in letters) {
                    var metaletter = letters[ml];

                    if (cmeasure + metaletter.measure > maxWidth) {
                        awords.push({ "word":cword, "len":cword.length, "measure":cmeasure });
                        cword = "";
                        cmeasure = 0;
                    }

                    cword += metaletter.letter;
                    cmeasure += metaletter.measure;
                }
                // there will always be one more word to push.
                awords.push({ "word":cword, "len":cword.length, "measure":cmeasure });
                return awords;
            })(word, maxWidth);

            // could use metawords = metawords.concat(edgwords)
            for (var ew in edgewords)
                metawords.push(edgewords[ew]);
        }
        else {
            metawords.push({ "word":word, "len":word.length, "measure":measure });
        }
    }

    // build array of lines second.
    var cline = "";
    var cmeasure = 0;
    for (var mw in metawords) {
        var metaword = metawords[mw];

        // If current word doesn't fit on current line, push the current line and start a new one.
        // Unless (edge-case): this is a new line and the current word is one character.
        if ((cmeasure + metaword.measure > maxWidth) && cmeasure > 0 && metaword.len > 1) {
            lines.push(cline)
            cline = "";
            cmeasure = 0;
        }

        cline += metaword.word;
        cmeasure += metaword.measure;

        // If there's room, append a space, else push the current line and start a new one.
        if (cmeasure + spacemeasure < maxWidth) {
            cline += " ";
            cmeasure += spacemeasure;
        } else {
            lines.push(cline)
            cline = "";
            cmeasure = 0;
        }
    }
    if (cmeasure > 0)
        lines.push(cline);

    return lines;
}

Performance:
I executed this test on my machine in IE9. Note the assumption of a table called "splittertest" with the columns: Words, MaxWidth, New (ms), Old (ms). The original function is called fragmentText_old in this test.

var tests = [{"twc":50, "tmw":500},
             {"twc":50, "tmw":50},
             {"twc":500, "tmw":500},
             {"twc":500, "tmw":50},
             {"twc":5000, "tmw":500},
             {"twc":5000, "tmw":50},
             {"twc":10000, "tmw":500},
             {"twc":10000, "tmw":50}];
var results = [];

for (var tt in tests) {
    var test = tests[tt];

    var testline = (function(twc) {
        var testwords = [];
        for (var x = 0; x < twc; x++) {
            var len = 3 + Math.floor(Math.random()*11);
            var letters = [];
            for (var y = 0; y < len; y++)
                letters.push(String.fromCharCode("a".charCodeAt() + y));
            testwords.push(letters.join(""));
        }
        return testwords;
    })(test.twc).join(" ");

    var st, dur1, dur2;

    st = new Date().getTime();
    var ss = fragmentText(testline, test.tmw);
    dur1 = new Date().getTime() - st;

    st = new Date().getTime();
    var sso = fragmentText_old(testline, test.tmw);
    dur2 = new Date().getTime() - st;

    results.push("
" + test.twc + "	" + test.tmw + "	" + dur1 + "	" + dur2 + "
");
}

$("#splittertest").append(results.join(""));

The results show mine about twice as fast when there is no chance a word will exceed the maxWidth, and exponentially faster when words frequently exceed the maxWidth.

Words  MaxWidth  New (ms)  Old (ms)
50     500       1         1
50     50        3         5
500    500       3         7
500    50        16        331
5000   500       31        76
5000   50        195       167820 (2.8 mins)
10000  500       60        155
10000  50        337       1121565 (18.7 mins)

It's worth noting that the results are significantly less on subsequent runs in the same browser because of some caching done - probably within the canvas context.


Getting the top 10 stores within a category

There are some things that you don't need here

SELECT u.id,
       u.avatar,
       u.storeName,
       (SELECT COUNT(o.id) FROM orders o WHERE o.storeId = u.id) AS orders
FROM users u
WHERE (SELECT c.id
       FROM categories c, products p
       WHERE c.id = p.categoryId
       AND p.userId = u.id
       GROUP BY p.categoryId
       ORDER BY COUNT(p.id) DESC
       LIMIT 1) = 9
ORDER BY orders DESC
LIMIT 10

like the ORDER BY and the LIMIT 1 and the GROUP BY in the Select statement that is nested in your where clause.

SELECT u.id,
       u.avatar,
       u.storeName,
       (SELECT COUNT(o.id) FROM orders o WHERE o.storeId = u.id) AS orders
FROM users u
WHERE (SELECT c.id
       FROM categories c, products p
       WHERE c.id = p.categoryId
       AND p.userId = u.id
       ) = 9
ORDER BY orders DESC
LIMIT 10

You should also rename your column orders to orderCount

one more thing that I would suggest is to take it all out of the WHERE clause, this is slow

do it like this

SELECT u.id,
       u.avatar,
       u.storeName,
       (SELECT COUNT(o.id) FROM orders o WHERE o.storeId = u.id) AS orderCount
FROM users u INNER JOIN products p ON u.id = p.userId
WHERE p.categoryID = 9
ORDER BY orderCount DESC
LIMIT 10


Highest pit - only climbing through the pit once

Your code over-complicates the basic premise. The idea of having an ascending or descending element is right, but can be simplified further by just tracking maxima/minima, there is no need to track the actual index of the deepest pit.

If you identify peaks, and pits, and as you walk through the data, identify whether the current value increases the depth of the current pit, and increase the max if it does, then your code can be reduced to just a single check that identifies inflections, and another max/min check that compares depths.

private static int deepest(int[] data) {

    if (data.length < 1) {
        return 0;
    }

    int inflection = 0;
    int max = 0;
    int descent = 0;
    boolean ascending = true;
    for (int i = 1; i < data.length; i++) {
        boolean goingup = data[i] == data[i - 1] ? ascending : data[i] >= data[i - 1];
        if (goingup != ascending) {
            ascending = goingup;
            descent = ascending ? (data[inflection] - data[i - 1]) : 0;
            inflection = i - 1;
        }

        max = Math.max(max, Math.min(descent, data[i] - data[inflection]));
    }
    return max;
}

(See this running with some tests in ideone)


Some suggestions:

Upper case names are by convention reserved for exported variables.
Use More Quotes™, especially around $@
Use arrays for constructing commands
Variables are by default declared in the global scope. It would be better to declare the variables in the function local.
Use getopt to parse options - the default pattern is a bit wonky but it's easier to deal with for complex cases.
You can use readarray to read .hidden into an array in a single command.
The returns are redundant.
in $@, or more correctly in "$@", is redundant. for argument does the same thing.
You don't need semicolons if you put then on the next line like you already do with do.
You shouldn't have to use index variables. For example, both times $F is used you can instead use FILES[${#FILES[@]}]=…
$* and its accomplice ${name[*]} split every argument on $IFS, and is therefore extremely rarely useful. Use $@ and ${name[@]} instead.


Style

Use proper styling. You should use more whitespaces, this will make your code more readable. Instead of num_sort=new use num_sort = new, insead of i!=min_index use i != min_index, etc
Follow the Java naming conventions: variable and function names should use camelCase, not snake_case.
You should include documentation that explains the user how the class is used. For example, without looking at the code I would not expect that creating a new instance of the class automatically sorts the list, so it is something you must make clear in the documentation.

Comments

Commenting the code is good, but too many comments can make a simple function look complicated. The general rule is that code tells you how, comments tell you why.

For example, I think int min = this.num_sort.get(i); does not need to be commented; it's pretty clear that you are getting the i-th item of the list.

Also, leave a whitespace between // and the text, it's more readable.

Code structure

It does not make sense to have this in a class; new SelectionSort(userlist) is not the way someone would expect to sort a list. I am going to make some recommendations that for the class design, but for the rest of the review I will restructurate the code so that it is more conventional.

As a user I expect select_sort to sort the list and that's all; I decide whether I want to print the list or not (what if I want to print it differently to you?). So you should move the printing code to the main function.

Class design

If you were to continue with the current class design, there must be some changes:

Do not sort the list in the construction. It is not the expected behaviour. Let the user call sortSelect(). Actually, I think selectionSort() would be a better name.
Is exchange a method that is meant to be used by the user? I don't think so, so make it private instead of public so only the class code can use it.
num_sort does not seem like an intuitive name; I had to look at the code to know what it is. Just calling it list would be better.
You don't care how the list is internally implemented, you only care that it is a list. So use the more generic List interface instead of ArrayList.
You are assigning your list twice: on num_sort=new ArrayList<>() and on this.num_sort=userlist;. The first one is not necessary, because it will always be replaced in the constructor. Furthermore, since you never reassign the list again, you should declare it final.

private final List<Integer> list;

public SelectionSort(List<Integer> userList) {
    this.list = userList;
}

Alternative design

In my opinion, your selection sort algorithm should just be one static method that takes the list as input. That would make it similar to the Collections.sort() method that already exists in Java.
Scanner is a resource that must be closed. You can make Java close it automatically by using a try with resources.

try (Scanner in = new Scanner(System.in)) {
    // your code
}

You can still keep the convenience method exchange (as static and taking the list as parameter), but since it is quite short and you only call it in one place I think you could just write the code directly. If you decide to keep the function, I would change the parameter names to just i and j, and the method name to swap (it's more common). Since it's the same doing exchange(current_elem, new_min) than exchange(new_min, current_elem) those parameter names do not make much sense. BUT you don't even need to implement that method, you can just use Collections.swap()

Final code

/**
 * Sorts the given list using a selection sort algorithm.
 * @param list The list to be sorted.
 */
public static void selectionSort(final List<Integer> list) {
    // outer for loop to pick one element at a time
    // e.g if list is 20,12,3,4,5,6,98----this loop will first pick 20
    for (int i = 0; i < list.size(); i++) {
        int min = list.get(i);
        int minIndex = i;
        // Go over the rest of the list and compare minimum by rest of list. If number smaller than min is found, then it is assigned as new min
        // So go over list starting from 12 and comparing 20 with each of them and finding the new min, in this case it will be  3
        for (int j = i + 1; j < list.size(); j++) {
            if (list.get(j) < min) {
                min = list.get(j);
                minIndex = j;
            }
        }
        if (i != minIndex) {
           Collections.swap(list, i, minIndex);
        }
    }
}

public static void main(String[] args) {
    try (Scanner in = new Scanner(System.in)) {
        System.out.println("Enter how many numbers you want to sort");
        int count = in.nextInt();

        System.out.println("Enter the numbers you want to sort");
        List<Integer> list = new ArrayList<>();
        for(int i = 0; i < count; i++) {
            list.add(in.nextInt());
        }

        selectionSort(list);

        System.out.println("Sorted entered are: ");
        for (int x : list) {
            System.out.print(x + " ");
        }
    }
}


Return array with products of old array except i

Review:

So there are some changes that can be made. As you are running a nested for loop that should be the first candidate for removal, python isn't the best with lots of loops. I've made some changes below to improve your code.

Here we actually use n, instead of ind, they are the same, so ind is excessive
I've expanded the if ... else block as this improves readability
I've changed i for x as this is easier to quickly differentiate from 1

def coding_solution(_arr):
    new_arr = []
    for n in range(len(_arr)):
        v = 1
        for m, x in enumerate(_arr):
            if m != n:
                v *= x
            else:
                v *= 1
        new_arr.append(v)
    return np.array(new_arr)

Alternate solutions:

I have two methods that work, one is pure python (using two core libraries), but could include numpy; the other is all numpy. They both work on a similar principal, that is that all new values are the same product (the entire array) divided by the value at the same index in the original array. Therefore, you can just divide the product of the entire array by each value in the original array, as long as there are no zero values (thanks One Lyner!).

Pure python:

from functools import reduce
from operator import mul

arr = [1, 2, 3, 4, 5]

def f(_arr):
    arr_prod = reduce(mul, _arr)  # You could use np.prod(_arr) instead of reduce(...)
    return [arr_prod / x for x in _arr]

The pure python function could be a single line, but then you might end up computing the product of the entire array on every iteration.

Numpy

import numpy as np

arr = np.array([1, 2, 3, 4, 5])

def g(_arr):
    return np.ones(_arr.shape) * _arr.prod() / _arr

# Even more succinct, thanks Graipher
def h(_arr):
    return _arr.prod() / _arr

This Numpy solution would be vectorised and would scale well, but may be slower on smaller arrays. It works by creating a new np.array of all 1; multiplying it by the product, so all the values are the product; finally dividing the 'product array' by the original array, which is element-wise.


Performance in Hackerrank challenge "Sherlock and Queries"

This loop can be tuned in some ways:

for i, factor in factors.iteritems():
    for j in range(1, n/i + 1):
        idx = j*i-1
        a[idx] *= factor
        a[idx] %= 1000000007;

Use the third argument of range (step size).
Use xrange in Python 2.
The in-place operators may actually slow you down vs. a single expression.

Modified:

for i, factor in factors.iteritems():
    for idx in xrange(i-1, n, i):
        a[idx] = a[idx] * factor % 1000000007

The fileinput module offers convenience for reading multiple files, but adds some overhead. If you are reading from standard input, use for line in sys.stdin directly.

As noted in comments, the above changes do not make much difference. However, I now found something that actually matters. There is a subtle bug in the translation from C++ to Python here:

factors[b[i]] *= c[i] % 1000000007

Written like this the modulo operator applies to c[i] while it is supposed to apply to the result of the multiplication. The programs still gives the correct result because you apply the modulo in the later loop, but in the meanwhile Python has to multiply much larger numbers. I get a 100-fold speed increase by changing the line to

factors[b[i]] = factors[b[i]] * c[i] % 1000000007


Updating the icon of every JLabel in a JLabel ArrayList

We will start by cleaning up the code:

First, let's make the for loop cleaner to read. A compiler is able to inline variables that are only used once in a scope.

for (int i = 0; i < board.size(); i++) {

    final ImageIcon tileToDisplay = displayTile(i);

    final int height = tiles.get(i).getHeight();
    final ImageIcon resizedTileToDisplay = resizeIcon(tileToDisplay,height,height);
}

Second, in displayTile(int num), StringBuilder is more efficient when concatenating strings. Also, if(num != 0) is redundant because you apply the same logic in both cases.

public static ImageIcon displayTile(int num) {

    final StringBuilder pathBuilder = new StringBuilder("src/resources/");
    pathBuilder.append(num);
    pathBuilder.append(".png");

    return new ImageIcon(pathBuilder.toString());
}

Lastly, resizeIcon changes the parameter i; methods should not change the parameters that they receive:

public static ImageIcon resizeIcon(ImageIcon icon, int x, int y) {

    Image resizedImage = icon.getImage().getScaledInstance(x,y,java.awt.Image.SCALE_SMOOTH));
    return new ImageIcon(resizedImage);
}

Now, let's deal with performance:

You are loading 100 - 200 images from a file, resizing each one and then placing it on a screen. This is a resource intensive task and you need to optimise it. Here are some suggestions

Use a ThreadPool to load the images asynchronously on start up. Cache them in memory and use them as needed.
Only load images as needed. For example, the board may have 200 tiles, but only 10 are visible at a given time. So load the first ten tiles. Anticipate which tiles will be needed and load them as necessary
If resizing is a one time operation, perhaps saved the resized images to disk so that you won't have to resize them after the first time.
BufferedImage offers getSubimage. You could have one big image with all 100-200 tiles. Load this one big image once, and then show only the relevant part of the image using getSubimage. This is a concept known as Sprites and you can find a clearer example here.


What you're looking for is known as a "scan" in functional programming.  Surprisingly, ruby's Enumerable, which is where this method belongs (since what you're doing is not, ultimately, specific to strings), does not provide a scan method or its equivalent.

But we can write one easily enough:

module Enumerable
  def scans
    reduce([]) {|m,x| m << (m.last || []) + [x]}
  end
end

Now we have a general purpose method which we can use like so:

[9] pry(main)> (1..5).to_a.scans
=> [[1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [1, 2, 3, 4, 5]]

Your original problem now becomes a simple delegation to scans:

[14] pry(main)> 'abc'.split('').scans.map(&:join)
=> ["a", "ab", "abc"]


Use if statements rather than try/catch

Your method is understandable, you shouldn't use try catch, instead simply check that the index does not exceed the length.
e.g.

if (col < matrix.get(row).size()) {
   // print what you want
} else {
   // print just a space
}

Better Regex

Rather than sentence.split(" "); The regex you want is sentence.split("\\s+)
This ensures that you get all spaces and don't have an incorrect array length due to splitting on multiple empty spaces in a row. You can read more on Regex here.

Though this only applies if you don't want spaces to delimit words, ever, which is the assumption. The input itself sounds like it has to do with the specifications of the problem, but I simply took it as input and nothing more.

Use two dimensional arrays

You also don't need the list overhead for this.
Simply use a two dimensional of the same size as the original array and make the inner arrays the result of calling the aforementioned split() method.

public static String[][] convertToWordArray(String[] input) {
        String[][] result = new String[input.length][];

        for (int i = 0; i < result.length; i++) {
            result[i] = input[i].trim().split("\\s+");
        }

        return result;
}

Alternative Implmentation:

public class Format {
    public static void main(String[] args) {
        String[] target = {
            "How To Format",
            "put returns between paragraphs",
            "for linebreak add 2 spaces at end"
        };

        printWordsVertically(target);
    }
/* These next two methods are relics of my initial implementation
   You can adjust for the use of 2d arrays and only need 1 method. */
    public static int wordCount(String input) {
        return input.trim().split("\\s+").length;
    }

    public static int longestWordCount(String[] input) {
        int result = 0;

        for (String s : input) {
            if (result < wordCount(s)) {
                result = wordCount(s);
            }
        }

        return result;
    }

    public static void printWordsVertically(String[] input) {
        int longestWordCount = longestWordCount(input);
        int spacesBetweenColumns = 7; // use needed int, or pass as argument
        String formatSpecifier = "%-" + (longestWordCount + spacesBetweenColumns) + "s";
        String[][] words = convertToWordArray(input);

        for (int i = 0; i < longestWordCount; i++) {
            for (int j = 0; j < words.length; j++) {
                if (i < words[j].length) {
                    System.out.printf(formatSpecifier, words[j][i]);
                } else {
                    System.out.printf(formatSpecifier, "");
                }
            }
            System.out.println();
        }
    }

    public static String[][] convertToWordArray(String[] input) {
        String[][] result = new String[input.length][];

        for (int i = 0; i < result.length; i++) {
            result[i] = input[i].trim().split("\\s+");
        }

        return result;
    }
}


Implementing carryless multiplication using normal multiplication

Question 1

So which way should I go?

That depends on what is the assessment criteria. Three basic criteria are performance, readability and ease of use.
Readability
That depends on the reader. Knowing that bitwise operators coerce numbers to signed 32 ints the need to clarify this by using Math.imult is mute. Personally operators are more readable than functions, but some argue the opposite. I would opt for the second version.
Ease of use
Is the function easy to use? Can it be misused? Yes and no. The Math.imult is a little easier because it does not rely on coercion and thus handles different number types better.
The second version has a bug that makes its use difficult.
Example of a failure.
clmul_u32_coerced(0b1110000000000, 1.2); // >> incorrect 0b1111001100110
clmul_u32_imult(0b1110000000000, 1.2);   // >> correct 1110000000000

Why does clmul_u32_coerced fail? The reason is that javascript coerces to the left and for numbers to the highest precision. Thus if you have a double in the operation the result will be a double.
To fix  clmul_u32_coerced you need to coerce b to an int32. But this comes at a performance cost (see below) Well I assumed it would be slower, not so the extra line is worth it, even if you pass int's as args.
function clmul_u32_coerced_f(a, b) {
    var prod = 0;
    b |= 0;
    while (a !== 0) {  // Note strict not equal add ~1% performance
        prod ^= b * (a & -a);
        a &= a - 1;
    }
    return prod;
}

Ease of use means that the caller need not worry about type so clmul_u32_imult is the better option, or use the variant above.
Performance
In terms of performance the use of the * operator gives a benefit. This is expected as any function call has overhead that is generally unavoidable. Testing shows the performance comparison.
Tests using double. Note that 32Int coerced fails
Testing Compare clmul(0b1110000000000, 1.2) 400 times. Sorted by performance.
32Int coerced fixed *.: 0.836µs OPS 1,195,472 100% Total 786ms 940 cycles
Math.imul.............: 0.878µs OPS 1,139,002  95% Total 904ms 1030 cycles
32Int coerced **......: 0.973µs OPS 1,028,149  86% Total 1,002ms 1030 cycles

// * Fixed includes the line `b |= 0;`
// ** This call fails to return the correct result

Tests using arguments that are typed as Signed Int32 eg const a = 0b1110000000000 | 0, b = 1 | 0; clmul(a, b); so there is no failure.
Testing Compare clmul(0b1110000000000, 1) 400 times.
32Int coerced fixed *.: 0.358µs OPS 2,791,501 100% Total 1,214ms 1130 cycles
32Int coerced.........: 0.404µs OPS 2,478,225  89% Total 1,114ms 920 cycles
Math.imul.............: 0.525µs OPS 1,903,171  68% Total 1,497ms 950 cycles

// * Fixed includes the line `b |= 0;`

Thus the test device can do 2,791,501 * 400 ~= 1,116,600,400 clmul's a second. Not bad for Javascript on a 1.60GHz Core.
Question 2

Or perhaps there are better ways entirely?

In javascript there is no easy better way. The functions performance is dependent on the number of bits in a. The operation b * (a & -a) lets you shift b via a multiplication. However if you could get the bit position of (a & -a) then you could use b << bitPos(a & -a) which would be quicker if bitpos had no overhead.
Consider the following variation that avoids the multiplication by shifting b and xoring it with the product.
function clmul_u32_b(a, b) {
    var p = 0;
    while (a > 0) {
        while((a & 1) === 0) {
            a >>= 1;
            b <<= 1;
        }
        p ^= b;
        a >>= 1;
        b <<= 1;
    }
    return p;
}

The problem is that its performance is dependent on the position of the highest bit in a. Thus with four bits at the top it runs at a poor 35% of your fixed coerced version
Testing Compare clmul(0xF000000, 1).
32Int coerced.: 0.520µs OPS 1,924,528 100% Total 530ms 1020 cycles
Shifting......: 1.497µs OPS 667,984  35% Total 1,467ms 980 cycles

But swap the arguments and the table is turned upside down out performing all other versions with ease.
function clmul_u32_b(b, a) {  // swapped args
    ... code see above snippet
    return p;
}

Results
Testing Compare clmul(0xF000000, 1).
Shifting swap.: 0.188µs OPS 5,324,813 100% Total 563ms 1000 cycles
32Int coerced.: 0.521µs OPS 1,918,526  36% Total 1,564ms 1000 cycles

You may think, why not add a line that swaps the arguments, ensuring that a is less than b allowing for the least number of shifts. This does not work. A JS statement will force a cache miss and you lose any benefit.
Conclultion
In terms of ease of use, readability (4+ years JS experience reader), and performance your coerced version with the extra line to force b to an int has in my view the best for all 3 criteria.
// includes the line b |= 0
function clmul_u32_coerced(a, b) {
    var prod = 0;
    b |= 0;
    while (a != 0) {
        prod ^= b * (a & -a);
        a &= a - 1;
    }
    return prod;
}

Though the shifting version I present can in a best case out perform by a factor of 3, the best case is rare and any code to select for best cases will result in an overall performance loss.
Notes on testing

A call is via a function that grouped function calls by 400 see below.
Calls are run in strict mode.
Calls have been allowed to run until optimisations complete (eg testing waits till times are stable before logging time)
Device and setup "Chrome Version 70.0.3538.102 (Official Build) (32-bit)" on a  "Win10 CPU i7 Q720 @1.6GHz" laptop

function call(a, b) {
    var i = 25;
    while (i--) {
        clmul_u32(a, b);
        clmul_u32(a, b);
        clmul_u32(a, b);
        clmul_u32(a, b);
        clmul_u32(a, b);
        clmul_u32(a, b);
        clmul_u32(a, b);
        clmul_u32(a, b);
        clmul_u32(a, b);
        clmul_u32(a, b);
        clmul_u32(a, b);
        clmul_u32(a, b);
        clmul_u32(a, b);
        clmul_u32(a, b);
        clmul_u32(a, b);
        clmul_u32(a, b);
    }
}

In javascript the performance landscape is in constant flux, browser version changes can have significant changes to performance comparisons, and not always positive. If performance is important than you must monitor performance for each browser update, and use code that is tuned for each browser's type.


Given a sorted (increasing order) array, write an algorithm to create a binary tree with minimal height

Bug 1

if(first<last) {
    return null;
}

This is wrong. It will return a null for the very root of the tree. Change to

if (last - first < 1) {
    return null;
}

Bug 2

int midElement = arr[(first+last)/2];
Node newNode = new Node(arr[midElement]);
newNode.left = addToTree(arr, first, midElement-1);
newNode.right = addToTree(arr, midElement+1, last);

This is wrong too. You should have instead:

int middleIndex = (first + last) / 2;
Node newNode = new Node(arr[middleIndex]);
newNode.left = addToTree(arr, first, middleIndex);
newNode.right = addToTree(arr, middleIndex + 1, last);

Advice 1

if(first<last) {
    ...
}

According to Java coding conventions, you must have a single space after if and before an opening (. Also, each binary operator must have a single space before and after it. Putting things together, you must write

if (first < last) {
    ...
}

Advice 2

I suggest you move the tree node to its own file and declare it non-public. Also, I suggest you roll a public tree type that can validate that data is traversed in-order in the same order as the elements in the input array.

Alternative implementation

IntBinaryTreeNode.java

final class IntBinaryTreeNode {

    private int datum;
    private IntBinaryTreeNode leftChild;
    private IntBinaryTreeNode rightChild;

    IntBinaryTreeNode(int datum) {
        this.datum = datum;
    }

    int getDatum() {
        return datum;
    }

    IntBinaryTreeNode getLeftChild() {
        return leftChild;
    }

    IntBinaryTreeNode getRightChild() {
        return rightChild;
    }

    void setLeftChild(IntBinaryTreeNode leftChild) {
        this.leftChild = leftChild;
    }

    void setRightChild(IntBinaryTreeNode rightChild) {
        this.rightChild = rightChild;
    }
}

IntBinaryTree.java

import java.util.function.Consumer;

/**
 * Implements a simple binary tree in which each node contains an integer. This
 * implementation does not enforce any order so it is not a binary search tree.
 */
public class IntBinaryTree {

    private final IntBinaryTreeNode root;

    IntBinaryTree(IntBinaryTreeNode root) {
        this.root = root;
    }

    public void inOrderTraversal(Consumer<Integer> consumer) {
        inOrderTraversal(root, consumer);
    }

    private void inOrderTraversal(IntBinaryTreeNode node,
                                  Consumer<Integer> consumer) {
        if (node == null) {
            return;
        }

        inOrderTraversal(node.getLeftChild(), consumer);
        consumer.accept(node.getDatum());
        inOrderTraversal(node.getRightChild(), consumer);
    }
}

IntArrayToBinaryTreeConverter.java

    public final class IntArrayToBinaryConverter {

    public IntBinaryTree convert(int[] array) {
        IntBinaryTreeNode root = convert(array, 0, array.length);
        return new IntBinaryTree(root);
    }

    /**
     * Converts a range {@code array[fromIndex], ..., array[toIndex - 1]} into
     * a binary search tree.
     *
     * @param array     the array of integers to convert into nodes.
     * @param fromIndex the starting, inclusive index of the range to convert.
     * @param toIndex   the ending, exclusive index of the range to convert.
     * @return
     */
    private IntBinaryTreeNode convert(int[] array,
                                            int fromIndex,
                                            int toIndex) {
        int rangeLength = toIndex - fromIndex;

        if (rangeLength < 1) {
            return null;
        }

        int middleIndex = fromIndex + ((toIndex - fromIndex) >>> 1);
        IntBinaryTreeNode node =
                new IntBinaryTreeNode(array[middleIndex]);
        node.setLeftChild(convert(array, fromIndex, middleIndex));
        node.setRightChild(convert(array, middleIndex + 1, toIndex));
        return node;
    }
}

Main.java

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter the array length: ");
        int arrayLength = scanner.nextInt();
        System.out.print("Enter all the array components: ");
        int[] array = new int[arrayLength];

        for (int i = 0; i < arrayLength; ++i) {
            array[i] = scanner.nextInt();
        }

        IntBinaryTree tree =
                new IntArrayToBinaryConverter().convert(array);

        tree.inOrderTraversal(System.out::println);
    }
}


C#/Design related comments

Use small-letters for passing arguments.
Put your comments (The <summary> ) about the class on top of the class definition, not the field.
The way of using # regions is not really done the way you do in C# usually. There should be a description of the region right after the region on same line.
Use C# comments styling when commenting classes, methods, their parameters.
There is not much sense in designing Heap class that stores just a single integer (heap size). You could simply have public static methods (utility methods) for that purpose, because it seems none of your methods really need to store a state
If you design this as a Heap, depends on use-cases you might want to design Push/Pop methods and store the underlying array in the class. Then having a class would make sense.
Try to use C# Generics instead of strongly defined int. This way you can make your code re-usable for other types (e.g. short) and/or for any object that implements IComparable (check out MSDN for more info on these).

Where to use Heap.

In addition to sorting you can use Heap as PriorityQueue.
If you add Push/Pop methods and slightly modify the implementation, then it can serve as a PriorityQueue, which allows you to add elements(any object that implements IComparable) in random order, and the higher/lower ones will get to the top/bottom of the queue. You can go even further by designing another method - Update(...), which can modify the priority of an element (technically you could implement it by removing the old value from queue and then adding the updated value back to the queue).

Didn't validate your code correctness, but you can/should validate it by testing on some regular and corner cases etc.


Did I convert this C++ class to Common Lisp correctly?

Code review - mostly style

You did a litteral translation from C++ to CL that seems good. I have some stylistic issues with it:

(defclass training-data ()
  ((training-data-stream :reader training-data-stream
                         :writer |set training data stream (using a funky    name)|
                         :initarg :training-data-stream)))

I guess |set training data stream (using a funky    name)| is an attempt at obfuscating the writer method, so that you can have a kind of "private" setter. Don't do that.

:writer is optional: if you don't specify it, you won't generate a specific setter for your slot. You can always use slot-value to alter a slot. However, I don't recommend this appropach.
You can define a :accessor method, which acts as both a reader and a writer method (resp. (my-accessor instance) and (setf (my-accessor instance) value)). Since your C++ field is private and has no public getter/setter, this is an appropriate approach:

Define only an accessor, say training-data-stream, and
Do not export the training-data-stream symbol from your package.
Visibility is handled at package level in CL.

Your initarg could be made shorter: it is used when making an instance of a training-data class, so :training-data-stream is redundant, just use :input-stream (:stream would be too vague).

Then...

;;; initialize-instance :after -- This is your 'constructor' code.

(defmethod initialize-instance :after ((td training-data)
                                       &key
                                       training-data-stream
                                       &allow-other-keys)
  ;; Initialize the slot.

So far, so good; just rename training-data-stream as input-stream.

  ;; Note that 'opening' a stream, as it is implied by the C++ class
  ;; definiton and leaking the open stream handle is very impolite.

Your own comment highlights that

the original C++ class might not be good at following C++ best practices (RAII, for example), and
you are doing a verbatim clone of the C++ class instead of having a more idiomatic CL approach. Since you are just copying an existing codebase in order to understand it, it is not so bad. Maybe you could try to refactor it later, as an exercise.

Besides, "impolite" is not the word I would have used, because it is not accurate (it sounds as-if you ignore, or side-step, the real problems behind leaking resources).

Hereafter, your let binding is useless:

  (let ((is (etypecase training-data-stream
              ((string pathname) (open training-data-stream :direction :input))
              (stream (if (input-stream-p training-data-stream)
                          training-data-stream
                          (error "Not an input stream.")))))
        )
    (|set training data stream (using a funky name)| is td)
    ))

In other word, (let ((x (something))) (use x)) could simply be (use (something)).
Moreover, you changed the original behavior by allowing the constructor to be initialized with streams, and not only strings (was it necessary?).

Note that instead of etypecase, which is good, you could also let initialize-instance call a new generic method, say initialize, that dispatches on the type of the stream, either string or stream (we can't dispatch on &key arguments, otherwise initialize-instance would suffice).

    (setf (training-data-stream td)
          (etypecase input-stream
            ((string pathname) (open input-stream :direction :input))
            (stream (if (input-stream-p training-data-stream)
                        training-data-stream
                        (error "Not an input stream."))))))

Your objective

  I'm trying to learn Neural Networks by converting a C++ nn to Lisp

Learning high-level concepts like neural networks using an implementation like the one you linked is not very effective, in my opinion.

Even though you have difficulties with C++, this is not the language that prevents you from understanding neural networks; for example:

    Layer &outputLayer = m_layers.back();
    m_error = 0.0;

    for (unsigned n = 0; n < outputLayer.size() - 1; ++n) {
        double delta = targetVals[n] - outputLayer[n].getOutputVal();
        m_error += delta * delta;
    }
    m_error /= outputLayer.size() - 1; // get average error squared
    m_error = sqrt(m_error); // RMS

Those are just math operations, and the fact that they are written in C++ is not what makes them difficult to grasp. In fact, I never really studied neural networks and all the above code is cryptic, even though I am familiar with the language.

I doubt that rewriting it in CL will help you.

What you need first is a book and tutorials for high-level concepts.
Experiment with a easy-to-use library, like for example PyBrain, which has a good documentation.

Maybe when you have a good understanding of neural networks, you can go back to the linked code and inspect the implementation to see how it was designed, and why.


Checking for an undefined nested variable in a JS object

There's a lot of ways to do this. Here's an exotic (and costly) one:

if(((json || {}).data || {}).formkeys !== void 0){}

As commented, a try-catch will work

// JS has function scope. foo starts its life as declared but undefined
// If the try-catch fails, foo will remain undefined.
try{ var foo = json.data.formkeys; } catch(){}

if(foo !== undefined){}

A longer and possibly better way to do it is to create a resolver function. Most frameworks I have encountered use some form of this in their getter functions so that getting a value from a half-complete path will just return undefined instead of throwing midway.

function resolve(path, root){
  root = root || window;
  return path.split('.').reduce(function(parent, child){
    // A quick check for brevity. You can replace this with a better check
    // and return logic.
    return parent && parent[child];
  }, root);
}

var foo = resolve('json.data.formkeys');

if(foo !== undefined){}


Overall, LGTM.
A protection against negative indices being passed to parent doesn't worth the effort. parent is a private method, so you are in control of the indices at all times. A strong indication that the protection is not needed is the fact that insert doesn't bother to test the return value for validity.
Along the same line, left() and right() returning -1 doesn't look like a good idea. Effectively, you test the same condition twice: ((2 * i) + 1) < heap.size() - 1 in left, and l != -1 in heapify.
Notice that anytime right is valid, left is also valid. That allows a certain optimization (see below).
C++ is very good in recognizing tail recursion and optimizing it out. I strongly recommend to do it explicitly anyway.
Combining the three bullets above, consider

void heapify(int i)
{
    while ((r = right(i)) < heap.size()) {
        follow your swapping logic
    }

    if ((l = left(i)) < heap_size()) { // No need to loop - it may only happen once!
        if (heap[l] < heap[i]) {
            std::swap(heap[i], heap[l]);
        }
    }
}

MinHeap::heapify is a misnomer, and somewhat confusing. Usually heapify refers to the process of turning an array into a heap. Your method is normally called sift_down.
Too many comments to my taste.


if (condition == true)

Instead of

if (testDataGenerated == true) {

just write

if (testDataGenerated) {

Rewriting ifs

You can move your checks to the top of the method like this to avoid nested ifs:

    if (!testDataGenerated) {
        WriteTo.testgoal(nameTestcase, TestgoalState.NOK,
                "testdata is not generated");
        throw new Exception("NO TESTDATA GENERATED");
    }
    if(!currentPage){
        WriteTo.testgoal(nameTestcase, TestgoalState.NOK,
                "Page synchronize failed");
        throw new Exception("PAGE SYNCHRONIZE FAILED");
    }
    this.verifyEventDetailFull();