Character pattern replacement using gsub, loops, and data.table

Is there a reason that you are using mapply to gsub through the number columns as well? You can just replace in the first column if that is all you need, which gets some speed improvement, about 2x on my machine. I also tried using stringi instead of gsub but it was not faster. This is also a speedup on the order of milliseconds though!

library(data.table)
#> Warning: package 'data.table' was built under R version 3.5.1
library(microbenchmark)
#> Warning: package 'microbenchmark' was built under R version 3.5.1
library(stringi)
df1 <- data.frame(name = rep(LETTERS, 250), number = rep(c(1:26), 250), stringsAsFactors = FALSE)
df1$name[df1$name == "D" | df1$name == "F" | df1$name == "L"] <- "foo*"
df2 <- data.frame(name = rep(LETTERS, 250), number = rep(c(1:26), 250), stringsAsFactors = FALSE)
df2$name[df2$name == "A" | df2$name == "R" | df2$name == "T"] <- "*foo*"
df3 <- data.frame(name = rep(LETTERS, 250), number = rep(c(1:26), 250), stringsAsFactors = FALSE)
df3$name[df3$name == "C" | df3$name == "Q" | df3$name == "W"] <- "f*oo"

df <- list(df1, df2, df3)
dt <- lapply(df, as.data.table)

mapply.remove.asterisk = function(x){
  df2 <- data.frame(mapply(gsub, "\\*", "", x, perl = TRUE))
  colnames(df2) <- colnames(x)
}

dt.remove.asterisk = function (x) {
  x[, lapply(.SD, function(x) gsub("\\*", "", x, perl = TRUE))]
}

stringi.remove.asterisk = function (x) {
  out <- x
  out$name <- stri_replace_all_regex(x$name, "\\*", "")
  out
}

gsub.remove.asterisk = function(x) {
  out <- x
  out$name <- gsub("\\*", "", x$name)
  out
}

mapgsubtest = function(x) {
  df.test <- lapply(x, mapply.remove.asterisk)
}

dtgsubtest = function(x) {
  dt.test <- lapply(x, dt.remove.asterisk)
}

strisubtest = function(x) {
  str.test <- lapply(x, stringi.remove.asterisk)
}

gsubtest = function(x){
  gsub.test <- lapply(x, gsub.remove.asterisk)
}

microbenchmark(mapgsubtest(df), dtgsubtest(dt), strisubtest(df), gsubtest(df))
#> Unit: milliseconds
#>             expr      min       lq     mean   median       uq       max
#>  mapgsubtest(df) 8.031179 8.789332 9.429985 9.164945 9.740215 12.913776
#>   dtgsubtest(dt) 7.276307 7.867076 8.553440 8.217892 8.855339 22.473660
#>  strisubtest(df) 8.149333 8.745572 9.391304 9.221469 9.846153 13.492875
#>     gsubtest(df) 4.153983 4.667258 5.053101 4.789789 5.231771  9.813332
#>  neval
#>    100
#>    100
#>    100
#>    100

Created on 2018-10-20 by the reprex package (v0.2.0).


Everything seems fine for 99% of the time, but occasionally I get an
  email from my script stating that growth in the past hour is something
  like ".08%", well below my current threshold of 0.75%. Is something
  wrong with my logic?

When the tools seem to defy your logic, play with simple examples.

The code that generates the message with ".08%" is this, roughly:

printf "\"$monDrive\" has grown $results%% in the past hour. | mail ...

where the $results variable comes from:

results=$(bc -l <<< $current-$prev )

and the threshold is checked with:

if  [[ $results > $percentThreshold ]]

Now let's play a little:

$ [[ 0.08 > 0.75 ]] && echo true || echo false
false
$ [[ .08 > 0.75 ]] && echo true || echo false
true

A-ha! Apparently, 0.08 is smaller than 0.75, as expected but .08, with the leading zero omitted, is not smaller than 0.75, at least in Bash.

But why do you have .08 instead of 0.08 in the first place?
Let's play a bit more:

$ bc -l <<< 2.81-0.79
2.02
$ bc -l <<< 0.81-0.79
.02
$ bc -l <<< 0-0.79
-.79

Ah. So when the result is below 1, apparently, bc drops the leading zero.

So how to fix this? It seems there's no obvious way to prevent bc from dropping the leading zero. But as you're already doing many calculations using awk, you can move this calculation there too:

results=$(awk '{print $1 - $2}' <<< "$current $prev")

Note the space between $current and $prev,
so that they can be used as $1 and $2 in awk.

Code review

   df "$monDrive" | awk 'END{printf "%0.2f",$2/$1*100; exit}'

In the END block of awk you don't need to exit,
as the command will exit anyway.
I also recommend to add more spaces to make the expression easier to read:

    df "$monDrive" | awk 'END { printf "%0.2f", $2 / $1 * 100 }'

This seems completely pointless, you can delete it:

#Validate file content
printf "%0.2f" "$prev" > /dev/null || exit


Mainly style comments:

var SB = {muted: false, previousVolume:1}: you should have whitespace after your last colon.
Math.pow(v,2): you should have a space after the comma.
In the following four lines, you should have extra whitespace in between your brackets:

function globalVolumeChange(v){ globalVolume = Math.pow(v,2);}
function globalStop(){liveSounds.forEach(function(snd){killSound(snd)});}
function globalPause(){ liveSounds.forEach(function(snd){snd.pause();}); }
function globalGetLive(){return liveSounds.slice();}

if( snd.src !== match ) return;: you should wrap this in curly brackets, as it can have undesired effects
You should avoid having extra space in your if-else statement brackets like in the point above, and in a few different places.


RPi script to periodically collect data from Arduino through serial port

A simple technique to avoid busy wait is to

import select
....
select.select([], [], [], timeout)

The timeout is simply target_time - current_time in seconds. Since select interprets it as a floating point, the granularity is in  milliseconds at least.

I see no possibility for time drift.
The nested loops in read_data do not look right. Consider instead

def read_data():
    data = []

    temp = None
    while temp != '*':
        temp = arduino.read()...

    while temp != '#':
        temp = arduino.read()...
        data.append(temp)

    return data[:-1]

I am not sure why do you sleep() before reading the response.


Changing button colors based on user input

This one's pretty straightforward. If you have rows of length rowLength, then the row is j / rowLength (note that with integer arithmetic this automatically rounds down to the nearest integer) and the column is j % rowLength.

Altough there was a very simple answer in this particular case, in general, if you look at a method like the one you wrote, the very repetitive code should stand out, and you should think "loop".

In fact, a good starting point is to just say, in plain English, what you're doing with what you've written. Something like:

  Starting from 10, and adding in increments of 10, I check if j is less than that number. If it is, I subtract the previous multiple of 10 from j, and add a tenth of that number to row. Otherwise I go on to check the next increment of 10.

That's a start, but a good general idea with programming is to say what you're doing, not how you're doing it. So the above might become:

  In order to check which row the item is in, I check each multiple of the row count, starting from the first, until I find the first one greater than the position. Then I record that the number of the row is that multiple - 1. Then I know that the column is the position minus the number of items in all the previous rows, which is the number of previous rows multiplied by the number of items per row.

A bit cumbersome in English, but the above is actually the exact basis of what you did. So the next task is to translate that as plainly into code as possible.

First, we look at "I check each multiple". That doesn't say "I check 1 * the row count, then I check 2 * the row count, then I check 3 * the row count". It expresses all of those in a single statement: each. So translating that as literally into code as possible, it's not a bunch of if statements, it's a single loop:

int i = 0; //Starting from the first...
do
{
    i++; //I check each...
    int rowMultiple = i*rowLength; //...Multiple of the row length
} while(true);  //Not sure when I stop yet

Next: "until I find the first one greater than the position":

int i = 0; //Starting from the first...
do
{
    i++; //I check each...
    int rowMultiple = i*rowLength; //...Multiple of the row length
} while(rowMultiple <= position);  //Until I find the first one greater than the position

Note that I renamed j to position, since that's what it is. Now we've found the desired i, and we know that to do with it:

int i = 0; //Starting from the first...
do
{
    i++; //I check each...
    int rowMultiple = i*rowLength; //...Multiple of the row length
} while(rowMultiple <= position);  //Until I find the first one greater than the position
int rowNumber = i - 1; //Then I know the row number is this multiple minus 1
int columnNumber = position - (rowNumber*rowLength); //And the column number is the position minus the number of items in previous rows

And there you have it! Of course you wouldn't really include those comments, those are just for in-line illustrations of how directly each line- in code- corresponds to what you're actually trying to do- in English. The fact that each line so clearly describes what it's doing without comments is a sign that you're on the right track.

From there, the solution with / and % is really just noticing that you can predict what the loop will produce without actually having to go through each iteration, and likewise knowing about the modulo (%) operator and thinking to use it, to simplify the column bit. But being able to clearly state what you want to do in English and turn that into concise, readable code is a far more general and wide-reaching skill.


Striping a matrix concentrically, anticlockwise

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

Fix the bug

The code allocates memory for the passed arr_lengths but never returns a pointer to the newly allocated memory to the caller.  The code currently has this:

int* lengths = *arr_lengths;
// more code
(lengths) = malloc((max_dis+1) * sizeof(matrixOptimizationValue));

Instead it should be this:

// more code
*arr_lengths = malloc((max_dis+1) * sizeof(matrixOptimizationValue));
int* lengths = *arr_lengths;

Provide complete code to reviewers

This is not so much a change to the code as a change in how you present it to other people.  Without the full context of the code and an example of how to use it, it takes more effort for other people to understand your code.  This affects not only code reviews, but also maintenance of the code in the future, by you or by others. The code comments are good, but a sample program would be better.

Use the required #includes

The code uses printf which means that it should #include <stdio.h>.  It was not difficult to infer, but it helps reviewers if the code is complete.  I had to add these three lines:

#include <stdio.h>
#include <math.h>
#include <stdlib.h>

Avoid the use of floating point math

On many computers, floating point mathematics is slower than integer math.  For this reason, it's often better to avoid if you can.  In this case, it's easily done.  We can replace this:

const int max_dis = (columns > rows) ? round((double)(rows)/2) : round((double)(columns)/2);

with this:

const int max_dis = (rows < cols ? rows+1 : cols+1) / 2;

I also changed the variable columns to cols but that's a personal preference.  The longer name is arguably more descriptive.

Check return values for errors

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

Choose descriptive names

