Implementing a generic class and choosing a collection based on a type

It seems like you could just mirror the way FetchFromDatabase is implemented. First thing you will need is a something like a DbContext, but for collections. This new class should be capable of returning an IEnumerable<TEntity> for any TEntity defined -- just like DbContext.

public class CollectionContext
{
    private Dictionary<Type, object> _cache;

    public CollectionContext()
    {
        _cache = new Dictionary<Type, object>();
    }

    public void AddCollection<TEntity>(IEnumerable<TEntity> collection)
    {
        _cache.Add(typeof(TEntity), collection);
    }

    public IEnumerable<TEntity> Set<TEntity>()
    {
        return (IEnumerable<TEntity>)_cache[typeof(TEntity)];
    }
}

Now FetchFromCollection can be implemented exactly like FetchFromDatabase, with exception of the type used in the constructor.

public class FetchFromCollection<TEntity> : IFetchData<TEntity>
where TEntity : class
{
    private readonly CollectionContext context;

    public FetchFromCollection(CollectionContext context)
    {
        if (context == null)
            throw new ArgumentNullException("Collection context");
        this.context = context;
    }

    public IEnumerable<TEntity> GetItems()
    {
        return context.Set<TEntity>();
    }
}

This is how you'd use it.

// Load up all your collections
var context = new CollectionContext();
context.AddCollection<Module>(new ModelModules(components).Set());
context.AddCollection<Specialization>(new ModelSpecializations(components).Set());
context.AddCollection<Teacher>(new ModelTeachers(components).Set());

// Example usage
IFetchData<Module> modules = new FetchFromCollection<Module>(context);

I think you can further improve on your design by getting rid of the generic type parameter on FetchFromDatabase and FetchFromCollection. Each of these classes is capable of pulling any TEntity out of their contexts'. By making this change you'd only need to have one instance of FetchFromDatabase and FetchFromCollection for your entire application, instead of one instance of each for every TEntity. You can just move the generic type parameter down to GetItems(). This same change would need to be made to IFetchData. Here is an example for FetchFromCollection, the same change can be made to FetchFromDatabase:

public class FetchFromCollection : IFetchData
   {
    private readonly CollectionContext context;

    public FetchFromCollection(CollectionContext context)
    {
        if (context == null)
            throw new ArgumentNullException("Collection context");
        this.context = context;
    }

    public IEnumerable<TEntity> GetItems<TEntity>()
    {
        return context.Set<TEntity>();
    }
}


This is not a constructive way to protect your scripts from SQL injection — the objective of SQL-injection prevention should not be to disallow characters or words, but to escape characters. What you have now, prevents your users from submitting perfectly valid English words such as select, update, etc. and/or perfectly valid characters such as --, " and '.

Consider this fictional comment:

  When I select "where" from the menu, it updates the procedure -- strange.

This would be rejected by your code.

Now, I'm sure, for your application, this might (currently) be irrelevant, but your code is not very flexible or portable. What happens if your current application, or another future application needs to accept these words? You'd have to rewrite your code, and for a possible new application you wouldn't be able to copy existing code.

More importantly though, your current code is probably not elaborate enough to mitigate all possible attack vectors. You'd really be wise to implement prepared, parameterized  statements by using PDO, instead of trying to prevent your users from entering possible SQL keywords and characters. With prepared, parameterized statements you don't have to worry about escaping the correct characters anymore — PDO (or, if the driver supports it natively, the database driver) will escape the parameter values you supply for you.

Let me give you a short introductory example of how you could implement SQL-injection prevention with PDO:

// create a database connection handle
$driver   = 'odbc';
$database = 'kn_online';
$username = '*redacted*';
$password = '*redacted*';
$dbh = new PDO( "$driver:$database", $username, $password );

// create a parameterized statement to select a record from CURRENTUSER
// uses a named parameter (denoted by :), called accountId
// that will be properly escaped by PDO
$sql = 'SELECT * FROM CURRENTUSER WHERE StrAccountID = :accountId';

// prepare the statement; returns a PDOStatement object
$stmt = $dbh->prepare( $sql );

// execute the statement by passing the parameter values in an associative array
$executionResult = $stmt->execute( array(
    ':accountId' => $acc
) );

// if the execution succeeded
if( $executionResult )
{
    // fetch the record as an associative array
    $record = $stmt->fetch( PDO::FETCH_ASSOC );
}

The beauty of prepared statements is that you can also easily execute them repeatedly, with new parameter values. Consider this example (connection handle creation omitted for brevity):

// insert into some table
$sql = 'INSERT INTO SOMETABLE VALUES( :id, :name )';

$stmt = $dbh->prepare( $sql );

// some fictional data
// parameter value keys don't need : prepended
$data = array(
    array( 'id' => 1, 'name' => 'Name One' ),
    array( 'id' => 2, 'name' => 'Name Two' ),
    array( 'id' => 3, 'name' => 'Name Three' )
);

foreach( $data as $datum )
{
    // using the same prepared statement
    // to execute for each datum
    $stmt->execute( $datum );
}


How to simplify nested conditional for loop in R?

This bit:

for (i in 1:m) {
  if(i == 1 && x == 'site') {
    vars <- c(vars, 'beta.site[1]')
  }
  if (i > 1) {
    vars <- c(vars, paste('beta.', x, '[', i, ']', sep=''))
  }
}

Says handle the first pass differently from all the others.  So I would replace it with this:

if (x == 'site') {
  vars <- c(vars, 'beta.site[1]')
}
for (i in 2:m) {
  vars <- c(vars, paste('beta.', x, '[', i, ']', sep=''))
}


Promise for request/response with timeout

await is only applicable in async functions. The executor function passed to Promise constructor at the code at the question is not defined as async.

The second Promise constructor is not necessary. resolve and reject defined at the single Promise executor can be used.

Include .catch() or function at second parameter of .then() chained to Promise constructor to avoid Uncaught in Promise error and handle potential error within Promise constructor function body.

new Promise((resolve, reject) => {
  try {
    const complete = () => !clearTimeout(time)
      && this.removeListener(listener);
    const listener = ({command}) => command === "pong"
      && !complete() && resolve();
    this.addListener(listener);
    this.sendMessage({ command: "ping" });
    const time = setTimeout(() => !complete() && reject(), timeout);
  } catch (e) {
      throw e
  }
})
// handle resolved `Promise`, handle error
.then(() => {}, e => console.error(e));


Return the prime numbers that are dividers of a some numbers in a list

Here are some suggestions for improving readability of your code. The more readable / easily understandable your code is, the easier it is to properly review regarding performance.

Naming
This is probably the most important point regarding your code. More or less none of the variables have meaningful names. This makes it that much harder to understand your algorithm.
Single letter variable names (r, z, y) are only a good idea when following well-known conventions like iterating over an index (for i in range(...)). The same goes for lst and newList, these names say nothing about content and function of the variables. Without fully understanding your algorithm I would presume some names like divisor, numbers, candidate_primes, results, etc. might be useful.
Variables should be named in snake_case instead of camelCase. PEP 8
for r in r:: Using the same variable name for different variables (in this case: the single elements of an iterable and the iterable itself) is confusing to the reader and might lead to some unexpected behaviour in some cases.

Conditions
Line 5: After checking all(i%x != 0 for x in r), you don't need to additionally check if i not in r. Since i % i == 0, the first condition would already fail if i in r.

Comments & docstrings
You should include comments and docstrings in your code to explain at least the key functionality / algorithmic approach.

You can remove the entire elif case from this for loop:
for num in lst:
    for i in range(2, abs(num)+1):
        if num%i == 0 and i%2 != 0 and all(i%x != 0 for x in r) and i not in r:
            r.append(i)
        elif i == 2 and num%i == 0 and 2 not in r:
            r.append(i)

like this:
for num in lst:
    if num % 2 == 0 and 2 not in r:
        r.append(2)

    for i in range(3, abs(num) + 1):
        if num % i == 0 and i % 2 != 0 and all(i % x != 0 for x in r) and i not in r:
            r.append(i)

This will save you some unnecessary checks for each i in range(3, abs(num) + 1) for each num.


An approach to the network messaging service

In addition to RubberDuck's answer, I'd also propose the following improvements.

I don't really see the need to do this:

if (!handlers.ContainsKey(handler.Command))
    handlers.Add(handler.Command, handler);
else
    handlers[handler.Command] = handler;

You can omit the if/else logic and simply assign the value:

handlers[handler.Command] = handler;

I also would advise to avoid a "negative" check in the if-clause. IMHO this is much easier to understand:

if (handlers.ContainsKey(handler.Command))
    handlers[handler.Command] = handler;
else
    handlers.Add(handler.Command, handler);

But like I said, the whole if/else logic isn't necessary in this case anyway; I'm just using it as an example.

Do not that your code currently doesn't prevent overwrites of existing key/value pairs. You might not want this; if you'd use this (instead of your four line if/else block):

handlers.Add(handler.Command, handler);

... then there'd be an exception if the same command is used more than once as a key.

I also advise against this:

if (handlers.ContainsKey(message.Command))
    handlers[message.Command].ProcessMessage(message);

And instead use TryGetValue to avoid unnecessary lookups:

IMessageHandler handler;
if(handlers.TryGetValue(message.Command, out handler)
{
    handler.ProcessMessage(message);
}


The fastest way to import and edit data in R

1) Firstly you could use fread from data.table to speed up reading of .csv files.

2) It looks like that you do not need the two inner loops, you could do that with vectorization.

If you could provide some example data of df and df_names(using dput) then I could write the necessary code, and test the timings...

Update:

It looks like for smaller files (200 cols and 2000 rows) read_csv2 from readr is faster than data.table's fread:

Unit: milliseconds
                                                               expr      min       lq     mean   median       uq      max neval cld
 read.csv(tempPath, skip = 5, header = FALSE, sep = ";", dec = ",") 475.7547 480.2411 488.7772 484.3644 487.7255 515.8005     5   c
                                      read_csv2(tempPath, skip = 4) 179.2461 181.9832 182.2904 182.3569 182.4955 185.3702     5 a
                               fread(tempPath, skip = 4, dec = ",") 463.4811 468.1232 470.4556 468.3920 469.5664 482.7155     5  b

You should test it yourself and see if there is significant difference.

The end code could look something like this:

files_data <- list.files(path_data, full.names = T)
files_data

files_data <- grep(".csv", files_data, value = T, fixed = T)
length(files_data)

files_data # paths to files

myAproach <- function(i) {
  require(readr)
  tempPath <- files_data[i]
  name <- basename(tempPath)
  name <- gsub('-', '_', substr(name, start = 0,
                                stop = (nchar(name) - 4)),
               fixed = T)
  print(name)

  df <- read_csv2(tempPath, skip = 4)

  dfnames_test_MS7 <- colnames(df)
  dfnames_test_MS7[1] <- "DateTime"
  dfnames_test_MS7 <- gsub('V', 'x', dfnames_test_MS7, fixed = T)
  #fixed for speed
  colnames(df) <- dfnames_test_MS7
  df
}
resDflist <- lapply(1:length(files_data), myAproach)

