In Google Apps Script, Less code doesn't always mean greater efficiency wrt real-time. According to best practices, focus first on reducing service calls.

To save real time, use a single .setValues() with ALL the desired content. "Javascript" operations are very fast compared to calls to Google's services.

You do have redundant code because of the structure of your if / then / else blocks; you can move repeated portions outside of that logic.

function SendToWorkLogCL() {

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet1 = ss.getSheetByName("CL");
  var sheet2 = ss.getSheetByName("Work Log");
  var repsheet = ss.getSheetByName("Representing");
  var rep = sheet1.getRange("D15");
  var repvalue = rep.getValue();

  var clRange = sheet1.getRange("A2:W2");
  if (repvalue == 'Yes') {
    clRange.copyTo(repsheet.getRange(repsheet.getLastRow() + 1, 1, 1, 7), {
      contentsOnly: true
    });
  }

  // This part does not need to be in an if/then/else, because it's always done.
  clRange.copyTo(sheet2.getRange(sheet2.getLastRow() + 1, 1, 1, 7), {
    contentsOnly: true
  });

  // Only need this block once, instead of two identical copies.
  var sheet = SpreadsheetApp.getActiveSheet();
  var dataRange = sheet.getDataRange();
  var values = dataRange.getValues();

  values[3-1][ColA1ToIndex('A')] = 'Ctrl+SHIFT+V';

  // ...getRange('A3:B23').setValue('') handled in loops
  for (var col=ColA1ToIndex('A'); col <= ColA1ToIndex('B'); col++) {
    for (var row=(3-1); row<=(23-1); row++) {
      values[row][col] = '';
    }
  }
  values[12-1][ColA1ToIndex('D')] = 'Chargeback';
  values[13-1][ColA1ToIndex('D')] = 'Yes';
  values[14-1][ColA1ToIndex('D')] = 'No';
  values[15-1][ColA1ToIndex('D')] = 'No';
  values[17-1][ColA1ToIndex('D')] = '';
  values[18-1][ColA1ToIndex('D')] = '0';
  values[20-1][ColA1ToIndex('D')] = '';
  // Finally, one service call to write ALL values. Fast!
  dataRange.setValues(values);
  // Formulas would have been overwritten by values, so need to be refreshed
  sheet.getRange('D16').setFormula("=IF(A2=\"\",\"\",VLOOKUP(E18,'Data Validation'!C2:E204,3,FALSE))");
}

Helper functions: For clear conversion between A1Notation and 0-based array indices (full implementation in this gist):

/**
 * Return a 0-based array index corresponding to a spreadsheet column
 * label, as in A1 notation.
 *
 * @param {String}    colA1    Column label to be converted.
 *
 * @return {Number}            0-based array index.
 */
function ColA1ToIndex( colA1 ) {
  if (typeof colA1 !== 'string' || colA1.length > 2)
    throw new Error( "Expected column label." );

  var A = "A".charCodeAt(0);

  var number = colA1.charCodeAt(colA1.length-1) - A;
  if (colA1.length == 2) {
    number += 26 * (colA1.charCodeAt(0) - A + 1);
  }
  return number;
}

/**
 * Return a 0-based array index corresponding to a spreadsheet row
 * number, as in A1 notation.
 *
 * @param {Number}    rowA1    Row number to be converted.
 *
 * @return {Number}            0-based array index.
 */
function RowA1ToIndex( rowA1 ) {
  return rowA1 - 1;
}


Determine if one string is a rotation of the other Python

Good work! This is certainly primarily an improvement from your previous implementation. However, there are still a few problems.

Don't raise an error when passed two lists of differing length. Not only is this unexpected by users, it breaks some of your tests.

# 1 empty, 1 not empty
lst1, lst2 = [], [1]
assert not is_rotated(lst1, lst2)
lst1, lst2 = [1], []
assert not is_rotated(lst1, lst2)

The pattern of if condition return True else return False should be replaced with return condition. This is easier to read and reduces the amount of code you have to write!
Joining the lists of integers with the empty string as a separator is dangerous. If I pass in [1, 23] and [12, 3] the function will incorrectly return True. If the function only has to handle integers, you can easily fix this by using a comma (or any other character) as a separator. (Just remember to include it when checking if the string is contained in the other string str1 + ',' + str1)

I would prefer a more general solution that works for lists containing any type of element. Using Nas Banov's answer from Stack Overflow to handle the sub list check, this is a really simple function to write.

def contains_sublist(lst, sublst):
  n = len(sublst)
  return any((sublst == lst[i:i+n]) for i in range(len(lst)-n+1))

def is_rotated(lst1, lst2):
  if not len(lst1) == len(lst2):
    return False
  return len(lst1) == 0 or contains_sublist(lst2 * 2, lst1)


