Finding shortest distance between a point and a surface using Lagrange Multipliers

As far as I can tell what you do is a static optimization with constraints. Two comments on that:

1) Matlab provides fmincon to solve exactly this type of problem.

2) You use matlab, which is a numerical calculation program and make extensive use of symbolic variables. Your main loop manipulates a symbolic variable l. I suggest you research ways to replace the syms line completely. The direction I can see is using anonymous functions, ie something like

k1 = 3;
k2 = 10;
k3 = -7;
plane = @(x,y,z) k1*x+k2*y+k3*z;

this is a very powerful concept. You can set the parameters by other variables of course and in the end define your function (without symbolic variables!). You can even hand the function over to another function! e.g. solution = minimizerfun(plane,point);, and inside the minimizerfun you call the plane dist = plane(x,y,z) - start_point;! Surely, this can be vectorized plane = @(x) k1*x(1)+k2*x(2)+k3*x(3); which is close to what you should use here.

Mupad is some extension of matlab, mex is their term for externally compiled stuff (like C/Fortran programs compiled for matlab). My best bet is, that the symbolic toolbox uses some parts of this "external part". - But even if I'm wrong here, the toolbox is VERY slow compared to numerical calculation (which matlab is meant for)!


Compare File with ignore some line/last line

There is no need for python here, you can use the head command to filter out the last line of a file:

diff <(head -n -1 "Golden_File") <(head -n -1 "cp.log")


Rendering content conditional on the authentication state of the user

One way you could handle this, because it's server side rendering, is perform whatever checks you wish to perform in the controller, and then route to a ViewModel that has the relevant included pages. That results in having more code to maintain, however, it enables you to have partial view rendering as well.

Edit:

I thought I would expound on this idea some. It appears to be what you are doing with the AuthenticatedUserPanel and UnauthenticatedUserPanel.

I don't see a problem with this approach. At the end of the day, you have to put this logic somewhere. Some purists may so no logic in the view. That's fine. My approach, in this situation, is to create all the necessary components, and render a different view (or ViewModel) based on some user context. The benefit to this approach is that the user can only see UI elements for actions they are able to perform, or only view data they have permission to view. It also enables you to (easily) customize the action links for subsequent navigation. The challenge I usually have with this approach is designing a view that is relevant for each type of user.

In closing, I don't see any problem with putting some of this logic in the view, but I also tend to build smaller sites. This is largely a matter of taste, and it's important to do it the same way across the project. In trying to design the way that you will handle this sort of scenario, I would consult other areas of the project that are doing it today. If there are none, then it's usually a good time to discuss with other members of the team how you will handle this case, because you will undoubtedly encounter it again.

I hope my post was helpful, and wish you the best with the project :)


BinarySearch Tree implementation & traversals

Here are a few things you can do to improve this:

You don't specify visibility of your methods or variables.  Presumably you want your variables to be private, but I'm not sure which of your methods you want public or not. I imagine you don't want setLeftChild or setRightChild to be public since you can't enforce your ordering constraints if anyone can just change children when they feel like it.
Both setLeftChild and setRightChild will throw NullPointerExceptions when passed a null value. You want != instead of == in your check.
Do your nodes need references to their parents?
In your Traversals class you have nodes named parent, but you are actually referring to the root node of your tree. I would rename that.
You don't need to create the other three TreeNode classes since you only use them to get the value that you passed into them when you call insertInOrder.  Just call insertInOrder with the values you want.
You shouldn't pass in the parent parameter to your traversal methods. These are instance methods and can just refer to the member variables directly.
Initialize size once.  Currently you set it to 0 and then 1.
I'm assuming you have plans to use size later on. Otherwise you can just remove it entirely.


First, I'm going to go through and do a little nitpicking.

In the procedural version, why is everything indented except for main?

When you are closing the object in the object version, the closing brace should be in the same column as the beginning line of the object.

So this:

var pageLoader = {

      ...

};                     <---

Rather than this:

var pageLoader = {

      ...

    };                 <---

Once you change this, you'll notice that the things inside the object are indented two indents, so I recommend knocking off one indent.

How much you are indenting is all messed up:

You are indented 8 spaces (2 indents) in the object.
You indented everything else 4 spaces (1 indent).
You indented the code inside functions 2 spaces (1/2 indent).

I recommend that you choose one and stick with it (I use 1 indent).

You don't need a return at the end of the function event listener (onclick); where is that false going to get returned to?

There is nothing inside your init functions... why are these here?

Other than that, your "translation" from procedural to object seems fine; all you basically did was stick the methods and variables in an object and add pageLoader. to the beginning of a few things.

I think that the code is good in an object because, as you said, it aids organization. However, since I don't know the full/rest of the code, I can't be sure if this is the best approach for your situation.


DAO to create, update, and delete a project