resDflist is list of data.frames. In my opinion it is easier to work with lists than assign the data.frames to global environment.


LeetCode 1638: Count Substrings That Differ by One Character

It looks nice, and you got the right algorithm.
Still, there are problems and additional ideas:

The const-qualifier on the two functions return-value is ignored. Didn't your compiler warn?

Denoting the start of a string-slice by pointer to start of the whole string and offset into it is cumbersome and inefficient. Just give a pointer to the start of the slice.

You are playing Shlemiel The Painter with all four strlen()-calls in your loops. The compiler might be able to hoist it four you, or it might not.
If it cannot, at least those in countSubstrings() are cheaper by some constant factor than the calls to a fixed getCounts(), and thus don't influence your codes big-oh.
But those in getCounts() turn the function from linear to quadratic, and thus the algorithm from quadratic to cubic.
What I don't get is why you ask for the strings length at all.
Just substitute !s[n] for strlen(s) == n.

Either int is always big enough, and should be used throughout, or it isn't,
and you have to play it safe by using size_t.

By the way, the problem is symmetric in its two arguments. That can be used.

And that was all I found.
static int getCounts(const char* a, const char* b) {
    int prev = 0;
    int curr = 0;
    int r = 0;
    for (; *a && *b; r += prev) {
        ++curr;
        if (*a++ != *b++) {
            prev = curr;
            curr = 0;
        }
    }
    return r;
}

static int manyCounts(const char* a, const char* b) {
    int r = 0;
    while (*a)
        r += getCounts(a++, b);
    return r;
}

int countSubstrings(const char * a, const char * b) {
    return !*a ? 0 : manyCounts(a + 1, b) + manyCounts(b, a);
}


Using Iterator

Rather than building and passing a string around.

std::string fmt_internal(unsigned long long value) const;

Why not use the output iterator directly?

You build a string letter by letter in the order you would output it, then you move that back to the calling function, then you copy the string to a stream (via an iterator). You can bypass the move and the copy by just writing the letters to the iterator.

Output Iterator not passed through:

template <class charT, class OutputIterator = std::ostreambuf_iterator<charT> >
class roman : public std::num_put < char > {
         //        Expecting =>    ^^^^^^  <CharT, OutputIterator>

OR not making it a template class.

class roman : public std::num_put<char> {

Member Types

Your base type defines some member types.

char_type   CharT
iter_type   OutputIt

This is exactly like your class. Usually I would expect you to pull these types from the parent rather than defining them independently ( unless there is a good reason).

So I would have expected:

typedef std::num_put<CharT, OutputIterator>   parent;
typedef parent::char_type  char_type;
typedef parent::iter_type  iter_type;

Return value

std::copy(s.begin(), s.end(), i);
return i;

Should this not be:

i = std::copy(s.begin(), s.end(), i);
return i;

It still seems to work (even when the stream is std::stringstream), but I am a tiny bit surprised. You are supposed to return the value of the iterator after putting stuff on the stream (not the original value). It seems to work anyway because the iterator changes the state of the object that it is putting stuff into.


I don't do JS, even less node.js, but from the looks of it you seem to be taking in a string for your query, which means client code can do something like "select x, y, sum(z) from mytable where x = " + someValue + " group by x, y" - which is prone to SQL-injection: your client code needs to remember that.

If your executeQuery also took parameters, I think it would be clearer that when you need parameters, they should be passed as arguments to that function, not concatenated into the query string.


Is there a way to speed-up the following code?

Yes, there is:

Since i and ii and browse$V4 and browse$V5 are outside of the loop, you can precalculate this before going into the loop. That way you can save a small bit of calculating.

if (sum(browse$V4 == i & browse$V5 == ii) > treshold)

I dunno what you're doing here, but from what I can see, you're calling sum(1) or sum(0). Naturally, this produces 0 or 1. Then you're comparing it to treshold. Well, if treshold is below 1 but not below 0, then you can just remove the check, as well as the for loop, since browse doesn't change in the for loop!

If treshold is below 0, then the check is not needed. Thus, (please check if my syntax is correct)

SESSION_NUMBER<-length(resultTable$V1)

if(treshold < 1 && treshold >= 0){
    //check if browse$V4 and browse$V5 are in range
    if(browse$V4 >= 1 && browse$V4 <= 55 && browse$V5 >= 1 && browse$V5 <= 21){
        actionVec<-NULL
        for(iii in 1:SESSION_NUMBER){
            actionVec[iii]<- sum(browse$V2==resultTable$V1[iii])
        }
        resultTable[,browse$V4+1] <- actionVec
    }
} else if (treshold < 0){
    for(i in 1:55){
        for(ii in 1:21){
            actionVec<-NULL
            temp<-browse$V4 == i & browse$V5 == ii
            for(iii in 1:SESSION_NUMBER){
                actionVec[iii]<- sum(browse$V2==resultTable$V1[iii] & temp)
            }
            resultTable[,i+1] <- actionVec
        }
    }
}


Why don't you format your code nicely?
An IDE can easily reformat it for you,
for example, this is how IntelliJ reformats your code:

public class TestClass {