Most of the variables and function are well-named and clear in their usage and intent, but I found matrixOptimizationValue both somewhat misleading (it's not a value, but rather a type) and also overly long.  I renamed it DataType which is also not a brilliant name, but is, at least, shorter.

Minimize system calls

If you're looking for performance, it's often a good idea to avoid system calls, such as for malloc.  In this case, I'd suggest changing the code to do only one single allocation.  This has the benefits of speed, simplification of error checking and handling, and simplification of cleanup after the call (only one call to free is required).

Consider separating I/O from the algorithm

The strip function uses printf to print to the console and then exits via exit if the input is malformed.  Consider changing that to return NULL on error and letting the caller figure out what to do.

Simplify the algorithm

I found the length of the code and many variables something of an impediment to my understanding of the algorithm.  It can be simplified considerably by remembering that the passed variables may also be used directly.  In the rewrite I created, pointers are used extensively to simplify the code.  It also uses the fact that we can calculate in advance when to change direction.

Results

Following all of these suggestions, I created the following rewrite:

#include <stdlib.h>
#include <stdio.h>
#include <stddef.h>

typedef unsigned short DataType;
#define DataTypeStr "u"

DataType* strip(const DataType* matrix, int rows, int cols, int** arr_lengths){
    if (rows == 0 || cols == 0) {
        return NULL;
    }
    const int max_dis = (rows < cols ? rows+1 : cols+1) / 2;
    // return value is a single vector of the same size as
    // the input, followed by an int value n, which is the
    // count of arrays represented, followed by n ints which
    // represent the lengths of those sub-arrays.
    DataType *retval = malloc(rows * cols * sizeof(DataType*)
            + (1 + max_dis) * sizeof(int));
    if (retval == NULL) {  // bail out on allocation error
        return NULL;
    }
    *arr_lengths = (int *)(&retval[rows*cols]);
    DataType *out = retval;
    int *len = *arr_lengths;
    *len++ = max_dis;
    // precalculate down, right, up, left
    enum compass { DOWN, RIGHT, UP, LEFT, DIRCOUNT };
    const int dirs[DIRCOUNT] = { cols, +1, -cols, -1 };
    // because we move and then fetch a value,
    // move one row above matrix
    matrix += dirs[UP];

    for (int matnum=0; matnum < max_dis; ++matnum) {
        if (rows > 1 && cols > 1) {
            *len++ = 2 * (rows + cols - 2);
        } else {
            *len++ = rows + cols - 1;
        }
        // start by moving down
        int dir = DOWN;
        while (rows && cols && dir < DIRCOUNT) {
            // down and up
            for (int i = rows; i; --i) {
                matrix += dirs[dir];
                *out++ = *matrix;
            }
            --rows;
            --cols;
            ++dir;
            // right and left
            for (int i = cols; i; --i) {
                matrix += dirs[dir];
                *out++ = *matrix;
            }
            ++dir;
        }
    }
    return retval;
}

int main(int argc, char *argv[]) {
    if (argc != 3) {
        puts("Usage: matstripe rows cols\n");
    }
    int rows = atoi(argv[1]);
    int columns = atoi(argv[2]);
    printf("Input is a %d x %d matrix\n", rows, columns);
    DataType *input = malloc(rows * columns * sizeof(DataType));
    if (input == NULL) {
        puts("Out of memory error, quitting program.");
        return 1;
    }
    int colcounter = columns;
    for (int i = 0; i < rows*columns; ++i) {
        input[i] = i+1;
        printf("%3" DataTypeStr " ", input[i]);
        if (--colcounter == 0) {
            printf("\n");
            colcounter = columns;
        }
    }
    int *arr_lengths;
    DataType* answer = strip(input, rows, columns, &arr_lengths);
    free(input);
    puts("Output:");
    if (answer) {
        DataType* mat = answer;
        for (int matnum = 0; matnum < *arr_lengths; ++matnum) {
            printf("[%" DataTypeStr, *mat++);
            for (int i = arr_lengths[matnum+1] - 1; i; --i) {
                printf(",%" DataTypeStr, *mat++);
            }
            puts("]");
        }
        free(answer);
    }
}

This takes two command line parameters for the nmber of rows and number of columns  and constructs a test input matrix of that size filled with cardinal numbers.  Here's an example of output.

Input is a 5 x 4 matrix
  1   2   3   4
  5   6   7   8
  9  10  11  12
 13  14  15  16
 17  18  19  20
Output:
[1,5,9,13,17,18,19,20,16,12,8,4,3,2]
[6,10,14,15,11,7]


First steps in Scala: does this look idiomatic?

Ok, I'm changing the answer now that I understand what you are doing.

The main problem here is @/ -- while Scala people, in general, don't mind special operators, they don't add operators just because they can either. You can replace @/ with the existing / just by adding .toFloat to any one of the terms.

Views aren't often used either, and it's important to have a very good understanding of how they work if you are going to use them, and it's not that easy to gain performance with them, since the machinery they use to support non-strictness is quite heavy, and not everything takes advantage of it. For example, sortBy will create a new collection before take and map are applied.

Views can gain when you have many mapping/slicing steps, and few elements of it are ever used. Most of the time, iterators will gain you much more performance, at the cost of the mutability problems iterators have.

If you want to reduce the number of times you iterate through the list of proportions, there's at least one place where you can simplify:

    val remainders = (
        approximations.view.zipWithIndex
        map { x => if (lowValuesIndices contains x._2) 1 else 0 }
    ).force

    (byDifect, remainders).zipped map { _ + _ }

Can be reduced to

    byDifect.zipWithIndex map {
      case (bd, i) => bd + (if (lowValuesIndices contains i) 1 else 0)
    }

One could also keep byDifect a Float, then either use it alone when computing approximation (instead of zipping stuff), or skip that altogether and put that computation on sortBy -- incurring the cost of computation O(nlogn) times instead of O(n) times. It would make the code shorter, but whether it would be faster or not is something I'd leave to a benchmark with a real application -- I'm guessing it would depend on actual sizes for proportions.

So, let's talk a bit about performance. Before Scala 2.10, if you want performance you should avoid methods added through implicits on critical paths. The code you wrote will probably get inlined by JIT. You can also reduce the number of computations by pre-computing amount / sum, and if you make that amount.toFloat / sum, then you don't need /@.

More specifically, views are not guarantees of speed, particularly if the computations are light, such as here. I'd not use them at all, unless I'm specifically optimizing the code.

Doing a fixed size of multiple passes on small data structures is often not a problem. You are not changing the complexity, just losing memory locality. If the data is bigger, you can incur in gc overheads, which are more substantial. If maximum performance is required, just drop immutability and go to mutable arrays.

Finally, contains is faster on Set than Seq -- and, in this particular case, a BitSet would be way faster. Call it apply, however, since contains is a general method on traversables, while set's apply is a fundamental operation. If one of them is less than optimized, it will be contains.

This is the most idiomatic beginner's code I have ever seen... do you come from another functional language?


Find last zero in infinite stream of 0's followed by 1's

You might have misunderstood the program requirements: an ArrayList is not an infinite Stream.

If you don't want a stream and do instead want to assume that multiple-threads are adding to it then you shouldn't use ArrayList because it's not thread-safe; apparently, a better alternative for that purpose would be Vector.


Replacing English words in a string with their Spanish equivalents by dictionary lookup

Problems

not properly handling words, just substrings. Currently, you are using str.replace() that would replace substrings in a string, not complete words, which means that it would behave incorrectly when your replacement is a part of another word - e.g. "Cheese" would be replaced from "Cheesecake" becoming "Quesocake"
just a single substring is replaced. you have that break statement which basically stops all the replacements after the first one occurred
handling words in different cases. You are also not properly handling the titled or upper-cased words


Commented out Code

You should remove code that is commented out. If you think that you might need it in the future, think about using version control.

set_session_id()

This is only called in your commented out code. Does the user have to call it manually? If they don't, get_session_id() will return a wrong result. Maybe rewrite it like this (you don't seem to be using the field $sessionID, so you might as well get rid of it):

public function get_session_id(){
    return session_id();
}

if-else and session_exist

If you have code like this:

if( isset($_SESSION[$session_name]) ){
    return true;
}
else{
    return false;
}

you can rewrite it like this:

return isset($_SESSION[$session_name]);

Also, when you define a function like this, then use it. Instead of

