Remove vulnerabilities from query on public website

Though prepared statements do a pretty good job protecting your DB from injection attacks, it never hurts to perform some additional checks on the data you're receiving. For example: when a request is supposed to contain an email address, you might perform a SELECT query usign that email address, or insert it in your DB. If so, you should add this:

if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL))
{
    exit();//redirect, optionally show error message
}

Same goes for any posted data, as one of the comments mentions: XSS attacks are one of the biggest threats on the web today. I've dealt with the matter in this answer.
The very least you could do is:

$execParam = array_map(
    'strip_tags'
    array(
        ':buildtitle' => $_POST['addbuildtitle'],
        ':builddesc' => $_POST['addbuilddesc'],
        ':buildcover' => $imagepath,
        ':userid' => $_POST['adduserid'],
        ':frontpage' => $frontpage,
        ':addtags' => $_POST['addtags']
    )
);
$statement->execute($execParam);

Here, I've just called strip_tags on each and every single item you're about to insert, to avoid some jokester posting

<script>location.href = 'http://malware-infested-site.org';</script>;

in the addbuilddesc field... because, if you don't filter those things out, people visiting your site won't be all too happy about that... and be honest: would you?

You can take this as far as you want. Since you're obviously using a traditional *SQL DB, you might use the table schema, to determine if the POST params are of the correct type and length:

//assume blogtitle is a VARCHAR(255) field:
':buildtitle' => sprintf('%255s',$_POST['addbuildtitle'])
//and userID is an unsigned int, 11 long
':userid' => sprintf("%11d",abs((int)$_POST['adduserid']))

This ensures your :buildtitle bind will be no longer than 255 chars. The userid value will not be negative, and will be an integer of max 11 digits long.
But to implement this would mean a huuuge mess of sprintf calls, so you could use dataModels for this (check pretty much all of my DB related answers on this site for details), and use getters and setters that use this sprintf function to format the data accordingly.
still, this will mean a lot of overhead for each and every query. Sadly, the tradoff will always be one of performance vs security. If security is all you're after, you'll also note that, in my other answers, I basically advise everybody who's trying to create a solid (as in strong, but also as in S.O.L.I.D.) query system, to have a look at doctrine. No need to reinvent the wheel...
Anyway, I'm going off course...

Now, as far as injection goes, prepared statements are pretty robust, provided you don't take it to new, absurd, extremes. I've seen people use variables instead of the DB name, just like I've seen them use POST params to fill in the table name. You don't seem to do that, and that's good... great even. Just a friendly warning: if ever you consider using variables in those parts of your query that should be static (SELECT fieldnames FROM tblNames), step back and rethink your approach, because that's where you may still introduce vulnerabilities to your system.

Basically, prepared statements work like this:

Pass a string, from which a statement is to be prepared. This is processed by the DB server as is.
The DB server parses, and "prepares" the query (optimization etc...)
Pass the arguments, with which the statement is to be executed. These values (binds) are sent via a different protocol and here's where they're being escaped correctly.

As you can see, the binds are what is being escaped and sent completely separatly, that's why prepared statements are safe. This also explains why the actual SELECT and FROM clauses in a prepared statement may not be gotten from user input. This part of the query isn't processed in the same way the binds are...

Other niggles:

At no point do you seem to be checking isset($_POST['adduserid']) and other post keys. You just seem to expect they're there. That might trigger notices, and slows your code down. Just isset() all those params.
You have a semi-colon at the end of your if statement. If you copy-pasted this code, then that's going to give you grief.
Ensure, especially with INSERT's to set the PDO::ERR_MODE correctly, and insert in transactions. In case something goes wrong, you can still use rollBack!

Here's a little sample of how that would look

$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);//force PDO to throw on error
try
{
    $db->beginTransaction();//start here
    $stmt = $db->prepare($query);
    $stmt->execute($sanitizedInsertParamsArray);
    $db->commit();//make insert permament
}
catch(PDOExcpetion $e)
{
    $db->rollBack();//revert insert!
    exit($e->getMessage());
}

The code above will throw an instance of PDOException if the prepare, execute call or even the commit fails. As long as commit hasn't been called, the transaction is still pending (ie the data isn't really inserted yet).
So simply put, this snippet asks the DB: prepare this statement, then try to execute it with these values, if you did that, then save it. If any of these three steps failed, $db->rollBack() just tells the DB: OK, so it didn't work, forget about it... don't try and save half of the data, just forget everything.