    public static void main(String[] args) throws Exception {
        Date d = new Date();

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        ArrayList<StringBuffer> al = new ArrayList<StringBuffer>();
        int count = 0;
        int no = Integer.parseInt(br.readLine());
        for (int i = 0; i < no; i++) {

            String line = br.readLine();

            al.add(new StringBuffer(line));
        }
        long ts1 = System.nanoTime();
        int i = 0;
        int j = 0;
        for (i = 0; i < al.size(); i++) {
            StringBuffer str = al.get(i);
            String comp = str.toString();
            for (j = i + 1; j < al.size(); j++) {
                StringBuffer rev = al.get(j);

                String st = (rev.reverse()).toString();

                if (st.equals(comp)) {
                    count++;
                }

            }
        }
        System.out.println(count);

    }

}

An IDE can do far more than this,
for example warns of bad practices,
in this code:

Unused variable: d,
new ArrayList<StringBuffer>(); can be simplified as new ArrayList<>();
Unused variable ts1
Redundant initializer int i = 0 and int j = 0

After eliminating the above, import java.util.Date also becomes unnecessary, and the code is starting to become more compact.

There remain many obvious bad practices:

The loop variables i and j should be declared inside the for statements: if you do that, they cannot be used outside. Which is a good thing, as they were not intended to be used outside.
Variables should be declared as close to where they are used as possible. Similar to the previous point, the idea is to limit mistaken uses, by minimizing the "window of vulnerability". For example, int count should be declared right before the second for loop that performs the counting.
ArrayList<StringBuffer> al can be declared as List<StringBuffer> al, using the interface type List instead of a specific implementation ArrayList
Instead of StringBuffer, it's recommended to use StringBuilder. It has exactly the same interface, so you can safely replace it everywhere in your code.
Avoid throwing (or catching) Exception. Try to use the most specific exception type.
The variable names are poor throughout. The only variable that is well-named is count. All the others could have better names.

Applying the above corrections, the program becomes much better:

public static void main(String[] args) throws IOException {
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    int lineCount = Integer.parseInt(reader.readLine());

    List<StringBuilder> lines = new ArrayList<>();
    for (int i = 0; i < lineCount; i++) {
        String line = reader.readLine();
        lines.add(new StringBuilder(line));
    }

    int palindromePairCount = 0;
    for (int i = 0; i < lines.size(); i++) {
        StringBuilder str = lines.get(i);
        String comp = str.toString();
        for (int j = i + 1; j < lines.size(); j++) {
            StringBuilder rev = lines.get(j);
            String st = (rev.reverse()).toString();
            if (st.equals(comp)) {
                palindromePairCount++;
            }
        }
    }
    System.out.println(palindromePairCount);
}

We're only getting started.
There are much bigger problems with the posted code,
here are some tips to get you started:

Rework the code, replacing the List<StringBuilder> with List<String>
Extract the counting logic to a dedicated method that takes a List<String> and returns an int
Extract the palindrome checking logic to a dedicated method that takes a String and returns a boolean

These are the most obvious improvement ideas.
After you implement them,
more improvement opportunities will likely become apparent.


When I need a simple strategy pattern I'll use a Dictionary. This can drastically reduce code by cutting repetition.

Note the use of StringComparer.InvariantCultureIgnoreCase for comparer to do away with the String.ToLower calls.

private static readonly IDictionary<string, Tuple<string, string>> NamesDictionary =
    new Dictionary<string, Tuple<string, string>>(StringComparer.InvariantCultureIgnoreCase)
    {
        { "kydd", Tuple.Create("question 1", "link1") },
        { "zydd", Tuple.Create("question 2", "link2") },
        ...
    };

private static void DoSomething(string name)
{
    Tuple<string, string> questionAndLinkTuple;

    if (!NamesDictionary.TryGetValue(name, out questionAndLinkTuple))
        return;

    var question = questionAndLinkTuple.Item1;
    var link = questionAndLinkTuple.Item2;

    Question.AskQuestion("Input answer here", question, link);
}


I will answer your question in an unexpected way : the better solution is, as far as I can tell, much more straightforward than what you are doing.

Indeed, you don't need a class : your class has an __init__ and a single method to_rna, it might as well be a single function.

from string import maketrans

def dna_to_rna(dna_string):
    """Return the RNA complement of the DNA strand."""
    return dna_string.translate(maketrans('GCTA', 'CGAU'))

I think see this the neatest solution. Then if on only want to create the table only once for performance reason, you can put it a variable outside the function but it's probably not needed.


I've added a few comments in your source,

#!/usr/bin/env perl

use strict;
use warnings;
use autodie; # automatic die/checks for http://search.cpan.org/~pjf/autodie/lib/autodie.pm#CATEGORIES
use File::Copy;

sub sort_files {
    # my $dir = shift || '.';
    my $dir = shift // '.'; # defined short circuit to allow '0' as argument
    $dir =~ s/\/$//;

    # opendir(DIR, $dir) or die $!;
    opendir(my $DIR, $dir);  # use lexical variable instead of glob
    my @files = grep {
        !/^\./      # not needed if you only want to skip '.' and '..'
        && -f "$dir/$_"
        } readdir $DIR;

    my $len = @files;
    print "sorting $len files\n";

    foreach my $file (@files){
        my ($ext) = $file =~ /([^.]*$)/;

           #
           # what do you want to do when $ext is undefined?
           # my ($ext) = $file =~ /([^.]*$)/ or next; # to skip such files

        my $dest = "$dir/$ext/";
        # if (not -d "dest"){  # typo?
        if (not -d $dest){
            mkdir $dest;       # added autodie to check on mkdir
            print "\tcreated directory $dest\n";
        }
        move("$dir/$file", $dest) or die $!;   # autodie doesn't handle File::Copy
        print "\t$file moved to $dest\n"
    }
}

sort_files(@ARGV); # parentheses around arguments for non core functions are good idea https://eval.in/139428 vs https://eval.in/139430
# exit 0; # not needed


Sum of differences of adjacent elements in an array

General implementation

using namespace std; is considered bad practice and should be avoided.
The C++ style std::cin and std::cout are used for input and output, but the C style fprintf is used for error reporting. Maybe choose one style for consistency (e.g. use std::cerr for errors)?
The whole array arr could as easily be replace by a std::vector<int>, letting the container take care of bookkeeping and memory cleanup.

Algorithm

Your algorithm uses (as you correctly stated) \$O(K^2)\$ time by calculating all possible combinations. This can be reduced to \$O(K)\$ with a bit of cleverness:

As far as I understand it, the problem basically boils down to: f = last - first, maximize f by removing up to m <= K total elements. This means to maximize f, one needs to find how many elements to remove from each "end" of the array, because as you correctly deduced, only those matter.

Now we can step from one end up to K elements in, and for each step calculate the change in f if we were to remove elements up to this point. If it's the best result so far, we note it for the current position, else we note the previous better result (after all, we always can take less elements away). We do this for both ends.

Then we can add the noted values for taking x elements from the front and K-x elements from the back together (so up to K elements total), and find the maximum for this value. This value is the highest increase possible for f.

Adding this value to the previously calculated original value of f gives us then the maximum value for f.

Step by step

Let's take your example: A = [1 7 2 5 3 8 2 3 6 5 5] , K = 4.

Let B = [? ? ? ? ?] be the map x elements removed from the front -> max increase of f so far.

If we were to remove m = 0 elements from the front, f wouldn't change. B = [0 ? ? ? ?].
If we were to remove m = 1 element from the front, f would change by 1 - 7 = -6. This is worse than removing 0 elements, so we store the result for that instead (after all, we can always remove less elements for a better result). B = [0 0 ? ? ?].
If we were to remove m = 2 elements from the front, f would change by 1 - 2 = -1. Since this is again worse than removing nothing (our best result so far), let's store that again, B = [0 0 0 ? ?].
Same results for m = 3 (1 - 5 = -4) and m = 4 (1 - 3 = -2) respectively (so final B = [0 0 0 0 0]).

Let's do this again with C = [? ? ? ? ?], but now we remove elements from the back.

If we were to remove m = 0 elements from the back, nothing changes. C = [0 ? ? ? ?].
If we were to remove m = 1 elements from the back, nothing would change (5 - 5 = 0). C = [0 0 ? ? ?].
If we were to remove m = 2 elements from the back, f would increase by 6 - 5 = 1. This is better than previous results, so we store that. C = [0 0 1 ? ?].
If we were to remove m = 3 elements from the back, f would change by 3 - 5 = -2. This is worse than our best result (1) so far, so let's store that instead. C = [0 0 1 1 ?].
If we were to remove m = 4 elements from the back, f would change by 2 - 5 = -3, so let's again store the best result so far. C = [0 0 1 1 1].

Now we can go over both B and C and look what the best results for removing up to  x elements from the front and K - x (so m <= x + (K - x) = K)  elements from the back.

x = 0: The best result we could get by removing up to 0 elements from the front and K elements from the back is B[0] + C[K] = 0 + 1 = 1.
x = 1: The best result we could get by removing up to 1 elements from the front and K-1 elements from the back is B[1] + C[K-1] = 0 + 1 = 1.
x = 2: B[2] + C[K-2] = 0 + 1 = 1.
x = 3: B[3] + C[K-3] = 0 + 0 = 0.
x = 4: B[4] + C[K-4] = 0 + 0 = 0.

So the best we could get is an increase of f by 1 (by removing 0 elements from the front and 2 elements from the back, though that wasn't asked).

Algorithm code

In code (using arrays for consistency with existing code):

/* other stuff, like reading arr, up to this statement */
max = arr[N-1] - arr[0];

auto frontRemovals = new int[K+1]; // B
auto backRemovals = new int[K+1]; // C
auto maxFront = = frontRemovals[0] = 0;
auto maxBack = baxkRemovals[0] = 0;

for(auto frontIndex = 1, backIndex = N-2; frontIndex <= K; ++frontIndex, --backIndex) {
    if(arr[0] - arr[frontIndex] > maxFront) {
        maxFront = arr[0] - arr[frontIndex];
    }
    frontRemovals[frontIndex] = maxFront;

    if(arr[backIndex] - arr[N-1] > maxBack) {
        maxBack = arr[backIndex] - arr[N-1];
    }
    backRemovals[frontIndex] = maxBack;
}

auto maxDifference = 0;
for(auto x = 0; x <= K; ++x) {
    if(frontRemovals[x] + backRemovals[K - x] > maxDifference) {
        maxDifference = frontRemovals[x] + backRemovals[K - x];
    }
}

max += maxDifference;
/* printing result, freeing array, etc. */

  Note: With a bit more cleverness, this operation can be done in one pass. However, this exercise is up to the reader ;)


Determine fragment identifier from HTML page in Swift

I don't know how stable the precise HTML structure of those pages is, could that change in the future? Using a HTML parsing library might be a more robust approach.

Some remarks concerning the Swift implementation:

Don't force-unwrap optionals. If one of the searched strings is not found, your program will terminate with a runtime error. Use optional binding with if let or guard let instead, and handle the failure case properly.
Instead of converting revisionGUID to lowercase you can do a case-insensitive search.
The first search string can be created with string interpolation instead of concatenation, that makes the expression slightly shorter:

#"onclick="StackExchange.revisions.toggle('\#(revisionGUID)')""#

Use a regular expression with positive look-ahead and look-behind for the second search. That allows to find the precise range of the spacer, without relying on a particular length.
Put the code in a function, and add documentation.

Putting it together, the function could look like this:

/// Find spacer fragment for GUID on revisions page
/// - Parameter html: HTML of a revisions page
/// - Parameter revisionGUID: A revision GUID from the StackExchange API
/// - Returns: The spacer fragment, or `nil` if not found

func findFragment(html: String, revisionGUID: String) -> String? {
    let pattern1 = #"onclick="StackExchange.revisions.toggle('\#(revisionGUID)')""#
    guard let range1 = html.range(of: pattern1, options: .caseInsensitive) else {
            return nil
    }
    let pattern2 = #"(?<=<tr id=")[^"]+(?=")"#
    guard let range2 = html.range(of: pattern2,
                                  options: [.backwards, .regularExpression],
                                  range: html.startIndex..<range1.lowerBound) else {
            return nil
    }

    return(String(html[range2]))
}


Something somewhat confusing is the comparison to of each $footer# to the string '0' then later comparing it to greater than integer 0.  This is practically the definition of weakly typed languages.  If you know what $footer# variables actually contain you might be able to simplify this, but here is a fully functioning replacement to the first code block.

One could simplify this a bit, but the core concepts are there.  '0' casts to False, and True casts to 1.  There are plenty of other ways to accomplish the same thing, especially if you have significantly more incoming $footer#'s, or if they are stored in something iteratable like an array.

//$footer1 = '10';
//$footer2 = '-5';
//$footer3 = '0';

$footer1Bool = (bool) $footer1;
$footer2Bool = (bool) $footer2;
$footer3Bool = (bool) $footer3;

$footer1Int = (int) $footer1Bool;
$footer2Int = (int) $footer2Bool;
$footer3Int = (int) $footer3Bool;

$footerCombined = $footer1Int + $footer2Int + $footer3Int;

if ( $footerCombined >= 3 ) {
    $footerWidth = 'one_third';
} else if ( $footerCombined == 2 ) {
    $footerWidth = 'one_half';
} else {
    $footerWidth = 'full';
}


Answers:

Input iterator is not suitable for your plunge function. The reason
is in std::advance(). It increments the iterators, which
invalidates all previous ones. Bidirectional iterators are ok.
Use std::next() as mentioned in the comment by
user2296177.
No. Only random access iterators are mandated to support the
operation.

Here is the piece of C++ 14 standard that proves answer #1.

Paragraph 24.2.3 of N4296 (Input Iterators). Note from table 107 - Input Iterator requirements (in addition to Iterator).

Expression:

++r;