if( !isset($_SESSION[$session_name])  ){

write

if(!session_exist($session_name]) ){

XSS

Using Session for XSS might be a possibility, depending on how your code is used. So in display_session I would clean the session with htmlentities to prevent XSS attacks.


The two first things that come to my mind:

Using template strings
Modifying the dropdown HTML once:

$(document).ready(function () {
    $("#ddlReleaseYears").change(function () {
        var data = "[2021,2020,2019,2018,2017,2016]";
        var arr = JSON.parse(data);
        $('#toptitle').text(arr[0]);
        var HTML = ""
        $.each(arr, function (index, value) {
            HTML += `<option value="${value}">${value}</option>`
        });
        // No need to set the html to "" and then append
        $("#ddlReleaseYears").html(HTML);
     })
});


Reverse shell allows connection between computers

Any suggestions?

The block of flavor text within that if/else...

    print "  |     |  | ,--` ,--` |  | --- ,--`"
    print "\ * /   |  | |  | |    |  |  |  |  |"
    print "-*+*-   |  | |--, |    |--|  |  |  |"
    print "/ * \   |  | | \  |    |  |  |  |  |"
    print "  |     `__, |  \ `__, |  | --- |  |"
    print ""
    print "Developer : Keegan Kuhn (keeganjk)"
    print "Version   : v1.1.1 (Pluteus)"

... might be easier to extend upon via Python formating...

__about__ = """
  |     |  | ,--` ,--` |  | --- ,--`
\ * /   |  | |  | |    |  |  |  |  |
-*+*-   |  | |--, |    |--|  |  |  |
/ * \   |  | | \  |    |  |  |  |  |
  |     `__, |  \ `__, |  | --- |  |

Developer: {author_name} ({author_nic})
Version:   v{version_num} ({version_nic})
"""

# ... other setup stuff maybe

if 'Windows' in platform.system():
    os.system('cls')
    print(__about__.format(author_name = 'Keegan Kuhn',
                           author_nic = 'keeganjk',
                           version_num = '1.1.1',
                           version_nic = 'Plauteus'))
else:
    os.system("clear")
    print(__about__.format(
        author_name = 'Keegan Kuhn',
        author_nic = '\033[1;31mkeeganjk\033[0;0m',
        version_num = '1.1.1',
        version_nic = '\033[0;32mPlauteus\033[0;0m'))

    How can I make this work better?

@Joshua Klein already pointed out that the code be blocking ya from the joys of multi-client access. Though I'd suggest considering some form of encryption and authentication of each connection and their messages first.

If you're really going after multi-OS support I'd advise having a handy way of spawning shells on each, Windows (last I checked) does not have Bash pre-installed.

After that it might be fancy to add argpars to the client and server scripts as well as some form of configuration file parsing.

Looking closer, one wonders what happens when you assign a variable and later try to access it?


Calling static methods

   public class Permutation{

Permutation doesn't really fit.  This isn't a permutation.  It's something that creates permutations.  Consider names like Permuter or PermutationUtils.

        Permutation p = new Permutation();
        String str = "1234";
        int n = str.length();
        p.permute(str, 0 ,n-1);

     }

     public static void permute(String str, int l, int r){

You don't need to call static methods from an object.  This could be just

        String str = "1234";
        int n = str.length();
        Permutation.permute(str, 0, n - 1);
     }

     public static void permute(String str, int l, int r) {

There's no need to instantiate an object.

Beyond that, I'd actually prefer

         PermutationUtils.permute("1234");
     }

     public static void permute(String str) {
         permute(str, 0, str.length() - 1);
     }

     private static void permute(String str, int l, int r) {

The caller shouldn't have to know details about how the method is called in my opinion.

Instantiating and using an object

class Permuter {

    private final String original;
    private final List<String> permutations = new ArrayList<>();

    public Permuter(String original) {
        this.original = original;
    }

    public List<String> permute() {
        if (permutations.empty()) {
            permute(original, 0, original.length() - 1);
        }

        return permutations;
    }

That's an example of how the class could be defined if it was meant to be instantiated.  Then you could call it like

    public static void main(String[] args) {
        Permuter p = new Permuter("1234");
        for (String permutation : p.permute()) {
            System.out.println(permutation);
        }
    }

This also returns the permutations and only displays them in the main method.  This is generally a better practice.  This way if what they really wanted was the permutations, you don't have to rewrite the whole code to give it to them.

You may want to consider using a longer variable name than p.  It's OK here, as it's only used on adjacent lines.  But in a longer method, single letter variables names can get confusing.

Don't do unnecessary work

         for(int i=l;i<=r;i++){
             str = swap(str,i,l);
             permute(str, l+1, r);
             str = swap(str,i,l);
         }

This pattern is what you would use if str were a mutable, like a StringBuilder or array.  Since swap creates a new string, you could just say

         for (int i = l; i <= r; i++) {
             permute(swap(str, i, l), l + 1, r);
         }

It's not necessary to call swap twice, since it doesn't change the original string.  This way str never changes.

I also changed the spacing.  It's easier to see where the variables start and end if there are spaces around the operators.

If efficiency matters

If efficiency matters, consider using a mutable instead.  This version creates a new string every time swap is called.  With a mutable, it could create a new string only when it needed to add to the list or display.


There is a couple of problems with your implementation.

The most important trait of the merge sort is stability: the elements compared equal retain their relative order. It does not matter when sorting integers, but is extremely important when sorting more complex data. The comparison

    if(A1[0] < A2[0]):

loses stability, because in case A1[0] is equal to A2[0] the element from A2 will be merged first. The correct way is to if A1[0] <= A2[0].
pop(0) has a linear time complexity, which renders the overall performance quadratic. B1 = B1 + A1 + A2 creates yet another copy of the list, and it doesn't help the performance either.

Manipulating indices, if done right, does reduce memory allocations and deallocations indeed. Unfortunately the GeeksForGeeks code you provided doesn't do it right.


This comparison can fail if there are any padding bytes within T, as those extra bytes are not initialized to any particular value.

Another source of failure can come from inheritance.  If one of the objects is part of a larger class (T is being used as a base class) with virtual functions, the vtable pointers can be different if a and b are part of different class hierarchies.  Virtual inheritance of base classes of T can also cause problems.

sizeof(char) is always 1, so there is no need to divide by it.

Since you're only reading from your parameters, you should take them by const &T to avoid making unnecessary copies.


Making empty cells in Underscore template

For one thing, the
 is opened but never closed here:

<% _.each(schemeCodeDetails, function (item, index) { %>
    <%= index % 7 == 0 ? '
' : null %>

                <%= item.schemeCode %>

<% }) %>

For another, it would be better if the template didn't have knowledge about the number 7 at all, for two reasons:

Right now both the JavaScript and the template share this number. If you change it in one place, you must remember to change in the other too.
The template needs special handling for the empty cells, using % 7. Ideally templates should be kind of dumb, and have as little logic as possible.

I suggest organizing the data into rows in the JavaScript, for example in obj.rows, like this:

var obj = {
    "schemeCodeDetails": [
        {"schemeCode": "AFN"},
        {"schemeCode": "BBT"},
        {"schemeCode": "BCH*"},
        {"schemeCode": "BCY*"},
        {"schemeCode": "BDP"},
        {"schemeCode": "BDQ"},
        {"schemeCode": "BDV"},
        {"schemeCode": "BDW"}
    ],
    "rows": []
};

var maxItemsPerRow = 7;
var i;
for (i = 0; i < obj.schemeCodeDetails.length; i++) {
    if (i % maxItemsPerRow == 0) obj.rows.push([]);
    obj.rows[obj.rows.length - 1].push(obj.schemeCodeDetails[i]);
}

for (var j = i % maxItemsPerRow; j < maxItemsPerRow; j++) {
    obj.rows[obj.rows.length - 1].push({"schemeCode": ""});
}

var template = _.template($('#scheme').html());

$('body').append(template(obj));

Using the new field, you could rewrite the HTML like this:


There are two issues I personally dislike very much.

Messing with date/time using homebrew algorithm and math

While looking easy to handle time/date are by far more complcated to handle than you ever can think of. Timezones, locals, leap years and so on. When doing time/date math and/or serialisation/deserialisation always(!) go for a library. For python this is datetime

When the code is lying to me when I'm reading it as natural language

With lying I mean your line

people_sorted_time[j].prio1 = people_sorted_time[j].prio2

This is not true. The person clearly stated a first priority project. When you change that value as an algorithmic side effect you immediatly break data integrity. Your person suddenly has both priorities on the same project. You even got yourself tricked. What happens, when a person got the first prio project taken away and later the second one as well?

Other issues

There is no need to have people_sorted_time, as you never refer to the read order again. Just do

people = sorted(people, key=lambda x: x.time)

Never loop over range(len(something), always try to loop over the elements directly. Your output loop rewrites (still lying about prio1) to

for p in people:
    res.write(p.name + "\t" + p.prio1 + "\n")

You use numpy only for reading a file, then convert back to standard python. This is a fail. Read with python directly.

with open("data.txt") as infile:
    lines = infile.readlines()
people = [Person(*line.split()) for line in lines]

You need time for comparison only. There is no need to mess with it, string comparison will do.

self.time = time

Do not modify the people data but maintain a set of available projects

prio1_projects = set(p.prio1 for p in people)
prio2_projects = set(p.prio2 for p in people)
projects_available = prio1_projects | prio2_projects

When assigning projects we do it like

people = sorted(people, key = lambda p: p.time)
assignments = []
for p in people:
    if p.prio1 in projects_available:
        proj = p.prio1
    elif p.prio2 in projects_available:
        proj = p.prio2
    else:
        proj =  None
    assignments.append(proj)
    if proj is not None:
        projects_available.remove(proj)

Note the new None case.

The output code

with open("results","w") as res:
    res.write("Name"+"\t"+"Assigned Project"+"\n")
    for p, a in zip(people, assignments):
        res.write(p.name + "\t" + str(a) + "\n")


Moving from normal threads to ExecutorService thread pools in java

A few simple remarks :

thread = new Thread(this, "SocketThread"); is no longer needed in MyRun, since the ExecutorService is the one creating and managing the Threads.
you will want to call execService.shutDown() to properly clean up the resources of the executorService.


Vectorizing a polar coordinate conversion loop in a fingerprint-matching process

You said your code works good, as the input isn't too big, so I won't go ahead an try to vectorize this. So, I've provided a general review of the code.

Overall your code looks nice. You should however attempt to have a bit more spaces

[Tdrow, Tdcol] = size(Td);  <-- This
[Tdrow,Tdcol]=size(Td);     <-- Not this

There are only a few things I would do differently in the code:

You can speed this up quite a bit even without vectorization: The size of the cells Tdp1 and Idp1 are known, so these cells can be pre-allocated in front of the loop:

[Tdp1{1:Tdrow, 1:Idrow}] = zeros(Tdrow, Tdcol);
[Idp1{1:Tdrow, 1:Idrow}] = zeros(Idrow, Idcol);

This way you avoid creating Tdrow*Idrow arrays inside the loop. That should save you some time.
Tdp(:,:) is the same as just Tdp, so you can do:

Tdp1{ii,jj} = Tdp;

Note,  ii and jj are better than i and j as iterator names in Matlab.
You are converting angles from radians to degrees a few places atan2(x,y) * 180 / pi. Instead, use atan2d(x,y). It returns the value in degrees directly.


Magic numbers

    final Node[] children = new Node[26];

Consider changing this to

    final Node[] children = new Node[Trie.ALPHABET_SIZE];

Now you don't have to manually change the array size if you change the alphabet size.  It may not matter here (we are unlikely to add a letter to the alphabet and you may not need to change alphabets), but it is good practice to set things up so that the system makes them the same.

Range-based for loops

        for (int i = 0; i < str.length(); i++) {
            int idx = str.charAt(i) - 'a';

This could be

        for (char c : str.toCharArray()) {
            int idx = c - 'a';

Then you don't have to maintain i manually.

You also may want to check that idx is in the range 0 to 25.  You currently just trust that that will be so.

Early exit

    void DFS(Node root, String prefix, List<String> list) {
        if (root != null) {

This could be

    static void DFS(Node root, String prefix, List<String> list) {
        if (root == null) {
            return;
        }

This way you don't have to enclose the entire method inside an if.  You can just bail out immediately.

The method should be static because it doesn't use any of the state of the trie.  In fact, one of its parameters has the same name as an object field.

Performance

I don't see anything that leaps out at me performance wise.  Tries are best at prefix searches and relatively slow and memory intensive to build.  For many uses, a HashSet (for full word searches) or even an ArrayList is faster.  We need a long run to amortize out the build time enough to give faster prefix lookups.

Anyway, time your actual usage to see if this solution is faster than other solutions.


Sort numbers in ascending order using Python

You could combine your input to a single line to improve ease of use. For example,

storage = input("Enter values separated by spaces:")
storage = [int(x) for x in storage.split()]

This way you have the entire list of input and can avoid having to have the user enter the number of input, and avoid having to declare the num variable at all.

However, you probably also want to include some form of input validation or throw a meaningful error as right now if your user was to enter non-integers, your program would simply crash and output a vague error that the user would probably have a difficult time understanding.

try:
    storage = [int(x) for x in test.split()]
except ValueError:
    print("Non-integers in input!")

Alternatively, you could check if all the values are numeric and if not, have the user re-enter their input.

As for your sorting algorithm, if you don't want to use Python's implemented sort() or sorted(), you should research more efficient algorithm's such as quick sort or even implement the bubble sort that you learned.

Currently, your min_sort algorithm finds the minimum value in the list, which is O(n) then removes that element from the list (separately from the search) which is again O(n). This is extremely wasteful as you may end up searching through the entire list again and again (n times), so it would be better to use a more efficient sorting algorithm or at least recognize that we don't need to pass through the entire list twice on each iteration, just pass through the list once and keep track of the minimum value. You could do this by writing your own function like:

def find_remove_min(nums):
    """Returns the minimum number and the list without the min number"""
    if nums:
        min_index = 0
        for i in range(1, len(nums)):
            if nums[i] < nums[min_index]:
                min_index = i
        return nums[min_index], nums[:min_index] + nums[min_index+1:]

Then you could do something like,

while storage:
    min_num, storage = find_remove_min(storage)
    result.append(min_num)

which would be more readable and efficient imo.


Extension pattern in a flask controller using importlib 2.0

Can you give me your opinion on this piece of code ? Is it "pythonic" ?

I don't really see anything non-pythonic about it.
Some minor coding style issues though:

Minor PEP8 violations:

put 2 blank lines before class and top-level function definitions
use snake_case for function names instead of camelCase

Unnecessary parentheses in if (endpoint_name in self._endpoints_classes):

A bigger issue I see is that the module loading is convoluted and fragile:

HandlerCollection.getClass tries to import a module : violates the single responsibility principle, it would be better to move this logic somewhere else
The imported module is expected to have a register function : a semantic rule, not obvious enough from the code itself. There are no docstrings either, so as it is, implementors have to dig this piece of information out of the current implementation details
The register function must pass a class that has a name property defined : semantic rule, see the previous item
The logical flow of HandlerCollection.getClass is convoluted:

try to import module if missing
pass self to module.register
module.register calls me.addClass

I suggest to move the module loading part out to a different method, perhaps HandlerRegistry.load_and_register_if_missing, and let getClass behave as a simple cache.


To be honest I don't quite understand what you are asking in your question, so I'll just do a general review:

You said your class names are temporary (you should only be posting "finished" code here), however currently they are very confusing because they are all very generic or don't actually say what they are for.

Apart from that you have far too many class names and possibly too many unnecessary DIVs. Use class names only in exceptional cases. For example, having all list items have the same class name is useless. Also use other HTML elements other than div and lists. header, 'nav' and h# would help here a lot.

The triangle DIV is unnessary. Use the CSS pseudo element :before instead.

And have the title element ("E-Mail") should not be identified by be the first element of the list, but should either have a class, or possible moved out of the list all together and marked up with a heading element (h3 or so).

The HTML could look something like this:

E-Mail

Settings

Account

Download Software

Help

Sign Out


Review

You should avoid hardcoded strings. Take advantage of nameof. Also, expression-bodied members (arrow notation) makes code cleaner to read.

public string Name
{
    get => GetFieldValue<string>(nameof(Name));
    set => SetFieldValue(nameof(Name), value);
}

EntitySubset<T>'s method GetFieldValue makes sure a clean (but technical) error message is thrown whenever an asked field is not available.

public override U GetFieldValue<U>(string fieldName)
{
    if (!Fields.ContainsKey(fieldName))
    {
        throw new Exception($"{typeof(T).Name} must contain {fieldName} as a key!");
    }
    return base.GetFieldValue<U>(fieldName);
}

However, don't fallback to this method to perform business rules checks. The business layer should check that mandatory fields are filled in, before mapping the entities to the data layer.

You should also optimize ContainsKey and base.GetFieldValue. You don't want to perform 2 lookups here. Implement something like a TryGetFieldValue.


Assumption: k << N, where N = len(points)

There is no need to sort the entire list of points!

Instead, take the first k points, and determine their distance values, and sort them.  Then, for each success point:

determine its distance,
if it is smaller than the maximum,

discard the maximum, and insert the new point in the sorted list.

Sorting N points by distance is O(N log N); creating and maintaining a sorted list of k smallest elements is only O(N log k), which should be considerably faster.

I'm not sure if heapq.nsmallest() is built into CPython or not ...

k_neighbours = heapq.nsmallest(k, points, key=distance)
counter = Counter(x.classif for x in k_neighbours)

Well, I'm disappointed to see heapq.nsmallest() performed up to 40% worse that sorted on CPython, but I'm happy to see PyPy validates my assertion that you don't need to sort the entire list.

Continuing with that thought, bisect.insort() may be used to maintain a list of the k-nearest neighbours so far:

    neighbours = [(float('inf'), None)] * k
    for pnt in points:
        dist = distance(pnt)
        if dist < neighbours[-1][0]:
            neighbours.pop()
            bisect.insort(neighbours, (dist, pnt))

    counter = Counter(pnt.classif for dist, pnt in neighbours)

This gave me 4% speedup over sorted()[:k] with your gist sample set.

Significant, but not impressive.  Still, it was enough encouragement to press on an look for other inefficiencies.

How about the distance() code.  It gets called a lot; can we speed it up?  Sure!

def predict(target: Coordinates, points: Sequence[KNNPoint], k: int, *,
            sum=sum, zip=zip) -> str:

    def distance(p: KNNPoint) -> float:
        return sum((a - b) ** 2 for a, b in zip(target, p.coords))

    # ...

Instead of searching the global scope for the sum and zip functions, they are saved as variables sum, zip in the local scope, along with target, for use in distance().  Total improvement: 6%.

Applying the same sum=sum, zip=zip change to the original code, without the bisect.insort() change, also speeds it up by 2%.

Further, adding insort=bisect.insort to the function declaration, and using insort(neighbours, (dist, pnt)) in the function body also provides a minor improvement.

Finally, I was concerned about neighbours[-1][0].  Looking up the first tuple of the last element in the array seemed inefficient.  We could keep track of this in a local threshold variable.  Final total speedup: 7.7%.

neighbours = [(float('inf'), None)] * k
threshold = neighbours[-1][0]
for pnt in points:
   dist = distance(pnt)
   if dist < threshold:
      neighbours.pop()
      insort(neighbours, (dist, pnt))
      threshold = neighbours[-1][0]

YMMV


Rsync script that does Daily, Weekly and Monthly backups with hard links

Error handling

Error handling is always important,
especially when working with something so important as backups.
In particular, the result of the rsync commands is not checked,
the script logs "backup completed" messages,
which doesn't say anything about success or failure.

I suggest to add a check on the exit status of all the rsync commands,
and to make the log message reflect the state of success/failure (or simply include the exit code directly).

Don't repeat yourself

There are some repeating elements in the code:

logger $period REDBackup $result -t$PROG_NAME $(date "+%m-%d-%Y %r")
/usr/local/emhttp/webGui/scripts/notify -e "unRAID Server Notice" -s "Server Backup" -d "$period REDBackup $result" -i "normal"

I replaced with $period and $result the parts that could be parameterized.
Extracting these commands to helper functions can greatly reduce duplicated logic, and improve readability.

A word on quoting

It's recommended to double-quote all variables used as command arguments.
For example instead of this:

rsync -a -v --delete $BACKUPPOINT/ $MOUNTPOINT/Daily/ 2>&1

It will be safer to write:

rsync -a -v --delete "$BACKUPPOINT"/ "$MOUNTPOINT"/Daily/ 2>&1

Maybe you know that these variables will always be safe.
But it's good to take this simple precaution anyway,
and make it a habit so it's automatic and you will never fall in a trap of unintended word splitting or globbing.


Brute-force search for solution to an unsolved mathematical inequality

A first step in optimizing would be to avoid computing the same values multiple times.

Secondly, I would drop the floating point arithmetic altogether. You have integer bases with integer exponents, so use integers. \$(\frac{3}{2})^k\$ = \$\frac{3^k}{2^k}\$ and applying floor also results in an integer.

I'm not familiar with the problem at hand, but the mention that none are known leads me to think that the values might be quite higher than 1000, otherwise a solution would have been trivial to find.


Filtering JSON objects from array of values

You are basically making your object filtering into an \$0(m * n)\$ complexity function ( where \$m\$ is number of type id’s) that your are filtering against and \$n\$ is number of objects in the fetched result set.   This function should only be \$0(n)\$.

To do this, make type id’s into a Set which allows \$O(1)\$ lookup and then use this Set to filter the fetched objects.

For example:

const typeIds = new Set([ /* ids here */ ]);
const isFilteredType = (element) => typeIds.has(element.type);

// and later when filtering results
.then( (out) => out.filter(isFilteredType) );

It is also customary in javascript to use lowercase first letter for variable names. Your code would look odd to most JS developer for this reason.

There is really not much of a reason to use var in modern JavaScript.  You should primarily use const with let being used where the variable needs to be reassignable.

It is not really clear here why JSONpull and FilterJSON are even needed.


Serializing object graph to proprietary binary file

BinaryFormatter is not adding any extra information. It does not store "here comes a double", this must be stored/handled by the reading algorithm.

But to reproduce a certain byte order, you have to overwrite almost every serializing routine. At the end you gain nothing, comparing to your self-implementation. So it's not the extra-information, it's the order of elements, that might cause trouble when using the given BinaryFormatter.

Each class can be responsible for it's own serialization, if you have only one serialization. If you can always modify your own code, the classes and the serialization never go separate ways to separate libraries, then this might be a good way.

A more sophisticated approach would be a Visitor-pattern. This way you can implement multiple Serializers (Visitors), store in different formats, etc.

One way you have everything concerning a class in the class, the other way you have everything concerning one specific file format in one class. This you have to make up with yourself, it depends on how often you plan to modify or extent anything later on.

Serializing is a streaming process. You create only one Stream ( a File or MemoryStream), don't use one per item, and assemble it later on. You create one Formatter/Writer, and pass this to each item. Each item is storing it's stuff into the output stream. So an item with one property to store, should have one line of code in it's Serializer method.


Count of category occurances (multiple cateogries can fall under each row)

All I did was convert all if statements with exact values into a dictionary. This way will allow you to increment the values of each key without as much if/else usage. If you then want to later on pass the values of each key to a variable of your choice, you can just loop through the dictionary once, which is less time consuming and it also makes debugging easier.

I didn't touch the if statements using in. You can try placing it in the dict too.

all_dict = {'customer service':0,
    'long-wait_times':0,
    'contact_issues':0,
    'canada_related':0,
    'product + info':0,
    'design issues':0,
    'gift_wrapping':0,
    'stores':0,
    'email' :0,
    'suggestions':0,
    'rewards':0,
    'registry' :0,
    'returns_cancellations':0
    'technical_issues':0,
    'product_not_available':0,
    'site_performance':0,
    'unable_to_checkout':0,
    'unable_to_add_or_remove_products':0,
    'promotions':0,
    'payment_options':0,
    'paypal':0,
    'shipping_cost':0,
    'order_total_wrong':0,
    'backorder':0,
    'address_not_fitting_or_incorrect':0,
    'where_is_my_order':0,
    'BOPIS':0,
    'delivery_issues':0,
   'no_communication_or_delays':0,
   'damaged_product':0,
  'unassembled_assembly_issues':0
  }

for index, row in df.iterrows():
    for key in (row['taxonomy'] ) :

        if key in technical_issues_list:
            technical_issues += 1

        elif key in checkout_list:
            checkout += 1

        elif key in fulfillment_list:
            fulfillment += 1

        elif  'returns_cancellations' in key:
            returns_cancellations +=1

        else:
            all_dict[key] += 1


Python/Django Filter with Datetime and extra options

Set your locale globally

I would recommend doing this in your settings.py file or within a global __init__.py file.

locale.setlocale(locale.LC_TIME, "de")

Django template tags allow multiple parameters, use them

Right now you have a single complex parameter which is being used to store two pieces of information: whether to use a sentence and if only the date should be rendered. Since this is passed in as a single string, you have to use the str2bool function from Stack Overflow in order to parse it. You don't need to parse that string if you use separate arguments.

@register.filter
def naturaldaytime(daytime, sentence=False, only_date=False):
    from django.conf import settings

    if daytime is None:
        return daytime

Use descriptive variable names in your comparisons

Right now you have to look into nested calls to understand what comparisons are actually being done. While this still needs to happen, you can make us to intermediate variables which makes it a lot more clear what is happening.

todays_date = datetime.now().date()
yesterdays_date = todays_date - timedelta(days=1)

daytime_week_number = daytime.date().isocalendar()[1]
todays_week_number = todays_date.isocalendar()[1]

Construct the format key you need so you can avoid repetition

Right now you have a complex set of conditional statements that you are using to determine what date format to use. This is resulting in a ton of repetition when it comes to doing the actual formatting, so I would recommend separating the "getting the right format settings" part from the actual "do the formatting".

if not only_date:
    setting_key = "DATETIME_FORMAT"
else:
    setting_key = "DATE_FORMAT"

if daytime.date() == todays_date:
    setting_key += "_TODAY"
elif daytime.date() == yesterdays_date:
    setting_key += "_YESTERDAY"
elif daytime_week_number == todays_week_number:
    setting_key += "_THIS_WEEK"
elif daytime.date().year == todays_date.year:
    setting_key += "_THIS_YEAR"

if sentence:
    setting_key += "_SENTENCE"

This way you don't need to keep repeating the same logic for every "sentence" or "not only the date" variant, and you can keep settings keys consistent at the same time.

Get the right date format using that settings key you already built

This part doesn't change much, except you now need to dynamically retrieve the setting from the settings object.

date_format = getattr(settings, setting_key)

return daytime.strptime(date_format)


Function to discard repeats, applied to numbers

Nice solution. Your solution already works great with sequences of numbers (and more) already. The comp multi-method is not a good idea. It is a function which can take either a seq or a number. You should avoid creating functions that take arguments that can be different types (it is confusing and suggests your might be better off with 2 functions or a protocol) unless there is a really good reason. In this case comp does not add anything useful (why did you add it? do you have an example use case?)


Get the highest role of a user across all the organizations he is member of

Well, this is what I did. Not sure if that's the best way to go.

def getMaxUserLevelByUserId(userId: Muid)(
      implicit connection: Connection): Option[OrganizationMembership.Level.Value] = {
    val organizationMemberships = getAllByUserId(userId)

    if (organizationMemberships.nonEmpty) {

      val levelMap = Map(
          OrganizationMembership.Level.Guest -> 0,
          OrganizationMembership.Level.Member -> 1,
          OrganizationMembership.Level.Admin -> 2
      )

      val maxLevel = organizationMemberships.foldLeft(OrganizationMembership.Level.Guest) {
        (level, organizationMembership) =>
          if (levelMap(organizationMembership.level) > levelMap(level)) {
            organizationMembership.level
          } else {
            level
          }
      }

      Some(maxLevel)

    } else {

      None

    }
  }

The idea behind the code above, is the fact that we are iterating through the collection only once, regardless of the collection size.
The levelMap was created strictly for the reason of easier comparison.

The cool thing about foldLeft in this case is that we don't need to create mutable variables while iterating through the collection and it is actually very short and quite readable code.


Binary search that returns bitwise complement of missing index

• First comment is about the way you are adding the functions to the Array prototype : by just adding them this way, you 'pollute' the keys of the array, so anyone doing a for ... in for instance will enumerate also on the added functions.
-->> Use Object.defineProperty to have those function non enumerables.
The pattern could look like :

(function () {

    var newArrayMethods = {
        //  Returns a shallow copy of this array
        copy: function () {
            return this.slice(0);
        },

        // Returns true if this array contains 'element', returns false otherwise
        contains: function (element) {
            return this.indexOf(element) >= 0 ;
        }
    }

    // let's install those methods on the prototype
    for (var newMethodName in newArrayMethods) {
        installFunction(newMethodName, newArrayMethods[newMethodName]);
    }

    function installFunction(name, fn) {
        if (Array.prototype[name]) throw ('Array method ' + name + '() already defined.');
        Object.defineProperty(Array.prototype, name, {
            value: fn
        });
    }

})();

• Second thing is that typeof is slow : you don't want to use it within a loop.
The code below also avoids one branch per loop.

function binarySearch (target, comparator) {
    var l = 0,
        h = this.length - 1,
        m = 0,
        comparison = 0;
   comparator = comparator || compareNumbers ;

    while (l <= h) {
        m = (l + h) >> 1;
        comparison = comparator(this[m], target);
        if (comparison < 0) {
            l = m + 1;
        } else if (comparison > 0) {
            h = m - 1;
        } else {
            return m;
        }
    }
    return~l;
};

function compareNumbers(a,b) { a-=b;  return (a<0) ? -1 : ( a>0 ) ? 1 : 0 ;  } ;

• Array.splice is to be avoided if you seek performances : it is slow and creates garbage.
Do the insertion yourself.
I wrote below insertion function moving forward, to avoid cache miss.

You'll notice i changed the insert function signature so it is more alike to the search (target + comparator arguments first).

Also no need to process an argument that defaults to false.

function binaryInsert(target, comparator, duplicate) {
    var i = this.binarySearch(target, comparator);
    if (i >= 0 ) {
        if (!duplicate) return i;
    } else {
        i = ~i;
    }
    insertOneAt(this, target, i);
    return i;
};

function insertOneAt(arr, item, index) {
    var tmp1=item, tmp2=item;
    var len = arr.length;
    for (; index<=len; index++) {
       tmp2 = arr[index]
       arr[index]=tmp1;
       tmp1=tmp2;
    }
}

• Detail : change your binaryInsert comment about the return value to something like :

Returns: Index of new item added to array, or of the existing item if  duplicate==false and the item was found.

• You have also some decision/changes to make about the way you handle duplicates in your search.
As of now search returns any matching item's index (compare==0), it does not ensure, for instance, that it is the smallest index.
If it's ok just mention it, otherwise you have to change a bit your search.

Since the insert relies on search, your decision on the search will affect insert's semantic as well.


Is there a better way to avoid repeated 'Len == 1' when interpreting booleans from strings?

How can I improve my function, to not be as redundant while checking if Len is equal to 1?

Make the null character part of the check. Len not needed anywhere.
// if (Len == 1 || (Len == 5 && !memcmp(Str+1, (const char[]){'a', 'l', 's', 'e'}, 4))) {

if (StrIn[1]==0 || !memcmp(Str+1, (const char[]){'a', 'l', 's', 'e', 0}, 5))) {
// or
if (StrIn[1]==0 ||
    (StrIn[1]=='a' && StrIn[2]=='l' && StrIn[3]=='s' && StrIn[4]=='e' && StrIn[5]==0)) {

Bug
BoolFromStr(const char *const StrIn, register const unsigned char Len) is a wrong when the length of the string is say 257 and called as
const char *s = "ttt....ttt"; // 257 t's
BoolFromStr(s, strlen(s)); // reports 1 even though `s` is not `"t"`.

Recommend size_t and drop the register.  Do not tie the compilers hands.
BoolFromStr(const char *StrIn, size_t Len);

To reduce size and improve speed I'd consider a hashing of the first byte of StrIn
// Pseudo code

int BoolFromStr(const char *StrIn) {
  const char *tf[] = {"0", "1", "false", "true", "no", "yes", "", "" };
  unsigned hash = hashf(StrIn[0])%8;
  const char *cmps = tf[hash];
  if (StrIn[0] == cmps[0] && (StrIn[1] == 0 || (strcmp(StrIn, cmps) == 0))) {
    return hash & 1;
  }
}

See similar What's the fastest way to interpret a bool string into a number in C?.


takeWhile, groupBy and group higher order functions

struct equal is kind of useless. There's std::equal_to, which does the same thing.
You can make the design more flexible (and more standard library-like) by passing an output iterator to the groupBy and group function instead of creating a new container inside the function. It's useful if the user wants to write pairs that represent groups to an existing container or to a C-style array.


If you're using C# 6.0, I believe you can drop the null-check:

public static string WithMaxLength(this string value, int maxLength)
{
    return value?.Substring(0, Math.Min(value.Length, maxLength));
}

Other than that, it's like Jeroen said: that's pretty much as good as it gets.

The class and parameter naming is exactly as I'd have it, and the name of the extension method is decent, although I'd try to find a name that better indicates that truncation will occur when value is longer than maxLength... but WithMaxLength isn't a bad name.


A switch case statement that returns a timespan

private const double yearMultiplier = 365.2425;

private Dictionary<TimeUnit, Func<double, TimeSpan>> timespanConverters = new Dictionary<TimeUnit, Func<double, TimeSpan>>
{
    { TimeUnit.Seconds, TimeSpan.FromSeconds },
    { TimeUnit.Minutes, TimeSpan.FromMinutes },
    { TimeUnit.Hours,   TimeSpan.FromHours },
    { TimeUnit.Days,    TimeSpan.FromDays },
    { TimeUnit.Months, t => TimeSpan.FromDays((int)t * (yearMultiplier / 12))) },
    { TimeUnit.Years,  t => TimeSpan.FromDays((int)t * yearMultiplier)) }
}

// ....

public TimeSpan ResetTimeSpan
{
    get
    {
        return timespanConverters[ResetTimeUnitEnumValue](ResetTime);
    }
}

Bit of a shame that System.TimeSpan doesn't have FromMonths or FromYears methods otherwise this would look really neat :)


public static Task<PaginatedList<T>> ToPaginatedListAsync<T>(
  this IQueryable<T> source, int pageSize, int pageIndex = 1)

Your method says Async, returns a Task<PaginatedList<T>>, but... it doesn't say async.

public static async Task<PaginatedList<T>> ToPaginatedListAsync<T>(
  this IQueryable<T> source, int pageSize, int pageIndex = 1)

With the async keyword specified, you can now await your result - not sure what AsAsyncEnumerable does, but it doesn't seem necessary then:

return await Task.Run(() =>
{
    var count = source.Count();
    return
        source.Skip((pageIndex - 1) * pageSize).Take(pageSize)
        .Aggregate(new PaginatedList<T>(
            totalCount: count,
            pageSize: pageSize,
            pageIndex: pageIndex), (list, x) => { list.Add(x); return list; });
});

On the other hand, you're not really aggregating with Aggregate; LINQ stands for Language-INtegrated Query, and a query that has side effects isn't really a query.

source.Skip((pageIndex - 1) * pageSize).Take(pageSize)

That part is fine. Or is it? Why do you need to -1? Is pageIndex 1-based? That's pretty confusing, given the list itself is 0-based. What's the meaning of "page 0" then? Why make it throw when assigned to 0, in the setter, when the only caller for that setter is in the constructor? Better fail early and put a guard clause in the constructor and throw that ArgumentOutOfRangeException with a shorter stack trace.

I don't know why, the more I look at the Aggregate call, the more I want the method to be returning an IEnumerable<T>.

The caller already knows the totalCount (well it can have it), the pageIndex and the pageSize, and you're only ever returning a single page - I don't see why a PaginatedList<T> needs to know this metadata at that point.

If you can return an IEnumerable<T>, then you could yield the results and have this:

public static IEnumerable<T> OfPage<T>(this IQueryable<T> source, int pageIndex, int pageSize = 10)
{
    foreach (var item in source.Skip((pageIndex - 1) * pageSize).Take(pageSize))
    {
        yield return item;
    }
}

Notice I made the pageIndex mandatory, and pageSize optional - anyone using this API would expect to be able to pass a page index as a first argument to a method called OfPage.

Now, yield is pretty much the opposite of async, and it's not really buying anything here, since Take should already materialize the query, so you could have this async one-liner then:

public static async Task<IEnumerable<T>> OfPageAsync<T>(this IQueryable<T> source, int pageIndex, int pageSize = 10)
{
    return await Task.Run(() => source.Skip((pageIndex - 1)*pageSize).Take(pageSize));
}

If PaginatedList<T> doesn't need to know the totalCount, pageIndex and pageSize, then it doesn't need to exist - it's not adding any functionality, merely carrying metadata that the caller already knows, and if it needs to be carried along with the items on that page, then PaginatedList<T> can exist, but then as a composition:

public class PageItems<T> // not a list
{
    private readonly IEnumerable<T> _items;
    private readonly int _page;
    private readonly int _pageSize;

    public PageItems(IEnumerable<T> items, int page, int pageSize)
    {
        _items = items;
        _page = page;
        _pageSize = pageSize;
    }

    public IEnumerable<T> Items { get { return _items; } }
    public int PageIndex { get { return _pageIndex; } }
    public int PageSize { get { return _pageSize; } }
}

Notice that's exposing IEnumerable<T> and not List<T> or even IList<T>: if you don't need to do anything other than iterate these items, you don't need a List, you need an IEnumerable. The code doesn't change much:

public static async Task<PageItems<T>> OfPageAsync<T>(this IQueryable<T> source, int pageIndex, int pageSize = 10)
{
    return await Task.Run(() =>
    {
        var items = source.Skip((pageIndex - 1)*pageSize).Take(pageSize)
        return new PageItems(items, pageIndex, pageSize);
    });
}


Very interesting and fun question. Boilerplate code is a reason to close questions down, but this code is a perfectly valid question.

Naming

JavaScript uses lowerCamelCase variable and function names, avoid names like public_interface and option_one.
You have anonymous functions, this makes stack-traces needlessly complicated, go for __construct: function pluginConstructor (options) {
Prefixing with _ should be avoided. If you do it, ensure _ items are 'private' unlike __construct

Idioms and Custom

Yoda conditionals like if ( undefined == $.data(this, "plugin_" + PLUGIN_NAME) ) are hard to read
Worse, your conditionals are not consistently Yoda: if ( typeof plugin.public_fn[prop] === 'function' )

Comments

I like your approach to commenting

JSHint.com

Your have problems in your code:

Unnecessary semicolon
Declaring functions in an extra set of {} is bad practice
Use plugin.container, not plugin['container']
prop leaks in to the global namespace here: for ( prop in plugin.public_fn ) {

Finally, having undefined as a parameter is silly. If you were to pass anything but undefined, then your yoda condition would fail.


Project Euler #14: Longest Collatz sequence

Your algorithm involves the following:

Make a list of size 1,000,000
Until done:
a. Make a new list of size 1,000,000
b. Make  another new list of size 1,000,000
c. Make another new list of size 1,000,000
d. Iterate over it twice
e. And then another time

That strikes me as extremely expensive to start out. Furthermore, consider all the extra work we're doing. The sequence in the problem example is:

13 --> 40 --> 20 --> 10 --> 5 --> 16 --> 8 --> 4 --> 2 --> 1

You are calculating all 10 of those chains independently. That means you're calculating the chain for 16 six times. That's an enormous amount of extra work. The actual longest chain is of length 525. That means that for the actual answer, we are doing 524 more iterations than necessary, and we end up having to create over 1500 lists of size one million. Even if most of the time, most of our elements will be 0! We can do way better by just memoizing, which also takes less memory to boot!

Just looking at some runtimes for small values of target (10x each via timeit):

target        OP
100        0.09s
1000       1.29s
10000     19.07s

A few code comments before I get into a simpler algorithm. Don't use map(). It's far more complicated than a list comprehension. These two:

first_list = list(map(lambda x : x , range(1,target+1)))
new_list = list(map(lambda x : x/2 if x%2==0  else 3*x+1 , given_list))

Can be replaced by:

first_list = range(1, target+1)
new_list = [x/2 if x%2 == 0 else 3*x+1 for x in given_list]

The latter could be wrapped further to avoid the extra list comprehension just to move your 1s to 0s but it's overkill anyway. Similarly, your:

reduce(lambda x,y : x+y, new_list)

Could be replaced by:

sum(new_list)

Better Algorithm

First, let's start with our handy memoize decorator:

def memoize(f):
    cache = {}
    def wrapper(*args):
        if not args in cache:
            cache[args] = f(*args)
        return cache[args]
    return wrapper

And then start separating our concerns. We will write a function that for ONE value of n finds the length of a chain:

@memoize
def collatz_chain(n):
    if n == 1:
        return 1
    elif n % 2 == 0:
        return 1 + collatz_chain(n/2)
    else:
        return 1 + collatz_chain(3*n+1)

And then we just need to wrap all of that:

return max(range(1, target+1), key=collatz_chain)

It's still linear time, but I end up doing FAR less work than you have to, since most of the time I'm doing almost nothing. And the numbers show it:

target        OP    memoize
100        0.09s     0.003s   ~30x
1000       1.29s     0.024s   ~54x
10000     19.07s     0.239s   ~80x


How do I reduce lines of code in this piece of code? A number of lines are being repeated in updateProfileFlags and fetchProfileObj

I am not sure how many lines of code can be reduced but one thing is for sure: whenever you encounter a resource that can be closed, you should use Java try-with-resources feature (since java 7).  Not only this feature saves you the close() operation (one line less!) but also ensures that the resource is properly closed by the end of the try block no matter if it ended successfully or not (the compiler adds a finally clause). in the current code, if an exception is thrown, the Ttransport resource is not closed properly.

I looked at the thrift javadoc and indeed from version 0.10.0, Ttransport is auto-closeable.  So the code on both methods should be

try (TTransport transport = new TSocket("172.XX.X.XXX", 9321)) {
  transport.open();
  ...  // do not call close()!!
  // do not call close()!! it is added by the compiler
} catch(Exception e) {
  e.printStackTrace();
}

Regarding reducing duplicated lines, I can offer that you make a method to create the ids map.  so if the contents of the map need to be modified due to modifications in the requirements or API, there will be only one place to modify them.  creating constant variables instead of embedded literals is also considered best practice.  This can apply to other literals used in the code

public static final String PROFILE_REQUEST_KEY = "requestId";
public static final String PROFILE_REQUEST_VALUE = "settingsService";
public static final int    PROFILE_WHATEVER_105_MEANS = 105;
public static final String PROFILE_WHATEVER_RESMAN5_1_MEANS = "resman5_1";

public Map<String, String> getProfileRequestProperties() {
  return Collections.singletonMap(PROFILE_REQUEST_KEY, PROFILE_REQUEST_VALUE);
}

now, since we eliminated close(), we can return the value direct from the call to the client, eliminating the creation of the profileObj reference:

return resumeServiceClient.getFullActiveProfileFromUserId(
         getProfileRequestProperties(),
         PROFILE_WHATEVER_105_MEANS,
         userId,
         PROFILE_WHATEVER_RESMAN5_1_MEANS);

so, I ma not sure how many LOC are now present, but im my eyes, the code is clearer and more maintainable and extensible.


Which is better practice for this if elif… else statement?

The following is better IMO. Duplicated "A is odd" / "A is even" strings are omitted from the output. They could be added if required.
if A % 2 == 0:
    if A % 6 == 0:
        msg = "a multiple of 6 (6, 12, 18, 24, 30)"
    elif A % 10 == 0:
        msg = "a multiple of 10 (10, 20)"
    else:
        msg = "a number out of 2, 4, 8, 14, 16, 22, 26, 28"
    print(f"A is even and {msg}.")
else:
    if A % 3 == 0:
        msg = "a multiple of 3 (3, 9, 15, 21, 27)"
    else:
        msg = "a number out of 1, 5, 7, 11, 13, 17, 19, 23, 25, 29"
    print(f"A is odd and {msg}.")

As for which one of the two versions of the provided code is better, I agree with @stefan's answer.


Scaling up the intelligent concatenation of 2 columns in R

R is well-suited for vector operations.
It's not well-suited for loops,
which you should avoid as much as possible.

Consider this condition in your code:

if(is.na(data$Term_code[i]) && !(is.na(data$Term_code1[i]))){
  data$Term_code[i] <- data$Term_code1[i]
}

How about if we remove the second condition after the &&:

if(is.na(data$Term_code[i])){
  data$Term_code[i] <- data$Term_code1[i]
}

The outcome won't change, right? If Term_code1 is not NA, then we'll get its value, if it's NA, well, we already had NA, so it makes no difference.

The good thing about this transformation is that now we can convert this directly to a vector operation without a loop:

no.term.code <- is.na(data$Term_code)
data$Term_code[no.term.code] <- data$Term_code1[no.term.code]

That is, set the values of Term_code to the values of Term_code1 where Term_code is NA.


I usually think that a mutable array or dictionary as a return value is a bad thing, unless there is a good reason. By this I mean the promise of the API, not the actual value returned. I don't see a reason that the value returned must be mutable, so if you're not planing to modify the return value often I'd change the return type of parse to NSDictionary (you can still return the mutable dictionary in its implementation, that's OK; if you'd like to feel save do return [result copy];).
Since your class actually only has just one method, and that can be made generic, I'd either turn that method into a class method or turn it into a free function altogether (unless you plan to add more functionality, of course). Like:

@interface FileStructureRepresentation : NSObject
+ (NSDictionary *)fileStructureRepresentationForPath:(NSString *)path;
@end

// or even

NSDictionary *FileStructureRepresentationForPath(NSString *path);

-[NSFileManager contentsOfDirectoryAtPath:error:] returns an array of NSString objects, so it should be for(NSString *s in listOfFiles).
When you detect an error (if(error.code != 0)) you should return. I'd return nil. A better way to check for error here would be if(error != nil) since the error code 0 might be a valid value in certain error domains.
In your if([fileType isEqualToString:@"NSFileTypeRegular"]) block you are not using braces, even though you do use them for if(error.code != 0) (both have only one line bodies). I'd make sure they're consistent, but especially with respect to goto fail I recommend to always use braces unless you have the if and the body on the same line. It's a matter of taste, though.
Instead of [fileAttributes valueForKey:NSFileType] you really want [fileAttributes objectForKey:NSFileType] or even simply fileAttributes[NSFileType]. See Difference between objectForKey and valueForKey?.
This is minor: instead of doing [NSString stringWithFormat:@"%@/%@", path, s] it's more explicit and "correct" to do [path stringByAppendingPathComponent:s].
You're not evaluating and handling the error from your call to [fileManager attributesOfItemAtPath:temporaryPath error:&error];. If you don't plan to, just pass NULL instead of &error. Otherwise, the question is how to react to the error, that's up to you and your requirements: maybe just skip the entry: if (error != nil) { /* Clear error for next iteration. */ error = nil; continue }


I did that ugly try, because of NullReferenceException (if form is filled correctly, there would be no summary element, and if form is filled incorrectly, there would be no popup element).

This problem can be easyly handled by a null check of the returned WebElement from the call to Driver.FindElement().

A little bit more problematic is IMO the looping condition because the condition only could evaluate to true if the passed TimeSpan is negativ. If this is what you want you really should place a comment there. If you didn't mean to pass a negative timespan then you should reverse the looping condition to DateTime.Now < deadline.

Extracting the repeated call to TimeSpan.FromSeconds(5) to a variable will make the code easier to read.

You know although copy & pasta will save time, you need to check if the pasted code is correct (empty data vs tooMuchData)

    // check if empty data
    try
    {
        var tooMuchData = new WebDriverWait(Driver, TimeSpan.FromSeconds(5))
    .Until(ExpectedConditions.TextToBePresentInElement(Driver.FindElement(By.Id("popup")), "Empty data"));
        if (tooMuchData) return false;

Implementing the mentioned points will look like so

public bool? GetResult(TimeSpan timeout)
{
    var deadline = DateTime.Now.Add(timeout);
    var waitTimeout = TimeSpan.FromSeconds(5);

    do
    {
        WebElement summaryWebElement = Driver.FindElement(By.Id("summary"));
        if (summaryWebElement != null)
        {
            var success = new WebDriverWait(Driver, waitTimeout).Until(ExpectedConditions.TextToBePresentInElement(summaryWebElement , "Success!"));
            if (success) return true;
        }

        WebElement popupWebElement = Driver.FindElement(By.Id("popup"));
        if (popupWebelement != null)
        {
            var notEnoughData = new WebDriverWait(Driver, waitTimeout).Until(ExpectedConditions.TextToBePresentInElement(popupWebElement, "Not enough data"));
            if (notEnoughData) return false;

            var tooMuchData = new WebDriverWait(Driver, waitTimeout).Until(ExpectedConditions.TextToBePresentInElement(popupWebelement, "Too much data"));
            if (tooMuchData) return false;

            var emptyData = new WebDriverWait(Driver, waitTimeout).Until(ExpectedConditions.TextToBePresentInElement(popupWebElement, "Empty data"));
            if (emptyData) return false;
        }

    } while (DateTime.Now > deadline);

    return null;
}

Because the checks for the popup text only differs from the expected text you could think about using a foreach loop over an array containing the expected strings.


Surprising name

default_capacity is in the public .h file

In a header for list_this and list_that, finding default_capacity is not good and a name-space collision headache.  Suggest list_default_capacity instead.

0 allocation

Be careful about allocating 0 memory (possible with default_capacity == 0 and list_create(0, ...)).  Receiving NULL in that case does not certainly indicate an out-of-memory condition.

// list->elements = (void**) malloc(sizeof(void*) * initial_capacity);
// if (!list->elements) return NULL;

list->elements = malloc(sizeof list->elements[0] * initial_capacity);
if (list->elements == NULL && initial_capacity == 0) {
  return NULL;
}

default_capacity not needed

With generic list code, I'd expect the ability to create a 0 length list and not have 0 indicate "use a default value".


Delegating to a lazily loaded object in Ruby

You could pass in a string instead of a proc and use Object.const_get().

class_const = Object.const_get 'String'
=> String
class_const.new "hello"
=> "hello"

With a call-able constructor.

constructor = class_const.public_method :new
=> #<Method: Class#new>
constructor.call "ohai"
=> "ohai"

You need to guard against NameErrors.

Object.const_get('NotThere')
NameError: uninitialized constant NotThere

A lazy load method to build the dependency (Error checking elided for clarity).

def model
  @model ||= build_model('arg1', 'arg2')
end

def build_model(*args)
  Object.const_get(self.configure.model_name).send(:new, *args)
end


What is generally less efficient is iterating over an unordered set. This is because the set is actually a hash table of the keys. So whenever you want to iterate over the key-value pairs, a std::map is generally better.

Also what i apparent is that there is one function to do everything. This makes the code rather hard to follow and oversee. You should rather create one function for every functionality you want to implement and build your algorithm from short but clear functions. In your case there are at least 4 natural subfunctions that occur on the first glance.


ActionGroupContext to know an id of the current context

Your Dispose pattern is somehow flawed.

public void Dispose()
{
    Dispose(true);
    GC.SuppressFinalize(this);
}

protected virtual void Dispose(bool disposing)
{
    if (disposing)
    {
        GuidStore.SetGuid(oldId);
    }
}

You don't check if the object already is disposed, so calling Dispose() over and over will result in each time calling GuidStore.SetGuid(oldId);.

So using a private variable for saving if the object is disposed would be the way to go.

private bool disposed = false;

public void Dispose()
{
    Dispose(true);
    GC.SuppressFinalize(this);
}

protected virtual void Dispose(bool disposing)
{
    if (!disposed && disposing)
    {
        GuidStore.SetGuid(oldId);
        disposed = true;
    }
}

Also for completeness you should also use the finalizer like so

~ActionGroupContext()
{
    Dispose(false);
}

One thing what should never happen is that a call to Dispose() throws an exception. If you are 100% sure this can't happen, you are fine. If you aren't 100% sure, you should enclose the call to SetGuid() inside a try..catch block.

Please read this: proper-use-of-the-idisposable-interface

In your posted code I see neither in the ThreadStore nor in the HttpStore any usage of this ActionGroupContext so I see no reason to reference System.Web to use this context.


I agree with @rolfl that this would be much simpler as a one-line shell pipeline.  The -s option to du makes it produce a total.  awk is a good tool to use for processing multi-column text.

du -s --si | awk '$1 ~ /G/ { exit 1 }'

However, the --si option seems to be a non-portable GNU extension.  A more portable version would look at the number of 512-byte blocks.  The magic number 1953125 is \$\dfrac{10^9}{512}\$.

du -s | awk '$1 < 1953125 { exit 1 }'

The second version also works even if the total is in the terabyte or exabyte range.

There is an inefficiency, though: you should be able to exit early as soon as you find that the total exceeds 1 GB.  For that, you would go back to Perl, but with a proper Perl program instead of a wrapper around du.

use File::Find;
use strict;

my $sum = 0;
my %seen_inodes;
find(sub {
    my ($inode, $blocks) = (stat)[1, 12] or die "${File::Find::name}: $!";

    # Do not double-count hard links
    if (!$seen_inodes{$inode}) {
        $seen_inodes{$inode} = 1;
        $sum += 512 * $blocks;
        exit 0 if $sum >= 1_000_000_000;
    }
}, ".");
exit 1;


IdNumber: a string of fixed length and with character constraints

I will review your code from top to bottom.

private string idnumber;

this should be named using camelCase casing and because you don't change its value you should make it readonly which means you can only assign a value to it inside the constructor or by initialising like e.g private string idnumber = "somevalue";. Because you set this value only inside the implicit operator you should add a private constructor which has a string as argument. This would then look like this

public class IdNumber
{
    private readonly string idNumber;
    private IdNumber(string idNumber)
    {
        this.idNumber = idNumber;
    }

Because the implicit operator is public you should validate the argument value wether it is null. It just looks better to throw an ArgumentNullException than to receive an NullReferenceException.

Instead of using value.All(c => IsDigit(c) || IsLowercaseLetter(c)) you could use a simple Regex to do the validation for you. This will shorten your code because the two methods IsDigit() and IsLowercaseLetter() won't be needed anymore.

The implicit operator would then look like this

public static implicit operator IdNumber(string value)
{
    if (value is null) { throw new ArgumentNullException(nameof(value)); }

    if (Regex.IsMatch(value, "[0-9a-z]{10}"))
    {
        return new IdNumber(value);
    }
    throw new ArgumentException("id numer must have length 10 and must only have digits and lower case-letters");
}

ToString() and GetHashCode() are both fine but in the Equals() method you can either just remove the else like so

public override bool Equals(object obj)
{
    if(obj is IdNumber other)
    {
        return this.idNumber == other.idNumber;
    }

    return false;
}

or combine the if condition with the idNumber comparision like so

public override bool Equals(object obj)
{
    return (obj is IdNumber other)
        && this.idNumber == other.idNumber;
}


Dijkstra algorithm implementation in Swift

The algorithm

Let's first have a look at your implementation of Dijkstra's algorithm in the

func shortestPath(source: Int, destination: Int, graph: Graph) -> Int

function:

The visited property of a node is updated, but nowhere tested. As a consequence, the distance of all neighbors of a node is updated, not only the distance of unvisited neighbors. This does not lead to wrong results (as far as I can see) but causes unnecessary comparisons.
It is unclear to me what this is for:

        if (connectedEdge.to.visited == true) {
            connectedEdge.to.visited = false
        }

The  Dijkstra algorithm does not mark nodes as unvisited, and I cannot see when the condition should be true at all.
The algorithm does not work if start node and destination node are identical. This can be fixed by computing the next current node (and comparing it with the destination) at the beginning of the main loop, not at the end. This also removes the necessity to check if !toVisit.isEmpty twice (as the loop condition and again inside the loop).
The distance of the initial node is set to zero twice.

Here is a possible implementation which fixes the above issues:

func shortestPath(source: Int, destination: Int, graph: Graph) -> Int {

    let startNode = graph.nodes.first{ $0.identifier == source }!
    startNode.distance = 0
    var toVisit = [startNode]

    while (!toVisit.isEmpty) {
        // Select node with smallest distance.
        let currentNode = toVisit.min(by: { (a, b) -> Bool in
            return a.distance < b.distance
        })!

        // Destination reached?
        if currentNode.identifier == destination {
            return currentNode.distance
        }

        // Mark as visited.
        currentNode.visited = true
        toVisit = toVisit.filter { $0.identifier != currentNode.identifier }

        // Update unvisited neighbors.
        for edge in currentNode.edges where !edge.to.visited {
            let neighbor = edge.to
            toVisit.append(neighbor)
            let dist = currentNode.distance + edge.weight
            if (dist < neighbor.distance) {
                neighbor.distance = dist
            }
        }

    }

    // Destination not reachable.
    return -1
}

There is one more issue: The toVisit array (which is build “on the fly” while traversing the graph) can contain duplicate elements. A possible fix is to use a set instead of an array. This would required the Node class to be Hashable – see below.

Code and design improvements

Your function returns -1 if there is no path from the start to the destination node. The Swift way of returning a value or failure is to return an optional, where nil means “no result.”
All properties of class Edge are never mutated after object creation, they should be declared as constants (with let).
The Node initializer needs only the identifier – and that should be a constant property.
It is not possible to compute the shortestPath() function multiple times (with different parameters) because it relies on the visited and distance property to be initialized.
I would replace the function

func setupGraphwith(edges: [[Int]]) -> Graph

by an initalizer of the Graph class, and

func shortestPath(source: Int, destination: Int, graph: Graph) -> Int

by a method of that class:

 class Graph {

    init(edgeList: [[Int]])
    func distance(from: Int, to: Int) -> Int?
}

The usage would then be

let graph = Graph(edgeList: ...)
let distance = graph.distance(from: 1, to: 6)

The optional bindings in setupGraphwith(edges:)

if let fromNode = graph.nodes.first(where: { $0.identifier == edge[0] })
if let toNode = graph.nodes.first(where: { $0.identifier == edge[1] })

cannot fail because those nodes were all created before. Therefore a forced unwrap would be appropriate:

let fromNode = graph.nodes.first(where: { $0.identifier == edge[0] })!
let toNode = graph.nodes.first(where: { $0.identifier == edge[1] })!

An alternative would be to have a “find or create” method in the Graph class.

Performance improvements

At various points, arrays are used to store, locate, and remove nodes. Each lookup requires a traversal of the array. Using sets would be more efficient. That requires the Node class to be Hashable. I would base equality (and consequently, the hash value) on object identity instead of the numerical identifier.

A priority queue would be more efficient to determine the node with the currently minimum distance.

Putting it all together

Summarizing the above suggestions (with the exception of the priority queue) the code code look like this. I have only omitted the CustomStringConvertible conformance for brevity.

class Node {

    let identifier: Int
    var distance = Int.max
    var edges = [Edge]()
    var visited = false

    init(identifier: Int) {
        self.identifier = identifier
    }
}

extension Node: Hashable {
    static func == (lhs: Node, rhs: Node) -> Bool {
        return lhs === rhs
    }

    func hash(into hasher: inout Hasher) {
        hasher.combine(ObjectIdentifier(self).hashValue)
    }
}

class Edge {
    let from: Node
    let to: Node
    let weight: Int

    init(to: Node, from: Node, weight: Int) {
        self.to = to
        self.from = from
        self.weight = weight
    }
}

class Graph {
    var nodes: Set<Node>

    // Find or create node with the given identifier
    func node(identifier: Int) -> Node {
        if let node = nodes.first(where: { $0.identifier == identifier }) {
            return node
        } else {
            let node = Node(identifier: identifier)
            nodes.insert(node)
            return node
        }
    }

    init(edgeList: [[Int]]) {
        nodes = []
        for edgeDescription in edgeList {
            let fromNode = node(identifier: edgeDescription[0])
            let toNode = node(identifier: edgeDescription[1])
            let edge = Edge(to: toNode, from: fromNode, weight: edgeDescription[2])
            fromNode.edges.append(edge)
        }
    }

    func distance(from: Int, to: Int) -> Int? {
        guard let fromNode = nodes.first(where: { $0.identifier == from }) else {
            return nil
        }
        guard let toNode = nodes.first(where: { $0.identifier == to }) else {
            return nil
        }

        if fromNode == toNode { return 0 }

        for node in nodes {
            node.visited = false
            node.distance = Int.max
        }

        fromNode.distance = 0
        var toVisit = Set([fromNode])

        while !toVisit.isEmpty {
            // Select node with smallest distance.
            let currentNode = toVisit.min(by: { (a, b) -> Bool in
                return a.distance < b.distance
            })!

            // Destination reached?
            if currentNode == toNode { return currentNode.distance }

            // Mark as visited.
            currentNode.visited = true
            toVisit.remove(currentNode)

            // Update unvisited neighbors.
            for edge in currentNode.edges where !edge.to.visited {
                let neighbor = edge.to
                toVisit.insert(neighbor)
                let dist = currentNode.distance + edge.weight
                if (dist < neighbor.distance) {
                    neighbor.distance = dist
                }
            }
        }

        return nil
    }
}


The CONSTRAINT word used within a CREATE TABLE or ALTER TABLE tells MySQL engine that this value is not a separate column, but rather it is applied on a column within the table.

The FOREIGN KEY word tells MySQL that whatever is in that field must reference a valid PRIMARY KEY from the other table on INSERT or UPDATE record, otherwise an error is raised.

CONSTRAINT FOREIGN KEY is simply how you phrase it. For more information I suggest reading up about it in the manual.

Now for your criteria:

A patient must have a name: FALSE

That one is not true, unless you added either of those two to your CREATE TABLE PATIENT

NOT NULL to the userID column and a CONSTRAINT FOREIGN KEY (userID) REFERENCES USER(userID)
or, preferably in my opinion:
nameID MEDIUMINT NOT NULL, CONSTRAINT FOREIGN KEY(nameID) REFERENCES NAME(nameID),

A patient can be a user: TRUE
A doctor must have a name: TRUE
A doctor must be a user: TRUE
A patient can be a doctor and vice versa...: TRUE (via userID)
By 3 & 5, if a patient is a doctor that patient must be a user: TRUE


The code is basically fine.
The if condition is perhaps a little complicated though. To interpret it you have to read "if not ((i is not a multiple of 3) and (i is not a multiple of 5))", which is a double negative.
Given the problem statement, we'd expect something more like "if (i is a multiple of 3) or (i is a multiple of 5)", so:
if ((i % 3 == 0) || (i % 5 == 0))

Nitpicking:

If we don't need argc and argv, we can declare main as int main() with no arguments.
The return 0; at the end of main happens automatically in C++, so we don't have to write it ourselves.

Note that there exists an arithmetic solution to the problem, which is much faster (it could even be done at compile-time in C++).

We want to sum all the multiples of 3 or 5 less than 1000. We can think about the sequence of multiples of 3 as (3, 6, 9, 12, 15, ..., 999), which is the same as 3 * (1, 2, 3, 4, 5, ..., 333). [...]
Such a sequence, where the difference between each number is constant, is called a finite arithmetic progression [and the sum is] a finite arithmetic series. The formula for the sum is 1/2 * n * (a_1 + a_n). where n is the number of terms being added, a_1 is the first element in the sequence, and a_n is the last element in the sequence.


Python program to find Armstrong numbers in a certain range

Names

Using sum as a variable name is not adviced as it hides the sum builtin. I'd suggest sum_pow as an alternative.

Also, temp does not convey much information. I'd use remaining even though I am not fully convinced.

Extracting digits from a number

You've used divisions and modulo to compute the different digits for a number. You can use divmod which is a pretty unknown builtin which returns the result for both operations in one go.

That would give:

   remaining = num
   while remaining:
       remaining, digit = divmod(remaining, 10)
       sum_pow += digit ** order

Also, a better alternative would be to avoid doing this ourselves: extracting the different digits is pretty much what str does for us. Also, we already call it anyway, we could make the most out of it and reuse the result.

   num_str = str(num)
   order = len(num_str)
   sum_pow = 0
   for digit in num_str:
       sum_pow += int(digit) ** order

More builtins

Disclaimer: next comment may be a bit overwhelming for a beginner. Don't worry, just take your time and read documentation online if need be.

We've already delegated most of the hard work to Python builtins but we can go further. The summing part could be handled by the sum builtin along with generator expressions.

for num in range(lower, upper + 1):
   num_str = str(num)
   order = len(num_str)
   sum_pow = sum(int(digit) ** order for digit in num_str)
   if num == sum_pow:
       print(num)

Going further

A few other things could be improved from an organisation point of view:

split the code in functions
use the if name == "main" check

Going even further, we could write unit tests for the logic.