Finding the Minimum and Maximum Value in an Image

Using signed integer loop counters is leading to some extra work outside the loop, but it doesn't seem to be hurting the inner-most loop in the compiler's asm output.  Still, you might as well use size_t for memory sizes; that's what it's for and usually compiles efficiently.  OTOH, limiting your args to signed makes it easier to express the condition that the loop should run zero times (because size - unroll width can be negative, instead of having to code it like asm, with an explicit compare and then a do{}while() loop.)

numColsPad should be called rowStride or stride.  numColsPad is ambiguous whether it means number of columns including padding, or whether it's the width of the padding!  Stride is a well-established term for the distance in memory between rows.  stride - cols doesn't even have to be small: separating the storage layout from the width lets you pass a sub-image to a function without copying the data to another buffer.

numColsSse is an awkward variable name.  SSE should be all-caps.  Or better, just call it something else, like colVecs.  I'm not a fan of your other variable names, or camelCase in general.  HorizontalMaxSse is also a silly name.  Max of what?  Call it HorizontalMax_ps to indicate that it's packed-single-precision floats.

You should use const float* for the read-only input array.  You could also return min by value and only use the output-pointer for max.  It would be better C++ style to declare your variables as you use them, instead of C89-style at the top of the function.

The two biggest performance things I see are:

Handling the tail of every row with a 2nd loop over all the rows is horrible (for(jj = numColsSse + 1; ...).  That data will be hot in L1D cache from HW prefetch while doing a row, so you should grab it then instead of waiting until later when it's probably evicted again.  Striding over the rows to load a couple columns is a bad access pattern which will hurt a lot for tall and narrow image.

You also don't need to do it scalar.  You can accumulate tailMin and tailMax vectors, and after the fact take only the elements that are actually part of the image.  (e.g. loop over 1 to 4 elements of the vector, depending on numCols%4.  Not 0-3, because that would mean we'd want to do it conditionally to avoid wasting work.)

If you need to avoid loading past the end of the last row, then peel the last row out of the main loop and do it specially.

