Write a program that simulates a lottery

There's quite a few things I would change here. Getting quality random number generation right is difficult, (these questions come up a lot so it's something I've blogged about), but thankfully with the newer c++11 standard things are a fair bit easier.
Program Correctness
Making sure that your program is correct is extremely important. As it stands this program is not correct (as in does not meet the specification):
cout << " \nThere are " << count << " matching elements ";
for(int i=0; i<size; i++){
    if(winningDigits[i]==player[i]){
        cout << i+1 << " ";
    }
}
cout << "\n";

This comparison assumes that the arrays are sorted, which is not the case. So matching elements could be completely missed here. Sort the arrays first before comparing them or consider a different data structure to store the results from generating the numbers.
Basic things:
There's commented out code in the source, this is almost always a bad sign. Keep code changes tracked by version control, not commented out blocks.
Loops like this are a nightmare formatting wise:
for(int i=0; i<size; i++)
cout << winningDigits[i] << " ";

I personally always use braces (as does the coding standard we go by at my work) but whatever you do you need a tab here:
for(int i=0; i<size; i++){
    cout << winningDigits[i] << " ";
}

Another thing is this:
using namespace std;

Other people have commented on this, but generally speaking the only time you would really want to do this is when you are making some small throwaway program for testing a concept or making an example or similar. You probably don't want to do it in any production code. This pollutes the namespace which is something you don't want, see this https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice for more info on that.
If you want to cut down on on typing you can bring in just the names you need by doing:
using std::cout;
using std::cin;

an so on.
Standard library containers
Generally speaking with c++ you don't want to use raw arrays, the standard container classes are safer and allow you to be more productive. There's a c++ FAQ article that deals with just this, so give that a read.
int winningDigits[size];
int player[size];

Instead of these I would use std::array for both of these as the length is both fixed and known at compile time. Were then lengths not known then std::vector would most likely be the best choice. These become:
#include <array> //header needed for std::array

std::array<int, size> winningDigits;
std::array<int, size> player;

Now this ends up being the same type in a bunch of different places so a typedef will help make things easier:
typedef std::array<int, size> lottery_results_t;
lottery_results_t winningDigits;
lottery_results_t player;

An additional benefit of the typedef is that if you do change the type later it will be easier to do so.
Random number generation
rand() is a really bad random number generator, to the point where the standard committee actually made a report about depreciating it. Additionally rand() gets worse when you take the modulus of it (statistically speaking).
We can avoid all these problems by just using the newer c++ random number library in a manner like this:
std::default_random_engine generator;
generator.seed( time(0) );
std::uniform_int_distribution<int> distribution(0,9);//note the min and max parameters are inclusive here
while(true)
{
    std::cout << distribution(generator) << std::endl;
}

Demonstration here: http://ideone.com/xzgcZy
The output code definitely violates the "don't repeat yourself" principle. Success200 has posted a great answer that outlines some of the things you can do to reduce that duplication.


Exporting a UserForm from the VBE... and working around API bugs

Well, here's a form saved from Excel 2013.

Notice the VB_Exposed, VB_HelpID and VB_Description attributes. I set the Description and Help attributes using the Object Browser Context Menu ("Properties"), but a user might have manually edited the attributes in a previous export/import, and so they might be in a different order

VERSION 5.00
Begin {C62A69F0-16DC-11CE-9E98-00AA00574A4F} UserForm1
   Caption         =   "UserForm1"
   ClientHeight    =   3165
   ClientLeft      =   45
   ClientTop       =   390
   ClientWidth     =   4710
   OleObjectBlob   =   "UserForm1.frx":0000
   StartUpPosition =   1  'CenterOwner
End
Attribute VB_Name = "UserForm1"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False
Attribute VB_HelpID = 55
Attribute VB_Description = "This is a description"
Private Sub UserForm_Click()
  Debug.Print "Test"
End Sub

There is a trailing blank line, but CR MarkDown isn't showing it.

Edit:
With Excel working again, I imported the file, and I do get the extra header line, and if it is exported with a header line, and reimported, there are then 2 header lines, so I'm getting the same behaviour as you.

You won't be able to rely on the position/order of VB_Attributes, so you'll have to parse the file.

You're also assuming a user won't have intentionally placed a blank line at the top of the module. And what happens if the user has more than one blank line at the top of the module?

The safest approach would probably be to count the blank lines at the top of the code module, before the export, and then adjust the number of blank lines found after the last VB_Attribute but before the actual code begins.

That would potentially deal with any fix that might come to VBE.


One more review, where I'd like to point out two Java pitfalls you should avoid in professional code.

byte[] array to represent text

Your public static String toMorse(byte[] bytes) { ... } method signature gets the input as byte array and only internally creates a String out of that array.

That's dangerous, as that String(byte[] bytes) constructor is documented as (emphasis mine):

  public String(byte[] bytes)

  Constructs a new String by decoding the specified array of bytes using
  the platform's default charset. [...]

That means that the same byte array will produce different results when running under different operating systems, as even nowadays there are still many different character encodings in use all over the world and all over the various operating systems.

A computational method like your morse converter should have a String argument instead of a byte[] array, then it's run-anywhere reproducible. If necessary, have your file I/O methods handle character encodings.

Rule of thumb: to pass around things that represent text, use String.

Repeated String appending

In your loop, you build the output string by repeatedly doing lines like

morseText = morseText + morseChar[text.charAt(i) - 'a'];

That's ok if you know the text is rather short, but it will become quite slow for strings with thousands of characters.

Why? Every time the machine executes such a line, it creates a completely new morseText string, copying all the characters from the old morseText, plus the additional morse snippet. So, the first morse snippets get copied over and over and over again. To avoid that, use a single StringBuilder, and in every loop iteration, append() the morse snippet to that StringBuilder, and only after the loop, convert the StringBuilder to the String you want to return.


Simple library for an undocumented archive format

Overall, your coding style is pretty clean, but here are some improvement suggestions to make the code more robust and portable, as well as safer:
Use fixed sized integers
In C, sizeof(char) is guaranteed to be 1 by the standard, but sizeof(unsigned int) is not guaranteed to be 4.
Fortunately, C99 introduces fixed size integers such as uint32_t that is guaranteed to be 32 bit (4 bytes) defined in stdint.h.
Since you are using non standard fopen_s I assume you are not required to stick to ANSI C.
Add error checking
In the code you posted, you never check the return value of your file read operations or memory allocation operations.
You also never check the sanity of the data you read.
For a library, robust error handling is important, so you should always check if read operations success, and if data such as entry sizes or offsets are reasonable - match expected size / do not go past end of file.
On error, you should return one of several error codes you define for you library and list in documentation.
Reduce disk operations
You will probably not feel this in your testing, both due to modern hardware, small file size, and multiple caches on different levels, but your seekToEntry function is inefficient due to many back and forward disk operations (both seek and read).
There are two approaches here, which you can choose depending on how you want to trade memory for speed, and how would your library be used:

Preload the entire "catalog" of file entries in to array of structures in memory and search that when you need to find entry position in file.
Since your entries are guaranteed to be sorted, you may want to implement a more efficient search, maybe arrange them in a tree by prefix.

Since every entry has fixed size, read at least the current entry completely in to a structure.
If you don't want to load them all to memory in advance, at least load all data (name, size, offset) for each entry as you iterate, and save your self a bunch of seek operations.

Either approach will also give you the opportunity to create a documented structure for "entry" of this archive file, which will be good for you and your library users.
Create a name space
Since this is a library, it may be used in a big project with other libraries or many functions defined in the project it self.
You want to avoid name collision for your functions, structures, and defines.
Though C does not support special syntax for namespces, one convention for libraries is to use a fixed and consistent prefix to names followed by an underscore.
If your library is for handling "Big File Archive" you could prefix all your names with BFA_ like so: BFA_loadFile, BFA_seekToEntry.
Avoid non-standard functions
While MS may claim fopen_s is more secure, it is also non-standard, so if you or one of your library users ever switches compiler or OS, your library will no longer work.
You should use C standard fopen instead and just add proper error checking as specified above.
Also, there is no reason to reimplement strncmp as you do with your loops.
Unlike strcmp which is not safe if the string is not guaranteed to be null terminated, strncmp is perfectly safe for your use case where maximum length is known in advance.
Use consistent interface
It is hard to tell with only two functions, but you seem to have some difference in how your library functions work:
One returns an "object" (the BIGFile structure), another returns error / success codes instead.
While this is technically valid approach, it would be more consistent and comfortable for the user to have a unified interface where all functions would return the same thing - error codes.
If a function must also return a value for the user, such as a pointer to a structure, it should return it using one of the parameters.
Your open function could look like this:
/**
 * Opens an archive file and loads its header
 *
 * @param fpath   path to the archive file
 * @param header  place to return loaded header data if the file is successfully loaded (structure will be allocated by the function)
 * @return success / error status code
 */
int BFA_loadFile(char *fpath, BFA_FileHeader **header) {
    ...
}

Here, I also included one common method of documenting functions in libraries which can be used with automated tools such as doxygen to produce documentation files in HTML and other formats.


.NET - Get a DateTime from a pointer to an OLE Date

I agree with @IAbstract that the inline code looks fine. I would wrap it and name it differently since nothing in the current code reveals that it is a pointer to an OLE/OA Date.

public DateTime DateTimeFromOLEDatePointer(Int64 oaDate)
    {
        var dateAsULong = Marshal.ReadInt64(oaDate);
        var dateAsDouble = BitConverter.Int64BitsToDouble(dateAsULong);
        var dateTime = DateTime.FromOADate(dateAsDouble);
    }

Usage:

private void GetDateFromWinMsg(Message message)
    {
        return DateTimeFromOLEDatePointer(message.LParam);
    }

Could also make it an extension method.


Module to validate and sum a string containing no negative numbers

module.exports is just an object. Set properties on it that you want to expose.

exports.add = add

This is also equivalent in this case.

module.exports = {add: add}

Now, when you require this module, you'll get an object with one property: add.

There are a few other small issues:

Nothing about your design depends on accessing methods via this. This module
is clearer without bringing this into the mix.

function add (string) {
  _checkForError(string)
  _checkForNegatives(string)
  return _result(string)
}

This code is quite easy to follow already, but It would be even better if you
had your methods in the order they are called so the code reads like an article:
broad info at the top, specific details later on.

I'd also leave out semicolons where they will be handled by automatic semicolon
insertion, but that's a style choice.

function _checkForError (string) {
  if (string.match(/\n$/)) {
    throw 'Expression ending in newline!'
  }
}