  pre: r is dereferenceable.
  post: r is dereferenceable or
  r is past-the-end.
  post: any copies of the
  previous value of r are no
  longer required either to be
  dereferenceable or to be in
  the domain of ==.

where r is Input Iterator. Additionally, it is stated that post increment has the same effect. Either pre or post increment should be used to implement std::distance(), so it invalidates all copies of Input Iterators according to the standard.

Comments about the code

template<
    class InputIt,
    class Key = std::less_equal<
        std::iterator_traits<InputIt>::value_type
    >
>

Very arguable gain in readability.

Combo of first and last if preferred when referring to range. value is used to refer to some instance of T. ii and il make things even worse. Don't be lazy to type!

Bad idea to make iterators const. May be you wanted iterator pointing to const?

Nice usage of standard library (though you will need to be sure what it does, which you're trying to do).

The code is not working for input iterators, as mentioned in answers.

Nice one for the first try overall.


A few things I've noticed.

while(temp != Empty) {
  temp match {
    case Empty => println("Empty")
    . . .

That will never print "Empty".

case object Empty extends List {
  var prev : List = Empty
  var next : List = Empty
}

That looks like a reasonable definition of an empty end-point, but the member elements are both mutable variables which means that some code later on could modify the Empty object to have real prev and/or next values.

What you're after is a set of references to prev and next nodes if the node exists, otherwise it should be a meaningless, or "empty", reference. To me that suggests Option[Node].

You say you seek "brevity and functional approach," and there's room for improvement on both fronts, but the basic design, class instances that maintain mutable state, goes against the fundamental FP concept of referential transparency.

What's more, the add() method returns a List instance that can allow code outside of the DoubleLinkedList definition to modify its state and introduce hard-to-find bugs.

val dll = new DoubleLinkedList(3)
dll.print()
dll.add(9)
dll.add(8)
dll.add(7)
dll.add(6).prev = Empty
dll.print()  // dll has been corrupted

Here's an implementation of your basic design that is a bit more concise and needs fewer vars. It still exposes mutable nodes to the outside world, but that seems to be an inescapable aspect of your design.

class DoubleLinkedList[A](maxSize: Int) {
  class Node(val v :A, var prev :Option[Node], var next :Option[Node]) {
    def print() :Unit = {
      Predef.print(s"$v <-> ")
      next.fold(println("End"))(_.print())
    }
  }
  private var head :Node = _
  private var tail :Node = _
  private var currentSize = 0
  def print() :Unit = Option(head).fold(println("Empty"))(_.print())
  def add(i :A) :Option[Node] = {
    head = new Node(i, None, Option(head))
    head.next.fold(tail = head)(_.prev = Some(head))
    if (currentSize < maxSize) {
      currentSize += 1
      None
    } else {
      val retVal = tail
      tail = tail.prev.get
      tail.next = None
      Option(retVal)
    }
  }
}

usage:

val dll = new DoubleLinkedList[Int](3)
dll.print()  // "Empty"
dll.add(9)
dll.add(8)
dll.add(7)
dll.add(6)
dll.print()  // "6 <-> 7 <-> 8 <-> End"


First, note how you're doing a if len(original) > 0 and original.isalpha(): check, then printing "empty" if it fails. This means though that "empty" will be printed out if you input a non-alphabetical word, which is confusing. I'd either handle those two checks separately, or print out a generic error message instead like "Invalid Input".

You have

new_word[1:len(new_word)]

To discard the first letter. There's actually a short-cut for this though:

new_word[1:]

If you omit the second argument to the slice operator, it defaults to the length of the collection. If you omit the first, it defaults to the beginning of the collection. Combined, that's why my_list[:] makes a shallow copy of my_list.

first = word[0]
new_word = word + first + pyg
new_word = new_word[1:]

This chunk breaks off the first letter, does some concatenation, then chops off the first character of the new string. Note though that word will be on the front of new_word, so you can just chop off the first character of word at the same time you do word[0].

If you were using Python 3, you could simply write:

first, *rest_word = word
new_word = ''.join(rest_word) + first + pyg

It's just deconstructing the string, except that instead of the second character being stored in rest_word, everything that's left is stored in it. This essentially just separates the "head" of the string from the "tail".

Unfortunately, I came back a few hours later and realized that my original code that I had posted was wrong. rest_word is a list of strings, not a string itself. This necessitated the ''.join(rest_word) bit. This method isn't quite as efficient in this case, but you may find that it's useful if you don't care what exact type the rest * variable is. If you just want to iterate it, it wouldn't matter.

You overwrite new_word instead of creating a new variable. I would have created a new one to preserve the old new_word. That can be helpful when debugging.

On success, you print out new_word outside of the if. That makes less sense than printing inside of it, and it causes an error to be raised if the if was False since new_word isn't defined.

At the top you have pyg. It's a constant though, and according to Python's style guide, constants should be uppercase, and separated by underscores. I'd also make it more descriptive:

PIG_LATIN_SUFFIX = 'ay'

You stated that the goal was to be short, so I won't go too into this, but you should make use of functions here. You have a couple discreet things going on here:

Handling input from the user
Doing the conversion on the input

And you have both of those things mixed up together.

I'd separate things out properly, and do some basic input checking:

PIG_LATIN_SUFFIX = 'ay'

def convert_to_pig_latin(original_word):
    word = original_word.lower()
    first = word[0]
    rest_word = word[1:]

    return rest_word + first + PIG_LATIN_SUFFIX

def ask_for_input():
    while True:
        word = raw_input('Enter a word:')

        if len(word) > 0 and word.isalpha():
            return word

        else:
            print("Invalid Input. Please try again.")

def main():
    original_word = ask_for_input()
    pig_word = convert_to_pig_latin(original_word)
    print pig_word

ask_for_input will ask until it gets valid input now instead of just ending the program.

Oh ya, and switch to Python 3! Python 2 is about to have support for it discontinued.


Parsing ODataQueryOptions to Expression>

I guess that you're assuming that the MethodCall expression should be a call to Queryable.Where(...) ?

You should check that explicitly via something like :

// yea, that's ugly. But that's for the demo.
//   I'm pretty sure you'll find the proper way to get the method info with your favorite method
static readonly MethodInfo QueryableWhere = ((MethodCallExpression)(
   (Expression<Func<IQueryable<string>>>)
    (() => ((IQueryable<string>)null).Where(x => true)))
   .Body.Unquote())
   .Method.GetGenericMethodDefinition();

and in your code

 if(!mce.Method.IsGeneric || mce.Method.GetGenericMethodDefinition() != QueryableWhere)
     throw an exception;

Unary expressions are not necessarily quotes! (a negation is an unary, for instance). Thus, you want to check mce.Arguments[1].NodeType instead of checking its type.

Moreover, quote un-quoting is quite common, so it can be useful to replace.

var quote = mce.Arguments[1] as UnaryExpression;
if(quote != null)
{
    return quote.Operand as Expression<Func<TEntity, bool>>;
}

by

return mce.Arguments[1].Unquote();

with

public static Expression Unquote(this Expression quote)
{
    if(quote.NodeType == ExpressionType.Quote)
        return ((UnaryExpression)quote).Operand.Unquote();
    return quote;
}

Returning a lambda is OK in my opinion. No problem with that IF AND ONLY IF there is no chance that the enclosed predicate does not contains any reference to an outer parameter (or variable), which is the case here, so it's okay.


Your comments describe what the code is doing, not why the code's doing what it is. And so are generally unhelpful.
Please don't use profanity in comments, or anywhere. It makes you look unprofessional, and is not really that helpful.
To hell with sys.setrecursionlimit. It just delays the inevitable, rather than fixes your problem.
Rather than using global variables, you could instead use a closure.
Your recursion should be in a separate function. That only gets user input. But it'd be better if it were a while loop.

For example you could use:

def get_user_input(fn, prompt='', exception_message=''):
    while True:
        try:
            return fn(input(prompt))
        except ValueError:
            print(exception_message)

Don't repeat yourself. You write get_user_input out twice. In different ways.
The while loop for your higher or lower game seems pretty good. Nice job on that.

And so ignoring your error part I'd use:

import random

def get_user_input(fn, prompt='', exception_message=''):
    while True:
        try:
            return fn(input(prompt))
        except ValueError:
            print(exception_message)

def main():
    limit = get_user_input(int, prompt='Input the Maximum number: \t',
                           exception_message='Input whole numbers only.')

    print('I am thinking of a whole number between 1 and {limit} (both inclusive).'.format(limit=limit))
    number = random.randint(1, limit)
    count = 0
    while True:
        print("Guess the number.")
        guess = get_user_input(int, exception_message='Input whole numbers only.')
        count += 1
        if guess == number:
            break

        if guess > number:
            print('Too high!\nTry a little lower.')
        else guess < number:
            print('Too low!\nTry a little higher.')

    print('Congratulations!!!\nYou guessed the number after {count} tries.'.format(count=count))

if __name__ == '__main__':
    main()

If errors is super important to you, you could return the amount of errors from get_user_input and add it to a local errors variable.
Say:

errors = 0
while True:
    limit, input_errors = get_user_input(...)
    errors += input_errors


Neatest way to filter an array of strings by another array in ruby

How about this?

valid_files = Dir.entries(path).select do |f|
  allowed_types.any? {|suffix| f.end_with? suffix}
end


A triply nested loops always look scary. Especially with while (true).
First thing first, trust yourself. The leaf node (and the ptr_a contains only leafs) has only one neighbour. The
for (const auto& node : graph[leaf].neighbors)

loop is effectively
auto& node = graph[leaf].neighbors.begin();

Second, no naked loops please. And more functions please. The
for (const auto& leaf : *ptr_a)

prunes leaves from the tree. Factor it out into a prune_leaves function, which would return a set (technically a vector) of the new leaves:
leaves = prune_leaves(leaves, graph);

Third, the outer loop shall naturally terminate when less than 3 leaves remain.
Finally, separate IO from the business logic. That said, a code along the lines of
    graph = build_graph();
    leaves = collect_leaves(graph);
    while (leaves.size() < 3) {
        leaves = prune_leaves(leaves, graph);
    }
    return leaves;

would win my endorsement. Notice how ptr_a and ptr_b - which are not the most descriptive names - disappear.


Build an entity, based on a defined model by comparing table column to entity names and building

You can cache the properties to improve performance. No need to retrieve them repeatedly within the body of that for loop.

Also, simplify the LINQ expression to gather all the matching properties, and then iterate over the result set in one fell swoop.

protected IEnumerable<GroupTitle> BuildProductGroup()
{
    var productGroups = new List<GroupTitle>();
    using (var connection = new SqlConnection(_dbConnection))
    using (var command = new SqlCommand(_getProductGroups, connection))
    {
        connection.Open();
        command.CommandType = CommandType.StoredProcedure;
        using (var reader = command.ExecuteReader())
        {
            while(reader.Read())
            {
                var productGroup = new GroupTitle();
                BuildEntity<GroupTitle>(reader, ref productGroup);
                productGroups.Add(productGroup);
            }
        }
    }

    return productGroups;
}

protected TEntity BuildEntity<TEntity>(IDataReader reader, TEntity model)
{
    var type = model.GetType();
    var table = Enumerable.Range(0, reader.FieldCount).Select(reader.GetName).ToArray();

    var properties = type.GetProperties();
    var matchedColumns = properties.Where(property => string.Compare(property.Name,
                                                                     column,
                                                                     true) == 0
                                                      && !reader.IsDBNull(reader.GetOrdinal(matchColumnToProperty.Name)));

    foreach (var property in matchedColumns)
    {
        var value = reader.GetValue(reader.GetOrdinal(matchColumnToProperty.Name));
        matchColumnToProperty.SetValue(model, value, null);
    }

    return model;
}


Feedback

I know it has been nearly 3 years since this was posted and you likely have learned more about javascript and jQuery since then. Perhaps the information below is old news but nevertheless...

I like the styles and the sound that plays when the timer is done is fun! I did notice that if I decrease the Session Length to 0 and click the start button, it shows -01:59 and then appears to jump up to 05:58. Perhaps it would be wise to not allow the user to click the start button if the value for session length is 0.

Recommendations

I only see a couple things I would change:

It is recommended that DOM elements be stored in a variable - e.g.

var breakElement = $('#break');

And then later on use breakElement instead of $('#break') - e.g.

breakElement.html(setBreakMinutes);

The switch statement at the end seems a bit heavy - why not just use an if/else:

switch (runState) {
        case false:
            $('#status').html('reset');
            countDown();
            runState = true;
            break;
        case true:
            $('#status').html('start');
            stopCountDown();
            runState = false;
            break;
    }

While it is only few lines shorter, there is no need to remember the break statements:

if (runState) {
    $('#status').html('start');
    stopCountDown();
    runState = false;
}
else {
    $('#status').html('reset');
    countDown();
    runState = true;
}


City and District class examples for teaching OOP in PHP

Here are some questions I'm asking myself related to your chosen design:

Why not return type on the id() functions – You have return types on most of the other functions, but why not on either of the id functions?
Why the getArray()? – This seems like something used by functions like var_dump(), but then it would be better to implement __debug_info, which var_dump() could take usage of directly.
Possibly rename the private variables – I'm not sure if php has naming standards, but in my view having both a private variable name and a function name() seems kind of redundant, and possibly unfortunate. I would possibly rename the variable into _name or similar.

Unfortunate connection between District and City

In a City you might add Districts, and each district has links to the id of the cities, making a complete circle. This could be unfortunate, and possibly dangerous. Still you don't have a circular reference as you store only the city id, and not a complete reference to the City object.

But I fail to see the good usage of these classes, as they seem to miss any useful methods. Like you can't look up a district and find the corresponding city. Neither can you do anything besides creating or deleting the cities and districts. A good object design would make the object have all needed variables and methods for handling related functions.

Lastly regarding the addDistrict() function, I think I would find it natural to allow the City class to fully create districts. That is to have function addDistrict($id, $name) within City class, and then let it create the District object.


React App with external route table and cookie-based routing

In general, your code does a good job at naming variables/functions, and at splitting logic up in ways that make sense.
However, there are a few places where you are inconsistent with your code style - maybe using a linter would help out:

In some files you indent with 2 spaces. Other files are indented with 4.
There's a number of import statements that have an extra space between the words. e.g. import  ParseRoutes from "./Utils/ParseRoutes"

A note on casing: Generally, we use TitleCase for classes and components only. camelCase is used for almost everything else. A file (or folder with an index.js) with a default export of a class or component may use TitleCase too. However, folders like "Util" or "Components" should probably all be in lowercase. Your "getCookieValue()" function is properly cased, but in the same file, your "RedirectIfRequested()" function is not - RedirectIfRequested is not a class or component. (there's a couple other examples like that).
The local variables in getCookieValue() could probably be named better then "a" and "b". Maybe rename "a" to "cookieKey" and "b" to "match".
.pop() is not a common way to get a group from a regex. If you want to get the second group, just say that with code: match[2]. Note that since you don't actually care about the value of the first group in your regex, you can use a non-capturing group instead (the syntax is (?:...)). For example, if your regex is a(b|B)c(d|D)e, then b/B is group 1 and d/D is group 2, but if its a(?:b|B)c(d|D)e, then you can't get b/B, and d/D is group 1. You don't have to use non-capture groups, but I just want to make sure you know that that's an option.

Finally, and most importantly, all of this routing logic you made is actually not needed. The proper way to configure a server to handle single-page-application (SPA) routing is as follows:
Lets assume your SPA exits at example.com/my-app, and your app has routes such as example.com/my-app/ (the home page) and example.com/my-app/widget/2. You need to configure your server to return the same react bundle no matter which route they hit, as long as its within example.com/my-app. So, going to example.com/my-app/does-not-exist will give you the same javascript bundle as going to example.com/my-app/widget/2. (Note that this is not the same as a redirection). Finally, javascript can check which URL you used (was it /my-app/does-not-exist/ or /my-app/widget/2) and route based on that information - something that react-router will do for you. If the route doesn't exist, just show a 404 page from your React app.


Saving model's data in the model vs an external data manager class

In my opinion the first example you've given is the best. It seems to adhere more to the single responsibility principle. What this basically means is that your classes should only one responsibility.

Note: You're actually still breaking the principle, because I think activeJDBC requires objects to save themselves? (I'm not experienced with activeJDBC, but after looking around a little it seems that this is the way it's done). For example Person.saveit() isn't really a great solution in my opinion, but we'll ignore that.

The reason why I would prefer the first example is because it makes a lot more sense to use something called a DataManager for insertions, than a Person class.

If you look the the second example Person.insertPerson() just really doesn't make much sense. Does a Person really insert a person? In my opinion you should stick as close to reality as possible (of course there are exceptions), and letting a person insert a person doesn't really reflect reality. Person.sit() or Person.eat() is something I would expect to find in a Person class.

A DataManager (what's in a name) indicates that it manages data. And at first thought I could assume/think that this would be used for inserting/receiving/updating objects (if I hadn't inspected the code). Saying DataManager.insertPerson() seems like the more logical solution for me (even though it still has to actually use Person.saveit() for it to actually insert/save the object).

TL;DR I guess you're question could be put as "Should I save a model's data in the model or in an external data manager class?". My answer to this would be use the external data manager class (DataManager). Just because it makes more sense to have a data manager have an insertPerson() method, than an actual model have that method.


1-line conditional statement needs to be trimmed down

You could combine all the tests into one regular expression, but I don't recommend it.  The following is equivalent to what you wrote:

do_stuff if @string =~ /(?'i'<ingr?>).*(?'a'<prod:alchemy?>)|\g<a>.*\g<i>|<key?>/i

Your regular expressions are a bit odd, so I suspect that what you wrote is not what you meant to write.

The non-capturing grouping parentheses (?:…) don't seem to serve any purpose, so you can get rid of them.

The other question marks make the preceding letter optional.  For example, /<key?>/i matches <key> or <Key> or <ke> but not <ken>.

The tricky obstacle to merging the regular expressions is that the <ingr?> and <prod:alchemy?> tests both have to pass, and they can occur in either order.  Therefore, you have to allow <ingr?>.*<prod:alchemy?> as well as <prod:alchemy?>.*<ingr?>  That's possible with

<ingr?>.*<prod:alchemy?>|<prod:alchemy?>.*<ingr?>

Of course, repeating yourself is bad for verbosity and maintainability.  You can lessen the pain slightly by using named groups and subexpression calls.

After having done all that, though, the one long regex is more difficult to understand than your original code.  Therefore, I recommend leaving it alone.

If you're dissatisfied with the original code, though, there may be other improvements that you could make, but you haven't provided any context for your question so I can't make alternative suggestions.


Writing filter with one or more comparison values

If I'm understanding your question right, you want to write a function that will take a call like this:

(matching-entries entries :ssn "xyz-ab-caba" :health-desc "HEALTHCO")

and it will return a seq of entries with matching data for the given keys:

("666/0010|RET|xyz-ab-caba|SMITH|JOHN|HEALTHCO|377.94|20140702|201407| 2014-07-01")

(in this case, only one match was returned)

The most idiomatic syntax I can think of for a function like this would be something like this:

; notes:
;
; 1) rows has to be the first argument, as everything after '&' is assumed to be
;    a key-value combination
;
; 2) This is assuming that each row is represented as a map, so that you can easily
;    grab the value for a given comparison key. If your rows are simply strings,
;    then you'll need to convert them to maps first, perhaps by writing a helper
;    function that splits the string on `|` and zips your comparison keys with the
;    data in each cell., e.g. (zipmap [:foo :bar :ssn ...]
;                                     (clojure.string/split #"|" row))

(defn matching-entries [entries & queries]
  (letfn [(match? [entry]
            (every? (fn [[k v]] (= v (k entry)))
                    (partition 2 queries)))]
    (filter match? entries)))

(partition 2 queries) takes arguments like :ssn "xyz-ab-caba" :fname "JOHN" and turns it into a list of key-value "queries", i.e. '((:ssn "xyz-ab-caba") (:fname "JOHN")). Then every? checks to make sure that each one of these queries is satisfied by a given entry. Finally, we use filter to find all the entries that have the desired values for the given keys.


Encryption and decryption using alphabetic shifts

Part 1, Caesar cipher

Instead of printing one character at a time (inefficient), create a string using the str.join method.

''.join(chr(ord(char) + 5) for char in text)

The variable name i is associated with integer indexes and is misleading to use for a character.

Separate the encryption/decryption into a function

Rather than forcing printing text to screen, a function returning a string can be used in any other context as well. It also lets us use the similarity between encryption and decryption to reduce repetition in the code.

def caesar_shift(text, places=5):
    text = text.lower().replace(' ', '')
    return ''.join(chr(ord(char) + places) for char in text)

The number of places to shift is a parameter instead of hardcoded, with a default of 5 to work the same as your example when the argument is omitted. A value of -5 then decrypts the resulting string.

Handle out-of-range characters

The technique appears to be meant to only work on (English) letters. To avoid unintended results on different inputs, one option is to leave other characters unmodified.

Also, "wrap around" instead of substituting for characters outside of the alphabet, by using the modulus operator %.

from string import ascii_lowercase

def caesar_shift(text, places=5):
    def substitute(char):
        if char in ascii_lowercase:
            char_num = ord(char) - 97
            char = chr((char_num + places) % 26 + 97)
        return char
    text = text.lower().replace(' ', '')
    return ''.join(substitute(char) for char in text)

With the character substitution logic now being too long to fit comfortably in one line, I chose to separate it into a nested function.

Part 2, Vigenère cipher

Loop variables

Your loop here is somewhat confusing, in that the actual loop variable i goes unused while an additional variable j is used as the index. It could be written as follows to avoid that particular issue (using min in case the lengths are different).

for i in range(min(len(text), len(key))):
    print(chr(ord(text[i]) + ord(key[i]) - 96))

An even better, more idiomatic way to loop over multiple sequences (strings, lists etc.) is with the built-in zip function, which creates a tuple of elements for every loop iteration.

for text_char, key_char in zip(text, key):
    print(chr(ord(text_char) + ord(key_char) - 96))

Write as a function

Let's also apply the advice from the previous part and write it as a function.

def vigenere(text, key):
    return ''.join(caesar_shift(tc, ord(kc)-96) for tc, kc in zip(text, key))

Notice how it can be implemented using the caesar_shift function from above.

Handle different text and key lengths

What if the text to be encrypted or decrypted and the key are of different lengths? The convention is to repeat the key phrase.

While it wouldn't be too hard to write code for this from the beginning, it's often a good idea to look for something useful in the standard library. In this case, the itertools.cycle function turns out to be convenient.

from itertools import cycle

def vigenere(text, key):
    key = cycle(key)
    return ''.join(caesar_shift(tc, ord(kc)-96) for tc, kc in zip(text, key))

I've left out the input and output parts from this answer.


Before I go into another possible solution I will give you some suggestions on your current code:

Use val instead of var whenever possible. This is possible for all variables in your code.

No need to specify <Int> on setOf, Kotlin can figure out the best applicable type itself.

The function twoInThree is capable of handling any kinds of sets, not just ints. You can use a generic type parameter for this.
Change the method to fun <T> twoInThree(a: Set<T>, b: Set<T>, c: Set<T>): MutableSet<T>
And naturally also val results = mutableSetOf<T>()

Prefer to return immutable types unless you really need to do otherwise, in this case prefer to return a Set over MutableSet (callers don't need to care about the fact that you are using a MutableSet in your implementation)

The approach
Your approach involves checking for multiple intersections and then creating a union of all sets and removing the intersection of all sets.
The assignment is about finding elements which exists in exactly two of the three given sets a, b, c.
Your approach is fine, there's nothing wrong with it, but... Will it scale?
If you would check for elements which exists in all three of the sets, or in exactly one set, that could be done quite easily by returning different intersections and unions and so on. But what if there would be five sets?
The assignment is about exactly two of the three sets.
One, two, three.
We can use counting!
By counting the number of times each element appears, we can iterate over all sets (no matter if it's three, five, or twenty) exactly once.
By counting the number of times each element appears, we can easily change the code to return elements that occur only once, twice, or three times.
So how to do this?

My approach
Start with creating a list of all sets. listOf(a, b, c)
Then go through the list and map each set to all its elements. .flatMap { it } which can also be written as .flatten()
Then create a grouping of the elements .groupingBy { it }
Then create a map with the counts of each element .eachCount()
listOf(a, b, c).flatten().groupingBy { it }.eachCount()

This gives you a map Map<Int, Int> where the keys are the elements and the values are the number of times each element occurs.
Now you can filter this map and return the keys which matches your requirement .filter {  it.value == 2 }.map { it.key }
Full code:
val result = listOf(a, b, c).flatten()
     .groupingBy { it }
     .eachCount()
     .filter { it.value == 2 }
     .map { it.key }


Just to have a more readable (than the answer by @Justin) and complete (than the answer by @Sedsarq) version of the algorithm presented in the other answers, here is a version that keeps the factors in a set and uses the fact that factors always come in pairs:

from math import sqrt

def get_factors(n):
    """Returns a sorted list of all unique factors of `n`."""
    factors = set()
    for i in range(1, int(sqrt(n)) + 1):
        if n % i == 0:
            factors.update([i, n // i])
    return sorted(factors)

Compared to your code this has the added advantage that it is encapsulated in a function, so you can call it repeatedly and give it a clear name and docstring describing what the function does.

It also follows Python's official style-guide, PEP8, which programmers are encouraged to follow.

With regards to which code is fastest, I'll let this graph speak for itself:

For the op function I used this code which has your checking of all factors up to x:

def op(x):
    factors = []
    for i in range(1,x+1):
        if x%i==0:
            factors.append(i)
    return factors

And the factors function is from the answer by @Justin.

If all you really want is the number of factors, the best way is probably to use the prime factor decomposition. For this you can use a list of primes together with the algorithm in the answer by @Josay:

from math import sqrt
from functools import reduce
from operators import mul

def prime_sieve(limit):
    prime = [True] * limit
    prime[0] = prime[1] = False

    for i, is_prime in enumerate(prime):
        if is_prime:
            yield i
            for n in range(i * i, limit, i):
                prime[n] = False

def prime_factors(n):
    primes = prime_sieve(int(sqrt(n) + 1))
    for p in primes:
        c = 0
        while n % p == 0:
            n //= p
            c += 1
        if c > 0:
            yield p, c
    if n > 1:
        yield n, 1

def prod(x):
    return reduce(mul, x)

def number_of_factors(n)
    return prod(c + 1 for _, c in prime_factors(n))

Comparing this with just taking the len of the output of the get_factors function and this function which implements your algorithm as op_count:

def len_get_factors(n):
    return len(get_factors(n))

def op_count(n):
    c = 0
    for i in range(1, n + 1):
        if n % i == 0:
            c = c + 1
    return c

The following timings result (note the increased range compared to the previous plot):


Nitpicks

Why is this indented?

  ALTER PROCEDURE [dbo].[Product_GetID]

This indentation is inconsistent:

UPDATE Product SET CategoryID = @CategoryID,
Description = @Description,
FullDescription = @FullDescription,
Price = @Price,
MarkupPer = @MarkupPer,
 LabourHours = @LabourHours,
LabourRate = @LabourRate,
 Stock = @Stock
 WHERE ProductID = @ProductID
END

The comments are just noise, it's pretty obvious from the way the code reads to figure out what it does. Especially comments like this:

/* Update Record */
UPDATE Product SET CategoryID = @CategoryID,

Vertical white space would make your code easier to read. For example:

ALTER PROCEDURE [dbo].[Product_SaveRecord]
@ProductID as int, @CategoryID as tinyint, @Description as varchar(80),       @FullDescription as         varchar(240), @Price as decimal(8, 2), @MarkupPer as   decimal(8, 2), @LabourHours as decimal(8, 2), @LabourRate as decimal(8, 2), @Stock as integer

Compare to:

ALTER PROCEDURE [dbo].[Product_SaveRecord]
    @ProductID as int,
    @CategoryID as tinyint,
    @Description as varchar(80),
    @FullDescription as varchar(240),
    @Price as decimal(8, 2),
    @MarkupPer as   decimal(8, 2),
    @LabourHours as decimal(8, 2),
    @LabourRate as decimal(8, 2),
    @Stock as integer;

Also, consistency would be good in how you capitalize keywords. Either do all caps, or all lower caps; it's less confusing that way.

End your SQL statements

Not using the delimiter ; throughout your query makes it more difficult to understand the logic of your code. Use ; and even GO if need be. MS SQL Server is forgiving on syntax errors (try PostgreSQL for fun), that doesn't mean you shouldn't follow good practices of ending statements properly.

Your question

You're trying to insert a row and then use the ID of the row you inserted. There is an easier way to do this using @@IDENTITY in Transact-SQL.

Here would be a simpler way to do this your way, with above advice applied:

ALTER PROCEDURE [dbo].[Product_GetID]
    @ProductID AS INT,
    @CategoryID AS TINYINT,
    @Description AS VARCHAR(80),
    @FullDescription AS VARCHAR(240),
    @Price AS DECIMAL(8, 2),
    @MarkupPer AS DECIMAL(8, 2),
    @LabourHours AS DECIMAL(8, 2),
    @LabourRate AS DECIMAL(8, 2),
    @Stock AS INTEGER
AS
BEGIN
INSERT INTO Product (CategoryID, Description, Price)
VALUES (0, '', 0);
UPDATE Product
SET CategoryID = @CategoryID,
Description = @Description,
FullDescription = @FullDescription,
Price = @Price,
MarkupPer = @MarkupPer,
LabourHours = @LabourHours,
LabourRate = @LabourRate,
Stock = @Stock
WHERE ProductID = @@IDENTITY;
END

BUT...

Why do you not simply insert your parameters within one single INSERT transaction?

ALTER PROCEDURE [dbo].[Product_GetID]
    @ProductID AS INT,
    @CategoryID AS TINYINT,
    @Description AS VARCHAR(80),
    @FullDescription AS VARCHAR(240),
    @Price AS DECIMAL(8, 2),
    @MarkupPer AS DECIMAL(8, 2),
    @LabourHours AS DECIMAL(8, 2),
    @LabourRate AS DECIMAL(8, 2),
    @Stock AS INTEGER
AS
BEGIN
INSERT INTO Product(
    CategoryID,
    Description,
    FullDescription,
    Price,
    MarkupPer,
    LabourHours,
    LabourRate,
    Stock
) VALUES (
    @CategoryID,
    @Description,
    @FullDescription,
    @Price,
    @MarkupPer,
    @LabourHours,
    @LabourRate,
    @Stock
);
END


My feedback:

Separation of concerns

You have three main concerns on your program:

Retrieving the input data (the text)
Splitting the text into 100 character tweets
Outputting the data to twitter

Here, you can have three functions, one per concern. Once you separate those concerns, your final code will become more flexible. You'll be able to (for example) take data from a different place than a file (e.g. a text field on GUI), output to some place different than twitter (e.g. you may want to output to the console for debugging), test different splitting algorithms (e.g. you may try an algorithm that tries not to break any words).

def readFile(filename):
    """Returns a string with the file text"""

def splitText(text, size):
    """Splits text into chunks of length size"""

def tweetEverything(texts):
    """Tweet each text in texts, adding the index of text in texts"""

Descriptive variable names

abc can become splitted_text, val can become excerpt, n can become split_size.

Cleaner ways of doing the same

(val+' ['+str(i+1)+'/'+str(len(abc))+']'

can be done using the string method format

'{} [{}/{}]'.format(val, i+1, len(abc))

Note how by doing it this way you avoid casting to str, and you clearly put the output format on the left side and the variables you render using that format on the right side.

list(filter(bool, abc))

in this case, that is the same as:

filter(None, abc)

because the default filtering behaviour is filter out false values. Another option is to use a list comprehension:

[excerpt for excerpt in abc if excerpt]

Reference


"Does an array contain the same elements as another array?"

if (list1[i] == list2[0]) {
            for (int j = 1; j < list2.length; j++) {
                if (list1[i + j] == list2[j]) {

We can drop this from three lines to one.

        for (int j = 0; j < list2.length && list1[i + j] == list2[j]; j++) {

A side benefit is that this handles the case where list2 is empty (zero length).  The original code would crash in that case.

At the expense of an extra comparison (which could be compiled out), we get rid of two levels of indent and

                } else {
                    break;

Because this will leave the loop automatically.  It won't be necessary to break out manually.

It might be better to replace

        if (list1[i] == list2[0]) {
            for (int j = 1; j < list2.length; j++) {
                if (list1[i + j] == list2[j]) {
                    if (j == (list2.length - 1)) {
                        return true;
                    }
                } else {
                    break;
                }
            }
        }

with

        int j = 0;
        while (j < list2.length && list1[i + j] == list2[j]) {
            j++;
        }

        if (j == list2.length) {
            return true;
        }

Moving the scope of j outside the inner loop allows us to move the test out of the loop as well.  So rather than testing on every iteration, we can test just once.

Alternately

        for (int j = 0; list1[i + j] == list2[j]; j++) {
            if (j + 1 >= list2.length) {
                return true;
            }
        }

Does the same thing as the original code.  It may not be obvious, but this does the same thing with fewer comparisons.

But we're back to throwing an exception if list2 is zero length.  This does exactly the same thing as the original code with fewer comparisons and less code.


JavaScript function for finding perfect numbers

If you check the wikipedia article you linked, you'll see the following:

  It was not until the 18th century that Leonhard Euler proved that the formula \$2^{p−1}(2^p − 1)\$ will yield all the even perfect numbers. Thus, there is a one-to-one correspondence between even perfect numbers and Mersenne primes; each Mersenne prime generates one even perfect number, and vice versa. This result is often referred to as the Euclid–Euler theorem.

A Mersenne prime is a prime that's constructed from \$2^p−1\$, where \$p\$ is prime. Not all values of \$p\$ produce a Mersenne prime, but it makes for much simpler code for finding perfect numbers:

For a prime \$p\$
Calculate \$m = 2^p-1\$
If \$m\$ is prime, it's a Mersenne prime
And thus \$2^{p-1}m\$ is a perfect number

So you'll want code to generate prime numbers, and code to check whether a number is prime.

There are a bunch of ways to generate primes (like this for starters) but for illustration let's use the simplest way: Loop through numbers, and check if they're prime. That's also the same feature we'll need later to check for Mersenne primes anyway.

const isPrime = (n) => {
  const limit = Math.sqrt(n);
  for(var i = 2 ; i <= limit ; i++) {
    if(n % i === 0) return false;
  }
  return true;
}

I.e. if a number is divisible by anything between 2 and its own square root, it's not prime.

Now, let's use that to generate, say, 10 primes:

const primes = [];
var i = 2;
while(primes.length < 10) {
  if(isPrime(i)) primes.push(i);
  i++;
}

So now we have 10 primes. Again, this is a very naïve way to do things, but it works for illustrative purposes.

So now, we can loop through those primes, and use them to construct Mersenne primes (sometimes), and from there, perfect numbers:

primes.forEach(p => {
  const m = Math.pow(2, p) - 1; // calculate 2^p - 1

  if(!isPrime(m)) {
    return; // go to next prime if m isn't a (Mersenne) prime
  }

  // calculate and print the perfect number
  const perfectNumber = Math.pow(2, p - 1) * m;
  console.log(perfectNumber);
});

Another way to write (and get an array back) might be:

const perfectNumbers = primes
  .map(p => { return {p: p, m: Math.pow(2, p) -1} })
  .filter(pair => isPrime(pair.m))
  .map(pair => pair.m * Math.pow(2, pair.p - 1));

Point is, from the first 10 primes you get the first 7 perfect numbers:

6
28
496
8128
33550336
8589869056
137438691328

in a few milliseconds.

So that's cool. But don't overdo it; this is not a simple problem. Wikipedia notes that only 49 Mersenne primes are known to date (the largest has 44,677,235 digits!) and thus only 49 perfect numbers. And in JavaScript, things will go wrong long before that: Since all JS numbers are 64-bit floats they simply can't hold large enough values.

The largest integer that a JS number can hold without introducing floating point errors is Number.MAX_SAFE_INTEGER, which is 9,007,199,254,740,991. Pretty big, sure, but only big enough for the first 7 perfect numbers listed above. The 8th should be 2,305,843,008,139,952,128 but the closest JS can do is 2,305,843,008,139,952,000. Oh well.

You might try looking just for the many-orders-of-magnitude-smaller Mersenne primes, and skip the actual calculation of the corresponding perfect number. If you have a Mersenne, you have a perfect number, after all. Unfortunately though, the 8th Mersenne prime is already \$2^{61} - 1\$ and thus too big to store. So in regular JS, you'll have to be happy with the first 7 Mersenne primes/perfect numbers.


Using PHP's password_hash and password_verify for a login function

Would this be the correct usage of password_hash and password_verify to log the user into the site

Yes. You didn't post your password_hash code, but you are using password_verify correctly, so if your code is working, everything is correct.

  Is there anything I could do to make this function more secure?

Not really. You are using prepared statements as you should, and you are using the currently recommended hashing approach.

Misc

Your in-function comments are just repeating your code, which is not ideal. Readers of your code will notice this and start ignoring all your comments, even important ones.
I do understand the desire to structure your code via these kinds of comments, but it would be better to either just remove them, or to introduce additional functions, and to slightly change your method signature. You could for example add a function such as getUserPassword($connection, $username) (possibly in a User class, or possibly just a method getByUsername($connection, $username) in a user class, which returns a User object, on which you could call getPassword). That way, you don't need the comment, as the code is even clearer about what it does.
I would pass the username to your function, not some data array, from which only the username is needed.
If possible, functions shouldn't have side effects as it makes them harder to (re-)use. Instead of echoing, return true on successful login, and false otherwise. That way, the calling code can decide what to display. That way, you can have all the code that does display something in one place, making it easier to change.


Search a list recursively and return the index of the smallest value

Yes, there is a concise way to do this, even without a recursive function and that is to use the built-in min function with a custom key:

from operator import itemgetter

def min_index(x):
    return min(enumerate(x), key=itemgetter(1))[0]

The enumerate function adds the indices and the operator.itemgetter ensures that min cares only about the actual value (here it is equivalent to lambda t: t[1]). The [0] at the end gets the index from the minimum tuple.

The usage is almost the same as your function, it returns the value so you have to  print it yourself. This is actually good practice because this way you can use the output of the function for other things afterwards.

if __name__ == "__main__":
    print(min_index([3,2,4,0,1,5,-6,2,5]))
    # 6

If you want to use numpy (i.e you are going to do some heavy calculations with these objects), there is a function which does exactly what you want already implemented, numpy.argmin:

import numpy as np

np.argmin([3,2,4,0,1,5,-6,2,5])
# 6


Faster and cleaner SHA-1 leading zero histogram with Python

Instead of str(random.getrandbits(128)).encode('ASCII') I'd use os.urandom(16). Much simpler, ought to be more random, shorter result, and a bit faster (at least for me). Or convert your random number to bytes directly, even faster (at least for me):
>>> timeit(lambda: str(random.getrandbits(128)).encode('ASCII'))
1.320366100000001
>>> timeit(lambda: os.urandom(16))
0.7796178000000111
>>> timeit(lambda: random.getrandbits(128).to_bytes(16, 'big'))
0.6476696999999945

From the doc:

os.urandom(size)
Return a string of size random bytes suitable for cryptographic use.

And to count zeros, perhaps use digest(), make an int from it and ask for its bit length:
    hashvalue = hashlib.sha1(os.urandom(16)).digest()
    i = int.from_bytes(hashvalue, 'big')
    zeroes = 160 - i.bit_length()

Benchmark results (numbers are times, so lower=faster):
0.56 zeroes_you
0.31 zeroes_me
0.29 zeroes_me2
0.26 zeroes_me3

0.60 zeroes_you
0.31 zeroes_me
0.28 zeroes_me2
0.24 zeroes_me3

0.57 zeroes_you
0.31 zeroes_me
0.28 zeroes_me2
0.24 zeroes_me3

Benchmark code:
import hashlib
import random
import os
from timeit import repeat

def zeroes_you():
    randomInput= random.getrandbits(128)
    hashvalue = hashlib.sha1(str(randomInput).encode('ASCII')).hexdigest()
    b = bin(int(hashvalue, 16))
    c= b[2:].zfill(160)
    zeroes = str(c).index('1')

def zeroes_me():
    hashvalue = hashlib.sha1(os.urandom(16)).digest()
    i = int.from_bytes(hashvalue, 'big')
    zeroes = 160 - i.bit_length()

def zeroes_me2():
    randomInput = random.getrandbits(128)
    hashvalue = hashlib.sha1(randomInput.to_bytes(16, 'big')).digest()
    i = int.from_bytes(hashvalue, 'big')
    zeroes = 160 - i.bit_length()

def zeroes_me3(randbits=random.getrandbits, sha1=hashlib.sha1, int_from_bytes=int.from_bytes):
    hashvalue = sha1(randbits(128).to_bytes(16, 'big')).digest()
    zeroes = 160 - int_from_bytes(hashvalue, 'big').bit_length()

for _ in range(3):
    for zeroes in zeroes_you, zeroes_me, zeroes_me2, zeroes_me3:
        t = min(repeat(zeroes, number=100000))
        print('%.2f' % t, zeroes.__name__)
    print()


Finding count of character occurrences in a string

I am not sure I agree that a for loop is more elegant per se. The downside of your method compared to a traditional for loop is that it requires a bit more processing most of the time, because you need to create a new character buffer and put the replacements in there, and you create a new String object.

I would probably create an initial implementation with a Java 8 Stream, e.g.:

String string = "hello";
char letter = 'l';
long count = string.chars().filter(character -> character == letter).count();

To me this is probably more elegant than a traditional for loop. With Streams it is possible to write it in a declarative way. In a lot of cases they are also trivial to parallelize, requiring only a parallel function call on the Stream. Furthermore, they are lazy which means the processing can stop early, only the necessary data will be processed. Note that in this case, we have to process each element (each character), so it makes no difference here.


You should use an interface instead of an abstract class:

public interface IPlugin {
    void Start();
    void Stop();
}

There are many reasons for this, as detailed in https://stackoverflow.com/questions/56867/interface-vs-base-class

I would also separate the plugin logic out of the form, and create a "PluginResolver" class to handle these concerns (This is where you hide the ugly reflection stuff you don't want to touch again).

In terms of the rest of the code, it's pretty basic, so not much to add.

In terms of creating a "plugin architecture" it's kind of a waste without using dependency injection (or a dependency resolver of some kind), because there's no obvious way for plugins to communicate with each other, unless they get coupled together (which defeats the whole point of the plugin architecture), instead by having a set of root services that can be injected into the particular plugins, you can have a disconnected way of giving them all access to say "the primary error logger".


Group Anagrams Together approach in Java

for (int i = 0; i < word1.length(); i++) {

Since you never use i except to calculate word1.charAt(i), you could more easily do

        for (char current : word1.toCharArray()) {

Then you could replace word1.charAt(i) with current.

But as noted in a comment, it would actually be more efficient to use a different algorithm.  The issue is that indexOf is \$\mathcal{O}(n)\$ and of course the for loop is \$\mathcal{O}(n)\$.  Nested, they become \$\mathcal{O}(n^2)\$.  Worse, isAnagram is itself inside nested for loops.  So the overall approach is \$\mathcal{O}(m^2n^2)\$, where \$m\$ is the number of words and \$n\$ is the maximum length of each word.

If you instead normalize each string by sorting it (\$\mathcal{O}(n\log n)\$), you can then put the normalized strings in a HashMap of ArrayList (\$\mathcal{O}(1)\$ each or \$\mathcal{O}(m)\$ total).  This is only \$\mathcal{O}(m\cdot n\log{n})\$, which is much better.

Or skip the ArrayList and just use a counter.  The overall algorithm would look something like

    public static Map<String, Integer> countAnagrams(String[] words) {
        Map<String, Integer> anagramCounts = new HashMap<>();

        for (String word : words) {
            String sorted = sort(word);

            Integer count = anagramCounts.get(sorted);
            if (count == null) {
                count = 0;
            }

            anagramCounts.put(sorted, count + 1);
        }

        return anagramCounts;
    }

This expects the caller to handle the output, which is better practice (Single Responsibility Principle, as applied to methods; see also SOLID, Separation of concerns, and Don't Repeat Yourself).

The basic idea here is that the method should either generate data or display it.  That way, if you want to reuse the data generation for something else, you can.

In the original, you generate the data and then display it in the same method.  If you wanted to do something else with the data, you'd have to refactor.  This is more flexible and easier to test with automation.

Consider

public static void displayAnagramCounts(String[] words) {
    Map<String, List<String>> groups = groupAnagrams(words);
    List<Integer> counts = countValues(groups);
    Collections.sort(counts);
    displayNumbers(counts);
}

Now countValues and displayNumbers can be written in generic ways.  The former takes a Map of List and flattens it into a List of the sizes of the List elements.  The latter displays a list of numbers with spaces between them.  Both those methods can be reused and tested separately.

        for (Map.Entry<String,Integer> entry : anag.entrySet()) {
            //System.out.println(entry.getKey() + " " + entry.getValue());
            counts.add(entry.getValue() + 1);
        }

There is an argument that you shouldn't include commented out code in a code review.  Commented out code is code not ready for source control (it should either be deleted or commented in).

You don't actually need an entrySet here, as values is enough.  E.g.

        for (int value : anag.values()) {
            counts.add(value + 1);
        }

With my alternative algorithm, you wouldn't even have to add one here.


Packet process time simulation using queue

Efficiency

Your algorithm is actually quite simple and efficient.  Keeping track of the scheduled finish times for each packet in the buffer (using ts_te) is a great idea.  The main problem is your poor choice of data structure for ts_te.

Actually, even though ts_te stores the scheduled start and end times for each buffered packet, you never care about the start times.  So, you can just store the end times.  (Incidentally, if you had to store a pair of immutable elements, you should use a tuple rather than a list.  A list implies that the length may vary or that the contents may change.)

You have a performance problem in ts_te.pop(0).  Removing the first item in a list requires all the subsequent elements to be copied over to fill in the hole.  What you want is a data structure that lets you efficiently remove items from the head and append items at the tail.  Such a structure is called a deque (a double-ended queue), and it's in Python's standard library:

  Deques are a generalization of stacks and queues (the name is pronounced “deck” and is short for “double-ended queue”). Deques support thread-safe, memory efficient appends and pops from either side of the deque with approximately the same O(1) performance in either direction.

  Though list objects support similar operations, they are optimized for fast fixed-length operations and incur O(n) memory movement costs for pop(0) and insert(0, v) operations which change both the size and position of the underlying data representation.

Futhermore, if you specify a maxlen when creating the collections.deque, then it acts as a ring buffer, which is often how fixed-size buffers are implemented in real-life systems.

On a related note, I recommend creating results to be the same size as packets, since you know exactly how long it is supposed to be.  That would be more efficient than repeatedly calling .append() and letting Python resize the list as necessary.  (Each resizing operation can be expensive, possibly involving the copying of the entire existing contents.)  Alternatively, if you don't need the results to be a list, simply yield the results instead of building a list.

Style

Follow PEP 8 naming conventions.  buffSize and startTime don't comply.

Avoid introducing special cases.  I don't think that buffSize == 0 should result in an empty list; rather, the results should all be -1, since every packet would have to be dropped.  Furthermore, your algorithm should be designed so that it does not rely on the buffer always being non-empty.

To avoid writing this:

for packet in packets:
    packetArr = packet[0]
    packetDur = packet[1]

… use destructuring assignments:

for packetArr, packetDur in packets:

As a rule, it's more elegant to write if failure_condition: (e.g detecting a dropped packet) rather than if success_condition:.  Usually, failure cases have short code to handle them, and there may be multiple failure cases to handle.

Suggested solution

from collections import deque

def process_packets(packets, bufsize):
    # Stores the scheduled finish times for packets
    buffer = deque(maxlen=bufsize)

    start_times = [None] * len(packets)
    for i, (arrival, duration) in enumerate(packets):
        # Remove packets from the buffer that have been processed by the
        # arrival time.
        while buffer and buffer[0] <= arrival:
            buffer.popleft()

        if len(buffer) >= bufsize:
            # Buffer overrun
            start_times[i] = -1
        else:
            # This packet will start being processed after the finish time of
            # the last buffered packet (if there is anything in the buffer).
            start_times[i] = max(arrival, buffer[-1] if buffer else 0)

            # Store the scheduled finish time for this packet.
            buffer.append(start_times[i] + duration)
    return start_times


Implementation of resizable array (Vector or ArrayList) in C

Do not typedef a pointer.
exit on a bad index is a bit too harsh. Consider returning a success/failure indication instead.
vector->capacity *= 2 and vector->capacity /= 2 embody the reallocation policy. It doesn't feel right that this policy is spread across many functions. I recommend to consolidate it in a single function (resize_vector is a good candidate), and call it unconditionally with the desired new size.
number_of_elements is not exposed to the client. It means that the client cannot iterate over the vector elements, which severely limits the utility of the array. Either expose it, or provide a mapping interface, along the lines of

typedef (*op)(int, void *);
.... map(Vector vector, op, int, void *);

(the void * argument to share a state across the op invocations).


The main issue is that the key event handler and the timer tick will run on different threads which means that someone could press a key while the timer tick fires - in which case the HashSet could be modified while you are trying to read it from another thread. You will need to safeguard against that by protecting the access to the HashSet with a lock You can probably get away with it because the DispatcherTimer runs on the UI thread where the KeyDown/KeyUp events are also being raised.
The idiomatic way of subscribing to event handler is to let the user subscribe to the event rather than passing the event handler via the constructor. What happens if the user has shorter lifetime than the event provider? In your case it would keep it alive because you can't unsubscribe.
When raising the event you need to check if the vent handler is null - subscriptions to an event are considered optional which means no subscriber might exist. Also you should not pass null as sender or EventArgs. The idiomatic pattern in C# goes like this:

private void kbTimer_Tick(object sender, EventArgs e)
{
    var handler = kbEvent;
    if (handler != null)
        handler(this, EventArgs.Empty);
}

The KeyDown method can be reduced to 1 line of code:

return keyPressed.Contains(key);

The name for the event is a bit non-descriptive. How about keyboardTick?
Standard naming convention in C# for public fields/properties/methods is PascalCase (so the event should be KeyboardTick).

In summary the final code could look like this:

class KeyboardController
{
    public event EventHandler KeyboardTick;
    private DispatcherTimer timer;
    private HashSet<Key> pressedKeys;
    private readonly object pressedKeysLock = new object();

    public KeyboardController(Window c)
    {
        c.KeyDown += WinKeyDown;
        c.KeyUp += WinKeyUp;
        pressedKeys = new HashSet<Key>();

        timer = new DispatcherTimer();
        timer.Tick += kbTimer_Tick;
        timer.Interval = new TimeSpan(0, 0, 0, 0, 10);
        timer.Start();
    }

    public bool KeyDown(Key key)
    {
        lock (pressedKeysLock)
        {
            return pressedKeys.Contains(key);
        }
    }

    private void WinKeyDown(object sender, KeyEventArgs e)
    {
        lock (pressedKeysLock)
        {
            keyPressed.Add(e.Key);
        }
    }

    private void WinKeyUp(object sender, KeyEventArgs e)
    {
        lock (pressedKeysLock)
        {
            keyPressed.Remove(e.Key);
        }
    }

    private void kbTimer_Tick(object sender, EventArgs e)
    {
        var handler = keyboardTick;
        if (handler != null)
        {
            handler(this, EventArgs.Empty);
        }
    }
}

and the usage:

public MainWindow()
{
    kbc = new KeyboardController(this);
    kbc.KeyboardTick += HandleKeyboardTick;
}

private void HandleKeyboardTick(object sender, EventArgs e)
{
    if (kbc.KeyDown(Key.Right))
    {
        // do something.
    }
    else
    {
        // do something.
    }
}


Swift protocol with lazy property requirement

You don't need the additional _footype variable and a computer “wrapper” property. The protocol requirement can be satisfied with a lazy stored property:

struct Bar: Foo {
    lazy var footype = calculateFoo()

    func calculateFoo() -> Double {
        print("calc")
        return 3.453
    }
}

Now footype is read-only for instances of type Foo

var foo: Foo = Bar()
print(foo.footype)
foo.footype = 12.3 // Error: Cannot assign to property: 'footype' is a get-only property

but as a property of Bar it is read-write:

var bar = Bar()
print(bar.footype)
bar.footype = 12.3 // OK

If assigning to the footype property should be inhibited then you can mark it with a private(set) access modifier:

struct Bar: Foo {
    private(set) lazy var footype = calculateFoo()

    func calculateFoo() -> Double {
        print("calc")
        return 3.453
    }
}

var bar = Bar()
print(bar.footype)
bar.footype = 12.3 // Cannot assign to property: 'footype' setter is inaccessible

With respect to

  However, I would not put calculateFoo in the protocol because it sounds like an implementation detail.

Yes, in your current code it is an implementation detail of the Bar class. The only use would be that a caller can “enforce” the evaluation:

var foo: Foo = Bar()
foo.calculateFoo()

The situation would be different if there were a way to provide a default implementation in an extension method:

protocol Foo {
    var footype: Double { mutating get }

    func calculateFoo() -> Double
}

extension Foo {
    var footype: Double {
        // Call calculateFoo() on first call only ...
    }
}

so that conforming to the protocol is sufficient, i.e. Bar only has to implement the calculateFoo() method, but not the footype property.

But I am not aware of a way to do this lazily so that the function is called only once. The reason is that extensions cannot add stored properties to a type.

For subclasses of NSObject you can come around this problem with “associated objects,” but not for structs.


In a high-level language, I would write it as:

def put_nibble(buf: array[byte], n: int):
    buf[0] = '0' + ((n shr 3) bitand 1)
    buf[1] = '0' + ((n shr 2) bitand 1)
    buf[2] = '0' + ((n shr 1) bitand 1)
    buf[3] = '0' + ((n shr 0) bitand 1)

def char_to_nibble(ch: byte) -> int:
    if '0' <= ch <= '9': return ch
    ch = ch bitor 0x20  # convert to lowercase
    if 'a' <= ch <= 'z': return ch - 'a' + 10
    error

def byte_to_binary(b: str):
    buf = byte[8]  # reserve memory on the stack
    hi = char_to_nibble(b[0])
    put_nibble(buf, hi)
    lo = char_to_nibble(b[1])
    put_nibble(but + 4, lo)
    sys_write(1, buf, 8)

This way you avoid comparing each possible digit on its own.

The above code also reduces memory access to the memory on the stack, since it doesn't need any external strings for the bit patterns.

Sure, the put_nibble code looks a bit repetitive, but you can merge all the '0' + … together into a single addition:

add dword [buf], 0x30303030  ; 0x30 == '0'

You could also compute the buffer for a whole nibble in a register and then write it to memory in a single instruction:

; input: al = the nibble to print
; output: ebx = 4 bytes ASCII buffer containing the 4 binary digits
xor ebx, ebx

rcr al, 1
adc ebx, '0'
rol ebx, 8

rcr al, 1
adc ebx, '0'
rol ebx, 8

rcr al, 1
adc ebx, '0'
rol ebx, 8

rcr al, 1
adc ebx, '0'
rol ebx, 8

mov [buf], ebx

Once you have translated the above high-level code into assembler, you probably want to optimize the code a bit. Or just use a compiler to do the heavy work for you. Write your code in C or in Go, assemble it into machine code and look at the result. Some keywords for searching:

go tool objdump
gcc -S binary.c -O2

By the way, you should not place the string literals for the prompt and the bit patterns in a writeable segment since they are not intended to be overwritten by any part of your program.


You could have used identical to compare objects. However, I would recommend representing all objects by their MD5 digests, so you can then use match to find the matches:

nameListObjects <- function(LIST, ENV = NULL, NAMES.ONLY = FALSE) {

  if(is.null(ENV)) ENV <- .GlobalEnv
  require(digest)
  list.md5   <- sapply(LIST, digest)
  env.names  <- ls(envir = ENV)
  env.md5    <- sapply(env.names, function(x)digest(get(x, envir = ENV)))
  list.names <- env.names[match(list.md5, env.md5)]

  if(NAMES.ONLY) list.names else setNames(LIST, list.names)
}

nameListObjects(modelList, NAMES.ONLY=TRUE)
[1] "mod1" "mod2" "mod3" "mod4" "mod5" "mod6"