Having tests is great (I'd love to see more questions with tests), keep it up! Other parts I would keep simpler.

You might want this as a tag in your revision control system instead of commenting:

* @version 1.0.0 - Mar 9, 2014

This is also in the revision control history, so it's usually unnecessary:

* @author mhemphill

See: Pros and cons of versioning javadoc
I would not want to maintain comments on test methods like this:

/**
 * Test method for
 * {@link com.getgnosis.tutorials.tutorial01001.AdvancedHelloWorld
 *      #toString()}.
 */
@Test
public void testToString() {
    ...
}

I don't see why would it be useful. I haven't seen anyone who likes reading javadoc of test classes instead of the test code directly. The name of the method is good, it contains the main point: it's a test for toString, keep that and remove the superfluous comment.

@Test
public void testMain() {
    final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
    System.setOut(new PrintStream(outContent));
    AdvancedHelloWorld.main(null);
    assertEquals("Hello World!" + System.getProperty("line.separator"), outContent.toString());
    System.setOut(null);
}

The System.setOut(null) statements should be in an @After tearDown method or at least in a finally block. If the assertEquals throws an exception (or something else) out won't be set back.
I the same testMain method I'd create a local variable for the expected result:

final String expected = "Hello World!" + System.getProperty("line.separator");
assertEquals(expected, outContent.toString());

It's easier to read. (Clean Code by Robert C. Martin, G19: Use Explanatory Variables;  Refactoring: Improving the Design of Existing Code by Martin Fowler, Introduce Explaining Variable)

@Test
public void testAdvancedHelloWorld() {
    try {
        new AdvancedHelloWorld();
    } catch (Exception e) {
        fail("Construction failed. ");
    }
}

The following is the same:

@Test
public void testAdvancedHelloWorld() {
    new AdvancedHelloWorld();
}

If the constructor throws an exception (or anything inside a @Test method) JUnit will tell you.
This comments does not say anything which isn't in the code already, I'd remove it:

/**
 * The default constructor. Initializes the value of message via the static
 * block.
 */

(Clean Code by Robert C. Martin: Chapter 4: Comments, Noise Comments)

static {
    message = "Hello World!";
}

/**
 * The {@link String} instance representing the message to be displayed.
 */
private final static String message;

The following is the same:

private final static String message = "Hello World!";

I would keep it simple.

@Override
public String toString() {
    StringBuilder builder = new StringBuilder();
    builder.append("AdvancedHelloWorld [");
    if (getMessage() != null)
        builder.append("message=").append(getMessage());
    builder.append("]");
    return builder.toString();
}

The if condition can't be false (the message field is final and has a non-null value), so the following is the same:

StringBuilder builder = new StringBuilder();
builder.append("AdvancedHelloWorld [");
builder.append("message=").append(getMessage());
builder.append("]");
return builder.toString();

I'd move the main method to a separate class. It's usually a good idea to separate a class from its clients.


function BaseClass () {}

BaseClass.prototype.talk = function () {
    alert("I'm BaseClass");
}

function MyClass() {
    BaseClass.call(this);
}

MyClass.prototype = new BaseClass();
MyClass.base = BaseClass.prototype;

MyClass.prototype.talk = function () {
    alert("I'm MyClass");
    MyClass.base.talk.apply(this, arguments);
}

var a = new MyClass();
a.talk();

To make all this easier on yourself, don't re-invent the wheel. Look into John Resig's tiny inheritance library: Simple JavaScript Inheritance.


Passing many configuration options to Java code formatter

I'd extract it out to a helper method:

private static Map<String, String> getOptionsMap() {
    final Map<String, String> options = DefaultCodeFormatterConstants.getEclipseDefaultSettings();

    options.put(JavaCore.COMPILER_COMPLIANCE, JavaCore.VERSION_1_6);
    options.put(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, JavaCore.VERSION_1_6);
    options.put(JavaCore.COMPILER_SOURCE, JavaCore.VERSION_1_6);

    // TODO: rename the variable
    final String aligment0 = DefaultCodeFormatterConstants.createAlignmentValue(true,
            DefaultCodeFormatterConstants.WRAP_ONE_PER_LINE,
            DefaultCodeFormatterConstants.INDENT_ON_COLUMN);
    options.put(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ENUM_CONSTANTS, aligment0);

    // TODO: rename the variable
    final String aligment1 = DefaultCodeFormatterConstants.createAlignmentValue(false,
            DefaultCodeFormatterConstants.WRAP_NO_SPLIT,
            DefaultCodeFormatterConstants.INDENT_DEFAULT);
    options.put(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_PARAMETERS_IN_METHOD_DECLARATION, aligment1);
    options.put(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_PARAMETERS_IN_METHOD_DECLARATION, aligment1);
    options.put(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_THROWS_CLAUSE_IN_METHOD_DECLARATION, aligment1);
    return Collections.unmodifiableMap(options);
}

Maybe you can split it up to two or more methods. The aligment0 and aligment1 variables should be renamed to a proper name. Note that you can reuse the Map, since Collections.unmodifiableMap() ensures that it cannot be changed by clients.


Determine if a String has a mirroring head and tail

Below your question:

  Is it safe to say that in terms of time complexity the solution is
  optimal already?

Yes, you are comparing chars from front and back of the string and stop when you encounter two different chars so this is a complexity O(n).

Some minor changes to your code, instead of iterate over your string transform it to a char array and instead of break the cycle return directly the result with the use of a StringBuilder for the result:

char[] arr = string.toCharArray();

StringBuilder builder = new StringBuilder();
for (int i = 0; i < half; ++i) {
    if (arr[i] != arr[len -1 -i]) {
        return builder.toString();
    }
    builder.append(arr[i]);
}

return string;

In this way you avoid the use of consecutive creation of substrings and the code is simpler.

Your method can be rewritten then in this equivalent way:

public static String mirrorEnds(String string) {
    final int len = string.length();
    final int half = len / 2;
    char[] arr = string.toCharArray();

    StringBuilder builder = new StringBuilder();
    for (int i = 0; i < half; ++i) {
        if (arr[i] != arr[len -1 -i]) {
            return builder.toString();
        }
        builder.append(arr[i]);
    }

    return string;
}


You could use guard statements and extract out the switch(response.StatusCode) block to a method. Furthermore, I'd replace the three-letter magic strings with constants. Their name could come from the comment around the magic string (UP_TO_DATE for "UTD" etc.). It would make the comment(s) unnecessary.

private Exception CreateHttpStatusException(Request Request, HttpWebResponse response) {
        switch (response.StatusCode)
        {
            //Generated by web app
            case HttpStatusCode.BadRequest:
                return new ArgumentException(String.Format("The Request passed to CheckForUpdate was incomplete: AppName:{1}; Channel:{2}; Version:{3}", Request.AppName, Request.Channel, Request.Version));
            case HttpStatusCode.Unauthorized:
                return new UnauthorizedAccessException("The serial number for this application was invalid.");
            case HttpStatusCode.ServiceUnavailable:
                return new AppDomainUnloadedException("The web service is currently unavailable.");
            //Common server errors
            case HttpStatusCode.NotFound:
                return new FileNotFoundException("The updater server page could not be accessed.");
            case HttpStatusCode.InternalServerError:
                return new WebException("The web server encountered an error.");
            //Unexpected server errors
            default:
                return new ApplicationException("An unexpected error occured: " + response.StatusCode);
        }
}

public bool CheckForUpdate(Request Request)
{
    HttpWebRequest httpRequest = (HttpWebRequest)HttpWebRequest.Create(UpdateServerAddress + "http://{0}/update.php?{1}" + Request.ToString());
    httpRequest.UserAgent = "KMUpdaterClient/" + Assembly.GetExecutingAssembly().GetName().Version.ToString();
    httpRequest.Accept = "text/plain";
    HttpWebResponse response = (HttpWebResponse)httpRequest.GetResponse();
    if (response.StatusCode != HttpStatusCode.OK)
    {
        throw CreateHttpStatusException(Request, response);
    }

    string responseString = String.Empty;
    using(StreamReader sr = new StreamReader(response.GetResponseStream()))
    {
        responseString = sr.ReadToEnd();
    }
    response.Close();
    switch (responseString.Substring(0, 3))
    {
        case "UTD":
            //Application is up to date
            return false;
        case "AVL":
            return true;
        case "ERR":
            throw new ApplicationException("An error occured on the server: " + responseString.Substring(4));
        default:
            //Unexpected
            throw new ApplicationException("An unexpected response was recieved by the server: " + responseString);
    }
}


well I used the MS sql for reference but that should be a bit batter. I would also reccomend you to structure your sql cos that way you get a better overview of things.
Carefull the below seelect is not grouped you can group it as a subquery again

SELECT q.id, q.topic_id, q.question, a.answer, a.is_correct, a.id as ans_id,
    q.answer_type, q.image_url, q.created_date, uaAll.topic_id as userdone_topic,
    uaCorrect.answer_id as user_correct_id
FROM questions q
    inner join topics t on q.topic_id = t.id
    inner join answers a on q.id = a.question_id
    inner join status s on q.created_date = s.month_date
    left outer join
    (
        SELECT top 1 ua.topic_id
        FROM UserAnswers ua
        where ua.userid = ''
    ) as uaAll on t.id = uaAll.topic_id
    left outer join (
        select ua.answer_id,ua.question_id
        FROM UserAnswers ua
            inner join answers a on a.id = ua.answer_id
        where ua.userid = ''
            and a.is_correct <> 0
    ) as uaCorrect on q.id = uaCorrect.question_id AND a.id = uaCorrect.answer_id
WHERE s.status = 2


ScreenUpdating

In order for you to interact with a spreadsheet (e.g. moving the mouse, selecting a cell) , the display on your monitor is re-drawn something like 30+ times per second. This takes a lot of processing power.

If you set Application.ScreenUpdating = False then, while it is false, the screen will not be updated, and your code will run much faster.

Crucially though, make sure it is set back to True before your code ends. Else your code will finish running, but your user will think that Excel has frozen because the screen won't respond to their mouse.

Make sure that before any End/Exit statements, or if errors are thrown, that you change the setting back.

Like so:

Public Sub DoThing()

    Application.ScreenUpdating = False

    On Error Goto CleanFail

    ...

    ...

    Code

    ...

    ...

CleanExit:

    Application.ScreenUpdating = True

    Exit Sub

CleanFail:

    On Error Goto 0

    '/ Handle errors here

    Resume CleanExit

End Sub

And now, assuming you put some kind of error handling in, your sub will always exit through CleanExit, which will always reset ScreenUpdating back to normal.


Quick sort implementation in JavaScript in prototype style

Looks okay to me.

I would probably go for if ( i != j ) { which could be faster than if ( i < j ) {
You have a ton of short variable names, I guess that's ok for a sorting routine, though I would still rename x to m(iddle).
I would have declared tempItem right under i and j

For the part you are not so interested in;

Capital S in Sort is reserved for constructors
I think reduce is more appropriate than forEach in DumpArray
You should not put code on the same line after an else statement
Now that I think about it the dump routine could be reduced to

Sort.prototype.DumpArray = function() {

var prefix = 'The content of array: [ ';
//Duck typing, just test for join
if( this.arrayTest.join )
    console.log( prefix + this.arrayTest.join(', ') + ' ]'  )
else
    console.log( "Input: " , this.arrayTest );
};


Create one httpservice and extend it in your service, for example:

HttpService:

export class HttpService  {
    protected userInfo:IUserModel;

    constructor(public http: Http, public user: User) {
        this.userInfo = this.user.getInfo();
    }

    /**
     * method http get
     * @param url
     * @param params
     * @returns {Http}
     */
    fetch(url, params, addData) {
        let headers = new Headers();

        headers.append('Content-Type', 'application/json');
        headers.append('User-Id',  this.userInfo.id);
        headers.append('Token',  this.userInfo.accessToken);

        if(addData.accessType) {
            headers.append('Access-Type', '1');
        }

        if(addData.limit) {
            headers.append('Offset-Step',  addData.limit);
        }

        if(addData.page || addData.page === 0) {
            let count = (parseInt(addData.page )- 1) * parseInt(addData.limit);
            headers.append('Count',  count.toString());
        }

        let options = new RequestOptions(
            {
                headers: headers,
                search: params,
            });

        return this.http
            .get(
                url,
                options
            )
             .map(this.extractData)
            .catch(this.handleErrors);
    }

    /**
     * method http post
     * @param url
     * @param data
     * @returns {Http}
     */
    send(url, data) {

        let body = JSON.stringify(data);
        let headers = new Headers({
            'Content-Type': 'application/json',
            'User-Id':  this.userInfo.id,
            'Token':  this.userInfo.accessToken
        });

        let options = new RequestOptions({ headers: headers });

        return this.http.post(url, body, options)
             .map(this.extractData)
            .catch(this.handleErrors);
    }

    /**
     * method http put
     * @param url
     * @param data
     * @returns {Http}
     */
    stick(url, data) {
        let body = JSON.stringify(data);

        let headers = new Headers();

        headers.append('Content-Type', 'application/json');

        headers.append('User-Id',  this.userInfo.id);
        headers.append('Token',  this.userInfo.accessToken);

        return this.http
            .put(url, body, {headers:headers})
            .map(this.extractData)
            .catch(this.handleErrors);
    }

    /**
     * method http delete
     * @param url
     * @param params
     * @returns {Http}
     */
    remove(url, params) {
        //var data = Object.keys(params).map(function(k) {
        //    return encodeURIComponent(k) + '=' + encodeURIComponent(params[k])
        //}).join('&');
        //url += '?' + data;

        let headers = new Headers();

        headers.append('Content-Type', 'application/json');

        headers.append('User-Id',  this.userInfo.id);
        headers.append('Token',  this.userInfo.accessToken);

        for(var i in params) {
            headers.append(i,  params[i]);
        }

        return this.http.delete(url, {headers:headers})
             .map(this.extractData)
            .catch(this.handleErrors);
    }

    private extractData(res: Response) {
        let data = res.json();
        return data.body ? data.body.message ? data.body.message : {} : {};
    }

    private handleErrors(error: Response | any) {
        let errMsg: string;
        if (error instanceof Response) {
            const body = error.json() || '';
            const err = body.error || JSON.stringify(body);
            errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
        } else {
            errMsg = error.message ? error.message : error.toString();
        }
        console.error(errMsg);
        return Observable.throw(errMsg);
    }

}

And in your child service extends by HttpService:

export class SomeService  extends HttpService {

  constructor(private urls: Urls, http: Http, user: User) {
    super(http, user);
  }

  getCheckoutDetails(data): Observable<UserDetail> {
    let query = `7668`;
    header = {};
    return  this.fetch(this.appConfig.getAPIUrl() + `/buy/getDetails?${query}`);
  }

}

Maybe you need a correct HttpService.


Efficient storage and calling of varying objects

It's hard to know where to start with this, but here are some things that may help you improve your code.

When seeking a review, provide full code

The posted code is just a fragment with a lot of pieces missing.  For instance, all of the taste_box_x functions are missing and it's not really very obvious what they might be.  To get a better review, post a better question.

Pass complex types reference rather than by value

For complex types such as std::vector, it's usually better to pass by reference rather than by value to avoid forcing each function call to make copies.  If the passed object should not be modified by the routine, pass a const reference.

Use classes

Since this is C++, it would make sense to use classes.  For example, one could imagine that there is a base class box from which each of the box types might be derived.  User taste preference could be an std::unordered_set in which each fruit type is the key and the value would be that user's taste weighting value.  Fruits might be an enum class, etc.

Don't abuse using namespace std

Putting using namespace std at the top of every program is a bad habit that you'd do well to avoid.


You can construct LINQ queries step by step instead of writing them all at once

parts = Database.Parts;
if (filter == "123") {
    parts = parts.Where(p => p.Number[0].IsDigit())
} else if (filter != "All") { // Alphabetic filter
    parts = parts.Where(p => p.Number.StartsWith(filter))
}
int totalParts = parts.Count();
parts = parts
    .OrderBy(p => p.Number)
    .Skip((page - 1) * pageSize)
    .Take(pageSize);

I followed the DRY software design principle here. DRY = Don't Repeat Yourself. If you repeat the same (or almost the same) code over and over, the code is less maintainable and is more susceptible to mistake. The fact that you have to write more, if you repeat yourself, is rather secondary.


How is my Java code for stack implementation?

The stack that you have implemented (I guess for an assignment) is too limited because of the following:

It does not support generic types. Since every container class in Java can store any object, I would suggest you to incorporate that facility in your data structure as well.
It has only a limited storage capacity, due to the use of Java array. It would be better to use a container class that can grow dynamically, such as an ArrayList, LinkedList or a Vector.
You should properly handle the boundary condition of popping from an empty stack.
Try to test your main function with a real-life application, such as evaluating a post-fix expression or checking valid parenthesization etc.


Hint:

$$
\sum_{i=1}^ni = \frac{n (n+1)}{2}
$$

With this you can compute the sum of 1 to n without looping. Can you figure out a way to do this for all digits with increments of 3? And 5?

The last thing to consider is that with this method, you are counting all digits divisible by 15 double, since they are both divisible by 3 and 5.


Sum of primes between two number from optimized Sieve of Eratosthenes

What you did is called Sieve of Sundaram and saves half the memory. You can save factor 8 if you use a BitSet (or implement it manually e.g. using a long[]). For small numbers it costs some time, but for big numbers it may be faster when random access is involved (less memory means that more fits in cache). When dealing with really big primes, you want both optimizations.

private static boolean[] isPrime(){
    int root=(int) Math.sqrt(MAX)+1;
    int limit=(MAX-1)/2;
    boolean[] isPrime=new boolean[limit];
    Arrays.fill(isPrime, true);
    root = root/2 -1;

You really shouldn't do things like this. The problem is already confusing by the fact that you start with a number but work with an index which is half as big (and rounded down and in your case I guess additionally decremented). It's much better to use one variable for one thing.

    for(int i = 0; i < root ; i++){
        if(isPrime[i]){
            for( int j = 2*i*(i+3)+3 , p = 2*i+3; j < limit ; j=j+p ){

Is it correct? How do you know that you should iterate exactly up to root? Why 2*i*(i+3)+3? The first value to cross out is usually p*p, which you need to transform to index.

I wouldn't use the p = 2*i+3 formula. When compared to p = 2*i+1, you save one bit, bit it gets even more confusing.

What about something like

int numberToIndex(int oddNumber) {
    // Asserts cost nothing unless switched on.
    assert (oddNumber & 1) == 1;
    // The right shift is just a faster division by 2
    return oddNumber >> 1;
}

int indexToNumber(int index) {
    return 2 * index + 1;
}

? By using these functions, you could make it nearly readable.

    truetruetruefalsetruetruefalsetruetruefalsetruefalsefalsetruetruefalsefalsetruefalsetruetruefalsetruefalsefalsetruefalsefalsetruetruefalsefalsetruefalsetruetruefalsefalsetruefalsetruefalsefalsetruefalsefalsefalsetruefalse

Can you read it? Do you want to read it? Maybe you should write a formatting method and get something like

3, 5, 7, -9, 11, 13, -15

where the negatives denotes non-primes (or leave them out or whatever debugging output suits you). In any case you should write a test, so that you don't have to look at the output every time you change anything. You can test some probes like

assertTrue(isPrime(127));
assertFalse(isPrime(129));

and test some small primes in loop (and get the expected value using some trivial method). Finally, you can verify that there are 105_097_565 primes which fits in int.

I wouldn't call the array isPrime as isPrime[0] must be false as 0 is no prime. So let's call it isPrimeIndex.

  Now what really bugging me is the indexing i did in primeSum() method for this optimized sieve

Sure, the 2 needs a special handling and then you should make sure that m and n are odd. I guess that you code is wrong and I'd try something like this instead:

private static int primeSum(int n, int m) {
    if (m < 2) {
        return 0; // no primes below 2
    }
    if (n < 2) {
       n = 2; // no primes below 2
    }
    // Add 2 if in range.
    int sum = n <= 2 && 2 <= m ? 2 : 0;
    // Round up to next odd in a very hacky way.
    n += ~n & 1;
    // Round down to next odd.
    m -= ~m & 1;
    for (int i = numberToIndex(n), p = n; i<=numberToIndex(m); ++i, p+=2) {
        sum += isPrimeIndex[i] ? p : 0;
    }
}

How does my hacky rounding work: If n is odd, then ~n is even and ~n & 1 is 0, so nothing changes. If n is even, then ~n is odd and ~n & 1 is 1, so n gets incremented. You could use something like n += (n % 2) == 0  ? 1 : 0 which is equivalent (but slower) or whatever suits you.

  So should i again include these cases and deal with it separately ? like this

My strategy is to handle special cases upfront (here: deal with the two) and normalize everything ASAP (here: ensure that m and n are odd). This tends to make things simple.


Any reason you can't use the SORTs /COMPARE refinement here?

Here is a working example of sort-by that uses it:

sort-by: function [
    series     [block!]
    comparator [block! word!]
  ][
    sort/compare series func [`a `b] either word? comparator [
        [`a/:comparator < `b/:comparator]
    ][
        sortie: function [by] [
            s: to-paren copy/deep comparator
            forall s [
                if all [path? s/1  s/1/1 = 'object] [s/1/1: by]
            ]
            s
        ]

        compose [(sortie '`a) < (sortie '`b)]
    ]
]


Exporting doc types using queues and multithreading

Rather than reviewing your specific code -- which at first glance seems very, very buggy -- let me answer your question directly:

  What are the best practices with multithreading in C#?

Don't. Multithreading is a bad idea. Programs are hard enough to understand already with a single point of control flow in them; why on earth would you want to add a second, third, fourth... ? Do you enjoy tracking down incredibly difficult-to-reproduce, impossible-to-understand bugs? Do you have an encyclopaedic knowledge of the differences between weak and strong memory models? No?  Then don't write multithreaded programs!  Processes are a perfectly good unit of work; if you have work to do, spawn a process.
Oh, so you want to do multithreaded programming anyways.  In that case use the highest level of abstraction available.  Programming against threads directly means writing programs about workers when you could be writing programs about jobs. Remember, workers are just means to an end; what you really want to get done are the jobs.  Use the Task Parallel Library: tasks are jobs, threads are workers. Let the TPL figure out for you how to make efficient use of workers.
Wait, let's go back to point one again.  Ask yourself do you really need concurrency? With true concurrency we have two or more points of control in a program actually active at the same time. With simulated concurrency the two points of control take turns using the processor, so they are not actually concurrent. Most of the time we end up with simulated concurrency, because there are more threads than there are processors. This leads us naturally to the conclusion that perhaps actual concurrency is not what we need. Much of the time what people really want is asynchrony; concurrency is one way to achieve asynchrony, but it is not the only way.  Use the new async/await functionality in C# 5 to represent asynchronous workflows.
If you are confused by the previous point, and think wait a minute, there is no way to achieve asynchrony without multiple threads of control in a process, read Stephen Cleary's article There Is No Thread.  Don't try to write multithreaded programs until you understand it.
At all costs avoid shared memory. Most threading bugs are caused by a failure to understand real-world shared memory semantics. If you must make threads, treat them as though they were processes: give them everything they need to do their work and let them work without modifying the memory associated with any other thread. Just like a process doesn't get to modify the memory of any other process.
Oh, so you want to share memory across threads even though doing so is incredibly bug prone? Again, let me go back to use the highest level tool available to you. Those tools were written by experts. You're not an expert. Do you know how to make a lazily-computed value written to a field such that you are absolutely guaranteed that the lazy computation executes no more than once and the field is never observed to be in an inconsistent state no matter what is in any given processor cache?  I don't. You probably don't. Joe Duffy does, which is why you should use the Lazy<T> primitive he wrote rather than trying to write your own.
Oh, so you want to write your own code that shares memory? Then take the lock for heaven's sake. I see so much buggy code where people get into their heads that locks are expensive and they write this convoluted godawful wrong code that evades taking a lock that would have cost them twelve nanoseconds to just take. Avoiding a lock to save on its cost is like complaining that the electricity takes too long to get to the light bulb when you flip the switch. Locks are a powerful tool for ensuring memory consistency; if you're going to program shared memory at the thread level, you avoid locks at your peril.
If you use Thread.Sleep with an argument other than zero or one in any production code, you are possibly doing something wrong. Threads are expensive; you don't pay a worker to sleep, so don't pay a thread to sleep either. If you are using sleeps to solve a correctness issue by avoiding a timing problem -- as you appear to be in your code -- then you definitely have done something deeply wrong. Multithreaded code needs to be correct irrespective of accidents of timing.


Check sum of all primes under two million

Ruby favours Functional Programming, let me show you an example.

def prime?(n)
  limit = Math.sqrt(n).to_i + 1
  (2..limit).all? { |i| n % i != 0 }
end

This improves readability as the code makes use of all? to implicitly loop (Instead you looped explicitly) and is faster as the limit is the sqrt of n and not n and all? short-circuits (returns as soon as one condition is false).

Also the second part would benefit from FP:

puts (2..2000000).select{ |n| prime?(n) }.inject(:+)

In general, in Ruby explicit looping is the exception and not the norm, as there are so many built-ins and shortcuts to make use of.

Each function I made use of here is listed at The Ruby Enumerable Documentation and I warmly suggest studying in detail that page, it will take a bit of time, but the time you will save in the future by using it instead of reinventing the wheel each time will be more than worth it.


Filter out comments in Delphi source code

I only have a few minor comments.
The first is about your empty while loops, such as:
    for (i = sbuf->sbumpc(); i == '{'; i = sbuf->sbumpc()) {
        while ((i = sbuf->sbumpc()) != '}');
    }

I generally prefer to at least put the semicolon on a line by itself, to make it fairly obvious that it's intentional that the semicolon wasn't just accidentally entered at the end of a line where it shouldn't have been:
for (i = sbuf->sbumpc(); i == '{'; i = sbuf->sbumpc()) {
    while ((i = sbuf->sbumpc()) != '}')
        ;
}

In this case, there's no other statement there before the closing brace that the loop could be controlling so it's probably less serious than usual, but I still prefer consistency (even though: "a foolish consistency is the hobgoblin of small minds").
Second, if you're going to do all this, I'd probably add a little commentfilterstream class on this order:
#include <fstream>
#include <istream>

class commentfilterstream : public std::istream {
    std::filebuf buffer;
    commentfilterbuf buf;

public:
    // or use an `std::filesystem::path` instead of a string.
    commentfilterstream(std::string const& filename)
        : buf(&buffer)
        , std::istream(&buf)
    {
        buffer.open(filename.c_str(), std::ios_base::in);
    }

    ~commentfilterstream() { buffer.close(); }
};

This lets you simplify the client code a bit to become something like this:
int main(int argc, char* argv[])
{
    if (argc != 2) {
        std::cerr << "Usage: testfilter inputfile\n";
        return 0;
    }

    // Opening stream is now one step, just like usual:
    commentfilterstream in{argv[1]};

    if (!fin) {
        std::cerr << "Error: could not open " << argv[1] << "\n";
        return 1;
    }

    std::string line;
    for (std::string line; std::getline(in, line); ) {
        std::cout << line << '\n';
    }
}

Finally, I'd probably put the buffer and filter into a namespace (e.g., Delphi) to give a little better indication of their intended purpose (Delphi::commentfilterstream).


Setting manager class for reading and managing Settings.ini file of my program

Defualt Java style is to have the opening braces on the same line, but that's down to preferences. Just be consistent in your code.

private static final String SETTINGS_FILE_PATH = "D:/Programing/Java/Software Installer/src/main/resources/Settings.ini";

You want to pass that path, somehow, as it is not portable.

public class SettingsManager
{
    private static SettingsManager instance;

    public static SettingsManager getInstance()
    {
        if(instance == null)
        {
            instance = new SettingsManager();
        }
        return instance;
    }
}

This is not thread-safe, in case you care about it. An obligatory number of threads could end up with their own, not-shared instances of the SettingsManager. There are three ways to prevent that:
The first is to use a static initializer:
public class SettingsManager
{
    private static SettingsManager instance;

    static
    {
        instance = new SettingsManager();
    }
}

Static initializers are guaranteed to be synchronized and will only be executed once the class is accessed.
The second option is to synchronize the whole method:
public class SettingsManager
{
    private static SettingsManager instance;

    public static synchronized SettingsManager getInstance()
    {
        if(instance == null)
        {
            instance = new SettingsManager();
        }
        return instance;
    }
}

This guarantees a single instance for everyone, but it means that an expensive lock is acquired for each access. "Expensive" in this case means "compared to simply getting the value", in 99.99% of the cases you will not notice the performance difference to method #3.
The third method is to check twice whether the value is available, once "cheap", and then synchronized:
public class SettingsManager
{
    private static SettingsManager instance;

    public static SettingsManager getInstance()
    {
        if(instance == null)
        {
            synchronized(SettingsManager.class)
            {
                if(instance == null)
                {
                    instance = new SettingsManager();
                }
            }
        }
        return instance;
    }
}

That skips the locking in most instances, except when required, namely if two threads try to access the instance for the first time.

private static final String SETTINGS_FILE_PATH = "D:/Programing/Java/Software Installer/src/main/resources/Settings.ini";

You want to pass that path, somehow, as it is not portable in the slightest in this way.
Now, that leads to the problem that you only have one single, global instance, and if you pass the path you have to ask yourself the question what should be done when a second instance with a different path is requested. It might be better to have a single instance which you pass around in your application, or which you make globally accessible throughout your application, and not through the class level of this class.

        Ini settings = null;

        try
        {
            settings = new Ini(new File(SETTINGS_FILE_PATH));
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }

You most likely want to re-throw that exception, or let it propagate freely by letting loadSettings throw IOException. Silently swallowing exceptions might lead to a really bad headache when debugging problems.

Map<Software, String> list = new HashMap<Software, String>();

That's not a list, that's a map. Naming like that is confusing. Also, in Java 8+ you can omit the types in the constructor, as they are derived from the declaration:
Map<Software, String> list = new HashMap<>();

public enum Software
{
    AIMP,
    CCleaner,

Java convention is that enum members are considered constants, therefor should be UPPER_SNAKE_CASE.

Now, what you don't want is that Software enum, that should be configuration that you read, too, because that allows easier maintenance and extension of the software. Overall, your ini format seems not suited for what you want, it looks more like you want to invert the format:
[AIMP]
Local Repository=...
Network Repository=...
Online Repository=...
Arguments=...

[CCleaner]
Local Repository=...
Network Repository=...
Online Repository=...
Arguments=...

Because with that in place, you can kill off Software completely and make your application driven by configuration. You simply read the ini file and display the list of software that is configured instead of having it hard-coded.


Let me first review this from an readability point of view, then answer your question and an proposed solution.

Naming

Your variable names could be more descriptive.

$array -> (maybe) $conjugations (german: $konjugationen)
$stamm -> $word_stem (german: $wort_stamm)
$zeiten -> $tenses (german: $zeitformen)?

Structure

The most intriguing part for me is $array's structure.
As I understand it, it is a 2D table of conjugations of the $verb where rows have the same tense and columns the same person. This should be somehow reflected in the data structure because it is not obvious to the viewer.
Maybe you should even implement a class for that.

Comparison

Maybe it has to do with my lack of domain knowledge (I don't speak french) but I find both solutions unreadable.
This is enforced by the naming problems.

The second one looks slightly more general with regard to reuse but the if portion is not very flexible.

Improvement

As I said, I have no idea about french but I suppose this holds true:

Each verb can be conjugated for person and tense. There is a set of rules that defines how this happens for each person and tense depending on the verb's form and a set of exemptions from those rules.

The solution to the problem consists of:

Classifying the verb as to which rule/exemption to apply
applying the rule

To me this sounds like 1. could be solved by a factory that creates strategy instances for 2.

$conjugator = get_conjugator($verb, $tense, $person);
$conjugated_verb = $conjugator->conjugate($verb);

Maybe the exceptions/rules are even partial per tense or person. This would mean you would have to make this distinction as well and produce a separate conjugator for each tense, person, verb triple.

Now the code you have posted is pretty much the part that goes into the implementation of a conjugator. And seeing that there could be many of them it would be nice to make implementing them as simple as possible.

Their interface would probably consist of a function that detects whether they are applicable (the if condition in your case) and a function that does the actual flexion of the input (the if's then code block).


The CoffeeScript looks fine to me. You'll still need the context var just as in plain JS, because you're not dealing with this. If you were, you could maybe use the fat arrow to preserve the this context, but even so it'd require some refactoring, and end up very different from the original JS.

CoffeeScript's fat arrow is basically meant to be used where you'd otherwise do the var that = this; trick in JavaScript. But since you're not doing such things in your JavaScript, there's no need or opportunity for it in the CoffeeScript either.


I think you can use querySelectorAll() - for example:

function on (type, target, callback) {
  document.querySelectorAll(target).forEach(function (elem) {
     elem.addEventListener(type, callback);
  })
}

Your function findParent seems similar to element.closest() . In case you need it to work with IE, you can use the code below. It works with a selector, not just a class name.

closest = (element, selector) => {
    while(element) {
        //For IE11
        if (!element.matches)
            element.matches = element.msMatchesSelector;

        if (element.matches(selector))
            return element;

        element = element.parentElement;
    }
}


Some suggestions:

You can use sys.argv or argparse to pass the size on the command line. The latter can check the type and range for you, and print an appropriate error message and usage string. You can specify a validator function in the type argument to check for non-trivial values.
print_tree does not print the tree, it returns a string representation of it. That is the job of __str__, a special internal method you can override to define the string representation of a class.
"node" in add_node is redundant.
Running this code through black will improve the formatting slightly. flake8 and mypy (with a strict configuration) can help make the code more idiomatic.


Some thoughts:

It is good that you explicitly annotated the function's definition with its required calling convention. Make sure that you do the same thing for the declaration in the public C++ header, and for the P/Invoke declaration (if applicable) in your .NET application.

Calling convention mismatches are a common source of bugs, and you don't want to rely on the correct compiler flags (specifying the default calling convention) having to be specified in order for the code to work correctly.
This line:

dpi = *reinterpret_cast<int *>(inEntryInfo->UserData);

hoists a giant red flag, for at least a couple of reasons:

Why is dpi a global (module-scoped?) variable? It looks to me like it just needs to be a local variable. I'm assuming that you raised its scope so it would be usable within the GetFooAddress and/or FrobnicateFoo functions? If so, you should pass it as a parameter to these functions. Always keep the scope of variables to the minimum level necessary—this is the same rule as in C#/VB.NET, of course.
That reinterpret_cast business is dicey. Reinterpretation casts are always a bit dicey, and this one especially, since it doesn't have a reassuring comment nearby that explains how it is safe. :-) You didn't show us the definition of the ENTRY_INFO type, so it's hard to confirm whether or not this actually is safe, but there really aren't that many cases where you can legitimately reinterpret a pointer to one primitive type as a pointer to another primitive type. If I had to guess, I'd say that UserData is a void*? If at all possible, you should just change it to be the int* that you ultimately want. The only advantage of a void* would be to achieve something akin to VB's Variant, but that requires some way to determine what the actual type is. Your code doesn't have that, it just assumes that the pointer is actually to an int. Lots of different ways that can go wrong. Hard to say exactly how you should fix this without more information, but definitely know that this smells funny and very likely hides a bug.
Beyond the question of the cast, you are potentially dereferencing a null pointer, which is undefined behavior and definitely a bug. You need to be checking this explicitly, just like you are all of the other error conditions, unless you can guarantee that the caller will never pass you a null pointer (in which case, verify that assumption using an assert).

  As a .NET developer, I'm used to "Unicode is default unless there's a very good reason against it", and, thus, I just use L"..." string literals and ...W API methods without giving it further thought.

This is completely correct. In fact, this doesn't have anything to do with .NET; it is more precisely a Windows thing. The Windows operating system uses Unicode internally (at least, all versions of NT do, which means everything modern and semi-modern), and there is no reason to ever use narrow/ANSI strings unless you need the code to run on Windows 9x. Therefore, your adopted practices make very good sense.

  (std::wstring(...) + ... + ...).c_str() seems to be the simplest way in C++ to do string concatenations of wchar arrays (denoted as ...) without having to worry about memory allocations.

Indeed, the + operator is the simplest way to concatenate strings in C++. However, it is not necessarily the most efficient. Use of the + operator is creating a bunch of temporaries, which the compiler may or may not be able to optimize out. In general, you should prefer the += operator to help stave off the proliferation of temporary objects (or the append member function, which is slightly less terse, but may be easier to reason about because there are no operator precedence concerns).

Also, not having to worry about memory allocations may be a curse disguised as a blessing. In general, pre-allocating the required amount of space (using the reserve member function) will net you better performance than letting the library code do incremental allocations as-needed, assuming of course that you have some idea in advance of how much space you will need.

That said, neither of these things matter if the code you're writing is not performance-sensitive. And obviously this isn't, since it's calling OutputDebugString, which is a very slow function.

  We're talking about a few bytes here. Isn't that a case of premature optimization? Or is it generally "good practice" in C++ to worry about such things?

Yes, it is probably "good practice" in C++ to worry about such things. A major reason for people to write code in C++ is because they care about efficiency.

  I could use wostringstream, but it would just make the code more complicated.

Well, that is arguable, and I see that πάντα ῥεῖ already made the argument. This is ultimately up to you: either will work, and since debug output is not performance-sensitive, there isn't a clear case to be made either way as far as I'm concerned. However, on the readability front, you can actually get a similar effect by using the += operator (which I'd recommended anyway—see code below).

I do want to quibble slightly with one thing πάντα ῥεῖ said, though—or at least, my interpretation of what he said… While it is, in general, completely true that more lines of code do not make a program slower or more complicated, using stream output probably is going to be slower than simple string concatenation. I would only resort to streams if I needed to format the output in some way.
Also, speaking of OutputDebugString, this is almost certainly a function that you only want to call in debugging builds. It won't be conditionally compiled out like the equivalent Debug functions in .NET; you have to do this manually. The simplest way is to use a preprocessor conditional, something like:

#ifdef DEBUG
    OutputDebugStringW(...)
#endif  // DEBUG

Another alternative would be to write your own TRACE macro (MFC and other commonly used C++ libraries have one included) that either expands to a call to OutputDebugString or to a no-op, depending on the build settings. For example:

#ifdef DEBUG
    #define TRACE(str)    OutputDebugStringW(str)
#else
    #define TRACE(str)    (void)(str)
#endif  // DEBUG

There are all sorts of ways to make this more complicated, more flexible, and more useful. In fact, you might not decide that you don't want to base it on the definition of a DEBUG preprocessor symbol at all, since you might want this debug trace available in an instrumented but otherwise optimized build. However, I would not recommend spewing a bunch of debug info in a shipping build. It is slow and unhelpful to the typical user.

If you really need this information for remote debugging, you should almost certainly be writing it into a log file, instead, since OutputDebugString is effectively an expensive no-op if there is no debug listener attached! Investigate a logging framework for C++, or write your own if you have unlimited time on your hands. Either way, make it so that this "verbose" mode can be enabled as a run-time option at the request of your technical support staff.
One last point about OutputDebugString: I personally believe that any string you pass to it should always end with a trailing new-line character. It doesn't get inserted automatically, so multiple back-to-back calls to OutputDebugString—even in completely different modules—will result in cluttered and unreadable output otherwise. A TRACE macro could certainly automatically append this \n, though.

  I know that failing silently is bad practice, but the signature of FooEntryPoint is part of the interface contract I'm given, so this is "by design".

Fair enough, but I have to again agree with πάντα ῥεῖ that you should be using an assert here for ease of debugging—unless that is, failure is an expected scenario.

You should be aware, though, that idiomatic C++ would use exceptions for things like this that cannot reasonably be handled by the callee, just like idiomatic C#/VB.NET code. This wouldn't affect the signature (the function would still return void), but it would certainly affect the interface, so I realize that may not be an option for you.
Instead of the NULL macro that you would use in C code, modern C++ code should prefer to use nullptr for a variety of reasons. You can basically use it as a drop-in replacement, with the advantage that it is a distinct type so it won't ever be ambiguous with the integer literal 0.
I also like to obsessively make every local variable that I'm not going to change in subsequent code const. Although this doesn't really enable any additional optimizations, it makes it easier for me to reason about the code and increases the likelihood that the compiler will catch bugs. In fact, I'm of the opinion that const should have been the default for locals, and you should have had to explicitly mark them as mutable if you wanted that. As a case in point, I would make the address and result variables explicitly const.
My last observation is almost purely stylistic, and probably at least somewhat controversial, but I would format the code differently to ensure only a single exit point. I'm not at all dogmatic about this, but I think in this particular case it is clearer to think about the operations you're doing in a chain or hierarchy, so it is natural to format them as a series of nested blocks:

const FARPROC address = GetFooAddress();
if (address != nullptr)
{
    const NTSTATUS result = FrobnicateFoo(address);
    if (FAILED(result))
    {
    #ifdef DEBUG
        std::wstring str = (L"Failed to frobnicate foo: ");
        str += RtlGetLastErrorString();
        str += L"\n";
        OutputDebugStringW(str.c_str());
    #endif  // DEBUG
    }
}
else
{
#ifdef DEBUG
    OutputDebugStringW(L"Foo address not found.\n");
#endif  // DEBUG
}

I'm neutral on whether the error condition (address == NULL) should come first, or whether the success condition should come first. There are readability arguments both ways. I tend to prefer putting the success condition first to increase the likelihood of successful static branch prediction, but that's becoming a non-issue on current generations of processors that don't simply assume "not taken" for all forward conditional jumps. I just wrote a crazy-long answer about this that ultimately concludes it doesn't matter.


Find the largest sum of the GCD and LCM of two numbers in a range

I decided to take a stab at this, and I ended up reducing your algorithm down to one line (tested for equality with the original algorithm from n = [0,500] :

highest_value = (n > 2) ? ( 1+n*(n-1) ) : ( 2*n );

If you would like to see the steps I took, then please see my steps below...

Let's start by removing the comparison in the 2nd loop by splitting up the 2nd loop into 2 parts:

for(int i = 1; i <= n; i++) {
    // smaller = j
    for(int j = 1; j < i; j++) {
        for(int y = 1; y <= j/*smaller*/; y++) {
            if(i%y==0 && j%y==0) gcd = y;
        }
        equation = gcd+((i*j)/gcd); //since lcm(x,y) = (x*y)/gcd(x,y)
        if(equation > highest_value) highest_value = equation;
    }
    // smaller = i
    for(int j = i; j <= n; j++) {
        for(int y = 1; y <= i/*smaller*/; y++) {
            if(i%y==0 && j%y==0) gcd = y;
        }
        equation = gcd+((i*j)/gcd); //since lcm(x,y) = (x*y)/gcd(x,y)
        if(equation > highest_value) highest_value = equation;
    }
}

Now let's extract the simple case where i == j by adding

// i == j
// gcd = i;
// equation = gcd+((i*j)/gcd);
// equation = i + (i*i)/i
equation = 2 * i;
if(equation > highest_value) highest_value = equation;

and changing the limits of the second loop to exclude i == j

for(int j = i+1; j <= n; j++) {

we now have

for(int i = 1; i <= n; i++) {
    // i == j
    equation = 2 * i;
    if(equation > highest_value) highest_value = equation;
    // smaller = j
    for(int j = 1; j < i; j++) {
        for(int y = 1; y <= j/*smaller*/; y++) {
            if(i%y==0 && j%y==0) gcd = y;
        }
        equation = gcd+((i*j)/gcd); //since lcm(x,y) = (x*y)/gcd(x,y)
        if(equation > highest_value) highest_value = equation;
    }
    // smaller = i
    for(int j = i+1; j <= n; j++) {
        for(int y = 1; y <= i/*smaller*/; y++) {
            if(i%y==0 && j%y==0) gcd = y;
        }
        equation = gcd+((i*j)/gcd); //since lcm(x,y) = (x*y)/gcd(x,y)
        if(equation > highest_value) highest_value = equation;
    }
}

we can observe that the second loop checks the same values (just mirrored with i and j), so we can get rid of the second loop entirely giving us:

for(int i = 1; i <= n; i++) {
    // i == j
    equation = 2 * i;
    if(equation > highest_value) highest_value = equation;
    // smaller = j
    for(int j = 1; j < i; j++) {
        for(int y = 1; y <= j/*smaller*/; y++) {
            if(i%y==0 && j%y==0) gcd = y;
        }
        equation = gcd+((i*j)/gcd); //since lcm(x,y) = (x*y)/gcd(x,y)
        if(equation > highest_value) highest_value = equation;
    }
}

we can also observe that the maximum value for the i == j case will be where i == n, so we can get rid of that section and start our highest_value at 2*n :

int highest_value = 2*n;
int equation, gcd;

for(int i = 1; i <= n; i++) {
    // smaller = j
    for(int j = 1; j < i; j++) {
        for(int y = 1; y <= j; y++) {
            if(i%y==0 && j%y==0) gcd = y;
        }
        equation = gcd+((i*j)/gcd); //since lcm(x,y) = (x*y)/gcd(x,y)
        if(equation > highest_value) highest_value = equation;
    }
}

return highest_value;

Now let's look at the inner-most loop

for(int y = 1; y <= j; y++) {
    if(i%y==0 && j%y==0) gcd = y;
}

we know that y == 1 is a simple case where gcd = 1 and equation = 1 + i*j, so we can extract that from the loop:

equation = 1 + i*j;
if(equation > highest_value) highest_value = equation;

for(int y = 2; y <= j; y++) {
    if(i%y==0 && j%y==0) gcd = y;
}

let's also notice that the equation 1 + i*j has a maximum consistent with the maximum values of i and j where i = n and j = n-1 which gives us 1 + n*(n-1) or 1 + n*n - n. Now we can move this equation to the beginning of the function and check it against our initial highest_value of 2 * n. Don't forget to exclude the case where n == 0, because it is impossible to achieve a value of i or j == 0 inside the loop.

int highest_value = 2*n;
int gcd, equation;

if ( n > 0 ) {
    equation = 1 + n*(n-1);
    if(equation > highest_value) highest_value = equation;
}

We can notice that our new equation exceed our initial equation at a value of n >= 3

int highest_value, gcd, equation;

if ( n > 2 ) {
    highest_value = 1 + n*(n-1);
} else {
    highest_value = 2 * n;
}

We can notice that i == 1 and j == 1 will never be divisible by the initial value of y, so we can start them at 2. Then notice that the j loop never happens if i == 2, so we can start i at 3.

int highest_value, gcd, equation;

if ( n > 2 ) {
    highest_value = 1 + n*(n-1);
} else {
    highest_value = 2 * n;
}

for(int i = 3; i <= n; i++) {
    for(int j = 2; j < i; j++) {
        for(int y = 2; y <= j; y++) {
            if(i%y==0 && j%y==0) gcd = y;
        }
        equation = gcd+((i*j)/gcd);
        if(equation > highest_value) highest_value = equation;

    }
}

return highest_value;

Finally... We can notice a pattern where we can take this approach indefinitely where we can continue to factor our i and j, so I noticed a pattern where the initial highest_value is true for every i and j, so the final function is :

highest_value = (n > 2) ? ( 1+n*(n-1) ) : ( 2*n );


Reading Large Files in Java getting really slow

The issue is almost certainly in the structure of your Trace class, and it's memory efficiency. You should ensure that the instrType and hexAddress are stored as memory efficient structures. The instrType appears to be an int, which is good, but just make sure that it is declared as an int in the Trace class.

The more likely problem is the size of the hexAddress String. You may not realise it but Strings are notorious for 'leaking' memory. In this case, you have a line and you think you are just getting the hexString from it... but in reality, the hexString contains the entire line.... yeah, really. For example, look at the following code:

public class SToken {

    public static void main(String[] args) {
        StringTokenizer tokenizer = new StringTokenizer("99 bottles of beer");
        int instrType = Integer.parseInt(tokenizer.nextToken());
        String hexAddr = tokenizer.nextToken();
        System.out.println(instrType + hexAddr);
    }
}

Now, set a break-point in (I use eclipse) your IDE, and then run it, and you will see that hexAddr contains a char[] array for the entire line, and it has an offset of 3 and a count of 7.

Because of the way that String substring and other constructs work, they can consume huge amounts of memory for short strings... (in theory that memory is shared with other strings though). As a consequence, you are essentially storing the entire file in memory!!!!

At a minimum, you should change your code to:

hexAddr = new String(tokenizer.nextToken().toCharArray());

But even better would be:

long hexAddr = parseHexAddress(tokenizer.nextToken());

EDIT: Request to get help on how to debug the code:

To debug the code, you need to set a break-point in the method. Select the line System.out.println(...); and use the key-board short-cut Ctrl-Shift-B which will toggle a break-point, and you will get the 'dot' marker like the picture below:

Then, with that break-point enabled, you need to debug the program:

Right-click on the 'main' word in the public static void main (String[] ...) and select 'Debug As -> Java Application'

This should prompt you to go to the 'Debug' perspective, and you will have a window with the 'Variables' displayed. One of the variables will be hexAddr and you can expand it to show its contents. Here's a screen-shot:

From the variables section there are a few things of note. At the bottom, the 'value' variable is highlighted, and it's internal value is shown in the area below ( [9, 9,  , b, o, ......, r]

You can see the count and offset variables for hexAddr too. This means that the hexAddr variable stores the char[] array for the entire line, but also stores an offset and count in that array which it uses for managing the subset of the chars that this String instance is interested in


Python function to map True, False, and None to symbols for display

Because the code snippet is so small and missing any other context, it's hard to identify any problems in scaling / that may arise elsewhere in the code. Thus if you want a more tailored answer, you should add more code.

Yes, this is fine.

Regarding the isinstance() check, no. That only adds an extra level of indentation without justification.


Function to build a string based on the recursion depth

Review on code.
The term "ugly" is subjective. For some ugly is bad practice or anti-patterns, and there are others that will argue that current standards of good practice are "ugly" due to inefficiencies.
I will take ugly in this case to mean inelegant in the mathematical sense of the term. Thus below is a review in terms of improving code for simplicity and efficiency.
Simplify.
There is no reason to use statement clause for undefined in the form typeof blah === "undefined". Assuming that no input will equate to false apart from no arguments then if(! input) { is simpler.
However, there may be an input like f()(false), where the expected output is "fofalse", which will require a more robust test for undefined. So the safe option without knowledge of possible input is if(input === undefined){ which is still simplier (and more efficient).
For each call of the function f there are only two possible return values, the string that terminates the chain of calls or the function that is used to expand the return string.
Your inner function has 4 return possibilities, which is an obvious unneeded complication.
Simplicity also means not to repeat code. The outer function and inner function have the same functionality. Thus the outer function only needs to begin a process of building a string. This can be done via a closure, so all the outer function need do is define a communicating variable and a function to hold the closure. It does not need to do any form of logic.
Efficiency
Simplicity and efficiency go hand in hand.
The inner function should only return a string or a function to do the same.
The communication between the function calls is where you have added too much overhead with the creation of objects to communicate to the outer function.
You can use a closure variable to communicate information between calls and reduce the call stack depth by not needing to call the outer function. The closure is maintained by returning the inner function in the case of an undefined input.
The result.
The result is hopefully less ugly in your eyes. For me it is far simpler and nicely elegant.

function f(str) {
    var content = "f";
    return (function inner(str){
        if (str !== undefined) { return content + str }
        content += "o";
        return inner;
    })(str);
}

console.log(f("a"));
console.log(f()("a"));
console.log(f()()("a"));

Alternative.
I did toy with the following version but for me it is not as elegant due to the forced flow unique to Javascript that will put those from other languages out of joint. Though it is simpler in terms of token count but not in complexity.

function f(str) {
    var content = "f";
    return (function inner(str){
        return str ? content + str : ( content += "o", inner );
    })(str);
}

console.log(f("a"));
console.log(f()("a"));
console.log(f()()("a"));


Refactoring a series of if-return statements.

It seems that you are wanting your Check enum to be able to provide a little more information for you without the messiness of the if-then clutter. What about combining the status strings with the enumerator? Something like:

public class CheckStatus{
    public static readonly CheckStatus
      IsSuccessful = new CheckStatus { Value = "Approved" },
      AreClarificationsSent = new CheckStatus { Value = "Clarifications" },
      IsInProgress = new CheckStatus { Value = "Check in progress" },
      IsTemplateSent = new CheckStatus { Value = "Sent" },
      IsReceived = new CheckStatus { Value = "Received" },
      NotReceived  = new CheckStatus { Value = "Not Received" };

    private CheckStatus() { }
    public string Value{ get; private set; }
}

Very easy to maintain and puts the minor implementation details behind the purpose of the Check enumerator. Provides much the same benefit of an enumeration. I would have liked to make this a struct, but I would not (without going into IL) have a parameterless private ctor.


Generating and storing a unique salt in Oracle database using Java

Please use best practices in general when dealing with password hashing.

If you have to verify the database for your generated salt to be unique, you're using a bad salt generator. Make sure to focus on using a good generator instead.
Your hash function also seems weak. Consider using key stretching.

This should not be required:

while(isFound){
   isFound=false;
   String randomSalt=createRandomString(); //creates salt/random string
   ResultSet rs = stmt.executeQuery("SELECT * FROM mvUser where salt="+randomString);
   //check if salt is unique
   while (rs.next()) {
     isFound=true;
   }
}

And for hash, I would expect something like below, where hash is an established hash library (PBKDF2, bcrypt, scrypt, ..).

var hashedPW = hash(iterations, randomSalt, pw);


Let's start by analysing the current algorithm.

Each day that plants are dying, we iterate through all living plants. So the worst case would be if only one plant dies each day. In this case, we can see that the algorithm will take \$O(N^2)\$ time.

For example, the input sequence \$ 1, 2, 2, 2, 2, \ldots, 2\$ will exhibit this quadratic behaviour.

From the problem statement, \$1 \leq N \leq 10^5\$, so we will have to do better than \$O(N^2)\$.

We start with the easy case, when the current plant has more pesticide in it than the one to its immediate left. Then we know that the current plant dies after one day.

Otherwise, we look for the right-most plant to the left of us that has less pesticide than the current plant.

If there is no such plant then we know that the current plant will never die.

So suppose there is such a plant, and let's say it's at index \$i\$. I claim that the current plant (at index \$k\$) will die on day
$$\max \left\{ d[j] \,\middle|\, i < j < k \right\} + 1,$$
where \$d[j]\$ is the day on which plant \$j\$ dies.

What this means is that for plant \$k\$ to die, I have to wait for all the plants between plant \$i\$ and plant \$k\$ to die, at which point \$i\$ will be to the immediate left of \$k\$, and then I have to wait one more day.

So far, we still have an \$O(N^2)\$ algorithm. If we think about the input \$ 1, 2, 2, 2, 2, \ldots, 2\$, for every plant we have to iterate all the way back to the start to find the plant with less pesticide in it.

Let's think about the following input:

$$ 2, 5, 1, 10, 3, 11 $$

The first plant will never die, and the second plant will die on day one.

For the third plant, we look at the previous two values and see that they both have more pesticide than the third, so the third plant will never die. The key here is that we can now forget that the first and second plants ever existed.

Why? Because any plant waiting for the first or second plant to die will have to wait for the third plant to die first.

The fourth plant dies on day one.

For the fifth plant, we look at the previous two values, 1 and 10. The fifth plant will die a day after the 10, and again we can forget the 10 ever existed, because any plant waiting for the 10 to die will have to wait for the 3 to die first.

Spoilers

How would this look in code? Suppose we have a stack containing pairs of the amount of pesticide in the plant and the day on which the plant dies.

If we are in the interesting case, where the plant doesn't die on day one, then we keep popping elements off the stack while they have at least as much pesticide as the current plant. While we're popping elements, we keep track of the maximum number of days it takes for these plants to die.

If we have popped all elements off the stack, the current plant will never die. Otherwise, the plant will die on the maximum number of days that we've seen, plus one.

One we have calculated the number of days it takes for the plant to die, we push it onto the stack.

Since exactly \$N\$ elements are pushed onto the stack, we cannot have more than \$N\$ pops. So we can see that this algorithm is \$O(N)\$.


Append blank value(s) to missing fields in a CSV line

As I understand it, you'd like to make buildShortErrorLine more elegant. In that case, why not try something like this algorithm:

Initialise a String array of length equal to the number of required entries per line to all empty Strings.
Copy in the String array of the entries of the line just read into the array of empty Strings defined above, starting at the first index of each array, until the array of entries has been exhausted.
Et voila! Entry padding for (somewhat) free!

An implementation may look like:
(if Java supported real immutable lists we could have tried to cache the empty String array for hopefully better performance, but we're stuck with what we have...)
private String[] emptyStrings(int length) {
     String[] emptyStrings = new String[length];
     Arrays.fill(emptyStrings, "");
     return emptyStrings;
}

private String buildErrorLine(String[] line) {
     String[] padded = line;
     if(line.length < 5) {
          padded = emptyStrings(5);
          System.arraycopy(line, 0, padded, 0, line.length);
     }
     System.out.println(Arrays.toString(padded));
     return appendCommas(padded);
}

Note that the buildShortErrorLine method is now obsolete.
Also, the number 5 is used twice in the above code, so it appears to be a magic number. As it doesn't change according to your use-case, you could refactor it into a constant, say private static final int STANDARD_LINE_LENGTH = 5, as @mdfst13 said. However, in my opinion, this should actually be a parameter of buildErrorLine, as follows:
private String buildErrorLine(String[] line, int standardLineLength) {
     String[] padded = line;
     if(line.length < standardLineLength) {
          padded = emptyStrings(standardLineLength);
          System.arraycopy(line, 0, padded, 0, line.length);
     }
     System.out.println(Arrays.toString(padded));
     return appendCommas(padded);
}

Then call this with:
buildErrorLine(<data>, STANDARD_LINE_LENGTH);

Thus getting the best of both worlds. The parametrization is assuming the declaration and call sites of this method are in 2 different classes, but otherwise it's perfectly fine to lose the parameter and inline the constant - however, the code remains more flexible this way.
You'd notice that here we're doing reference copying (shallow copying), but that isn't a problem as Strings are immutable and interned (there is only one copy of 2 identical String constants).
Other notes:
1. Naming:
buildShortErrorLine is a pretty weird name for what this function does; why not just call it something like padRowEntries or something?
Otherwise, the rest of the naming in the code looks OK.
2. Unnecessary code:
The check you've got in buildErrorLine approach becomes irrelevant using my algorithm.
3. Notes about appendCommas:
Firstly, appendCommas could be (somewhat) better named as interleaveCommas? I'm not too sure, both are applicable given the context.
If you can use Java 8, you can significantly reduce the complicated StringBuilder logic with a simple stream map and collect. It would look like this:
private String appendCommas(String[] line) {
     return Arrays.stream(line)
           .map(entry -> "\"" + entry + "\"")
           .collect(Collectors.joining(","));
}

Note that @mdfst13's approach below also relies on Java 8, and although his is more efficient, I feel that my approach conveys the idea behind the process a bit better. By all means, please use his version in production code, mine might be too slow for that. Just reproducing his approach below:
private String appendCommas(String[] line) {
     return "\"" + String.join("\",\"", line) + "\"";
}


DRY the throwing of ArgumentNullException("ParameterName")?

Google Guava's Precondition class contains good patterns for this problem. For example, the checkNotNull method is the following:

T checkNotNull(T reference, String errorMessageTemplate, Object... errorMessageArgs)

Usage:

checkNotNull(parameter, "parameter cannot be null");

Note its return value. If the value is not null it returns the referencce, so you can use it in the following way:

public MyClass(MyObject dependency) {
    this.dependency = checkNotNull(dependency, "dependency cannot be null");
}

It also supports error message templates with %s.

Although it's a Java library, you can implement the same methods in C# too, they are really simple.

See also: Preconditions Explained


Beginner's Knight's tour in Python (BFS)

For a beginner this is pretty good, there are some serious styling issues though which I would like to point out.

Review

imports

.Only import what you need, ==> from random import randint
Doing import random as r does not help readability IMO

Constants should be UPPERCASE, rename UP and DOWN accordingly

See PEP8#constants

def valid(*num):

This could be made simpler with the all() keyword

return all(n in range(P.DOWN, P.UP) for n in num)

Here all() checks if all points are in range and will return True if it is, else it will return False

t = [P(self.x + i, self.y + j, self) ...

This list comprehension is way too long, and you actually repeat yourself

A few fixes are needed

It is good to split up your lines for better readability like this:

[P(...)
 for i in a
 for j in b
 ...]

You loop over [-1, 1], [2, -2] with 2 contatinated list comprehensions you could do this in one turn. By having a constant of all possible directions for instance, this will make it look a little better.

I end up with this:

DIRECTIONS = ((1, 2), (1, -2), (-1, 2), (-1, 2), (2, -1), (2, 1), (-2, 1), (-2, -1))
paths = [P(self.rank + delta_rank,
           self.file + delta_file,
           self)
         for delta_rank, delta_file in P.DIRECTIONS
         if valid(self.rank + delta_rank, self.file + delta_file)]

Always guard your code!
There is the issue of naming.
You have many unmeaningfull names

class P() What is P? Point?

a, b This doesn't say much

e, s I would rename to end, start

etc (t, ls, ...)

In chess x is called a RANK and y is called a FILE

When writing good code, it helpfull to give your variables and instances good names, where it is clear on first sight what they do. So when you revisit your code, or let other people use your code they know what is what.

Revised code

from random import randint
from itertools import chain
import numpy as np

class P:
    UP = 8
    DOWN = 0
    DIRECTIONS = ((1, 2), (1, -2), (-1, 2), (-1, 2), (2, -1), (2, 1), (-2, 1), (-2, -1))

    def __init__(self, rank=0, file=0, parent=None, random=False):
        self.rank = rank if not random else randint(P.DOWN, P.UP-1)
        self.file = file if not random else randint(P.DOWN, P.UP-1)
        self.parent = parent

    def __str__(self):
        return '({},{})'.format(self.rank, self.file)

    def __repr__(self):
        return '({},{} [{},{}])'.format(self.rank,
                                        self.file,
                                        self.parent.rank if self.parent else '-',
                                        self.parent.file if self.parent else '-')

    def __eq__(self, other):
        return self.rank == other.rank and self.file == other.file

    def __gt__(self, other):
        return self.rank + self.file > other.rank + other.file

    def __lt__(self, other):
        return self.rank + self.file < other.rank + other.file

    def __hash__(self):
        return hash((self.rank, self.file))

    def valid_moves(self):
        def valid(*num):
            return all(n in range(P.DOWN, P.UP) for n in num)

        paths = [P(self.rank + delta_rank,
                   self.file + delta_file,
                   self)
                 for delta_rank, delta_file in P.DIRECTIONS
                 if valid(self.rank + delta_rank, self.file + delta_file)]

        return np.unique(paths)

def find_path(start, end):
    valid = start.valid_moves()
    while True:
        if end in valid or end == start:
            curr = valid.pop(valid.index(end))
            path = [curr]

            while curr != start:
                curr = curr.parent
                path += ['->']
                path += [curr]

            return path

        tmp = [p.valid_moves() for p in valid]
        valid = list(chain(*tmp))

if __name__ == '__main__':
    start, end = P(), P(random=True)
    print('Finding shortest path from {} to {}'.format(start, end))
    print('Path ', find_path(start, end))


TopCoder problem "Substitute" - SRM 160 (Division II Level One)

Analysis

You've picked an interesting problem about which to ask about Big-O complexity.  The problem is, you're being sloppy about what you call "n".  This function has two inputs: a key of length 10 and a code of variable length.  Let's say that m is the length of key (which is 10) and n is the length of code.

The outer i loop executes n times.  For each of those, outer loops, the inner j loop executes m times.  For each inner loop, key.indexOf() — an O(m) operation — is called; then we might do s = s + x — an O(n) operation.  Finally, Integer.parseInt(s) is an operation that I would expect to be O(n).

The complexity, therefore, is O(n ∙ m (m + n) + n).  If we consider m to be constant, that simplifies to O(n2).

However, the "silliest" part of the code is s = s + x.  That O(n) operation could be O(1) if you had used a StringBuilder instead of repeated string concatenation.  With a StringBuilder, your function would become O(n).

Perspective

It's important to keep a sense of perspective, though.  Big-O complexity is useful for getting a feel for how well an algorithm scales to handle large input.  For example, it can help you estimate whether an algorithm that analyzes a million DNA bases will finish in seconds or hours.

On the other hand, Big-O analysis is nearly useless for predicting the performance of "small" problems like this one.  The challenge states that n is at most 9 — and in any case, a result larger than 9 digits would overflow an int.  It is very possible that an algorithm that Big-O analysis predicts will scale well could actually perform worse than a simpler algorithm that in theory should scale poorly.  For example, the time it takes to initialize an "efficient" data structure could exceed the time it takes to do a naïve String.indexOf() search.

Suggested solution

Building a string and then parsing it as an integer is inefficient.  Why not just compute the integer as you go?

public int getValue(String key, String code) {
    int value = 0;
    for (int i = 0; i < code.length(); i++) {
        int pos = 1 + key.indexOf(code.charAt(i));
        if (pos == 10) {
            value *= 10;
        } else if (pos > 0) {
            value = 10 * value + pos;
        }
    }
    return value;
}


I see you have tested the case when there is no path to the destination, but I'm not convinced that returning seemingly valid data in that case is a good idea. You can easily catch such case by adding an else clause to the main while loop. You will land there if the loop ends without break.
Disregarding the no path case you can simplify the second while loop to

path = []
while f in prev:
    path.append(f)
    f = prev[f]

The visited set is redundant because it is the same as the set of keys of prev, and v not in prev has similar performance to v not in visited.


Download a file given an url to a restricted area and a cookie container

You mentioned that the download is slower than you'd expect, I'll focus on just that for a quick review.

Look at your code here:

var percentage = (short)(bytesRead * 100 / response.ContentLength);
if (oldPercentage < percentage)
{
    await reportStatus(percentage);
    oldPercentage = (short)(oldPercentage + 5);
}

Can you see why that might be slowing down your download?

await reportStatus(percentage);

You're waiting for the task reporting the status to finish before reading the rest of the stream! What if reportStatus were logging the progress to a database or doing something else really time consuming?

I think you should just execute the callback and not care when/how it finishes:

reportStatus(percentage); // Don't wait

Oh and oldPercentage is really confusing when you scan the code... I'd rename it to something like reportingThreshold.

if (percentage > reportingThreshold)
{
     reportStatus(percentage);
     reportingThreshold = (short)(reportingThreshold+ 5);
}


Randomly generate a Hex Colour code and its contrasting colour using Python

Review

Globals should be ALL_CAPS

start

=> START
Accumulation: Loop variables that are not explicitly used within the loop block should be replaced by _ , as is standard Python style.

for i in range(6):

You don't use the i later on, so the convention is to use _ for a dummy variable.

=> for _ in range(6)
The name of the variable value_dict implies it's a dict (Python's built-in dictionary type) but it's implemented as a list.

value_dict = [['A','10'],['B','11'],['C','12'],['D','13'],['E','14'],['F','15']]
...
for thing in value_dict:
    if x == thing[1]:
        x = thing[0]

You could change this to use an actual dict like this:

val_dict = {'10' : 'A', '11' : 'B', '12' : 'C', '13' : 'D', '14' : 'E', '15' : 'F'}
...

if x in val_dict:
    x = val_dict[x]

Or better yet why not immediately convert to an hexadecimal using hex?
Check your naming. Don't be overly generic.

values #
thing  # Each of these could literally be anything
x      #

colour = colour + x
can be rewritten as colour += x
Use spaces around the comma: a,b => a, b
Use a if __name__ == '__main__' guard

Essentially your startcolour() can be rewritten as a one-liner

from random import randint
_HEX = list('0123456789ABCDEF')
...
def startcolour():
    return '#' + ''.join(_HEX[randint(0, len(_HEX)-1)] for _ in range(6))


The code demonstrates some nice effort towards writing good code, so a professional mindset. However, it does have issues, which I'll explain below.

1. Testing input arguments

I believe that you could have done without that, as the point of the exercise is not to check the parameters, but rather to calculate properly the binomial coefficient.

Anyway, your test condition isNaN(parseFloat(n)) && isFinite(n) && isNaN(parseFloat(n)) && isFinite(n) has issues. Firstly, it only tests the value n, and not the value k (this is a typo, but your following tests have not found it, meaning your tests are incomplete). Secondly, you do not check for positive integers. Thirdly, you convert the variables into numbers (fine), but still use the original values thereafter. Finally, if the test fails, then you should probably do something more than return undefined (and document that behavior as well).

2. The factorial function

Your inputs have been checked already, so I think that you should keep this function as simple as possible, e.g.

function factorial(n) {
  if (n <= 1) {
    return 1;
  }
  return n * factorial (n - 1);
}

... or using the ternary operator (less readable in a recursive algorithm, but some people prefer that form), e.g.

function factorial(n) {
   return n <= 1 ? 1 : n * factorial (n - 1);
}

3. The algorithm

This is where, I believe, lies the real point of the exercise. The provided formula C(n,k) = n! / [ k! (n - k)! ], if implemented "as is", has duplications. After all, n! contains both k! and (n - k)!, so you'd be calculating k! or (n - k)! twice, which can be quite expensive. You should therefore remove one of them from n! (the most expensive one), depending on k being superior or inferior to n / 2.

4. The tests

The test named "example" should be removed. Either C is a function, and the following tests are enough, or it is not, and their subsequent execution will lead to a runtime error anyway.

The message property is intended as the name of the test, so there is no need to check the value of the pass variable - and so, there's no need for that variable either.

Finally, I believe that the statement tests[test].apply(undefined) was provided to you by the company. This is... not pretty, and quite unnecessary.


Even though Number doesn't provide any methods to check for divisibility directly, it does provide a method to make the Number into a double, and as we all know, doubles do support the % operator.

Other slight modifications:

Your method can be static
You don't need to specify the (T dividend) ->, simply using dividend -> is enough.

Final:

public static <T extends Number> Predicate<T> isDivisibleBy(T divisor) {
    return dividend -> dividend.doubleValue() % divisor.doubleValue() == 0;
}

I have tested this code for many cases using a for-loop, and it works mostly fine.

I had one problem with using Long though as the Long value = -195798407404780179L was converted into -1.95798407404780192E17, which loses some accuracy. So it seems like you need a special case for Long:

public static Predicate<Long> isDivisibleBy(Long divisor) {
    return dividend -> dividend % divisor == 0;
}

However, be aware that there are some primitive variants available for Predicate:

IntPredicate
LongPredicate
DoublePredicate


Matching entities in SQL Server to replace iterative Python script

Without knowing exactly what your old code was it is hard to pinpoint where the slowdown came from. That being said, here are some things you're doing in your query that are going to make it slower:

Using a UDF prohibits parallel plans. You could throw 1000 CPUs at this problem and it would still only use one of them. If computing this is too complex to do inline, then use an inline table-valued function instead, which enables parallelism.
JOINing on functions (UDF or otherwise) performs really poorly. SQL Server has no cardinality estimate for LEFT(input.name, 3), but it does for input.name. If at all possible find another way to do this join (a suggestion is below). Similarly, filtering in a WHERE clause has the same restrictions.

To address this, I would likely change your join to just be on RefCode - this gets you a good hash match (probably), but will increase your granularity. Then, make your edit_distance function table valued, like so

SELECT <<stuff>>
  FROM dbo.Sample input
    INNER JOIN dbo.Company target_db
      ON input.ReFcode = target_db.Refcode
    CROSS APPLY dbo.edit_distance( input.name, target_db.CompanyName ) levenshtein

Then, inside of dbo.edit_distance I would include the LEFT, SOUNDEX and LEN calculations (LEN calc would also be better if you did LEN( input.name ) - LEN( targetdb.CompanyName ) BETWEEN -7 AND 7).

If levenshtein returns some score, then you could do something like this to only get the best score per input name. Alternatively if you want them all, then have it return everything and do whatever calculations the consuming app needs.

SELECT name,
       CompanyName,
       Country,
       RefCode,
       levenshtein_score
  FROM ( SELECT input.name,
                target_db.CompanyName,
                input.Country,
                input.ReFcode,
                levenshtein.levenshtein_score,
                ROW_NUMBER() OVER ( PARTITION BY input.name
                                    ORDER BY levenshtein.levenshtein_score ASC ) RowNumber
           FROM dbo.Sample input
             INNER JOIN dbo.Company target_db
               ON input.ReFcode = target_db.Refcode
             CROSS APPLY dbo.edit_distance( input.name, target_db.CompanyName ) levenshtein ) ComputedLevenshteinScores
  WHERE ComputedLevenshteinScores.RowNumber = 1
  ORDER BY levenshtein ASC;


This looks pretty good! I'm still fairly new to Rust myself, so I'm not sure how familiar I am with the idioms beyond those outlined in the book. That said, there's a few improvements I can suggest.

Unsigned integer for day

Since day is never negative, you can use an unsigned integer instead of an i32 here:

fn gen_lyrics(day: usize) -> String

If you use usize specifically, you also avoid the cast to usize here:

start.push_str(&LYRICS[11 - (i as usize)]);

That would then just be:

start.push_str(&LYRICS[11 - i]);

Ordinal suffix match expression

You can avoid some .to_string() calls and repetition of numbers by making the match expression return just the suffix of the ordinal. You can then append that suffix to the number itself in the format!() call:

let ordinal_suffix = match day {
    1 => "st",
    2 => "nd",
    3 => "rd",
    _ => "th",
};

let mut start = format!(
    "On the {}{} day of Christmas, my true love gave to me:\n",
    day,
    ordinal_suffix
);

Inclusive range

You can use ..= instead of .. to create an inclusive range:

fn main() {
    for i in 1..=12 {
        println!("{}\n", gen_lyrics(i))
    }
}

Iterators and the skip method

You can iterate directly over the LYRICS array, skipping over the number of lines you don't want to include:

for line in (&LYRICS).iter().skip(12 - day) {
    start.push_str(line);
    start.push_str("\n");
}

The problem with this is that there's no longer an i variable to check whether an iteration is the last line or not, so it can't conditionally insert a newline. The code above will always insert a newline.

But we can cheat a little

If you remove the newline from the end of the start variable:

"On the {} day of Christmas, my true love gave to me:"

You can push the newline first, that way you no longer need a conditional in the loop:

for line in (&LYRICS).iter().skip(12 - day) {
    start.push_str("\n");
    start.push_str(line);
}

Bringing it all together

This is the code with all the changes applied:

const LYRICS: [&str; 12] = [
    "Twelve drummers drumming",
    "Eleven pipers piping",
    "Ten lords a-leaping",
    "Nine ladies dancing",
    "Eight maids a-milking",
    "Seven swans a-swimming",
    "Six geese a-laying",
    "Five golden rings",
    "Four calling birds",
    "Three french hens",
    "Two turtle doves, and",
    "A partridge in a pear tree",
];

fn gen_lyrics(day: usize) -> String {
    let ordinal_suffix = match day {
        1 => "st",
        2 => "nd",
        3 => "rd",
        _ => "th",
    };

    let mut start = format!(
        "On the {}{} day of Christmas, my true love gave to me:",
        day,
        ordinal_suffix
    );

    for line in (&LYRICS).iter().skip(12 - day) {
        start.push_str("\n");
        start.push_str(line);
    }

    start
}

fn main() {
    for i in 1..=12 {
        println!("{}\n", gen_lyrics(i))
    }
}


ExitCode class and derived Status class able to return a value

Overall I would say this is good code. Still, there are a few things that you should (or, at least, could) improve:

TResult& GetResult() const is a bug. This should read TResult const& GetResult() const (and if you had done more testing, your compiler likely should have told you).
You are missing an include (#include <utility>) for std::move.
Depending on how you intend to use these classes, you should add a virtual destructor to ExitCode. The reason is that, if you do fancy polymorphism and try to delete an instance of Status through a pointer to ExitCode, you get undefined behavior. If you don't care about the possible polymorphism, you should be fine as-is.
I share your worry about implicit conversions. I would consider making your constructors explicit.
Keep your formatting consistent. Although your formatting is almost always the same, there is one place where you diverge from it, namely const std::string & msg = "" in the first two constructors of Status. Why do you have a space between std::string and &? (I suppose it's just some oversight of yours).
Why is the default value to two of the constructors of Status for the parameter state TState::OK, but the last constructor has TState::FAILED instead? This is very likely to cause confusion.


find in which sublist of a list are any value of a list in python

I'm assuming Elements is always a list of continuous indices from zero to the length of Nodes minus one and thus strictly not needed.
As a general guideline, explicit loops tend to be slow and also hard to read (and non-Pythonic).
To solve your problem efficiently, use data structures (namely sets):
import numpy as np

# Suppose you start with these lists
u = [1,2,10,40,400,1000]
n = [[1,20,25],[30,400,35],[500,501,502]]

# Convert them into sets
u = set(u)
n = [set(x) for x in n]

#  An individual bit is true if the corresponding list is "interesting"
idx = [bool(a.intersection(u)) for a in n]

# Perhaps convert to integer indices if you wish
np.where(idx)


The number one improvement you can make is to include Option Explicit as the first line of your script and explicitly declare your variables using Dim. This will save you a lot of heartache in the future (e.g., if you make a typo in a variable name, it becomes a runtime error, instead of just silently creating a new variable).


Is this "smart" way of populating the admin page ok code-wise?

The usual "django" way of doing this  - is to use get_app_config() function to get the AppConfig instance, then call .get_models() method:

from django.apps import apps

app = apps.get_app_config('auth')

for model in app.get_models():
    admin.site.register(model)


Design for class which accepts large array in constructor

Don't pass arrays as pointers ...

... for multiple reasons. Your current design

always copies the arrays x, y deeply
can be misused by passing nullptr and trusts the user that length is chosen correctly.

Instead of

interpolator(const Real* const x, const Real* const y, size_t length) {  /* ... */ }

use

interpolator(std::vector<Real> x, std::vector<Real> y)
: m_x{std::move(x)}
, m_y{std::move(y)}
{ if (m_x.size() != m_y.size()) throw std::logic_error{"NO!"}; }

or if the memory layout doesn't effect the performance too much

interpolate(std::vector<std::array<Real, 2>> xy): m_xy{std::move(xy)} {}

If you want to initialise your data from any range use templates and constrain its type to guard for errors at compile time.

Prefer regular functions for computations

This means, that an implemented function is also a function in the mathematical sense. Same input data produces same output data. I found that this almost always leads to evaluations which do not change an inner state. Thus it smells to me that

Real interpolate_at(Real);

is not

Real interpolate_at(Real) const;


In JPA you could use JpaSpecificationExecutor<T> in repository, with that you could utilize it's method.

TransactionRepository

public interface TransactionRepository extends JpaRepository<Transaction, Long>,
                                                JpaSpecificationExecutor<Transaction> {

}

If you look at the source of JpaSpecificationExecutor it has,

Page< T > findAll(@Nullable Specification<T> spec, Pageable pageable);

With that you just pass the specification and Pageable to return what you expected.

Specification

@AllArgsConstructor
class TransactionSpecification implements Specification<Transaction> {

       private TransactionFilter transactionFilter;

       @Override
        public Predicate toPredicate(Root<DataImport> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
            // You could add multiple Predicates based on the transactionFilter
            return criteriaBuilder.equal(root.get("table_name"), "value");
        }
}

Controller

    @Autowired
    private TransactionRepository transactionRepository;

    @GetMapping
    public Page<TransactionDTO> find(TransactionFilterDTO filter, Pageable page) {
        TransactionFilter transactionFilter = mapper.toFilter(filter);
        return transactionRepository.findAll(new TransactionSpecification(transactionFilter), page);
    }

I am pretty late answering but you could give it a try