Nitpick

 public boolean create(Project project)  {
 String id = UUID.randomUUID().toString().toUpperCase().replace("-", "");
 project.setId(id);

The last two lines should be indented relative to the method declaration.  Perhaps this was just a copy/paste error that doesn't exist in the original code.

try

    try {
        Class.forName("org.h2.Driver");
        Connection connection = DriverManager.getConnection("jdbc:h2:~/dao_db", "sa", "");
        PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO PROJECT VALUES(?, ?,?)");

        preparedStatement.setString(1, id);
        preparedStatement.setString(2, project.getName());
        preparedStatement.setString(3, project.getTrigram());
        int resultSet = preparedStatement.executeUpdate();

        if(resultSet!=0)
        {
            System.out.println("Project created");
            connection.close();
            return true;
        }

        else {
            System.out.println("No project was  created ");
            connection.close();
            return false;
        }

    } catch (ClassNotFoundException | SQLException e) {
        e.printStackTrace();
    }

This is a really long try block, and most of the code doesn't seem to need it.  Also, it doesn't make use of the try with resources, even though it seems to exactly cover the use case.  Instead consider breaking it into two smaller try blocks.

    try {
        Class.forName("org.h2.Driver");
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
        return false;
    }

All this code does is verify that the class exists.  I would actually do this outside a try block, as it seems like a fatal error.  But this version at least isolates the class problem from the SQLException issue, as they have different responses.

    int resultSet = 0;

Technically, the 0 is unnecessary here, as it is already the default.  I find it clearer to initialize it explicitly.  Others disagree.

Removing from the try block will allow it to be used outside the block later.

    try (Connection connection = DriverManager.getConnection("jdbc:h2:~/dao_db", "sa", "")) {
        PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO PROJECT VALUES(?, ?,?)");

        preparedStatement.setString(1, id);
        preparedStatement.setString(2, project.getName());
        preparedStatement.setString(3, project.getTrigram());

        resultSet = preparedStatement.executeUpdate();
    } catch (SQLException e) {
        e.printStackTrace();
    }

Now you don't have to worry about explicitly closing the connection.  The try with resources will handle that automatically no matter how or when you leave the try block.

Note that in the original code, an exception after the connection was made but before the connection was explicitly closed would bypass closing the connection.  You could have used a finally block to work around this, but the try with resources is simpler and more reliable.

    if (resultSet != 0) {
        System.out.println("Project created");
        return true;
    }

    System.out.println("No project was created");
    return false;

This block of code cannot generate either of the caught exceptions.  As such, it does not need to be in the try block.  So go ahead and take it out.

Consistent formatting

There are three common ways to handle a {} block.  You use all three.  Please pick one and stick to it consistently.  Consistent formatting makes it easier to both read and modify the code.

Start and end on the same line:

    } else {

Start and end on separate lines:

    }
    else
    {

Closing } alone:

    }
    else {

Also, note that the second and third versions allow you to put extra blank lines between the braces and the else.  Please don't do that.  When you do that, it obscures that the previous block has an else.  It's much clearer if you treat the braces and the else as one symbol and always write them the same way.  Then the reader can immediately see which block ends and which will continue later.

Personally, I prefer the first form, but all three are in common use.  The Java coding standard also prefers the first form, but some prefer one of the others.  Consistent use of any of them within your code will allow most programmers to adapt.


.attr() can work on all jQuery matched elements at once.

Assuming that performance isn't a concern, I think that the clearest way would be to "reset" all nodes to have a tabIndex of -1 first.

var leaves = $(".leaf");
var trees = $(".tree");

$(".my-class").on("click", function(e) {
    leaves.add(trees).attr("tabIndex", -1);

    var selected = $(e.target).hasClass("leaf") ? leaves : trees;
    selected.attr("tabIndex", 1);
});


Pass logger dependency to PostSharp aspect

You're reading and writing the GetLogger static field on multiple threads simultaneously, so the shown code is not thread-safe. You can mark the field with the [ThreadStatic] attribute to have a unique value on each thread.

Also, you don't need to mark the field as [NonSerialized] because static fields are not serialized anyway (https://stackoverflow.com/questions/3903079/does-default-serialization-in-c-sharp-serialize-static-fields).


Enabling or disabling a login view based on authentication state

Short code vs longer code:

Writing shorter code can in certain situations be a good thing. But in your case I would not recommend this as it makes your code hard to read and/or maintain. Try something like this:

//I don't know the return-type of getLoginParamInfo(), hence the "LoginState".
LoginState parameterInfo = DataHolder.i().getLoginParamInfo();
boolean isLoggingIn = parameterInfo.equals(LoginState.stateLoggingIn);
getView().findViewById(R.id.login_button).setEnabled(isLoggingIn);

If you want, you can combine the first two lines into one. This gives following code:

boolean isEqual = DataHolder.i().getLoginParamInfo().equals(LoginState.stateLoggingIn);
getView().findViewById(R.id.login_button).setEnabled(isEqual);

But again, pumping al code in one line is certainly not a good practice.

Method naming:

Giving your functions/methods names like i() is definitly not good practice. It doesn't tell anything about what it does and what it eventually returns.


Check if strings from a list in a text and return first longest match

You can use an early return in your function to get rid of a few lines, because python's default return value is already None:

from operator import itemgetter

def get_item(text, bindings):
    text = text.lower()
    matches = []
    for phrase, item in bindings:
        index = text.find(phrase)
        if index != -1:
            matches.append((phrase, item, index))
    if matches:
        matches.sort(key=lambda x: len(x[0]), reverse=True)
        matches.sort(key=itemgetter(2))
        return matches[0][1]

Algorithm wise, I'm not sure this code is up to the specification you wrote. You said, phrases should be preferred over single words. However, you only sort by length. Therefore

bindings = [('i am a', 'item1'), ('terminator', 'item2')]
text = 'I am a terminator'
print get_item(text, bindings)

will print 'item2' and not 'item1', even though it is a single word and the other binding is a phrase. Maybe also use something like len(x[0].split()) to give you the number of words as the sort key?

Also, your code scales with something like \$\mathcal{O}(m)*\mathcal{O}(n*k)\$, where \$m\$ is the number of defined bindings, \$n\$ is the length of the text and \$k\$ is the average length of the phrases in the bindings. I'm not sure whether there is a better algorithm, though.


Continually process results of multi-thread worker

I think you are misunderstanding the concept of Executor (and ExecutorService). It already acts as a queue, so you don't need to maintain a queue of your own. Your code actually creates one job per thread, and every job processes multiple questions from the queue. Instead, you should rather have one task per question:

Collection<String> questions = ...;
for (String question : questions) {
    executor.execute(new QueryTask(question));
}

Also note that you're calling your class QuestionThread. But it's not a thread, it's a task! Please always differ between task and thread: A task is a piece of work that should be done, while threads are a mechanism to execute tasks in parallel.

Your QueryTask should only execute one single query and return it as a result:

class QueryTask implements Callable<String> {
    private final String question;

    public QueryTask(String question) { this.question = question; }

    public String call() {
        // maybe long running
        // get and return answer!
    }
}

The processing part is flawed too, because you're doing a busy-wait there! Instead, you can solve your problem very elegant using a CompletionService. The full algorithm will then be as follows:

public void query(ExecutorService executor, Collection<String> questions, Consumer<String> answerConsumer) throws InterruptedException, ExecutionException {
    CompletionService ecs = new ExecutorCompletionService(executor);
    // execute all tasks
    for (String question : questions) {
        ecs.execute(new QueryTask(question));
    }

    // wait for tasks to complete and hand them over to consumer
    final int size = questions.size();
    for (int i = 0; i < size; i++) {
        answerConsumer.accept(ecs.take().get());
    }
}

(The interface Consumer exists since Java 8; it can easily be replaced by something similar).

Appendix: Calling query from UI thread

Note that the calling thread is blocked until all questions and answers are processed. In case this is the UI thread, it will not be able to run UI events in the meantime. As a result, your UI will "freeze" (it will not react to any user input nor doing repaints of dirty UI regions).

To solve this problem, the call to query must be asnychronous and the consumer must put the result into a UI updating task and hand it over to the UI thread (how this exactly works depends on the UI framework you are using. SWT: Display.(a)syncExec(...), Swing: SwingUtilites.invokeLater(...), JavaFX: Platform.runLater(...), ...). The following example will assume you're using JavaFX (it also uses Java 8 lambda expressions):

public void queryAsynchWithUIUpdate(Collection<String> questions) {
    Executor e = Executors.newSingleThreadExecutor();
    e.execute(() -> {
        ExecutorService executor = Executors.newWorkStealingPool();
        query(executor, questions, answer -> {
            Platform.runLater(() -> {
                // update UI using answer, e.g.:
                answerTextField.setText(answer);
            });
        });
        executor.shutdown();
    });
    e.shutdown();
}


It is fine and very convenient to keep the database handler as a property.  However, you should pass it in the constructor via dependency injection, rather than call it's factory method inside the class.  This can ease unit testing when you need to mock a database connection object.

public function __construct($db) {
    $this->db = $db;
}


Having two abstract (static inner) classes within the interface they implement

As a matter of principle,
an interface definition should not include implementation.
These abstract classes are by definition implementations,
even though they are mostly empty and seemingly harmless.
As such,
yes, you should move the inner abstract class definitions outside.

There are different kinds of "outside":

Outside of the class but in the same file
Outside of the class in other file(s)

If they are in the same file, they cannot be public.

If they are in different files, they can be public.

Either way, to achieve the cleanest separation of interface and implementations,
I recommend to move them to different file(s).


This implementation is great and works well, but you should add an "escape door" when no path is found.

For instance, remove these two lines:

$_distArr[4][5] = 6;
...
$_distArr[6][5] = 9;

If you comment both lines, you enter an infinite loop.

To avoid this problem, I think you can add these lines right before the "calculating while" loop:

if (!array_key_exists($b, $S)) {
    echo "Found no way.";
    return;
}

Then you're set; no infinite loop!


Converting an already-uploaded file and saving it to a model's FileField

Clean, easy to understand code. However:

Never hide errors with a bare except. Change

try:
    ...
except:
    return False

into

try:
    ...
except (IOError, AnyOther, ExceptionThat, YouExpect):
    logging.exception("File conversion failed")

Also, unless you need to support Python 2.4 or earlier, you want to use the files context manager support:

with open('%s.flv' % output_file, 'r') as f:
    filecontent = ContentFile(f.read())
    video.converted_video.save('%s.flv' % output_file,
                               filecontent,
                               save=True)
remove('%s.flv' % output_file)

That way the file will be closed immediately after exiting the with-block, even if there is an error. For Python 2.5 you would have to from __future__ import with_statement as well.

You might also want to look at using a temporary file from tempfile for the output file.


capturing counts of open items between dates

In looking at your query, I think there may be a few things you can do to improve your performance.  The first is that you can aggregate your ticket_table ahead of time based on the request interval. Second, unless it is needed for the logic that you redacted, I would avoid using the CTE once you start doing the real logic. You may be depriving the optomizer of information it could use.  You might try something like the following query:

WITH query_interval AS
(
  SELECT TO_DATE('09/01/2012', 'MM/DD/YYYY') AS START_DATE, TRUNC(SYSDATE) AS END_DATE
  FROM DUAL
),
interval_dates AS
(
  SELECT qi.start_date + ROWNUM - 1 AS I_DATE
  FROM query_interval qi
  CONNECT BY ROWNUM < qi.end_date - qi.start_date
)
SELECT i.i_date, SUM(sub.cycle_count)
FROM interval_dates i
LEFT JOIN (SELECT GREATEST(TRUNC(tt.start_date), qi.start_date) AS OPEN_DATE,
                 LEAST(TRUNC(tt.end_date)-1, qi.end_date) AS CLOSE_DATE,
                 COUNT(*) AS CYCLE_COUNT
          FROM ticket_table tt
          CROSS JOIN query_interval qi
          WHERE GREATEST(TRUNC(tt.start_date), qi.start_date) <= LEAST(TRUNC(tt.end_date)-1, qi.end_date)
          GROUP BY GREATEST(TRUNC(tt.start_date), qi.start_date), LEAST(TRUNC(tt.end_date)-1, qi.end_date)) sub ON I_DATE BETWEEN sub.open_date AND sub.close_date
GROUP BY i.i_date
ORDER BY i.i_date;

Most of this is similar to what you already had, but there are some differences.  First you notice that I added a CTE with just the interval.  This allows me to perform the aggregation that I mentioned earlier.  The aggregation works like this:

First, we limit our search to tickets which were open at some point during our query interval.  That I'm using the GREATEST <= LEAST to determine an overlap between the ticket and the query interval.
We clip tickets that hang over the ends of our search interval.  You really don't care that they are open before your search, just that they are open during your search.
We aggregate all cycles which now have the same start and end dates.

After that, the logic is pretty similar to what you already had.  A left join between the full list of dates and our modified table.  Then instead of using COUNT, we use SUM.


Can XSS or anything else get through this?

Looks safe to me, but I would change the way you request the server. This way, you send many requests to the server and for more then few people using it, the server could be flooded by these requests. It would however require switching txt file for script file. Then you could use so called long poll.

You are probably wondering what long poll is and how it works. Long poll is technique where client opens connection to the server and leaves it open. When new message comes, server sends it and closes the connection. Trick is, client immediately opens new connection. Same happens when old connection times out.

Problem here is, when you use PHP on server side, it just executes some code and closes the connection. So, you have 2 possibilities: Best idea is to use server written in node.js, which is made for such things (and there are other advantages like that you don't have to store the message anywhere, you just recieve it and immediately send it to all clients and other...). If you want or have to use PHP, then you must use the sleep() function. Then, you have while loop, that each for example 200 miliseconds check for new message in database and either sends it or sleeps for another 200 miliseconds.

If you want to try, here is part of my client code which takes care of server communication:

//function, that returns right kind of AJAX object based on browser
//I don't have worst case scenario (AJAX not supported) here, because I usually check for required support at the beginning of the script
function createAjax() {
    if (window.XMLHttpRequest) {
        return new XMLHttpRequest();
    } else {
        return new ActiveXObject('Microsoft.XMLHTTP');
    }
}

/*
Class that takes care of receiving new messages from server
PARAMS:
    longPollServerURL - string - URL of server file, which acts as long poll server
    lastIdGetURL - string - URL of txt file, where last message id is saved
    newMessageCallback - function - callback to get called when new message is received
        it is called with 4 params:
            id of the message, time when the message was sent as unix timestamp,
            nickname of the person who sent it, message text itself
*/
function ChatLongPoll(longPollServerURL, lastIdGetURL, newMessageCallback) {
    var mainContext = this,
        httpRequest = createAjax();

    //function that starts long poll and sets what should happen when connection ends
    this.startLongPoll = function() {
        httpRequest.onreadystatechange = function() {
            if (httpRequest.readyState == 4) {
                var _decodedResponse = JSON.parse(httpRequest.responseText);
                if (_decodedResponse.status == 'new') {
                    for (var i = 0; i <_decodedResponse.messages.length; i++) {
                        newMessageCallback(_decodedResponse.messages[i].id, _decodedResponse.messages[i].time, _decodedResponse.messages[i].from, _decodedResponse.messages[i].messageText);
                        mainContext.lastMessageId = _decodedResponse.messages[i].id;
                    }
                }
                mainContext.openLongPoll();
            }
        };
        mainContext.openLongPoll();
    };

    //function that opens connection to the server
    this.openLongPoll = function() {
        httpRequest.open('GET', longPollServerURL + '?lastId=' + mainContext.lastMessageId, true);
        httpRequest.send(null);
    };

    //function that downloads ID of last message sent
    this.getLastMessageId = function() {
        var _id = false;
        httpRequest.onreadystatechange = function() {
            if (httpRequest.readyState == 4) {
                _id = httpRequest.responseText;
            }
        };
        httpRequest.open('GET', lastIdGetURL, false);
        httpRequest.send(null);
        return _id;
    };

    this.lastMessageId = this.getLastMessageId();
}

/*
Class that takes care of sending messages to server
PARAMS:
    newMessageServerURL - string - URL of file, which saves and validates the message
    callback - function - function to handle response from server (ok / wrongFormat / noName / ... status etc... (that depends on how you make your server))
*/
function ChatSendMessage(newMessageServerURL, callback) {
    var httpRequest = createAjax();

    httpRequest.onreadystatechange = function() {
        if (httpRequest.readyState == 4) {
            callback(JSON.parse(httpRequest.responseText));
        }
    };

    //function that sends the message to server and saves it to httpRequest.lastMessage
    this.sendMessage = function (from, messageText) {
        var L_postData = 'from=' + encodeURIComponent(from) + '&messageText=' + encodeURIComponent(messageText);

        httpRequest.lastMessage = messageText;

        httpRequest.open('POST', newMessageServerURL, true);
        httpRequest.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
        httpRequest.send(L_postData);
    };
}

/*
Short class that just simplifies access to those 2 classes before
PARAMS:
    newMessageServerURL - string - URL of file, which saves and validates the message
    longPollServerURL - string - URL of server file, which acts as long poll server
    lastIdGetURL - string - URL of txt file, where last message id is saved
    messageReceivedCallback - function - callback to get called when new message is received, it is called with 4 params: id of the message, time when the message was sent as unix timestamp, nickname of the person who sent it, message text itself
    sentMessageCallback - function - function to handle response from server (ok / wrongFormat / noName / ... status etc... (that depends on how you make your server))
*/
function ServerCommunicator(newMessageServerURL, longPollServerURL, lastIdGetURL, messageReceivedCallback, sentMessageCallback) {
    var longPoll = new ChatLongPoll(longPollServerURL, lastIdGetURL, messageReceivedCallback);
    var sendMessage = new ChatSendMessage(newMessageServerURL, sentMessageCallback);

    this.sendMessage = sendMessage.sendMessage;
    this.startLongPoll = longPoll.startLongPoll;
}


Code to generate a dictionary from two lists

zip and itertools.zip_longest do exactly what you are looking for, you only need to choose between the two depending on the lengths of the lists:

def generator(listKeys, listWords):
    if len(listKeys) > len(listWords):
        zipped = zip_longest(listKeys, listWords)
    else:
        zipped = zip(listKeys, listWords)
    return dict(zipped)

This can even be shortened to

def generator(listKeys, listWords):
    my_zip = zip_longest if len(listKeys) > len(listWords) else zip
    return dict(my_zip(listKeys, listWords))

Note that generator is not a good name for this function as the word generator has a particular meaning in Python.


Display the relative time difference between two dates

I guess you have a bug here:

$ret = $diff->format('%y years, %m months, %a days, %h hours, %i minutes, %S seconds');

%a should be %d. With %a

time_elapsed("2012-07-08 11:14:15.889342", "2014-09-10 13:15:17.889342");

prints total number of days:

2 years, 2 months, 794 days, 2 hours, 1 minute, 02 seconds

Using %d changes 794 days to 2 days.
Another approach is iterating through of an array of units:

function time_elapsed2($start, $end) {
    $start = new DateTime($start);
    $end = new DateTime($end);

    $interval = $end->diff($start);

    $units = array(
        "%y" => sp("year", "years"),
        "%m" => sp("month", "months"),
        "%d" => sp("day", "days"),
        "%h" => sp("hour", "hours"),
        "%i" => sp("minute", "minutes"),
        "%s" => sp("second", "seconds")
    );

    $result = array();
    foreach ($units as $format_char => $names) {
        $formatted_value = $interval->format($format_char);
        if ($formatted_value == "0") {
            continue;
        }
        $result[] = get_formatted_string($formatted_value, $names);
    }

    return implode(", ", $result);
}

function sp($singular, $plural) {
    return array("singular" => $singular, "plural" => $plural);
}

function get_formatted_string($formatted_value, $names) {
    $result = $formatted_value . " ";
    if ($formatted_value == "1") {
        $result .= $names["singular"];
    } else {
        $result .= $names["plural"];
    }
    return $result;
}

(In production code I'd use constants instead of singular and plural.) The array also helps if you want to translate your page to other languages.


VBA Excel - Conditional Formatting Colour Grab

I can't test this code to see if it works because I have 2007 on this computer. But, I do have some things to add.

First things first, I have no idea what the variables are for - there is no description. You also don't have Option Explicit on and none of the variables are dimed. That's the first thing to address.

What is q? It iterates 1 to 26, but I don't see it being used anywhere. You're just doing the entire thing 26 times? Why? Oh, because you're using .Select - I'll get to that.

The same thing goes to i.

You use sCol = Split(ActiveCell.address,"$")(1) to get the column letter? Why not just get the column with ActivecCell.Columns?

Speaking of ActiveCell - why are you using it? Why not get a variable like Dim RangeToTest and set it to Sheets(1).Range("A1:A26") or whatever? At least Set RangeToTest = Selection - but using selection and activecell is generally bad form.

Instead this entire thing could be (using whatever numbers you need to use)-

  Dim RowNumber As Long
  Dim ColumnNumber As Long

  For RowNumber = 1 To 100
    For ColumnNumber = 1 To 26
        'do stuff to Cells(RowNumber, ColumnNumber)
    Next ColumnNumber
  Next RowNumber

If you're not sure you can do something like this to get what you need -

  Dim RowNumber As Long
  Dim ColumnNumber As Long
  Dim LastRow As Long
  LastRow = Cells(Rows.Count, "A").End(xlUp).Row
  Dim LastColumn As Long
  LastColumn = Cells(1, Columns.Count).End(xlToLeft).Column

  For RowNumber = 1 To LastRow
    For ColumnNumber = 1 To LastColumn
        'do stuff to Cells(RowNumber, ColumnNumber)
    Next ColumnNumber
  Next RowNumber

I can't tell what you're doing here -

sCol = Split(ActiveCell.Address, "$")(1)
sColNum = sCol & 1
Range(sColNum).Select

For i = 1 To 100

sColNum = ActiveCell.Address

From what I can tell you get the column, set sColNum (is that a string? A range?) to the first cell in the column, then you select the Range of the SColNum (string?). And then you set the sColNum that was selected to its own .address? What are you accomplishing here? Seems like it has something to do with your i loop - which can be eliminated and you can just use the example I gave, or something similar.

Now you check for .Interior.Color = 255 and if it's found, you msgbox where it was found with Y as activecell.address when sColNum is already the activecell.address. You don't need Y to say the least.

Instead you could do something like this -

Dim FindInteriorColor As Long

  FindInteriorColor = 255

  If Cells(RowNumber, ColumnNumber).DisplayFormat.Interior.Color = FindInteriorColor Then
    MsgBox ("Red Cell Found at " & Cells(RowNumber, ColumnNumber))
  End If

Now all you need to do is change the variable FindInteriorColor to whatever the value is of the color you want to find. You'd still need to change your msgbox to say the color, but that could be avoided with an input box or variable or something.

Again, I can't test the actual function of the code, but these are improvements you could make at least, if you want to run through cell by cell looking for something and saying each time it's found. If you want to only find the first one, just put an Exit Sub in the if loop.

In response to your comment - a simple way to get the letter of a column number (in case you need it in the future) is something like -

Sub test()
Dim RowBegin As Long
RowBegin = InStr(2, Cells(1, 200).Address, "$")
Dim ColumnLetter As String
ColumnLetter = Mid(Cells(1, 200).Address, 2, RowBegin - 2)
MsgBox ColumnLetter
End Sub


Immutable recursive binary search of a generic array

I would strive for symmetry:

        match array.[guess] with
        | x when x > target -> search (min) (guess - 1)
        | x when x < target -> search (guess + 1) (max)
        | _ -> guess


Converting an input string to a list of sub lists with numbers

re.sub(r"\(","",data) is not a very good use of regular expressions. You could have more easily achieved the same result with data.replace("(", "").

But since you are already using regular expressions, why not use them to do more:

>>> re.findall(r'\d+,\d+', "(2,2),(6,2),(2,6)")
['2,2', '6,2', '2,6']

This regular expression finds all digits (\d) (allows also multiple digits using +), which are separated only by a comma. Since different pairs also have parenthesis around them, this just gives you a list of the pairs.

By adding parenthesis around the digits, this captures each of them and splits each pair:

>>> re.findall(r'(\d+),(\d+)', "(2,2),(6,2),(2,6)")
[('2', '2'), ('6', '2'), ('2', '6')]

Now all that is left to do is convert them to integers and put it in a function:

def str_to_nbrs(data):
    return [list(map(int, p)) for p in re.findall(r'(\d+),(\d+)', data)]


What compiler are you using? Some implementations of the C++ standard library are better than others for supporting Regex.

Do you really need backreferences? That usually makes regex much slower.

It's very unusual to use a variable with the same name as the variable's type.

You don't need to initialize prefix=string before the loop, it's done first thing inside the loop.

Have you done any profiling of your code to see which lines are slowing it down? It'd be very good to know if the slowness is due to the regex or due to the string concatenation.


RSpec test for handling known IP addresses

I'll use this known_ips somewhere else.

I'm guessing that "somewhere" will still be in a test file. If so you can put this in support file (which is a common patern in RSpec).

# spec/support/ip_list.rb
IP_LIST = [
  # easily to recognize that IP address is first and the location name the second, but you can use your code that uses Hash here
  ['73.53.61.23',   'Seattle, Washington, US'],
  ['8.26.157.16',   'San Francisco, California, US'],
  ['174.112.13.21', 'Mississauga, Ontario, CA']
]

Then on spec_helper.rb (see this example)

# spec/spec_helper.rb
# after the last require
Dir[Rails.root.join("spec/support/**/*.rb")].each { |f| require f }

And in your actual test:

describe WelcomeController, type: :controller do
  it 'geolocalizes the visitor based on the ip' do
    IP_LIST.each do |(ip, location_name)|
      expect(controller.request).to receive(:remote_ip).and_return ip
      get :index
      expect(controller.current_location.name).to eq location_name
    end
  end
end

Note that I nested IP_LIST.each inside the it block, I don't think you need to create one it for each test. This is a personal opinion, I'm not sure what is the best practices here.


Place multiple imports from the same module on one line.
I would heartily recommend against interleaving a trait definition (Modulo) and a struct definition (Mod).
I prefer to not put trait bounds on the trait definition. Those usually want to be a supertrait or just on a trait implementation.
Similarly, I prefer not put trait bounds on a struct definition; just on  on implementation.
There's no need for the Clone bound — it's never used.
I'd make your new "operator" trait match others: Parameterize the right-hand side (Rhs) and the Output as an associated type.
Then you can DRY up your duplicated trait bounds by creating a new trait that has all the other traits as a supertrait.
While you are at it, remove the type parameter T  because you always use it in the same fashion; it might as well be hardcoded.
Place a space around = when restricting associated types in traits.
There's no need for the temp var in the Mod constructor.
Tests. TESTS. TESTS You are so close to already having tests! Your main function can be basically transformed into a sequence of tests. Then the computer can verify them, instead of having to read the output each time. Please give them useful names that describe what each tests, not my stupid sequential names.

use std::ops::{Add, Mul, Sub, Rem};

trait Modulo<Rhs = Self> {
    type Output;

    fn modulo(self, n: Rhs) -> Self::Output;
}

impl<T> Modulo<T> for T
    where T: Add<Output = T> + Rem<Output = T> + Copy
{
    type Output = T;

    fn modulo(self, n: T) -> T {
        ((self % n) + n) % n
    }
}

trait ZMod: Modulo<Output = Self> + Mul<Output = Self> + Sub<Output = Self> + Add<Output = Self> + Rem<Output = Self> + Copy {}
impl<T> ZMod for T
    where T: Modulo<Output = T> + Mul<Output = T> + Sub<Output = T> + Add<Output = T> + Rem<Output = T> + Copy
{}

struct Mod<T> {
    modulo: T,
    i: T,
}

impl<T> Mod<T>
    where T: ZMod
{
    fn new(modulo: T, i: T) -> Mod<T> {
        Mod {
            modulo: modulo,
            i: i.modulo(modulo),
        }
    }
}

impl<T> Add for Mod<T>
    where T: ZMod
{
    type Output = Mod<T>;
    fn add(self, other: Mod<T>) -> Mod<T> {
        Mod::new(self.modulo, self.i + other.i)
    }
}

impl<T> Sub for Mod<T>
    where T: ZMod
{
    type Output = Mod<T>;
    fn sub(self, other: Mod<T>) -> Mod<T> {
        Mod::new(self.modulo, self.i - other.i)
    }
}

impl<T> Mul for Mod<T>
    where T: ZMod
{
    type Output = Mod<T>;
    fn mul(self, other: Mod<T>) -> Mod<T> {
        Mod::new(self.modulo, self.i * other.i)
    }
}

#[test]
fn t0() {
    let x = Mod::new(-5i8, 3i8);
    let y = Mod::new(-5i8, 8i8);
    assert_eq!(-4, (x + y).i);
}

#[test]
fn t1() {
    let x = Mod::new(-5i8, 3i8);
    let y = Mod::new(-5i8, 8i8);
    assert_eq!(-4, (x + y).i);
}

#[test]
fn t2() {
    let x = Mod::new(-5i8, 3i8);
    let y = Mod::new(-5i8, 8i8);
    assert_eq!(0, (x - y).i);
}

#[test]
fn t3() {
    let x = Mod::new(-5i8, 3i8);
    let y = Mod::new(-5i8, 8i8);
    assert_eq!(-1, (x * y).i);
}

#[test]
fn t4() {
    let x = Mod::new(-5i16, 3i16);
    let y = Mod::new(-5i16, 8i16);
    assert_eq!(-4, (x + y).i);
}

#[test]
fn t5() {
    let x = Mod::new(-5i16, 3i16);
    let y = Mod::new(-5i16, 8i16);
    assert_eq!(0, (x - y).i);
}

#[test]
fn t6() {
    let x = Mod::new(-5i16, 3i16);
    let y = Mod::new(-5i16, 8i16);
    assert_eq!(-1, (x * y).i);
}

#[test]
fn t7() {
    let x = Mod::new(-5, 3);
    let y = Mod::new(-5, 8);
    assert_eq!(-4, (x + y).i);
}

#[test]
fn t8() {
    let x = Mod::new(-5, 3);
    let y = Mod::new(-5, 8);
    assert_eq!(0, (x - y).i);
}

#[test]
fn t9() {
    let x = Mod::new(-5, 3);
    let y = Mod::new(-5, 8);
    assert_eq!(-1, (x * y).i);
}

#[test]
fn t10() {
    let x = Mod::new(5u8, 3u8);
    let y = Mod::new(5u8, 8u8);
    assert_eq!(1, (x + y).i);
}

#[test]
fn t11() {
    let x = Mod::new(5u8, 3u8);
    let y = Mod::new(5u8, 8u8);
    assert_eq!(0, (x - y).i);
}

#[test]
fn t12() {
    let x = Mod::new(5u8, 3u8);
    let y = Mod::new(5u8, 8u8);
    assert_eq!(4, (x * y).i);
}


"Edit distance" UVA programming challenge

Generating all possible single-edit variations of a word results in a huge number of possibilities!  With a 10-letter word, for example, you could add 26 letters in each of 11 positions (before, after, or between letters), remove any of the 10 letters, or modify any of the 10 letters.  That's 26 × 11 + 10 + 25 × 10 = 546 possibilities.  On average, you could trim that in half if you only consider words that come lexicographically later than the input word.  Still, that's a huge inefficiency — enough to rule out that approach altogether.

Your is_edit_distance_one() should take const string & arguments to avoid copying.  The body would be improved if you break down the cases as:

switch (one.size() - two.size()) {
  case -1: // Is one is a subsequence of two (not necessarily consecutive)?
  case +1: // Is two is a subsequence of one (not necessarily consecutive)?
  case 0:  // Check for single-letter difference
  default: return false;
}

The challenge with the is_edit_distance_one() approach is that if you apply it naïvely (comparing every pair of words), your running time will be O(n2), where n is the number of words.

One technique to consider is to take the hint that no word exceeds 16 letters.  Create a char[25001][16] matrix and fill it with '\0' NULs.  You can then treat the NULs just like any other char for the purpose of determining edit distances.

Once you have determined which words are one edit distance apart, the search for the longest stepladder should be similar to the Longest Increasing Subsequence problem.


Take the following result :

<script type="text/javascript">
    var json = { "key" : "</script>" }
</script>

Unless you HtmlEncoded your data somewhere, the "</script>" will break your code. With Html Encoding, the result should look like this :

<script type="text/javascript">
    var json = { "key" : "&lt;/script&gt;" }
</script>

To easily encode all string, you can check this solution : http://pastebin.com/R2PWZkUq

Note that this should happen only with object declare inline. JSon coming from Ajax don't have this problem.


Java orchestration calls from two CRUD endpoints

It's because your presentation layer does the orchestration. I'd recommend to make the rest layer as stupid as possible. Its only purpose should be to get the request information from the URL, load the corresponding data from the service layer, and transform the data to JSON or whatever format it needs to be.


Calculating and printing a credit card balance

A good thing you can do is to create more functions, which return values in the dictionary form.

Pseudo-code:

def calculateCreditCardBalance(balance, annual_interest_rate, monthly_payment_rate):
    total_paid = 0
    curr_values = ["balance" => balance, "annual_interest_rate" => annual_interest_rate, "monthly_payment_rate" => monthly_payment_rate]
    foreach this_month in rage(1,13):
        month_values = calculate_month_values(curr_values)
        print_values(month_values)
        update_month_values(month_values,curr_values)
    print 'Total paid: ' + str(curr_values["total_paid"])
    print 'Remaining balance: '+ str(curr_values["total_paid"])


Spaces. You need spaces around things. For example, keywords should always have whitespace on either side. Brackets, too. Parentheses should have spaces on the outside -- that is, to the right of a closing, to the left of an opening one. Also, on either side of binary operators. In general, your use of whitespace is inconsistent and unconventional.

Aside from that:

You need to work on your variable names. Things like r, list, s1, and obj don't say anything about what they do or for what purpose they exist. In short, they're meaningless.

You always open list.get(0), so you're always opening the same file. I strongly suspect you mean list.get(i).

With that change, you can change the for from a normal for to an advanced one, which makes it much simpler semantically.

Still focusing on that line: Why are you assuming that the files to be merged are in INCOMINGFOLDER? That's a pretty risky assumption for a method that has no context other than being called mergeFiles, which suggests that it should merge any files, without modifying the paths.

Rather than hardcoding a line separator which doesn't work on all OSs -- which, incidentally, sorta breaks the biggest reason for using Java at all -- use BufferedWriter#newLine().

Instead of manually checking for null in a finally, just use a try with resources. It's much cleaner.

It's generally bad to swallow up errors without telling the use of the function. Rather than printing the stacktrace of possible IOExceptions, I'd recomment rethrowing it. I suggest removing the catch block -- that is, passing it up the chain.

You never use the instance of AggregateNj, so it's useless, so I got rid of it. You also never use BufferedReader r, so I removed that as well.

With all those put in, here's your (much nicer IMO) code:

public void mergeFiles(File outputFile, List<String> inputFiles) throws IOException {
    try (BufferedWriter output = new BufferedWriter(new FileWriter(outputFile))) {
        for(String fileName : inputFiles){
            try (BufferedReader in = new BufferedReader(new FileReader(fileName))) {
                String line;
                while ((line = in.readLine()) != null) {
                    output.write(line);
                    output.newLine();
                }
            }
        }
    }
}

You could also return a boolean depending on whether or not it completed successfully, and the method would look like this:

public boolean mergeFiles(File outputFile, List<String> inputFiles) throws IOException {
    try (BufferedWriter output = new BufferedWriter(new FileWriter(outputFile))) {
        for(String fileName : inputFiles){
            try (BufferedReader in = new BufferedReader(new FileReader(fileName))) {
                String line;
                while ((line = in.readLine()) != null) {
                    output.write(line);
                    output.newLine();
                }
            }
        }
        return true;
    } catch (IOException e) {
        return false;
    }
}

However, I'd recommend throwing an error instead of returning a boolean, as it gives a lot more information about what went wrong.

Note that I didn't review your design, since this is Code Review. If you want the design reviewed, please provide the code.


A thread that can be interrupted before starting

Review

A Java Thread's default behavior is:

  A thread interruption ignored because a thread was not alive at the
  time of the interrupt will be reflected by this method returning
  false.

Changing the default behavior of interruption in a thread's lifecycle seems a bit tricky to me. I don't think you should override exising methods to change their specification when dealing with such common and wellknown threading constructs.
Instead, I would create 2 new methods, requestRun() and requestInterruption() to clearly indicate different functionality from run() and interrupt().
If you do decide to override run() and interrupt() make sure to clearly state in the Javadoc that the specification of these methods has changed.
InterruptableThread is an unfortunate name, since Thread is also interruptible. A better name would be PreemptiveInterruptibleThread.
Since you have atomic booleans, perhaps you could check the value before taking the lock, in order to mitigate access to the locks. There is a possible race condition though. You can read more about Double-checked locking here. Is your question implementation Idempotent?
If the atomic booleans are only used inside this lock, they could be replaced with ordinary booleans.
I like the fact everything that could be made final, has been declared final.
I do believe there still is a race condition after releasing the lock in run() and before calling super.run().


Real skill means knowing your libraries. Instead of 20 lines of handcrafted code, I'd rather go for:

int max = Arrays.stream(array).max().orElseThrow(() -> new IllegalArgumentException("Array is empty"));

... the same for min.

As a general advice: Java is a very mature language, and chances are good that every "simple everyday task" is already solved in the library. (Also note that most books on Java are from the pre-java-8 era and may be considered somewhat outdated today.)


Caesar Cipher encoding process (customizable input and shifting) in Python

Some suggestions:

Pull out a function to shift a single character, and your top level code ends up being simply print(''.join([cipher(character) for character in input(…)]))
With an array containing the alphabet and a shifted array ("{}{}".format(alphabet[offset:], alphabet[:offset])) you can use str.translate to avoid any ord, chr, punctuation handling etc.
Use at least one linter like pycodestyle or flake8 to produce more idiomatic code.


Regular expressions are the right tool to use for this kind of test.  However, if you are going to use a regular expression to find lonely g characters, then you should use negative lookbehind and lookahead assertions instead of the negated character class [^g].

def geppy(str)
  !/(?<!g)g(?!g)/.match(str)
end


Optimization 1
Instead of constantly doing Character.getNumericValue(pattern[j])-1 in the inner loop, you could create a precomputed integer array to hold those values.  That way, you could replace that expression with patIndex[j].
Optimization 2
Instead of using multiple instances of StringBuilder, you could use and reuse a single char array and create strings from that.
Optimization 3
Instead of creating a char array from your designs[i] string, you could just leave designs[i] as a string and use String.charAt() to read each character.
Sample rewrite
Using the above 3 optimizations, I arrived at:
static String[] applyInterleave(String interleave, int lengthOfSequence,
        int numOfPermutations)
{
    String[] interleavedPatterns = new String[numOfPermutations];
    char  [] pattern  = interleave.toCharArray();
    int   [] patIndex = new int[lengthOfSequence];

    for (int i = 0; i < lengthOfSequence; i++) {
        patIndex[i] = Character.getNumericValue(pattern[i])-1;
    }

    for(int i = 0; i < numOfPermutations; i++) {
        String s = designs[i];
        for(int j = 0; j < lengthOfSequence; j++) {
            pattern[j] = s.charAt(patIndex[j]);
        }
        interleavedPatterns[i] = new String(pattern);
    }
    return interleavedPatterns;
}

I tested this against the original function and found that it was approximately 3x faster.


The updated code looks much better but you could try to extract some more common structure.

You can define fading in a general way that allows you to plug in some fading strategies. You already have fade in and fade out but you'll be able to reuse the same code for other 'fading'.

fade: function(fadingStrategy){
    if (volumeIntervalId) clearInterval(volumeIntervalId);
    volumeIntervalId = setInterval(fadingStrategy, volumeIntervalDelay);
}

You can then define fadeIn and fadeOut by simply passing the appropriate strategies to fade.

I think there is still room for improvement. Your code relies on some global state through volumeIntervalId and volumeIntervalDelay. Getting rid of the second one is trivial. You can just pass it as a parameter to fade, making it even more flexible as it will now support also different combinations of fading strategies and fading intervals.

Clearing the timed action could be a bit more tricky. One possible solution could be to make your function return another function that closes over volumeIntervalId. In that way you will only need to keep track of the function you got from the invocation of fade and invoke it when you want to stop its action.

fade: function(fadingStrategy, volumeIntervalDelay){
    var volumeIntervalId = setInterval(fadingStrategy, volumeIntervalDelay);
    return function(){clearInterval(volumeIntervalId);};
}

Disclaimer
I'm not a Javascript expert so I cannot guarantee that the code I wrote works flawlessly but I hope you at least got some ideas on how you could improve your code.


1. Bugs

If the open succeeds but the lseek fails (as it might if the file is a named pipe), the function omits to close the file descriptor, thus leaking it.
If read reaches the end of the file (as it might if the file was truncated after the lseek), then it returns 0. This will cause the function to go into an infinite loop.
There's no check on the result of the second call to lseek. If this call fails, then the function will go into the infinite loop described above.

2. Review

There's no specification. What does this function do? How do I call it? What does it return?
This is a worst-case \$\Theta(n^2)\$ algorithm, because realloc may have to copy the result each time it grows, and you grow the buffer by at most BUF_SIZE bytes each time you call realloc. It's usual in this kind of situation to grow the result exponentially, by multiplying the result size by some constant on each realloc call.
Even ignoring the copying due to realloc, each byte read from the file is copied again using memcpy. It would be better to realloc the result first, and then read directly into the result.
You go to the trouble of finding the length of the file, so why not read it all in one go?

result = malloc(total);
if (!result)
    /* handle error */
n = read(fd, result, total);
if (n != total)
    /* handle error */

Consider using fstat instead of lseek to determine the size of the file.
It's not a good idea to put multiple statements on the same line, like this:

if (fd < 0) return -1;

That's because in most debuggers you won't be able to set a breakpoint on the return statement.
There's repetition in the handling of the four failure cases. This makes the function difficult to modify (because you might fail to adjust one or more of the cases). The bug in §1.1 above might have been caused by this problem.
For reading the entire contents of a file into memory, consider using mmap.

mmap has advantages over read. (i) There's no need to allocate a buffer: the kernel maps the file directly into the process's virtual memory. (ii) mmap operates lazily: it maps the file into memory but does not actually copy any part of it until that page is touched, so programs that randomly access the file don't have to wait for the whole file to load.

mmap also has disadvantages. (i) mmap only operates on ordinary files (not pipes, sockets, or other kinds of file descriptor). (ii) Mapping lots of files creates lots of entries in the process's virtual memory table, and on some operating systems (notably OS X) this can lead to poor memory performance.

3. Revised code

#include <fcntl.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>

/* Map the contents of file into memory: if successful, update
 * *contents to point to the file contents, update *size to be the
 * size of the file, and return 0. Otherwise, return -1.
 */
int getFileContents(const char *file, void **contents, size_t *size)
{
    int fd = open(file, O_RDONLY);
    if (fd < 0)
        goto fail_open;

    struct stat st;
    if (fstat(fd, &st) < 0)
        goto fail_fstat;

    void *result = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
    if (result == MAP_FAILED)
        goto fail_mmap;

    *contents = result;
    *size = st.st_size;
    close(fd);
    return 0;

fail_mmap:
fail_fstat:
    close(fd);
fail_open:
    return -1;
}

4. Answers to comments

In comments, lesto suggests:

  I would return a different number for every error, to help the user of the function to identify the problem and try to recover.

In this context (Unix systems programming), it's conventional for a function to return a single distinguished value (typically −1) to indicate an error, with the cause of the error being stored in errno. See for example the POSIX specification of open:

  Upon successful completion, these functions shall open the file and return a non-negative integer representing the lowest numbered unused file descriptor. Otherwise, these functions shall return -1 and set errno to indicate the error.

It makes sense to stick to the Unix convention, so that the caller can apply the same kind of error handling to getFileContents as they do to other system interfaces.

  Every error between open and close need the call to close, and leaving it inline is easier than check the list of label is correct, IMHO. It is true that you are writing some more lines.

If you write out the error-handling code inline, then your functions have length that's quadratic in the number of error cases! This is disastrous for readability and maintainability. It is all too easy to forget one of the cases, as in the bug described in §1.1 above.

An alternative to goto is to use nested if statements. In this case the code would become:

int fd = open(file, O_RDONLY);
if (fd >= 0) {
    struct stat st;
    if (fstat(fd, &st) == 0) {
        void *result = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
        if (result != MAP_FAILED) {
            *contents = result;
            *size = st.st_size;
            close(fd);
            return 0;
        }
    }
    close(fd);
}
return -1;

but this quickly becomes hard to read because of the indentation.


You can merge the methods findBySlug, findByTitle and other findBy methods into one method that accepts parameter field and value

$this->findBy($field, $title);

And move it in BaseRepository Class. See this article Repository Pattern

so it would look something like this

public function findBy( $field, $value ) {
  return $this->model->where($field, $value);
}


I think I should use JOIN but I did this instead

First, about your current code:

You're doing a SELECT *. This is generally poor practice; instead, explicitly identify the columns you need: SELECT id, first_name.
Your $rep_array is a lookup table, so name it as such. Maybe $rep_id_to_name or something?
Your way of adding to the array is bad; it won't work if the rep ids are not contiguous. Instead, just directly set the id:

$rep_array = array();
while ($rep = mysqli_fetch_assoc($rep_query_result)) {
    $rep_array[$rep['id']] = $rep['first_name'];
}

Now, about using a JOIN...

I don't know the query for domains, but I'll assume it's something like this:

SELECT d.rep, ...
FROM `domains` d
WHERE ...

Then in order to use a join, you could do (note the absence of d.rep in the SELECT list:

SELECT r.first_name AS rep, ...
FROM `domains` d
JOIN `reps` r ON d.rep = r.id
WHERE ...

This will get the behaviour you want, but it wouldn't hurt to give a more meaningful name to rep. Keyboard strokes are (almost) free! Consider representative_name or something.


What percentage of down votes are users responsible for?

SQL casing shouldn't matter (much)
Every SQL developer I know writes their queries a bit differently. Case/style shouldn't matter much or at all, if the SQL code works but it's a bit sloppy. Favor substance over style. For example, these 3 queries are identical, as far as the database engine cares:
/* These are all exactly the same in SQL: */
SELECT FOO, BAR FROM TEST;
Select Foo, Bar From Test;
select foo, bar from test;

That being said...
...there are a few things we could probably improve in your own query...
Some indentation would feel nice, especially in the subqueries/CTEs. Some indentation will make your code much easier to read:
WITH foo AS (
    ...
),
bar AS (
    ...
)
--etc

Lines breaks
Line breaks...also feel nice, especially for breaking down business logic, which DownVoteWeight is (for instance), where it can be broken down into meaningful functions/operations. This one might deserve a bit more documentation.
SELECT
    DisplayName,
    UpVotes,
    DownVoteWeight = ROUND(
        DownVotes / (SELECT DownVoteCount from DownVoteCount) * 100, 4
    )


Separation of concern
You mention "separation of concern" in your question. It's fantastic that you actually know about it, and are trying to adopt good practices whilst learning about OO. However, allow me to be a pedantic tw*t for a second, and stress that SoC is not the same as SRP (Single Responsibility Principle).
It's the SRP that states that a class can have one, and only one reason to change. That's a fancy way of saying that 1 class == 1 job. SoC operates on a higher level. You may, or may not have, stumbled across buzzwords or terms like MVC. SoC is the main reason for architectural patterns like the MVC pattern: Each component (module) can, and often does, consist of a multitude of classes. Each of these classes have a single job that can be grouped under a specific module (ie: the "V" module (view) consists of a renderer class, a class that manages the cache, a class that manages the output buffers etc...).
Just a bit of a pedantic lecture, as an aside :-P
At first glance:
Well, the first thing that strikes me as, erm..., off is your failing to specify the visibility of your class/interface members. While it's true that PHP will default to public access unless you specify otherwise, and that interface members have to be public by definition, it's best to be specific, therefore change your methods from:
function init();//in interface

To:
public function init();

Another niggle I have is with your coding style. It might seem irrelevant at first, or a matter of personal preference (which it is, to a certain degree), but there are such things as coding standards. They exist for good reason, and should really be adhered to as much as possible. In this case, this means that:
function get_is_author_referrer();
//should become
public function getIsAuthorReferrer();
//or perhaps better still:
public function isAuthorReferrer();

In general, methods that start with get are getter methods  (methods that will return the value of a member/property). set methods are setters to set that member. If a method should return a boolean, it's quite common to see methods with an is prefix. Just like it's fairly common to see classes that implement a has method, to check the value of a given property, take this basic example:
class Foo
{
    /**
     * @var array|null
     */
    protected $someArray = null;

    /**
     * @param array|null $vals = null
     */
    public function __construct(array $vals = null)
    {
        $this->someArray = $vals;
    }

    /**
     * @return array|null
     */
    public function getVals()
    {
        return $this->someArray;
    }

    /**
     * @param array $vals
     * @return $this
     */
    public function setVals(array $vals)
    {
        $this->someArray = $vals;
        return $this;
    }

    /**
     * @return bool
     */
    public function isArray()
    {
        return is_array($this->someArray);
    }

    /**
     * @return bool
     */
    public function hasVals()
    {
        return !empty($this->someArray);
    }
}

I can check to see if the $someArray property of a given instance of Foo is null, or an array (using isArray). I can also check to see if that property isn't empty. I can get the value of the property, or set it using the getter and setter methods just fine. There's no real point in using additional properties for this, so I'd suggest you do something along the lines of:
protected $authorReferrer = null;
//in the init method:
$this->authorReferrer = isset( $_GET['aq'] ) ? $_GET['aq'] : null;
//add these methods:
public function isAuthorReferrer()
{
    return $this->authorReferrer !== null;//if not null
}
public function getAuthorReferrer()
{
    return $this->authorReferrer;
}

The upshot is that your class can now be used both to check if certain params were set in the $_GET superglobal (more on your use of this later), The instance can also be used to retrieve the values, and possibly validate or normalize them.
Try not to support people on EOL versions
Your class, and interface seem to be following the PSR-0 autoloading standard (to some degree). This standard states that the _ (underscores) in names like Single_Post_Referrer_Class will be replaced with directory separators. It was commonplace to use this in PHP versions prior to PHP 5.3 (which introduced namespace support). However, PSR-0 is now deprecated in favour of the PSR-4 standard, simply because there is no supported PHP version left that does not support namespaces. Heck, even 5.3 has been EOL'd about half a year ago.
What does this mean for you? Well, put simply: Shorter class names:
class Single_Post_Referrer_Class {}
//now becomes:
<?php
namespace MainNS\Single\Post;
class Referrer {}

Where MainNS is the root namespace for your project. I ditched the Class because that's a reserved keyword, and a rather dodgy class name anyway.
TL;TR: Embrace namespaces

Specific critiques
Now for some more specific critiques/issues I have with your code:
A constructor mustn't be abused
You're certainly not the only person to abuse a constructor. And to be honest, I've seen a lot worse that your code (honestly, it's not half bad), but let's be honest:
public function __construct()
{//standards: this { goes on the next line
    $this->init();
}

Your constructor calls a second method, and yes, all the method seemingly does is to initialize the instance, but look at your class from a user standpoint (the person using your code):
$x = new Referrer();

Does his code accurately reflect what is going on? Of course not! Can you force the user to only create instances of your class when there is a $_GET variable available? No, you can't. Someone might, for example, choose to write a CLI script using your codebase and (owing to name conflicts or for whatever reason) create an instance of your class, which relies entirely on their being a $_GET variable available.
I know there are many, many more complete definitions of a class out there, but here's what I think a class essentially is/should be:

"A class is a self-contained unit of code that couples data and functionality together in order to perform a single, task, regardless of the context in which task is to be performed"

What does that mean? Well, take the simplest of classes for example: a data model:
class Person
{
    /**
     * @var string
     */
    protected $name = null;

    /**
     * @var string
     */
    protected $email = null;

    /**
     * @var int
     */
     protected $age = null;

    /**
     * @param string $name
     * @param string $email
     * @param int $age
     */
    public function __construct($name, $email, $age)
    {
        $this->setName($name)
             ->setEmail($email)
             ->setAge($age);
    }

    /**
     * Basic, but somewhat unsafe setter (Relies on user to pass expected value)
     * @param string $name
     * @return $this
     */
    public function setName($name)
    {
        $this->name = $name;
        return $this;
    }

    /**
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Example of validating setter: throws exceptions if value isn't valid
     * @param string $name
     * @return $this
     * @throws \InvalidArgumentException if email is not a valid address
     */
    public function setEmail($email)
    {
        if (!filter_var($email, \FILTER_VALIDATE_EMAIL))
        {//<-- allman brackets, not standard, I know... :-P
            throw new \InvalidArgumentException(
                sprintf(
                    '%s expects $email to be valid email address, %s is not',
                    __METHOD__,
                    $email
                )
            );
        }
        $this->email = $email;
        return $this;
    }

    /**
     * @return string
     */
    public function getEmail()
    {
        return $this->email;
    }

    /**
     * Example of setter that attempts some basic normalization
     * @param int $age
     * @return $this
     */
    public function setAge($age)
    {
        $this->age = abs((int) $age);//use abs in case of negative vals, cast to int
        return $this;
    }

    /**
     * @return int
     */
    public function getAge()
    {
        return $this->age;
    }
}

This class does what it says on the tin: It represents a person, and all of its associated data (a name, an age, and an email address). The setters perform some normalization or validation, and regardless of where this class is used, or where the data comes from: this class will behave perfectly predictable:
$person = new Person('Foo Bar', 'foo@bar.com', 33);
echo $person->getName(), ' is ', $person->getAge(), ' years of age', PHP_EOL,
    ' and can be reached via: ', $person->getEmail();
try {
    $person->setEmail($person->getAge());//try 33 as email address...
} catch (\InvalidArgumentException $e) {
    //Person::setEmail expects $email to be valid email address 33 is not
    echo 'Rather predictable: ', $e->getMessage();
}

I could (and probably would) change this class a tad, making the constructor optional, or allow the user of the class to set the properties through an associative array, or an object, by simply adding this method:
/**
 * @param array|\stdClass|\Traversable $mixed
 * @return $this
 * @throws \InvalidArgumentException
public function setBuld($mixed)
{
    if (!is_array($mixed) && !$mixed instanceof \stdClass && !$mixed instanceof \Traversable)
    {
        throw new \InvalidArgumentException(
            sprintf(
                '%s needs either an array, or an instance of \\stdClass or \\Traversable to be passed, instead saw %s',
                __METHOD__,
                is_object($mixed) ? get_class($mixed) : gettype($mixed)
            );
        );
    }
    foreach ($mixed as $name => $value)
    {//create setter from $name
        $setter = 'set' . ucfirst(strtolower($name));
        if ($setter !== 'setBulk' && method_exists($this, $setter))
        {//ensure no recursive calls here, and make sure the setter exists:
            $this->{$setter}($value);//set value
        }
    }
    return $this;
}

Using this approach, you change your class and interface to be a bit more forgiving, and (more importantly) make it so that your class no longer relies on super globals like $_GET:
namespace MainNS\Single\Post;
interface ReferrerInterface
{
    /**
     * @param array $values
     * @return $this
     */
    public function init(array $values);
    /**
     * @return bool
     */
    public function isAuthorReferrer();
    /**
     * @return bool
     */
    public function isDateReferrer();
    /**
     * @param mixed $authorReferrer
     * @return $this
     */
    public function setAuthorReferrer( $authorReferrer );
    /**
     * @param string|\DateTime $authorReferrer
     * @return $this
     */
    public function setDateReferrer( $dateReferrer );
}

Here, I simply reworked your interface a bit, to ensure the public function init allows the user to pass an array of values to the instance upon which the method is called. So in your class, I'd rewrite a thing or two, too:
namespace MainNS\Single\Post;
class Referrer implements ReferrerInterface
{
    /**
     * @var mixed (string?)
     */
    protected $authorReferrer = null;
    /**
     * @var \DateTime
     */
    protected $dateReferrer = null;
    /**
     * @param array $values = null;
     */
     public function __construct(array $values = null)
     {
         if ($values)
             $this->init($values);
     }

    /**
     * {@inheritdoc}
     */
    public function init(array $values)
    {//or implement the setBulk I've shown earlier
        if (isset($values['dateReferrer']))
            $this->setDateReferrer($values['dateReferrer']);
        if (isset($values['authorReferrer']))
            $this->setAuthorReferrer($values['authorReferrer']);
        return $this;
    }

    /**
     * @param mixed $authorDate
     * @return $this
     */
     public function setDateReferrer($dr)
     {
         if (!$dr instanceof \DateTime)
         {
              $dr = new \DateTime($dr);
         }
         $this->dateReferrer = $dr;
         return $this;
     }
     //implement rest of the interface here...
}

The way you implement the interface is, of course, down to you entirely. However, keep in mind that PHP is quite forgiving in terms of breaches of contract (more so than other languages). That doesn't mean that breaking the inherited or implemented contracts is anything else than wrong (I'd be happy to go into this in a bit more detail if you want me to, just let me know in a comment).
It's therefore important to understand, and religiously follow the liskov principles at all times.
Anyway, I've been going on for some time now, and I guess I'll leave it at this for now. Hope this helps you on your way


Looping over a map requiring casting and instance checks

public String update(String initialText, Map<String, Object> productMap){         //  1
    if(StringUtils.isBlank(initialText) || MapUtils.isEmpty(productMap)){         //  2
        return initialText;                                                       //  3
    }                                                                             //  4
    for (Map.Entry<String, Object> productData : productMap.entrySet()) {         //  5
        String key = productData.getKey();                                        //  6
        Object value = productData.getValue();                                    //  7
        if(value instanceof String && ((String) value).matches("[0-9]+")){        //  8
            String offerValue = (String)value;                                    //  9
            initialText = initialText.replaceAll(key, String.format("%,d", Integer.parseInt(offerValue)));   //10
        }                                                                         // 11
    }                                                                             // 12
    return initialText;                                                           // 13
}                                                                                // 14

Line 1

The method and parameter names could be clearer. A method named update could do many things. How about something akin to replacePlaceholders. Analogously, initialText would become template. Also, the Hungarian notation for the map parameter isn't needed (How should I name a java.util.Map?). Maybe substitutionByPlaceholder or something similar. I feel like there could be a better name, but I lack the domain knowledge.

Also, I always make parameters, variables and such final. I swear by it, but maybe your style guide disallows it.

Making the parameters final also prevents you from reassigning them, which is usually a good thing, because it prevents silly mistakes like

public void setFoo(int foo) {
    foo = foo;
}

It looks obvious now, but in a more complex method, it can cause a bug real' quick.

Lines 5, 6, 7

Again, final variables are recommended.

Lines 6, 7

key and value aren't great names. How about placeholder and replacement?

Line 8

Your method of testing if the String is an int is flawed. How about negative Integers, or something like 100000000000000000000000000. That sure isn't an Integer. Be sure to think about corner cases like this!

If it's almost always an Integer or performance doesn't matter to you, you can just use Integer.parseInt wrapped in a try catch block. Deliberately catching Exceptions for control flow is usually not recommended though. For alternatives, see What's the best way to check if a String represents an integer in Java?

The rest looks okay, but it's a big method. Not huge by any means, but it still does too much. To quote Robert C. Martin in Clean Code:

  Functions should do one thing. They should do it well. They should do it only.

If you look at your method, it does multiple things. It guards against bad input, it loops over the map, it checks if entries are valid, and it does the replacement.

If we split your method into four method, they all become just a few lines each, each method doing exactly one thing (Barring the last one, which does two things, checking if the String is an integer and replacing, which is a symptom of us using try-catch for control flow) that is very easy to understand.

Also all methods may be static since they don't use any instance members.

public static String replacePlaceholders(final String template, final Map<String, Object> productMap) {
    if (StringUtils.isBlank(template) || MapUtils.isEmpty(productMap)) {
        return template;
    }

    return replaceAllPlaceholders(template, productMap);
}

private static String replaceAllPlaceholders(final String template, final Map<String, Object> productMap) {
    String result = template;

    for (final Map.Entry<String, Object> productData : productMap.entrySet()) {
        result = replacePlaceholderIfValueIsIntegerString(result, productData);
    }

    return result;
}

private static String replacePlaceholderIfValueIsIntegerString(final String template, final Map.Entry<String, Object> entry) {
    if (entry.getValue() instanceof String) {
        return replacePlaceholderIfReplacementIsInteger(entry.getKey(), (String) entry.getValue(), template);
    }
    return template;
}

private static String replacePlaceholderIfReplacementIsInteger(final String placeholder, final String replacement, final String template) {
    try {
        return template.replaceAll(placeholder, String.format("%,d", Integer.parseInt(replacement)));
    } catch (final NumberFormatException e) {
        return template;
    }
}

Recommended reading:

Robert C. Martin; Clean Code
Joshua Block; Effective Java, 3rd Edition


This is quite nice, but there are still several ways that would improve this.

Here are a  few ideas:

Relations instead of side-effects

First, I recommend to avoid side-effects. Instead, think in terms of relations. By this I mean that you should not use write/1 to print a solution, but express what constitutes a solution, as in the following:

solution(Days) :-
        Days = [[tuesday,_,_],[wednesday,_,_],[thursday,_,_],[friday,_,_]],
        etc.

Here, I have made Days available for reasoning as a predicate argument. This way, you can explicitly reason about solutions, and for example write actual test cases by stating what should and should not hold about given solutions. You cannot do this if the solution only occurs in the form of output on the system terminal.

If you need to print a solution in any way, you can use the more general form above to still do that. For example:

?- solution(Ds),
   maplist(writeln, Ds).
[tuesday,ms_green,water_tower]
[wednesday,mr_niven,frisbee]
[thursday,mr_klien,clothesline]
[friday,ms_barnum,balloon]

Use higher-order predicates

Suppose I give you the following auxiliary predicate:

list_member(Ls, E) :- member(E, Ls).

Then you can use maplist/2 to express members/2 as follows:

members(Es, Ls) :- maplist(list_member(Ls), Es).

When you encounter predicates that reason over lists, check the available higher-order predicates (especially maplist/N and foldl/N) to see if they can simplify your code.

Use dif/2 instead of (\=)/2

You are currently using the impure predicate (\=)/2 in your code. This prevents you from using Prolog to its fullest potential.

Use dif/2 instead to benefit from the declarative nature of true relations: You can then pull these goals towards the beginning of the clause or at least earlier, and benefit from their pruning in addition to the added flexibility of placing the goal anywhere you like in principle.

Indentation

Never put (;)/2 at the end of a line. It looks too similar to (',')/2, which typically occurs at that position.

In total, a solution could look like (in addition to the points mentioned previously):

solution(Days) :-
        Days = [[tuesday,_,_],[wednesday,_,_],[thursday,_,_],[friday,_,_]],
        before([_,mr_klien,_],[_,_,balloon],Days),
        before([_,_,frisbee],[_,mr_klien,_],Days),
        (   member([friday,ms_barnum,_],Days)
        ;   member([friday,_,clothesline],Days)
        ;   member([friday,ms_barnum,clothesline],Days)
        ),
        members([[_,mr_klien,_],[_,ms_barnum,_],[_,ms_green,_],[_,mr_niven,_]], Days),
        members([[_,_,balloon],[_,_,frisbee],[_,_,clothesline],[_,_,water_tower]], Days),
        dif(NOT_ms_green, ms_green),
        member([_,NOT_ms_green,frisbee],Days),
        dif(NOT_mr_niven, mr_niven),
        member([tuesday,NOT_mr_niven,_],Days),
        dif(NOT_mr_klien, mr_klien),
        member([_,NOT_mr_klien,water_tower],Days).

Now we can query:

?- solution(Ds).
Ds = [[tuesday, ms_green, water_tower], [wednesday, mr_niven, frisbee], [thursday, mr_klien, clothesline], [friday, ms_barnum, balloon]] ;
false.

And also ask something different, for example:

?- Ds = [[monday, ms_green|_]|_],
   solution(Ds).
false.

Thus, the system tells us: No, that's not a solution!

This is now easily possible because we can reason explicitly about solutions, having made them available as a predicate argument.


PHP Validate JSON objects with a JSON schema

Your solution is very "functional programming" in approach, with nested function declarations and such.  This in of itself is not "wrong", it is just a little bit unusual in the PHP world.

I would consider moving this into an object-oriented paradigm which is more common in PHP.  I would think in this case perhaps only a class with static functions might be needed, so you could make calls against the validator like:

$result = JsonSchemaValidator::validate($jsonSchema, $jsonPayload);

If you find you have one schema that is used multiple times for validation, then perhaps it makes sense to have concrete validator objects like this:

$validator = new JsonSchemaValidator($jsonSchema);
$result1 = $validator->validate($jsonPayload1);
$result2 = $validator->validate($jsonPatload2);

This would save you the overhead of having to re-validate the schema with each validation request.

I am not sure which is more appropriate to your application, but wanted to present both options for putting this logic into a class.

Some odd naming conventions are in play:

Why name a variable $json_payload when it does not contain JSON at all, but rather an object built from JSON?  Perhaps $payload is better here.
Why are you mixing camelCase and snake_case in your code?  I know PHP is not very consistent here, but that doesn't mean you shouldn't be - at least within the confines of a single library, class, set of functions, etc.
Why uppercase first c in reCursiveCheck()?

I think your main validateJSONPayload() function name and signature is odd. As noted above, the "payload" is not JSON at all.  Why pass one parameter as a JSON string and the other as an actual data structure?  This seems to be an incongruous approach.  I would probably just pass JSON for both parameters so caller doesn't need to decode one of the parameters beforehand.

Why define validation rules in a string like "type=string,min_length=7,max_length=10"?  You are introducing complexity in your code to have to perform string manipulation to get at these values when they should be defined as appropriate properties/values on the schema.
Why not mirror the already well-established JSON Schema format?

Do not echo error/validation messages to standard output.  A validator like this should do one thing - validate, not deliver end user messaging.  Leave that up to functionality further up the call stack that is more well-positioned to understand the context for how end user messaging should be delivered.  This code might throw exceptions and/or log errors when it gets put into a bad state (i.e. invalid JSON is passed) but outside of that, it's contract to the caller should be to just deliver validation results and leave it up to the calling code to determine what action to take from there.

If you are delivering error messages, you should also remove any HTML markup from it.  What if this code is being used in a RESTful service where response is going to be JSON format and not HMTL?  Now you have to go strip out the HTML mark-up that has been added.

The takeaway here is to separate your display concerns from your business logic.

This code is incredibly fragile and strictly "happy path" in nature, as you are doing no validation of the passed dependencies and you just assume that all of the steps in the code will work properly.  Most critically, you just assume the passed schema JSON will decode properly.

What if it doesn't?

Right now, your code will just silently fail, perhaps giving the caller the perception that validation passed, since you currently do not return any validation result to the caller (you just echo out failures).

To extend on my earlier class-based example, perhaps you need to do something like:

try {
    $result = JsonSchemaValidator::validate($jsonSchema, $jsonPayload);
} catch (InvalidArgumentException $e) {
    // perhaps we had schema or payload which could not be decoded
    // and we have the code throw InvalidArgumentExpection
    // perhaps log the error
    error_log($e->getMessage());
    // then perhaps do something to recover
    $result = false;
}

or

try {
    $validator = new JsonSchemaValidator($jsonSchema);
    $result1 = $validator->validate($jsonPayload1);
    $result2 = $validator->validate($jsonPatload2);
} catch (InvalidArgumentException) {
    // do something
}

I echo the sentiment mentioned in comments to question above that I am really not quite sure why you would want to roll your own solution to this problem.


UITableView allowing some kinds of requests to be deleted with swipe gestures

In your first implementation you can make deleteAction a  constant if you initialize it in all cases of the switch-statement:

    let deleteAction: UIContextualAction?
    switch currentShowingStatus {
    case .accepted:
        deleteAction = UIContextualAction(...)
    case .sent:
        deleteAction = UIContextualAction(...)
    case .received:
        deleteAction = nil
    }

That makes it clear that the variable is initialized exactly once before used. I would also replace default: by the explicit case received:. That makes it obvious to reader in which case no swipe action is configured (without looking up the enum definition) and forces you to update the code if more cases are added.

The double definition of UISwipeActionsConfiguration could be avoided by initializing the array of actions instead:

    let actions: [UIContextualAction]
    switch currentShowingStatus {
    case .accepted:
        actions = [UIContextualAction(...)]
    case .sent:
        actions = [UIContextualAction(...)]
    default:
        actions = []
    }

    let configuration = UISwipeActionsConfiguration(actions: actions)
    configuration.performsFirstActionWithFullSwipe = false
    return configuration

It remains the code duplication for UIContextualAction though.

In your alternative approach you append or remove elements from the actions array. But that array is initially empty. Similarly as above, you can simplify it to

    let deleteAction = ...

    let actions: [UIContextualAction]
    switch currentShowingStatus {
    case .accepted, .sent:
        actions = [deleteAction]
    case .received:
        actions = []
    }

But – as you noticed – you have to evaluate self.currentShowingStatus inside the closure again. I would avoid that for an additional reason: You are relying on the fact that the status has not changed when the closure is executed.

The code duplication for UIContextualAction can be avoided if you initialize the request  first:

   let request: Request?
   switch currentShowingStatus {
   case .accepted:
       request = self.acceptedRequests[indexPath.row]
   case .sent:
       request = self.sentRequests[indexPath.row]
   case .received:
       request = nil
   }

   if let request = request {
       let deleteAction = UIContextualAction(style: .destructive, title: "Delete") {
           _, _, completionHandler in
           self.deleteClientRequest(request)
           completionHandler(true)
       }
       let configuration = UISwipeActionsConfiguration(actions: [deleteAction])
       configuration.performsFirstActionWithFullSwipe = false
       return configuration
   } else {
       return UISwipeActionsConfiguration(actions: [])
   }

Note also that unused closure parameters can be replaced by the wildcard parameter _.

I would probably leave it like that, but of course you can combine the techniques:

    let request: Request?
    switch currentShowingStatus {
    case .accepted:
        request = self.acceptedRequests[indexPath.row]
    case .sent:
        request = self.sentRequests[indexPath.row]
    case .received:
        request = nil
    }

    let actions: [UIContextualAction]
    if let request = request {
        actions = [UIContextualAction(style: .destructive, title: "Delete") {
            _, _, completionHandler in
            self.deleteClientRequest(request)
            completionHandler(true)
            }]
    } else {
        actions = []
    }

    let configuration = UISwipeActionsConfiguration(actions: actions)
    configuration.performsFirstActionWithFullSwipe = false
    return configuration


Create a divisors list and identify primary numbers

This program has 4 parts: (1) get raw user input; (2) validate the input and
convert it to its proper data type (int in this case), halting program if
invalid; (3) compute the divisors; and (4) report them to the user. However,
your current code has those things jumbled up. While collecting raw input you
try to convert it to int (which could fail) and then you turn to preparing
some variables needed to compute the divisors and then you do a little bit of
validation. Here's your code with virtually no changes other than reordering
the existing lines so we can see the conceptual boundaries better. It's very
easy to get confused when writing code, especially if the language is new to
you; a disciplined, orderly approach to keeping different things clearly
separated will help you reduce the confusion.
import sys

# Get user input.
num = input("Please select a number between: ")

# Convert and validate. Stop if invalid.
num = int(num)
if num < 4:
    print("The number you entered is a primary number")
    sys.exit()

# Compute divisors.
y = num/2
if not y==0:
    y=int(y-0.5)
list_range = list(range(2,y+2))
divisors_list = []
for i in list_range:
    if num%i ==0:
        divisors_list.append(i)

# Report.
if not divisors_list:
    print("The number you entered is a primary number")
else:
    print(divisors_list)

Regarding Python's number limit, don't worry about it. The only applicable
limit for a program like this is your patience. Just decide and
validate.
Perhaps there are different ways of defining a divisor, but my understanding is
that every integer N above 1 has at least two divisors -- namely [1, N].
If you were to embrace that idea, your code would simplify because there would
be no need for special handling for prime numbers. The code below starts
looking for divisors at 1; switch it to 2 to stay with your current approach.
When computing divisors, each time you find one, you usually get a second for
free. For example, if the input is 24, when you find 4 you also know that
6 is one too. Also, there's no need to check for divisors beyond the number's
square root.
Regarding your question about the list_range needing y + 1 or y + 2, I
suspect that's because Python ranges have a non-inclusive endpoint: for
example, range(1, 4) is analogous to a list of [1, 2, 3]. The divisor_rng
in the code below also has to use a +1.
Here's an illustration of those comments.
import sys
import math

# Some constants.
MIN = 1
MAX = 1000

# Get user input.
reply = input(f'Enter an integer in the range {MIN}-{MAX}: ')

# Convert and validate.
try:
    num = int(reply)
    if num not in range(MIN, MAX + 1):
        raise ValueError()
except ValueError:
    print(f'Invalid reply: {reply}')
    sys.exit()

# Compute divisors.
divisors = []
divisor_rng = range(1, int(math.sqrt(num)) + 1)
for d in divisor_rng:
    if num % d == 0:
        # Store divisor.
        divisors.append(d)
        # Store its mate, unless d is the square root.
        d2 = num // d
        if d2 != d:
            divisors.append(num // d)
divisors.sort()

# Prime check.
is_prime = num > 1 and divisors == [1, num]

# Report.
print(is_prime, divisors)


Sending mail using nodemailer in Clojure

In my opinion the code looks great. What in particular looks out of place? When dealing with interop, there is no need to get hung up style, you are going to have to match the model exposed to you. I don't think there is any more proper way than as you have done.

Just as a matter of style I would make these suggestions based on my personal tastes:

Lean toward functions that take arguments over looking things up from the environment. Consider passing the result of create-mail to send-mail as an argument. Consider passing on-mail-sent to send-mail as an argument. Your functions will be more flexible this way.
Consider putting the try catch log around the call to send-mail, instead of inside it. Functions tend to be more reusable when they allow the caller to handle errors either by returning a result or possibly throwing.
Don't bother with comments that repeat the code.
nodemailer appears to be a global; should this be called like (js/nodemailer.createTransport)? Or is it a def?
clj-props doesn't convey meaning. Consider mail-config?
What does mail-adress-from-props do? is it just a keyword lookup? If so consider just using the direct lookup instead.


Some suggestions:

The trailing slash in the mkdir command is redundant.
$(…) is preferred over backticks for command substitution.
Why use seq in one command? They both do the same loop, so you might as well use {1..100} in both places.
Semicolons are unnecessary in the vast majority of cases. Simply use a newline to achieve the same separation between commands.
Use More Quotes™
set -o errexit -o noclobber -o nounset at the start of the script will be helpful. It'll exit the script instead of overwriting any files, for example, so you can get rid of the inner if statement if it's OK that the script stops when the file exists.
[[ is preferred over [.
The whole exercise is probably easier to achieve with some standard pattern like GNU parallel. Currently the script starts N commands, then waits for all of them to finish before starting any more. Unless the processes take very similar time this is going to waste a lot of time waiting.
N (or for example processors for readability) should be determined dynamically, using for example nproc --all, rather than hardcoded.
If you're worried about speed you should probably not create a subshell for your two script commands. { and } will group commands without creating a subshell.
For the same reason you probably want to do a single redirection like { "$script" … && "$script" …; } > "data/file_${i}-${j}.txt"
Since you're "only" counting to 10,000 you don't need to reset q every time. You can for example set process_count=0 outside the outer loop and check the modulo in a readable way such as:

if [[ "$process_count" % "$processors" -eq 0 ]]
then
    wait
fi

The inner code (from the line starting with ((q=q%N))) should be indented one more time.