Transactions are a good way to avoid orphaned data (as are FK's, btw). And they make for a safer query all together, too...


Greatest difference between numbers in list

Consider that the greatest difference of the following 2 sets exceeds the int range.  For a more robust solution, return a wider type or detect failure.

{INT_MIN, INT_MAX}
{INT_MAX, INT_MIN}

// int custom_max(int n, int const* list)
long long custom_max(int n, int const* list)

Better to use size_t for array indexing.  int may be too narrow.

A solution in liner time, as answered by @janos, is do-able, yet a few changes are needed to handle an ever decreasing list like {10,8,7,4,0}.

For each element arr[i] from 1 to n-1, find if the difference of that element and the prior minimum is a greater difference.

Then update the minimum.

// Detect rare cases when long long and int have similar ranges.
#include <limits.h>
#if LLONG_MIN/2 > INT_MIN || LLONG_MAX/2 < INT_MIN
#error Need wider type
#endif

long long custom_max(size_t n, int const* list) {
   if (n < 2) {
     // Handle pathological case.
     // Avoid magic number
     // return 0x80000000;
     return LLONG_MIN;
   }
   int min = list[0];
   long long maxdiff = LLONG_MIN;
   for (size_t i = 1; i < n; i++) {
     long long diff = (long long) list[i] - min;
     if (diff > maxdiff) {
       maxdiff = diff;
     }
     if (list[i] < min) {
       min = list[i];
     }
   }
   return maxdiff;
}


The new version of your function does not have any actual mistakes I could spot. It is good that you have replaced the assignment to *(reinterpret_cast<int*>(cursor)) with a call to std::copy_n because the old version (presumably) violated strict aliasing rules and therefore invoked undefined behavior. (Also think about alignment.) It also seemed wrong in your old function that you casted data.length() + 1 to short instead of int.

I have a few “soft” remarks, though.

Avoid output parameters

Taking a pointer by reference and then modifying does not appear pretty to me. Instead, I'd take the pointer by-value and return the number of bytes by which it was advanced.

std::size_t PackData(char * cursor, const std::string& data);

It looks better and allows for more flexible use.

Chose the appropriate library function

The string manipulation functions from the C standard library all operate on NUL terminated strings. That is, std::strcpy has to look at every byte of the string to determine whether it is the end of the string. You've mentioned that your string does not contain NUL bytes today. But what if it will do so in the future? Will you remember to update the function? And even if you are sure that NUL bytes will never be an issue, it is still less efficient than it could be. Since the std::string already knows its own length, you have a couple of options available.

std::memcpy – if you like doing things the C way
std::copy – if you like doing things the STL way
std::string::copy – if you like doing things the OO way

Note that none of these functions will NUL terminate the copied string, so you'll have to add the NUL byte yourself. Not hard to do.

cursor[size] = '\0';

Using std::memcpy could also help you with storing the length. Since its arguments are void pointers, there is no need to cast anything.

std::memcpy(cursor, &size, sizeof(size));

looks cleaner to me than

std::copy_n(cursor, sizeof(int), reinterpret_cast<char*>(&size));

Don't repeat yourself

Your code mentions the type of size three times. Once in the declaration – which is fine – and then two times in sizeof expressions. By using sizeof(size) instead of sizeof(int), you can eliminate this redundancy. If you ever change the data type, you only need to do so in one place and you can't get it inconsistent.

Verify your assumptions

The cast

const int size = data.size() + 1;

looks rather safe. But are you sure? Integer overflow is a nasty source of bugs and a potential entry door for crackers. I would recommend two things.

First, make the fact that you're narrowing explicit by spelling it out.

const auto size = static_cast<int>(data.size() + 1);

Note that I can use auto now in order to follow the advice from the previous section.

Second, add defensive code (before the cast) to verify your assumptions.

assert(INT_MAX > data.size());

This is safe if your function is only called with trusted input. If attackers are of concern, assert is the wrong tool because it may be compiled out and you don't want your debug builds to be safe only to open security holes in your release builds. Therefore, an explicit check like

if (INT_MAX <= data.size())
  throw std::invalid_argument {"data too large"};

would be preferred in this case.

This code is safe as long as sizeof(int) <= sizeof(std::string::size_type) which I believe is true on almost any implementation. However, it might still trigger a compiler warning about comparing a signed and an unsigned integer. Actually, size could be unsigned anyway.

Alternatively, you could use a helper function checked_cast<int>(data.size() + 1). I believe that the argument cannot overflow because a std::string always has to account for the possibility to NUL terminate its buffer.

Watch out for data leaks

I don't know about the environment in which your function is called but is the buffer that cursor points to aligned? If so, watch out for unused padding bytes after the end of the string and the next thing that is written into the buffer. They might leak information you'd rather not have anybody see.


There's a lot to cover and talk about here. I'm going to take a line by line approach, so this review might seem nitpicky (and it probably is), but there are some seemingly innocuous things here that can cause bigger problems given a chance.

const forReading = 1, forWriting = 2, forAppending = 8

This is good. I like well named constants. These are implicitly Public though. That means they're available to all scripts. Which is also okay. I see no reason these can't be, but it's always better to be explicit and declare the scope.

Public Const forReading = 1, forWriting = 2, forAppending = 8

public maxWaitTime
maxWaitTime = 60 '1800 '30mins
public connLogFileName
connLogFileName = "connectionLog.txt"

Neither of these should be Public. Nor should they be variables. They're constants and should be declared as such. Let the compiler warn you if you ever try to assign a new value to these.

public pathToRemoteServer
pathToRemoteServer = "c:\"
public errMessage
public fs
set fs = createObject("scripting.fileSystemObject")

pathToRemoteServer = "c:\"

'::::::::::::::::::::::::::::::

Same advice here. These variables should be private to the script. Also, you're reassigning the same value to the same variable just a few lines apart?? Make it a constant and forget it.

I try not to pick on names, but fs would be better named fso. The latter seems to be an idiom in the community. Generally, I don't recommend overly abbreviated names like this, but idioms are ok. VBA/VBScript developers will recognize both of these as a FileSystemObject.

'::::::::::::::::::::::::::::::
call mainSub()

'::::::::::::::::::::::::::::::
sub mainSub()

Two things jump out at me here.

mainSub isn't a good name. It doesn't say anything at all about what the subroutine does.
It doesn't seem to make much sense to have a subroutine here at all. You could remove the Sub...End Sub statement and just execute it in your main script without changing the semantics or execution at all. (I don't recommend actually doing that, but I'm not quite there yet.)

sub mainSub()
  call createLogFile()

  errMessage = ""
  dim curDir
  curDir = fs.GetAbsolutePathName(".")
  dim logName
  logName = curDir & "\" & connLogFileName
' ....
End Sub

'::::::::::::::::::::::::::::::
sub createLogFile()
  dim logName
  logName = fs.GetAbsolutePathName(".") & "\" & connLogFileName
  If not fs.FileExists(logName) Then
    fs.createTextFile logName, false
  End If
end sub

So, you're going to your file system object to get the current directory twice in rapid succession and sharing a variable between these two methods. That's smelly to me. createLogFile should take in a full file path as an argument. Then, connLogFileName doesn't need to be scoped outside of mainSub. Actually, I don't see a need for that constant at all in this case. You can keep it if you want, but I've removed it below.

sub createLogFile(logName)
  If not fs.FileExists(logName) Then
    fs.createTextFile logName, false
  End If
end sub

sub mainSub()

  errMessage = ""

  dim logName
  logName = fs.GetAbsolutePathName(".") & "\" & "connectionLog.txt"

  call createLogFile(logName)

  Dim aFile
  set aFile = fs.openTextFile(logName, forAppending, True)

I also think it would be worthwhile to pass pathToRemoteServer into mainSub as an argument. It makes the sub more re-usable, but I would definitely think up a decent name for it.

I would rename checkFolderPath. Consider this snippet.

 if (checkFolderPath(pathToRemoteServer)) then

Wouldn't it read better as:

if (folderPathExists(pathToRemoteServer)) then

Speaking of method names, I really recommend PascalCased method names. It distinguishes them from camelCased variable names.

I'm surprised this compiles.

downTime => maxWaitTime

In VBA this results in a compiler error and it's expected to be downTime >= maxWaitTime. Perhaps VBScript is more forgiving, but it also looks like the lambda operator from another popular Microsoft language. So two things happen here. I can't paste this into the VBA Editor and run it and it could cause confusion for someone expecting this to be the lambda operator.

':::::::::::::::::::::::::::::::::::::::::
function lineToWrite()
  dim curUser
  curUser = createObject("WScript.Network").userName
  lineToWrite = curUser & ": " & Now()     '& vbCrLf
end function

I like this function and the abstraction it provides, but you are calling it over and over and over to get the same string. Declare a variable and call this function once. Also, as an option, It would be completely acceptable to remove the curUser variable and one line this function.

Function LineToWrite()

    LineToWrite = CreateObject("WScript.Network").userName & ": " & Now()

End Function

Also, you should remove dead, commented out code. It serves no purpose but to clutter things.

One last thing. Your error messages kind of suck. It's one thing to abbreviate variable names, but it's an entire other matter to abbreviate error/log messages.

errMessage = "Error on crt: " & err.description
errMessage = "Error on cls: " & err.description
errMessage = "Error on del: " & err.description

Don't do that. Spell it out for whoever has to read that log.

It's also noteworthy that there's a lot of copy paste in the CheckFolderPath function, as evidence by the snippet above. It's wholly worth while to extract that logic into a function that takes an Err object and a string in as arguments.


Splitting a String into words and add to an array, Only using StringBuffer and String Array

Thanks for sharing your code,

This looks very good for just having a few weeks' experience.

Let's start with a some small things,

1 Initialization vs declaration

this line of code tweet myTweet; declares a variable, while this line of code myTweet = new tweet(); instantiates it. When possible it's preferable to do both on the same line. This has a few benefits.

There's less change for things to go wrong. In a larger application, there could be many things happening between declaration and initialization leading to potentially difficulty to track down bugs.
It makes the code easier to follow for other developers (and future you)

for these reasons, I would prefer to see

tweet myTweet = new tweet();
Scanner input = new Scanner(System.in);
String sentence = input.nextLine();

etc.

2 Java naming conventions

Classes should start with a capital letter. You'll notice all the standard library classes begin with a capital letter (String, List, Scanner etc.) while primitive types (int, float, double) start with a lower case letter. With this in mind, it would be better to have your class called Tweet

3-0 Add setters to classes only if you absolutely need to

If your code, you call myTweet.setSentence(sentence); setters generally exist when you need to update the state of an object some time after its creation, in this case, we update it right away! Why not simply pass sentence as another constructor argument, it could look like this.

Scanner input = new Scanner(System.in);
String sentence = input.nextLine();
Tweet myTweet = new Tweet(sentence);

No need to update the Tweet once it has been created.

3-1

Staying on the topic of unnecessary mutation, we call myTweet.computeSentence(); the first thing I notice about this method is that it has a void return type. This usually means one thing. side effects. In this context, a side effect means we call a method and something else is happening (in this case, we're mutating the state of the object.)

One other potential problem, is that in order for me to get the expected result from myTweet.getNewSentence(); I need to remember to call myTweet.computeSentence(); first! In a small program, not a big deal, but as our objects get more and more complicated, this becomes more of an issue. What if my entire main method could look like this.

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    System.out.print("Enter a sentence: ");
    String sentence = input.nextLine();
    Tweet myTweet = new Tweet(sentence);
    String [] newSentence = myTweet.getNewSentence();
    for(int y = 0; y < newSentence.length; y++){
        System.out.print(newSentence[y]+" ");
    }
    System.out.println();
}

This is very similar to what you already have. But there area few notable changes.
1. I declare and initialize variables at the same time.
2. I pass all dependencies to the Tweet constructor (the sentence) at creation time.
3. I don't need to remember to call certain setup methods (computeState)
4. Conform to Java naming standards (Tweet vs tweet)

4 Storing unneeded instance variables

Let's take a quick look at the Tweet class, so we store all these

private String sentence;
private int strlen;
private StringBuffer word;
private String newSentence[];
private String newWord;
private int wordCount;

I was curious as to why we need to store all these. In our constructor, we initialize a lot of them. Why not just do that in the getNewSentence method instead

We end up with a Tweet class that looks like

public class Tweet {

    private String sentence;

    public Tweet(String sentence){
        this.sentence = sentence;
    }

    //get method, returning new sentence to app class
    public String[] getNewSentence(){
        StringBuffer word = new StringBuffer();
        String newWord = " ";
        int wordCount = 1;

        int strlen = sentence.length();//get length of sentence
        for(int x = 0; x < strlen; x++){//transverse the string,
            if(sentence.charAt(x)==' '){//calculate word count
                wordCount = wordCount +1;
            }
        }
        String[] newSentence = new String[wordCount]; //use word count to set size of the array
        for(int j = 0; j < newSentence.length; j++){//transverse the array,
            for(int i = 0; i< strlen; i++){//transverse string,
                if(sentence.charAt(i) == ' '){//check if char is a space,
                    j = j+1;//if so,increment j by 1
                    word = new StringBuffer();//start a new buffer
                }
                else{
                    word.append(sentence.charAt(i));//char at i, append to buffer,
                    newWord = word.toString();//convert buffer to string,
                    newSentence[j] = newWord;//add to j'th place of array
                }
            }
        }
        for(int x = 0; x < newSentence.length; x++){//change any instance of cannot to can't
            if(newSentence[x].equalsIgnoreCase("cannot")){
                newSentence[x] = "can't";
            }
        }
        return newSentence;
    }
}

With this class, we don't need to worry about who used it before, or how they used it. It will never be in a bad state we can call getNewSentence all day long and it will always return the same thing, no need to worry about set up with setSentence or computerState

Hopefully you found this review useful, I'd like to reiterate again that this looks very good for just a few weeks! Keep it up!


Add item at the beginning of each inner array in jagged array

I guess your code will behave very bad performance wise.
I would suggest to create the cellsRange object first as a List<whatever> and add 0,linkDisplayFieldValue first and then call AddRange() on cellsRange passing row.ToList() as parameter.


From a once over:

The following is not DRY at all, you have to find a way to not do this:

//Types
'alphanum': {        'parsley-type': 'alphanum'    },
'email': {        'parsley-type': 'email'    },
'url': {        'parsley-type': 'url'    },
'number': {        'parsley-type': 'number'    },
'digits': {        'parsley-type': 'digits'    },
'dateIso': {        'parsley-type': 'dateIso'    },
'phone': {        'parsley-type': 'phone'    },

I am pretty sure you can throw all that way by changing to the below statement:

att = $.fn.parsley.mapping[validationName] || {  'parsley-type': validationName  };

Also, $.fn.parsley.mapping could use some aligning to look better
You are calling $.map without capturing the array it returns, perhaps you meant to use forEach ? Also, it seems that your code will not work correctly if there is more than 1 property in parsley.mapping.You keep assign to the same key and value.
Your var statement is too messy:

var name, validations, validationName, validationValue, att, key, value, form = $(this),
    addValidations = function (validationRules) {

Comparisons with undefined should be either with === or by doing a falsey check so use either if(validations === undefined) or if(!validations)
There is no var validation for for(validation in validations){
There are plenty of comma and semicolon problems, you should use jshint to find & solve them

All in all, I like the value of your wrapper, but I think it needs some more polishing.


Printing a singly linked list with time complexity O(n) and space complexity O(sqrt(n))

Reverse the list

A quick search on the internet will show you that you can reverse a linked list in-place using \$O(n)\$ time and \$O(1)\$ space.  All you need to do after that is print the list in order:

void display_reverse(List *list)
{
    list = reverseList(list);
    printList(list);
    list = reverseList(list);
}

This whole function will take \$O(n)\$ time and \$O(1)\$ space.

Without modifying the list

If you can't modify the list, you can do it by making copies of part of the list.  If the list is \$n\$ items, you can make \$\sqrt n\$ sized sublist copies, and reverse/print them one at a time.  To do that, you will need to use a \$\sqrt n\$ sized array to keep track of these sublists.  Here is what the program would look like:

void display_reverse(const List *list)
{
    int n     = countItemsInList(list);
    int sqrtn = sqrt(n);
    const List *subLists[sqrtn];
    const List *p;

    // Remember the head of each sqrtn sized sublist
    for (int i=0, p = list; i < n; i++, p = p->next) {
        if (i % sqrtn == 0)
            subLists[i / sqrtn] = p;
    }

    // Make a reversed copy of each subList and print it.
    for (int i=sqrtn-1; i >= 0; i--) {
        int subListSize = sqrtn;
        if (i == sqrtn-1) {
            // The last subList size may be different.
            subListSize = n - (sqrtn-1) * sqrtn;
        }
        List *tempList = createReversedList(subList[i], subListSize);
        printList(tempList);
        freeList(tempList);
    }
}

static List *createReversedList(const List *head, int size)
{
    List *ret = NULL;

    for (int i=0; i<size; i++) {
        List *newNode = malloc(sizeof(List));
        newNode->data = head->data;
        newNode->next = ret;
        ret = newNode;
        head = head->next;
    }
    return ret;
}

This program uses \$O(\sqrt n)\$ space because it uses one array of that size and one temporary list of that size.  It runs in \$O(n)\$ time.

You may want to round up using sqrtn = ceil(sqrt(n)).  That prevents the last sublist size from exceeding sqrtn, so it has a slightly better space utilization.


Create a structure to store data about a movie

Looks pretty good overall. The biggest issue that I see is that the input reading doesn't check for errors, and it's pretty rough. It can be helpful with assignments like this to build up a little library of IO helpers:

// Read a line from the provided stream.
std::string readLine(std::istream& is) {
    std::string line;
    if (!std::getline(is, line)) {
        // Could stand to be a more specific exception, but you get the point
        throw runtime_error("Unexpected stream failure");
    }
    return line;
}

// Helper to output a prompt and read a line.
std::string promptLine(std::ostream& os, const std::string& prompt, std::istream& is) {
    os << prompt; // Note that I've assumed output won't fail. Depending on situation,
                  // that might be a bad assumption.
    return readLine(is);
}

// Attempt to parse an int from a line of input that must contain only an int.
bool readIntLine(std::istream& is, int& val) {
    std::string line = readLine();
    char* parseEnd = nullptr; // NULL if < C++11
    int val = std::strtol(line.c_str(), &parseEnd, 10);
    return (parseEnd - line.c_str() == line.size());
}

// Keep showing the same prompt until the user inputs an integer (and only an integer)
int promptInt(std::ostream& os, const std::string& prompt, std::istream& is) {
    int val;
    do {
        os << prompt;
    } while (!readIntLine(is, val));
    return val;
}

// If you wanted, you could take it a step farther and make convenience wrappers that assume std::cin/std::cout.
// Example:
int promptInt(const std::string& prompt) {
    return promptInt(std::cout, prompt, std::cin);
}

This looks like quite a bit of code (and it is -- unfortuntely IO just kind of sucks to do non-carelessly), but it makes reading in the data a bit cleaner while also providing verification of data:

MovieData getMovieData()
{
    MovieData movie;

    movie.title = promptLine("Enter the title of the movie: ");
    movie.directory = promptLine("Enter the name of the movie's director: ")
    movie.year_released = promptLineInt("Enter the year the movie was released: ");
    // ...

    return movie;
}

Other minor issues:

Using using namespace std; is a bad habit to get into.
Overusing std::endl can likewise be a bad habit as it not only writes a new line but also flushes the buffer. This can result in surprisingly bad performance when heavvy IO is involved. It's much better to use '\n' by default and only use std::endl when you specifically want a flush to happen (for example, your print function could use all \n and then have one std::endl at the end).
Some of your comments are a bit pointless and should be removed to reduce noise.
system("PAUSE") is a bad habit

As an aside, it might be worth noting that there's actually a super useful pattern of reading things from a stream. It's relatively poor performance considered to something specialized like std::strtol, but it can be quite handy if you're in a bind (i.e. can't use Boost or some other library) and need something highly generic:

template<typename T>
bool readLine(std::istream& is, T& val) {
    std::string line;
    if (!std::getline(is, line)) {
        // throw exception ...
    }
    std::istringstream ss(line);
    return (ss >> val);
}

It also might be worth noting that instead of a bool, functions like this will often return the input stream with certain bits set. In other words, some people prefer to set the fail bit instead of return false.


Pytest fixture for testing a vertex-parsing function

This is one of the way you can use fixtures. Fixtures are a form of dependency injection. For example, I use pytest to execute integration testing for an embedded target over ssh. So I want to reuse the ssh connection between tests.

The pytest fixture documentation has a similar example with SMTP:
https://docs.pytest.org/en/latest/fixture.html

Note that if you want to reuse the same exact object between tests, you need to specify the scope @pytest.fixture(scope='module')

Another reason to use fixtures is that they are the basis for writing plugins. Here's the pytest documentation on turning fixtures into plugins:
https://docs.pytest.org/en/latest/writing_plugins.html

If you want to learn more about fixtures I would recommend checking out the source for some of the 3rd party plugins they have one their website:
https://pytest.readthedocs.io/en/2.7.3/plugins_index/index.html

So that should give you an idea that fixtures are really flexible and people have implemented a lot of really cool ones.

Pytest fixtures let you do things like examine the values of existing command line options and add new command line options.
https://docs.pytest.org/en/latest/example/simple.html#pass-different-values-to-a-test-function-depending-on-command-line-options


Simplifying conditional statements for transaction code

You could do it like this:

public void func()
{
    if (string.IsNullOrEmpty(customerpay) || string.IsNullOrEmpty(warrantypay) || string.IsNullOrEmpty(maintanceplan))
        return;

    if (customerpay != "Include" && warrantypay != "Include" && maintanceplan != "Include")
        return;

    List<char> parts = new List<char>();
    if (customerpay == "Include")
        parts.Add("C");
    if (warrantypay == "Include")
        parts.Add("W");
    if (maintanceplan == "Include")
        parts.Add("I");

    transactiontype = ",[Population].[Transaction Type Code].&[" + string.Join("^", parts) + "]";
}

First, we simply return if any of the strings is empty; by inverting the logic, we can reduce one indentation level that makes the code unecessarily complicated. We also return for the single case that isn’t handled in your original code: If all three strings are not "Include".

After that, it’s easy once you find out the pattern of your string. The only changing part of your result string is in the brackets at the end. There are three possible characters: C, W, and I. They appear if the corresponding string equals to "Include". The characters are separated by a ^. So we just check each condition alone, and collect the characters in a list. Then we join with the separation character and build the final result string.


Don't import 'wildcards'

Especially if the module is not part of the Standard Library people will be confused and not understand where the function is coming from. You can cut down typing as follows:

 import pyprimes as pr

Use longer names

def sequence_exists(l,ls,limit = 100):

In the above l and ls tell nothing to the reader.


Tag Cloud using 2 queries (one nested), and a foreach loop: Is there a better way?

Note: Your table and especially column names are quite verbose. I would remove the table name from each column as a first start and be more consistent with the names. I'll use better names below. You'll have to map it out yourself.

You can get the used tags with their counts in a single query with this statement:

select
    tag_id,
    tag_name,
    count(publication_id)
from
    tag join publication_tag using (tag_id)
group by
    tag_id


Recursive JavaScript permutations function

Remarks

The algorithm used seems vastly ineffective (lots of sliceing and concating greatly contributes to it),
The strict equality operator shall be used in place of the equality operator wherever applicable,
Use the for...of statement instead of for...in.

Rewrite (ES2015+)
The below rewrite is my implementation of the non-recursive variant of the Heap's algorithm, which might be the most effective algorithm for the job. Another noteworthy one is the "Steinhaus–Johnson–Trotter algorithm", but it's more complicated and less performant in practice.
Please note, many portions of the below code could have been written in a far more idiomatic way, e.g. the swap function could have been completely replaced with a destructuring assignment which is far more concise, but that would come at a price of performance, which in this case is a critical point.
const permute = arr => {
  const permutations = [];

  const swap = (a, b) => {
    const tmp = arr[a];
    arr[a] = arr[b];
    arr[b] = tmp;
  };

  const c = new Array(arr.length).fill(0);
  permutations.push(arr.slice());

  let i = 0;
  while (i < arr.length) {
    if (c[i] < i) {
      swap(i, i % 2 ? c[i] : 0);
      permutations.push(arr.slice());

      c[i] += 1;
      i = 0;
    }
    else {
      c[i] = 0;
      i += 1;
    }
  }

  return permutations;
};

Benchmark
The times change, try it yourself!

Original ― 69,330.36 ops/s ± 1.05% (93.9% slower)
The above implementation ― 1,135,764.38 ops/s ±2.29% (fastest)


This isn't quite a full review, but here goes anyway:

It looks like you're using 8-space indents. That's quite a lot. I think 4 is more common, but it is a matter of preference and it is consistent, so it's definitely not wrong
You have KEY, presumably a typedef of char*, but then you call strcmp on it. If you want it to be general across key types (which is a pretty good idea IMO), you should pass in a comparator function that takes two keys as arguments.
I'm going to assume that the other fields of TNODE exist for some reason, but is there a chance you could move them out to rbtree_t and leave TNODE smaller?
I don't know the naming conventions for types in C, so don't take this as implicit agreement or disagreement
talloc and lalloc probably don't need to be their own functions; malloc(sizeof(TNODE)) is probably sufficient


Environment-specific code in @Async mail method with Spring

Use Spring's dependency injection more aggressively

You are right to be suspicious about hardcoded environment-specific logic.
But you're in luck. This is one of the typical problems that Spring can help you solve.

One way to solve this is to create an interface for controlling the destination email address, and inject an implementation appropriate for the environment. For example:

interface OutgoingEmailController {
    void adjustOutgoingEmail(MimeMessageHelper helper, String email, String body);
}

Implementation to inject in QA:

class QAOutgoingEmailController implements OutgoingEmailController {
    @Override
    public void adjustOutgoingEmail(MimeMessageHelper helper, String email, String body) {
        if (isTestMode()) {
            if (!email.equals(getTestEmailAddress())) {
                helper.setTo(getTestEmailAddress());
                body += "<br/>This email was originally intended for " + email +
                        " but was redirected to " + getTestEmailAddress() + " for testing.";
                helper.setText(body, true); //HTML on
            }
        }
    }
}

Implementation to inject in other environments:

class CommonOutgoingEmailController implements OutgoingEmailController {
    @Override
    public void adjustOutgoingEmail(MimeMessageHelper helper, String email, String body) {
        helper.setTo(email);
        helper.setText(body, true);
    }
}

In your original code you will have an @Autowired OutgoingEmailController outgoingEmailController;, and the IFFY code replaced with outgoingEmailController.adjustOutgoingEmail(helper, email, body);.

Or something like that.

Other remarks

It's odd that you check for null email at the beginning but check for null body at the end. It would be better to move the check on the body further up to the beginning.


Confirmation to delete items using a jQuery modal dialog

The main benefit to your refactoring job is to clarify what the code is doing. The original version lacks names for things, so does clicking the .button-delete element delete the item? After further reading the code, "oh, it appears to be showing a modal dialog. Now where to we actually delete the item..." - so your intent here is very good. :)

Use $(...) instead of $(document).ready(...) as this is more idiomatic for jQuery.

So $(document).ready(App.onReady); becomes $(App.onReady);
No need to App.onReady, just use an anonymous function:

$(function() {
  App.initHandlers();
});

Remember that the context of what this points to changes based on how you call a function in JavaScript. Using the code above means the this variable in initHandlers refers to the App object, instead of the window object.
Don't maintain state if it is not necessary

The rowCount and visibleCount properties are only referenced in the updateToolbar. Use local variables instead of properties, since you overwrite the values of those properties on every invocation of updateToolbar
Cleaning up repeated HTML code

The HTML code to generate the
 tag in the toolbar has only one minor difference, which is the HTML class name. Use a local variable for that class name and then have one hard coded HTML string for the heading tag:

var headingClass = App.visibleCount === App.rowCount
    ? "label-default"
    : "label-primary";

var headingMarkup = '
Showing ' + App.visibleCount + ' of ' + App.rowCount + ' rows
';

$('div.toolbar').html(headingMarkup);

The name App is pretty generic. Methods like "initHandlers" and "deleteRow" are also too generic. This class could end up expanding way beyond what it should. A more focused approach will prevent this class from becoming an unmaintainable monster later on.

Based on the naming of things in the code, it looks like something that is deleting items from a "shopping cart" table. A more appropriate name would be ShoppingCartTableController instead of App.

Now names like "initHandlers" and "deleteRow" have a little context, and a clear focus.

Calling this a "controller" is appropriate here, because it is responding to events in the View, which is precisely what a "Controller" does in the MVC design pattern.
In the deleteRow method, a <form> tag is created, then two hidden inputs are appended. There is a hidden cost to this. HTML is being parsed 3 times, and the document tree on the page is being modified 3 times. With a little rearranging you can parse the HTML once, and only append to the document tree once:

// Build form for submission
var html = '<form action="" method="POST">'
         +      '<input type="hidden" name="id" value="' + id + '">'
         +      '<input type="hidden" name="reqType" value="Delete">'
         + '</form>';
var $form = $(html);

$(document.body).append($form);

$form.submit();

Second of all, passing $form into the $ function is completely unnecessary, since $form is already a jQuery object. Just call $form.submit() directly.

Refactoring this into an object isn't really gaining you anything. Instead, you could opt for a named function that much more clearly makes your intent known:

function ShoppingCartTableController() {
  var showDeleteModal = function (e) {
    // ...
  },
  deleteRow = function (e) {
    // ...
  },
  log = function (message) {
    if (ShoppingCartTableController.debug) {
      console.log(message);
    }
  };

  $('.delete-button').click(showDeleteModal);
  $('#confirm-delete-button').click(deleteRow);
}

ShoppingCartTableController.debug = true;

$(ShoppingCartTableController);


Customize data types in a generated model with hibernate

It's not unreasonable that a maximum length should be specified for a field that is backed by a VARCHAR. In some frameworks, for example Django (Python), a max_length parameter is mandatory to create a CharField, but optional for a TextField. This makes sense: how else can the framework know the size of the column. A VARCHAR column needs a max size.

Make the maximum size a conscious design decision when using a relational database as storage. If the data is text and you need to support arbitrary length, then in the database it should be stored as a TEXT field instead of a VARCHAR. For that, use @Column(columnDefinition="text") or @Type(type="text"), as @ferada said in a comment,
and as discussed in this related post.

You remarked in a comment that H2 used the type VARCHAR(2147483647).
That's an irrelevant implementation detail of how H2 supports TEXT type.
It's indeed a bit funny.


As a guideline: your inner loop should contain no operation more expensive than O(log(N)). This means no iterating over the entire closed/open list, and no making heaps over and over again! Here's how:

Use a std::set sorted by weight instead of a heap. begin() is your next node, and to update the weight of a node first remove it from the set, change the weight, and put it back again.
Don't use find_if to test for set inclusion. Use an std::unordered_set for the closed or open nodes.


Simulating Natural Sorting in MySQL with PHP

Essentially, you want to have a custom, non-trivial sorting order,
based on logic that doesn't exist in the table schema and not supported by standard SQL operators.

The general (and perhaps obvious) solution to this problem seems to be including the necessary data in the table schema explicitly.
In other words, adding a dedicated column to represent the sorting key seems a sensible solution.

Suppose it's possible to use some SQL operations to generate this sorting key on the fly.
The problem with that is that you would have to re-type the (potentially complicated) operation every time you want to select an ordered subset from the table.
An option to make that more workable is embedding the sorting key logic inside a view on the source table.
If this approach is possible,
then the right solution will depend on the impact on performance due to the recalculation of the sorting key column in the view every time you access it.


Use Braces:
Consider using braces for more readable code:

public static Direction vectorToDirection(Vector2 vector) {
    if (vector.y >= 0) {
        if (vector.x >= 0) return NORTH_EAST;
        else return NORTH_WEST;
    } else {
        if (vector.x >= 0) return SOUTH_EAST;
        else return SOUTH_WEST;
    }
}

Becomes (with eclipse Ctrl + Shift + F):
public static Direction vectorToDirection (Vector2 vector) {
     if (vector.y >= 0) {
         if (vector.x >= 0) {
             return NORTH_EAST;
         } else {
             return NORTH_WEST;
         }
      } else {
         if (vector.x >= 0) {
             return SOUTH_EAST;
         } else {
             return SOUTH_WEST;
         }
     }
}

And suddenly it becomes extremely obvious and readable what happens here.
Naming:
Additionally I'd consider naming your method fromVector() instead. Compare:
Direction.vectorToDirection(someVector);

against
Direction.fromVector(someVector);

Documentation:
When I see the implementation I know, but how would anyone outside know you prefer east > west and north > south? Write some JavaDoc. Example:
/**
* @param vector the 2-dimensional vector to be converted to a direction
* @returns The Direction. hereby North is preferred over South and
* East is preferred over West.
* Example: Direction.fromVector(new Vector2(0, 0)); will return NORTH_EAST
* Direction.fromVector(new Vector2(-1, 0)); will return SOUTH_EAST
*/
public static Direction fromVector(Vector2 vector) {
// ...


I think this is fairly impressive. I don't know if I would have done this in-place if I sat down to do this today. That said, I do see a few things you could improve.
Naming
I think your variable names could use some work. Why did you choose Wall? That name just doesn't strike me as useful in this context.
I notice that you're mixing capitals and lowercase letters for the first letter of your variables. Typically variables start with a lowercase letter and type names start with an uppercase letter. You don't necessarily have to follow that convention, but you should be consistent.
C++
The only line of code in this that differentiates it from C is the print statement, which I assume is just for debugging. If you #include <utility> you get some very useful functions. (You'll need to #include <algorithm> if you're using C++ that pre-dates C++11.) For example, std::swap() will swap 2 values for you without the need to write out 4 lines of code:
std::swap(Array[Wall], Array[index]);

does the same thing as:
int Temp = 0;   //Variable used for swaping array members
...
            Temp = Array[Wall];
            Array[Wall] = Array[Index];
            Array[Index] = Temp;

Also, you don't need std::endl where you've used it. That will flush the buffer which will slow things down. You can simply use:
std::cout << Wall << "\n";

And if you're really paranoid, you can add a single call to:
std::cout << std::endl;

after QuickSort returns;
Recursion
As you found, when you have a deeply recursive function, it can eventually eat up the entire stack if you're not careful. Luckily, you can eliminate recursion in many cases. I modified yours to remove the recursion by adding a simple std::queue and putting the ranges in the queue instead of calling back into the function. First, I made a simple struct to hold a range of indexes to sort:
struct Range {
    int start;
    int end;

    Range(int newStart, int newEnd) : start(newStart), end(newEnd) {}
};

Then I updated the function to use a std::queue and the new Range type:
void QuickSort(int* array, int start, int end)
{
    std::queue<Range>  queue;
    queue.push(Range(start, end));
    while(!queue.empty())
    {
        Range next    = queue.front();
        queue.pop();

        int start = next.start;
        int end = next.end;
        int Wall = start;
        if (start < end)
        {
            for (int Index = start; Index < end; Index++)
            {
                if (array[Index] <= array[end])
                {
                    std::swap(array[Wall], array[Index]);
                    Wall++;
                }
            }
            std::swap(array[end], array[Wall]);
            queue.push(Range(start, --Wall));
            queue.push(Range(++Wall, end));
        }
    }
}

I kept most of your code, but used std::swap and removed the recursion.
To be honest, I didn't think the performance of your version was bad at all. It seemed to work plenty fast for me.


Counting Monday and Friday from a Date Range

Your code is already good enough.

static int CountDays(DayOfWeek day, DateTime start, DateTime end)
{
    start = start.Date.AddDays((7 + day - start.DayOfWeek) % 7);
    if (end < start)
        return 0;
    else
        return ((int)(end - start).TotalDays) / 7 + 1;
}


Recursion function for prime number check

Python and recursion are not a good mix, because Python doesn't do tail call optimization.  (There's a fun blog post here that explores a cheesy workaround that you probably don't want to do for this project: https://chrispenner.ca/posts/python-tail-recursion)

Leaving that aside, there are two opportunities I see for optimization:

if i + 1 == n:
    return True

The largest minimum factor of any given number is going to be its square root, so you don't need to look for factors all the way up to n.

return has_divisors(n, i + 1)

If n wasn't divisible by 2, it's not going to be divisible by any other even number, so this recursive call is a waste of time (and stack space) at least half the time.  Are there any other ways you might be able to know before you recurse that a given new value of i isn't going to be fruitful?


Everything's on the front-end You're using HTM to interpret the JSX by putting the JSX through a template literal. It's quite an interesting option, but for a professional project, I think compiling the JSX beforehand in a build process would be a better choice:

It's very easy to make syntactical typos in the template literal, and you have to run the script in order to see them. If something gets conditionally rendered, you may not see problems with your syntax until the component gets rendered, which may be uncommon; the potential bugs will be significantly harder to encounter and fix. In contrast, if you put the JSX inside a JSX file, and use a syntax-aware IDE like VSCode, you'll be able to spot such mistakes on sight and fix them immediately.
Transpiling the script ahead of time also makes things much easier if you decide to make the project larger. For example, if you have component A and notice that something isn't working right with it, you could have a standalone A.jsx file that you could go to and debug. (In contrast, if you have, say, 200 or 400 or 1000 lines of code in a single file without a build process, it gets more difficult to navigate around than it should be)
Having standalone .js / .jsx files also allows for linting, which I consider to be absolutely essential to enforcing code style and quality, and which can turn difficult-to-debug runtime errors into trivially fixable compile-time errors.
It also allows you to transpile ES2020+ syntax down to ES2015 or ES5 or whatever you prefer, which can make code easier to read and write while remaining compatible with as many browsers as possible.

It's just an option to consider. If you're not happy at the amount of setup it requires, you can use boilerplate like create-react-app so that it's nearly ready to go out of the box.
Avoid let and reassignment When variable names are permitted to be reassigned, it can make code more difficult to understand at a glance, when you always have to keep in mind "This variable was declared with let, so I need to be on the lookout for when it may be reassigned." (Linting rule: prefer-const). See this post on softwareengineering about the topic. There are a number of other places in the code where you're using let where const can be used instead.
In the reducer, rather than reassign store and then return it at the bottom of the switch, you can return it immediately. (You could also consider avoiding the switch here, since it requires a lot of unnecessary boilerplate).
// When an argument list requires multiple lines,
// I think it's easier to read to put each argument on a separate line like this:
function reducer(
    model={total: 0},
    action={type:'', payload: null}
) {
    switch(action.type){
        case 'TOTAL_COST':
            return { total: action.payload.total };
        default:
            return model;
    }
}

or, if the reducer won't be expanded in the future:
function reducer(
    model={total: 0},
    action={type:'', payload: null}
) {
    return action.type === 'TOTAL_COST'
        ? { total: action.payload.total };
        : model;
}

this binding and mount actions You do:
constructor(props){
    super(props);
    this.state = {
        principal: 1000,
        years: 7,
        rate: 0.025
    };
    this.submit = this.submit.bind(this);
    this.update = this.update.bind(this);
    this.submit(new CustomEvent('init'));
}

There are 2 improvements that can be made here: first, consider using class fields to define the methods instead of using .bind in the constructor, to be more concise and avoid boilerplate. Secondly, populating the component initially with this.submit(new CustomEvent('init'));, an event that is passed only so that calling e.preventDefault on it later doesn't throw is weird. How about using optional chaining in submit instead of passing a parameter?
class App extends React.Component{
    state = {
        principal: 1000,
        years: 7,
        rate: 0.025
    };
    constructor(props){
        super(props);
        this.submit();
    }
    submit = (e) => {
        e?.preventDefault();
        this.props.dispatch( actions.updateTotal(this.state) );
    }
    update = (e) => {

You could also consider using functional components instead; React recommends using them instead of class components for new code - they make code a bit easier to understand and maintain.
Update You have:
update(e){
    let { valueAsNumber, value, name } = e.target;
    const state = {...this.state};
    if(isNaN(valueAsNumber)){
        valueAsNumber = 0;
    }
    state[ name ] = valueAsNumber;
    this.props.dispatch( actions.updateTotal(state) );
    this.setState({[name]: valueAsNumber});
}

When using React, seeing something like
state[ name ] = valueAsNumber;

should look scary, because it looks very close to mutating state, and state should never be mutated in React - see here for lots of articles on the subject. While your current method works, it may well be worrying at a glance. Consider using a more functional approach, to construct the new state all at once, without mutation:
update = (e) => {
    const { valueAsNumber, value, name } = e.target
    const newState = {
      ...this.state,
      [name]: valueAsNumber || 0
    };
    this.props.dispatch( actions.updateTotal(newState) );
    this.setState(newState);
}


Note: I did not check whether your code matches the formula correctly and I am not an expert of the mathematical background. I only refer to your code.

Style

[12,11,13,13, 9,10,10,13, 5,10,10,13,10,10, 5, 8, 9, 8, 8, 9, 9,10,11, 5,12]

This looks very inconsistent. You should add a space after each comma.

Naming

Xmean and X are unusual names for variables. x_square is the style you should use for Python, which is lower case with underscores, also known as "snake case".

Your names however make no sense at all semantically. You can name local variables x and y if they are e. g. coordinates, or if you use them for iterating. If they represent lists of numbers, why not just call them numbers1 and numbers2? (This might still not be perfect, but it shows what the variables mean. Edit: Note that this mainly concerns the problem of having two variables that only differ in being lower/upper case, and not nowing what x is somewhere inside your code, whereas numbers tells you that it is a collection or sequence of numbers. See below.) Note that I used a lower case x to refer to your X. Having another x later is the next problem. How do you know the difference without reading your whole code again?

x = [var-Xmean for var in X]

This took me some time to understand. You can improve it by using a common iterator variable like i and adding spaces around operators. With these improvements, and also better variable names, this could be for example:

subtracted_average = [i - mean_x for i in numbers1]

sum_xy = sum(xy)

Saving intermediate results of calculations like this is good, when you need them more than once. But here you don't. So sum(xy) is more readible if it is inside of another formula than sum_xy.

sum_x_square_sum_y_square

If you read this, do you know what it means without reading the code next to it? Is it a sum of sums? A product of sums? Or a completely different thing altogether? When trying to find a good variable names, think about "what is this"? The answer might be e. g. "the product of sums of squared numbers". product_of_sums_of_squared_numbers is long, but it tells you what it is.

Implementing Formulas

Judge for yourself. What is more readible?

1.

sum_x_square = sum(x_square)
sum_y_square = sum(y_square)

sum_x_square_sum_y_square = sum_x_square*sum_y_square
sqrt_sum_x_square_sum_y_square = math.sqrt(sum_x_square_sum_y_square)

or 2.

result = math.sqrt(sum(x_square) * sum(y_square))

The second one is actually how you write formulas in maths. So when implementing a function to represent that formula, go the same way. (Hint: Maybe this code should be a function.)

Using Functions

def pearson_correlation(numbers_x, numbers_y):
    mean_x = sum(numbers_x)/len(numbers_x)
    mean_y = sum(numbers_y)/len(numbers_y)

    subtracted_mean_x = [i - mean_x for i in numbers_x]
    subtracted_mean_y = [i - mean_y for i in numbers_y]

    x_times_y = [a * b for a, b in list(zip(subtracted_mean_x, subtracted_mean_y))]

    x_squared = [i * i for i in numbers_x]
    y_squared = [i * i for i in numbers_y]

    return sum(x_times_y) / math.sqrt(sum(x_squared) * sum(y_squared))

Call it like this:

# Contrary to what I said above about variables in general,
# the names X and Y are ok here because they match the names in the formula.
X = [12, 11, 13, 13, 9, 10, 10, 13, 5, 10, 10, 13, 10, 10, 5, 8, 9, 8, 8, 9, 9, 10, 11, 5, 12]
Y = [11, 10, 10, 10, 9, 13, 10, 11, 6, 7, 13, 14, 14, 11, 11, 10, 10, 7, 8, 12, 11, 11, 8, 7, 13]

print(pearson_correlation(X, Y))


If this is your real use-case then I'd not go beyond the obvious optimizations. In this case you're creating a new string for each replacement, you can use StringBuilder.Replace() instead:

public string ReplaceTokenBySample(string value)
{
    var result = new StringBuilder(value);
    GetTokenList().ForEach(x => result.Replace(x.TokenValue, x.SampleValue));

    return result.ToString();
}

If instead of List<Token> you have IEnumerable<Token> (or if you want to avoid List<T>.ForEach()) then you can use:

public string ReplaceTokenBySample(string value)
{
    GetTokenList().Aggregate(new StringBuilder(value),
        (result, item) => result.Replace(item.TokenValue, item.SampleValue));

    return result.ToString();
}

Few things to consider:

You're performing ordinal case-sensitive comparison, it seems to be appropriate to replace placeholders with their actual value and it has the benefit to be reasonably fast. If this is not the case then you should definitely go with t3schb0t's answer (which handles this properly and it's incredibly more readable.)
Parameters should be camelCase.
It's usually confusing to overwrite parameters value with something else (especially for non trivial code), compiler is able to optimize your code to get the best of it even when using a local variable.

Few more notes about overall design: you do not validate your parameters anywhere, if they're only used internally to your assembly then mark them internal or private (as appropriate) and ASSERT about their content (for example: why do you declare Token as public?)

Names sound little bit strange, you do not need to repeat the type in the name: TokenSample and TokenValue inside the Token class (and StringValue for a value of type String).

If you intend to fill Token programmatically then adding a Token(string, string) ctor may help to keep your code shorter.


General

As per PEP 8 conventions, the variables in functions should be in lowercase.
Adding docstrings is recommended. PEP 257
Names should be short and meaningful. For example, convert_number_to_binary should actually be to_base_minus_two. Also, calculate_number should be from_base_minus_two
Use type hints
Instead of x == 0 python allows you to use use not x. Similarly, x != 0 can be replaced with x.
Envelop the main code inside if __name__ == '__main__':. This will prevent the code from being run if imported from another module.
Following  @Martin R's advice, you can change -2 to a constant BASE

Function solution

value = math.ceil(from_base_minus_two(A) / 2)
p = to_base_minus_two(value)
return p

Can be replaced with the one liner:

return to_base_minus_two(math.ceil(from_base_minus_two(a) / 2))

Function from_base_minus_two

total = 0
for i in range(0, len(a)):
    total += a[i] * BASE ** i
return total

Instead, you can use:

return sum(j * BASE ** i for i, j in enumerate(a)))

Function to_base_minus_two

The value you are finding isn't exactly binary. Change it to base_minus_two

You don't need to use

if number == 0:
    return base_minus_two

Automatically, the while loop will terminate immediately as number is 0, and will return base_minus_two which is []

Here's what the final code might look like:

import math
from typing import List

BASE = -2

def from_base_minus_two(a: List[int]) -> int:
    """ Converts base 'BASE' to decimal """

    return sum(j * BASE ** i for i, j in enumerate(a))

def to_base_minus_two(number: int) -> List[int]:
    """ Converts decimal to 'BASE' """

    base_minus_two = []

    while number:
        number, remainder = divmod(number, BASE)

        if remainder < 0:
            number += 1
            remainder -= BASE

        base_minus_two.append(remainder)

    return base_minus_two

def solution(a: List[int]) -> List[int]:
    """

    * Converts from 'BASE' to decimal
    * Divides the decimal by 2
    * Converts the decimal back to 'BASE'

    """

    return to_base_minus_two(math.ceil(from_base_minus_two(a) / 2))

if __name__ == '__main__':
    print(solution([1, 0, 0, 1, 1, 1]))


Improving createKey

First of all, when the same couple of lines appear duplicated several times, there's clearly a problem. I'm talking about this one:

if(isSizeTwenty == true){
    break;
}

A good first step is to try to eliminate this. Consider this situation:

boolean isSizeTwenty = false;

for (int i = 0; i < 20; i++) {

    if(isSizeTwenty == true){
        break;
    }

    // ...

    if(isSizeTwenty == true){
        break;
    }
}

Notice that the first check inside the loop will be always false: isSizeTwenty is initialized with false, and since you have this check as the last step of the loop, the condition can never be true at the beginning of the loop.

Also, don't write conditions on boolean expressions like this:

if (someboolean == true) { ... }

You can write simpler and better like this:

if (someboolean) { ... }

But, the entire method can be refactored far better, for example:

public String createKey() {
    int letterWeighting = determineLetterWeigthing();
    int numberWeighting = determineNumberWeigthing();

    int[] chosenNumbers = selectNumbers();
    char[] chosenLetters = selectLetters();

    StringBuilder key = new StringBuilder();

    while (key.length() < targetLength) {
        for (int j = 0; j < letterWeighting && key.length() < targetLength; j++) {
            int randomIndex = random.nextInt(chosenLetters.length - 1);
            key.append(chosenLetters[randomIndex]);
        }
        for (int k = 0; k < numberWeighting && key.length() < targetLength; k++) {
            int randomIndex = random.nextInt(chosenNumbers.length - 1);
            key.append(chosenNumbers[randomIndex]);
        }
    }
    return key.toString();
}

I made a couple of changes there:

Replaced the number 20 with a meaningful variable named targetLength
Removed of the isSizeTwenty variable, and moved the condition key.length() < targetLength
Moved StringBuilder inside the method. No need to make that a member variable
Replaced the outermost for (int i; i < 20; i++) { ... } with a more natural while (key.length() < targetLength) { ... }
Replaced the hardcoded number 9 with chosenLetters.length - 1 and chosenNumbers.length - 1. This is more than just about removing another magic number, this is also safer, because now randomIndex can never be accidentally out of bounds. Now it is derived from the length of the available letters and numbers.
Renamed randomNum to just random, because there is nothing "num"-like about an instance of Random

Improving determineLetterWeigthing and determineNumberWeigthing

You could reduce these methods to single lines:

private int determineLetterWeigthing() {
    return random.nextInt(4) + 1;
}

private int determineNumberWeigthing() {
    return random.nextInt(4) + 1;
}

Unit testing

I would make random and targetLength final members, and add these constructors:

private final Random random;
private final int targetLength;

public Key(int targetLength) {
    this(targetLength, new Random());
}

public Key(int targetLength, Random random) {
    this.random = random;
    this.targetLength = targetLength;
}

This way, and thanks to the new version of createKey that returns the key instead of printing it, now you can add some unit tests:

@Test
public void testExampleKeys() {
    assertEquals("VAT3735TVV4949RVJ793", new Key(20, new Random(0)).createKey());
    assertEquals("SBM8PBJ8PSJ6MWS2SBO2", new Key(20, new Random(1)).createKey());
    assertEquals("DGG77DJS28SDP13GGD77", new Key(20, new Random(2)).createKey());
    assertEquals("PGB844MGM477GCG728PL", new Key(20, new Random(3)).createKey());
}

@Test
public void testCreateMultipleKeysFromOneGenerator() {
    Key keygen = new Key(20, new Random(10));
    assertEquals("YTD15DTT52YTO12IRL21", keygen.createKey());
    assertEquals("IK617LP637LG611IK619", keygen.createKey());
    assertEquals("VH1WY5YO1YP8SO9YO1YW", keygen.createKey());
}

Actually, it would be better to rename your class to KeyGenerator.
Notice the 2nd unit test above: I called the instance keygen, which is just natural, and changing the class name to match would be natural too.

Other things

An easier way to create possibleLetters:

private final char[] possibleLetters = "ABCDEFGHIJKLMOPQRSTUVWXYZ".toCharArray();

Btw, do you have something against the letter "N"? It wasn't on your list :)

In selectLetters and selectNumbers, 10 is a magic number:

char[] chosenLetters = new char[10];

It would be better to make it a private static final constant at the top of the class with a good name.

Actually it would be better to make selectLetters and selectNumbers take a parameter.


Minimum Number of swaps required to group all ones together in array of 0s and 1s

The algorithm is sound, and it's O(N). There are only two things I see you can improve.

Make use of the standard library

The C++ library comes with a lot of functions, including ones that can take care of summing elements of a vector for you. So to find the number of ones in the input vector, you can just write:

#include <algorithm>
...
int window = std::accumulate(std::begin(data), std::end(data), 0);

You don't need onesTillNow

When moving your window over the input array, you don't need to store all the number of ones for every window position. You just want to know the maximum number of ones in a window. If you just have a single variable int onesInWindow, and initialize it with the sum of ones in the first window:

int onesInWindow = std::accumulate(std::begin(data), std::begin(data) + window, 0);
int maxOnes = onesInWindow;

Then you can iterate over all the other window positions like this:

for(int i = window; i < size; i++) {
    onesInWindow -= data[i - window];
    onesInWindow += data[i];
    maxOnes = std::max(maxOnes, onesInWindow);
}


Finds a position to break a string that is not part of a

You want to check if the letter that you have matched is part of a
.
But you're doing a strange check. That has bugs.

Lets say we test:

a<bc>d

we say that maxLength is 1.
You'll not break the <bc>.
For a dry test of this:

text.includes('
') # true
text.charAt(maxLength).toLowerCase() # '<'
switch ('<')
case '<':
text.charAt(maxLength + 3).toLowerCase() === '>' # true
maxLength -= 1 # maxLength = 0

Instead you can use, indexOf, slice and length to check if the text is not allowed.
This allows for you to easily change what you want to remove, and to expand on it.
Whilst being much smaller than what you have.

Get the, lowercase, charAt.
Find the indexof it in the remove string.
Set the start as maxLength minus the index.
Check if the index is in the remove string, and check if the slice of text from start to start plus the remove strings length is the remove string.
If it is change the maxLength to start - 1.

Or in JavaScript:

var text = 'a
d
';
var remove = '
';
var maxLength = 4;

var char = text.charAt(maxLength).toLowerCase();
var index = remove.indexOf(char);
var start = maxLength - index;
if (index != -1 && text.slice(start, start + remove.length).toLowerCase() == remove) {
    maxLength = start - 1;
}


This:

  Or should I just don't care about it and allow user to create instance
  of class?

If you plan to write unit tests, which is recommended these days: for your class AND the code that will use it.

http://googletesting.blogspot.co.uk/2008/05/tott-using-dependancy-injection-to.html


The code seems all right; you might add the uniform variable initialization: int n_num {};. Furthermore, the way you read the number of rows is unstable, when you use std::cin to do it. Imagine you enter "b" instead of a number. Your program has no loop, that prevents that. You could use a function that only reads integers:

int readInt(std::istream& stream) {
    /*
     * Function to get integers, that are entered by the user
     */
    int input;
    stream >> input;
    return input;
}

Then int num_n {readInt(std::cin)}; would be a possible way to do it.

Second off: why do you have the line else if (i % 2 == 0) ? I suppose you could just use else instead. If i % 2 == 1 returns false, it has to be 0. So there is no need to check again. It's like checking if your number is odd, and if it's not checking again if it's even.


Yes you can use computed properties:

computed: {
    endDate: function() {
      //determine endDate based on value of selectedRange
    },
    startDate: function() {
      //determine startDate based on value of selectedRange
    }
}

And v-model can be used to bind the value of the select list to that data property:

<select v-model="selectedRange">

Then use that property in the computed properties:

  computed: {
    endDate: function() {
      return this.rangeOptions[this.selectedRange].endDate;
    },
    startDate: function() {
      return this.rangeOptions[this.selectedRange].startDate;
    }
  }

With this approach there is no need to define the rangeSelection method and bind it to the onchange property.

rangeOptions could also be moved outside the component, and then the first key could be used to select the default value of selectedRange instead of hard coding it. See the snippet below.

const rangeOptions = {
  last7Days: {
    display: 'Last 7 Days',
    startDate: moment().subtract(8, 'days'),
    endDate: moment().subtract(1, 'days')
  },
  lastWeek: {
    display: 'Last Week',
    startDate: moment().startOf('week').subtract(1, 'week'),
    endDate: moment().endOf('week').subtract(1, 'week')
  },
  last30days: {
    display: 'Last 30 days',
    startDate: moment().subtract(31, 'days'),
    endDate: moment().subtract(1, 'days')
  }
};
const form = new Vue({
  el: '#DateRangeChooser',
  data: () => {
    return {
      selectedRange: Object.keys(rangeOptions)[0],
      rangeOptions
    }
  },
  computed: {
    endDate: function() {
      return rangeOptions[this.selectedRange].endDate;
    },
    startDate: function() {
      return rangeOptions[this.selectedRange].startDate;
    }
  }
});

  <select v-model="selectedRange">
    <option v-for="(option, key) in rangeOptions" :key="key" :value="key">
      {{option.display}}
    </option>
  </select>

Start: {{startDate.format('LL')}}

End: {{endDate.format('LL')}}

Edit

@blindman67 brought up an interesting point:

  Sorry my VUE knowledge is limited but I thought computed properties were cached. Could be a problem in some edge cases, eg time near midnight and user selects, then changes their mind waits till after midnight selects again?1

That is true:

  ... computed properties are cached based on their dependencies2

if caching is an issue, then you may need to look at using a watcher or just calculate the computed property each time instead of referencing values within this.rangeOptions.

1Vue component over-complication

2https://vuejs.org/v2/guide/computed.html#Computed-Caching-vs-Methods


First of all: drop the row function, which is the anonymous function as the second argument of csvParse...

var data = d3.csvParse(csvData, function(d) {
    d.date = d.date;
    d.type = d.type
    return d;
})

... because you are not changing anything!

So, it can be just:

var data = d3.csvParse(csvData);

Back to your question:

Indeed, you don't need to reference the array by the indices, which forces you to sort the data array and then to sort the resulting array... that's not only confusing and error-prone, but also very computer-intensive for the browser: sorting big arrays of objects can take quite some time. It's a good idea avoiding sorting, specially because, as we'll see, you don't need it.

There is a way to omit that step, making it automatic. Better than that, you can make the whole thing automatic!

In my proposed solution, you don't even need to set the keys, as you do right now...

var keys = ["E","U"];

You can easily get all the unique type values:

var keys = [...new Set(data.map(function(d) {
    return d.type
}))];

And then, creating your lineData:

var lineData = nestData.map(function(d) {
    var obj = {};
    obj.date = d.key;
    keys.forEach(function(e) {
        obj[e] = d.values.find(function(f) {
            return f.key === e
        }).value
    });
    return obj;
});

The above code will work for any number of different types you have, and since you already have the dates in the chronological order, you don't need any sort.

This, in short, is what the function does:

For each map interaction we create a new object:

var obj = {};

We set the key/value pair for the dates, since there is always a date:

obj.date = d.key;

Then, for each value in the keys array, we find the respective value in the values array:

keys.forEach(function(e) {
    obj[e] = d.values.find(function(f) {
        return f.key === e
    }).value
});

Finally, we return the object:

return obj;

Here is a demo, using only the relevant parts in your code:

var csvData = `date,type
2017-01,E
2017-01,E
2017-01,E
2017-01,U
2017-01,U
2017-02,E
2017-02,E
2017-02,U
2017-02,U
2017-02,U
2017-03,U
2017-03,U
2017-03,E
2017-03,E
2017-03,E
2017-03,E`;

var parseTime = d3.timeParse("%Y-%m");

var data = d3.csvParse(csvData);

var keys = [...new Set(data.map(function(d) {
  return d.type
}))];

var nestData = d3.nest()
  .key(d => d.date)
  .key(d => d.type)
  .rollup(leaves => leaves.length)
  .entries(data);

var lineData = nestData.map(function(d) {
  var obj = {};
  obj.date = d.key;
  keys.forEach(function(e) {
    obj[e] = d.values.find(function(f) {
      return f.key === e
    }).value
  });
  return obj;
});

lineData.forEach(function(d) {
  d.date = parseTime(d.date);
})

console.log("Nested: ", nestData)

console.log("Mapped: ", lineData)
<script src="https://d3js.org/d3.v4.min.js"></script>
<svg></svg>

Now, using this code, you can automatically create the adequate lineData array regardless the number and the order of the type properties in your data array.


Downloading 2 tables from db, does calculation and uploads resulting table

I know, that you know, that your code is messy, but I'm still going to give some tips on your coding style. Here are a few tips I have on what can be improved there.

Don't use % for string formatting, as it is deprecated. You should be using str.format() instead. Here's an example: print "Hello {0}".format("world")
You can remove the docstring at the end of your file containing """!@endcond""". This does nothing, and serves no purpose.
Separate this out into different functions. In it's current state, it's really hard to read as one large block of code.
Add more comments. Comments will make your code much clearer, and easier to read. Functions and classes should use docstrings, over regular inline comments.

Don't import multiple modules on one line. If an error occurs with one module, it can be hard to distinguish where the error came from.
Some variable names could be better. For example, the names sts, or shp2pgsql provide no useful information. Try to find any other names with not so great names, and see how you can improve them.
I'm not an expert on asynchronous programming, or any of the modules provided in Python made for this, but if you want to do a task like this, Python 3.5 will include the async and await keywords built for asynchronous programming.

The official style guide for Python, PEP8, can be found here.


My grade calculator with special weighting

A couple of minor things:

fog and ing aren't very meaningful id names, they would be better as something like formal_grades and informal_grades instead.
This part of the code:

var is_formal = document.getElementById('formal_radio').checked;
var gradelist = null;

if (is_formal) {
    new_grade = document.getElementById("new_grade_input").value;
    if (document.getElementById('radio_old_grade').checked) {
        old_grade = document.getElementById("old_grade_input").value;
        formal_grades[formal_grades.indexOf(old_grade)] = new_grade
    } else {
        formal_grades.push(new_grade);
    }
} else {
    new_grade = document.getElementById("new_grade_input").value;
    if (document.getElementById('radio_old_grade').checked) {
        old_grade = document.getElementById("old_grade_input").value;
        informal_grades[informal_grades.indexOf(old_grade)] = new_grade
    } else {
        informal_grades.push(new_grade);
    }
}

repeats very similar code where the only difference is which array is used. Also, gradelist isn't used anywhere. You can avoid the repetition like this:

var is_formal = document.getElementById('formal_radio').checked;
var gradelist = is_formal ? formal_grades : informal_grades;

new_grade = document.getElementById("new_grade_input").value;
if (document.getElementById('radio_old_grade').checked) {
    old_grade = document.getElementById("old_grade_input").value;
    gradelist[gradelist.indexOf(old_grade)] = new_grade
} else {
    gradelist.push(new_grade);
}

by assigning the array that needs to be used to gradelist.

This works because when you assign an array (or any object) to a variable in javascript, it assigns the reference to the array instead of copying the value. For example, if formal_grades is assigned to gradelist they will both refer to the same array.


You don't need to comment so often. Comments are good for explaining code or the abstract reason behind code, if either of those is unclear. Your comment about imports isn't necessary:

# we use pandas and regular expression libraries
import pandas as pd
import re

The code is clear, people using Python know what imports are and so this will be perfectly readable. On the other hand, your note about how you're filtering the pandas data is useful to me. It may be just because I don't use pandas, but the explanation of these commands cleared code that otherwise made no sense.

You could make your mock_df much quicker with a dictionary comprehension of your new_params list:

mock_df = {key: [] for key in new_params}

Of course this leaves out comb_str and catchall, but you can add those manually after.

mock_df['comb_str'] = []
mock_df['catchall'] = []

If you need a copy of df['input'] to iterate over a list comprehension is a slow way. Depending on how different dataframes are you might be able to use copy from the copy module.

from copy import copy

...

for entry in copy(df['input']):

If that doesn't seem to work, I also see pandas has its own copy function.

But it's unclear why you need to duplicate it. THe data shouldn't be affected by looping over it. And in any case you don't use it or your copy after this point.

Also, you append every entry to mock_df['comb_str='], why not just assign the full list to that after the loop? It'd save you time appending on each iteration.

Using params as your name for each element of new_params is quite confusing. Surely you only have one parameter at a time that you're using? Having that as a plural throws me off and makes me think it's a list of parameters.

I think you're making the flow a bit complicated too. Instead of using any try looping over all your new_params and then set a flag if a parameter is found. Then after the loop test if this flag was ever set, if not you could append to 'catchall'. Here's what I mean:

found_param = False
for params in new_params:
    if params in entry:
        mock_df[params].append(re.search(params+'(.*?)(?=_[^_=\n]+=|$)', entry).group(1))
        found_param = True
    else:
        mock_df[params].append('')
mock_df['catchall'].append('' if found_param else entry)

This makes sure that every value is being set and it's clearer to see that happening. Also in case you're not familiar with them, I'm using a ternary expression to append to 'catchall'.

('' if found_param else entry)

A ternary will return one of 2 values based on an evaluated boolean. In this case the boolean is found_param, and if it's True then it returns the first value, which is an empty string. However if it's False then it will be set as entry instead. You can just use the normal if syntax if you prefer. Opinions differ on whether ternaries are more readable.


Rails just isn't taking chances, so when you call vote.article it's performing a new DB query, and thus creating a new instance rather than grabbing a cache. And that's a good thing! You might run into trouble otherwise, since you call save. If it was the same Article instance everywhere, you'd suddenly be calling save on it from a non-obvious point in the code.

I.e. pretend that Rails does reuse the same Article instance, and that instance has other unsaved changes. Perhaps these changes aren't valid, and in that case, the save call in ArticleVote would fail although you're only trying to change the article's score. It would also update the article's updated_at timestamp, although that may not be relevant; an article receiving or losing a vote doesn't really mean that the article itself was updated.

So, for one I'd recommend using article.update_column(:score, article.score - value) in you before_destroy method. And, yes, you'll still need to call reload elsewhere.

However, the underlying issue is that you're modifying an article "from the outside". I'd recommend a different approach altogether, with no articles.score column in the database, and using Rails' caching API instead:

class Article
  has_many :votes, class_name: "ArticleVotes"

  # score is not part of the DB schema;
  # it's computed and cached as necessary
  def score
    # get or update the cached score
    Rails.cache.fetch(score_cache_key) { votes.sum(:value) }
  end

  def flush_score_cache
    Rails.cache.delete(score_cache_key)
  end

  # let's not use or override the built-in
  # #cache_key method for this, since that
  # relies on the updated_at timestamp.
  def score_cache_key
    "article/#{id}/score" # or something similar with the ID in it
  end
end

(In the above, you may want to handle the possibility of the record being new, and thus having a nil id.)

And in ArticleVote:

class ArticleVote
  after_commit :flush_article_score

private

  def flush_article_score
    article.flush_score_cache
  end
end

Now whenever a vote is added, removed or updated, the article's score cache will be busted, forcing a article.score to do a proper recount if/when it's called.

This also has the advantage that the article's score remains consistent with the actual votes: It's computed entirely from what's in the database.  Alternatively, you can simply increment/decrement the cached value instead of flushing it, and still avoid having a database column.

Of course, there are some drawbacks too. Since it is a cache the usual disclaimers apply (you have to be diligent about busting it when necessary, or you'll hit a stale cache, etc..). And if you've got heavy voting traffic you might end up busting the cache so often it just always does the SUM() query. In that case, you could still go with your current solution of having a database column that you increment and decrement, but I might still want to stick that in a different table to avoid the aforementioned issues with implicitly calling save on an article (or, like now, overwriting an updated score with a older one if you forget to reload). You could also consider a more "raw SQL" approach of actually incrementing or decrementing rather than writing the value directly, i.e. UPDATE ... SET score=score + 1 WHERE .... That would avoid race conditions. Optimally, you might do a bit of both: A database column holding the canonical score of an article on disk, and a memory cache you use most of the time for reads, so you only have to hit the database for writes.


Using Collectors.toList instead of forEach and a new ArrayList

This is one way using flatMap and Collectors.toList():
public List<SearchSuggestion> suggest() {
   return someService.findAll().stream()
            .flatMap(wl->wl.getWatchlistItems().stream())
            .map(wli->mapToSearchSuggestion(wli.getInstrument()))
            .collect(Collectors.toList());
}

However (since this is Code Review) the method mapToSearchSuggestion seems more appropriate to be in the class Instrument. If you can move it there then the function becomes:
public List<SearchSuggestion> suggest() {
    return watchlists.stream()
            .flatMap(wl ->wl.getWatchlistItems().stream())
            .map(WatchlistItem::getInstrument)
            .map(Instrument::mapToSearchSuggestion)
            .collect(Collectors.toList());
}

Instrument class:
public class Instrument {
    //...
    public SearchSuggestion mapToSearchSuggestion() {
        return SearchSuggestion.builder().symbol(getSymbol()).build();
    }
    //...
}


First comment, there is no need for the closure inside _forEach which makes the code unnecessarily difficult to read.  More importantly I would argue that the function would be much more useful if did not transform the original object and instead returned a new object.

Object.map = function (obj, mapping) {
    var mapped = {};

    if (typeof obj !== 'object') {
        return mapped;
    }

    if (typeof mapping !== 'function') {
        // We could just return obj but that wouldn't be
        // consistent with the rest of the interface which always returns
        // a new object.
        mapping = function (key, val) {
            return [ key, val ];
        };
    }

    Object.keys( obj ).forEach(function (key) {
        var transmuted = mapping.apply(obj, [ key, value ]);

        if (transmuted && transmuted.length) {
            mapped[ transmuted[0] || key ] = kv[ 1 ];
        }
    });

    return mapped;
};

This is not only less dangerous for widely available object but it also makes the function more flexible by allowing it to be chained or used within an expression:

Object.map(oldCss, function (key, value) {
    // ...
}).doSomethingElse();

At the very least I would have your original function return the passed in object to allow for chaining or use within an expression.


Deleting a Specific Node from a Linked List

Code Review
Removing the Element:
Your four choices do seem to cover all the situations.
  if (H->next == nullptr)
  {
    H = nullptr;
    delete TMP1;
  }
  else if (TMP1 == H)
  {
    H = H->next;
    delete TMP1;
  }
  else if (TMP1->next == nullptr)
  {
    TMP2->next = nullptr;
    T = TMP2;
    delete TMP1;
  }
  else
  {
    TMP2->next = TMP1->next;
    delete TMP1;
  }

But in reality there are only two situations. You are deleting the head node. You are deleting another node. The other two are special cases of deleting the tail and we should handle that separately.
  Node* TMP1 = H;
  Node* TMP2 = nullptr;   // set a value for TMP2 so we can check it/

  // Find node to delete

  // Check if the item being removed is the tail
  // and update the tail appropriately.
  if (T == TMP1) {
      T = (T == H) ? nullptr : TMP2;
  }

  // Now update the list.
  if (TMP2 == nullptr) {       // If TMP2 is null this is the head
      H = TMP1->next;          // Node we are deleting. So reset H
  }
  else {
      TMP2->next = TMP1->next; // Otherwise TMP1 is being deleted and
                               // TMP2 is the previous node.
  }

  // Now the node is unlinked delete it.
  delete TMP1;

You can simplify this even more by using an extra helper function.
Objects
Why is this a free standing function?
void deleteSpecific(DataType N, Node *&H, Node *&T)

I would expect this to be part of a class. Where head and tail are part of the object. So you don't need to pass them around.
Separation of Concerns
Your code should either be resource management or business logic. Your code mixes the two different types of code together. Here the resource management is removing the node from the list. But you also have some business logic inside your code that is talking to the user.
std::cout << std::endl << std::endl;
std::cout << "\t" << "-> LL| ERR: The List Is Empty. Deletion Not Possible.";
std::cout << std::endl << std::endl;

Is it really an error in the first place? But why is it part of the resource management code?
The resource management code should be wrapped in another layer of code that does the business logic and informs the user. That way you can re-use the deleteSpecific() function from another piece of code that does not care if the data is in the list or not.
Style Comments
Naming
Variable names are supposed to be self documenting.
 H:   head
 T:   tail

That's no so self documenting as you think. Just spell it out. There are a couple of other conventions you need to keep in mind.

Identifiers that are all caps are usually reserved for macros.
Identifiers with an initial cap are usually user defined "Types"
Identifiers with an initial lower case letter are usually objects.

These are good conventions to follow and will help you spot things as your code gets more complicated.
Pointer & Reference
In "C" the "*" was usually placed by the object. But "C++" is much more strongly types and the "*" and "&" are considered part of the type information so you usually place these with the type.
void deleteSpecific(DataType N, Node *&H, Node *&T)

Is more usually written as:
void deleteSpecific(DataType N, Node*& H, Node*& T)

But you say "AHhhh, but what about"
Node *TMP1 = H, *TMP2;

Yes it does not work in this situation. But there is a more important rule recommendation that makes this situation obsolete. The rule is to declare one variable per line. So this should actually be written as:
Node*  TMP1 = H;
Node*  TMP2 = nullptr;

Please stop writing C++ like it was C. These are completely different languages with their own styles and idioms.
Prefer "\n" over std::endl
The difference between the two is that endl flushes the buffer. Usually this is not what you want and makes the code exceedingly inefficient (user flushing is almost always wrong). If you think you need it then add an explicit flush.


can we use of $this in closure for jquery plugin

Try this type of closure

    $this.add(tip).hover(function() {
        return function() {
            var timeoutId = $this.data('timeoutId');
            if(timeoutId) {
                clearTimeout(timeoutId);
            }
            tip.fadeIn("slow");
        };

    }(), function() {
        return function() {
            var timeoutId = setTimeout(function() {
                tip.fadeOut("slow");
            }, 650);
            $this.data('timeoutId', timeoutId);
        };
    }());

Just dont forget to tell if it solves the problem. Good luck.


Finding a delimiting character in a text file

The first way to deal with this issue is to examine what is the actual problem that you're attempting to solve.  Understand the problem fully before you solve it or you will end up with a mess.  There are two parts to why you might need this function...

1) You want to process the data.

To perform processing you are looking to extract blocks of numbers.  Knowing the delimiter is not relevant to your processing of the data.  You're looking for 1 or more numbers which are contiguous and anything that is not a number can be ignored until you hit another number block.

That's your matrix processing taken care of without having to ever address any of your concerns or having a findDelimiter at all.

2) You want to reformat the file

If you want to output a formatted file with the same delimiter then your overall idea to identify a delimiter by building a frequency table and excluding certain values is on the right track.

To handle the issue of spaces, you can just set the [space] count to a maximum of 1 and if no other delimiters are present then then [space] will be the most frequent character.

There are some potential issues since you're dealing with arbitrary input.  You have no guarantee the delimiter will remain constant throughout the file; it wouldn't be unreasonable to see two matrix files concatenated for example.

Equally you can avoid dealing with the very large datatypes if you limit your scanning to the first few kilobytes of a file.  This would also provide a usable result without the overhead of processing the whole file; though you could argue that it's premature optimisation I would consider it justified in this case as you are expecting very large files.

Other potential issues...

This code assumes ASCII so far as I can tell.  There could be some "undefined behaviour" should someone give this code a file with Unicode content.

You spelled delimiter as delimeter - while this shouldn't be a big issue as most IDE's autocomplete, it's worth keeping an eye on as if another coder worked on your code and spelled it properly there could be confusion.  Many IDE's offer spellcheck and you should make sure yours is set up.

isNumeric will be an existing function.  Though you could eliminate the need for it entirely by setting the frequency counts for characters you want to ignore (like 0...9 and control characters) to a frequency of 0 before you process the frequency table.  This would also help remove or manage some of the 'magic numbers' in your code and make the intent clearer.

It's good practice to delay defining variables until you need them.  This can be useful should you come to refactor the code as compiler errors will point out when you attempt to modify a variable before it has been initialised.

I'd like to see c and f have meaningful names and for there to be a few more blank lines to illustrate the program flow blocks - the steps of the process become more obvious with the blank lines (as they are here... build a frequency table, remove the unwanted values, de-emphasise space, find the most common term and return it).  When the higher levels are clearly visible it makes refactoring easier.

unsigned char findDelimiter(FILE * fileToScan)
{
    rewind(fileToScan);

    int character;
    long long int frequencies[UCHAR_MAX] = { 0 };
    while ((character = fgetc(fileToScan)) != EOF) {
        frequencies[character]++;
    }

    const char IGNORECHARS[] = "0123456789\r\n";
    // todo: set the IGNORECHARS frequencies to 0 here
    // todo: set [space] to a maximum of 1 here

    long long int maxFrequency = 0;
    unsigned char delimiter = '\0';
    for (character = 0; character < UCHAR_MAX; character++) {
        if (frequencies[character] > maxFrequency) {
            maxFrequency = frequencies[character];
            delimiter = character;
        }
    }

    return delimiter;
}

With the code formatted this way it's easier to see how you could split the frequency analysis from the file reading should you want to do that later.

delimiter should be initialised with a reasonable value like ',' or be checked to throw an exception if a delimiter has not been found.


pattern matching, replacement and for loop optimization in R

You can try something like this:

# function for string preperation:
preperString <- function(x) {
  require(stringr)
  x <- str_to_lower(x)
  x <- str_trim(x)
  x
}

setDT(loc_df) # convert data.frames to data.table
setDT(city_df)

loc_df <- loc_df[, lapply(.SD, preperString)] # apply string preperation to all columns of loc_df
city_df[, City := preperString(City)]

loc_df <- merge(loc_df, city_df, by.x = 'Organization.Location.1',
                by.y = 'City', all.x = T, sort = F)
loc_df <- merge(loc_df, city_df, by.x = 'Organization.Location.2',
                by.y = 'City', all.x = T, sort = F)
loc_df
#    Organization.Location.2         Organization.Location.1 Country.x Country.y
# 1:                                        zug  switzerland        NA        NA
# 2:  san francisco bay area zug  canton of zug  switzerland        NA        NA
# 3:     london  canada area                        zimbabwe  zimbabwe        NA
# 4:     beijing city  china       zigong  chengdu  pr china        NA        NA
# 5:    greater atlanta area        zhuhai  guangdong  china     china        NA
# 6:      paris area  france                 zaragoza  spain     spain        NA

# and then you can write rule tu create org_new1, for example:
loc_df[, org_new1 := Country.x]
loc_df[is.na(org_new1), org_new1 := Country.y]
loc_df
#    Organization.Location.2         Organization.Location.1 Country.x Country.y org_new1
# 1:                                        zug  switzerland        NA        NA       NA
# 2:  san francisco bay area zug  canton of zug  switzerland        NA        NA       NA
# 3:     london  canada area                        zimbabwe  zimbabwe        NA zimbabwe
# 4:     beijing city  china       zigong  chengdu  pr china        NA        NA       NA
# 5:    greater atlanta area        zhuhai  guangdong  china     china        NA    china
# 6:      paris area  france                 zaragoza  spain     spain        NA    spain