function _checkForNegatives (string) {
  var negatives = _negatives(string)
  if (negatives.length > 0) {
    throw 'Negatives not allowed: ' + negatives.join(', ')
  }
}

function _negatives (string) {
  var numbers = _numbers(string)
  var negatives = numbers.filter(function (number) {
    return number < 0
  })
  return negatives
}

function _result (string) {
  var numbers = _numbers(string)
  var result = numbers.reduce(function (sum, number) {
    return sum + number
  })
  return result
}

function _numbers (string) {
  var modded = _modded(string)
  var numbers = modded.map(function (number) {
    return parseInt(number, 10) || 0
  })
  return numbers
}

function _modded (string) {
  var delimiter = _delimiter(string)
  return string.replace(/\n/, delimiter).split(delimiter)
}

function _delimiter (string) {
  return (string.substr(0, 2) === '//') ? string[2] : ','
}


At first I decided to load all the feeds at the end of all the asynchronous requests. This only required one DOM request at the end. The problem with that approach is that it just takes too long to load. Some requests timed-out and others just took a while.

It's unclear to me why the requests are timing out, but you could simply store the results of the responses in memory as opposed to what you might be doing; synchronization logic is not necessary, you only need to know when all requests ended. However, the downside of this approach is that time outs can make your application show nothing to your visitors, which is something you really don't want to do...

  What I'm doing right now is changing the DOM after each feed request (e.g. twitter). At the moment this means 8 DOM changes.

It feels to me that 8 DOM changes are trivial to do by your browser; but the thing to do here is to actually figure out how many requests your code needs to be capable of handling.

A bad option would be to update the DOM on each X-th response, because you are introducing the timed-out problem again. So, a better option is adding your responses to a queue and updating the DOM each X ms. That way you have the best of both worlds, and it doesn't matter how much feeds you'll be adding because it scales pretty well. There might probably be other problems at the high end, like updating too much DOM at once, but that's out of the question here...


Use a set instead of a dictionary

The current algorithm sets the value to true for each character it finds,
and at the end it checks if there is anything still unset. This is a bit tedious, and inefficient. Checking if any value is false is an \$O(n)\$ operation.

A simpler and more natural solution would be using a set data structure (HashSet in C#). You could add characters that you found, and in the end check the size of the set, and compare it with the size of the alphabet.

If the input may contain letters not in the alphabet, then before adding letters to the found set, don't forget to check the letter is actually part of the alphabet. (Thanks @tym32167 for the reminder.)

Use a simple array instead of a dictionary

If the alphabet is always the English alphabet, then an interesting simple alternative is using a simple boolean array of size 'z' - 'a' + 1. As you iterate over the letters, you can derive the array index to use by letter - 'a'. It will be simpler and more storage efficient than using a dictionary.

Generate the alphabet once

The English alphabet is regenerated on each call of IsPangram.
This is unnecessary, as it never changes between calls.
You could generate it once and reuse.


All in all, that is some good looking, idiomatic Haskell. Well done!

You seem to be using the mod n x == 0 idiom quite often, so let's extract that to its own function.

divides :: Integral a => a -> a -> Bool
n `divides` m = m `mod` n == 0

You could also make your predicate polymorphic. No need to restrict yourself to Int, any Integral will do the trick.

isPrime :: Integral a => a -> Bool
isPrime 2 = True
-- and so on

I've often read that rem is faster than mod, but I've never checked... maybe it does give you some speed.

Through clever reordering of the guards, you can get rid of the if then else.

Instead of having a simple comment to explain the function, consider writing actual Haddock documentation.

Putting it together:

-- | @divides n m@ checks whether @n@ evenly
--   divides @m@, meaning that @m `mod` n == 0@.
divides :: Integral a => a -> a -> Bool
n `divides` m = m `rem` n == 0

-- | Checks whether a given number is prime.
isPrime :: Integral a => a -> Bool
isPrime 2 = True
isPrime 3 = True
isPrime n
    | 2 `divides` n = False
    | 3 `divides` n = False
    | otherwise     = check 5 2
  where check i w
      | i * i > n     = True
      | i `divides` n = False
      | otherwise     = check (i + w) (6 - w)

Maybe check 5 2 deserves a comment, as I couldn't see why these numbers are there on a first glance.


Base 26 (letters) and Base 10 using recursion

As others already said, recursion doesn't quite fit here. But I’d say it doesn't fit because strings are immutable. In your implementation, you are either concatenating strings or slicing them, which are operations that will produce new strings each time where it shouldn't be necessary.

Instead, iteration is more natural in Python, and you have several builtins that can help you so. The first ones being reversed and enumerate that give you the ability to iterate over each letter in a string in reverse order while knowing the index of the letter: usefull when converting from base alphabet to base 10. And for the base 10 to alphabet conversion, you can extract individual "digits" using divmod and join the generated letters.

Lastly, I’d recommend to stick to the lower_case_with_underscore naming convention for functions as recommended per PEP8.

A_UPPERCASE = ord('A')
ALPHABET_SIZE = 26

def _decompose(number):
    """Generate digits from `number` in base alphabet, least significants
    bits first.

    Since A is 1 rather than 0 in base alphabet, we are dealing with
    `number - 1` at each iteration to be able to extract the proper digits.
    """

    while number:
        number, remainder = divmod(number - 1, ALPHABET_SIZE)
        yield remainder

def base_10_to_alphabet(number):
    """Convert a decimal number to its base alphabet representation"""

    return ''.join(
            chr(A_UPPERCASE + part)
            for part in _decompose(number)
    )[::-1]

def base_alphabet_to_10(letters):
    """Convert an alphabet number to its decimal representation"""

    return sum(
            (ord(letter) - A_UPPERCASE + 1) * ALPHABET_SIZE**i
            for i, letter in enumerate(reversed(letters.upper()))
    )

But, you could use recursion in _decompose in order to not have to reverse the string produced by join:

A_UPPERCASE = ord('A')
ALPHABET_SIZE = 26

def _decompose(number):
    """Generate digits from `number` in base alphabet, most significants
    bits first.
    """

    number -= 1  # Account for A in base alphabet being 1 in decimal rather than 0
    if number < ALPHABET_SIZE:
        yield number
    else:
        number, remainder = divmod(number, ALPHABET_SIZE)
        yield from _decompose(number)
        yield remainder

def base_10_to_alphabet(number):
    """Convert a decimal number to its base alphabet representation"""

    return ''.join(
            chr(A_UPPERCASE + part)
            for part in _decompose(number)
    )

def base_alphabet_to_10(letters):
    """Convert an alphabet number to its decimal representation"""

    return sum(
            (ord(letter) - A_UPPERCASE + 1) * ALPHABET_SIZE**i
            for i, letter in enumerate(reversed(letters.upper()))
    )


Fastest and minimal random access data structure in Java

Wow, this is pretty nice code. I've only got a few little nitpicks.

NB: I have not benchmarked the code before and after making these changes. If you'd like, I can, but as of right now, these are untested changes.

NB2: Most of these are just conforming to convention, since after a bit of research I've discovered that the JIT makes things scary fast after a few thousand iterations by putting in every optimization I'd never think of.

In remove(E) and contains(E), you compare equality with == instead of equals. This is a bad idea, because sometimes people want to specify their way of comparing objects. If they don't, this will default to Object's implementation, which is just ==. The exception, of course, is when you're dealing with either primitives or null, but you don't have to worry about that, since you can't use primitive types as E, and their class equivalents all define equals appropriately.
It's standard for remove to return the element it just removed, so you'll want to change the internals of the for a little bit:

if (element.equals(arr[i])) {
    set(i, null);
    return element;
}

and change the method signature to match.
I'd recommend adding a remove(int) as well, which does basically the same thing as remove(E) but doesn't have to loop through. It would look something like this:

public E remove(int index) {
    E ret = get(index);
    set(index, null);
    return ret;
}

Continuing with the trend of "I think your methods are bad and here's how I think you should do them instead", I think your lack of indexOf is bad and here's how I think you could implement it:

public int indexOf(E element) {
    for (int i = minIndex; i < size; i++) {
        if (element.equals(arr[i]))
            return i;
    }
    return -1;
}

In set(int, E) I'd recommend renaming last to original, or it might be confused with the last element of the array.
In iterator()'s anonymous class's next(), you should add a check to make sure that you're not overstepping the array's bounds, even if all you end up doing is throwing a different error. corsiKa suggested using an IllegalStateException, which makes a good bit of sense. The most important thing is that, from the name of the exception alone, you can figure out roughly what went wrong, though not necessarily the details.

That's about it! Well-written code all. If you give me some test cases, I can benchmark the version with my tips and the version without.


Converting decimal to Roman numerals using MATLAB

Your use of ans is very difficult to understand, it took me 5 minutes reading the lines to understand what []; really does and why it is necessary.

function r = dec2rom(z)
d = [ 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1];
c =  {'M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I'};
r='';
for ii = 1:numel(d)
    if z >= d(ii)
        r = [r,repmat(c{ii},1,fix(z/d(ii)))];
        z = rem(z,d(ii));
    end
end

/second version following the discussion to the other answer:

function r = dec2rom(z)

t={ 1000, 900, 500,  400, 100,   90,  50,   40,  10,    9,   5,    4,   1;
    'M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I'};
r='';
for ii = t
    num = ii{1};
    symb = ii{2};
    r = [r,repmat(symb,1,fix(z/num))];
    z = rem(z,num);
end

Now having the chars and numbers aligned in a data structure and using a simplified for loop.


How can I better test whether the player won in my tic-tac-toe?

I hate this sort of hard-coded testing - there is usually a better approach to represent our data.
A few thoughts come to mind.

You don't stop players playing into an already occupied cell.
Why not use a 2-d array (actually an array of arrays)? Then you can more naturally scan rows, columns, and even diagonals.
If you score X as 1 and O as -1, then a winning row, column or diagonal adds up to 3 (X wins) or -3 (O wins).
If you initialise the cells to an appropriate value, I think you can also detect a hung game early - for example if you initialise to 4, then any row, column or diagonal with a sum < 4 but not 3 or -3 is unwinnable. If they're all unwinnable, there's no point making further plays. (I need to think this through a bit more!)
I thought it through more carefully. If X is 1, O is -1 and an empty cell is 4 (for example), then a line summing to 3 is a win for X; summing to -3 is a win for O; 4 is an unwinnable line as it must have an X, an O and a blank cell; other values are undecided lines. If there are 8 unwinnable lines, then the match is a draw.]


Simple does not mean fast, so you cannot judge performance based on how simple the implementation looks. Usually the most efficient way to perform a non-trivial task is not also the simplest way to do it. In this case though, there is a much more efficient solution that is about equally simple, and is probably sufficient.

