Split a file into multiple files if it reaches a particular limit?

You want to limit file size, measured in bytes.
You write records, one for each task, terminated by line.separator.
You are concerned about performance (with a limit of just 50 kB on file size - oh well).

do not encode chars more than once (with 2n (guesstimated: 50) records per file, your average char gets encoded n+1 (26) times with the second generateFile() presented)
using "old Java IO", have a FilterOutputStream tally bytes
do not use a buffered Writer: it would obscure record boundaries

giving it a try:

/** Writes a limited amount of bytes to each of
 *  a succession of files numbered from 0 where necessary.
 *  Buffers liberally. */
static class SequentialFileOutputStream extends java.io.FilterOutputStream {
    final static int MAXBUF = 1<<20;
    final byte[]buffer;
    int pos, index;
    final long limit;
    long left;
    File file;
    String path, name, suffix;
    /** Creates an OutputStream that starts writing
     *  to file, creating numbered files as necessary. */
    public
    SequentialFileOutputStream(File file, boolean append, long limit)
        throws IOException
    {
        super(null);
        File parent = (this.file = file).getParentFile();
        if (null == parent)
            parent = new File(".");
        // checks path, too
        if (parent.getFreeSpace() < limit)
            throw(new java.io.IOException("free < limit"));
        this.limit = left = limit;
        buffer = new byte[(int) Math.min(limit, MAXBUF)];
    }
    /** Closes the current part, if any. */
    void closePart() throws IOException {
        if (null != out) try {
            flush();
        } finally { try {
            out.close();
        } finally {
            out = null;
        }}
    }
    /** Finishes the current part, if any.
     * Prepares a new one as far as necessary. */
    void nextPart() throws IOException {
        closePart();
    }
    /** Ensures out is open and buffer reset. */
    void ensureOpen() throws FileNotFoundException {
        if (null != out)
            return;
        left = limit;
        pos = 0;
        if (null == suffix) {
            path = file.getPath();
            name = file.getName();
            int dot = name.lastIndexOf('.');
            if (0 <= dot) {
                suffix = name.substring(dot);
                path = path.substring(0,
                    path.length() - suffix.length()) + '_';
            } else
                suffix = "";
            out = new java.io.FileOutputStream(file);
        } else {
            if (null != file) {
                File zero = new File(path + '0' + suffix);
                zero.delete();
                file.renameTo(zero);
                file = null;
            }
            out = new java.io.FileOutputStream(path + ++index + suffix);
        }
    }
    @Override
    public void write(int b) throws IOException {
        byte[]a = { (byte) b };
        write(a, 0, a.length);
    }
    @Override
    public void write(byte[] b, int off, int len)
        throws IOException {
        if (len <= 0 || null == b)
            return;
        ensureOpen();
        if (left < len && 0 < pos) {
            flush();
            nextPart();
        }
        if (limit < len)
            out.write(b, off, len);
        else {
            System.arraycopy(b, off, buffer, pos, len);
            pos += len;
            left -= len;
        }
    }
    @Override // closePart()?
    public void flush() throws IOException {
        if (0 < pos) {
            ensureOpen();
            out.write(buffer, 0, pos);
            pos = 0;
        }
        out.flush();
    }
    @Override
    public void close() throws IOException { closePart(); }
}
private final String clientId;
private final Collection<Task> tasks;