It makes the cleanup trivial if we use an unaligned potentially-overlapping load that gets the last 4 elements of a row (then we don't have to ignore any elements of separate tail accumulators).  Overlap is fine because x=min(x,y) is idempotent.  Unlike a sum reduction, looking at the same element multiple times doesn't change the result.  If we're clever, we can use this to simplify the unrolling.

OTOH, branching based on numCols & 7 would probably be better to avoid doing a fully-overlapped vector, since we bottleneck on min/maxps throughput, not on the front-end.  Still, this is pretty good and makes the source simple.  Optimize further however you like.

Unroll the inner vector loop with multiple accumulators.  maxps has 3c or 4c latency, 1c or 0.5c throughput on recent Intel CPUs (http://agner.org/optimize/, and see also this SO Q&A about using multiple accumulators for FMA.)

On Skylake, you need 8 accumulators to keep 8 min/maxps instructions in flight at once to max out execution-unit throughput (it runs FP add/cmp/min/max on the FMA units on p0/p1, same as mul and fma).  You only have 2, one each for min and max.  On Broadwell (3c latency, 1c throughput, runs on port1 only) this will in theory get you 2/3rds of theoretical max throughput.

This is what MSVC CL19 does for the inner loop:

$LL7@ExtractMin:
    movups   xmm0, XMMWORD PTR [rdx]
    lea      rdx, QWORD PTR [rdx+16]   ; ADD would be better, but this probably doesn't create resource conflicts
    minps    xmm1, xmm0
    maxps    xmm2, xmm0
    sub      r8, 1                  ; will macro-fuse with JNE on Intel SnB-family
    jne      SHORT $LL7@ExtractMin

That's 5 fused-domain uops, so it can issue at about 1 iteration per 1.25 clocks.  So actually even on Haswell/Broadwell, min/maxps latency is a bigger bottleneck than CPU front-end throughput (4 uops per clock max, or slightly less in loops that aren't a multiple of 4 uops in some cases.)  Still, unrolling will let out-of-order execution see the loads earlier.

OTOH, unrolling introduces more code to get the iteration count right (especially if you need your code to work for very narrow images where you can't assume the width is at least one full vector).

This can be outside the outer loop if the whole nested loop is duplicated.  (Either in the source or in the compiler output if it decides to factor out a check).  Or we can do something simple and branchless like always doing a first vector and then starting j from 0 or 4 depending on whether numCols is a multiple of SSE_STRIDE*2 or not (ignoring the low 2 bits).  Overlap is fine because min and max are idempotent. (I haven't thought through the possibilities with NaN; _mm_min_ps() and max are not commutative without -ffast-math or equivalent for other compilers.  You are using them with the operand order that allows the compiler to avoid extra movaps instructions.)

Here's an example of most of those ideas.  I'm only unrolling by 2, but you need to unroll by at least 4 to max out performance on Skylake (for cases where you don't bottleneck on memory).

source + asm on Godbolt.  It looks good for MSVC and gcc and clang.  Clang does further unrolling of the inner loop, but without using more accumulators so it's useless for speeding up Skylake.

Returning a 2-member struct by value ends up taking slightly more code than just storing twice, so it's probably not a win.  I'd recommend picking one method (or just returning min by value as a float and max by pointer), instead of storing both and packing both into a struct.  The caller will have to unpack the struct into separate registers in most cases, so it's not that great.

#include <immintrin.h>

struct minmax { float min, max; };

// pre-condition: numCols >= 8
// numRows >= 1
minmax ExtractMinMax(float* vMinMax, const float* mI, int numRows, int numCols, int rowStride)
{
    static const int VEC_WIDTH = 4;
    //if (numCols < 2*VEC_WIDTH) {
    //    return alternate_version(vMinMax, mI, numRows, numCols, rowStride);
    //}

    // if you want to support numCols < 8, a simple way is _mm_load1_ps(mI)
    // but you'd also have to change the non-multiple-of-8 handling in the loop
    __m128 min0 = _mm_loadu_ps(mI);
    __m128 min1 = _mm_loadu_ps(mI + VEC_WIDTH);
    __m128 max0 = min0, max1 = min1;
    // TODO: skip the first 2 vectors of the first row

    int i=0;
    do {  // let the compile know this loop runs at least once
        // manually hoisting the row pointer mostly helps human readability; compilers usually already do this
        const float *row = &mI[i * rowStride];

        for (int j=0 ; j < numCols - VEC_WIDTH*2; j += VEC_WIDTH*2) {
            // for large unroll counts, a function or macro is useful.  (not recommended, don't go nuts)
            // for small unrolls, manual repetition is usually the most readable.
            __m128 pxI0 = _mm_loadu_ps(row+j);
            min0  = _mm_min_ps(min0, pxI0);
            max0  = _mm_max_ps(max0, pxI0);
            __m128 pxI1 = _mm_loadu_ps(row+j + VEC_WIDTH);
            min1  = _mm_min_ps(min1, pxI1);
            max1  = _mm_max_ps(max1, pxI1);
        }
        // loop stops with 1 to 2*VEC_WIDTH elements left to do, depending on numCols & (2*VEC_WIDTH - 1)

        // last 2 vectors ending at the end of the row, could overlap with above
        // but won't for multiple-of-8 numCols
        __m128 tail = _mm_loadu_ps(row + numCols - VEC_WIDTH*2);
        min0  = _mm_min_ps(min0, tail);
        max0  = _mm_max_ps(max0, tail);

        tail = _mm_loadu_ps(row + numCols - VEC_WIDTH);
        min1  = _mm_min_ps(min1, tail);
        max1  = _mm_max_ps(max1, tail);
        // This isn't really optimal; 2 unaligned loads is more chances to CL-split or 4k-split
        // assuming the start of each row is aligned
        // but it does avoid any branching on the low bits of numCols.
    } while(++i < numRows);

    // reduce the multiple accumulators to one
    min0 = _mm_min_ps(min0, min1);
    max0 = _mm_max_ps(max0, max1);

    // horizontal min/max.
    float min = HorizontalMin_ps(min0);
    float max = HorizontalMax_ps(max0);

    vMinMax[0] = min;
    vMinMax[1] = max;
    return { min, max };
}

Using AVX if available could help, too, but probably not if you're totally memory bottlenecked from looping over giant images doing not much work for the amount of memory traffic.  Still, AVX can help saturate memory bandwidth better because the same number of in-flight loads covers twice as much data.  (But requests from L1 to L2, and L2 to L3, are tracked in whole cache lines.)

Try to combine the min/max calculation into whatever wrote the image in the first place, to increase computational intensity.  Doing a separate pass for min/max isn't great.  (Although it's twice as good as doing separate passes over your data for min and for max.)

Using multiple threads can help even if you're memory-bound, especially on Intel CPUs with more than quad cores.  IDK how bad single-threaded memory performance is on your 6-core Broadwell i7-6800k, but on many-core Xeons the extra latency to L3 and DRAM hurts single-threaded bandwidth a lot.  (bandwidth = max concurrency / latency).  See the Latency-bound platforms section of this answer for more details.

My quad-core Skylake (i7-6700k) can use most of the total memory bandwidth with only one thread, but that's with a quite high core / uncore clock speed.

Also, with enough cores for a medium-size image, it might start fitting in L2 cache (since each core only looks at part of it).  But 2k*2k * 4B is 15.25MiB, which is larger than the 15MB L3 cache on your CPU.

If you're going to use this with unaligned input pointers very often (e.g. a sub-image), it might make sense to do the unaligned head of each row separately, and a potentially-overlapping aligned loop over the main part of each row.  cache-line splits won't be a problem on recent Intel (you're only going to do 1 load per clock max), but 4k-splits will still cause bubbles on pre-Skylake.  Like 34 cycle load-use latency on Haswell for a 4k-split instead of only 11 for a cache-line split.

NaN behaviour: this will ignore NaN in the input (unless it's in the initial values that we start with.

max and _mm_min_ps() are not commutative without -ffast-math (or equivalent for other compilers).  You are using them with the operand order that allows the compiler to avoid extra movaps instructions, so that's a good thing.


You have to allocate sizeof(int) bytes for socket file descriptor, not 1
fflush(stdin) has undefined behavior
its not good idea to access a file descriptor in two threads simultaneously, be careful
joins are never happens, because none of two threads have exit conditions, so the socket will never close gracefully


Clearing and loading values on HTML form fields

Good question,

you can clear all (visible) input elements like this:

$("input:text").is(":visible").val('');

In general, google queries are a gold mine here. Just google 'jQuery clear all text fields' and you will find a link to StackOverflow with several approaches.

You are correct that there are easier ways to get your response in the correct fields, something like this might work for you:

}).done(function(response) {
    Object.keys(response).forEach( function( field ){
      $('#'+field).val(response[field]);
    });
    var updateInfo = "";
    ...
    $('#updateInfo').html(updateInfo);
    $('#modal').modal('show');
});

As for #3 you should look into libraries to that work for you. A number of folks have done all the heavy lifting for that already.


Click handler for setting the active color and shape button in a drawing program

Why would you have one actionPerformed() method for multiple UI elements instead of creating each button with its individual Action instance? Like:

Action clearAction = new AbstractAction("Clear") {
        public void actionPerformed(ActionEvent e) {
            btnLine.setBorder(UIManager.getBorder(defaultbtnLable));
            btnRectangle.setBorder(UIManager.getBorder(defaultbtnLable));
            btnCircle.setBorder(UIManager.getBorder(defaultbtnLable));
            panelContent.repaint();
        }
}
btnClear = new JButton(clearAction);

[Disclaimer: may contain typos, didn't check it in an IDE]

Then the Action is a first-class object, can be bound to multiple UI elements (e.g. a button and a main menu item) and contains both the name (plus an icon if you like) and the implementation.

And if the Actions have common elements, maybe it's worth having them inherit from a common base Action class.


It is considered bad practice to use goto-statements in modern programming because it quickly gets hard to follow the structure, so avoid that. Instead you could use a while-loop in a kind of this manner:

while (list.Count < 75)
{
  var number = random.Next(75);
  if (list.Contains(number))
    continue;
    ...
}

var item = random.Next(75);

This statement sets item to a number in the interval of \$[0, 75[\$, but you were supposed to handle the interval \$[1, 75]\$

instead of if (item >= 61) it is more readable to write if (item > 60)

It seems that GetNumber() is missing a stop-condition. It will run forever between goto Start and Start: when the list is full. (That may be your "time out"-problem).

Instead of the long list of if-statements, you could use the simple relation between the prefix's position in the word "BINGO" and the random number to extract it as:

string bingo = "BINGO"; // Make it a class field.
int index = ...
char prefix = bingo[index]

(it has something to do with 15).

The pattern of filling a list with found numbers tends to be slower and slower in response time as the size of the list grows because the next random number is more and more likely to be in the list. Potentially a valid number may never be found...

A better approach could be to create the list of the 75 numbers in the constructor in advance and then remove them one by one from the list when found by random.Next():

...
var number = list[random.Next(0, list.Count)];
list.Remove(number);
...

This will decrease in response time and you avoid the looping.

A solution could be:

  public class BingoCaller
  {
    private Random random;
    List<int> list;
    string bingo = "BINGO";

    public BingoCaller(Random random)
    {
      this.random = random;
      list = Enumerable.Range(1, 75).ToList();
    }

    public string GetNumber()
    {
      if (list.Count == 0)
        return "";

      var number = list[random.Next(0, list.Count)];
      list.Remove(number);
      char prefix = bingo[(number - 1) / 15];
      return $"{prefix}{number}";
    }
  }


You are on the right track, and I think you would benefit by having your class implement the Java List<T> interface like so:

public class LinkedList<T> implements List<T> {

You would then have to change your methods so that their names and signatures conform to the interface. You can read about the details here for Java 7 or here for Java 8. If you do this then you could pass instances of your class into already implemented functions like Collections.sort.


Finding the maximum value in a binary tree

Trees are often most useful when they're sorted. If the tree is sorted, you can just descend into the right side of the tree.

Since we're assuming an unsorted tree, we have to search the whole thing. Let's build this up by cases. First assume that the current node has the largest value:

int maxValue(Node *node)
{
    if (node == nullptr)
        throw "BT is empty";

    max = node->data;
    return max;
}

Nice, but not likely. We can do better. What if the largest value is in the left side of the tree?

int maxValue(Node *node)
{
    if (node == nullptr)
        throw "BT is empty";

    max = node->data;

    if(node->left != nullptr) {
        int leftMax = maxValue(node->left);
        if(max < leftMax)
            max = leftMax;
    }

    return max;
}

Great! Now we have a function that will check its left side for larger values, all the way down the left side. But what if the largest value is on the right of some node? We'd better cover that case too:

int maxValue(Node *node)
{
    if (node == nullptr)
        throw "BT is empty";

    int max = node->data;

    if(node->left != nullptr) {
        int leftMax = maxValue(node->left);
        if(max < leftMax)
            max = leftMax;
    }

    if(node->right != nullptr) {
        int rightMax = maxValue(node->right);
        if(max < rightMax)
            max = rightMax;
    }

    return max;
}

Now since we only have  to check for NULL that will throw on the first node we can optimize slightly:

int maxValue(Node *node)
{
    if (node == nullptr)
        throw "BT is empty";

    return maxValueNonNull(node, node->data);
}
int maxValueNonNull(Node* node, int currentMax)
{
    if (node == NULL)
    {    return currentMax;
    }

    currentMax = currentMax > node->data ? currentMax : node->data;

    int leftMax  = maxValueNonNull(node->left,  currentMax);
    int rightMax = maxValueNonNull(node->right, currentMax);

    return leftMax > rightMax ? leftMax : rightMax;
}

That should do it.


When using callbacks, the first parameter is the error. So instead of throwing the error, you should pass it as the first argument. The signature of the callback should look like this function(err, all, other, arguments).

So instead of this

var fs = require('fs');

module.exports.getHandler = function(type,callback) {
    if(!type) {
        throw new Error('Please specifiy a type');
    }
    var nodeModule = type.ucFirst()+'FieldHandler';
    var file = __dirname+'/'+nodeModule+'.js';
    fs.exists(file, function(exists) {
        if (exists) {
            var handler = require('./'+nodeModule);
            var instance = new handler;
            callback(instance);
        } else {
            throw new Error('Handler for "'+type+'" does not exist. ' +
                'Expect file of handler to have the name "'+file+'"');
        }
    });
};

You should have something like

var fs = require('fs');

module.exports.getHandler = function(type,callback) {
    if(!type) {
        callback(new Error('Please specifiy a type');
    }
    var nodeModule = type.ucFirst()+'FieldHandler';
    var file = __dirname+'/'+nodeModule+'.js';
    fs.exists(file, function(exists) {
        if (exists) {
            var handler = require('./'+nodeModule);
            var instance = new handler;
            callback(null, instance);
        } else {
            callback(new Error('Handler for "'+type+'" does not exist. ' +
                'Expect file of handler to have the name "'+file+'"');
        }
    });
};

Then it should become pretty easy to test. As a bonus, you can have a look at https://github.com/cjohansen/Sinon.JS. It's a good module for mocks, stubs and spies.

Also, I realized that you are doing a synchronous for loop calling asynchronous functions. var aString = handleField(field); will never do what you are expected. handleField does not return anything. You should expect it in a callback. If you want a tip to handle the flow properly, use https://github.com/caolan/async. With this module, you will stay away of the mythical "callback-hell".

Enjoy, node.js!


Can reverse it the input with less code than these? Java

Searching on the site maybe this can help.

for(int i = 0; i < validData.length / 2; i++) {
  int temp = validData[i];
  validData[i] = validData[validData.length - i - 1];
  validData[validData.length - i - 1] = temp;
}

To reverse an int array


Avoiding repetitive code for timestamping and updating status

No idea about groovy, but it looks like a case for an EnumMap<RequestStatus, Data> with the map storing the (last) corresponding time and user. You need a single method

def action(RequestStatus status) {
    map.put(status, new Data(new DateTime(), springSecurityService.currentUser))
    this.status = status
}

If you really need 5 methods, you can define them trivially via action.


Generic methods to find the maximal element in part of a list

I'd just say to go with your implementation; just because it is easier to read! Also, you only .get() from the list once, whereas the proposed solution does it twice.

Shorter is not a synonym for better!

However, the generics are not good; you should at least use <T extends Comparable<? super T>>. Not sure why the proposed solution uses Object as a lower bound...


Singleton Pattern + unavoidable Public Constructor

The question is: what do you want to achieve.

As you store the singleton in the database it seems to me that your singleton is semantic and not technical.

Technical singletons have that unified structure of static instance field, maybe lazy initialization and private constructor to ensure only ONE instance per JVM.

Semantical singletons do not have the assertion to be unique per object identity in the JVM. Their assertion is they BEHAVE the same EVERYWHERE and they have semantic identity (equals) in ANY JVM to ensure identity beyond JVM boundaries.

Often this kind of singleton is used to have a central entry point to a domain/module.

To avoid the public constructor in the semantic singleton I have separated the requirement "central entry point" from "object instantiation". In my design I have a SingletonX class that adresses "central entry point". Furthermore I have a class X that is more or less a POJO Finally I have an interface InterfaceX to redefine the public interface of class X. Class X should be resolved at runtime and is mostly out of scope to be instantiated through client code. Class X is the class to be serialized.


Memory Handling

I see new but I don't see delete. Your tree leaks memory. It needs to clean up after itself in a destructor. And once you add that, you get into the Rule of Three: you need to add the copy constructor and the copy assignment operator, otherwise you'd still leak when you copy your tree.

Usage

Your code looks like an implementation of std::map, and your usage suggests the same, so it'd be better to change your template arguments from T and V (which mean nothing) to Key and Value. Using value as the key is confusing - you should name it key. Although conventionally nodes for maps in the C++ standard library use std::pair<const Key, Value>s.

You should make it clear that Key needs to be both LessThanComparable and EqualityComparable, or provide ways of passing comparators in as template arguments.

If I try to search() for something not in the map, x will eventually become nullptr and then you return x->data. Oops!

You can insert elements with duplicate values. Is that intentional?

inOrderTreeWalk should be spelled std::ostream& operator<<(std::ostream&, const BinarySearchTree &).

Other

Avoid using namespace std;, especially in headers.
Take your arguments by reference to const to avoid having to deal with copies.
You should support erasing elements.
You should look into various balancing algorithms for you tree so that if I insert 1 then 2 then 3 then 4 then 5, I don't end up with linear-time search.
return 0; from main() is implied, you don't need to explicitly provide it.


var propertiesToBeUpdated = properties.Select(p => {
    var prop = _context.MyObjectProperties.FirstOrDefault(x => x.Key == output.Key);

    return prop == null ? null :
        new MyObjectProperties {
            Key = prop.propertiesKey,
            Name = prop.propertiesName,
            Value = prop.propertiesValue
        };
}).Where(p => p != null);

The extra set of {} inside your LINQ statement allow you to do multiple lines. If for some reason, you're going to be absolutely POSITIVE that prop would never be null, it would simplify the LINQ a lot more by not having to return nulls (since you have to return SOMETHING for each item in the collection you're iterating). You also then wouldn't need the Where() at the end as well.

UPDATE

If it will never be null, then it is even simpler:

var propertiesToBeUpdated = properties.Select(p => {
    var prop = _context.MyObjectProperties.First(x => x.Key == output.Key);

    return new MyObjectProperties {
            Key = prop.propertiesKey,
            Name = prop.propertiesName,
            Value = prop.propertiesValue
        };
});


Forming all multiples of 3 using the given digits

How can I improve the performance of this code? Or should it be scrapped entirely?

I personally would consider taking a wildly different approach, but there are major performance improvements which can be made and which might be sufficient for your purposes.

        if (!combinations.includes(newPrefix)) {
          combinations.push(newPrefix)
        }

combinations is an array: combinations.includes is a linear search. I understand from the question that you're using Node, so the best way to improve this is probably hashset. However, if you want to stick to JavaScript primitives you can achieve a similar (albeit hacky) performance improvement by using an object as a hashmap:

        if (!combinations.hasOwnProperty(newPrefix)) {
          combinations[newPrefix] = 1;
        }

         else {
          console.log('encountered duplicate')
        }

If you also use a map for the remaining digits, you can ensure that you only try to extend with each digit once, and avoid the unnecessary work of handling duplicates.

I said that I would consider a wildly different approach. In combinatorics, if you only want to count objects then ideally you don't generate them all. You may have been taught in primary school that you can check whether a number is a multiple of 3 by adding its digits and seeing whether you get a multiple of 3. What's really going on there is that \$10 \equiv 1 \pmod{3}\$, so \$10^n \equiv 1 \pmod{3}\$ for any non-negative integer \$n\$. Thus you can cluster numbers by their values modulo 3. There are various directions in which this can be taken, and the need to avoid duplicates complicates things, so I suggest that you first try the earlier suggestions.


A program to tell you if there are 2 numbers in an array that add to a given sum

There are a few problems with the function right now.

gotPair leaks variables to the global scope. When you say this.data, this refers to the global scope so you create a global property called data. See How does the "this" keyword work? on SO.
Instead of storing an out variable, you can just return true when you find a match. This both reduces the complexity of the function and improves the speed. Imagine you have an array of 10 billion elements and you find the match in the first 2 elements. There's no need to go through the rest of the array.
Avoid creating variables you don't need. this.data is just arr, num isn't necessary as the subtraction can be performed in the call to includes, this.sum is the same as sum, and check is not needed as it is just a copy of arr from index 0 to i.

Here are a few alternative implementations.

Similar to your logic, but looping backwards so that we can take advantage of the fromIndex argument of the includes function. I've included type checks in this function to show how they might be done, but some people prefer to leave them out in Javascript and let the function throw "naturally".

function hasSumPair(arr, sum) {
    if (!Array.isArray(arr)) throw new Error('The first argument must be an array')
    if (Number.isNaN(sum)) throw new Error('The second argument must be a number')

    for (let i = arr.length - 2; i >= 0; i--) {
        if (arr.includes(sum - arr[i], i)) {
            return true
        }
    }
    return false
}

Explicitly looping through the array twice. This makes what the function is doing very clear but results in code that is somewhat uglier.

function hasSumPair(arr, sum) {
    for (let i = 0; i < arr.length; i++) {
        for (let j = i + 1; j < arr.length - 1; j++) {
            if (arr[i] + arr[j] === sum) {
                return true
            }
        }
    }
    return false
}

Here is a one liner that will have some problems with very large arrays since it will copy the array for each run.

function hasSumPair(arr, sum) {
    return arr.some((num1, index) => arr.slice(index + 1).some(num2 => num1 + num2 === sum))
}

This implementation is not the fastest as it has to sort the array first. If you can assume that the array is sorted, this would be the fastest solution (which is often very important at interviews for companies like Google)

function hasSumPair(arr, sum) {
    // .sort() mutates the array, so copy it using .slice() first.
    let sorted = arr.slice().sort()
    for (let i = 0; i < sorted.length - 1; i++) {
        for (let j = i + 1; j < sorted.length && sorted[j] + sorted[i] <= sum; j++) {
            if (sorted[j] + sorted[i] === sum) {
                return true
            }
        }
    }
    return false
}

The same function as above, but making use of some (Note that on the last iteration, arr[i + 1] will be undefined which will result in a NaN result and will work as expected). This is likely the implementation I would use if the array is sorted, and likely even if the array isn't sorted if the speed is not an issue.

function hasSumPair(arr, sum) {
    return arr.slice().sort()
        .some((a, i, sorted) => sorted.slice(i).some(b => a + b == sum))
}

Which of these functions is best is largely a matter of opinion and the case in which it will be used. Most of the time I recommend choosing readability over speed. Speed should only be considered if the time it takes to run the function is creating problems.


Overall, good code. There is a trap code fell into though.

while (!input.eof())

One of the frequently encountered problems with iostreams. Check the output if it has one extra newline. I'm sure you'll find it. intput.eof() is true when EOF is read, not before it.

Instead, use stream >> variable as a condition or the function that behaves like that. The expression returns a reference to stream itself, but the stream is convertible to bool to see if some failure occured. Basically, the expression above is all these steps:

Try to read.
Set failure flags if error encountered
Return the status

Put in a condition, it is the exact combination one needs to perform more or less controlled input. One needs to check if the read succeeded before doing anything. Some other functions in standard library behave like operator>>, std::getline() included.

As a result of above, the first line of the loop would just become a condition, and everything else intact.

while (std::getline(input, in)) {
    output << std::regex_replace(in, pattern, "($1 * resize.x) + pos.x, ($3 * resize.y) + pos.y")
       << '\n';
}

Smaller things follow.

Usage message would be nice. Usually frequently used utilities are put away from the code. Though in case of single argument programs it might not be much of a problem.

std::ofstream output(path.substr(found_name + 1, steps) + ".txt");

Is a little bit alerting. Since this is end user program (e.g. for a human), they might get something wrong.

Some missing consts here and there.

return 0 is redundant.


A small api that delays api requests using async/await with Node.js

setTimeout for a delay is as good as any other approach if you're happy to keep the load on the server. Other option is to separate the processing from the scheduling e.g. offload those particular requests to a scheduling service and then drip feed those back into your app for processing.

From a code point of view, there are some small things you can do to tidy it up a bit.... but the biggest issue I see with your code at the moment is there is absolutely zero error handling. Express does have a default error handler which conveniently catches an errors thrown inside middleware, however, just be wary that you do run the risk of leaking internal server details to the client if you let you just leave your errors to bubble up.

Here's a bit of a tidy up & better error handling

// handle post requests for getting yelp data
app.post('/post', async (req, res, next) => {
  try {
    // nice use of map makes handleYelp redundant :)
    const searches = req.body.map(x => searchPlace(x));
    const results = await Promise.all(searches);
    return res.send(results);
  } catch (e) {
    console.error(e); // log internal error
    return next(new Error('Internal Server Error')); // return public error to client
  }
});

function searchPlace(city) {
  return new Promise((resolve, reject) => {
    // use async / await here too :)
    setTimeout(async () => {
      try {
        const name = city.name;
        const location = `${city.coords.lat},${city.coords.lng}`;
        const result = await client.search({ name, location });
        const business = result.jsonBody.businesses[0];
        resolve({
          name: business.name,
          img: business.image_url,
          hours: business.is_closed,
          revcount: business.review_count,
          rating: business.rating,
          price: business.price,
          location: business.location.display_address.toString(),
          phone: business.display_phone,
          url: business.url
        });
      } catch (e) {
        return reject(e);
      }
    }, 100);
  })
}


Implement a range behaviour in Python using iterators

You have an iterator
Your code implements an iterator, you are right. You have defined a __next__ method and it works well.
I would tweak your code slightly, though:

remove the check because iterators can be empty and that is okay;
fix minor spacing issues around operators, etc;
use augmented assignment to increment;
change order of statements in __next__ to be more idiomatic.

All in all, MyRange would end up looking like this:
class MyRange():
    def __init__(self,data):
        self.data = data
        self.index = -1

    def __iter__(self):
        return self

    def __next__(self):
        self.index += 1
        if self.index == len(self.data):
            raise StopIteration
        return self.data[self.index]

In particular, the changes to __next__ are because you start by setting self.index to the value of the index you would like to read. Then, just before reading the value from data, you ensure you can actually use that index and raise StopIteration if you can't.
range is not any iterator
However, the "problem statement" says to implement an iterator that behaves like range, and as brought to your attention in the comments, range is a very specific iterator that can take up to 3 arguments: start, stop, and step.
Take a look at the docs for the range function here.
Having said that, solving this "issue" does not need to be very difficult.
You could do something as simple as having my_range take the three arguments,
generate the data you need, and then feed it into MyRange to iterate, but that seems like a waste.
What I think is more or less the intended approach, is to define MyRange to expect the start, stop, and step values, and the my_range function is what the user calls, which then fills in the start, stop, and step values that are used by default and calls MyRange.
E.g.,

my_range(10) would call MyRange(0, 10, 1);
my_range(4, 12) would call MyRange(4, 12, 1);
my_range(0, 13, -3) would call MyRange(0, 13, -3).

(In the examples above, I assumed you changed MyRange to do what I described.)
Therefore, just for the sake of clarity: what would be happening is that the __next__ method would use the three arguments start, stop, and step (and possibly other auxiliary variables you create) to compute the successive values, instead of generating all of them at once and then returning one by one.


N-tier application with BAL and DAL methods

Let's start with this anti-pattern.

    catch (Exception ex)
    {
        throw ex;
    }

You need to immediately search the code base for every instance of this pattern and remove it immediately. It serves no purpose but to destroy the stack trace. That makes it much harder to debug production issues, because you've no idea where the exception really came from.

(While you're at it, look for any place the previous developer may have been simply swallowing exceptions too.)

Next is this patten:

        DataSet DS = new DataSet();
        DS = CreditIntfDB.GetCreditRqstInfo(GeoID);
        return DS;

This allocated memory, only to instantly overwrite it with the value returned from the static method. This whole thing could be simplified down to a single line.

return CreditInfDB.GetCreditRqstInfo(GeoID);

Now, it's tempting to get rid of the BAL when it's just passing through like this, and eventually you might, but for now, leave it in place. It'll give you some wiggle room while you're replacing that abomination of a data layer with something modern.

Next thing to go is the static declaration on all of the BAL methods. Just remove it (one at a time!), then compile. Follow the errors until you've instantiated instances of the class everywhere you need it. This is called Leaning on the compiler.

Once that's complete, you'll need to stop returning those DataSets from the BAL. This will be by far the most tedious and painful part, but well worth the effort. Start modeling the data and creating POCO's to be returned from the BAL. Databindings client side will need to be updated. This means invasive changes in your views. Use the BAL to map the DataSets coming out of the DAL to your POCOs.

For example:

public class CreditMgr
{
   public IEnumerable<CreditRequestInfo> GetCreditRqstInfo(String GeoID)
    {
        DataSet ds = CreditIntfDB.GetCreditRqstInfo(GeoID);
        return ds.ToCreditRequestInfo();
    }
    //...
}

Where ToCreditRequestInfo() is an extension method that transforms a dataset into a list of your model class.

Now you're in a position to extract an interface for the BAL so it can faked during testing.

Finally, you'll be able to think about ditching the DAL entirely by replacing the guts of the BAL with calls to an ORM like Entity Framework.

public class CreditManager : ICreditManager
{
   public IEnumerable<CreditRequestInfo> GetCreditRqstInfo(String GeoID)
    {
        using (var dbContext = new CreditDbContext())
        {
            return dbContext.GetCreditRequestInfo(GeoID).ToList();
         }
    }

    //...
}

This is not for the faint of heart, and I wouldn't want to tackle it without an excellent refactoring tool like ReSharper and a copy of Working Effectively with Legacy Code by Michael Feathers nearby.

Best of luck. Remember, keep your changes small and safe. Don't change logic if you can avoid it and drive as many tests as you can at the code before changing it. (Although, you'll have to make a few changes to make it testable first... So... Slow and steady friend. Slow and steady.)


Inserting a record into MySQL with a timestamp

Security

SQL Injection

It's probably[*] secure, but it's not the right way to do it, see for example here why prepared statements are better than escaping. Sooner or later, you will mess up when escaping.

Prepared statements are not difficult to use, and result in code that is more secure and more readable, there is really no good reason not to use them.

[*] if $_SESSION['user_id'] is user supplied in any way, it's not secure.

XSS

Your call to strip_tags doesn't make any sense:

ENT_QUOTES isn't a correct value for the second argument, which actually accepts a list of allowed tags.
you should encode user input when echoing it, not when inserting it into the database.
strip_tags isn't enough to prevent XSS in all contexts.
strip_tags mangles your data.

Misc

you are mixing the object oriented style and the procedural style of mysqli, which isn't a good idea.
variables should start with a lower-case character.


Parsing a complicated CSV generated on election nights

# Make one more candidate than necessary into winners list
winners = sorted(cnds, key=lambda k: int(k['votes'], reverse=True)[0:num_win + 1]

# A tie to be resolved happens when two last candidates have equal vote count.
# if so, go backwards removing everybody with the same vote count.
# Binary search would work faster, of course. If a standard library
# provides something similar to std::lower_bound from STL -  its even better.

index = num_win
while index > 0 and winners[index - 1]['votes'] == winners[num_win]['votes']:
    index -= 1

# Finally, adjust your list
winners = winners[0:index]

PS: One more thing to mention. The final nested loop is not really the best approach. You should decorate the original list with the sequential numbers (or use some other method to remember initial ordering), sort it, mark the winners which are at the beginning of the list, and sort it by sequence numbers back to the original state.


Hint

Taking the example from the Project Euler page, if you have computed the Collatz number for 5 in the past and you know it's 6, then when computing Collatz number for 10, you probably don't need to go through the whole chain. You can stop when you reach 5.

It might be interesting to cache the computed value to be able to reuse them.

(Disclaimer : I solved this problem a long time ago and cannot really remember how I did it)


There is much to improve. I recommend you read PEP 8, the official Python style guide. It includes many important tips like:

Use consistent 4-space indentation
Multiple statements on the same line are discouraged

Furthermore:

You should use words instead of single letters for your variable names. All those variables like x, l, w, d, lt, wt, dt aren't self-explaining. What is their purpose? Instead: count_rounds, count_losses, count_wins, count_draws, ….
Your usage of object oriented features is extremely weird. Get rid of all classes for now.
Instead of x = x + 1 write x += 1.
Your code is really complicated because it munges together the user interface (prompting the user for choices, displaying results) with the actual logic of your program. Put the logic into separate functions, e.g.

def beats(choice_a, choice_b):
    if choice_a == 'rock' and choice_b == 'scissors':
        return 'smashes'
    if choice_a == 'scissors' and choice_b == 'paper':
        return 'cuts'
    if choice_a == 'paper' and choice_b == 'rock':
        return 'wraps'
    else:
        return None

This could be used as

def result_string(computer, player):
    verb = beats(computer, player)
    if verb:
        return "computer beats player because %s %s %s" % (computer, verb, player)
    verb = beats(player, computer)
    if verb:
        return "player beats computer because %s %s %s" % (player, verb, computer)
    return "draw"

which in turn could be used as print(result_string(computer_choice, player_choice)).

Please try to fix these issues and to clean up your code, then come back and ask a new question for a second round of review.


That's a pretty concise routine there.
If you had to change it, I would add methods to parse the user input so now your program logic is less nested and we get back to the good old principal of each method having a single purpose.

Normally in a simple app that has a menu structure I would say use case logic instead of if statements as this will allow you to easily extend the options later, but your cleaver use of the dictionary of functions does away with this altogether.

namespace CalculatorCA
{
    using System;
    using System.Collections.Generic;
    class Program
    {
        static void Main()
        {
            Dictionary<int, Func<double, double, double>> MyDict =
                new Dictionary<int, Func<double, double, double>>();
            FillDictionary(MyDict);
            bool KeepOn = true;
            while (KeepOn)
            {
                double first = ReadInput("Enter the first number!");
                int choice = ReadInput("Please choose one of the following:\n1-Add\n2-Substract\n3-Multiply\n4-Divide", 1, MyDict.Count);
                double second = ReadInput("Enter the second number!");

                Console.WriteLine("The result is : {0}", MyDict[choice](first, second));

                Console.WriteLine("Continue?[Y/N]");
                KeepOn = Console.ReadKey().Key == ConsoleKey.Y;
                Console.Clear();
            }
        }
        private static double ReadInput(string prompt)
        {
            Console.WriteLine(prompt);
            double userInput;
            if (double.TryParse(Console.ReadLine(), out userInput))
                return userInput;

            Console.WriteLine(" - Sorry, I expected a double, try again");
            return ReadInput(prompt);
        }

        private static int ReadInput(string prompt, int? min = null, int? max = null)
        {
            Console.WriteLine(prompt);
            int userInput;
            if (int.TryParse(Console.ReadLine(), out userInput))
            {
                if (userInput >= min.GetValueOrDefault(int.MinValue) && userInput <= max.GetValueOrDefault(int.MaxValue))
                    return userInput;

                Console.WriteLine(" - Sorry, I expected an integer, between {0} and {1}", min, max);
                return ReadInput(prompt, min, max);

            }

            Console.WriteLine(" - Sorry, I expected an integer, try again");
            return ReadInput(prompt, min, max);
        }

        public static void FillDictionary(Dictionary<int, Func<double, double, double>> myDictionary)
        {
            myDictionary.Add(1, (x, y) => x + y);
            myDictionary.Add(2, (x, y) => x - y);
            myDictionary.Add(3, (x, y) => x * y);
            myDictionary.Add(4, (x, y) => x / y);
        }
    }
}


OpenCV calculate center of mass for a single contour

It seem like you can definitely merge the two loops together.

Also you should avoid iterating using i, instead, use iterators, or the range-based for loop (since C++11).

// if you needed this vector
mu.reserve(contours.size());

// Get the mass centers:
std::vector<cv::Point2f> mc( contours.size() );
for( auto& c : contours )
{
  auto m = moments(c, false);
  mu.push_back(m); // only if you need the mu vector
  mc.push_back(cv::Point2f( m.m10/m.m00 , m.m01/m.m00 ));
}

And this can even be simplified to a call to std::transfer with std::back_inserter:

std::transform(
  std::begin(contours),
  std::end(contours),
  std::back_inserter(mc),
  [](const contour& c) -> cv::Point2f {
    auto m = moments(c, false);
    return cv::Point2f( m.m10/m.m00 , m.m01/m.m00 )
  }
);

And of course if you only need to know moments of one countour, there is no need to count it for all, but since you haven't included that part of the code, it's hard to tell anything about it.


The two versions execute exactly the same steps,
the only difference is the number of intermediary local variables.

Which version is more clear can be a matter of opinion.
Beginners may find your verbose version more clear,
more experienced programmers may find it tedious.

The good thing about the second version is that the local variables mark bigger logical steps that are quite intuitive. With one weakness, the meaning of the lines variable is not immediately clear. If you say "lines", it might mean a collection, or the count of lines.
But actually it's neither, it's the number of newline characters.

By contrast, your version marks the steps in too much detail,
for example it's not particularly interesting that readFileSync(file) doesn't return a String and it needs to be converted.
That step could be collapsed, as it is a too specific implementation detail,
not something "logical".

I think the best of both worlds would be more like this:

var fs = require('fs');

var path = process.argv[2];
var text = fs.readFileSync(path).toString();
var lines = text.split('\n');
var newlines_count = lines.length - 1;
console.log(newlines_count);

Each step marks a bigger logical step, with slightly more natural variable names.


Issue a citation based on speed, with lenience for your birthday

This function should probably be static, since it does not rely on any instance variables.

On your birthday, your speed can be 5 higher in all cases — so don't make three more cases for the birthday.

If you have already determined that the speed is not <= 60, then there is no point in testing 61 <= speed — that will always be the case.

Since all three branches similarly return an expression, I would use a ternary statement.

public static int caughtSpeeding(int speed, boolean isBirthday) {
    int birthdayAdjustedSpeed = isBirthday ? speed - 5 : speed;
    return (birthdayAdjustedSpeed <= 60) ? 0 :
           (birthdayAdjustedSpeed <= 80) ? 1 :
                                           2;
}


Speeding up storage of about 220000 values in Core Data

Ten seconds for reading/writing nearly half a million lines from/to disk is actually relatively decent.

The autorelease pool doesn't actually slow us down.  Autorelease pool is handled by the preprocessor.  So is ARC.  Instead of us manually writing our release/retains, ARC, or autorelease pool, will do this for us.  However, I actually would make a change to how you're handling the autorelease pools so that you're minimizing the amount of information you're keeping in RAM at any given time.  For example:

@autoreleasepool {
    // read waypoints from file into memory
    // loop through waypoints array putting them into core data
}

@autoreleasepool {
    // read navaids from file into memory
    // loop through navaids array putting them into core data
}

Make no reference to waypoints outside the first autorelease pool and no reference to navaids outside the second autorelease pool and you'll be using approximately half as much RAM throughout this method.

Though... a cleaner way might be to just put each in their own method and then the same is accomplished without autorelease pools (which again, will not slow down your code).

We can however speed up your code.  If we use a forin loop rather than a traditional for loop the code will run faster as we'll overall be passing significantly fewer messages.  For example:

for (NSString *waypoint in wayptContentLines) {
    NSArray *brokenFix = [waypoint componentsSeparatedByString:@"|"];

    newContact = [NSEntityDescription insertNewObjectForEntityForName:@"Waypoints"
                                               inManagedObjectContext:context];

    [newContact setValue: [brokenFix objectAtIndex:0] forKey:@"name"];
    [newContact setValue: [brokenFix objectAtIndex:1] forKey:@"latitude"];
    [newContact setValue: [brokenFix objectAtIndex:2] forKey:@"longitude"];
}

Now, instead of calling to wayptContentLines twice per iteration (nearly a million times) (once to check length, once to grab the object at index), we're instead calling to the array less than once per iteration (the exact amount varies).

A forin loop in Objective-C reads several objects into a buffer then deals with the objects in the buffer before reading the objects in.  I think on average it reads in about 8 objects, so you go from 2/i to 1/8i messages to wayptContentLines.  In English, a for loops probably sends about 16 times as many messages to the array as a forin loop would... and over 400,000+ iterations, thats a LOT of messages and it will take up a lot of time.


How to refactor that content_tag adding method?

Just use variables for repeated expressions:

def set_caption(result)
  type_div = content_tag(:div, result.type_name, class: 'type-name')
  if result.respond_to?(:app_name)
    type_div + content_tag(:div, result.app_name, class: 'app-name')
  else
    type_div
  end
end

Note that you can move the conditional further in: type_div + (condition ? app_div : ""). Use this style whenever this adds readibility (here I'd say it doesn't).


Determine the winner of a coin flip game

The biggest simple improvement you could make would be to declare your variables in a more limited scope.  As you have written it, I cannot easily tell whether the statistics are cumulative, or each line is being treated as an independent problem.

count being a double is weird; it should be an int.

I suggest calling .toLowerCase() once per line instead of once per word.

It's probably worthwhile to do an extra simple check to ensure that every word that is not an "H" is a "T".

The calculation for ratio is more complicated than it needs to be.

You aren't using printf() effectively — the whole point of printf() is to take advantage of the format string rather than concatenation.

public static void coinFlip(Scanner input) {
    while (input.hasNextLine()) {
        int heads = 0, tails = 0;

        StringTokenizer tokens =
            new StringTokenizer(input.nextLine().toLowerCase());
        while (tokens.hasMoreTokens()) {
            String token = tokens.nextToken();
            if ("h".equals(token)) {
                heads++;
            } else if ("t".equals(token)) {
                tails++;
            }
        }

        double ratio = 100.0 * heads / (heads + tails);
        System.out.printf("%d heads (%1.1f%%)\n", heads, ratio);
        System.out.println((heads > tails) ? "You win!\n" : "");
    }
}

One alternative to StringTokenizer would be to use Scanner.findInLine().

public static void coinFlip(Scanner input) {
    while (input.hasNextLine()) {
        int heads = 0, tails = 0;
        String token;
        while (null != (token = input.findInLine("\\b[HhTt]\\b"))) {
            switch (token) {
                case "H": case "h": heads++; break;
                case "T": case "t": tails++; break;
            }
        }

        double ratio = 100.0 * heads / (heads + tails);
        System.out.printf("%d heads (%1.1f%%)\n", heads, ratio);
        System.out.println((heads > tails) ? "You win!\n" : "");
    }
}


Returns the year for each month by period - nested case statements

Assuming that billing_increment is always an integer that is a factor of 12, the code should be entirely formulaic.

def return_year_by_month_and_period(month)
  period_len = property_water.first.billing_increment.to_i
  if 12 % period_len != 0
    # TODO: decide what the appropriate behavior should be
    self.property_water.first.year
  else
    nth_period = (month - 1) / period_len + 1
    property_water.where(period: nth_period).first.year
  end
end

I've incorporated additional suggestions from @tokland:

In Ruby it's not idiomatic to write self., nor parens on calls without arguments.
Write the second case in an else. Full conditional branches are easier to read.


Finding the number of times the code will generate an alert depending upon whether the transaction is fraudulent

close

You had an opportunity to acquire (and then close) this resource
using try-with-resource

private static final Scanner scanner = new Scanner(System.in);

Similarly for this one:

new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));

streaming input

You're reading 200,000 numbers here:

    String[] expenditureItems = scanner.nextLine().split(" ");

They won't fit in the lower levels of the cache hierarchy, they are spilling to RAM.
Consider reading as you compute.
You never need much more than d numbers to be resident at once.

no-op

This doesn't appear to do anything for you. Consider deleting it.

    scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

temp var

The compiler optimizes it away,
but needlessly introducing a temp variable makes your code harder to read:

        int expenditureItem = Integer.parseInt(expenditureItems[i]);
        expenditure[i] = expenditureItem;

Just phrase it as:

        expenditure[i] = Integer.parseInt(expenditureItems[i]);

Not sure why you wanted to allocate 200,000 strings and then 200,000 ints,
when you could have streamed through them one string at a time.

Integer.toString

In addition to needless temp var,
it seems you chose to define an inconvenient API:

    int result = activityNotifications(expenditure, d);
    bufferedWriter.write(String.valueOf(result));

You might find it slightly more convenient to write the result
if activityNotifications returned Integer.

API

You might have found it convenient to pass in two separate arrays,
one containing d entries and the other containing the n - d
entries that you have to make decisions on.

Ok, it appears you spend almost no time in main,
relative to what activityNotifications consumes.

sort

The pair of nested loops headed by

        //Sort the exSub array

is quite insane.
You know d shall be "large".

You have an opportunity to use Arrays.sort() with cost O(d log d),
yet you went for the quadratic solution, O(d**2).

printing

I don't understand the comment "Printing the exSub array in each iteration".
Why would you want to spend time doing that?
Only the return value count is relevant for evaluating your submission.
Similarly for your debug print of mid.

algorithm - heap

You (re-)sort d elements every single time.
Even though only a single value entered the d-day window,
and a single value left.
Maintain a heap, at cost of O(log d) for each operation.

algorithm - counting values

Go back and read the problem.

Are expenditures floats of arbitrary precision? No, they are integers.

Can expenditures have arbitrary magnitudes as large as the U.S. debt?
No, only two hundred and one distinct values are allowed.

Recall that a median value separates the low half from the high half of the values.
Maintain 201 counts,
and a circular FIFO list of daily expenditures
(or continue using the giant n-entry input array,
indexing it d behind today).
Increment a count corresponding to today's expenditure,
and decrement a count for the day exiting the d-day window.
Identify the point at which the sum of the low counts
matches the sum of the high counts, that's your median.
You can do it in time proportional to 201 (much less than d),
or you can choose to do it faster than that
by maintaining cumulative sums
and remembering what yesterday's median was.
Good luck!


You're correct that nesting a case in an elsif ladder is a bit clunky here, but the two things that jump out at me as making the code difficult to comprehend are: 1) we have to know everything that's going on with the Regexp passed to scan() in order to figure out the intent of the if clauses, and 2) the variable string is not a String, but an Array.

You can remove the capture groups from your Regexp to just get an Array of Strings back from scan() (instead of an Array of Arrays of Strings), and figure out what exactly was matched by looking at the strings themselves - which means you don't need a nested case anymore, and makes it a little more obvious what scan() is doing without having to actually parse its argument.

Like this:

# example.rb
code = '--+++.,,'
code.scan(/\++|\-+|[.,]/).map { |str|
  case str[0]
  when '+'
    "Plus signs: #{str.length}"
  when '-'
    "Minus signs: #{str.length}"
  when '.'
    'Dot!'
  when ','
    'Comma!'
  end
}.each {|ll| puts ll}

Produces:

$ ruby example.rb
Minus signs: 2
Plus signs: 3
Dot!
Comma!
Comma!


Simplify function to sum the absolute value of the difference between all pairs of elements of a sorted array

Let's see this mathematically. I am assuming that a is an ascendingly sorted array. I start with indexes from 1, to get better readability (by avoiding n-1 as often as possible).

We want the following sum:

$$\begin{array}{l@{}l@{}l@{}l}
\sum_{i=1}^{n-1} \sum_{j=i+1}^n (a_j - a_i) = (a_2 - a_1) &+ (a_3 - a_1) &+ (a_4 - a_1) + & \dots + (a_n - a_1) +\\
                    &+ (a_3 - a_2) &+ (a_4 - a_2) + & \dots + (a_n - a_2) +\\
                                &&+ (a_4 - a_3) + & \dots + (a_n - a_3) +\\
                                            &&& \dots
\end{array}$$

So, we:

add a1 zero times, a2 once,... ak k-1 times, and
subtract a1 n-1 times, a2 n-2 times,... ak n-k times.

I'd say that your sum is

$$
\sum_{k=1}^n (k-1)a_k - \sum_{k=1}^n (n-k)a_k = \sum_{k=1}^n (2k-n-1)a_k
$$

Given your example (1,2,3,4), we get:

$$
\sum_{k=1}^4 (2k-4-1)a_k = -3 \cdot 1 + (-1 \cdot 2) + 1 \cdot 3 + 3 \cdot 4 = -3 - 2 + 3 + 12 = 10.
$$

This has a linear complexity, which is optimal, because you need to "visit" each member of the array at least once (which is linear).

I believe you can write your code by yourself. Just set indexes to go from zero, but be careful about the formula: 2k - n - 1 becomes 2k - n + 1 when k starts from zero.


Cleaning up the code of a C++-based Personal Web Page Generator

There is a lot that can be improved here.  Here are some ideas.
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.
Use all required #includes
This code fragment uses a number of features that require included library headers.  In this case they appear to be:
#include <iostream>
#include <fstream>
#include <string>

It was not difficult to infer, but it helps reviewers if the code is complete.
Provide complete code to reviewers
This is not so much a change to the code as a change in how you present it to other people.  Without the full context of the code and an example of how to use it, it takes more effort for other people to understand your code.  This affects not only code reviews, but also maintenance of the code in the future, by you or by others.  One good way to address that is by the use of comments.  Another good technique is to include test code showing how your code is intended to be used.
Decompose your program into functions
All of the logic here is apparently in main in one long and repetitive chunk of code.  It would be better to decompose this into separate functions.
Don't use std::endl if you don't really need it
The difference betweeen std::endl and '\n' is that '\n' just emits a newline character, while std::endl actually flushes the stream.  This can be time-consuming in a program with a lot of I/O and is rarely actually needed.  It's best to only use std::endl when you have some good reason to flush the stream and it's not very often needed for simple programs such as this one.  Avoiding the habit of using std::endl when '\n' will do will pay dividends in the future as you write more complex programs with more I/O and where performance needs to be maximized.
Simplify and consolidate steps
Rather than having two separate lines to declare and then open the webpage file, do it in a single step:
std::ofstream webpage{"Webpage.html"};

Use string concatenation
The program has many repeated lines where the ostream operator<< is used multiple times with a fixed string.  Those multiple calls don't need to happen.  You could simply rely on the fact that C++ merges separate constant strings automatically.  For example, here is a recoded portion:
std::ofstream webpage{"Webpage.html"};
webpage << "\n"
    "\n"
    "\n"
    "\n"
    "\t\n"
    "\t\t
" << name << "
\n"
    "\t\n"
    "\t
"
    "\t" << description << "\n"
    "\t
"
    ""
    "";

First, HTML parsers don't care about newlines, so it really doesn't matter much if they are present or not.  Second, this is now a single explicit invocation of ostream operator<<.
Understand relevant standards
The HTML  tag is obsolete and should not be used.
Adding features
Using an HTML template instead is a good idea and would keep the code generic while enabling customization of use.  One way to do that would be to read in a file and then substitute special tags such as @name@ and @description@ but simply copying the rest verbatim.


Creating validators

I think it's perfectly readable. However, there's a lot of repetition.

To make creating validators simpler and more declarative, you could take it one step further and lift the test/return-Optional logic into a higher-order function:

public class StudentControl {

  public static final StudentValidator namesValidator = validator(
    student -> namePattern.matcher(student.getName()).matches(),
    "Invalid name"
  );

  ...

  private static StudentValidator validator(Predicate<Student> pred, String error) {
    return student -> pred.test(student)
      ? Optional.empty()
      : Optional.of(error);
  }
}

and then if you have other models besides Student, you might genericize the validators.

interface EntityValidator<T> extends Function<T, Optional<ValidationError>> {}

public abstract class EntityControl<T> {
  protected final List<EntityValidator<? super T>> validators = new ArrayList();

  protected EntityValidator<T> validator(Predicate<T> pred, String error) {
    return x -> pred.test(x)
      ? Optional.empty()
      : Optional.of(error);
  }

  // Or, if you want to allow any subclass to create a validator for any type,
  // it could be static:
  protected static <T> EntityValidator<T> validator(...)

  public Optional<List<ValidationError>> validate(T entity) {
    ...
  }
}

This feels a bit cleaner to me as far as separation of concerns, but if you're only ever going to validate Students it's probably overkill.

Other

You might also consider having validate() return an Optional<Set<ValidationError>> instead of the List, if order isn't important. Since validation errors are just strings, you can't effectively do any further handling of them, so I assume they just get piped out to the user somehow?

  Does it comply with the MVC pattern?

I'm not an MVC expert, but: what is the view supposed to be? You haven't included anything that displays Students or errors, receives input, or otherwise does anything with Students, so it's hard to thoroughly assess this.


Try to make the input and output types the same

In your example, remove_outliers() takes a NumPy array as input, but returns a regular Python list. It would be nicer to have the function return a NumPy array in this case.

The axis parameter only works when using the median

Make sure that when you specify axes, that the resulting behaviour of the function is what you would expect. If, for some reason, the axis parameter could not work with means, then you should throw an error if the caller explicitly specified which axes to work on.

Don't calculate values you are not going to use

You calculate both the median and the mean, but only use one of them. This is inefficient, just write the code as:

if use_median:
    measure = np.median(data, axis)
else:
    mean, std_dev = cv2.meanStdDev(data)
    measure = mean

I know you always need the standard deviation, but see the next comment.

Avoid using CV2 for something as simple as calculating mean and standard deviation

NumPy has functions for calculating those things as well. By avoiding importing cv2, you reduce the amount of dependencies users would have to install. As a bonus, the NumPy functions for mean and standard deviation also take an axis parameter. So consider writing:

std_dev = np.std(data, axis)

if use_median:
    measure = np.median(data, axis)
else:
    measure = np.mean(data, axis)

Don't special-case 3-dimensional data

Why are you reshaping the input array only if len(data.shape) == 3? Your should aim to make your code work generically with arrays of any number of dimensions.


Scale an image to fit some maximum dimension using vanilla JavaScript code

I would probably use Math.max(), as that seems more readable to me and would make what is happening more clear. However, I don't think it will affect efficiency in any meaningful way since it's still making a comparison to determine the max.

var scale = maxdim / Math.max(width, height);


Summation and multiplication of digits of a number

Using std::accumulatewould be more idiomatic. Also use auto whenever possible.

#include <algorithm>
#include <functional> // requires C++14, else use a lambda for the predicate
auto sum = std::accumulate( digits.cbegin(), digits.cend(), 0 );
auto prod = std::accumulate( digits.cbegin(), digits.cend(), 1, std::multiplies<>);

Comment on the accepted answer, which I at first mistook for an edit of the question:

Class names should be nouns, function names should be verbs. As in DigitsCalculator.
Your no argument constructor can be written as CalcDigits = default.
Having a setter and getter for a private variable effective eliminates the encapsulation. There are divergent opinions on this topic. Some say a setter is better, because you can add logic for accessing the variable later. I, personally, have never "added logic" to a setter, and would just make the variable public.
You have an invariant: CalcDigits c; c.SetNumber(42); c.GetSum(); c.GetMul();. Interfaces should be "easy to use correctly, difficult to use incorrectly.
Overall, I like the new look better. You have separation of concerns (command line communication and actual calculation). You also have an encapsulated object, that you can pass around with clear intent.


It's a bad idea to modify the session state from inside a view or a partial view. Instead, I would create an alert view model

public class AlertViewModel
{
    public AlertType AlertType { get; set; }
    public string Message { get; set; }
}

public enum AlertType
{
    None,
    Success,
    Error
}

and use that from inside the view/partial view, for example:

@if (Model.AlertType != AlertType.None)
{
    string alertClass = Model.AlertType.ToString().ToLowerInvariant();

    <text>

@Model.Message

    </text>
}

This way, you avoid modifying the session where someone else may not expect it, and you have a cleaner view.

About populating the view: I do not know why you are using the session, but if the value is only needed for one request, you should consider using TempData instead. In any way, just populate the view model in the controller and remove the session value if you need to.


Firstly, Date objects can be compared directly.

Secondly, even if you did need to convert to something numeric, Date already has a getTime method, which returns an Epoch timestamp with milliseconds.

Thirdly, your function has serious side-effects. It overwrites a property on every object - which there's really no call for.

And lastly, you're missing semicolons, and should indent the chained function calls.

You should be able to get by with just:

var sorted = _.sortBy(arr, dateProp);

Or, without any libraries whatsoever:

function orderByDate(arr, dateProp) {
  return arr.slice().sort(function (a, b) {
    return a[dateProp] < b[dateProp] ? -1 : 1;
  });
}

Of course, if your dates are strings, you may need moment.js for that (though JS's Date can parse some stuff on its own). But in that case, you should probably also supply moment.js with the format it's supposed to parse, or at least have it as an optional argument.


Keep ABC size down for conditional string concatenation in Ruby

Perhaps just extracting the hash lookups would help:

def comment_event_string(comment)
  EVENT_TEXT[comment.event.to_sym]
end

def comment_reason_string(comment)
  " due to #{REASON_TEXT[comment.reason.to_sym]}"
end

def comment_text_string(comment)
  ": #{comment.text}"
end

def comment_text(comment)
  text = ''
  if comment.event.present?
    text += comment_event_string(comment)
    text += comment_reason_string(comment) if comment.reason.present?
  end
  text + comment_text_string(comment) if comment.text.present?
end

Passing comment around seems to be to be something of a code smell though, and I wonder if this code would be better placed inside the Comment class.

private def event_string
  EVENT_TEXT[event.to_sym]
end

private def reason_string
  " due to #{REASON_TEXTreason.to_sym]}"
end

private def text_string
  ": #{text}"
end

def nice_text(comment)
  nice_text = ''
  if event.present?
    nice_text += event_string
    nice_text += reason_string if reason.present?
  end
  nice_text + text_string if text.present?
end


Flip coin Game in an Object oriented way

Smurf naming convention

Link

internal class Player
{
    public string playerName { get; set; }

playerName is redundant since it's a preoperty of the Player class. Name is sufficient.

Assigning a coin option to a player

There are a few issues here, it's hard to separately address them.

Firstly, you're violating SRP by making your Player class responsible for UI interactions:

public CoinOptions chooseCoinOption()
{
    //Console.WriteLine("Chose a coin option");
    //Console.ReadKey();

    return coinOption;
}

I see where your confusion comes from. "The player chooses the side of the coin" is a correct statement. But, and this is an important distinction, this is not equivalent to "the Player class should handle the UI logic for choosing the side of the coin". The second statement is incorrect as it breaks SRP.

The Player class needs to be told what its option is (= an external caller sets the value). The decision logic for deciding which value to set is not part of the Player class' responsibility. It shouldn't care why or how a particular side was chosen, it should only care which side was chosen.

chooseCoinOption() needs to be removed.

Secondly, the setCoinOption(CoinOptions opponent) method's intention really irks me.

public void setCoinOption(CoinOptions opponent)
{
    coinOption = opponent == CoinOptions.Heads ? CoinOptions.Tails : CoinOptions.Heads;
}

As an aside, opponent is a really bad name for this variable. When reading your code I initially assumed opponent to be of the Player type. A better name for your parameter would've been opponentCoinOption.

You're adding in a lot of custom logic that does not simplify the code. Anyone who calls this method needs to know exactly what it does (= pick the other option), which means that it's a meaningless encapsulation. Calling the method does not meaningfully simplify the external caller's responsibility.

When removing the opponent parameter, you are left with a default set method. And since the property already has a public setter:

public CoinOptions coinOption { get; set; }

There is no point to also having a setter method. You need to remove one of the setters. Which one you remove is up to you. I prefer just using the default set; in this case.

Checking for victory

public bool didPlayerWin(CoinOptions winningFlip)
{
    return winningFlip == coinOption;
}

This method doesn't really provide anything. It's a wrapper around an equality check, and the value you're comparing (coinOption) is already publically accessible.

I'd remove this method altogether.

Secondly, I just want to point out that the Player class should not be determining what a Win is. A win is defined by the rules of the game, and the Player does not define the rules of the game. This is again violating SRP.

As a simple example, imagine if the rules of the game were changed so that you lose the game when your option is called. Suddenly, your method name conflicts with the rules of the game, which proves the point that your Player class somehow depends on the rules of the game you're playing, which means you're leaking your abstractions.

I know this is pedantic, but if you had named this method HasCoinOptionEqualTo(CoinOptions option), I would not have considered this an SRP vioaltion, because you are no longer checking for a win, you are simply checking an equality (which coincidentally just happens to be the win condition of the game you're playing).

Minor comments

 private List<Player> players = new List<Player>(Enumerable.Repeat(default(Player), 2));

I don't see you having defined a default for Player anywhere, which means that you're simply creating a list with two null values. What is the benefit of doing so? I suggest simply doing new List<Player>() and adding the players at a later stage.

However, I would take it further and do away with the list altogether. You will always have two players, and you're going to have to create logic to always retrieve the correct player from the list. It's much easier (believe me, I've built a few two player games before) if you just keep these as two separate properties:

private Player player1;
private Player player2;

class Coin { ... }

I see no added purpose to making an object out of Coin. This can be a simple static class:

public static class Coin
{
    private static Random random = new Random();

    public static CoinOptions Flip()
    {
        // ...
    }
}

internal class CoinGame
{
    public void playCoinFlip() { ... }

    public void gameResult() { ... }
}

Similar to mentioned before, don't mix your game logic with your UI logic. gameResult() should not be in here.

Instead, playCoinFlip() should return the outcome of the game (in whatever form you choose), and then the UI logic can choose to display the outcome however it wants.

This ties into how your main function works:

coinGame.playCoinFlip();
coinGame.gameResult();

Doing it this way requires the main function to call different methods in a particular order, which again requires the main method to know how the CoinGame works internally, thus infringing on your encapsulation.

It would be much cleaner if you could do something like:

Player winner = coinGame.playGame();

Console.WriteLine($"{winner.Name} won the coin flip!");

public void playCoinFlip()
{
    int chooseIndex = new Random().Next(2);
    int applyIndex = chooseIndex == 0 ? 1 : 0;
    var selectedOption = players[chooseIndex].chooseCoinOption();
    players[applyIndex].setCoinOption(selectedOption);
    winningFlip = coin.flipCoin();
}

What I find very weird is that you let the external caller (your main function) choose the names of the players, but you don't allow the external caller to choose the coin option that each player chooses.

I understand that since either choice is a 50/50, it doesn't really matter here. But if that is the case, then Player shouldn't even need a CoinOptions to begin with.

I would reshuffle this so your CoinGame receives two players, rather than two names. This gives your external caller to choose the coin options.

public CoinGame(Player p1, Player p2)
{
    player1 = p1;
    player2 = p2;
}


Reading in millions of lines of AOL query logs for query suggestion/expansion

Maybe some of my answers and thoughts from this thread (Scanning through logs (tail -f fashion) parsing and sending to a remote server) can help you.

What I want to point out: It's very important, to measure. If you just post a piece of code and tell, it takes that amount of time and ask, how to increase 'performance', it's usually ghost hunting. If you can reduce the time of a routine by 99% but it only takes 1% of the overall time - you just wasted your time.

My main concern about the app is the use case: You're reading millions of lines into memory into a tree structure for further processing/querying - at least that's my interpretation. Have you thought about using an indexing library, such as Apache Lucene? Usually, people invest more time in better response times, instead of "indexing times" - which is, of course, also important, if you have a real-time or near-real-time requirement. But then I would analyze the software architecture first.

Other than that, I can't identify any major problem with the code. One problem could be the garbage collector, since millions of lines are using a lot of memory. And more memory means more memory managament. But that has to measured too and also analyzed in detail. Playing around with collectors, heap sizes, collector threads and so on, can improve throughput significantly.

Hope this helps,

slowy


classList fallback (IE & older browsers)

I'm not a big fan of neither the function name classes nor the parameter name type. Something like modifyClassOfElement and action would be better fitting.

You should define constants for the type/action values.

It's convention in JavaScript to have a space between keywords and a following open bracket: if  (

In classIndex the second if is unnecessary. Just put return null; after the loop. Or, even better, you can replace the whole function with an .indexOf() call.

Move if (type == "remove" || type == "toggle") { up one level so you don't need it twice. Alternatively I'd just drop the special case for a single class, as it's an tiny optimization that is hardly worth it.

Remove one level of brackets on the final else:

else if (type == "add" || type == "toggle") {
  element.className += " " + targetClass;
}

I'd consider throwing an exception, if the type/action is unknown to aid debugging.

It would be nice for the function to use classList if it's available. Personnally I'd implement this as a function that returns an existing classList or an object that implements the same interface (DOMTokenList)


using (IDisposable) in c# factory pattern

No, you can't use a factory to dispose your objects, your code is creating and immediately disposing the SPSite  as soon as it steps out of your method.

public override SPSite GetSite(string url = null)
{
    return new SPSite(string.IsNullOrEmpty(url) ? Url : url))
}

Have the disposing be handled by the calling code. You can't handle the disposing from a factory method.

If you want to check it out, build your own disposable type, put a breakpoint in the Dispose method and check for yourself.


First: The Pascal Triangle will grow very rapidly. And rows=100, your maximum value is 1.27388061294904e+28. Yes, that's right it will overflow int, uint, long, and ulong within 100 rows. Check it out on interactive pascal triangle site
The only suggestion is Numerics.BigInteger where there is no upperbound.

Second: Why are you using List<List<int>>? You can use a jagged array, which is much shorter: int[][], and effectively does the same. You just need to initialize them ahead with their size

var triangle = new int[rows][];
for(int i = 0; i<rows;i++){triangle[i] = new int[i+1];}

Third: if you know the first and last element is always a 1, then the if-statement for the first 2 rows is redundant

// This part is redundant, you already check if the first/last element is 1
if (x == 0 || x == 1)
{
    result.Add(Enumerable.Repeat(1, x + 1).ToList());
}

So with all the improvements, you code would be shorter and could handle much more rows. As a bonus I removed the dependency on system.linq. It could look like this:

public static BigInteger[][] GetPascalTriangleImproved(int rows)
    {
        BigInteger[][] result = new BigInteger[rows+1][];
        for (int x = 0; x < rows; x++)
        {
            result[x] = new BigInteger[x + 1];
            result[x][0] = 1; // first element is ALWAYS 1

            for (int x1 = 1; x1 <= x; x1++)
            {
                // last element is always 1 (just like the first)
                if (x1 == x) { result[x][x] = 1; continue; }

                // in all other cases, just add the 2 digits in the upper row
                result[x][x1] = result[x - 1][x1 - 1] + result[x - 1][x1];
            }
        }
        return result;
    }


I can't write the code in Objective-C, but in C, you could create yourself a structure type to get the information in one move.  I don't know whether the NSStringDigestTypeXXX values are conveniently numbered compactly from 0 or 1, so I'm taking the pessimistic view that they are not.  You can simplify the code below if they are compact and small.

struct Digestifier  // Declaration in a header (probably)
{
    int      hashtype;
    void   (*hash)(const char *source, size_t length, char *result);
    size_t   hashlen;
};
static const struct Digestifier digests[] =
{
    { NSStringDigestTypeSHA1,   CC_SHA1,   CC_SHA1_DIGEST_LENGTH   },
    { NSStringDigestTypeMD5,    CC_MD5,    CC_MD5_DIGEST_LENGTH    },
    { NSStringDigestTypeSHA512, CC_SHA512, CC_SHA512_DIGEST_LENGTH },
};
{ enum NUM_DIGESTS = sizeof(digests) / sizeof(digests[0]) };

You can then write a lookup function for this:

const struct Digestifier *digest_lookup(int hashtype)
{
    for (i = 0; i < NUM_DIGESTS; i++)
    {
        if (digests[i].hashtype == hashtype)
            return &digests[i];
    }
    assert(i != NUM_DIGESTS);  // Or other error handling!
    return 0;
}

And in your function:

- (NSString *)hashWithDigestType:(NSStringDigestType)type {
    const char *s = [self UTF8String];
    const struct Digestifier *digest = digest_lookup(type);

    // Error check digest if digest_lookup() does not do it for you!
    unsigned char result[digest->hashlen];
    digest->hash(s, strlen(s), result);

    NSMutableString *digest = [NSMutableString stringWithCapacity:(digest->hashlen * 2)];
    for (NSUInteger i = 0; i < digestLength; i++)
        [digest appendFormat:@"%02x",result[i]];

    return [NSString stringWithString:digest];
}

Note that you could also write the hash function invocation as:

    (*digest->hash)(s, strlen(s), result);

To some of us old-school (pre-standard) C programmers, that might perhaps be clearer.

Also, if Objective-C supports the C99 designated initializer notation, you could make the initializer for the digests[] array more robust (and render the hashtype member superfluous except for a cross-check):

static const struct Digestifier digests[] =
{
    [NSStringDigestTypeSHA1]   =
           { NSStringDigestTypeSHA1,   CC_SHA1,   CC_SHA1_DIGEST_LENGTH   },
    [NSStringDigestTypeMD5]    =
           { NSStringDigestTypeMD5,    CC_MD5,    CC_MD5_DIGEST_LENGTH    },
    [NSStringDigestTypeSHA512] =
           { NSStringDigestTypeSHA512, CC_SHA512, CC_SHA512_DIGEST_LENGTH },
};

This initializer correctly places the three rows in the array regardless of which member of the enumeration is mapped to 0, 1, 2.

With the additional information that the NSStringDigestTypeXXX values are 0, 1, 2, you can simplify the digest_lookup() function by:

Ensuring that the rows in the digests array are in the correct (0, 1, 2) sequence.
Changing from a search loop to a direct array lookup.
Probably asserting that the value is under control.

For the purposes of the code below, I'm assuming that NSStringDigestTypeMD5 is 0 and NSStringDigestTypeSHA512 is 2, but the ordering of the names is arbitrary; just choose the equivalent of 0 for the first name in the assert and 2 for the second.

const struct Digestifier *digest_lookup(NSStringDigestType hashtype)
{
    assert(hashtype >= NSStringDigestTypeMD5 &&
           hashtype <= NSStringDigestTypeSHA512);
    assert(digest[hashtype].hashtype == hashtype);
    return &digests[hashtype];
}

The first assertion ensures that the value is in range.  The second assertion ensures that the table is properly sequenced and you are getting back the entry your expect.


Listing all directories, sub directories and files starting from the root

well . and  .. are not directories, thats are navigationpoints of directories, . means go inside a root directory, .. means go one folder back,

you might noticed this already in includes like include ../../../foo/bar.php

also instead of scandir and readdir php has classes for this purpose DirectoryIterator or FileSystemIterator

And if you wish to create reusable methods, dont do output there, instead return an array of folders/files something like

$directories = scanDirectories($rootDirectory); //create output array
foreach($directories as $directory){
    echo $directory.'
';
}

this allowes you to modify the output without editing the sourcecode, you could also wrap the output within a function e.g. viewDirectories and reuse it on different places.

here is a small Example

    ini_set('html_errors', 'On');

function scanDirectory($path) {
    $path = realpath($path);

     return  new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::SELF_FIRST);

}

foreach(scanDirectory('./') as $name=> $object){

    echo $name.'
';
}

About your question:

$root.$dir_list[$var].$name //this is your directory name

but youre checking if this name is . and ..

$dir_list[$var]

so its never becomes true


You can do the whole thing with a single regexp:

import re

data = """

Fire Danger Ratings

Bureau of Meteorology
forecast issued at: Mon, 4 Nov 2013 05:30 AM

Central: LOW-MODERATE

"""

rgx = re.compile("(forecast issued at: |
Central: )(.*?)
")
results = rgx.findall(data)
print results[0][1]
print results[1][1]

Output:

$ python rss_parse.py
Mon, 4 Nov 2013 05:30 AM
LOW-MODERATE

If this only runs a time or two a day, pre-compiling the regex is not important.

...
results = re.findall("(forecast issued at: |
Central: )(.*?)
", data)
print results[0][1]
print results[1][1]

We can simplify how the result is handled:

...
[when, rating] = [x[1] for x in
                  re.findall("(forecast issued at: |
Central: )(.*?)
",
                             data)]
print("%s\n%s" % (when, rating))


Do you have any constraints?

Is your example wrong? I would expected lloHe
If you are concerned of modifying your method parameters make them final. Copy it to local variables and don't change the variables is kind of useless.
Don't use short variables names (exception: the loop counter)
If you use Integer instead of int, you should handle null
Maybe a simple static utility method would be fine here, except you have some inheritance scenario in mind.
Maybe you should also indicate that you are shifting left for positive numbers
You should take the length of you string for the char.

Assuming your example is wrong, what about:

import java.util.Objects;
import javax.annotation.Nonnull;

public final class Shift
{
    @Nonnull
    public static String left( @Nonnull final String string, final int shift )
    {
        final int length = string.length();
        if( length == 0 ) return "";
        final int offset = ((shift % length) + length) % length; // get a positive offset

        return string.substring( offset, length ) + string.substring( 0, offset );
    }

    public static void main( String... args )
    {
        assertEquals( "loHel", Shift.left( "Hello", -2 ) );
        assertEquals( "oHell", Shift.left( "Hello", -1 ) );
        assertEquals( "Hello", Shift.left( "Hello", 0 ) );
        assertEquals( "elloH", Shift.left( "Hello", 1 ) );
        assertEquals( "lloHe", Shift.left( "Hello", 2 ) );
        assertEquals( "loHel", Shift.left( "Hello", 3 ) );
        assertEquals( "oHell", Shift.left( "Hello", 4 ) );
        assertEquals( "Hello", Shift.left( "Hello", 5 ) );
        assertEquals( "elloH", Shift.left( "Hello", 6 ) );
        assertEquals( "", Shift.left( "", 3 ) );
    }

    private static void assertEquals( String expected, String actual )
    {
        if( !Objects.equals( expected, actual ) ) throw new AssertionError( "Expected: >" + expected + "< was: >" + actual + "<" );
    }
}


Creating an 2D array using pointer/malloc, and then print it out

It seems OK to me as far as it goes. A couple of suggestions though:

read_matrix may be better split up into two functions, one to create it and the other to read the contents from the source, even if the create_matrix function is called from read_matrix - and you need to be aware of the possibility that the allocation may fail.
On the other hand, you may wish to consider just allocating a single block of size rows*cols of memory, and indexing it via y*rows + x rather than allocating several smaller blocks.
For 'neatness', you should consider using calloc( number_of_elements, sizeof (double) ) instead of malloc, just to give a (possibly) sensible initial value.
print_matrix could do with some layout changes, such that each row is on a separate line, and the corresponding cells line up under each other, something like %10.3f (but would depend on the type of data expected).


The standard version of itoa takes a parameter named base (which you have assumed is 10).

You probably don't need a second hidden function; this would do instead:

if (n < 0)
{
    *s++ = '-';
    n = -n;
}
// ... itoa implementation continues here ...

Recursing is clever; you could also probably do it with two loops instead (untested code ahead):

i = 1;
while ((i * 10) <= n)
    i *= 10;
for (; i != 0; i /= 10)
{
    int x = n / i;
    *p++ = (char)(x % 10 + '0');
    n -= (x * i);
}
assert(n == 0);


Stopping Google from tracking Search results

to stop Google from hijacking Search results URLs for tracking purposes when you click them

Wrong, there's a lot of ways websites profile you. One other method is your device fingerprint, the combination of hardware, software and network information that normally gets sent to the server. A server can then compute a hash and link it to you.

No matter how you block the click-jacked search results, if you end up on a page that happens to have some widget that reports back to their server (with the same hardware, software and network info), consider yourself tracked. These "widgets" come in a variety of forms, like ads, like buttons, tweet buttons, follow buttons etc.

As for your code...

node.onmousedown = null

You are only removing the inline/property handler. You're not preventing handlers that are assigned via addEventListener and delegated (handlers assigned to ancestors to listen to a descendant).

function foo(message){
  alert('No stopping ' + message);
}

var link = document.querySelector('a');

// Assigned as a property
link.onmousedown = function(){
  foo('property');
};

// Assigned as listener
link.addEventListener('mousedown', function(){
  foo('handler');
});

// Body property
document.body.onmousedown = function(){
  foo('delegated property');
};

// Delegated handler
document.body.addEventListener('mousedown', function(){
  foo('delegated handler');
});

// Your script only does this:
link.onmousedown = null;
Test

Now there's several steps needed to prevent it.

First, we cannot prevent addEventListener handles since removeEventListener requires the reference of the handle function which we normally don't have access to. The best we could do is to clone the node, which doesn't copy over handlers assigned via addEventListener.

Then we override the inline onmousedown by defining your own function. Then we prevent delegated handlers by calling stopPropagation.

Lastly, we replace the original element with the clone.

function foo(message){
  alert('No stopping ' + message);
}

var link = document.querySelector('a');

// Assigned as a property
link.onmousedown = function(){
  foo('property');
};

// Assigned as listener
link.addEventListener('mousedown', function(){
  foo('handler');
});

// Body property
document.body.onmousedown = function(){
  foo('delegated property');
};

// Delegated handler
document.body.addEventListener('mousedown', function(){
  foo('delegated handler');
});

var clone = link.cloneNode(true);

clone.onmousedown = function(event){
  event.stopPropagation();
}

link.parentNode.replaceChild(clone, link);
Test


You can avoid repeating whole blocks of code by isolating the dynamic components of your function and assign them to an array.  Then as you wish to modify the fields/columns to be checked, you merely need to update the array and not the functional/checking parts.

public function edit_project_master(){
    $no_pro     = 'PRJ-2017-501';
    $check_pro  = $this->MProject->get_det_pro($no_pro); //get data form table

    $checklist=[
        ['input'=>'na_pro','column'=>'NAMA_PROJECT','table'=>'PM_REQUIREMENT_PROJECT'],
        ['input'=>'i_metode','column'=>'JADWAL_PROJECT','table'=>'PM_REQUIREMENT_PROJECT']
    ];

    //checking script
    foreach($check_pro as $res_check_pro){
        foreach($checklist as $listrow){
            $pro = $this->input->post($listrow['input']); //value for edit
            if($pro != $res_check_pro[$listrow['column']]){  //IF VALUE DIFFERENT
                foreach($res_check_pro as $key_pro => $val_pro){
                    if($res_check_pro[$listrow['column']] == $val_pro){
                        $col_name = $key_pro;            //GET COLUMN NAME
                        break;  // I assume you want to break as soon as you find a match
                    }
                }
                $data['ACTIVITY']       = "UPDATE";
                $data['OLD_VALUE']      = $res_check_pro[$listrow['column']];
                $data['NEW_VALUE']      = $pro;
                $data['COL_AFFECTED']   = $col_name;
                $data['TABLE_AFFECTED'] = $listrow['table'];  // I'm not sure how you mean "automatically", this is "dynamically"
                $data['ANNOTATION']     = NULL;
                $data['EXECUTOR']       = $this->session->userdata('nip');
                $data['CHANGED_ON']     = date("Y-m-d H:i:s");
                $data['CHANGED_BY']     = $_SERVER['REMOTE_ADDR'];
                $data['STATUS']         = 1;
                $this->MProject->ins_system_log($data);
            }
        }
    }
}

Also...

I added break; to the innermost foreach() assuming there will only be one match.  This is best practice because it avoids doing pointless iterations.

I made the value for $data['TABLE_AFFECTED'] "dynamic" (modifiable via the $checklist array).  I don't know if this is what you had in mind by "automatic".