There is a serious problem with this implementation: it computes kenc**d.

kenc**d is in general a very big number that takes a long time to compute, and then it takes a long time again to reduce it modulo n. For example, trying it out with 1024bit RSA (the lowest setting!):

import Crypto
from Crypto.PublicKey import RSA
from Crypto import Random

random_generator = Random.new().read
key = RSA.generate(1024, random_generator)

def decrypt(kenc,d,n):
  kdec=(kenc**d)%n
  return kdec

(ciphertext,) = key.encrypt(42, 0)
print(decrypt(ciphertext, key.d, key.n))

This does not finish in a reasonable time.

There is a simple remedy: use modular exponentiation, which keeps the size of the numbers that it is working with low throughout the whole calculation by reducing modulo n as it goes along. You could implement it yourself, but Python handily provides a built-in function for this: pow(x, e, n)

So decrypt can be written as:

def decrypt(kenc, d, n):
  return pow(kenc, d, n)

With that change, the code above decodes the message quickly.

Further improvements are possible, but more complicated, and won't be drop-in replacements.


Unit testing
Definitely write some test cases for your code.  JUnit would be one possibility, but there are many test frameworks to choose from.
With any test framework, and at least one test per public method, this goof would have been immediately apparent:
  public boolean isEmpty() {
    return size() > 0;
  }

As Timothy Truckle points out in a comment below, one test per public method is not enough.
Misleading method argument name/implementation
While the way that you used ensureCapacity(length + 1) will work, it hides a subtle bug.
  private void ensureCapacity(int minSize) {
    if(minSize >= capacity) {
      capacity *= 2;
      elements = Arrays.copyOf(elements, capacity);
    }
  }

Consider if you exposed the method ensureCapacity(int minSize) as a public method, like the standard library's ArrayList#ensureCapacity method.  A caller might use:
  var container = new DynamicArray<Integer>();
  container.ensureCapacity(10000);
  // ...

The first statement creates the container, with an initial capacity of 10.  The next statement looks to resize the container to hold 10000 integers, but what actually happens is, since 10000 is larger than the current capacity, the capacity is doubled to 20.
Instead of capacity *= 2; perhaps you would want something more along the lines of:
  private void ensureCapacity(int minSize) {
    if(minSize >= capacity) {
      capacity = Math.max(capacity * 2, minSize);
      elements = Arrays.copyOf(elements, capacity);
    }
  }

Initial Capacity
Even without exposing ensureCapacity(int minSize) as a public function, the following test will cause the bug to appear in a different way, causing a ArrayIndexOutOfBounds exception:
  var container = new DynamicArray<Integer>(0);
  container.add(10);

The initial capacity is zero.  In attempting to add an item, the length + 1 will exceed the capacity of zero, so the capacity will be doubled from zero to ... zero!  Then, elements[length++] = element; will access the first element from an array of length 0.  Oops.
You could prevent this with validation in the constructor ...
    if(capacity <= 0)
      throw new IllegalArgumentException("Capacity must be positive");

With the capacity = Math.max(capacity * 2, minSize); fix, this could be relaxed to allow an initial capacity of zero:
    if(capacity < 0)
      throw new IllegalArgumentException("Capacity cannot be negative");

Iteration
You define an Iterator for your DynamicArray, but if the array is modified while your iterator is in flight over the list, odd things may happen.
For example: If you have a DynamicArray<String> containing "foo", "bar" and "baz", you might create the iterator and retrieve the first item: "foo".  If you then performed .removeElement(0), the next element returned by the iterator would be "baz", not "bar"!
The standard collections will raise a ConcurrentModificationException in these cases.  They achieve this by maintaining a modCount in the container.  Each .add() or .remove() operation would increment this by one.  When the iterator is created, it captures the current modCount value for the container.  On every iterator operation, it checks to see if the modCount has unexpectedly changed, and if so, raise the exception.
Compile time warnings related to generics
You can add @SuppressWarnings("unchecked") annotation to a statement, method, or an entire class.  Ideally, you should apply the annotations to the smallest possible scopes to avoid accidentally suppressing warnings you didn't intend to.
See this answer


Python class to abstract the iptables Linux firewall

There are violations of PEP-8 throughout and there are no PEP-257 docstrings. It sounds petty, but these mean the difference between an easy read and a hard one.

The class name Fwall is terrible, if you mean Firewall call it that. If you mean that it is a container of FirewallRules then say so. Names are extremely important.

If getrules() is not part of the public class interface, convention suggests naming it _getrules which tells the reader that it is expected to be used only by the class itself. Having print statements is fine for debugging, but a well behaved library should assume that there is no stdout and return lists of strings in production code.

Long lines are hard to read, especially on StackExchange. Fortunately, splitting within parenthesis is natural and preferred, thus:

s = subprocess.check_output("iptables --list --verbose",
        shell=True, stderr=subprocess.STDOUT)

but sticking a comment marker in code will certainly cause misreadings. Where you have

s = subprocess.check_output(...)#.split('\n')

you should drop the #.split('\n'). Also, following PEP-8, put spaces after argument separating commas.

You use iteritems() unnecessarily as the standard iteration behavior of a dictionary is now assumed. Where you have for k,v in self.dicolumns.iteritems(): the line

for k, v in self.dicolumns:

is equivalent. To bang on the "names are important" drum, every dictionary has k and v, using more descriptive names would tell me what the meaning of the keys and values are. For that matter I have no idea was a dipolicy or dicolumns are, they might be related or parallel lists but I don't know. You tend to use if len(item)==0 when if item means the same thing.

I had to edit your entry because the class methods were not properly indented; this usually means that you are using a mix of tabs and spaces. Tell your editor to forget that the TAB character exists and to use only spaces, there are instructions for most editors on how to make it pretend that the TAB key behaves like you expect without putting literal \t characters in your source code.

The structure of parseline() is so deeply nested and has so many return points and un-elsed ifs that I really can't follow the logic of it. Read The Zen of Python and keep it wholly.

Finally, iptables is notoriously hairy. I strongly suggest that you use python-iptables or at least study its class structure. You might also want to look at Uncomplicated Firewall as it is designed to abstract iptables into something most humans can understand. It doesn't handle all possible uses, but it makes the typical cases comprehensible.


Modified Z-Algorithm for string similarity with one char difference

Why it is slow

In your modified Z-algorithm, you start computing the Z array from i = patternLen + 1.  This means that for the whole pattern, your Z array will have value 0.  This defeats the purpose of the Z-algorithm.  Even if you removed the part where you ignore one mismatched character, this will have changed your search from a \$O(n)\$ search to a \$O(n*m)\$ search, where \$m\$ is the length of the pattern.

For example, I did a test where I searched a string containing 1 million 'a' in a row for a pattern containing 1000 'a' in a row.  This took 4 seconds.  When I changed the code to start at the beginning of the pattern (i.e. the real Z-algorithm), it took 0.08 seconds.

But...

You can't just start at i=1 and expect to fix the problem.  Your "ignore one mismatch" code requires that you start over from the beginning every time because you can't use partial substring matches like you can with the Z-algorithm.  The reason is you may have skipped over a mismatch, so the value in the Z array doesn't necessary correspond to the substring that you matched.

So in other words, perhaps Z-algortithm is not well suited for this problem, or at least you will need to modify it in a different way.


Calling tries to lazy load in every properties getter

There is the INotifyPropertyChanged event handler, but I'm not sure why you would need that in this case?  Instead why not just load the details when the ID changes as that seems to be the only value that will change between LoadDetails calls.

Perhaps something like:

public int ID
{
    get { return m_nOID; }
    set {

       if(m_NOID != value) {
          InitialiseUserDetails(m_nOID);
       }

       m_nOID = value;
    }
}

If this was ok, you could remove the private backing fields as I believe you wish to do.


Editing system files in Linux (as root) with GUI and CLI text editors

It's good form to return non-zero on error.  The not-optional option is a little ugly and an environment variable may work better.

Some extraneous syntax can go:

1 before >&2 is implied
{} around unsubstituted dereferences doesn't add anything
echo is an alias for printf "%s\n"
testing for error instead of success allows test && echo && return without braces
command -v tests validity for you; no need to test again
you've moved the complexity into a function already; reward yourself by using aliases to invoke it