public FileSplitter(String clientId, Collection<Task> tasks) {
    this.clientId = clientId;
    this.tasks = tasks;
}
/** Kludge to flush an OutputStreamWriter's encoder's buffer */
static class FlushWriter extends java.io.OutputStreamWriter {
    final static Class[]NO_CLASSES = {};
    static java.lang.reflect.Method flushEncoder;
    // further constructors left as an exercise
    public FlushWriter(OutputStream out) { super(out); }
    /** Flushes the encoder's buffer */
    java.io.Writer flushEncoder() {
        try {
            if (null == flushEncoder) {
                final Class<?> osWriter = FlushWriter.class.getSuperclass();
                flushEncoder = osWriter
                    .getDeclaredMethod("flushBuffer", NO_CLASSES);
                flushEncoder.setAccessible(true);
            }
            flushEncoder.invoke(this, (Object[])null);
        } catch (ReflectiveOperationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return this;
    }
}

public void generateFile() {
    String fileName = "tasks_info_" + clientId + ".txt",
        lineSeparator = System.getProperty("line.separator");
    try (FlushWriter writer = new FlushWriter(
            new SequentialFileOutputStream(
                new File(new File("."), fileName), false, 9000))) {
        for (Task task : tasks) {
            writer.append(task.toString()).append(lineSeparator);
            writer.flushEncoder();
        }
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

public static void main(String[] args) {
    Task t = new Task() {@Override public String toString() {
                return "I am the most useless task ever";
        }};
    Collection<Task>tasks = new java.util.ArrayList<>(999);
    for (int i = 999 ; 0 < --i ; )
        tasks.add(t);
    new FileSplitter("broke", tasks).generateFile();
}

The non-buffered OutputStreamWriter didn't suffice, in the end:
Sunsoft's encoder buffers. Trying to keep that from interfering messed things up.

The generateFile() from the question seems to have a correctness issue with the way it guesstimates byte count: it extends sb and accumulates "the length of byte[]s gotten from String representations of sb". It should rather

set the size to said length - or -
accumulate the "byte length" of the String for each Task
which, in combination with instantiating sb with an appropriate length, should lead to run time linear in the number of bytes in each file rather than quadratic.

But once you "have the byte[]", you might as well collect those.
This seems to call for java.nio.ByteBuffer &co:

public void generateFile() {
    ByteBuffer bb = ByteBuffer.allocate(limit);
    for (Task task : tasks) {
        byte[]taskBytes = task.toString().getBytes(
            java.nio.charset.StandardCharsets.UTF_8);
        int taskLen = taskBytes.length+LS_LENGTH;
        if (bb.remaining() < taskLen)
            buffer2file(bb, index++);
        if (limit < taskBytes.length+2*LS_LENGTH) {
            ByteBuffer big = ByteBuffer.allocate(taskLen);
            big.put(taskBytes).put(LINE_SEPARATOR_BYTES);
            buffer2file(big, index++);
        } else
            bb.put(taskBytes).put(LINE_SEPARATOR_BYTES);
    }
    buffer2file(bb, index++);
}

/** Write a numbered client file if bb not empty. */
private void buffer2file(ByteBuffer bb, int i) {
    bb.flip();
    if (bb.hasRemaining()) {
        String fileName = "tasks_info_" + clientId + "_" + i + ".txt";
        try (java.nio.channels.FileChannel
            fc = java.nio.channels.FileChannel.open(
                java.nio.file.Paths.get(fileName, NO_STRINGS),
                java.nio.file.StandardOpenOption.CREATE,
                java.nio.file.StandardOpenOption.WRITE)) {
            fc.write(bb);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    bb.flip();
}
static final String NO_STRINGS[] = {},
    LINE_SEPARATOR = System.getProperty("line.separator");
static final byte[]
    LINE_SEPARATOR_BYTES = LINE_SEPARATOR.getBytes();
static final int LS_LENGTH = LINE_SEPARATOR_BYTES.length;


This code binds your Db object to the global constants.  Its going to be difficult to connect to more than 1 database.  Your DB class isn't doing anything for you.

The solution to this is: injection.  You should pass in the settings for the Db in the constructor.  Below is the PDO class from my framework which I think is serving a similar role to what you are trying to achieve with your Db class.  The injection is achieved by accepting parameters in the constructor ($setup).

/// PDO wrapper class to ensure DB implements the Evoke Core DB interface.
class PDO extends \PDO implements \Evoke\Core\Iface\DB
{
   public function __construct(Array $setup)
   {
      $setup += array(
         'DSN'      => NULL,
         'Options'  => array(\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION),
         'Password' => NULL,
         'Username' => NULL);

      if (!isset($setup['DSN']))
      {
         throw new \InvalidArgumentException(__METHOD__ . ' requires DSN');
      }

      if (!isset($setup['Password']))
      {
         throw new \InvalidArgumentException(__METHOD__ . ' requires Password');
      }

      if (!isset($setup['Username']))
      {
         throw new \InvalidArgumentException(__METHOD__ . ' requires Username');
      }

      parent::__construct($setup['DSN'],
                          $setup['Username'],
                          $setup['Password'],
                          $setup['Options']);
   }
}

There are a number of differences with this approach:

The Db class is a Db type object (extends PDO).
Common database type functions are ensured (implements Iface\DB).
Setup for the database is injected (with the setup parameter).  This means that many databases could be connected to each with a different set of parameters injected.
Validity of the setup is enforced.

By creating an interface we can pass any type of object that implements the interface for use as our Db object.  This means our code is decoupled from the specific type of database object (I could replace PDO with mysqli very easily if I wanted to).

function index($db)
{
   if (!$db instanceof \Iface\DB)
   {
      throw new \InvalidArgumentException(__METHOD__ . ' we need a Db object.');
   }
}

Personally I have the small PDO wrapper you saw above and then a further abstraction for SQL statements.  With everything all of the dependencies are injected (normally in the constructor).  You can see more of my Db objects here.  Notice how the SQL class is injected with a Db (any sort of DB that implements the DB interface):

class SQL implements \Evoke\Core\Iface\DB
{
   protected $inTransaction = false;

   protected $setup;

   /// Class constructor
   public function __construct($setup=array())
   {
      $this->setup = array_merge(array('DB' => NULL), $setup);

      if (!$this->setup['DB'] instanceof \Evoke\Core\Iface\DB)
      {
         throw new \InvalidArgumentException(__METHOD__ . ' needs DB');
      }
   }


Not that familiar with C++, but that certainly looks like recursion to me...

The variable gcd contains a function, which then calls itself.  The very definition of recursion.

But I would ask what you gain by not making it a regular function?


Show dialog only once. Other calls should bring dialog to front, but otherwise not have a result

Shout in the dark, really...

public class DialogService : IDialogService
{
    private static readonly ConcurrentQueue<AuthenticationDialog> DialogQueue =
        new ConcurrentQueue<AuthenticationDialog>();
    private static volatile bool _isShowing;

    public DialogService(IServiceProvider serviceProvider)
    {
        DialogQueue.Enqueue(serviceProvider.GetService<AuthenticationDialog>());
    }

    public bool? ShowAuthenticationDialog()
    {
        AuthenticationDialog dialog;
        DialogQueue.TryDequeue(out dialog);

        if (dialog == null)
            return null;

        if (_isShowing)
        {
            dialog.Activate();
            return null;
        }

        _isShowing = true;
        bool? result = null;

        try
        {
            result = dialog.ShowDialog();
        }
        catch
        {}
        finally
        {
            _isShowing = false;
        }

        return result;
    }
}


Form that reveals more fields as each step has been completed

Code is pretty neat, though you might consider a couple of additional objectives :

ensuring that elements are re-disabled if the user revisits an earlier form field and makes it invalid.
allowing the validate/disable/enable system to work with as many cases as might appear in the form, without needing to amend the javascript.

I guess there are many ways these objectives could be met.

Here's one way, in which :

the key actions ('validate' and 'disable') are written as custom event handlers. That proves to be very convenient as it allows elements to be given behaviours that can be triggered en bloc without needing to write jQuery plugins or loop manually in the high level application code.
several assumptions are made about the HTML/DOM_tree, in particular that .case1, .case3, .case3 select one element each.

HTML

Add class name case to all "case" containers.

JavaScript

jQuery(function($) {
    var $cases = $('.case'),
        $finalElement = $('#subnewtide'),
        $casesPlus = $cases.add($finalElement)
        fieldSelector = 'input, select'; // a reusable selector string

    // attach event handlers to $cases
    $cases.on('validate', function(event) { // custom event
        var $this = $(this),
            n = $this.index($cases), // index of this within $cases
            valid = true;
        $casesPlus.slice(n+1).trigger('disable', [true]); // unconditionally disable everything below `this`
        $(this).find(fieldSelector).each(function() {
            if (!$(this).val()) {
                valid = false;
                return false; // break out of .each() iteration
            }
        });
        if (valid) {
            // conditionally enable next case and trigger 'validate' on it ... and so on in cascade ...
            $casesPlus.slice(n+1, n+2).trigger('disable', [false]).trigger('validate');
        }
    }).on('disable', function(event, bool) { // custom event
        if (bool) {
            $(this).addClass('disabled').find(fieldSelector).prop('disabled', true);
        } else {
            $(this).removeClass('disabled').find(fieldSelector).prop('disabled', false);
        }
    }).on('change', fieldSelector, function(event) {
        $(this).closest('.case').trigger('validate');
    });

    // attach event handlers to $finalElement
    // (slightly different from $cases)
    $finalElement.on('disable', function(event, bool) {
        $(this).prop('disabled', bool);
    });

    // initially, enable the first case and trigger 'validate' to disable everything else.
    $cases.eq(0).trigger('disable', [false]).trigger('validate');
});

untested

This style of programming tends to suit form validation and spreadsheet-like applications.


As @Brythan suggested, you should rename your variables. I propose:

arr instead of a
size instead of n
index instead of i
copy instead of b
items or elements or collection instead of c

I suppose that addAll returns a boolean to mimic the behavior of Collections.addAll. That is all well, except you're not actually implementing that behavior, only the method signature. The JavaDoc says:

  Returns:

  true if the collection changed as a result of the call

So you should change your implementation accordingly. Perhaps something like this:

public boolean addAll(int index, Collection<? extends T> items) {
    if (items.isEmpty()) {
        return false;
    }
    if (size + items.size() > arr.length) {
        resize(2 * (size + items.size()));
    }
    System.arraycopy(arr, index, arr, index + items.size(), size - index);
    for (T item : items) {
        arr[index++] = item;
    }
    size += items.size();
    return true;
}

This also includes my naming suggestions, as well as Brythan's advice to avoid calling add one by one for each element. For the resizing, I added a helper method and refactored the existing one like this:

private void resize() {
    resize(Math.max(2 * size, 1));
}

private void resize(int targetSize) {
    T[] copy = newArray(targetSize);
    System.arraycopy(arr, 0, copy, 0, size);
    arr = copy;
}

(Since I don't know what was "f" in your original f.newArray, I wrote my own newArray.)

Notice that I changed the visibility of resize to private.
This is an internal operation that shouldn't be accessible by any other class by default.

Finally, by the same logic of addAll (following existing examples), add should also return boolean: true if the collection was modified. (In your case always.)


Calculate maximum possible helpful flags for n days

You ought to check scanf return value and also that the input value is not negative. ++i please.


static int[] findDuplicates(int[] arr1, int[] arr2) {

"Duplicates" is probably not the best name here. You would expect a duplicate to occur twice in the same collection of values or objects, not at least once in two collections. Maybe findPairs would be better, however still not perfect.

You might consider using an interface like List or even Iterable for the parameter types, to be able to support different types of collections instead of just arrays.

HashMap<Integer, Integer> table = new HashMap<>();

Do you really need a HashMap? It seems like you always use 1 as value and actually just want the keys. Use HashSet in that case. Call it uniqueValuesFirstArray or similar, instead of table. Use a name that tells you what you use it for.

ArrayList<Integer> returnlist = new ArrayList<Integer>();

Call the list result or better pairwiseOccuring or duplicates, because that is what you are saving in it. The name should not imply what the code will be doing with it later, e. g. returning it.

int arr1Length = arr1.length;
int arr2Length = arr2.length;

This is obsolete. There is no reason to save these values, instead just access them directly.

// this is for the first array
for(int i=0; i<arr1Length; i++){
   int n = arr1[i];
   table.put(n, 1);
}

This comment is obsolete. The code tells you that it is for array1, even better if you improve your variable names and access the array's length directly, like for (int i=0; i < array1.length; i++). Note the spaces that I added, to make it more readable.

Saving the value in a variable an then accessing it is obsolete. Just do table.put(arr1[i], 1);.

If you use HashSet instead of HashMap, you can replace the whole loop with HashSet<Integer> uniqueValuesFirstArray = new HashSet<>(Arrays.asList(array1));

for (int i=0; i < arr2Length; i++) {
    int n = arr2[i];

    if (table.containsKey(n)) {
        returnlist.add(n);
    }
}

This is what the indentation and whitespaces in this part of your code should look like.

As above, you do not need the variable n. Just use the value from the array directly.

If you change HashMap to HashSet, replace containsKey with contains.

int[] arr = new int[returnlist.size()];

for(int i=0; i<=returnlist.size()-1; i++){
    arr[i] = returnlist.get(i);
}

This can be done much easier. Instead of the for-loop, just use returnlist.toArray(arr);. It is probably faster, and definitely shorter and more readable.


Javascript assignment as expression in fat-arrow one-liner

The only thing I think is "bad" when using the one-liner arrow is the implicit return. Whatever the expression evaluates to becomes the return value of the arrow function. In the case of promises, you should be careful when returning from within then callbacks since the return value becomes the resolved value of the promise.

Now in your case, the return value of then isn't going anywhere since the promise is not being used. So it shouldn't matter which form you should use. Therefore it should be fine.

A bigger problem is the entire snippet. You should make sure that project has a value by the time the code using it uses it or ensure that the code using it only runs after you fetch the value of project. If possible, since you have to wait for project anyways, you can make the call to get project synchronous instead.


Mapping properties between two Objects of different structure

Maybe I don't understand the question exactly, but what's stopping you from just creating a function to do the mapping, like this:

function obj1ToObj2(obj1){
    return {
        A: {
            B: obj1.a.b.c
        },
        B: {
            C: obj1.a.b.d
        }
    }
}


Is it ok to have NaN while comparing fields in JavaScript?

A blank string is not equal to null, therefore it can get through.
parseInt('') returns a NaN.
Always use parseInt() with the radix (the second parameter). In some implementations, it doesn't default to base 10 (decimal).
As much as possible, use string comparison (===, !==, etc). It's best practice.

Instead, check for a blank string. Then instead of parseInt, you can do a +.

var text = *get value*
if(text !== ''){
  var number = +text;
}


Standardizes Rows of a Pandas.DataFrame Object

Ways to improve and optimize:

function generate_standard is named too general whereas it loads concrete csv file 'solubility.csv' and processes a particular column 'SMILES'.A more maintainable and flexible way is to make the function more decoupled and unified such that it accepts an input csv file name and the crucial column name. The main purpose can be described as "aligning a specific column's values length by the longest value".Let's give a function the appropriate name with the following signature:

def align_col_length(fname, col_name):
    """Align a specified column's values length by the longest value"""
    df = pd.read_csv(fname)
    ...

finding the longest string value in SMILES column.Instead of for loop, since you are dealing with pandas which is powerful enough and allows str accessor on pd.Series objects (points to column values in our case):

  Series and Index are equipped with a set of string processing
  methods that make it easy to operate on each element of the array.
  Perhaps most importantly, these methods exclude missing/NA values
  automatically. These are accessed via the str attribute and
  generally have names matching the equivalent (scalar) built-in string
  methods

Thus, applying a flexible chain df[col_name].str.len() + pd.Series.idxmax we would be able to get the row label/position of the maximum value.Then, just easily get the column's longest value by the row position using:

longest = df.loc[df[col_name].str.len().idxmax(), col_name]

New dataframe['standard'] column with padded values. It only remains to apply a flexible one-liner using pd.Series.str.pad routine (to pad the col_name values up to width of len(longest))

The final optimized function now becomes a more concise and pandas-flavored:

import pandas as pd

def align_col_length(fname, col_name):
    """Align a specified column's values length by the longest value"""
    df = pd.read_csv(fname)
    longest = df.loc[df[col_name].str.len().idxmax(), col_name]
    df['standard'] = df[col_name].str.pad(len(longest), side='right', fillchar='0')

    return df, longest

Testing:

df, longest = align_col_length('solubility.csv', col_name='SMILES')

print('longest SMILE value:', longest)
print('*' * 30)   # just visual separator
print(df)

The output:

longest SMILE value: [Zn++].CC(c1ccccc1)c2cc(C(C)c3ccccc3)c(O)c(c2)C([O-])=O.CC(c4ccccc4)c5cc(C(C)c6ccccc6)c(O)c(c5)C([O-])=O
******************************
                                                                                SMILES  ...                                                                                standard
0  [Br-].CCCCCCCCCCCCCCCCCC[N+](C)(C)C                                                                       ...  [Br-].CCCCCCCCCCCCCCCCCC[N+](C)(C)C000000000000000000000000000000000000000000000000000000000000000000000
1  O=C1Nc2cccc3cccc1c23                                                                                ...  O=C1Nc2cccc3cccc1c23000000000000000000000000000000000000000000000000000000000000000000000000000000000000
2  [Zn++].CC(c1ccccc1)c2cc(C(C)c3ccccc3)c(O)c(c2)C([O-])=O.CC(c4ccccc4)c5cc(C(C)c6ccccc6)c(O)c(c5)C([O-])=O  ...  [Zn++].CC(c1ccccc1)c2cc(C(C)c3ccccc3)c(O)c(c2)C([O-])=O.CC(c4ccccc4)c5cc(C(C)c6ccccc6)c(O)c(c5)C([O-])=O
3  C1OC1CN(CC2CO2)c3ccc(Cc4ccc(cc4)N(CC5CO5)CC6CO6)cc3                                                       ...  C1OC1CN(CC2CO2)c3ccc(Cc4ccc(cc4)N(CC5CO5)CC6CO6)cc300000000000000000000000000000000000000000000000000000

[4 rows x 3 columns]


Comparing and counting thousands of dates converted using moment.js

If you have \$N\$ users and \$M\$ total sites, your two for loops have time complexity \$O(NM)\$. This is a bit high when \$N\$ and \$M\$ are on the order of a couple thousand, and probably explain your performance issues.

You are wasting a lot of time comparing sites with users with different site_url parameters. You can speed up your code to run in time \$O(N + M)\$ by doing the following:

Build a map siteMap from url values to their index in sites. That is, siteMap should satisfy siteMap[sites[i].url] = i. It is easy to construct this in \$O(M)\$ time by just looping over sites.
Omit the outer for loop over all sites. Instead, just set i in the inner for loop to siteMap[users[j].site_url]. I would also recommend renaming i to something more descriptive in this case, e.g. siteIndex.

This costs an extra \$O(M)\$ worth of space to store siteMap, but since you have multiple arrays of this size already, this shouldn't be a huge increase in memory burden.

One final note: usually it's good to make the database query do as much of the work as possible instead of filtering it out later manually in the client. One example here where you could possibly speed things up is, instead of checking that the user's time is between startDate and endDate in this JavaScript function, you should adjust your MongoDB query to just return to you the users in this range.

If you don't have the option of adjusting the MongoDB query (or this would be a bad idea for other reasons, like you need to find the answer quickly for a bunch of ranges and DB calls have high latency), then it would be a good idea to sort your users by their userSubmittedAt parameter. Then you can use a simple binary search to find the appropriate range of users in \$O(\log N)\$ time.


A big issue with your solution is that you have to repeat yourself a lot, even when you have a macro to help you. I've come up with an alternative that doesn't use macros at all, and reduces the amount of repetition, although it still is more verbose that I would like. It uses the following class, which is similar to your class encapsulate, except that it doesn't store a pointer to a setter function, but instead has virtual getter and setter functions that can be overridden in a derived class:

template<typename T>
class property
{
protected:
    T v;

    virtual const T &get(void) const {
        return v;
    }

    virtual void set(const T &o) {
        v = o;
    }

public:
    property() {}
    property(const T &v_) { set(v_); }
    property &operator=(const int &o) { set(o); return *this; }
    operator T() const { return get(); }
};

So now you can declare and use a property variable this way:

property<int> foo;
foo = 42;

When you assign a value to foo, it will call operator=(), which in turn will call the function set(). The trick is that since this is a virtual function, you can create a class or struct that inherits property<int>, and override the set() function. You can make use of the fact that you can declare a class or struct within another class or struct, and that you don't have to give them a name. It looks a bit weird at first, but it looks like this:

struct: property<int> {      // declare a nameless struct that inherits from property<>
    void set(const int &o) { // override the set() function
        ...;
    }
} bar;                       // declare a variable named foo with this type

The main problem is that while a bare property variable works perfectly fine:

property<int> foo;
foo = 42;

The moment you inherit from it, the derived class has an implicitly defined assignment operator which hides the one in the base class. To get the one from the base class back, you have to add using property::operator=; to the body of the derived class. The same goes for the constructor that takes a value.

Here is your class A converted to use class property:

template<typename T>
class A
{
public:
    struct: property<T> {
        using property::operator=; // required for assigning

        void set(const T &other) {
            std::cout << "Setting value..." << endl;
            property::set(other);
        }
    } v;

    struct: property<double> {
        using property::operator=; // required for assigning
        using property::property;  // required for initialization to explicit value

        void set(const T &gl) {
            if (gl < 0)
               property::set(0);
            else if (gl > 1)
               property::set(1);
            else
               property::set(gl);
        }
    } g = 0;
};

Another option that avoids having to add the using statements is to make the derived property struct hidden, and add a base property reference to it that is public, like so:

class example {
    struct: property<int> {
        void set(const int &o) { ... }
    } foo_;

public:
    property<int> &foo = foo_;
};

When assigning a value to foo, it doesn't know it's actually a derived class, so it will directly call operator= from the base class, which is what we want.

Perhaps the above class property can be combined with a macro that hides the verbosity. For example:

#define PROPERTY(type, setter) \
struct: property<type> { \
    using property::property; \
    using property::operator=; \
    void set(const T &value) { property::set(setter(value)); } \
}

This way, you can provide the name of a function that acts as the setter, or even a lambda. For example:

class B {
    static float invert(float x) {
        return -x;
    }

public:
    PROPERTY(float, invert) foo;
    PROPERTY(int, [](int v){ return v * v; }) bar = 0;
};

The drawback of this macro is that you can't easily use non-static member functions as getters and setters.


I have a few comments.

main takes argc/argv normally. Also start the function with the opening
brace in colum 0
Define one variable per line.
Your request for input might be better printed to stderr so that it can be
separated from program output.
Your initial loop should test for EOF. Currently it doesn't  You can test
this in the *NIX shell with (program is your executable):

/bin/echo -n "hello world" | ./program

terminate seems redundant
You can and perhaps should define loop variables in the loop (as long as
you don't need the value outside the loop):

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

The second for-loop is a little messy.  For a start it has a nested loop -
my advice is to avoid nested loops and extract the inner loop to a function.
This is not always practical, but more often than not it is useful.  In this
case, you can write a little function (eg. print_chars) that prints a
specified number of characters.
Your terminating loop can be replaced by a call to the print_chars
function.
putchar is preferable to printf("%c", ...)
while, for, if etc should be followed by a space.
Testing for ' ' might be better done using isspace, which will test for
other space-like characters too.

Here is my version, for what it is worth:

#include <stdio.h>
#include <ctype.h>

#define N 100

static inline void print_chars(const char *s, long n)
{
    for (int i = 0; i < n; ++i) {
        putchar(s[i]);
    }
}

int main(int argc, char **argv)
{
    char line[N];
    int ch; /* note that ch is an int to allow it to hold 'EOF' */
    int len = 0;

    fprintf(stderr, "Enter a sentence: ");

    while ((ch = getchar()) != EOF) {
        if (ch == '?' || ch == '.' || ch == '!' || ch == '\n' || len >= N-1) {
            break;
        }
        line[len++] = (char) ch;
    }
    line[len] = '\0';

    char *end = line + len;
    char *s = end;
    while (--s >= line) {
        if (isspace(*s)) {
            print_chars(s + 1, end - s - 1);
            putchar(*s);
            end = s;
        }
    }
    print_chars(line, end - line);
    if (ch != EOF) {
        putchar(ch);
    }
    return 0;
}


private async Task<MyResult> CheckItAsync(CheckRequest rqst, int timeout)

Never use abbreviations neither for method arguments not for variable/method/class names. A few more characters to make the name meaningful doesn't slow down the code nor does it increase the code size in a bad way. In fact you are saving yourself a lot of time if you come back in a few weeks/months to fix some bugs because you see at first glance what it is about.

MyResult Result = new MyResult()

This is a classname which doesn't tell what the class is about. Sure it will be some kind of result of some kind of operation but it neither tells what kind of result this is nor from which operation that result is coming. You could name it Result and it would have the same meaning (both times no meaning).

Variables names should be named using camelCase casing based on the .NET naming guidelines.

RemoteResponse response;

Variables should be placed as near to their usage as possible. Here you have placed this outside of the try..catch but you use it only in the try block.

Result.populate(response);

Methods should be named using PascalCase casing, hence populate should become Populate. The same is true for the other MyResult methods.

// Task timed out, populate result with timeout message
Result.timedOut(rqst.RequestNumber);

Comments should tell the reader why something is done in the way it is done. What is done should be told by the code itself using meaningful names for classes, methods, properties and variables. Furthermore comments shouldn't lie like this comment is doing. The result isn't populated with a timeout message but with the RequestNumber of the CheckRequest.

Because methodnames should be made out of verbs or verb phrases timedOut isn't a good name for a method.


Concatenate three 16-bit integers in one 64-bit integer with C++

Use a struct and a union to do what you want.  Note that this implementation is verbose and can be combined into a single declaration.  Also depending on your system architecture, you may need to pack the struct or declare the members in a different order.

typedef struct
{
  uint16_t Low;
  uint16_t Mid;
  uint16_t Hi;
  uint16_t Spare;
} Word64_t;

typedef union
{
  uint64_t Int64Val;
  Word64_t WordVal;
} Splitter_t;

Splitter_t splitter;
splitter.WordVal.Low = 0xaa;
splitter.WordVal.Mid = 0xbb;
splitter.WordVal.Hi = 0xcc;

printf("%x", splitter.Int64Val);  //should print 0xaabbcc


Functions
A more "Fortrany" way to do this might be to put calculations in their own functions,
program Calc
   implicit none
   ...
    print *, a, " + ", b, " = ", AddTwoNums(a,b)
    print *, a, " - ", b, " = ", SubTwoNums(a,b)
    print *, a, " * ", b, " = ", MultTwoNums(a,b)
    print *, a, " / ", b, " = ", DivTwoNums(a,b)
 contains
    pure function AddTwoNums(a,b) result(c)
       real, intent(in) :: a,b
       real :: c
       c = a + b
    end function AddTwoNums
    ...
 end program

where the ellipses (...) mean I'm skipping over the other details. The pure specifier gives details to the compiler that can optimize/vectorize it in some cases (probably not much it can do here, but for some more complex cases it might be useful).
Output
You might also want to specify formats for the output. Since you're using single-precision, you probably want to output the first 6-7 decimal digits,
print '(f12.6,a3,f12.6,a3,f12.6)', a," + ", b, " = ", AddTwoNums(a,b)

The f12.6 means it's a floating-point type number with 12 total digits and 6 after the decimal, a3 means it is a character string of length 3 (you can make this one simply a and let the compiler figure it out).
Precision
Single precision is nice, but you can do better; and there's a few ways how:
-ISO_FORTRAN_ENV (needs Fortran 2008 or later compiler)
Within this big module is the real32, real64, and real132 types

Kind type parameters to specify a REAL type with a storage size of 32, 64, and 128 bits. It is negative if a target platform does not support the particular kind. (Fortran 2008 or later.)

and would be used as
program Calc
   use iso_fortran_env
   real(kind=real64) :: a, b
   ...

-ISO_C_BINDING (need Fortran 2003 or later compiler)
This module is for improved compatibility with C programs/functions. Within it are C_double and C_long_double types that will match the equivalent C types. This would be used as
program Calc
   use iso_c_binding
   real(kind=c_double) :: a, b
   ...

-Kind specifier (part of the 1990 standard)
This is the default way to specify the precision without useing a module. This is done as
program Calc
   integer, parameter :: wp = selected_real_kind(15,307)
   real(kind=wp) :: a, b
   ...

where wp is typically short for "working precision" (some people choose to append an underscore in case they want to use wp as a variable). The first number in selected_real_kind is the decimal precision and the second number is the exponent range (-307 to +307). You are also not restricted to using integers associated with any particular precision (single or double) here, you can choose to use selected_real_kind(10,40), for instance. Fortran 2003 standards specify that absent values for the precision & radix are assumed to be zero.
Comments
This is general and not specific to Fortran, but I'm a big fan & proponent of comments. Even when it's absolutely trivial & blatantly obvious what is being done on the line below, it benefits you (as practice for the more complex computations) and potential future readers (so that they know what is being done & why).


Encrypting messages to be sent over a socket

gen_keys()

It's generally a bad idea to have both calculation logic and output in the same function. What if you have to move your system to somewhere you can't use print() such as a batch process or web server? Use the logging module instead, that way it can easily be redirected.
encrypt_full_message()

The problem with this one is that you are constructing many temporary string objects. Python strings don't support the append operation natively; what you're doing is throwing away the old string and constructing a new one. A better way would be to write an encrypt_and_sign_single_part() function and then this whole function would just be

def encrypt_full_message(message, _pubkey, privkey):
    return ''.join([encrypt_and_sign_single_part(part,_pubkey,privkey) for part in textwrap.wrap(message, max)])

Also why did you put the underscore before pubkey? That doesn't match the naming conventions you're using.

Similar warning about using print(). Really, check out the logging module.
decrypt_full_message()

AAAAAAAAGH! Did you even test this with a multi-part message? You're going to get n^2-n warnings for every n part-pairs!

The biggest problem is you separate the parts in two and then use the two streams separately. Python has tuples, use them. That way you only can use one loop, rather than the incorrect nested loops you have now.


Just few quick things come to my mind:

The way try/catch is used is to exit on error, which would happen anyway. Maybe you need to send some info to the user here instead.
Are you passing raw user input to the database, without validation? This would be clear security issue.
Why not if($user) instead of if($user != FALSE)?
What is the purpose to set headers and then exit without any request?


Algorithm to park cars with minimal moves

Ways you can improve your current code:

Follow PEP8, it builds consistency. Your assignments have either a space either side or no spaces. Pick one style, preferably the one with a single space either side.
You can use enumerate if you need to loop through both indexes and values of a list.
You can remove one level of indentation by inverting your if check, if flags[i] and using continue.
You can move the move_chain.add(i) and car_new_position[original_positions[i]] into the while loop.
This is by using new_pos = i, without adding it to the move_chain.
If you don't follow (4), rather than using move_chain = set(); move_chain.add(i) use move_chain = {i}.
You can move the logic for setting flags to true out of the while loop.
I prefer this as it's not needed to make the while loop work,
and so makes the code less complex.
Don't print rather than return from a function.
Changing your flags to a set can remove some code. I prefer sets, but it's probably slower.

def car_move(original_positions, new_positions):
    car_new_position = defaultdict(int)
    for i, pos in enumerate(new_positions):
        car_new_position[pos] = i
    result = []
    flags = set()
    for i in range(len(original_positions)):
        if i in flags:
            continue
        move_chain, new_pos = set(), i
        while new_pos not in move_chain:
            move_chain.add(new_pos)
            new_pos = car_new_position[original_positions[new_pos]]
        flags |= move_chain
        result.append(move_chain)
    print result

But what does your output even mean?
Take:

>>> carMove([-1,1,2,3,-1,4,5,6,-1], [-1,2,3,1,-1,5,6,4,-1])
[set([0, 8]), set([1, 2, 3]), set([8, 4]), set([5, 6, 7])]

What does this mean?
Do I have to move the cars ten times?
Do I need to notice that the set([0, 8]) is two empty car slots?
Why does the cycle 1, 2, 3 not have any empty car slots?
The output is unintuitive.
Instead, using the same idea of moving cycles you can make intuitive output.
By actually moving the cars.

Take the following:

>>> car_move([-1,1,2,3,-1,4,5,6,-1], [-1,2,3,1,-1,5,6,4,-1])
1, 1 -> 8
2, 2 -> 1
3, 3 -> 2
1, 8 -> 3
4, 5 -> 8
5, 6 -> 5
6, 7 -> 6
4, 8 -> 7
8

Sure it prints the moves, rather than returning them. But it's much simpler to understand.
Car1 moves from the first index to the eighth one. Car2 second index to first.
And there is a total of eight moves.

To make this you can:

Remove move_chain and flags, as we'll use other things.
This should get you something like:

def car_move(input, output):
    position = dict()
    for i, pos in enumerate(output):
        position[pos] = i
    for i in range(len(input)):
        if i in ...:
            continue
        new_pos = i
        while new_pos not in ...:
            new_pos = position[input[new_pos]]
    print result

Fix the conditions:

If the input and output value are the same, we'll skip that position.
While the input and output of the index are not the same.

Add a previous index and a current index to the while loop.
Add a swap function and call it in the while loop.

This function will swap the inputs, update the positions and print the swap.
We'll add a check to see if i's value is empty, if not swap it with an empty one.
Otherwise we may be swapping cars, not moving them to empty spaces.

And so should get you:

def car_move(input, output, empty=0):
    swaps = 0
    def swap(a, b):
        nonlocal swaps
        swaps += 1
        input[a], input[b] = input[b], input[a]
        position[input[a]] = a
        position[input[b]] = b
        #print(input)
        print('{0}, {1} -> {2}'.format(input[b], a, b))
    position = {
        pos: index
        for index, pos in enumerate(input)
    }
    for start in range(len(input)):
        if input[start] == output[start]:
            continue
        if input[start] != empty:
            swap(start, position[empty])
        index = start
        while output[index] != input[index]:
            prev_index = index
            index = position[output[prev_index]]
            swap(index, prev_index)
    return swaps

This is better as it finds the swaps, and adds a blank swap if needed.
It can also be changed quite easily to return an array of swaps, rather than print swaps and output the amount.
The biggest down side to my code is it requires nonlocal, a Python 3 only keyword, to increase the amount of swaps in the swap function.
But if you change it to output the actual swaps, then this is not needed.
As you can mutate a list in another scope. And would work in both Python 2 and Python 3.


I second the recommendation to invent a grammar and use a real parser.  A recursive descent parser is very easy to write, and a great place to start.  You might also have a look at a PEG (Parsing Expression Grammar).  It's almost as easy to use a PEG as it is to write a recursive descent compiler, and a PEG can parse more grammars than can a recursive descent compiler.
Here are two PEGs for Python (I haven't used either of them, so can't vouch for them):

pyPeg
parsimonious

I don't see a good reason to get the Dragon book yet.  Much of what it teaches is how to write the LEXX/YACC type tools, along with language theory.  I think it's too deep and too low level for someone who just wants to try creating a language in order to see how it's done.  If, however, you do want to dive that deep, it is a very good book.

I would, for now, steer clear of a traditional lex/yacc setup.  That's a harder road that can wait until you've had some experience with simpler schemes.  However, if you do want to go there, PLY is a lex/yacc type parser for Python.


I am also concerned if there can be situation that I free a pointer twice in my case

... and ...

  Yes just I am more interested in cases when/if there can be for example freeing unallocated memory or freeing already freed memory ...

After a quick inspection it doesn't appear that you free memory more than once:

free statements are only in the freeArray and main methods
Each free(a->array[0].name); is different because each name is allocated using its own malloc
free(a->array) is only called once
freeArray is only called once
free(x.name); doesn't free the same memory as free(a->array[0].name); because insertArray allocates new memory for each name

  and how to avoid that

Something which can help (though not guarantee) is to assign NULL to the pointer after you pass it to free.

It can help, because calling free on a previously-nulled pointer will harmlessly do nothing
It's not a guarantee, because you might have more than one pointer pointing to the same memory

dmcr_code's comment below points out a bug. You wrote,

for(int i=0; i<a->used; i++)
{
    free(a->array[0].name);
    a->array[0].name=NULL;
}

This should be,

for(int i=0; i<a->used; i++)
{
    free(a->array[i].name);
    a->array[i].name=NULL;
}

Because you set a->array[0].name=NULL; after freeing it, you don't free it twice.

But, you did fail to free the memory associated with a->array[i].name for values of i larger than 0.

  But then how do I protect against that - when array[i].name can contain random value and I try to free it?

To protect yourself:

Either, don't let it contain a random value (e.g. ensure that it's either a valid pointer, or zero)
Or, don't use it (e.g. ensure that your a->used logic is correct so that you don't touch elements which you haven't used/initialized).

  is memset in the initArray method fine for that?

memset is good:

You could use calloc instead of malloc to avoid having to use memset as well
You could use memset on the whole array at once instead of using memset on each element of the array

memset in initArray isn't enough. It's enough to begin with, but there's a realloc in insertArray. So to be good enough, you'd also need to use memset after realloc (to memset the as-yet-unused end of the newly-reallocated array; without using memset on the beginning of the reallocated array, which already contains valid/initialized/used elements).

  the only unclear part that remains from your response is how to memset realloced array

Your current code in initArray says,

// Initialize all values of the array to 0
for(unsigned int i = 0; i<initialSize; i++)
{
    memset(&a->array[i],0,sizeof(Student));
}

Another way to do that would be:

// Initialize all elements of the array at once: they are contiguous
memset(&a->array[0], 0, sizeof(Student) * initialSize);

The memset statement to add to insertArray would be:

if (a->used == a->size)
{
    a->size *= 2;
    a->array = (Student *)realloc(a->array, a->size * sizeof(Student));
    // Initialize the last/new elements of the reallocated array
    for(unsigned int i = a->used; i<a->size; i++)
    {
        memset(&a->array[i],0,sizeof(Student));
    }
}

Or:

if (a->used == a->size)
{
    a->size *= 2;
    a->array = (Student *)realloc(a->array, a->size * sizeof(Student));
    // Initialize the last/new elements of the reallocated array
    memset(&a->array[a->used],0,sizeof(Student) * (a->size - a->used));
}

  and this comment: "It's not a guarantee, because you might have more than one pointer pointing to the same memory " would be nice if you can address that too

This is safe:

void* foo = malloc(10);
free(foo);
// protect against freeing twice
foo = NULL;
// this is useless and strange, but harmless
free(foo);

This is not safe:

void* foo = malloc(10);
void* bar = foo;
free(foo);
// protect against freeing twice
foo = NULL;
// this is useless and strange, but harmless
free(foo);
// but this is dangerous, illegal, undefined, etc.
// because bar is now pointing to memory that has already been freed
free(bar);


Retrieve value from item wrapped in a Future[Option[Item]]

It's better that you are staying in the Futures domain, no longer trying to unwrap to String.

It's not so easy to follow all of the underscore-based function expressions. I'd try something like...

val subject: Future[String] = {
  repository.findById(someId) map { mbItem =>
    mbItem match {
      case Some( item ) => item.subject
      case None         => ""
    }
  }
}


1. Review

There are no docstrings. What do these functions do? How do I call them? What do they return?
The function odd_numbers_from could be implemented using itertools.count, like this:

def odd_numbers_from(n):
    """Generate the odd numbers greater than or equal to n."""
    return itertools.count(n + 1 - (n % 2), 2)

But if you started with earlier_primes=[2,3] then you could avoid the special case here.
The function takeWhile is built into Python under the name itertools.takewhile.
takePrimes is only called from primes, so would make more sense to be inlined there.
A Python object that can be looped over using the for statement (like the argument to takePrimes) is properly known as an iterable, not a iterator.
Instead of not 0 in expression, write all(expression).

2. Revised code

from itertools import count, islice, takewhile

def primes(earlier_primes=[2, 3]):
    """Generate the prime numbers.

    >>> list(islice(primes(), 10))
    [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]

    """
    yield from earlier_primes
    for n in count(earlier_primes[-1] + 2, 2):
        if all(n % p for p in takewhile(lambda p: p**2 <= n, primes())):
            earlier_primes.append(n)
            yield n


var mode = function(arr){

It's nice to name your functions for debugging purposes, if none other. You could replace this with a function declaration, e.g. function mode(arr) { or just name the function expression: var mode = function mode(arr) {

    var numMapping = {};
    for(var i = 0; i < arr.length; i++){
        if(numMapping[arr[i]] === undefined){
            numMapping[arr[i]] = 0;
        }
            numMapping[arr[i]] += 1;
    }

I would use arr.forEach(), since it lets you operate on the elements directly. You could also make the mapping a one-liner(but both of these things are more nitpicks/personal style choice)

    var greatestFreq = 0;
    var mode;
    for(var prop in numMapping){
        if(numMapping[prop] > greatestFreq){
            greatestFreq = numMapping[prop];
            mode = prop;
        }
    }
    return parseInt(mode);
}

You can do this whole part during your first loop! Also, parseInt, while safe in this case, is not generally safe to use without a radix(you'd have linters complaining about this usage here). You could use parseInt(mode, 10), or some ToNumber() transformation like +mode(http://es5.github.io/#x11.4.6).

Here's a revised example:

var mode = function mode(arr) {
    var numMapping = {};
    var greatestFreq = 0;
    var mode;
    arr.forEach(function findMode(number) {
        numMapping[number] = (numMapping[number] || 0) + 1;

        if (greatestFreq < numMapping[number]) {
            greatestFreq = numMapping[number];
            mode = number;
        }
    });
    return +mode;
}


Better code for converting a char to its UTF-8 percent encoding representation?

Documentation here

public static void main(final String[] args) {
        try {
            System.out.println(URLEncoder.encode("a?>éàùA-Z",
                    System.getProperty("sun.jnu.encoding")));
        } catch (final UnsupportedEncodingException e) {
            System.out.println("BIG PB");
            return;
        }
    }

Output :

  a%3F%3E%E9%E0%F9A-Z

You have the same for URLEDecoder

EDIT

For URI
Found in src  of iMeMex Dataspace ManagementSystem

public static URI encode(String uriStr) throws URISyntaxException {
    if (uriStr != null) {
        // poor man's encoding
        uriStr = uriStr.replaceAll(" ", "%20");
    }
    return new URI(uriStr);
}

JavaDoc here

But URI from Java does not change other %VALUES.


Path finding algorithm using recursion in Python

What's in a name?

This code is pretty easy to follow, and I could mostly understand it on the first read through. However, we could do better. Let's take a look at possible_paths(). This function doesn't return paths - it returns neighbors. It returns all the adjacent squares. Moreover, what is path[0] and what is path[1]? Let's name these things too.

Point = collections.namedtuple('Point', 'x y')

def neighbors(maze, coor):
    adjacent = (Point(coor.x - 1, coor.y),
        Point(coor.x, coor.y-1),
        Point(coor.x, coor.y+1),
        Point(coor.x+1, coor.y)
    )

    for p in adjacent:
        if 0 <= p.x < len(maze[0]) and 0 <= p.y < len(maze):
            if maze[p.y][p.x]: # I don't understand this flipping
                yield p

Having x and y is easier to grok than path[0], which looks like a point in a path, rather than an individual coordinate of a point. You could split this up even more by putting the adjacent points in their own function:

def adjacent(coor):
    yield Point(coor.x - 1, coor.y)
    yield Point(coor.x, coor.y - 1)
    yield Point(coor.x, coor.y + 1)
    yield Point(coor.x + 1, coor.y)

def neighbors(maze, coor):
    for p in adjacent(coor):
        ...

That's nice and bite-size. This idea should get propagated through to solve() so instead of starting with paths = ... we call it next_nodes = ... (or next_neighbors or something equivalent suggesting that we're talking about single points, not paths).

Global Variables

Right now, your solver is a little hard to use. You have to call it, then separately, check some global variable to see the result. Global variables are bad for a lot of reasons that I won't get into here, but the important one here is: you want your solver to return the answer. So let's do that:

if pos == exit:
    # we made it!
    return current_path

Okay that part is easy. What do we do in the other cases? First, there's not really a special case for len(paths) == 1 if you think about it. There is a special case for 0 though. Did we hit a dead end? Let's quit.

elif not next_nodes:
    # no path found
    return []

And for the rest, we just have to check the return of solve() every time. Note that there's no reason to copy the full list of current_path every time! That's expensive. You can just append to the end before the call to solve and pop afterwards:

else:
    for node in next_nodes:
        current_path.append(node)
        res = solve(maze, node, current_path)
        if res:
            return res
        current_path.pop()

Since current_path is what gets returned anyway, this can be simplified into just:

    for node in next_nodes:
        current_path.append(node)
        if solve(maze, node, current_path):
            return current_path:
        current_path.pop()

Now your usage is just:

>>> print solve(maze, Point(0,0), Point(2,0), [Point(0,0)])
[Point(0,0), ...]

Default values

Be very wary of having default values that are mutable. The canonical counterexample is something like:

def foo(x = []):
    x.append(1)
    return x

>>> foo()
[1]
>>> foo()
[1,1]
>>> foo()
[1,1,1]

Prefer to default to None. Then you can check it and assign it as appropriate:

def solve(maze, pos, exit, current_path = None):
    if current_path is None:
        current_path = [pos]

    next_nodes = [...]

What about other paths?

There may be more than one path. Let's return all of them. Or, rather than returning all of them, let's make this a generator. If the caller only wants one path, he can just take the first one!

def solve(maze, pos, exit, current_path = None):
    if current_path is None:
        current_path = [pos]
    if pos == exit:
        yield current_path # instead of return
    else:
        for node in neighbors(maze, pos):
            if node not in current_path:
                for result in solve(maze, node, exit, current_path + [node]):
                    yield result

A Path != Best Path

Depth-first search (what you're doing) will definitely find a path if it exists. But it won't necessary find the shortest one. Try out a few of the other path-finding algorithms. The direct corollary to DFS is Breadth-first search (which does exactly what it sounds like). And then there is a lot of room for optimization.


SQL subquery to determine whether or not a particular row is the first item that matches the subquery

There is no natural order.  With no order by the order of the rows is not guaranteed.

What you are looking for is not totally clear to me.  But I think this is what you are looking for.  Pretty sure window function is what you are looking and it is efficient.

  select tt.AuctionID, tt.StartingPrice
       , tt.rn
       , case when rn = 1 then 'first' else 'not first' end as [verb]
  from ( SELECT [AuctionID]
              , [Price]
              , ROW_NUMBER() over (partition [AuctionID] by order by [Price]) as rn
         FROM [Test].[dbo].[Auction]
       ) tt

select *
     , case when rn = 1 then 'entered rate of' else 'edited rate to' end as [verb]
from  ( select n.PayRate, n.CreatedOn, n.CreatedByUserName
            ,  row_number() over (partiton by RateID order by TrackRateID) as rn
          from Rates, TrackRates n
         where ClientID = @id
      ) tt
 order by RateID, TrackRateID


Updating necessary data using just one function

You are vulnerable to SQL Injections. Even when you are using Prepared statements, doing It wrong will kill you.

$sql = "UPDATE users SET " . $data[0] . "=? WHERE username=?";

This makes you exposed to SQL injections because your function is not private. You should not allow "user" access to "critical" functions. make that function private and you should be good to go.

As soon as the user is allowed to set $data[0] you're screwed.


Using an enum will only help if you know all the values/keys at compile time. If your data is coming from a database, then you can't know that, so you can't use an enum.

Note that your question assumes a double-key - the String value is unique, and the int value is also unique.

There are three common ways to do this problem, the easiest way is the one you have done, and then store the data in a HashMap with the most commonly used lookup as the key, and the less-common lookup as the value. This makes it quick to find the most common search on the key, and slower, but possible, to find the value.

I would improve your code by throwing an exception when the lookups fail to find a matching value. If someone asks getRole(-1) it should throw an exception... right?

The easiest solution for this type if problem is possible if you can assume that the key domain and value domain have no overlap (a value cannot also be a key). Since your keys and values are ints and Strings, it's clear there is no overlap.

To use this solution, create a "mapping" class, call it IDRole or something:

private static final class IDRole {
    private final int id;
    private final String role;
    IDRole(int id, String role) {
        this.id = id;
        this.role = role;
    }
}

Now your class can have just one HashMap<Object,IDRole> data store, and you can save each IDRole twice, once with the ID key, and once with the Role key.

private static final HashMap<Object, IDRole> mapping = new HashMap<>();

private static final addMapping(int id, String role) {
    IDRole idr = new IDRole(id, role);
    if (mapping.putIfAbsent(id, idr) != null) {
        throw new IllegalArgumentException("Cannot add duplicate mapping for " + id);
    }
    if (mapping.putIfAbsent(role, idr) != null) {
        throw new IllegalArgumentException("Cannot add duplicate mapping for " + role);
    }
}

OK, so, with the above, you can add a mapping that maps both the key, and value, in to the HashMap.

Your lookups are now easy too:

public static String getRole(int id){
    IDRole ird = mapping.get(id);
    if (idr == null) {
        throw new IllegalArgumentException("No mapping for input ID " + id);
    }
    return idr.role;
}

The getID would be similar.


Ensuring that attributes referenced by a mixin are present in the children class

The point of a mixin, at least as I've always understood it, is to inject
methods into other classes -- and not to create instances of the mixin class
itself. So putting an __init__() in a mixin does seem like an odd pattern. Of
course, __init__() is just a method: why not inject that method too? Fair
enough, but it still feels off. And is it really necessary?
One option is to inject the schema checking method and then call it in a proper
__init__():
class SchemaMixin:

    def _check_schema(self):
        ...

class Todos(SchemaMixin):

    def __init__(self):
        ...
        self._check_schema()

Or just use regular functions and get out of the awkward business of
inheritance. Without knowing more details about your case, I would lean in this
direction.
def check_schema(obj):
    ...

class Todos():

    def __init__(self):
        check_schema(self)

I find myself almost never using inheritance these days -- regular or
mixin-style. I don't have a blanket policy against it, but I increasingly find
that I just don't need it. If a class needs something, I pass it in as an
argument. If multiple classes need the same operation, I use functions.


Sorting object with null values underscore sortBy

flapdoodle!

if (o.activityOrder === null)
        o.activityOrder = 99999999999;

Dude, don't do this. Really.

Sorting idiom

Javascript supports sorting pretty much as you'll see in other languages.
Collections have sorting.
Sort functions can take a function delegate for customized sorting.
Typically, compare the desired values and return an integer that means less-than, equal-to, greater-than. Typically -1, 0, 1 respectively.
handling null does not require converting it to a valid value in your set domain.
Read the documentation!


Persist relation to a class (and not a class instance) in Ruby on Rails with Mongoid

It works that's for sure.

But enums could just as easily be defined in the database. Now that you've already got it working with enums, I would say stick with enums untill you have a good reason to change it.

anyways, here's how i probably would have done it:

e.g.

user has_many subscription_plans
subscription_plan can belong to many users.
Limit the ability for a user to have a max of two, one of each type. Or the user must have two at any one time etc.

You get the picture. You can change the subscription plan table to suit your needs.

Hope this helps.


Finding the length of the longest common substring from two given strings in Java

Stylistic review

You really need some whitespace here and there. Please put a space between operators and between keywords / brackets, etc. For example:

    for(int i=0; i<s.length(); i++){
        for(int j=0; j<t.length(); j++){

This would be more readable:

    for (int i = 0; i < s.length(); i++) {
        for (int j = 0; j < t.length(); j++) {

You also could use better variable names. s and t aren't very obvious, and neither is g.

Overall, the code could potentially be more readable if it could be restructured into using some of the Stream algorithms, but that's not an easy task.

Performance review

The easiest solutions to this problem take \$O(nm)\$ time, where \$n\$ and \$m\$ are the lengths of the 2 input strings. Your algorithm is slower than this. Here are some places that slow it down:

You keep incrementing g even once the strings become dissimilar. You want to break out of the while loop once t.charAt(j + g) != s.charAt(i + g). Because we keep incrementing i and j, you don't have to worry about missing later common substrings.
If s = "abcdefg" and t = "abcdefg", one iteration of the inner for loop will find the correct maxLength. However, you then increment j and have to iterate over bcdefg again with the inner while loop even though we know that bcdefg is a shorter substring than abcdefg. You can keep your count variable from the inner while and use that to skip forward in j, at the very least.
This isn't an algorithmic concern, but you compute Integer.max on every single char, but you only need to do it once you find a complete substring. This can be accomplished by moving that line into the else block (before the count = 0, which can be removed if you follow my first point).

Those are the easy performance improvements I can see. If you still need to speed up your code, the easiest thing to do would probably be to redesign your algorithm.

One of the more powerful techniques in algorithm design is known as dynamic programming. It is basically just breaking down the problem into smaller pieces, then combining it together. For example, if it was possible to find the largest common substring (LCS) of the left and right halves of s and t, then use that information to find the LCS of the whole thing, that would be solving the problem through dynamic programming.

Wikipedia helpfully has a page on this problem. For a dynamic programming solution, it shows that you can solve this by taking all the possible prefixes of the strings, and finding the longest common suffixes for each pair of possible prefixes. If that algorithm isn't efficient enough, it helpfully provides another one which is faster.


Volatile won't do anything here, as this basically only affects the reference to the map, not the contents of the map.

As for ConcurrentHashMap (as opposed to explicit synchronizing I suppose): this depends. If you want to make absolutely sure that no digest is ever computed twice, stick to your approach. If you just want general concurrency, but can accept that eventually in race-conditions, digest is called twice for the same input (sidenote: I suppose digest is deterministic, so that two calls with the same input yield the same result), you may simply repace the map with a ConcurrentHashMap and the whole method with:

return cache.computeIfAbsent(input, this::doDigest);


Bash script to simplify Git deployment workflow

Use exit codes directly

Instead of this:

merge $SOURCE_BRANCH 'staging'
status=$?
if [ $status -ne 0 ]
then
  echo "ERROR: STEP 1" >&2
  exit 1
fi

You can use exit codes directly in conditions, like this:

if ! merge $SOURCE_BRANCH 'staging'
then
  echo "ERROR: STEP 1" >&2
  exit 1
fi

Use it this way everywhere.

Handle errors consistently

The error handling is inconsistent throughout the script:

Sometimes you exit 1, sometimes you return 1 in functions. It would be better to do consistently
Sometimes you print the error message on stdout, sometimes on stderr. It would be better to print it consistently on stderr

Style

To print a blank line you can simply echo without a parameter.

You can drop return 0 as the last statement of a function. The exit code of the last  statement will be used as the exit code of the function.

A semicolon is unnecessary at the end of the line.

Long comments at the end of a line are generally hard to read. Move these to the previous line.

The indentation is not consistent. The code inside the functions looks nice, do the same way for the code outside.

Ex. ( edited by @WonderLand)

#!/bin/bash

function merge() {
    SOURCE=$1
    DEST=$2

    echo
    echo "---> Merging $SOURCE with $DEST"

    echo
    echo "---> ---> Checkout $DEST ..."
    git checkout $DEST

    echo
    echo "---> ---> Pull $DEST ..."
    if ! git pull --ff-only origin $DEST
    then
     exit 1
    fi

    echo
    echo "---> ---> Merging $SOURCE with $DEST ..."
    # --ff-only trigger errors if merge/pull is not possible
    if ! git merge --ff-only $SOURCE --no-edit
    then
      exit 1
    fi

    echo
    echo "---> ---> Push $DEST ..."
    git push origin $DEST
}

function deploy() {
    MODE=$1
    SOURCE_BRANCH=$2

    echo
    echo "---> Pull changes from Master ..."

    if ! git checkout $SOURCE_BRANCH
    then
        exit 1
    fi

    git pull --progress --no-edit --no-stat -v --progress origin master

    if ! merge $SOURCE_BRANCH 'staging'
    then
      exit 1
    fi

    if [ $MODE = "live" ]
    then
        if ! merge $SOURCE_BRANCH 'master'
        then
          exit 1
        fi

        if ! merge 'master' 'production'
        then
          exit 1
        fi
    fi
}

MODE=$1
SOURCE_BRANCH=$2

if [ -z "$MODE"  -o -z "$SOURCE_BRANCH" ]
then
    echo "Usage:"
    echo ""
    echo  "MODE BRANCH_NAME (MODE: live|staging)"
else
    if git show-ref --verify --quiet "refs/heads/$SOURCE_BRANCH"
    then
        echo
        echo "### START ###"
        echo
        deploy $MODE $SOURCE_BRANCH
        echo
        echo "### END ###"
        echo
    else
        echo
        echo "Error: Branch $SOURCE_BRANCH not found"
    fi
fi


Counters.Total = ticketList.Count();
Counters.Open = ticketList.Count(e => e.Status == StatusType.Open);
Counters.Responded = ticketList.Count(e => e.Status == StatusType.Responded);
Counters.Resolved = ticketList.Count(e => e.Status == StatusType.Resolved);
Counters.Archived = ticketList.Count(e => e.Status == StatusType.Archived);

You have so many counters there that you should really consider using a GroupBy on the Status column.

// Can't use LINQ-to-SQL here -- Is60To90DaysOld and Is90DaysOld aren't columns in database
List<TicketModel> list = ticketList.ToList();
Counters.Age60To90 = list.Count(e => e.Is60To90DaysOld);
Counters.Age90Plus = list.Count(e => e.Is90DaysOld);

This part could also benefit from another GroupBy if you added one more property Age and a helper enum:

public enum Age
{
    Unknown,
    Between60And90Days,
    GreaterOrEqual90Days
}

The new property could replace the other two as they are mutually exclusive anyway:

public Age Age
{
    get
    {
        TimeSpan age = DateTime.Today - DateOfCreation;

        if (age.Days >= 60 && age.Days < 90) return Age.Between60And90Days;
        if (age.Days >= 90) return Age.GreaterOrEqual90Days;

        return Age.Unknown;
    }
}


Python list "commander" (modify a list with user commands)

value_list = []

Global variables are almost never necessary.  If you are tempted to use a global, you have two choices:

Give the variable as an argument and reassign it to what the function returns (or just give it if the function mutates it).
Define a class and use instance attributes.

In this case, value_list is used by far too many things and with lambda functions and everything.  Therefore, I would suggest that you define a Commands class.

"/add": lambda *value : value_list.extend(list(value))

You don't need to convert value to a list.  That is just unnecessary processing time.  A list can be extended by a list, a tuple, a string, a generator, ... whatever iterable you want.

"/rindex": lambda value : value_list.pop(int(value)),

I wouldn't convert it to an integer within a lambda function.  I would create a whole function that uses a try block in case the user doesn't type a valid number.  That is also helpful if the user does type a number, but types a number that is too big or too small.

elif last_char == "append"
...
    last_char = "append"

Don't use magic numbers (or magic values).  You should define a constant called APPEND that can really be assigned to any object except a single-character string.

++current_args_index

Python doesn't use ++.  If x is 4, then +x is 4 and ++x is still 4.  If x is -4, then +x is -4 and ++x is still -4.  In other words, it does absolutely nothing.  Python isn't like C where that increments current_args_index.  If you want to increment it, do current_args_index += 1

cmd = ...
if cmd == None:
    ...

I have two problems.  First, if you treat None as a special case, you can simply use a try block.  Second, you should say is None, not == None because a class could define its __eq__ method to say that any instance is equal to None, but only None really is None.

Your main() function and how you use it looks terrific!  You take care of each error separately, and you don't call main() unless your file is being run as a program.  Keep it up!


That is really not how you should be using a Stopwatch...

E.g. this

while (Timer.Elapsed.TotalMilliseconds < Duration) { }

You're needlessly using CPU cycles while you're waiting. That's not good! You know exactly when you want to do something so you should scheduled something rather than do pretend work. A simple example could be:

private void ThreadMethod(IUnit unit)
{
    Activate(unit);
    Task.Delay(Duration).ContinueWith(_ => Deactivate(unit));
}

This isn't safe either:

while (Timer.ElapsedMilliseconds < Duration)
{
    if (Timer.Elapsed.TotalMilliseconds % TickTime == 0)
        ApplyTick(unit);
}

You're very unlikely to actually get true on that if statement meaning you're unlikely to call ApplyTick and almost certainly won't call it the number of times you want to! That's because a Tick is a really, really small measure of time... I want to say 1/10000 of a millisecond.

Edit - I misread your if statement - I thought you were using Ticks (due to the TickTime field. It's still not a great idea but less serious than the above implies.

You shouldn't need a stopwatch at all for this sort of thing.

You should use the highest level of abstraction you can. A double can be anything (e.g. hours, minutes, seconds...) - a timespan is a period of time, much more suitable for your LimitedTimeBehavior:

public abstract class LimitedTimeBehavior : IBehavior
{
    public abstract void ApplyBehavior(IUnit unit);

    public TimeSpan Duration { get; }

    protected LimitedTimeBehavior(TimeSpan duration)
    {
        Duration = duration;
    }
}

You said you're interested in design patterns so I though I'd draw your attention to one you're nearly using:

public abstract class ActivatableBehavior : IBehavior
{
    public abstract bool BehaviorImplentation(IUnit destinationPlayer);

    public void ApplyBehavior(IUnit unit)
    {
        BehaviorImplentation(unit);
    }
}

That's the Template Method pattern but it's more normal to call multiple methods within the template method.

public abstract class ActivatableBehavior : IBehavior
{
    public abstract void BehaviorImplementation(IUnit destinationPlayer);

    public abstract bool CanApplyBehvaiorTo(IUnit destinationPlayer);

    public void ApplyBehavior(IUnit unit)
    {
        if (CanApplyBehvaiorTo(unit))
        {
            BehaviorImplementation(unit);
        }
    }
}

Note that I've fixed your typo (Implentation -> Implementation) and have removed the bool return type that was never used.


Search father (x) of the number D(x) and measure time and memory consumed

PEP-8
Try to stick to PEP-8. So snake_case for variable and method names and a lot of other guidelines. Check any other Code Review Python post for tips from people who can explain this better than me.
Memory
Since you have 128MB of memory available, and a list of 1000 integers (l = list(range(1000)); sys.getsizeof(l) + sum(map(sys.getsizeof, l))) takes only 37kb on my system, I would not worry about clearing intermediate results.
Pre-calculate the primes to 1000
If the input number never goes beyond 1000, pre-calculating all the primes will be the fastest and most efficient. Here is method rwh_primes from this SO post adapted for Python 3:
def primes(n):
    # https://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python/3035188#3035188
    """ Returns  a list of primes < n """
    sieve = [True] * n
    for i in range(3, int(n ** 0.5) + 1, 2):
        if sieve[i]:
            sieve[i * i :: 2 * i] = [False] * ((n - i * i - 1) // (2 * i) + 1)
    return [2] + [i for i in range(3, n, 2) if sieve[i]]

This takes about 50µs on my PC.
prime_factors
You do some of unnecessary calls to set and list. I would implement this as a generator, and store it further upstream as a set:
def prime_factors(n):
    for factor in PRIMES:
        if factor > n**.5:
            yield n
            return
        while not (n % factor): # n is divisible by factor
            yield factor
            n //= factor
            if n == 1:
                return

sum_digits
This one looks okay. You could use divmod, but that is a matter of taste.
offspring
No need for the intermediate DX:
def offspring(x):
    return x + sum(set(prime_factors(x))) + sum_digits(x)

Main guard
Keep the main logic behind a if __name__ == '__main__': guard.
eval
Instead of using eval, since you know it will be int, better use int(). eval can be dangerous, since it can execute arbitrary code. If you need to interpret a python literal, use ast.literal_eval.
Then you do something very inefficient by creating a dict, then take only the values, apply list, set and list again. Easiest would be to just use a set-comprehension:
all_offspring = {offspring(i) for i in range(1, 1001)}

This will include some numbers over 1000, but this extra memory should be negligible.
Test
You can spoof input on your system by something like
test_case = '''2
4
20'''
input = iter(test_case.split('\n')).__next__

main
if __name__ == '__main__':
    PRIMES = primes(1000)
    all_offspring = {offspring(i) for i in range(1, 1001)}
    t = int(input())
    for i in range(t):
        n = int(input())
        if n in all_offspring:
            print('YES')
        else:
            print('NO')

Timing
To time it you can use timeit module. There are enough posts on SO about this, and for memory usage.


A simple SDL script that creates a window

Is there possibly a way to take out the nested if statements without losing the error reports?

Use RAII to encapsulate your resources into objects that enforce the create/destroy pairing. You can write your own RAII wrapper objects or (better) use a resource factory that creates std::unique_ptr/std::shared_ptr's. A concrete factory for arbitrary SDL resources:

namespace sdl2 {
template <typename Creator, typename Destroyer, typename... Arguments>
auto make_resource(Creator c, Destroyer d, Arguments &&... args) {
  auto r = c(std::forward<Arguments>(args)...);
  if (!r) {
    throw std::system_error(errno, std::generic_category(), SDL_GetError());
  }
  return std::unique_ptr<std::decay_t<decltype(*r)>, decltype(d)>(r, d);
}
} // namespace sdl2

This factory attempts to create the resource, checks to ensure it was created, and returns a unique_ptr that destroys the resource correctly when the pointer goes out of scope.  Specific helpers to provide higher levels of abstraction for resources like SDL_Window, SDL_Texture, SDL_Renderer, etc, can be created like so:

namespace sdl2 {
using WindowPtr = std::unique_ptr<SDL_Window, decltype(&SDL_DestroyWindow)>;

WindowPtr make_window(const char *title, int x, int y, int w, int h,
                      std::uint32_t flags) {
  return make_resource(SDL_CreateWindow, SDL_DestroyWindow, title, x, y, w, h,
                       flags);
}
} // namespace sdl2

You can write your own abstractions over SDL's C API to utilize some of the modern C++ constructs and ideally end with something like this:

int main() try {
  auto window = sdl2::make_window("Slime Runner Prelim Tests",
                                  SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
                                  640, 480,
                                  SDL_WINDOW_SHOWN);
  auto screen = sdl2::get_surface(window);
  auto image = sdl2::load_bitmap("Images/Background.tmp");
  sdl2::blit_surface(image, nullptr, screen, nullptr);
  sdl2::update_surface(window);
  sdl2::delay(4s);
} catch (...) {
  std::cout << "Error: " << error.what() << '\n';
}

Note: You don't have to use exceptions, but RAII does provide you with the flexibility to choose whichever error handling system you want (exceptions, checked errors, etc) while simplifying the cleanup process.

int main(int argc, char *argv[])

If you are not using argc and argv, omit them.

int main()

std::endl

Be aware of what std::endl actually does.  If you simply want to print a newline character, prefer '\n' since it's both shorter and correct.

SDL_BlitSurface(imageSurface, NULL, windowSurface, NULL);

Use nullptr instead of NULL.


Running SQL and mapping the reader to objects

It looks ok for me so, just a couple of suggestions:

First: given it is a protected method and not a private, it can be called be derived classes which probably could not be in the same assembly (this is true only if the class is public) then, you shouldn´t use optional parameters, they force you to recompile all when you change them.

Instead, use an overloaded method as follow:

protected List<T> Query<T, TFactory>(string query) where TFactory : IFactory<T>
{
    return Query<T, TFactoty>(query, Enumerable.Empty<IDbDataParameter>());
}

protected List<T> Query<T, TFactory>(string query, IEnumerable<IDbDataParameter> parameters)
    where TFactory : IFactory<T>
{

It also help you to remove the checking for nulls.

Second, if you return an IEnumerable, the callers will have less features. The rule is you you should require the most generic and return the most specific implementation so, if you have a list you could return a List<>, IList<> or a Collection. Then, callers have more options.

My attempts is this one:

protected List<T> Query<T, TFactory>(string query) where TFactory : IFactory<T>
{
    return Query<T, TFactoty>(query, Enumerable.Empty<IDbDataParameter>());
}

protected List<T> Query<T, TFactory>(string query, IEnumerable<IDbDataParameter> parameters)
    where TFactory : IFactory<T>
{
    var collection = new List<T>();

    var factory = Activator.CreateInstance<TFactory>();
    var connection = (Db == null) ? Connection : Db.Connection; // this line looks rare for me

    using (var manager = new DbCommandManager(connection, sql))
    {
        foreach (var parameter in parameters)
            manager.AddParameter(parameter);

        using (var reader = manager.GetReader())
        {
            while (reader.Read())
                list.Add(factory.CreateTFromReader(reader));
        }
    }

    return list;
}

Update:

One more thing about optional parameters, when you call the Query method with one argument, you really are passing two: the query and a null in 'parameters'. You have never pass nulls (or at least you have to try) because if you pass nulls then, you need to check for null values.

One more thing about the protected modifier, privates methods can trust that their parameter won´t be null but protected methods cannot do it. This is because private members will be called by other methods in the same class but protected method can be called by other methods in other classes.


The snippet you asked to re-write:

let(:mail) { ReminderMailer.send(time_format, user) }

Now, IMO using each to write specs is a bad practice. Why? Because rspec already provides idiomatic infrastructure to keep specs DRYed: use before and shared_examples. I'd write:

describe ReminderMailer, type: :mailer do
  let(:user) { ... }

  shared_examples "a reminder mailer" do |subject:, body:|
    it 'renders the subject' do
      expect(mail.subject).to eq(subject)
    end

    it 'renders the receiver email' do
      expect(mail.to).to eq([user.email])
    end

    it 'renders the sender email' do
      expect(mail['From'].to_s).to eq('24 Pull Requests <info@24pullrequests.com>')
    end

    it 'uses nickname' do
      expect(mail.body.encoded).to match(user.nickname)
    end

    it 'contains periodicity in body' do
      expect(mail.body.encoded).to match(body)
    end
  end

  describe 'daily' do
    let(:mail) { ReminderMailer.daily(user) }

    it_behaves_like "a reminder mailer",
      subject: '[24 Pull Requests] Daily Reminder',
      body: 'today'
  end

  describe 'weekly' do
    let(:mail) { ReminderMailer.weekly(user) }

    it_behaves_like "a reminder mailer",
      subject: '[24 Pull Requests] Weekly Reminder',
      body: 'week'
  end
end


Find the nearest coin to be collected in a game

object should be plural, and should more clearly indicate what it contains. gameObjects would be preferable.

It's a good idea to always include curly braces, even when they're not required. It removes a possible source of later bugs.

It’s easier to read isEmpty() than size() == 0. You also don’t need the else statement, since the if returns.

If handler.object is a type that has an iterator() method, it would be better to use that than a for loop.

The performance of LinkedList is often worse than ArrayList. You should consider testing their relative performances.

You should code to interfaces, not implementations, where possible. List<GameObject> objects = … is preferable to LinkedList<GameObject> objects =.

If ID has a correct implementation of equals(), you should probably be using that. == asks if it’s the ID is the same object, not just if it has the same value.

In java, it’s preferable to only capitalize the first letter of an acronym, so objectId is preferred to objectID.

There’s probably something wrong with getDistance() - it should either be an instance method or you shouldn’t need to pass in this.

You don’t need to loop twice. Every time you find an object with a matching id, compare it’s distance to the current nearest object. Only keep the nearest. This will also save you from computing the distance twice.

As far as optimizing performance, you'll have to do some testing and see if it's working fast enough for you. Cutting out the one loop will make it closer to optimal, but we can't know how that will interact with the game.

If you were to apply all my suggestions, your code might look something like:

public GameObject getNearest(final ID objectId) {
    GameObject nearestObject = null;
    int distance = Integer.MAX_VALUE;

    for (int i = 0; i < this.handler.object.size(); i++) {
        final GameObject currentObject = this.handler.object.get(i);
        if (!currentObject.getId().equals(objectId)) {
            continue;
        }

        final int currentDistance = this.getDistance(this, currentObject);
        if (currentDistance < distance) {
            nearestObject = currentObject;
            distance = currentDistance;
        }
    }

    return nearestObject;
}


Sign In or Sign Up - either way don't repeat yourself

Here is an example of where we could combine the Factory Pattern along with a Builder Pattern to extend your current code.

class SignUp : ViewModelBase
{
    private readonly List<Block> _content = new List<Block>();

    public SignUp()
    {
        _content.Add(BlockFactory.Create(BlockType.Email));
        _content.Add(BlockFactory.Create(BlockType.PostalAddress));
    }
}

class SignIn : ViewModelBase
{
    private readonly List<Block> _content = new List<Block>();

    public SignIn()
    {
        _content.Add(BlockFactory.Create(BlockType.Email));
    }
}

public static class BlockType
{
    public const string Email = "Email";
    public const string PostalAddress = "Postal Address";
}

public static class BlockFactory
{
    public static Block Create(string blockType)
    {
        if (String.IsNullOrEmpty(blockType)) throw new ArgumentNullException(nameof(blockType));

        switch (blockType)
        {
            case BlockType.Email:
                return new BlockBuilder()
                    .Name(BlockType.Email)
                    .Icon("email_icon.png")
                    .Build();
            case BlockType.PostalAddress:
                return new BlockBuilder()
                    .Name(BlockType.PostalAddress)
                    .Icon("postal_icon.png")
                    .Description("Give us your mailing address to get great stuff by postal mail!")
                    .BlockItems(
                        new List<BlockItem>()
                        {
                            new BlockItem() { Name = "Street", Value = "", IsVisible = true, template = "" },
                            new BlockItem() { Name = "Zip", Value = "", IsVisible = true, template = "" },
                            new BlockItem() { Name = "City", Value = "", IsVisible = true, template = "" }
                        })
                    .Build();
        }

        throw new ArgumentException("Invalid BlockType.");
    }
}

public class BlockItem
{
    public string Name;
    public object Value;
    public bool IsVisible;
    public string template;
}

public class Block
{
    public List<BlockItem> BlockItems = new List<BlockItem>();
    public string Name;
    public string Icon;
    public string Description;
}

public class BlockBuilder
{
    private List<BlockItem> _blockItems;
    private string _name;
    private string _icon;
    private string _description;

    public BlockBuilder BlockItems(List<BlockItem> value)
    {
        _blockItems = value;
        return this;
    }

    public BlockBuilder Name(string value)
    {
        _name = value;
        return this;
    }

    public BlockBuilder Icon(string value)
    {
        _icon = value;
        return this;
    }

    public BlockBuilder Description(string value)
    {
        _description = value;
        return this;
    }

    public Block Build()
    {
        return new Block
        {
            BlockItems = _blockItems,
            Name = _name,
            Icon = _icon,
            Description = _description
        };
    }
}

If you don't like the constants for the BlockType, you can remove this part, but I tend to lean towards easier refactoring instead of using "hand-coded" strings to pass into factories.

public static class BlockType
{
    public const string Email = "Email";
    public const string PostalAddress = "Postal Address";
}

The reason for Builders, is that you can really get good mileage on your class as you need to expand it with more properties and not have to write so many parameter overrides, etc.

For example you could do this in the future with relative ease and straight-forward implementation.

Block block = new BlockBuilder()
            .Name(BlockType.Email)
            .Icon("email_icon.png")
            .Template(...)
            .Styling(...)
            .CloseEventHandler(...)
            .OpenEventHandler(...)
            .Preloader(...)
            .Build();


foldl'

Your implementation is fine, but generally, seq is written infix, like a `seq` b. Therefore, I’d write it like this:

foldl' :: (b -> a -> b) -> b -> [a] -> b
foldl' f accumulator [] = accumulator
foldl' f accumulator (x:xs) =
    accumulator' `seq` foldl' f accumulator' xs
  where accumulator' = f accumulator x

I’ve also indented the second to last line to visually distinguish it more from the where clause.

foldr

Your implementation looks good to me.

length

You mention that you’re explicitly avoiding fold, but why? There’s no reason to avoid it here. Still, even without using it, your implementation can be improved.

Usually, helper functions like length' are nested inside a where clause, sometimes idiomatically named go. Additionally, your 1-element case is unnecessary, since (x:xs) will match a 1-element list. Finally, your use of an accumulator is pointless, since you never actually change it from 0, and your function isn’t tail recursive. Therefore, I would write length like this if you really want to avoid a fold:

length :: [a] -> Int
length = go 0
  where go accumulator [] = accumulator
        go accumulator (x:xs) = go (accumulator + 1) xs

This actually uses the accumulator, which allows it to be tail recursive.

map

Again, I would use a fold here. An implementation with foldr would look like this:

map :: (a -> b) -> [a] -> [b]
map f = foldr (\x xs -> f x : xs) []

However, if you want to write the recursion manually, your 1-element case is once again redundant. You could simplify your implementation to this:

map :: (a -> b) -> [a] -> [b]
map _ []     = []
map f (x:xs) = f x : map f xs

filter

Once again, I would use a fold here:

filter :: (a -> Bool) -> [a] -> [a]
filter f = foldr (\x xs -> if f x then x : xs else xs) []

If you want to use explicit recursion, though, your implementation looks fine.

(++)

Your 0-element case is redundant here because foldr will handle the 0-element case just fine on its own. You can eliminate it entirely:

(++) :: [a] -> [a] -> [a]
xs ++ ys = foldr (:) ys xs


From a once over;

Indent your code, it will be easier to read
Use lowerCamelCase for your names createMyTAGS -> createMyTags, though personally I would call the function createLinks

I would call createMyTAGS_DATA simply s for string or data
I would call createMyTAGS_LOCATION either id or element or elementID, you wont then feel the need to assign that parameter to the slightly better named linkTags

For your string handling, you should read up on .split(), it would make this so much easier
alert statements are terrible, this function should never go wrong. Consider using console.log instead if you must.
If you have long variables or chained variables (which you should avoid), consider +=:
document.getElementById(v1).innerHTML = document.getElementById(v1).innerHTML + linkNew;
becomes
document.getElementById(v1).innerHTML += linkNew;
Consider using addEventListener instead of assigning the event listener straight into the HTML

My counter proposal:

function createLinks(data, elementId){

    var element = document.getElementById(elementId),
        links = data.split(';;'),
        html = element.innerHTML,
        linkParts, url, text;

    links.forEach( function( link ){
        linkParts = link.split(';');
        text = linkParts[0];
        url = linkParts[1];
        html += ''+text+' ';
    });

    element.innerHTML = html;
}
click here


Read framed nested sensor data from memory stream

I think the first loop is somewhat redundant, because if read < startSequenceBuffer.Length after the first pass, the input memoryStream is shorter than the startSequenceBuffer and then there are no messages to follow anyway. Instead of the first loop you can do:

       int read = memoryStream.Read(startSequenceBuffer, 0, startSequenceBuffer.Length);

        if (!Helpers.ByteArrayCompare(startSequenceBuffer, frameStartSequenceBuffer))
            throw new InvalidDataException();

If the first loop is meant as a search for the start sequence, you'll have to find another stop condition, because it will stop after the first pass, unless the stream is shorter then startSequenceBuffer.

  while (memoryStream.Capacity > read) {...}

Be aware that MemoryStream.Capacity >= MemoryStream.Length, so the second loop can unintentionally try to read beyond memoryStream.Length which will cause an infinite loop because trying to read from a position greater than Length will add nothing to read. Use memoryStream.Length instead.

The meat of the second loop is a little confusing without any data to test on. At first sight it seems to work though. It seems odd that frameChecksumBuffer is written to more than once, because you only use it in one test at the end of the method, but maybe I just misunderstand the name or the format of the stream?


Delaying a function call for 30 seconds using sleep() or checking the time in a loop

There is no reason to avoid doing sleep(30);. Your colleague's concerns about the single responsibility principle and abstraction leak are unfounded. sleep() is designed to do exactly what you want, so why not use it? Constantly checking the time in a tight loop is a giant waste of computing power for no advantage at all.