sudoedit_internal()
{
    [ $# -lt 2 ] && echo "sudoedit_internal(): Invalid number of arguments." >&2 && return 1
    ! command -v "$1" >/dev/null && echo "sudoedit_internal(): The editor $1 does not exist on this system." >&2 && return 1
    editor="$1"; shift
    SUDO_EDITOR="$editor $opt" sudoedit "$@"
}

for ed in vi nano       ; do alias su$ed="opt=   sudoedit_internal $ed"; done
for ed in code subl xed ; do alias su$ed="opt=-w sudoedit_internal $ed"; done


MSDN documentation for this is a mess and for the most part, inadequate (it's better than MSDN's C++ ADO documentation though).

If you have access to MSXML, then you can use smart pointer wrappers that allow you to avoid worrying about releasing the objects. These smart pointers come with simplified function calls.

For instance, here is the normal function prototype for a IXMLDOMNodeList:

HRESULT IXMLDOMNodeList::get_length(long *listLength);

Here is the "smart" version of that function for IXMLDOMNodeList object:

long IXMLDOMNodeList::Getlength ();

This allows you skip the error checking (it throws an exception on failure).
You also have access to the source code for these new functions as well. The source code is in an automatically generated .tli file, so you can always know what they do. The .tli file is usually located in C:\Users\*User*\Local\Temp\msxml6.tli. Just looking through this file can help you partially learn how to use IXMLDom.

If you have access to comutil.h, you can use the _bstr_t type instead of BSTR for automatic memory management as well.

Here are a few examples of using the smart pointers. I used standard library containers such as std::string and std::vector, but you could easily change these out with CStrings or other string types.

#include <string>
#include <vector>
#include <tchar.h>
#include <comutil.h>
#import <msxml6.dll>

typedef std::basic_string <TCHAR>       tstring ;

typedef MSXML2::IXMLDOMNodePtr          NodePtr ;
typedef MSXML2::IXMLDOMNodeListPtr      NodeListPtr ;
typedef MSXML2::IXMLDOMDocumentPtr      DocumentPtr ;
typedef MSXML2::IXMLDOMElementPtr       ElementPtr ;
typedef MSXML2::IXMLDOMNamedNodeMapPtr  NamedNodeMapPtr ;

DocumentPtr LoadXMLDocument (const tstring &strFile)
{
    // Call ::CoInitialize or ::CoInitializeEx before this.
    HRESULT hr ;
    DocumentPtr pDoc = NULL ;
    hr = pDoc.CreateInstance (__uuidof (MSXML2::DOMDocument60)) ;
    if (hr != S_OK) {
        // This could happen if ::CoInitialize or ::CoInitializeEx hasn't been called.
        // Throw an exception.
    }

    pDoc->async = VARIANT_FALSE ;
    pDoc->validateOnParse = VARIANT_FALSE ;
    pDoc->resolveExternals = VARIANT_FALSE ;

    VARIANT_BOOL vbOk = pDoc->load (_variant_t (strFile.data ())) ;

    if (vbOk == VARIANT_FALSE) {
        // Throw an exception.
    }

    return pDoc ;
}

tstring GetAttribute (const NamedNodeMapPtr &pAttrs, const tstring &strKey)
{
    tstring str ;

    NodePtr pAttr = pAttrs->getNamedItem (_bstr_t (strKey.data ())) ;
    if (pAttr == NULL) {
        // Throw an exception.
    }

    _variant_t var = pAttr->GetnodeValue () ;
    if (var.vt == VT_BSTR) {
        str = (TCHAR *) (_bstr_t) var ;

    } else {
        // Throw an exception.
    }

    return str ;
}

tstring GetAttribute (const NodePtr &pNode, const tstring &strKey)
{
    NamedNodeMapPtr pAttrs = pNode->Getattributes () ;
    return GetAttribute (pAttrs, strKey) ;
}

tstring GetSubElementText (const ElementPtr &pNode, const tstring &strSubElement)
{
    NodePtr pSub = pNode->selectSingleNode (_bstr_t (strSubElement.data ())) ;
    if (pSub == NULL) {
        // Throw an exception.
    }

    _bstr_t bsRoot = pSub->Gettext () ;
    tstring strText = (TCHAR *) bsRoot ;
    return strText ;
}

void GetAttributes (const NodePtr &pNode, const std::vector <tstring> &vecKeys, std::vector <tstring> &vecValues, const tstring &strDefault)
{
    NamedNodeMapPtr pAttrs = pNode->Getattributes () ;
    for (unsigned n = 0; n < vecKeys.size (); ++n) {
        const tstring &strKey = vecKeys [n] ;
        tstring str = BVLib::GetAttribute (pAttrs, strKey) ;
        vecValues.push_back (str) ;
    }
}


This is a very good attempt for the first Python venture!

Here is what I would consider improving:

stylistic / PEP8

naming. In Python, it is recommended to use lower_case_with_underscores notation. Your function and variable names are inconsistent and there is a mix of styles - e.g. cur_startDateString follows both camelCase and lower_case_with_underscores
the user of blank lines. In Python, it is recommended to have 2 blank lines between top-level blocks of the code and have an extra new-line at the end of the script
the use of whitespaces. Watch for whitespaces after commas in expressions, e.g.:

for idx,entry in enumerate(gameEntries,start=1):
   ^                              ^

import grouping and order. See Imports section of the PEP8
parenthesis around the return value are redundant
consider adding docstrings explaining what your functions are about. For instance, getLatestFilename would benefit from a note about how does it define which file is the latest. And, parseUrl is not really easy to understand just by reading the code
if you are using Python 3.5+, consider adding Type Hints

Design and modularity

it is a good thing that you tried to logically separate scraping from parsing
I would also separate parsing and dumping the results into a CSV file

HTML Parsing

if performance is a concern, consider switching from html.parser to lxml - see "Installing a Parser" section of the documentation
you could also improve performance of the parsing stage by using a SoupStrainer which allows you to parse the desired part of the HTML tree in the first place:

from bs4 import BeautifulSoup, SoupStrainer

parse_only = SoupStrainer(class_='entry')
soup = BeautifulSoup(page.text, 'lxml', parse_only=parse_only)

.findNext() is deprecated in favour of .find_next()

Other

getUrl() method feels a little bit overcomplicated and you can definitely improve its readability and simplify it at the same time. Plus, I would make it return the URL as a string and not as a list to avoid any extra external code needed to make it a string. If you are using Python 3.6+, f-strings would be handy:

def get_url(filename: str) -> str:
    """Constructs a complete URL based on the filename and current date."""
    current_interval = parse_url(filename)

    now = datetime.datetime.now()

    return f"https://gematsu.com/{now.year}/{now.month}/media-create-sales-{current_interval}"

Having the complete URL string with placeholders helps to see what the end result might look like.

Note that most of the PEP8 violations mentioned above could be caught by running a linter (like flake8, or pylint) against your code.


Reducing repetition
The big if statement in printAvgCalPerGroup is a bit repetitive (as you pointed out).  Imagine if you increased the number of food groups.  You would have to copy/paste 4 places for each food group you added.
First, I would suggest using arrays for the counts and amounts of each foodgroup.  Then you only have to convert the letter such as 'v' into an array index.
Second, if the food groups could possibly change, I would suggest using an enum to keep track of them.  This is definitely optional, and you could use hardcoded numbers instead (e.g. 'v' -> 0, 'm' -> 1, etc).
Third, a small change to make would be to track the amounts using ints instead of doubles, since the amounts always increase by 1 only.
Here is what your code would look like using arrays and enums:
typedef enum FoodGroup {
    VEG,
    MEAT,
    DAIRY,
    GRAINS,
    FAT,
    FOODGROUP_MAX
} FoodGroup;

void printAvgCalPerGroup(Food * list)
{
    double    count[FOODGROUP_MAX] = {0};
    int       amnt [FOODGROUP_MAX] = {0};
    FoodGroup group;

    Food * temp = list;

    while (temp!= NULL) {
        switch (temp->foodGroup[0]) {
            case 'v': group = VEG;           break;
            case 'm': group = MEAT;          break;
            case 'd': group = DAIRY;         break;
            case 'g': group = GRAINS;        break;
            case 'f': group = FAT;           break;
            default : group = FOODGROUP_MAX; break;
        }
        if (group < FOODGROUP_MAX) {
            amnt [group]++;
            count[group] += temp->calories;
        }
        temp = temp->next;
    }

    for(group=0; group<FOODGROUP_MAX; group++)
        printf("%.2f\n", calcAvg(count[group], amnt[group]));
}

If you don't need the enum, just replace VEG with 0, MEAT with 1, etc.


As per my second comment, below is a possible solution. This solution involves a different querying method that will work for both console sessions and remote sessions. This method looks at all processes that are the explore.exe process, which is the user shell for each user that is logged into the server.  Once armed with the list of those processes, getting the owner for it is another WMI query (GetProcessOwner method).

// what to do if multiple users logged in?
foreach (var p in Process.GetProcessesByName("explorer"))
{
    _username = GetProcessOwner(p.Id);
}

// remove the domain part from the username
var usernameParts = _username.Split('\\');

_username = usernameParts[usernameParts.Length - 1];

...

    public static string GetProcessOwner(int processId)
    {
        var query = "Select * From Win32_Process Where ProcessID = " + processId;
        ManagementObjectCollection processList;

        using (var searcher = new ManagementObjectSearcher(query))
        {
            processList = searcher.Get();
        }

        foreach (var mo in processList.OfType<ManagementObject>())
        {
            object[] argList = { string.Empty, string.Empty };
            var returnVal = Convert.ToInt32(mo.InvokeMethod("GetOwner", argList));

            if (returnVal == 0)
            {
                // return DOMAIN\user
                return argList[1] + "\\" + argList[0];
            }
        }

        return "NO OWNER";
    }


Having to refer to $scope.$parent is absolutely bad-practice, because dependencies will go up and down and all sorts of ways in your application. It will become a big mess. It is best to only pass dependencies down the scope chain, not up.

Exactly what you describe, you got two options. Go the nested scope way or use a service.

It is indeed best-practice to use a service when more logic is being handled. It's really up to you to choose between the two options. Both are good, but you need to think about the use-case. Will there be more data be passed along to both controllers; definitely go for the service. Is it just a simple pass this variable to the underlying controller go the nested scope route.


Winforms tools for selection of items using ComboBox - binding datasource

Style & Conventions

Enums and delegates shouldn't be nested in a class.
The default event delegate is the EventHandler. If you want to create a custom event handler then its signature should be

delegate void ItemSelectedHandler(Object sender, EventArgs e);

but if you need custom event args then you should create a new class derived from EventArgs and with the properties that you need:

class SelectEventArgs : EventArgs
{
    ..ctor
    public IHasHeader item { get; }
}

then you can use the generic event-handler:

public event EventHandler<SelectEventArgs> TemplateSelectionChanged = delegate { };

You shouldn't use any other pattern for events like

public event Action RefreshingTemplatesList = delegate { };

If you want to follow the event style and conventions then stick to the EventHandler and event args.

Binding

public IEnumerable<IHasHeader> TemplatesDatasource
{
  set
  {
      doHandleSelection = false;
      bindSrc.DataSource = value;
      cboxTemplates.DataSource = bindSrc;
      cboxTemplates.SelectedIndex = -1;
      doHandleSelection = true;
  }
}

here you could write

 bindSrc.DataSource = value.ToList();

instead

bindSrc.DataSource = value;

so that you can later reuse this list for adding more items:

public void AddItem(IHasHeader item)
{
    var headers = bindSrc.DataSource as List<IHasHeader>;
    headers.Add(item);
    bindSrc.ResetBindings(false);
}

Don't abbreviate the names like bindSrc. Use full names and preferably meaninigful ones like headerSource or headerBindingSource. bindSrc doesn't say anything about what the binding source holds.


Naming

Choose an existing idiom such as "find a needle in a haystack" and consider putting the parameters in that order.
The name index implies some generic location within haystack. However, start makes it clear why that index is significant.

The rest of my answer assumes these changes.

Validating Input

You don't need to manually throw NullPointerException for null values when accessing the length of each string will do it automatically. If not, make sure to check both strings for consistency.
Consider how to handle negative values for start, typically by taking it from the end of the haystack. You'll need to decide whether to use modulo arithmetic or constrain overly-negative values to zero.

if start < 0
    start = Math.max(0, haystack.length + start)

Logic Yoga

Combine identical prefix expressions in an if chain.

if (A && R) { X }
if (A && S) { Y }
if (A && T) { Z }

This can be simplified and optimized to

if (A) {
    if (R) { X }
    if (S) { Y }
    if (T) { Z }
}

It works for || as well, though I can't think of a recent sighting in the wild.

if (A || R) { X }
if (A || S) { Y }
if (A || T) { Z }

becomes

if (A)
    X Y Z
else
    // same as "if (A)" above

Clarify intent by using else if after blocks that should exit. Adding else lets the compiler enforce that intent when they're modified.

myIndexOf(needle, haystack, start)
    if needle is larger than haystack
        return ...
    else if needle is empty
        return ...
    else
        return ...

Extract Methods

Move generic helper methods such as constraining an index to a library. Apache Commons probably has one. This way someone doesn't have to read the code three times to infer its intended purpose (versus what it actually does). Here index makes more sense without a context.

constrain(index, size)
    return Math.max(0, Math.min(index, size))

Separate parameter checking from the raw search algorithm when either is long enough.

findBoyerMore(needle, haystack, start)
    for index in boyerMoore(needle, haystack)
        if index >= start
            return index
    return -1

Extract a method to test if needle can fit inside haystack at start.

Also, you can fail fast in the case of myIndexOf("foo", "foobar", 5) without calling boyerMoore even though foo is shorter than foobar. Take start into consideration when comparing the length of the two strings.

canFitAt(needle, haystack, start)
    return start + needle.length <= haystack.length

Dead Code

Since index >= 0 and index < 0 cannot both fail, if (substr.length == 0 && str.length == 0) cannot succeed and can be removed.

End Result

Combining all of the above gives us a much-simplified method.

myIndexOf(needle, haystack, start)
    if canFitAt(needle, haystack, start)
        return findBoyerMoore(needle, haystack, start)
    else
        return constrain(start, haystack.length)


Your script isn't bad. But there is always room for improvement:

It's bad to mix tabs and spaces.  The fact that your code broke when you pasted it here shows why.  Good editors have a setting that will help you with this.  (It is recommended that you use spaces only.)
You don't need sys.exit(0) at the end of your script, since Python will exit automatically when it reaches the end.
Choose your variable names carefully. rand is not very descriptive and firstguess is plain incorrect (every guess, not just the first, gets assigned to this variable).
Don't repeat yourself.  Don't write ["Heads", "Tails"] twice, because if you have to change it for whatever reason, you have to remember to change it in two places.  Store it in a variable.
You can simplify this:

if answer == "Yes":
    pass
else:
    break

To this:

if answer != "Yes":
    break

I don't know easygui, but it seems you should use a
ynbox
when you're asking "yes or no?".  So you can change this:

answer = easygui.buttonbox("Play again?", choices=["Yes","No"])
if answer != "Yes":
    break

To this:

play_again = easygui.ynbox("Play again?")
if not play_again:
    break

Or simply:

if not easygui.ynbox("Play again?"):
    break

With all the changes made and after applying the rules from the the Python style guide PEP8, your code looks like this:

import random    # alphabetic order
import time

import easygui    # third-party modules after standard-library modules

CHOICES = ["Heads", "Tails"]    # ALL_CAPS for variables whose value never changes

while True:
    result = random.choice(CHOICES)
    guess = easygui.buttonbox("Pick one", choices=CHOICES)
    if guess == result:
        easygui.msgbox("Wow you win!")
    else:
        easygui.msgbox("Sorry you guessed wrong!")
    time.sleep(2)
    if not easygui.ynbox("Play again?"):
        break

easygui.msgbox("Ok, see you later!")


While others may have more specific suggestions related to the code, here are my observations:

If you're writing this as a Unix filter, make it Unix-y: instead of calling a function rot13, perhaps call it caesar_cipher() and use \$n\$th rotation. This would follow the idea by which Unix systems are characterized: modularity.
With modularity: while in the modern age it is safe to assume most systems have contiguous a-z and A-Z character encoding, a solution which accommodates EBCDIC and other locales than C is worth considering.
Because you're writing a Unix filter, I would look at the source code for GNU implementations of Unix filters (ie head, tail, uniq) to see how they deal with operations on files and error handling (specifically what types of errors could occur with Unix filters).
Ensure you are correctly checking if files exist, permissions, etc. Referencing GNU utils is helpful here as well.
Prefer fputc() instead of fprintf(): you're just printing a character to a stream.

Those are my thoughts. Some of these things you may have already considered, but I hope this was helpful.


Appending objects to an array based on a field

If $statement contains a huge amount of data

I'm assuming the 6500 records are in the $statement iterator, and that the $statement iterator somehow will fetch data from a database.

Just removing the iterator_to_array statement in the first line can increase the speed a lot. If it's coming from a database query, it will first load ALL queries into memory, which you will read afterwards in your foreach loop.

Since you don't actually use the array for anything other than doing a foreach, this might speed up the results, because the data will only be fetched per-line in the foreach loop, rather than first fetching everything, and then looping over it.

Watch out with your array_* methods

You're using the array* methods heavily. While this is nice and short, I think you're missing some complexity going on in using the methods.

You're looking up all values in the array of $items for every item in $statements, while looking up all id's in the array of items.

This is a worst-case complexity of [Amount of statements]*[Amount of items]*2

Which you could easily reduce to a single associative array lookup.

Since $items is not changing inside the loop, you can safely make a single version of $items:

Here you're trying to lookup if the id exists in a property of statement:

if (!$obj = array_search($statement->depositorId(), array_column($items,'id')))

Keep in mind that key lookups in PHP are a lot faster than in_array or array_search lookups (they're the same in this case).

Basically in_array is this:

function in_array($array, $item)
    foreach ($array as $arrayItem)
    {
         if ($arrayItem == $array)
         {
              return true;
         }
    }
    return false;
 }

You could optimize this by first creating an associative array of all keys (once, outside the foreach loop):

foreach ($items as $subItem)
{
    $idIndex[$subItem] = $subItem;
}

You can also cache this information if you're calling this method multiple times.

And then checking inside your foreach loop:

if (!isset($idIndex[$statement->depositorId()])) {
    continue;
}

The cost of a lookup in $idIndex will alway be 1, and worst-case scenario of the lookup cost you're doing now will be 2n the amount of items in $items (e.g. ), because you will iterate $items twice each row.

Watch out with your array_* calls, part 2

Exactly the same principle applies to this part:

And here you're trying to look up if an id exists in $balancesPerAccount[$accountType]

$balancePerDepositor = array_search($obj['id'],
    array_map(function($object) {
        return $object->depositorId();
    },
    $balancesPerAccount[$accountType]
)

Since this a simple lookup, I would really recommend building an index of all balancedPerAccount once, and then checking with isset() if it exists, rather than looping over each item in a doubly nested array.

I would recommend doing an exercise of writing all array_* methods by hand using foreach or for loops, then it will become obvious what these methods are doing.

Unsolicited advise: Style, comments, variable names, reusing variable names

This will not affect speed that much, but I generally recommend overwriting variables with a different kind of Object.
For example:

$items = json_decode(json_encode($items), true);

and

$obj = $items[$obj];

I would avoid this because

It's confusing to debug and test (obj used to be an int and now it's an object)
It becomes hard to read (what is actually the input and output of this method?)

PHP Doc
Also, depending on the objects, there's a lot of undocumented coding going on (documented by debugging). It's almost impossible to figure out what's happening without actually debugging the code. Make sure to use php annotations to describe what's inside the objects or arrays.

Variable naming

$items
$statement
$params
$order

Are all horribly generic in this case. If there are very clear comments on what they contain, this may not be a problem, but I would try using a bit more descriptive variable names.


Your code is quite complicated. What makes it so complicated is that you have recursive calls interacting with global objects. This makes it almost impossible to understand what the state is at a given point.

When you write an algorithm in a recursive way, your goal should be to make the (smallest amount of) information go in one direction only through the method parameters (and no global state whatsoever) and to use return values to give the answer back.

This being said, let's try to see how to make this work.

This idea is quite simple here:

If I have to reach 59 with 1, 2, 5, 10, 20, I can try to take 0 time 20 and see how I can reach 59 with 1, 2, 5, 10. I can also try to take 1 time 20 and see how I can reach the remaining 39 with 1, 2, 5, 10. I can also try to take 2 times 20 and see how I can reach 19 with the remaining 1, 2, 5, 10.

I've reduced solving the problem to the resolution of smaller (because we have a smaller number of coins) problems. The question is "when should I stop ?". If you have reached the target, you can stop. If you have no coin left to try, you can stop;

Once expressing this with code, you can write:

import java.util.ArrayList;
import java.util.Arrays;

public class coinsSum {
    public static final int TARGET = 59;

    public static void main(String[] args) {
        long start = System.nanoTime();

        int[] validCoins = new int[] {1, 2, 5, 10, 20};
        Arrays.sort(validCoins);

        int min = permutations(TARGET, validCoins);
        System.out.println("TOOK: " + (System.nanoTime() - start) / 1000000 + "ms to find " + min);
    }

    public static int permutations(int target, int[] coins) {
        return permutations(target, coins, coins.length);
    }

    public static int permutations(int target, int[] coins, int array_size) {
        System.out.println("TRYING " + target + " with " + array_size + " different coins");
        assert target >= 0;
        assert array_size >= 0;
        assert array_size <= coins.length;
        if (target==0) // target is reached (in 0 coin)
            return 0;
        if (array_size == 0) // no more coins to reach a positive target
            return -1;
        array_size--;
        int coin = coins[array_size]; // let's consider the biggest coin
        int nb = target/coin; // and check how many times it fits in the target
        int sol = -1; // we haven't found a solution so far (Integer.MAX_VALUE would be another way to do this)
        for (int i = 0; i <= nb; i++) // let's try all possible values
        {
            // to check if we can reach the target with the other coins
            int sol_cand = permutations(target - i * coin, coins, array_size);
            if (sol_cand >= 0) // if we did
            {
                if (sol == -1 || sol_cand + i < sol) // and the new solution is better
                    sol = sol_cand + i; // then we are happy
            }
        }
        return sol;
    }
}

This is already 24 times faster than your example.

Now, you can try to add optimisations. A simple optimisation is to say that if you can reach the current target with the biggest coin, there's no need to go any further because you'll need more coins if you use smaller coins.

    int coin = coins[array_size]; // let's consider the biggest coin
    int nb = target/coin; // and check how many times it fits in the target
    if (nb * coin == target) // if it fits an exact number of time, we won't beat this
        return nb;

This makes the code 70 times faster on the example. (If you do so, the check that target == 0 is not relevant anymore because we'll always have target > 0).

Also, not a particular optimisation but if you want to use with Integer.MAX_VALUE just like you used to, you can rewrite the loop:

    int sol = Integer.MAX_VALUE; // we haven't found a solution so far (Integer.MAX_VALUE would be another way to do this)
    for (int i = 0; i <= nb; i++) // let's try all possible values
    {
        sol = Math.min(sol, i + permutations(target - i * coin, coins, array_size));
    }

This is as simple as it gets. Then, you can write unit tests to check that your code behaves the way you want. Finally, if you want to, you can consider various optimisations: using a cache to avoid computing the same thing multiple times, add conditions to stop the loop earlier, etc.


Project Euler # 21 amicable numbers Python

Readability / maintainability

def get_sum_amicable(n, divs={2:1}):
    """Yields amicables below n."""
    for number1 in range(n):
        for number2 in range(number1):
            try:
                if divs[number2] == number1 and divs[number1] == number2:
                    yield number1
                    yield number2
            except KeyError:
                divs[number1] = sum(get_divisors(number1))
                divs[number2] = sum(get_divisors(number2))
                if divs[number2] == number1 and divs[number1] == number2:
                    yield number1
                    yield number2

This is awful. It violates the rule "Don't Repeat Yourself"; it expects exceptions as part of non-exceptional flow; and it relies on an obscure language feature/mis-feature.

All you need to do is sum numbers x in range(n) (or, perhaps better, range(2, n), to avoid complications around 0 and 1) for which d(x) < n and d(d(x)) == x. (And given the way the question is phrased, you might assume that there will be no amicable pair which is split around n, so the first half of the test is probably unnecessary). That's a one-liner.

If you want to cache d, instead of using default values you can use functools.lru_cache. But...

Performance

Whenever you're doing divisibility checks on every number from 1 to n, you should think about using a sieve. Either build an array of one prime factor of each number, and work from that, or (where appropriate) inline the calculation into the sieve processing.

It's fairly easy to adapt the sieve of Eratosthenes to generate an array of d efficiently using the inline approach.


Time and Space Complexity of Prime factorization

isPrime()

Complexity

This function contains a simple loop that iterates up to Math.sqrt(number) times, so assuming Math.sqrt(...) can be computed in \$O(1)\$ time, the function has \$O(\sqrt N)\$ time complexity.

Review

This function is terribly inefficient. Math.sqrt(number) is computed \$\lfloor \sqrt N \rfloor\$ times, yet the value is a constant.  This should be moved out of the loop.

The function fails when given a negative number.  The square-root is returned as NaN, the for loop executes zero times, and true is returned.

2 is the only even prime number.  It can easily be called out as a special case (like you are doing for 0 and 1, allowing the for loop to consider only odd numbers starting at 3, which should cut the function time in half.

Main Function - Outer loop

Complexity

Consider this loop:

    for (int nextPrime = 2; nextPrime < number; nextPrime = getNextPrimeNumber(nextPrime)) {
        ...
    }

The getNextPrimeNumber(int number) is a simple function which increments a number by one, and tests whether or not it is prime.  These two can be combined into an equivalent simpler loop, which is easier to reason about:

    for (int nextPrime = 2; nextPrime < number; nextPrime++) {
        if (isPrime(nextPrime)) {
            ...
        }
    }

Now, we can see that this loop iterates number - 2 times, so isPrime(nextPrime) is called number - 2 times.  This gives us a time complexity of \$O(N^{3/2})\$ without considering the inner loop.

Inner Loop

Complexity

The inner statement (the while loop) is executed for each prime number the outer loop finds.  From the Prime Number Theorem, we know that the number of primes \$π(N)\$ is approximately \$\frac{N}{\log N}\$.

Since the while loop is dividing the number by a constant factor, p, the prime number from the outer loop, it will execute a maximum of \$log_{p} N\$ times.  After each division, isPrime(number) is called.  This means \$log N\$ executions of a \$O(\sqrt N)\$ algorithm, so the inner statement is \$O(\log N \sqrt N)\$.

Executed for each prime number, this gives \$O(\frac{N}{\log N} \log N \sqrt N)\$, or \$O(N^{3/2})\$.

Since both portions have \$O(N^{3/2})\$ complexity, the overall complexity is \$O(N^{3/2})\$.

Review

The trial division while(number % nextPrime == 0) loop will exit once all of the factors of nextPrime have been divided out of number.  isPrime(number) can't become true while more than one factor of nextPrime exist, and since isPrime() is an "expensive" \$O(\log N)\$ operation, it would be more efficient to remove as many multiples of nextPrime as possible, and only then checking if the resulting number is prime.  In short, when the while loop executes one or more iterations, the isPrime() should execute once, but if the while loop executes 0 times, isPrime() shouldn't be executed at all.

Overall

You've separated isPrime() out from determining the factors of number, but isPrime() determines whether a number is prime or not by doing trial divisions, and you need to do trial divisions to remove factors from number.  One function which does both operations would be more efficient:

divide out as many factors of 2 as possible
starting with a divisor of 3, and increasing by 2:

if number can be divided by the divisor:
repeat as many times as possible:

number /= divisor

stop, if number < divisor * divisor

if stopped, and number > 1:

number is last factor


There is not much to comment on. In general the code looks fine.

I can only suggest making the return shorter by using the ?? (coalesce) operator

return clientService.GetAPI(query) ?? new ArinResponse();

and perhaps you should also consider using dependency injection for the HttpClientService.


Create a dictionary from a list of key and multi list of values in Python

One alternative approach is to take advantage of enumerate() -- which allows
you to iterate over what could be thought of as a zip() of a list's indexes and
values. To my eye, this version seems a bit clearer and simpler.
days = ['MON', 'TUE', 'WED', 'THU', 'FRI']

d = {
    day : [
        (5 + i * 14) + (j * 3)
        for j in range(4)
    ]
    for i, day in enumerate(days)
}

print(d)


Better importation of variables from .txt file

Storing the data in 18 independent variables is awkward.  The naming of your variables suggests that each group of six doubles represents an object, which I've called a Sexdoublet.

Throwing all the code into main() is poor practice; there should be a function to do the importing.  It should accept an istream parameter and return a vector of Sexdoublets.

I don't know what you were hoping to accomplish with if (!ifs) ifs >> trash; — if the ifstream is bad then you shouldn't try reading from it.

Hard-coding the filename is probably a bad idea.  I've used the convention of reading from either a file that is specified on the command line, or from standard input otherwise.

#include <fstream>
#include <iostream>
#include <string.h>
#include <vector>

/* A struct of six doubles */
struct Sexdoublet {
    double x, y, d, m, c, t;

    friend std::istream &operator>>(std::istream &in, Sexdoublet &r) {
        return in >> r.x >> r.y >> r.d >> r.m >> r.c >> r.t;
    }

    friend std::ostream &operator<<(std::ostream &out, const Sexdoublet &r) {
        return out << "[ x = " << r.x
                   << ", y = " << r.y
                   << ", d = " << r.d
                   << ", m = " << r.m
                   << ", c = " << r.c
                   << ", t = " << r.t << " ]";
    }
};

std::vector<Sexdoublet> import(std::istream &in) {
    std::vector<Sexdoublet> data;
    Sexdoublet s;
    while (in >> s) {
        data.push_back(s);
    }
    return data;
}

int main(int argc, char *argv[]) {
    // If the first command-line argument is not "-", treat it as the filename
    // from which to read the input.  Otherwise, read from STDIN.
    const char *filename = (argc >= 2 && 0 != strcmp("-", argv[1])) ?
                                argv[1] : NULL;
    std::ifstream f;
    std::istream &in = filename ? (f.open(filename), f) : std::cin;
    if (!f) {
        std::cerr << "Error opening " << filename << ": "
                  << strerror(errno) << std::endl;
        return 1;
    }

    std::vector<Sexdoublet> data = import(in);
    std::for_each(data.begin(), data.end(), [](const Sexdoublet &s) {
        std::cout << s << std::endl;
    });
    return 0;
}


All of this:

def get_tokens_for_model(cleaned_tokens_list):
    final_token_list = []
    for token in cleaned_tokens_list:
        token_dict = {}
        token_dict.update({token : True})
        final_token_list.append(token_dict)
    return final_token_list

positive_tokens_for_model = get_tokens_for_model(positive_lexicon)
negative_tokens_for_model = get_tokens_for_model(negative_lexicon)

positive_dataset = [(token, "Positive")
                     for token in positive_tokens_for_model]

negative_dataset = [(token, "Negative")
                     for token in negative_tokens_for_model]

dataset = positive_dataset + negative_dataset
#shuffle dataset
for i in range(len(dataset)-1, 0, -1):
    j = random.randint(0, i + 1)
    dataset[i], dataset[j] = dataset[j], dataset[i]

Is just a very verbose way to write:

dataset = [({token : True}, "Positive") for token in positive_lexicon]
dataset.extend([({token : True}, "Negative") for token in negative_lexicon])
random.shuffle(dataset)

The shuffling probabilities might be a bit different, though. random.shuffle basically has for each element equal probability to end up at any index. I think your method has a bias, but I'm not quite sure.

At least your custom shuffling seems to be unbiased:

However, I had to fix it to this, because otherwise it raises an IndexError, because random.randint is inclusive of the end (in contrast to range, slices and random.randrange):

#shuffle dataset
for i in range(len(dataset)-1, 0, -1):
    j = random.randint(0, i)
    dataset[i], dataset[j] = dataset[j], dataset[i]


Speed up position check for embedded length on stream

I agree with the comments that it's not likely to be your position checking code that's slowing you down.  Maybe you could squeeze some performance out with unsafe code, but that's maybe saving a copy from one buffer to another.  It would be nice to put that reading loop into a separate function, something like:

byte[] ReadBytes(SomeType tt1, int bytesToRead);

I can't guess what type tt1 is, but is it possible that retrieving the value for Connected is slow?  What about GetStream?


Print = print;
WebClient webClient = new WebClient();
Print("downloading page");
string urlWithoutNewLineCharacters = StripNewLineCharactersAndSpaces(url);
string html = webClient.DownloadString(urlWithoutNewLineCharacters);
_document = new HtmlDocument();
_document.LoadHtml(html);
Print("loading page");

You are doing too much in your constructor. Consider extracting some of this code into separate method(s) maybe an intitialize() method or buildDocument() method. The rule for this is know as Coding at Wrong Level of Abstraction.

Your method StripNewLineCharactersAndSpaces should be called right after the first time it is used not at the end of your class. this is known as Vertical Separation This allows reads to quickly ready your code without having to bounce around too much.

I do Like that you have kept your methods really small


You could help us by providing the output of the profiler:

Rprof(tmp <- tempfile())
RESA <- MAL(1, 2)
Rprof()
summaryRprof(tmp)
unlink(tmp)

, but I suspect the main bottleneck in your code is the use of parallel loops in TB and S, for operations that can be done faster using vectorized R functions. Please give this a try and let us know if it is faster for you:

G  <- function(p)    p^4*(15-4*p-((10*p^2)/(1-2*p*(1-p))))
d  <- function(p, q) p*q*(1-(p*(1-q)+(1-p)*q))^-1
TB <- function(p, q) sum(A[,1] * p^A[,2] * (1-p)^A[,3] *
                         q^A[,4] * (1-q)^A[,5] * d(p,q)^A[,6])
S  <- function(p, q) {
   Gp <- G(p)
   Gq <- G(q)
   sum(B[,1] * Gp^B[,2] * (1-Gp)^B[,3] * Gq^B[,4] * (1-Gq)^B[,5] *
      (Gp*Gq+(Gp*(1-Gq)+(1-Gp)*Gq)*TB(p,q))^B[,6])
}
M3 <- function(p, q) {
   s <- S(p,q)
   s^2*(1+2*(1-s))
}
DELTA_AB <- function(spwAC,rpwAC,spwBC,rpwBC) (spwAC-(1-rpwAC)) -
                                              (spwBC-(1-rpwBC))
PR <- function(spwAC,rpwAC,spwBC,rpwBC) {
   D <- DELTA_AB(spwAC, rpwAC, spwBC, rpwBC)
  (M3(p = 0.6 + D, q = (1 - 0.6)) +
   M3(p = 0.6, q = 1 - (0.6 - D))) / 2
}


Split dictionary of lists into two dicts based on binary values

You should indent with 4 spaces, as per PEP8.

You can move your if out of the inner loop, and use enumerate, leading to a ~9% speed up.

def split_d(d, key):
    include = defaultdict(list)
    exclude = defaultdict(list)
    for i, binary in enumerate(d[key]):
        if binary == 1:
            output = include
        elif binary == 0:
            output = exclude
        else:
            raise ValueError(f"Key {key} is not binary. Expected values 0 or 1")

        for k, v in d.items():
            if k == key:
                continue
            output[k].append(v[i])

    return include, exclude

You can also remove key from d and add it back when you've gone through both the loops. Leading to a further ~5% speed up.

def split_d(d, key):
    include = defaultdict(list)
    exclude = defaultdict(list)
    keys = d.pop(key)
    try:
        for i, binary in enumerate(keys):
            if binary == 1:
                output = include
            elif not binary:
                output = exclude
            else:
                raise ValueError(f"Key {key} is not binary. Expected values 0 or 1")

            for k, v in d.items():
                output[k].append(v[i])
    finally:
        d[key] = keys
    return include, exclude

Other than the above your code looks good and I don't think there is any way to increase the performance in vanilla Python. And so if this is not fast enough then looking into NumPy would be the best thing next.


Displaying a city name with concatenations

A model should not have presentation logic, and be mostly about containing data. The text "You are from ..." Doesn't belong in a model. As it is, your model includes logic that concerns representation, and so you're violating MVC. You could use another class to be in charge of formatting a Model instance. In other words, it would be best if your Model just contained fields and did nothing else. Furthermore, all fields can be private final, for example:

public class City {

    private final String name;

    public City(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }
}

I removed the other fields which seemed quite pointless for a model.
And I renamed Model to City, because "Model" is way too abstract and not useful.

In the activity it's strange to create fields when you only use them in onCreate.
It's best to limit variables to the smallest scope necessary.
As such, all these fields should be local variables in onCreate, like this:

EditText input = (EditText) findViewById(R.id.vInput);
TextView output = (TextView) findViewById(R.id.vOutput);
Button control = (Button) findViewById(R.id.vControl);

These names are terrible by the way.
(Now I realize your question may have been rather hypothetical, not a real program.)
Give them better names.


Java code to delete comments from an input string

Advice 1

newString += m.replaceAll("");

This is inefficient. Use StringBuilder for literally building the strings. Your approach works, but if you += \$n\$ characters one at a time, the time complexity is \$\Theta(n^2)\$. With StringBuilder it would be \$\Theta(n)\$.

Alternative implementation

The following is by no means a suggested implementation, but rather a starting point:

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {

    public static String deleteComments2(String str) {
        StringBuilder sb = new StringBuilder(str.length());
        boolean inText = false;
        char previousCharacter = '\u0000';

        for (int i = 0; i < str.length(); ++i) {
            char currentCharacter = str.charAt(i);

            if (inText) {
                if (currentCharacter == '\"' && previousCharacter != '\\') {
                    inText = false;
                }
            } else {
                if (currentCharacter == '\"') {
                    if (previousCharacter == '\\') {
                        throw new RuntimeException("bad syntax");
                    }

                    inText = true;
                }

                if (currentCharacter == '/' && previousCharacter == '/') {
                    sb.deleteCharAt(sb.length() - 1);
                    break;
                }
            }

            sb.append(currentCharacter);
            previousCharacter = currentCharacter;
        }

        return sb.toString();
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        while (true) {
            String str = scanner.nextLine();

            if (str.equals("quit")) {
                break;
            }

            System.out.println("1> " + deleteComments(str));
            System.out.println("2> " + deleteComments2(str));
            System.out.println("---");
        }
    }

    public static String deleteComments(String myString) {
        String newString = "";

        if (myString.contains("\"")) {
            if (myString.indexOf("\"") != 0) {

                String[] stringParts = myString.split("\"");

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

                    if ((i & 1) == 0) {
                        Pattern commentaryPattern = Pattern.compile("(/\\*((.|\n)*?)\\*/)|//.*");

                        Matcher m = commentaryPattern.matcher(stringParts[i]);

                        newString += m.replaceAll("");
                    } else {
                        newString += "\"" + stringParts[i] + "\"";
                    }
                }
            }
        } else {
            Pattern commentaryPattern = Pattern.compile("(/\\*((.|\n)*?)\\*/)|//.*");

            Matcher m = commentaryPattern.matcher(myString);

            newString += m.replaceAll("");
        }

        return newString;
    }
}


You can create your own Attribute to decorate all of your classes (e.g., Plus, ConsoleHelp, Minus, Divide, and even Exit).  In the sample below, the attribute is called SystemCommandAttribute.  It would require to specify what the name of the command would be as a constructor parameter (what the user would have to type on the command line).

The next step would be to have each of your command classes implement the same interface.  In the example code I used the name ISystemCommand.  That interface should have a single method:  Execute().  That way we know what to call when we want to invoke the command.

Then you can use reflection to search for all classes that have that attribute and load them into a dictionary of string to ISystemCommand.  The GetCommandsFromAssemblies() method handles instantiating each instance of ISystemCommand for you.

From there you can use the dictionary instead of the switch statement.

public class Program
{
    static void Main(string[] args)
    {
        Dictionary<string, ISystemCommand> commandToType = GetCommandsFromAssemblies();
        RunCommandLoop(commandToType);
    }

    /// <summary>
    /// Loop over all types currently loaded in the AppDomain looking for ISystemCommand
    /// </summary>
    /// <returns>A dictionary from command name to instance of command</returns>
    private static Dictionary<string, ISystemCommand> GetCommandsFromAssemblies()
    {
        var typesWithMyAttribute =
            from a in AppDomain.CurrentDomain.GetAssemblies()
            from t in a.GetTypes()
            let attributes = t.GetCustomAttributes(typeof(SystemCommandAttribute), true)
            where attributes != null && attributes.Length > 0
            select new
            {
                Instance = (ISystemCommand)Activator.CreateInstance(t),
                CommandName = attributes.Cast<SystemCommandAttribute>().Single().CommandName
            };

        Dictionary<string, ISystemCommand> commandToType = typesWithMyAttribute.ToDictionary(t => t.CommandName, t => t.Instance);

        return commandToType;
    }

    private static void RunCommandLoop(Dictionary<string, ISystemCommand> actions)
    {
        while (true)
        {
            Console.Write("command> ");
            string com = Console.ReadLine();
            if (com != null)
            {
                ISystemCommand action;

                if (actions.TryGetValue(com, out action))
                {
                    action.Execute();
                }
                else
                {
                    Console.WriteLine("The command is not supported. Enter one of the valid commands.");
                    break;
                }
            }
        }
        Console.ReadLine();
    }
}

public interface ISystemCommand
{
    void Execute();
}

public class SystemCommandAttribute : Attribute
{
    public SystemCommandAttribute(string commandName)
    {
        CommandName = commandName;
    }

    public string CommandName { get; set; }
}

[SystemCommand("plus")]
public class Plus : ISystemCommand
{
    public void Execute()
    {
        Sum();
    }

    private void Sum()
    {
        // your existing Sum logic here
        Console.WriteLine("Sum called");
    }
}

[SystemCommand("?")]
public class ConsoleHelp : ISystemCommand
{
    public void Execute()
    {
        Helper();
    }

    private void Helper()
    {
        // your existing Helper logic here
        Console.WriteLine("Helper called");
    }
}

[SystemCommand("c")]
public class ExitCommand : ISystemCommand
{
    public void Execute()
    {
        Environment.Exit(0);
    }
}

To add a new command in the future, all you would need to do would be to

create your command class
Inherit from ISystmeCommand
Add the SystmCommandAttribute

Your main program would not need to change at all.


Style

I suggest you check PEP0008 https://www.python.org/dev/peps/pep-0008/ the official Python style guide while writing your code and the following goes accordingly:

Docstrings: Python Docstring is the documentation string which is string literal, and it occurs in the class, module, function or method definition, and it is written as a first statement. Docstrings are accessible from the doc attribute for any of the Python object and also with the built-in help() function can come in handy. I suggest you include docstrings to your functions indicating what they do and what they return instead of writing a comment above each function.
Python naming conventions:

def getCombinations(elementTupleParam, rParam):

def partialCombinations(prevTuple, prevVisitedIndex):

Function names should be lowercase, with words separated
by underscores as necessary to improve readability same goes for
parameter names.
Descriptive variable names: thisIndex thisTuple prevTuple are examples of bad non-descriptive names. Names should reflect the significance of the variable/function/parameter they represent and the less ambiguous they are, the more readable is your code.

Code

Global variables: are bad in Python and programming languages in general and are advised against. I suggest enclosing variables inside functions. The reason they are bad that they may allow functions to have hidden/hard to detect side effects leading to an increased complexity potentially leading to Spaghetti code. Examples of good use of global variables include: algorithm optimization - caching and memoization.
There is a built-in Python library itertools that does the same functionality using itertools.combinations() which saves you the effort of implementing the thing yourself.

Code can be shortened into the following:
And according to GZO's comment, there is no need for the warpper function get_combinations(), use combinations() directly. I included it just for the sake of the example.

from itertools import combinations

def get_combinations(n: list, r: int):
    """Return combinations iterator."""
    return combinations(n, r)

if __name__ == '__main__':
    print(list(get_combinations([2, 3, 4], 2)))

Check these references(regarding global variables):

https://softwareengineering.stackexchange.com/questions/148108/why-is-global-state-so-evil
https://stackoverflow.com/questions/19158339/why-are-global-variables-evil


C function that emulates string concatenation operator '+' in Python or Go

It looks like this code needs a couple of headers to be included before it will compile:
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>

It also only works on platforms that have strdup().  It would be easy to make it more portable.
If s is a null pointer, then we have undefined behaviour, but we haven't indicated that we don't allow a null for the first argument.
Why are we not testing whether strdup() returns a null pointer?
Well done for avoiding the common hazard with realloc().  Too many C programmers fail to deal properly with allocation failure.  The scope of ptr could be reduced so that we declare and initialise together, and we don't need to multiply by sizeof (char) (which must be 1, by definition):
char *ptr = realloc(return_string, realsize + 1);

The use of strncat() in a loop is wasteful, since it starts from the beginning every time.  Since we know where the string ends, it's better to start from that position.
The algorithm could be much more efficient.  Instead of many realloc() calls, we could make two passes over the arguments: one to measure the total size, and one to copy the characters across.
Compare this extract from a Valgrind run of the code:
==25527== HEAP SUMMARY:
==25527==     in use at exit: 0 bytes in 0 blocks
==25527==   total heap usage: 5 allocs, 5 frees, 1,063 bytes allocated

against the two-pass version that doesn't need to realloc:
==24899== HEAP SUMMARY:
==24899==     in use at exit: 0 bytes in 0 blocks
==24899==   total heap usage: 2 allocs, 2 frees, 1,037 bytes allocated

That's fewer than half the allocations for a very simple "Hello World" test program:
char *mutant_string (const char *s, ...);

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

int main(void)
{
    char *s = mutant_string("Hello", " ", "World", "!", NULL);
    if (!s) {
        return 1;
    }
    puts(s);
    free(s);
}

Here's what the two-pass version looks like:
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>

char *mutant_string(const char *s, ...)
{
    if (!s) {
        return NULL;
        /* alternatively - return a new, empty string */
    }

    va_list argv;

    /* First pass - measure the total length */
    size_t total_len = strlen(s);
    va_start(argv, s);
    const char *c;
    while ((c = va_arg(argv, const char*))) {
        total_len += strlen(c);
    }
    va_end(argv);

    char *buf = malloc(total_len + 1);
    if (!buf) {
        return buf;
    }

    /* Second pass - copy the string data */
    char *p = buf;
    {
        /* first argument */
        size_t len = strlen(s);
        memcpy(p, s, len);
        p += len;
    }

    /* other arguments */
    va_start(argv, s);
    while ((c = va_arg(argv, const char*))) {
        size_t len = strlen(c);
        memcpy(p, c, len);
        p += len;
    }
    va_end(argv);
    *p = '\0';

    return buf;
}


Queues are not designed to be used like this.  Your iterable_queue clearly shows that you are not using queues the way they are supposed to be used.  And the checkValidity function should be simplified with std::is_sorted from the standard library.  In q.empty() || q.size() <= 1, the first condition is subsumed by the second.  The while(q.size()){ loop also seems to have no significance.  ++q.end() is also undefined behavior.  The bool_cast functionality is already provided by std::boolalpha.

Overall, I think you are seriously over-complicating everything:

#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>

int main()
{
    std::vector<int> numbers;
    for (int num; std::cin >> num && num >= 0;) {
        numbers.push_back(num);
    }

    bool valid = numbers.size() > 1 && std::is_sorted(numbers.begin(), numbers.end());
    std::cout << "Valid? " << std::boolalpha << valid << '\n';

    std::cout << "{ ";
    for (int num : numbers) {
        std::cout << num << ' ';
    }
    std::cout << "}\n";
}

(live demo)


Project Euler #14 solution takes quite a long time

Consider the chains starting at 13 and 26. When you reach 26, you go over its whole chain. Later, you reach 13, and go over its whole chain too - but 13's chain is the same as 26's, only without the first number (26).

If you implemented collatzChain using recursion, just adding the decorator @functools.lru_cache would create a cache for your function, and thus prevent Python from repeating the same job twice.


Hackerrank Sparse Arrays Solution in Java

String[] stringArr = new String[n];

        for (int i = 0; i < n; i++){
                stringArr[i] = scan.next();
            }

Why use an array?  Consider

        Map<String, Integer> inputCounts = new HashMap<>(n);

        for (int i = 0; i < n; i++) {
            String input = scan.next();

            Integer count = inputCounts.get(input);
            if (count == null) {
                count = 0;
            }

            count++;
            inputCounts.put(input, count);
        }

Now you know the count for each input string.  So

                String stringQue = scan.next();

                int occNum = 0;
                for (int j = 0; j < n; j++){
                    if (stringQue.equals(stringArr[j])) occNum++;
                }
             System.out.println(occNum);

could become just

                String query = scan.next();

                Integer count = inputCounts.get(query);
                if (count == null) {
                    count = 0;
                }

                System.out.println(count);

If the overhead of the hash accesses is less than the overhead of the for loop, this might be faster.

A HashMap converts the string key into a location in the Map.  This is more expensive than a numeric array selection but is probably similar to the cost of the equals method.

I think that we can safely say that accessing the HashMap is going to be faster than iterating over every member of the array unless the array is tiny.  The larger question is if the cost of building the HashMap is going to be greater than the savings in processing the queries.  For a large number of strings and a small number of queries, the cost of building the HashMap can outweigh the savings in processing the queries.  That's trivially true if there are zero queries.  And may still be true for one query.  There is some point where it stops being true.  You'd have to benchmark to be sure.

I prefer names like query and count to stringQue and occNum.


In general, you should never handle transactions in dao code, as you never know where the transaction boundary is. You should let whoever wants to control the transactions control them.

Code that starts and commits a transaction in every dao method is likely to be problematic.

Btw: not very keen at all on 'dao' but as you use it, so will i.


A program to display, update and save a dictionary as .csv

It's a pretty good program for a beginner.

A few points:

Put your import csv once at the top of the file, not in the functions that use csv. Importing is best thought of as an action at the start of your program, not as something that happens while performing an action.

You do this a lot:

while load_answer not in yes_no:
    load_answer = generic_prompt(load_question)
if load_answer == 'yes':

Anytime you find yourself repeating code, it'd be helpful to write a function instead. Something like:

   def ask_boolean_question(prompt):
       answer = ''
       while answer not in yes_no:
           answer = generic_prompt(prompt)
       return answer == 'yes'

Now your code can simply say:

  if ask_boolean_question(load_question):

And avoid repeating the loop everytime you ask a question.

Your program doesn't make its structure very clear. Given what your program does, your main function should read something like:

def main():
    manipulate_settings(default_settings)
    while ask_boolean_question(load_question):
         filename = generic_prompt(filename_question)
         manipulate_settings(filename)

Note that by reading this, you can see the program processes first the default settings, and then as many other settings files as you have inclination to use the program.


Is my script secure to prevent email injection?

Validate, but don't change user input

Don't change the value of a user input. Either accept or reject it, but don't try to guess what might be ment. Some examples:

The name could be Søren Kierkegård, which in many evironments will become Sren Kierkegrd due to your 'sanitation'.

An email address can be much more complicated than your test suggests. How about parenthesis, exclamation or question marks? Read this for other thoughts about email validation with regular expressions.

The message still could contain 'Bcc:' or 'Cc:'. Making the expression case insensitive will lead to the next problem: The sequence "People I met in Toronto: A, B, and C." would become "People I met in Toron A, B, and C."

Escape your output instead

Header fields are restricted to a single line (each). So is the name of a person. In these cases, all whitespaces are equivalent (at least for non-malicious input), so replacing newlines and tabs with spaces does not alter the (meaning of the) content.

$name    = isset($_POST['cf_name']) ? $_POST['cf_name'] : '';
$email   = isset($_POST['cf_email']) ? $_POST['cf_email'] : '';
$message = isset($_POST['cf_message']) ? $_POST['cf_message'] : '';

$mail_status = sendMail($name, $email, $message);

function sendMail($name, $email, $message)
{
    // Whitespace pattern, icluding different masking methods
    $whitespace = '~(<CR>|<LF>|0x0A|%0A|0x0D|%0D|\\n|\\r|\s)+~i';

    $name = trim(preg_replace($whitespace, '', $name));
    if (empty($name)) {
        return false;
    }

    $email = trim(preg_replace($whitespace, ' ', $email));
    if (empty($email)) {
        return false;
    }

    $mail_to = 'admin@mywebsite.com';
    $subject = 'New Contact for My Website from ' . $name;

    $body =  "From: $name\n";
    $body .= "E-mail: $email\n";
    $body .= "Message: $message";

    $headers =  "From: $email\r\n";
    $headers .= "Reply-To: '$email\r\n";

    return mail($mail_to, $subject, $body, $headers);
}


Did you post the right code?

What is TC.messenger?

You pass two arguments in

XX.namespace.ContactListController = (function(contactListModel, view)

and you save them as members, but never use them.


Nice use of the "Curiously Recurring Template Pattern".

The trouble with your design, is that any user of your class needs to declare their own version of the s_counter. Not strictly a problem but it does make it harder to use.

I would use static function variable as the counter. That way you don't actually need to declare your own version.

    struct counter
    {
        private:
            // Should not be used by friends.
            static std::atomic<uint32_t>& getCounterInstance() {
                static std::atomic<uint32_t>  counter = 0;
                return counter;
            }
    };

As counter is a private member of countable. Nobody else can see it (let alone access it). So you don't need to make countable a friend. Just use some standard public functions to get you accesses.

template<typename t_derived>
class countable
{
    struct counter
    {
        private:
            // Should not be used by friends.
            static std::atomic<uint32_t>& getCounterInstance() {
                static std::atomic<uint32_t>  counter = 0;
                return counter;
            }

       public:
            // Handy access methods:
            static void incrementCounter() {
                ++getCounterInstance();
            }
            static void decrementCounter() {
                --getCounterInstance();
            }
    };
};

The only person that has access to incrementCounter() and decrementCounter() are members of countable.

You got the default constructor and the copy constructor.

    countable()
    {
        ++counter::s_counter;
    }

    countable(const countable&)
    {
        ++counter::s_counter;
    }

But you forgot the move constructor.

    countable(countable&&)
    {
        counter::incrementCounter();
    }


Selecting all movies where specified actors worked together

Will this do the trick?

select m.Title
from Movie m
    inner join CastMember cm on cm.MovieId = m.Id
    inner join Actor a on cm.ActorId = a.Id
where a.Name in ('John Travolta', 'Uma Thurman')
group by m.Title
having count(m.Id) > 1 -- this should be replaced with the number of items in the "in" list minus 1.