Converting an integer to a hexadecimal string representation in Java I have rolled my own Java method for converting ints to the hexadecimal Strings:
import java.util.Arrays;
import java.util.Random;

public class Main {

    /**
     * Converts the input integer into its textual hexadecimal representation.
     *
     * @param a the integer to convert.
     * @return the string representing {@code a} in hexadecimal notation.
     */
    public static String intToHexString(int a) {
        StringBuilder stringBuilder = new StringBuilder(Integer.BYTES * 2);
        boolean inLeadingZeros = true;

        while (a != 0) {
            char digit = toHexChar(a & 0xf);
            a >>>= 4;

            if (inLeadingZeros) {
                if (digit != 0) {
                    inLeadingZeros = false;
                    stringBuilder.append(digit);
                }
            } else {
                stringBuilder.append(digit);
            }
        }

        if (inLeadingZeros) {
            return "0";
        }

        return stringBuilder.reverse().toString();
    }

    // Converts the integer digit to its textual hexadecimal representation:
    private static char toHexChar(int digit) {
        return digit >= 0 && digit < 10 ?
                (char)(digit + '0') :
                (char)(digit - 10 + 'a');
    }

    private static final int ITERATIONS = 10_000_000;
    private static final int WARMUP_ITERATIONS = 10_000_000;

    private static void warmup() {
        System.out.println("Warming up...");
        Random random = new Random();

        for (int i = 0; i < WARMUP_ITERATIONS; i++) {
            int a = random.nextInt();
            intToHexString(a);
            Integer.toHexString(a);
        }

        System.out.println("Warming up done.");
    }

    private static void benchmark() {
        long seed = System.nanoTime();
        Random random = new Random(seed);
        System.out.println("Seed = " + seed);

        int[] inputArray = new int[ITERATIONS];
        String[] outputArray1 = new String[inputArray.length];
        String[] outputArray2 = new String[inputArray.length];

        for (int i = 0; i < inputArray.length; i++) {
            inputArray[i] = random.nextInt();
        }

        // Benchmarking intToHexString:
        long startTime = System.nanoTime();

        for (int i = 0; i < ITERATIONS; i++) {
            outputArray1[i] = intToHexString(inputArray[i]);
        }

        long endTime = System.nanoTime();

        System.out.println(
                "intToHexString in " +
                        ((endTime - startTime) / 1000_000) +
                        " milliseconds.");

        // Benchmarking Integer.toHexString:
        startTime = System.nanoTime();

        for (int i = 0; i < ITERATIONS; i++) {
            outputArray2[i] = Integer.toHexString(inputArray[i]);
        }

        endTime = System.nanoTime();

        System.out.println(
                "Integer.toHexString in " +
                        ((endTime - startTime) / 1000_000) +
                        " milliseconds.");

        System.out.println("Methods agree: " + Arrays.equals(outputArray1,
                                                             outputArray2));
    }

    public static void main(String[] args) {
        warmup();
        benchmark();
    }
}

Sample output

Warming up...
Warming up done.
Seed = 1290249323142300
intToHexString in 1041 milliseconds.
Integer.toHexString in 562 milliseconds.
Methods agree: true

Critique request
Please tell me anything that comes to mind.

inLeadingZeros I find dubious; wrong name probably
0x00_00_03_44 would be output as "344" whereas conventional would be a two-fold "0344" (or even interspaced as "03 44"). The reason that from left-to-right one can create a byte by two chars.
The exceptional case probably can be dealt with in front.
Error if (digit != 0) { should be if (digit != '0') { or something else is meant.
toHexChar still expects an int digit 0..10. So probably a semantic clash.
a as parameter name is unfortunate especially in English; num or n is more clear.

I am uncertain whether your code is correct by just reading it, due to the variable & if.
/**
 * Converts the given integer into its textual hexadecimal representation.
 *
 * @param num the integer to convert.
 * @return the string representing {@code num} in hexadecimal notation.
 */
public static String intToHexString(int num ) {
    if (num == 0) {
        return "00";
    }

    StringBuilder stringBuilder = new StringBuilder(Integer.BYTES * 2);
    while (num != 0) {
        char digit = toHexChar(num & 0xf);
        num >>>= 4;
        stringBuilder.append(digit);

        digit = toHexChar(num & 0xf);
        num >>>= 4;
        stringBuilder.append(digit);
    }
    return stringBuilder.reverse().toString();
}

// Converts the integer digit to its textual hexadecimal representation:
private static char toHexChar(int digit) {
    return 0 <= digit && digit < 10 ?
            (char)(digit + '0') :
            (char)(digit - 10 + 'a');
}


"Finding number of factors" efficiency I have two functions to find the number of factors of a given number.
I was wondering which one will be more efficient to use?

def nu_of_factors2(n):
    return len(set(reduce(list.__add__,
            ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0))))

def nu_of_factors1(n):
    result_set = set()
    sqrtn = int(n**0.5)
    for i in range(1,sqrtn+1):
        q, r = n/i, n%i
            if r == 0:
            result_set.add(q)
            result_set.add(i)
    return len(result_set)

Both algorithms appear to be O(sqrt(n)), so there isn't anything to choose between them in terms of algorithmic complexity. The only significant difference I see is between a one-off conversion from list to set and a series of calls to add(). I would guess that the former will be quicker (i.e. your first implementation will be quicker), but this is definitely in the realm of things you should benchmark rather than attempting to guess. It depends on the particular implementation of the data structure in Python, and it may even depend on factors like the order in which you insert the elements (though I believe Python implements sets using a hash table rather than a binary tree, which should mean order of insertion doesn't matter).

A bigger question is whether you should be using a set at all. Your algorithm doesn't require a set to ensure uniqueness of factors. When you return the collection from the function the code that uses it might convert it straight to a list, in which case you've wastefully converted it to a set and back again. If you do the minimum of conversions necessary to get a result, then you avoid overhead and the caller can always convert it to a set if they need that.

On the other hand, returning a set clarifies the API by imposing two additional requirements on the returned value: it is a collection for which ordering is unimportant, and it has only unique elements. The second of these is certainly appropriate here. There is a natural ordering of the factors (namely numerical ordering), but it would take extra effort to arrange the results in this order. It might be cleaner to return a set (for which the caller can't rely on any ordering) than an order that exposes the internal implementation to the caller.

Speaking of ordering, the naive way to return a sorted list of factors would be to sort the list at the end, which is of course O(n*log(n)). A better way might be to invert the order in which you process the range and use a deque as the output collection. Then each time you discover a factor pair you can put the large factor on one end and the small factor on the other, returning a sorted list with O(1) insertion overhead.

Returning to your original question: I assume this is code you're writing as an exercise rather than as production code? The right thing to do depends a lot on where the code is to be used, and you don't give any context. If you're trying to build your skills at optimisation then by all means micro-optimise and return the collection in a list to save set overhead. If you're writing high-performance library code then maybe you need to pay more attention to the API. If this is for a production system where it's not time-critical, you should stop trying to optimise for speed and go for whichever solution will be easiest to maintain, which is probably the one that's easiest to read.


Variable cleaning class I've created a class that's used for cleaning variables for use. You set a name, value and options and it will set the value if it matches the criteria/options.

It is used like this:

$var = new Variable();
$var->clean('username', $_POST['username'], '3,13,alphanumeric,True');
echo 'Username', $var->clean("username");
echo 'Username', $var->html("username");

It seems very messy and as though it could be done in a better way.

<?php
include_once __DIR__ . '/header.php';

class Variable
{
    var $clean = array(); // Filtered data
    var $html = array(); // Escaped htmlentities() data

    /**
     * variable->addClean()
     *
     * @param mixed $name - Name of clean value
     * @param mixed $value - Value to clean
     * @param string $options - Options in the format specified
     * @return mixed - Clean value.
     *
     * Options format:
     *    {min length} - set to -1 to ignore.
     *    {max length} - set to -1 to ignore.
     *    {type} - set to null to ignore. Types:
     *       - Numeric.
     *       - AlphaNumeric.
     *       - Alpha.
     *    {trim} - default is true.
     *
     *    eg.
     *    $var = new Variable();
     *    $var->clean('username', $_POST['username'], '3,13,alphanumeric,True');
     *    echo 'Username', $var->clean("username");
     *
     */
    public function clean($name, $value = null, $options = '')
    {
        if ($value === null && $name !== null)
            return isset($this->clean[$name]) ? $this->clean[$name] : null;

        else if ($value !== null && $name !== null) {
            if (!empty($options)) {
                list($minlen, $maxlen, $type, $trim) = array_pad(explode(',', (string)$options), 4, '');

                if (strtolower($trim) !== 'false')
                    $value = trim($value);

                if ($minlen !== '-1')
                    if (!(strlen($value) > $minlen))
                        return false;

                if ($maxlen !== '-1')
                    if (!(strlen($value) < $maxlen))
                        return false;

                switch (strtolower($type)) {
                    case 'numeric':
                        if (is_numeric($value))
                            $this->clean[$name] = intval($value);
                        break;
                    case 'alphanumeric':
                        if (ctype_alnum($value))
                            $this->clean[$name] = $value;
                        break;
                    case 'alpha':
                        if (ctype_alpha($value))
                            $this->clean[$name] = $value;
                        break;
                    default:
                        $this->clean[$name] = $value;
                        break;
                }
            } else
                $this->clean[$name] = $value;
        }
        return isset($this->clean[$name]);
    }

    public function isClean($name)
    {
        return isset($this->clean[$name]);
    }

    public function html($name)
    {
        if (!isset($this->html[$name]) && isset($this->clean[$name]))
            $this->html[$name] = htmlentities($this->clean[$name], ENT_QUOTES, 'UTF-8');

        return (isset($this->html[$name]) ? $this->html[$name] : null);
    }
}

Yes, your class does too much.

First of all, it actually lying: It does not handle one variable as the name of the class suggest, but it does handle multiple variables at once.

Second, I do not like the overloading of the clean method. It is used both for getting a value inside, and for getting the same value back outside. Why are there not two methods?

Third point: Your clean method does too much! It should not be its responsibility to actually decide which filter to apply - this should be the task of a dedicated class that just deals with on single aspect.

Summarizing all this, your list of improvements would be like this:

a) Get rid of the multi-value-behaviour. One class instance per value. If you really need multiple values inside a structure, use a different class.

b) Move the actual filtering out of the class, into dedicated filter elements that do one task very good, but nothing else.

For example, create an "Alphanumeric" class that is configured with the rest of the parameters "3,13,true" that does exactly deal with strings, checks their min and max length and optionally trims them.

Create another class that deals with numeric representation. I doubt it would be useful to check for a string length in this case, but your implementation dictates that it has to be like this. On the other hand, there is no way to implement a min or max value.

The checking class should be passed as a parameter to the constructor of your class Variable, which means that you have to create the checking class beforehand.

c) Passing a string as configuration would then be somehow obsolete, because your new checking classes do not have any other parameters, so giving them four separate parameters isn't likely to overflow the parameter list. But remember that you do not need to make every class' parameter list the same - if some class does not need a configuration value, you can omit it. If another class needs more: Add one.

d) In the end you might come to a point where creating more than one instance of Variable is cumbersome because of all the additional stuff. This is where a factory comes in handy. It would take a configuration array that defines which instances of variable cleaners are needed, instantiates all necessary classes and would probably return an array of Variable objects.

e) One final suggestion: When implementing different classes for basically the same task, use an interface as a type hint to guarantee that you never mix something up. When using an IDE you get code completion as a bonus. :)


Create several homogeneous arrays from a larger heterogenous array efficiently I have a list of aircraft returned from a REST call which describes the status of each aircraft. In order to make the UI templating simpler, this single list is split into four homogeneous lists in order to group by status.

My primary concern is that we iterate over the primary array \$s\$ times which, while still in polynomial \$O(n \times s)\$ time, feels needlessly inefficient.

Perhaps there is a way to more efficiently split this array in a single pass?

Here is a representative code sample:

let aircraft = [
    {
        tail: "9736968",
        status: "DRAFT"
    },
    {
        tail: "5114419",
        status: "SERVICEABLE"
    },
    {
        tail: "8395671",
        status: "OUTOFSERVICE"
    },
    {
        tail: "332273",
        status: "SERVICEABLE"
    },
    {
        tail: "6123961",
        status: "UNSERVICEABLE"
    },
]

let serviceable = [];
let unserviceable = [];
let outOfService = [];
let draft = [];

function splitLists(aircraftStatusList) {
    serviceable = aircraftStatusList
                    .filter(aircraft => aircraft.status === 'SERVICEABLE');

    unserviceable = aircraftStatusList
                    .filter(aircraft => aircraft.status === 'UNSERVICEABLE');

    outOfService = aircraftStatusList
                    .filter(aircraft => aircraft.status === 'OUTOFSERVICE');

    draft = aircraftStatusList
                    .filter(aircraft => aircraft.status === 'DRAFT');
}

splitLists(aircraft);

Ideally, you would want a groupBy function, such as the _.groupBy() function offered by lodash.  If you don't want to load a library, it's not too hard to reimplement groupBy.

This solution also has the advantage of returning the result as one associative array rather than mutating four global variables as a side-effect.

let aircraft = [
    {
        tail: "9736968",
        status: "DRAFT"
    },
    {
        tail: "5114419",
        status: "SERVICEABLE"
    },
    {
        tail: "8395671",
        status: "OUTOFSERVICE"
    },
    {
        tail: "332273",
        status: "SERVICEABLE"
    },
    {
        tail: "6123961",
        status: "UNSERVICEABLE"
    },
];

// http://stackoverflow.com/a/34890276
function groupBy(collection, attr) {
    return collection.reduce(function(result, item) {
        (result[item[attr]] = result[item[attr]] || []).push(item);
        return result;
    }, {});
}

let aircraftByStatus = groupBy(aircraft, 'status');
console.log(aircraftByStatus);


Codeigniter - in the view or in the controller? Is this correct? Or am I overloading the responsibilities of the view?

            Estado
                Prioridad
                Responsable
                Categoría
                Solicitud
                Creado
                Cerrado

            <?php
                 $class = '';
                 $label = '';
                 foreach ($solicitud as $key => $value) {
                     if( $value['priority'] > 0 && $value['priority'] < 4 ) $class = 'badge-important';
                     if( $value['priority'] > 4 && $value['priority'] < 7 ) $class = 'badge-info';
                     if( $value['priority'] > 7 ) $class = 'badge-warning';

                     if( $value['id'] == 1 ) $label = 'label-info';
                     if( $value['id'] == 2 ) $label = 'label-success';
                     if( $value['id'] == 3 ) $label = 'label-danger';

                    echo '
';
                    echo '  '.ucfirst($value['status']).'	';
                    echo '   '.$value['priority'].'	';
                    echo '   '.$value['sname'].' '.$value['last_name'].'	';
                    echo '   '.$value['name'].'	';
                    echo '   '.$value['message'].'	';
                    echo '   '.$value['created'].'	';
                    echo ''.(( $value['closed'] )  ? $value['closed'] : 'pendiente').'	';
                    echo '
';

                 } ?>

These 0, 4 and 7 means nothing to any code reader, nor 1, 2 and 3 for the label.

Move this logic in the controller and consider using ENUMs in your controller class i.e.:

const BADGE_IMPORTANT = 0;
const BADGE_INFO = 4;
const BADGE_WARNING = 7;

This way it will be more readable for the one who will read and change it later, also it will became less hard changable and more reusable.

Also, try to not echo HTML, I mean, use PHP blocks only when you have PHP in it. HTML should be outside:

<?php foreach ($solicitud as $key => $value): ?>

              <span class="label label-sm<?=$label;?>"><?=ucfirst($value['status']);?>
              <span class="badge <?=$class;?>"><?=$value['priority'];?>
              <?=$value['sname'].$value['last_name'];?>
              <?=$value['name'];?>
               ....

<?php endforeach; ?>


Function declarations using macros to support multiple platforms I wrote a C++ plugin that retrieves screen pixel. It works on Windows and Android. I noticed that dllexport is only required on Windows but not on Android and causes error on other platform other than Windows. I fixed that by using #if macro to make it use dllexport only on Windows.

Here is the fixed header code:

#ifndef ANDROIDSCREENSHOT_NATIVE_LIB_H
#define ANDROIDSCREENSHOT_NATIVE_LIB_H

#define DLLExport __declspec(dllexport)

extern "C"
{
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(_WIN64) || defined(WINAPI_FAMILY)
DLLExport void initScreenPointPixel(void* buffer, int x, int y, int width, int height);
DLLExport void updateScreenPointPixelBufferPointer(void* buffer);
DLLExport void updateScreenPointPixelCoordinate(int x, int y);
DLLExport void updateScreenPointPixelSize(int width, int height);
int GetScreenPixels(void* buffer, int x, int y, int width, int height);

#else
void initScreenPointPixel(void *buffer, int x, int y, int width, int height);
void updateScreenPointPixelBufferPointer(void *buffer);
void updateScreenPointPixelCoordinate(int x, int y);
void updateScreenPointPixelSize(int width, int height);
int GetScreenPixels(void *buffer, int x, int y, int width, int height);
#endif
}
#endif //ANDROIDSCREENSHOT_NATIVE_LIB_H

It works and fixes the problem but I don't like the fact that I have to declare each of these functions twice. Once in the #if and another in the #else statement. I have many functions if not thousands and if I go this route, the code would be unnecessary long. The simple goal is to remove dllexport on non Windows platform without declaring the function twice like I am currently doing.

Is there a better way to do this with macro without having to declare each function again? Any solution without macros is also good as long as I don't have to declare each function multiple times.

Keep the DLLExport macro on all platforms, but make the definition resolve to nothing unless you're on Windows. You might also want to rename the macro to something more neutral. Something like this:

#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(_WIN64) || defined(WINAPI_FAMILY)
# define EXPORT __declspec(dllexport)
#else
# define EXPORT
#endif

extern "C"
{
EXPORT void initScreenPointPixel(void* buffer, int x, int y, int width, int height);
}

You should also be aware of that the extern "C" stuff is only recognized by a C++ compiler. The related statements should also be conditional, e.g.:

#ifdef __cplusplus
extern "C" {
#endif

... declarations here

#ifdef __cplusplus
}
#endif


Generic dynamic array Here is the interface of my generic dynamic array;

/* dynamic array interface */

#ifndef DA_HEADER
#define DA_HEADER

#include <stdlib.h> /* size_t */

/* creates a new dynamic array, with each element of "size" bytes */
void *danew(size_t unitsize);

/* returns pointer to element after the last element */
void *daend(void *arr);

/* appends new element after last element
   return pointer to array head
*/
void *daappend(void *arr, const void *elem);

/*
    removes the last element and returns a pointer to it or null if empty
*/
void *dapop(void *arr);

/*
  frees the array
*/
void dafree(void *arr);

#endif /* DA_HEADER */

and this is the implementation of my generic dynamic array:

/* dynamic array implementation */

#include <string.h> /* memcpy */
#include <stdlib.h> /* free */
#include "xalloc.h" /* xmalloc, xrealloc */

struct dynamic_array {
        size_t cap;
        size_t len;
        size_t unitsize;
        char data[1];
};

#define DATAOFFSET ((unsigned long)(((struct dynamic_array*)0)->data))
#define DA_STRUCT(DATAPTR) (struct dynamic_array *)((char *)DATAPTR-DATAOFFSET)

void *danew(size_t unitsize)
{
        /* -1 because we already have one byte in struct */
        struct dynamic_array *da = xmalloc(sizeof(struct dynamic_array) +
                                          unitsize - 1);

        da->cap = 1;
        da->len = 0;
        da->unitsize = unitsize;

        return &(da->data);
}

static __inline struct dynamic_array *__dagrow(struct dynamic_array *da,
                                                            size_t size)
{
        while(size > da->cap)
                da->cap = 2*da->cap;

        /* -1 because we already have one byte in sizeof(struct) */
        return xrealloc(da, sizeof(struct dynamic_array) + da->unitsize*da->cap
                                                         - 1);
}

void *daappend(void *arr, const void *elem)
{
        struct dynamic_array *da = DA_STRUCT(arr);
        da = __dagrow(da, da->len + 1);
        memcpy(&da->data[da->unitsize * da->len++], elem, da->unitsize);
        return &da->data;
}

void *dapop(void *arr)
{
        struct dynamic_array *da = DA_STRUCT(arr);
        if(!da->len)
                return NULL;

        return &da->data[da->unitsize * --da->len];
}

void *daend(void *arr)
{
        struct dynamic_array *da = DA_STRUCT(arr);
        return &da->data[da->unitsize * da->len];
}

void dafree(void *arr)
{
        struct dynamic_array *da = DA_STRUCT(arr);
        free(da);
}

And this is the example usage:

#include <stdio.h>

#include "dynamic_array.h"

struct foo {
        int number;
        char *text;
};

int main()
{
        struct foo *myfoos = danew(sizeof(struct foo));
        struct foo *tmp_ptr;
        struct foo tmp;
        int i;
        int numbers[] = {1,2,3,4,5};
        char *texts[] = {"ali", "veli","osman","zekiye","mahmut"};

        for (i=0; i < 5; i++) {
                tmp.number = numbers[i];
                tmp.text   = texts[i];
                myfoos = daappend(myfoos, &tmp);
        }

        /* Random access */
        printf("3rd element is number: %d, text: %s", myfoos[2].number,
                                                      myfoos[2].text);

        printf("Accessing sequentially\n");
        /* Sequential access */
        for (tmp_ptr = myfoos; tmp_ptr != daend(myfoos); tmp_ptr++) {
                printf("current element: number: %d, text: %s\n", tmp_ptr->number,
                                                                tmp_ptr->text);
        }

        printf("Accessing LIFO\n");
        /* LIFO access */
        while((tmp_ptr = dapop(myfoos)))
                printf("current element number: %d, text: %s\n", tmp_ptr->number,
                                                               tmp_ptr->text);

        return 0;
}

naming da* + all lower case makes it hard to parse the difference between the prefix and the name of the function, instead either pick da_snake_case or daCamelCase.
returning void* is not ideal instead create a opaque (incomplete) struct and just let the use pass pointers to that struct around:

struct DynamicArray;

DynamicArray* danew(size_t unitsize);


Greatest prime number smaller than N where N can be as large as 10^18 This is code for finding largest prime number smaller than \$N\$, where \$N\$ can be as large as \$10^{18}\$.  But, it takes 1 minute for \$10^{18}\$. I need to pass it in 2-3 sec.

What changes should I make to pass it?  My compiler used is g++ 4.3.2

The program here runs for multiple test cases.

#include <iostream>
#include <cmath>

#define c2 341550071728321
#define c1 4759123141

using namespace std;

unsigned long long int mul(unsigned long long int a, unsigned long long int b, unsigned      long long int mod)
{
    int i;
    unsigned long long int now = 0;
    for (i = 63; i >= 0; i--) if (((a >> i) & 1) == 1) break;
    for (; i >= 0; i--)
    {
        now <<= 1;
        while (now > mod) now -= mod;
        if (((a >> i) & 1) == 1) now += b;
        while (now > mod) now -= mod;
    }
    return now;
}

unsigned long long int pow(unsigned long long int a, unsigned long long int p, unsigned long long int mod)
{
    if (p == 0) return 1;
    if (p % 2 == 0) return pow(mul(a, a, mod), p / 2, mod);
    return mul(pow(a, p - 1, mod), a, mod);
}

bool MillerRabin(unsigned long long int n)
{
    int l;
     unsigned long long int ar[9] = { 2, 3, 5, 7, 11, 13, 17, 19, 23};
    if (n < c1) {

            l = 3;
    }
    else if (n < c2) {
            l = 7;
    }
    else {

            l = 9;
    }
    //l = 9;
    unsigned long long d = n - 1;
    int s = 0;
    while ((d & 1) == 0) { d >>= 1; s++; }
    int i, j;
    for (i = 0; i < l; i++)
    {
        unsigned long long int a  = min(n - 2, ar[i]);
        unsigned long long int now = pow(a, d, n);
        if (now == 1) continue;
        if (now == n - 1) continue;
        for (j = 1; j < s; j++)
        {
            now = mul(now, now, n);
            if (now == n - 1) break;
        }
        if (j == s) return false;
    }
    return true;
}

bool check_prime(unsigned long long int n) {

if(!MillerRabin(n)) return false;
return true;
if(n == 2) return true;
if(n % 2 == 0) return false;
for(unsigned long long int i = 3; i <= sqrt(n); i+=2) {
    if(n % i == 0) return false;
}
return true;
}

int main()
{
int t;

cin >> t;

while(t--) {
    unsigned long long int n;
    cin >> n;
    while(1) {
        if(check_prime(n)) {
            cout << n << endl;
            break;
        }
        else {
            n--;
        }
    }
}

}

These macros are not needed in C++:

#define c2 341550071728321
#define c1 4759123141

They should be constants, using the const keyword (or constexpr in C++11):

const int c2 = 341550071728321;
const int c1 = 4759123141;

I've only kept the names the same here because I have no idea what they mean.  Try to avoid using single-char variable names, unless their meaning is already obvious.
You use unsigned long long in many places, which could look verbose.  You could use a typedef so that you can use another (shorter) name in place of them:

typedef unsigned long long ull;

Better yet, you can use std::uint64_t from <cstdint>.  It is shorter, and it should be guaranteed to hold 64 bits on any system.
This is quite a bit of whitespace:

if (n < c1) {

            l = 3;
    }
    else if (n < c2) {
            l = 7;
    }
    else {

            l = 9;
    }

You already use four spaces for indentation, so it should be consistent:

if (n < c1) {
    l = 3;
}
else if (n < c2) {
    l = 7;
}
else {
    l = 9;
}

You're also lacking indentation within main() and check_prime(), but it's okay in your other functions.  I don't see the reason for all this inconsistency if you're not in a hurry to write the code itself.  Make it clean now so that fine-tuning will be easier, both for you and for others.


How can I ensure some structure for classes for a plug-in system written in Python? I have written a toolkit (hwrt) which has a plugin system. One type of plugin is a feature (see this) for many of them.

There are some restrictions of feature classes. I expect some structure amongst them:

# Every feature class must have a __str__, __repr__ function so that error
# messages can help you to find and fix bugs in features.
# Every feature class must have a __call__ function which is used to get the
# features value(s) for a given recording.
# Every feature class must have a get_dimension function so that the total
# number of features can be calculated and checked for consistency.
#
# * __call__ must take exactly one argument of type HandwrittenData
# * __call__ must return a list of length get_dimension()
# * get_dimension must return a positive number
# * have a 'normalize' attribute that is either True or False

I have a lot of lines starting with

def __call__(self, handwritten_data):
    assert isinstance(handwritten_data, HandwrittenData.HandwrittenData), \
        "handwritten data is not of type HandwrittenData, but of %r" % \
        type(handwritten_data)

which I would like to write in a shorter notation.

Currently, my classes all inherit from object. I thought about changing that to letting them inherit from a Feature class, but I'm not too sure how I should write it. This was one try:

import abc

class Feature:
    __metaclass__ = abc.ABCMeta

    @abc.abstractmethod
    def __call__(self):
        pass

    @abc.abstractmethod
    def get_dimension(self):
        pass

I expected that if I let a class which did not implement get_dimension inherit from Feature that I would get an assertion error as soon as the class is used, but nothing happened.

How can I rewrite the code to have less repetitions and to check for more mistakes programmatically instead of just giving this long comment and hoping that the user implements everything?

You did not mention which Python version you are targeting. If the ABCMeta metaclass does not seem to be working you are probably on Python 3 where you must apply a metaclass in this manner:

class Feature(metaclass=abc.ABCMeta):

To answer your main question, one possible approach is this: let the base class check the arguments, and call a different, abstract method to do the work. Subclasses will then override the abstract method only.

class Feature(object):
    __metaclass__ = abc.ABCMeta

    def __call__(self, handwritten_data):
        assert isinstance(handwritten_data, HandwrittenData.HandwrittenData), \
            "handwritten data is not of type HandwrittenData, but of %r" % \
            type(handwritten_data)
        return self._call(handwritten_data)

    @abc.abstractmethod
    def _call(self, handwritten_data):
        pass


Return the repeated number and the missing number Input:

Array of n integers, containing numbers in the range [1,n].

Each integer appears once except A which repeats twice and B which is missing.

Output:

Return A and B.

Example:

Input:[3 1 2 5 3]

Output:[3, 4]

A = 3, B = 4

My approach:

public class Solution {
// DO NOT MODIFY THE LIST. IT IS READ ONLY
public ArrayList<Integer> repeatedNumber(final List<Integer> A) {

   //O(n) solution
   //Store the count of all the numbers appearing in the list
   int [] count = new int[A.size()];

   int rep_num = 0,miss = 0;

   //Increase the count at the index location
   for( int i = 0; i < A.size(); i++ )
    {
        int ind = A.get(i);
        count[ind - 1]++;

        //
        if(count[ind - 1] == 2)
            {
                rep_num = ind;
                break;
            }
    }

    //If the count has not been updated, then the number is missing in the array
    for(int i = 0; i < count.length; i++ )
        {
            if(count[i] == 0)
                miss = i+1;

        }

    ArrayList<Integer> num = new ArrayList<Integer>();
    num.add(rep_num);
    num.add(miss);

    return num;

}
}

I have the following questions:

How can I further optimize my code?
Is there any better way to solve this question (i.e. using a better data structure, lesser lines of code)?

Question asked on: interviewbit.com

There is a shortcut you can take to find the missing number after you've found the duplicated number.  You may have come across this fact before, where the sum of the numbers 1 to n is n*(n+1)/2.  We can leverage this along with the duplicated number to find the missing number.  If you add up every number in your list and subtract that from what the expected sum would be from 1 to n, most of the terms will cancel, leaving you with missing - duplicate.  You can visualize that with an example:

 (1+2+3+4+5+6+7)
-(1+2+3+4+5+1+7)
=(6)-(1)

In that example, n is 7, the duplicated number is 1, and the missing number is 6.  So you get the formula expected_sum - actual_sum = missing - duplicate.  We can solve for missing by adding duplicate to both sides, leaving us with missing = expected_sum - actual_sum + duplicate!  Let's do that.

First, you can calculate the expected sum from that formula, n*(n+1)/2.  In your loop searching for the duplicate, you will need to keep a running total (and don't break early).  After you find the sum of your list and identify the duplicate number, you can calculate the missing number using the formula we talked about in the above example, missing = expected_sum - actual_sum + duplicate.

Also, you don't need to record the frequency as an integer, you can just keep a list of booleans for numbers already seen.  I've also taken the liberty of cleaning up the indentation issues and renaming some of the variables for the purpose of readability.  Here is the solution:

public class Solution {
    // DO NOT MODIFY THE LIST. IT IS READ ONLY
    public ArrayList<Integer> repeatedNumber(final List<Integer> A) {
        //O(n) solution
        //Keep a record of all the numbers appearing in the list
        boolean [] seen = new boolean[A.size()];

        int rep_num = 0, miss_num = 0;
        int expected_sum = A.size() * (A.size() + 1) / 2;
        int actual_sum = 0;

        //Find sum of list and identify duplicate number
        for( int i = 0; i < A.size(); i++ )
        {
            int num = A.get(i);
            if(seen[num - 1])
                rep_num = num;

            seen[num - 1] = true;
            actual_sum += num;
        }

        miss_num = expected_sum - actual_sum + rep_num;

        ArrayList<Integer> results = new ArrayList<Integer>();
        results.add(rep_num);
        results.add(miss_num);

        return results;
    }
}


Responsive video embedding I figured out a alternative way to make embedded videos responsive and I like to have some feedback on it.

Would this be considered a hack or just bad coding to add a extra piece of html to make this work?

.video-wrapper {
  position: relative;
}
.make-video-responsive-img {
  width: 100%;
  height: auto;
  display: block;
}
.video-wrapper iframe,
.video-wrapper object,
.video-wrapper embed,
.video-wrapper video {
  width: 100%;
  height: 100%;
  position: absolute;
  display: block;
  top:0;
  z-index:1;
}

Vimeo Responsive with base64 img

 <img class="make-video-responsive-img" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIYAAABLCAYAAAC1D//7AAAABGdBTUEAALGPC/xhBQAAAU1JREFUeAHt0rENwDAMBDHF+++cpHAj4EagARf68sBnZt7/ewqsAmddDgVuATBQyAJgZBYjGAxkATAyixEMBrIAGJnFCAYDWQCMzGIEg4EsAEZmMYLBQBYAI7MYwWAgC4CRWYxgMJAFwMgsRjAYyAJgZBYjGAxkATAyixEMBrIAGJnFCAYDWQCMzGIEg4EsAEZmMYLBQBYAI7MYwWAgC4CRWYxgMJAFwMgsRjAYyAJgZBYjGAxkATAyixEMBrIAGJnFCAYDWQCMzGIEg4EsAEZmMYLBQBYAI7MYwWAgC4CRWYxgMJAFwMgsRjAYyAJgZBYjGAxkATAyixEMBrIAGJnFCAYDWQCMzGIEg4EsAEZmMYLBQBYAI7MYwWAgC4CRWYxgMJAFwMgsRjAYyAJgZBYjGAxkATAyixEMBrIAGJnFCAYDWQCMzGIEg4Es8AFyOgGVosq9uwAAAABJRU5ErkJggg==">

There is no need to use an image to give the wrapper the neccesary height to contain the responsive video. I loaded the image in my browser and found that its dimensions are 75*134, using this we can set the height of the wrapper with a little trick.

HTML code:

CSS code:

.video-wrapper {
  position: relative;
}
.video-wrapper::after
{
  content : ' ';
  display : block;
  padding-top: 55%; /* 100*75/134 % proportional to the width of the parent */
}
.video-wrapper iframe,
.video-wrapper object,
.video-wrapper embed,
.video-wrapper video {
  width: 100%;
  height: 100%;
  position: absolute;
  display: block;
  top:0;
  z-index:1; /* there is no need of this z-index property */
}

If you need more information about this "trick", refer to this post: https://stackoverflow.com/questions/22673008/css-make-div-width-proportional-to-height

If you know the correct proportion, you'll be able to make it responsive.

And no, there is no problem, it's your layout ;)

Regards.


Binary heap (priority queue) implementation in JavaScript I wrote this heap implementation because I need it to run Dijkstra's algorithm to find paths in a game (for which reason I'd like this implementation not to be unreasonably slow...)

Sadly I don't know JavaScript well, much worse than C or C++ for sure, so I might've made some silly mistakes, I'd love You to point them out for me :)

For example, I'm unsure if keeping heap nodes in an array is an OK approach here; sadly I can't find the relevant SO post now, but I remember reading on SO that using arrays as memory pools results in a gross performance degradation in JavaScript. Keeping nodes in an array is pretty convinient for implementing a heap, but should I have refrained from this anyway?

Also I am aware that people usually tell me my coding style is horrible and unreadable, so I suppose I'm going to get similar comments here, how exactly did I fail this time?

The code seems correct though, it passes this test: https://paste.ee/p/edrYt which was generated with this C++ code: https://ideone.com/zpCtIz

Ah and I tried to stick to JSv5, I tried to refreain from using ES6 features. I hope none slipped through.

var GZKM = GZKM || {}

;(function() {

GZKM.Heap = function() {
    this.arr = []
}

GZKM.Heap.prototype._parentIndex = function(i) {
    return Math.floor((i+1)/2)-1
}

GZKM.Heap.prototype._leftChildIndex = function(i) {
    return 2*(i+1)-1
}

GZKM.Heap.prototype._rightChildIndex = function(i) {
    return 2*(i+1)
}

GZKM.Heap.prototype._swapNodes = function(node1, node2) {
    // Idea taken from this SO answer: https://stackoverflow.com/a/22053474/4385532
    // Doing it this way b/c this SO answer scared me that the standard way may lead to a memory leak: https://stackoverflow.com/a/872433/4385532
    this.arr[node1._i] = [this.arr[node2._i], this.arr[node2._i]=this.arr[node1._i]][0]
    node1._i = [node2._i, node2._i=node1._i][0]
}

GZKM.Heap.prototype._moveUp = function(node) {
    var canMove = function() {
        return node._i > 0
    }
    var mustMove = function() {
        return this.arr[this._parentIndex(node._i)].priority > node.priority
    }.bind(this)
    while(canMove() && mustMove())
        this._swapNodes(node, this.arr[this._parentIndex(node._i)])
}

GZKM.Heap.prototype._moveDown = function(node) {
    var canMove = function() {
        return this._leftChildIndex(node._i) < this.arr.length
    }.bind(this)
    var nextNode = function() {
        if(this._rightChildIndex(node._i) >= this.arr.length ||
                this.arr[this._rightChildIndex(node._i)].priority > this.arr[this._leftChildIndex(node._i)].priority)
            return this.arr[this._leftChildIndex(node._i)]
        else return this.arr[this._rightChildIndex(node._i)]
    }.bind(this)
    var mustMove = function() {
        return nextNode().priority < node.priority
    }
    while(canMove() && mustMove())
        this._swapNodes(node, nextNode())
}

GZKM.Heap.prototype.push = function(priority, elt) {
    var eltIndex = this.arr.length;
    this.arr.push({elt: elt, priority: priority, _i: eltIndex})
    var ret = this.arr[eltIndex]
    this._moveUp(this.arr[eltIndex])
    return ret
}

GZKM.Heap.prototype.pop = function() {
    if(!this.arr.length) return undefined
    this._swapNodes(this.arr[0], this.arr[this.arr.length-1])
    var ret = this.arr.pop()
    this._moveDown(this.arr[0])
    return ret
}

GZKM.Heap.prototype.reprioritize = function(node, newPriority) {
    node.priority = newPriority
    this._moveUp(node)
    this._moveDown(node)
}

})()

Big f...reakin' bug:

GZKM.Heap.prototype.pop = function() {
    if(!this.arr.length) return undefined
    this._swapNodes(this.arr[0], this.arr[this.arr.length-1])
    var ret = this.arr.pop()
    this._moveDown(this.arr[0])
    return ret
}

After this.arr.pop() the array may very well be empty, and _moveDown is not prepared to being called with undefined, so we will get an exception here. I really thought the tests would cover this...well, they didn't.

Fixing this seems simple though:

if(this.arr.length)
    this._moveDown(this.arr[0])


Java class for simple statistics calculations I've written a class for a project of mine whose responsibility is to perform basic statistic calculations like mean, median and mode. The aim is for it to be a helper class, so it should not be instantiable. I later want to extend it to include weighted mean and range/interquartile range as well as variance.

Here is the code:

import java.util.Arrays;
import java.util.HashMap;

public class BasicStatistics {

    //Prevent instantiation...
    //throws UnsupportedOperationException to defend against reflection
    private BasicStatistics() throws UnsupportedOperationException{
        throw new UnsupportedOperationException();
    }

    public static class Mode {

        private static int mode;
        private static HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();

        private Mode() throws UnsupportedOperationException{
             throw new UnsupportedOperationException();
        }

        public static int calculateMode(int ints[]){
            int max = 0;
            int temp = 0;

            for (int i = 0; i < ints.length; i++){
                if (hm.get(ints[i]) != null){
                    int count = hm.get(ints[i]);
                    count += 1;
                    hm.put(ints[i], count);
                    if (count > max){
                        max = count;
                        temp = ints[i];
                    }
                } else {
                     hm.put(ints[i], 1);
                }
            }

            if (temp == 0){
                mode = ints[0];
            } else {
                mode = temp;
            }

            return mode;
        }

    }

    public static class Mean {

        private static float mean;

        private Mean() throws UnsupportedOperationException{
            throw new UnsupportedOperationException();
        }

        public static float calculateMean(int ints[]){

            for (int element  : ints){
                mean += element;
            }

            return mean / ints.length;
        }

    }

    public static class Median {

        private static float median;

        private Median() throws UnsupportedOperationException{
            throw new UnsupportedOperationException();
        }

        public static float calculateMedian(int ints[]){

            Arrays.sort(ints);

            if (ints.length % 2 == 0){
                median = (float) (ints[ints.length / 2] + ints[(ints.length / 2) - 1]);
                median /= 2;
            } else {
                median = (float) ints[ints.length / 2];
            }

            return median;
        }
    }
}

Don't overdo Single Responsibility Principle

You have four classes, three of which calculate the mean, median, and mode respectively.  The thing is though that their responsibility doesn't match their names.  They have responsibility over the data, which they then express as the statistics.  But if all the Mode is responsible for is the mode, then it shouldn't know about the data.  All it should know about is the Mode itself.

Consider instead making one class with multiple methods.  Then the class can have the data as a member.

Don't overuse static

        private static int mode;
        private static HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();

This means that every single instance of this class has the same mode and hm.

        private int mode;
        private Map<Integer, Integer> counts = new HashMap<>();

I also changed HashMap to Map on the left.  Usually you make types the interface rather than the implementation.  That ensures that you can change the implementation easily later if desired.

I changed hm to counts as being more descriptive.

The <> notation will only work in newer versions of Java but saves typing when available.

If you need access to fields, then you should instantiate the class and access the fields through normal methods.  E.g.

        StatisticsCalculator statCalc = new StatisticsCalculator(data);
        statCalc.calculate();
        Set<Integer> modes = getModes();

Now you can create a second object with different data without losing the first.  Or worse, merging with it.

The presumption here is that calculate would calculate all the stats and you could just access them afterwards.  If you always use them together, this is more efficient.  You could also calculate them on a just-in-time basis.

The Map is unnecessary

First, you don't need to make the Map a class field.  It would be fine as a local variable.

Second, since you sort the data to get the median anyway, you might as well use the sorted data to get the mode as well.  With sorted data, you can simply track the mode of the data that you've seen.

    private Set<Integer> calculateMode() {
        Set<Integer> modes = new HashSet<>();
        int largestCount = 0;
        int count = 0;

        int previous = sortedData[0];
        for (int datum : sortedData) {
            if (previous == datum) {
                count++
            } else {
                count = 1;
            }

            if (count > largestCount) {
                largestCount = count;
                modes.clear();
                modes.add(datum);
            } else if (count == largestCount) {
                modes.add(datum);
            }
        }

        return modes;
    }

This version returns a Set, since there is no guarantee that there will be a unique mode.

This method is private because it requires sorted data.  A public version could check if the data was sorted prior to calling the private version.

I renamed temp to previous as being more descriptive.

Because sorting clumps all the like values together, we don't need to store anything but the current and largest counts.

Saying count++ is more idiomatic than count += 1.

I don't verify that there is at least one element in the data.  You might want to throw an exception in that case.  As is, both your original version and this version would crash, as they attempt to access the first element.  It's possible that the correct place to do that validation is outside this method.

What if there's a 0 in the data?

            if (temp == 0){
                mode = ints[0];

If the correct answer is a 0 that is not in the first position, this will return the wrong answer.

Consider making a calculateSum method

If you had a calculateSum method, you could make calculateMean a one liner.  And report the sum of the data if you wanted.


Batch rename files recursively, and number the directory index When dealing with iOS app bundle, It is not convenient to get the file by its path, but loading it by its name.

Need to batch rename images recursively, with Mac Bash. And to make the name unique, the directory index should be numbered.

To rename files ,turn

Root----A----0.png
|       |
|        ----C----9.png
|
 -------B----0.png
|
 -------0.png
|
 -------0.sh

to

Root----A----1_0.png
|       |
|        ----C----3_9.png
|
 -------B----2_0.png
|
 -------0_0.png
|
 -------0.sh

Just to rename the .png files. Keep the other file's name before.

Here is my code, it is ok to deal with the situation that dir A has a name of spacing.

 n=0
rename(){
    varN=$n
    for f in * ; do
        if [[ -f $f ]]; then
            extension="${f##*.}"
            if [[ $extension == "png" ]]; then
                mv "$f" $n"_$f"
                (( varN++ ))
            fi
        fi
    done
    if (( $varN > $n )); then
        ((n++))
    fi
    for d in */ ; do
    ( cd "$d" && rename)
    (( n++ ))
    done
}

rename

Any way to make it more brilliant?

With this code and your example data, both a/c/0.png and b/0.png get renamed to 1_0.png.  This happens because changes to $n inside ( ) get lost when you leave the subshell.

Use bash's "globstar" feature to recurse for you, and assign numbers as normal.  **/ matches all subdirectories.  You want the current directory too, so add . to the list.

This doesn't exactly match your example (A/C will be numbered before B) but it's close:

shopt -s globstar
n=0
for d in ./ **/ ; do
    (
        cd $d &&
            for f in *.png; do
                [[ -f $f ]] && mv "$f" $n"_$f"
            done
    )
    (( n++ ))
done


List files in a directory I have folder1 that contains other folders (which may contain other folders etc). This process stops at some point where a folder contains only files, and some of them end with the string "img".

I would like to write to a file for each line:

the complete path of the file (if ends with, say "img")
the immediate folder that contains it

something like

/path/start/folder1/folder2/.../folderN/file123-img folderN

My Python 3 code is

import os
file_list = []
with open("fileList.txt", "w") as fp:
    for root, folders, files in os.walk('path/start/'):
        if folders == []:
            for fil in files:
                if fil.endswith('img'):
                    final = (root.split("/"))[-1]
                    fp.write(root + "/"+fil + " " + final +"\n")

I wonder if i could use more pythonic tool (like comprehensions) instead for - if - for - if

You do not use file_list
Emptiness of container (as in PEP8) is usually checked by if not container.
For path operations os.path is preferred. Let's change 'final' to os.path.dirname and building path to os.path.join. Avoid os-specific solutions.
Let's reduce indentation by using continue statement.
IMHO using comprehensions is not preferable here. Pythonic means 'obvious' and 'simple' way, and this is very simple way.
I introduced explanatory variable and tweaked naming a little bit.
Consider separating building file list with writing it to file. Separating responsibilities is usually great idea. If you do that maybe you'll be able to find good place to use comprehensions.

Improved code (without separating) below:

import os
with open("fileList.txt", "w") as fp:
    for root, folders, files in os.walk('path/start/'):
        if folders:
            continue
        for fil in files:
            if not fil.endswith('img'):
                continue
            dir_name = os.path.basename(fil)
            full_path = os.path.join(root, fil)
            fp.write("{0} {1}\n".format(full_path, dir_name))


Making sure a block of code takes at least 5 seconds to execute I am working on a personal project where I analyse Big Data by using twitter statuses. Therefore I am trying to query the Twitter API as many times as I can.

The API has a limit of 180 queries per 15 minutes, so I figured I can do 1 query every 5 seconds (at the minimum) if I want to not exceed that limit.

In the code below I do this the old-fashioned way with System.currentTimeMillis():

while (true) {
    newStatuses.clear();

    long startTime = System.currentTimeMillis();
    // Querying the API
    newStatuses.addAll(DbTools.TWITTER_FACTORY.search(_query).getTweets());
    long totalTime = System.currentTimeMillis() - startTime;

    allStatuses.addAll(newStatuses);
    Thread.sleep((totalTime > 5000) ? 0 : 5000 - totalTime);
    System.out.println(System.currentTimeMillis());
}

Pretty much if the total querying time took more than 5 seconds then sleep() for 0 seconds, if it took less than or equal 5 seconds then sleep() for the time that is remaining.

What I basically want is the time period from between hitting the line newStatuses.addAll(DbTools.TWITTER_FACTORY.search(_query).getTweets()); each time to be at least 5 seconds.

Is there any better way to do this or do you have any suggestions of how I can improve my solution?

Rather than waiting for 5 second between calls, consider that Twitter API returns three HTTP headers that explicitly tells you your quota:

  X-Rate-Limit-Limit: the rate limit ceiling for that given request
  X-Rate-Limit-Remaining: the number of requests left for the 15 minute window
  X-Rate-Limit-Reset: the remaining window before the rate limit resets in UTC epoch seconds

You can just query as much as you like, until the X-Rate-Limit-Remaining reaches zero or until you receive a 429 Too Many Request status code, then sleep for X-Rate-Limit-Reset.

This gives you several advantages:

You're utilising your limit to the fullest
If twitter changes their rate limit (e.g. someone is DDoSing them and they need to stricken it up or they make a significant upgrade that allows them to increase their quota), then your application will automatically adapt.
sleeping can't take into account of the per-user quota when you share access tokens for multiple applications/multiple purposes

Refer to Twitter documentation: https://dev.twitter.com/docs/rate-limiting/1.1


Alternative to XML PATH This inserts into 3 tables really quickly. My SELECT at the bottom appears to take an age, I assumed it would be fairly quick but is not. Is the XML path the right way to go?

DECLARE @TEAMMEMBER TABLE
        (CAREPROVIDEROID BIGINT, Team VARCHAR(MAX))
DECLARE @MAINSPECIALTY TABLE
        (CAREPROVIDEROID BIGINT, MainSpecialty VARCHAR(MAX))
DECLARE @TREATSPECIALTY TABLE
        (CAREPROVIDEROID BIGINT, TreatSpecialty VARCHAR(MAX))

INSERT INTO @TEAMMEMBER
    SELECT
    TEAMMEM.CAREPROVIDEROID as CAREPROVIDEROID,
    CAST(REPLACE(TEAM.NAME,'&','AND')+'('+TEAM.IDENTIFIER+')' AS NVARCHAR(MAX)) as Team
    FROM LZO_TEAMMEMBER TEAMMEM
    INNER JOIN LZO_TEAM TEAM
    ON TEAM.OID = TEAMMEM.TEAMOID
    AND TEAM.STATUS = 'A'
    --ORDER BY TEAMMEM.CAREPROVIDEROID

INSERT INTO @MAINSPECIALTY
    SELECT USERRP.USERSOID as USERSOIDMAINSPECIALTY,
    CAST(s.NAME +'('+s.MAINIDENTIFIER+')' AS NVARCHAR(MAX)) as MainSpec
    FROM LZO_USERROLEPROFILE USERRP

    INNER JOIN LZO_ROLEPROFILEENTERPRISEOBJECT RPEO
    ON USERRP.ROLEPROFILEOID = RPEO.ROLEPROFILEOID
    AND 'SPECIALTY' = RPEO.IDENTIFYINGTYPE
    AND RPEO.STATUS = 'A'
    INNER JOIN LZO_Specialty s
    ON s.OID = RPEO.IdentifyingOID and s.SPETYCode = 'CC_CPSPE' --Specialty
    AND RPEO.STATUS = 'A'
    WHERE 1=1
    AND USERRP.STATUS='A'
    --ORDER BY USERRP.USERSOID

INSERT INTO @TREATSPECIALTY
    SELECT
    USERRP.USERSOID as USERSOIDTREATSPECIALTY,
    CAST(s.NAME +'('+s.MAINIDENTIFIER+')' AS NVARCHAR(MAX)) as TreatSpec
    FROM LZO_USERROLEPROFILE USERRP
    INNER JOIN LZO_ROLEPROFILEENTERPRISEOBJECT RPEO
    ON USERRP.ROLEPROFILEOID = RPEO.ROLEPROFILEOID
    AND 'SPECIALTY' = RPEO.IDENTIFYINGTYPE
    AND RPEO.STATUS = 'A'
    INNER JOIN LZO_Specialty s
    ON s.OID = RPEO.IdentifyingOID and s.SPETYCode = 'CC_TRTFN' --Treatment Function
    AND RPEO.STATUS = 'A'
    WHERE 1=1
    AND USERRP.STATUS='A'
    --ORDER BY USERRP.USERSOID

Select OID,
       (SELECT sub.Team + ', ' AS [data()]
            from @TEAMMEMBER as sub
            Where sub.CAREPROVIDEROID = LZO_USERS.OID
            Order by sub.Team asc
                  FOR XML PATH('')
        ) as [Teams]

FROM LZO_USERS WHERE STATUS = 'A'

Removing the ORDER BY worked wonders and slightly altering the code:

,SUBSTRING(STUFF((SELECT ', '+TEAM FROM @TEAMMEMBER WHERE E.OID = CAREPROVIDEROID FOR XML PATH('')),1,1,''),2,4000) AS TEAMS


Giving an alternative Async method to a service I have an interface, implemented by a service, that I inject here and there in my codebase.
I would like to give the opportunity to use either the normal method or its async equivalent.
public interface IServiceDoStuff
{
    void DoSomeHeavyWork();
    Task DoSomeHeavyWorkAsync();
}

In my implementation I just do it like this
public class Service: IServiceDoStuff
{
    public void DoSomeHeavyWork(){ ... }

    public Task DoSomeHeavyWorkAsync()
    {
        return Task.Run(() => { DoSomeHeavyWork();});
    }
}

So my consumers just go
await injectedService.DoSomeHeavyWorkAsync();

My question is simply : is that a correct way to offer those two alternatives ?
Tasks, async and await have been giving me headaches forever, as it has always been one of the most obscure .NET features I work with. I can never feel confident about the code I write using those features.

If your implementation does not create interrupts of some sort there is no point in making it async. If the consumer does not want to wait for your code to execute its better to let them control that and execute your code seperate from the main thread.
Edit: if the interface and implementation are shipped seperate or if its possible someone will replace default none async implementation with a async implementation. Than it could be a good practice to make the interface Async and in your default implementation return Task.FromResult or Task.CompletedTask.


Clearing Pictures Code The following code removes all pictures that are placed into Column A. When running the code however I have noticed it runs fairly slow. This will be attached to a command button that will be located in A1, it is important that the deleting of pictures doesnt target this command button. Any suggestions?

    ' Clears All Pictures
    Sub DeleteAllPics()
    Columns("A:A").Replace What:="No Picture Found", Replacement:="", LookAt:=xlPart
    Dim pic As Object
    For Each pic In ActiveSheet.Pictures
    pic.Delete
    Next pic
    End Sub

I forced @proxy156 to start a new question which we discussed here
Finding and pasting images into a specific cell

I just can't figure out how the formatting works in comments here.
The problem here is that it takes a minute to delete about ~3000 pictures
Also there was a problem with different shape objects that should not be deleted (Buttons)

This code should work a bit better

Sub DeleteAllPics()

    Dim wks         As Worksheet
    Dim shp         As Shape
    Dim picArray()  As String
    Dim index       As Integer

    On Error GoTo ErrorHandler

    Set wks = ActiveSheet
    index = 1
    For Each shp In wks.Shapes
        If shp.Type <> msoFormControl Then
            ReDim Preserve picArray(1 To index)
            picArray(index) = shp.Name
            index = index + 1
        End If
    Next shp

    wks.Shapes.Range(picArray).Delete

ExitRoutine:
    Set wks = Nothing
    Set shp = Nothing
    Erase picArray
    Exit Sub

ErrorHandler:
    MsgBox Prompt:="Unable to find photo", _
           Title:="An error occured", _
           Buttons:=vbExclamation
    Resume ExitRoutine

End Sub


Polymorphic components for graphics and program state I asked this question on StackOverflow, got some answers, most notably a link to this one, and basing on that I've implemented this:

{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE FlexibleContexts #-}

module Main where

import Control.Monad.State
import Control.Monad.IO.Class

-- Module
----------------------------------------------------------------------------------------
newtype Module m a b =
    Module (a -> m (b, Module m a b))

{-
instance (Monad m) => Applicative (Module m a)
instance (Monad m) => Arrow (Module m)
instance (Monad m) => Category (Module m)
instance (Monad m) => Functor (Module m a)
-}

-- GraphicsModule
----------------------------------------------------------------------------------------
data GraphicsState = GraphicsState Int

render :: (MonadState GraphicsState m, MonadIO m) => Int -> m ()
render x = do
    (GraphicsState s) <- get
    liftIO $ print $ x + s
    put . GraphicsState $ s + 1

type GraphicsModule = Module IO Int ()

initialGraphicsState = GraphicsState 0

createGraphicsModule :: GraphicsState -> GraphicsModule
createGraphicsModule initialState = Module $ \x -> do
    (r, s') <- runStateT (render x) initialState
    return (r, createGraphicsModule s')

initialGraphicsModule = createGraphicsModule initialGraphicsState

runModule (Module m) x = m x

-- Program
----------------------------------------------------------------------------------------
data ProgramState = ProgramState {
    graphicsModule :: GraphicsModule
}

renderInProgram :: (MonadState ProgramState m, MonadIO m) => Int -> m ()
renderInProgram x = do
    gm <- gets graphicsModule
    (r, gm') <- liftIO $ runModule gm x

    modify $ \g -> g { graphicsModule = gm' }

initialProgramState = ProgramState initialGraphicsModule

main = runStateT prog initialProgramState

prog = do
    renderInProgram 1
    renderInProgram 1
    renderInProgram 1

I can see how this could be quite easily extended to allow more functions in a module (instead of just render). I am not sure if I'm keeping the state correctly, though. That was the only way I saw to not expose the inner, stateful context (note that the outer monad to the module is just IO).

Also I am aware of the fact that Lens could make it less verbose. I deliberately chose to not depend on Lens, and I think it's really functionally equivalent.

The point of the Module approach is that you don't manage any state globally. Instead, each component (Module) manages its own state internally and you just express how they are connected together.

To give a simple example, let me first implement the standard type classes for Module:

{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE FlexibleContexts #-}

module Main where

import Prelude hiding ((.), id)
import Control.Applicative
import Control.Arrow
import Control.Category
import Control.Monad
import Control.Monad.State
import Control.Monad.Trans
import Control.Monad.IO.Class
import Data.Void

-- Module
----------------------------------------------------------------------------------------
newtype Module m a b =
    Module { runModule :: a -> m (b, Module m a b) }

instance (Monad m) => Category (Module m) where
    id = Module $ \x -> return (x, id)
    (Module g) . (Module f) = Module $ \x -> do
        (u, f') <- f x
        (v, g') <- g u
        return (v, g' . f')

mkGen :: (Monad m) => (a -> m b) -> Module m a b
mkGen f = let m = Module $ \x -> do
                    y <- f x
                    return (y, m)
           in m

instance (Monad m) => Arrow (Module m) where
    arr f = mkGen (return . f)
    first (Module f) = Module $ \(x, y) -> do
        (r, m) <- f x
        return ((r, y), first m)

instance (Monad m) => Functor (Module m a) where
    fmap f (Module k) = Module $ \x -> do
        (y, k') <- k x
        return (f y, fmap f k')

instance (Monad m) => Applicative (Module m a) where
    pure x = let m = Module $ \_ -> return (x, m)
              in m
    (Module f) <*> (Module k) = Module $ \x -> do
        (h, f') <- f x
        (y, k') <- k x
        return (h y, f' <*> k')

The above functions allow creating modules and combining them together in various ways.

Now one of the main functions is to step a module with no input/output, producing its next state:

step :: (Monad m) => Module m () () -> m (Module m () ())
step (Module k) = liftM snd (k ())

For example, in your case you'd have a counter module, that keeps an internal state:

counter :: (Monad m) => Module m () Int
counter = let m i = Module $ \_ -> return (i, m (i + 1))
           in m 0

And a state-less module that just prints what it gets and has no output

render :: (MonadIO m, Show a) => Module m a ()
render = mkGen (liftIO . print)

Their combination is a module with no input or output, and stepping them prints the counter each time:

main :: IO ()
main = do
    let m = counter >>> render
    step m >>= step >>= step
    return ()


Brightness Web Server This is the first real program I've written in Go so have at it! I wrote it because I use a tiling window manager that doesn't have any brightness control functionality (at least not that I know of).

package main

import (
    "fmt"
    "io/ioutil"
    "log"
    "net/http"
    "strconv"
    "strings"
    "os"
)

func main() {

    const BRIGHTNESS_AMOUNT = 25

    maxBrightness := func() int {
        buff, err := ioutil.ReadFile("/sys/class/backlight/gmux_backlight/max_brightness")
        if err != nil {
            log.Fatal(err)
            return -1
        }
        buffInt, err := strconv.Atoi(strings.Replace(string(buff), "\n", "", -1))
        if err != nil {
            log.Fatal(err)
            return -1
        }
        return buffInt
    }()

    currentBrightness := func() int {
        buff, err := ioutil.ReadFile("/sys/class/backlight/gmux_backlight/brightness")
        if err != nil {
            log.Fatal(err)
            return -1
        }
        buffInt, err := strconv.Atoi(strings.Replace(string(buff), "\n", "", -1))
        if err != nil {
            log.Fatal(err)
            return -1
        }
        return buffInt
    }

    http.HandleFunc("/increase", func(w http.ResponseWriter, r *http.Request) {
        brightness := maxBrightness
        if (currentBrightness() + BRIGHTNESS_AMOUNT) < maxBrightness {
                brightness = currentBrightness() + BRIGHTNESS_AMOUNT
        }
        buff := []byte(strconv.Itoa(brightness))
        err := ioutil.WriteFile("/sys/class/backlight/gmux_backlight/brightness", buff, os.ModeDevice)
        if(err != nil) { log.Fatal(err) }
        fmt.Fprintf(w, strconv.Itoa(brightness))
    })

    http.HandleFunc("/decrease", func(w http.ResponseWriter, r *http.Request) {
        brightness := 0
        if (currentBrightness() - BRIGHTNESS_AMOUNT) > 0 {
                brightness = currentBrightness() - BRIGHTNESS_AMOUNT
        }
        buff := []byte(strconv.Itoa(brightness))
        err := ioutil.WriteFile("/sys/class/backlight/gmux_backlight/brightness", buff, os.ModeDevice)
        if(err != nil) { log.Fatal(err) }
        fmt.Fprintf(w, strconv.Itoa(brightness))
    })

    log.Fatal(http.ListenAndServe(":5600", nil))

}

I am also a novice in Go, so can't say anything about the idiomatic of this approach, but some improvements can offer.

Makes no sense to return -1 in currentBrightness/0  because panic is panic.
By the way, Go instead of processing the code of the return value is customary to return the error value as, for example, in strconv.Atoi or ioutil.ReadFile.
Instead of replace better to use TrimSpace

strings.TrimSpace(string(buff))

Code duplication

Not necessary 2 times used strconv.Itoa(brightness).

str := fmt.Sprint(brightness)
checkError(ioutil.WriteFile("brightness", []byte(str), os.ModeDevice))
fmt.Fprintf(w, str)

Since the error handling in Go program a common thing, easy to create a special function.

func checkError(err error) {
    if err != nil {
            log.Fatal(err)
        }
    }

3.
In both handlers have a recurring part: update the value stored in the file. This can also be avoided creating a new function.

update := func(w http.ResponseWriter, brightness int) {
    str := fmt.Sprint(brightness)
    checkError(ioutil.WriteFile("brightness", []byte(str), os.ModeDevice))
    fmt.Fprintf(w, str)
}

Then get as result:

package main

import (
    "fmt"
    "io/ioutil"
    "log"
    "net/http"
    "os"
    "strconv"
    "strings"
)

func main() {

    const BRIGHTNESS_AMOUNT = 25

    maxBrightness := func() int {
        buff, err := ioutil.ReadFile("max_brightness")
        checkError(err)
        buffInt, err := strconv.Atoi(strings.TrimSpace(string(buff)))
        checkError(err)
        return buffInt
    }()

    currentBrightness := func() int {
        buff, err := ioutil.ReadFile("brightness")
        checkError(err)
        buffInt, err := strconv.Atoi(strings.TrimSpace(string(buff)))
        checkError(err)
        return buffInt
    }

    update := func(w http.ResponseWriter, brightness int) {
        str := fmt.Sprint(brightness)
        checkError(ioutil.WriteFile("brightness", []byte(str), os.ModeDevice))
        fmt.Fprintf(w, str)
    }

    http.HandleFunc("/increase", func(w http.ResponseWriter, r *http.Request) {
        if (currentBrightness() + BRIGHTNESS_AMOUNT) < maxBrightness {
            update(w, currentBrightness()+BRIGHTNESS_AMOUNT)
        } else {
            update(w, maxBrightness)
        }
    })

    http.HandleFunc("/decrease", func(w http.ResponseWriter, r *http.Request) {
        if (currentBrightness() - BRIGHTNESS_AMOUNT) > 0 {
            update(w, currentBrightness()-BRIGHTNESS_AMOUNT)
        } else {
            update(w, 0)
        }
    })

    log.Fatal(http.ListenAndServe(":5600", nil))

}

func checkError(err error) {
    if err != nil {
        log.Fatal(err)
    }
}


Project Euler 35 in Python I'm back with a Python solution for Project Euler 35. Any help would be appreciated; I generate the numbers by observing that all circular primes can only have digits 1, 3, 7, and 9. Then I use the Cartesian product built into itertools. I also have a local primes test from Wikipedia.

from primes import test as is_prime
from itertools import product # cartesian product
from timeit import default_timer as timer

def find_circular_primes_under(limit):
    def is_circular(digits):
        digits = list(digits)
        for digit in digits:
            if not is_prime(int(''.join(map(str, digits)))):
                return False
            else:
                digits.append(digits.pop(0))
        return True

    if type(limit) != int or limit <= 2:
        return "Error: primes are positive integers greater than 1."
    elif limit <= 11:
        sum = 0
        for k in range(limit):
            if is_prime(k):
                sum += 1
        return sum

    else:
        sum = 4
        for k in range(2, len(str(limit))):
            for combo in product([1, 3, 7, 9], repeat = k):
                if is_circular(combo):
                    sum += 1
        return sum

start = timer()
ans = find_circular_primes_under(10**6)
elapsed_time = (timer() - start) * 1000 # s --> ms

print "Found %d in %r ms." % (ans, elapsed_time)

Returning an error message instead of data is not a good approach to handling errors. Try and see what happens if you tweak your code to pass an invalid argument to find_circular_primes_under. Do you see your error message? No, the program raises an exception trying to format the return value as a number. It would be better to raise an appropriate exception instead of returning from the function.
Modifying a container while iterating over it causes undefined behavior. In is_circular you could use for _ in xrange(len(digits)): instead of for digit in digits: to be safe. The digit variable is not used anyway.
You could take advantage of collections.deque and its rotate method to produce the rotations.


A queue, used to print four strings I made a queue that prints out strings a, b, c, and d. It works, but I want to make sure I don't have any unnecessary code. I realized that my main method prints the strings without the queue. Is there any better way to write the main method and Imp method so that it uses my queue class?

    public class Main
{
    //this method reverses the string
    public static void Imp(StringBuffer str)
    {

        int n = str.length();       //str.length recognizes the number of
                                    //characters in n, which is also the stack array
        Queue obj = new Queue(n);   //we set n to a new variable, "obj"

        // Push all characters of string
        // to stack
        int i;
        for (i = 0; i < n; i++)
        obj.push(str.charAt(i));

        // Pop all characters of string
        // and put them back to str
       for (i = 0; i < n; i++)
        {
            char ch = obj.pop();
            str.setCharAt(i,ch);
        }
    }

    public static void main(String args[])
    {
        //create a new string
        //StringBuffer also takes recognizes the amount of characters
        StringBuffer a= new StringBuffer("bob");
        StringBuffer b= new StringBuffer("eat too much");
        StringBuffer c= new StringBuffer("I love greasy food");
        StringBuffer d= new StringBuffer("FORTRAN 77 RULES");

        //call Imp method
        Imp(a);
        Imp(b);
        Imp(c);
        Imp(d);

    //print the reversed string
        System.out.println(a + "\n" + b + "\n" + c + "\n" + d);
    }
}

//this method creates the stack
//This method creates the queue
class Queue {
int size;
    int top;
    int bottom;
    char[] queue;

    Queue(int n)
    {
        top = 0;            //set stack top pointer to 0
        bottom = -1;        //set bottom pointer to less than the top pointer
        size = n;           //set size to variable n
        queue = new char[size]; //make int n convert to char queue by using size
    }

    char push(char x){
            queue[++bottom] = x;    //increment the queue pointer and place x on the bottom of x
            return x;       //return that x value
    }

    char pop(){
            char x = queue[top++];  //get x from the top of the queue and increment the queue
            return x;

    }

    boolean isEmpty()
    {
    boolean empty;      //make variable "empty" a boolean
    empty = false;      //"empty" is set as false
    if (top >= bottom){     //if top is greater than bottom, then the stack is empty
        empty = true;
    }
        return empty;

        }
}

Virtually all of your comments are visual noise. Comments should explain why things happen, not what is happening. If you can’t read the code to see what is happening, the code is not clear enough.

Use curly braces and whitespace consistently. Open curly braces don’t take a line by themselves. Put whitespace before the open curly brace.

Queue

Your class is called Queue but it is a Stack.

All your member variables should be private. Your methods should probably be public and not default scope.

queue should be final, since it’s never being reassigned.

top and bottom can have their base values assigned when they’re declared as member variables. top will be assigned zero by default if you don’t explicitly assign it, but there’s some disagreement as to whether that’s more or less clear.

size does nothing for you and can be removed. n should be renamed size.

x is a poor name for a char variable. Traditionally it would be c.

pop doesn’t need a variable in it. Just return this.queue[this.top++].

You should consider whether using ++ as part of your array index value is a good idea or if it makes the code hard to read. The code might be more clear if you separate the array indexing from the variable change.

The body if isEmpty() can be reduced to return this.top > this.bottom.

Your class will only work for one round of pushing and popping. The class breaks because bottom and top only get larger. To make the class reusable, you need only one variable which goes up and down as items are pushed and popped. You’ll still have out of bounds errors if they try to pop from an empty stack or push to a full one.

Main

Imp is a poor name for a method that reverses a String. Why wouldn’t you name it reverse?

Methods should start with a lowercase letter.

Your comment says Imp “reverses theString”, but it doesn’t. It reverses a StringBuffer.

Curly braces should never be treated as optional. That's a bug waiting to happen.

StringBuffer is thread-safe, and should really only be used in multithreaded environments for performance reasons. Prefer StringBuilder.

Unless there’s a reason you need to do the reverse in O(1) space, it would be more idiomatic to create a new StringBuilder and push the characters into that. Your method could accept a CharSequence, and interface which String, StringBuilder, and StringBuffer all implement. I’ll assume O(1) space is a hard requirement, since it would really be preferable to not mutate the input parameter.

n is a poor variable name. You don’t really need a variable there anyway, since you can just reference length() directly when you need it.

obj is a poor variable name. Variable names should describe what is being referenced. stack would be generic, but at least it’s a bit more descriptive.

You should declare i inside the scope of the for loop.

The ch variable does nothing for you and can be folded into the assignment.

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

public class Main {

    public static void reverse(final StringBuilder characters) {

        final Stack stack = new Stack(characters.length());

        for (int i = 0; i < characters.length(); i++) {
            stack.push(characters.charAt(i));
        }

        for (int i = 0; i < characters.length(); i++) {
            characters.setCharAt(i, stack.pop());
        }
    }

    public static String reverse(final CharSequence charSequence) {
        final Stack stack = new Stack(charSequence.length());

        for (int i = 0; i < charSequence.length(); i++) {
            stack.push(charSequence.charAt(i));
        }

        final StringBuilder reversedCharSequence = new StringBuilder(charSequence.length());
        while (!stack.isEmpty()) {
            reversedCharSequence.append(stack.pop());
        }
        return reversedCharSequence.toString();
    }

    public static void main(final String args[]) {
        final StringBuilder a = new StringBuilder("bob");
        final StringBuilder b = new StringBuilder("eat too much");
        final StringBuilder c = new StringBuilder("I love greasy food");
        final StringBuilder d = new StringBuilder("FORTRAN 77 RULES");

        reverse(a);
        reverse(b);
        reverse(c);
        reverse(d);

        System.out.println(a + "\n" + b + "\n" + c + "\n" + d);

    }
}

and your Queue class might look something like:

class Stack {

    private final char[] stack;
    private int top = -1;

    public Stack(final int size) {
        this.stack = new char[size];
    }

    public char push(final char c) {
        this.top++;
        this.stack[this.top] = c;
        return c;
    }

    public char pop() {
        final char c = this.stack[this.top];
        this.top--;
        return c;
    }

    public boolean isEmpty() {
        return this.top >= 0;
    }
}


Load assemblies with injector module How can I improve the performance of this method or is it already good?

private static void LoadAssembliesWithInjectorModule(IEnumerable<FileInfo> files)
{
    var moduleType = typeof (InjectorModule);

    foreach (var file in files)
    {
        try
        {
            var assembly = Assembly.LoadFrom(file.FullName);

            var moduleTypes = from assemblyType in assembly.GetTypes()
                              where moduleType.IsAssignableFrom(assemblyType) && !assemblyType.IsAbstract
                              select assemblyType;

            if (!moduleTypes.Any()) continue;

            foreach (var instance in moduleTypes.Select(type => Activator.CreateInstance(type) as InjectorModule))
            {
                instance.Load();
            }
        }
        catch (BadImageFormatException)
        {
            //Files that aren't class libraries will throw this exception, just eat it and move on.
        }
        catch (ReflectionTypeLoadException e)
        {
            throw new AppDomainUnloadedException(string.Format("Error loading {0} exception {1} loading errors {2}", file.FullName, e.Message, e.LoaderExceptions), e);
        }
    }
}

I would suggest swapping the checks on this line from

where moduleType.IsAssignableFrom(assemblyType) && !assemblyType.IsAbstract

to

where !assemblyType.IsAbstract && moduleType.IsAssignableFrom(assemblyType)

Checking a boolean property will be faster than a method call to check the type. If it's not abstract why check the type?

You might also want to filter further by requiring that it is a class:

where assemblyType.IsClass
      && !assemblyType.IsAbstract
      && moduleType.IsAssignableFrom(assemblyType)


Drawing pixel to pixel I'm drawing a pixel by pixel image with the following code:

coord = np.where(np.all(imagen == (0, 0, 0), axis=-1))
cv2.imshow('imagen', imagen)

a = coord[0]
b = coord[1]

for x,y in zip(a,b):
    rectObs.append(pygame.Rect((y,x),(1,1)))

for rect in rectObs:
    pygame.draw.rect(screen, black, rect,20)

This code detects all the black pixels of an image and draws them in another window with the same coordinate. The problem is that there are so many black pixels that the processing is very very slow.

Any idea to improve performance or to graph in a more optimal (other than pixel by pixel)?

There're several places you could optimize your code.

First, though, I suggest profiling your current code, so you'd know which are your bottlenecks, and where you should concentrate your efforts.

The detection of the black pixels is a CPU intensive process, which means it could benefit from the techniques mentioned above.

The copying of the black pixels, on the other hands, is an I/O intensive process, which you can optimize in two ways:

Instead of copying the pixels as they are discovered to the other window, build a data structure - in memory - that represents the data for this other window, and then do the copy as one memory image copying, instead of a set of single pixels. Or,
Break the pixel copying into several threads/processes that will work in parallel. Note that this may not be possible, depending on your algorithm.


Rendering comments in a Backbone view I want to make show/hide logic more maintainable in my codebase.

Because they are too faraway located in separate js files, it hard for people to maintain.

The  flow in my codebase is:

  require.js init (hide the target DOM at first) → app.js → load_comments.js (show the target DOM if the comments length > 0)

main.js (require.js manifest file)

$("#target_dom").hide();

app.js

define([
    'load_comments',
    "jquery"
],function( comments, $){

    return {
        initialize: function(){
            console.log("app.js initialized");
        }
    }
})

load_comments.js

var CommentView = Backbone.View.extend({
    el: $("#comments_section"),
    render: function() {
        var notNullComments = comments.wellFormedComments();
        if (notNullComments.length > 0) {
            $("#target_dom").show();
        }
        var html = commentsTmpl(notNullComments.toJSON());
        $(this.el).append(html);
    },
});

From a once over:

load_comments should follow lowerCamelCase -> loadComments
Avoid console.log, at least wrap it in something that also takes in to account message severity and filters on that message severity
Personally I would have used either comments or wellFormedComments instead of notNullComments
It seems that if there are no comments, that you should get out, and not do the JSON parsing and the html appending
Where is commentsTmpl defined? Smells like a global variable
It is very confusing to have #target_dom there, I am guessing that it is a subelement of #comments_section, but I would have called it #comments probably?
Even more confusing is that you append the html to #comments_section and not #target_dom

All in all, I would go with something like this:

var CommentView = Backbone.View.extend({
    el: $("#comments_section"),
    render: function() {
        var comments= comments.wellFormedComments();
        if (!comments.length) {
            return
        }
        $("#a_descriptive_id").show();
        var html = commentsTmpl(notNullComments.toJSON());
        $(this.el).append(html);
    },
});


Computing a Discrete Cosine Transform matrix I'm learning Haskell and I needed to work with discrete cosine transform matrices, so I made a program that generates text (usable in WolframAlpha) containing the generated matrix.

The elements of the n-square matrix C are defined as:

\$[C]_{jk} = \gamma_jcos\dfrac{\pi(2k+1)j}{2n}\$ where \$\gamma_{j} = \begin{cases}\frac{1}{\sqrt{n}} & \text{j = 0} \\ \frac{2}{\sqrt{n}} & \text{otherwise} \end{cases}\$

I also wanted the program to simplify fractions and sqrt, which is where most of  the "dirtiness" came from. Is there any way to clean this up? It's simple enough, but I want to learn how to be concise.

import Ratio

-- Pretty-print a fraction
showFraction n d
    | n == 0            = "0"
    | d == 0            = error "Division by zero."
    | n == 1 && d == 1  = "1"
    | n == 1            = "1/" ++ show d
    | d == 1            = show n
    | otherwise         = show n ++ "/" ++ show d

-- Pretty-print a fraction, reducing the fraction
showFractionReduced n d = let x = n % d in showFraction (numerator x) (denominator x)

-- Pretty-print a fraction, with an additional numerator factor
showFraction' n d n'
    | n == 0            = "0"
    | d == 0            = error "Division by zero."
    | n == 1 && d == 1  = n'
    | n == 1            = n' ++ "/" ++ show d
    | d == 1            = show n ++ "*" ++ n'
    | otherwise         = show n ++ "*" ++ n' ++ "/" ++ show d

-- Pretty-print a fraction, reducing the fraction, with an additional numerator factor
showFractionReduced' n d = let x = n % d in showFraction' (numerator x) (denominator x)

-- Discrete cosine transform matrix element
dctElement j k n
    | n <= 1            = "1"
    | n == 2 && j > 0   = "cos(" ++ showFractionReduced' (j * (2 * k + 1)) (2 * n) "pi" ++ ")"
    | j == 0            = "sqrt(" ++ showFractionReduced 1 n ++ ")"
    | otherwise         = "sqrt(" ++ showFractionReduced 2 n ++ ")*cos(" ++ showFractionReduced' (j * (2 * k + 1)) (2 * n) "pi" ++ ")"

-- Discrete cosine transform matrix row
dctRow j n = "{" ++ foldr1 (\acc x -> acc ++ "," ++ x) [dctElement j x n | x <- [0..n - 1]] ++ "}"

-- Discrete cosine transform matrix
dctMatrix n = "{" ++ foldr1 (\acc x -> acc ++ ",\n" ++ x) [dctRow x n | x <- [0..n - 1]] ++ "}"

-- Inverse discrete cosine transform matrix row
dctRowInverse j n = "{" ++ foldr1 (\acc x -> acc ++ "," ++ x) [dctElement x j n | x <- [0..n - 1]] ++ "}"

-- Inverse discrete cosine transform matrix
dctMatrixInverse n = "{" ++ foldr1 (\acc x -> acc ++ ",\n" ++ x) [dctRowInverse x n | x <- [0..n - 1]] ++ "}"

The string generated by dctMatrix 3, for example, is:

  {{sqrt(1/3),sqrt(1/3),sqrt(1/3)},
  {sqrt(2/3)*cos(pi/6),sqrt(2/3)*cos(pi/2),sqrt(2/3)*cos(5*pi/6)},
  {sqrt(2/3)*cos(pi/3),sqrt(2/3)*cos(pi),sqrt(2/3)*cos(5*pi/3)}}

while the string generated by dctMatrix 2 is:

  {{sqrt(1/3),sqrt(1/3),sqrt(1/3)},
  {sqrt(2/3)*cos(pi/6),sqrt(2/3)*cos(pi/2),sqrt(2/3)*cos(5*pi/6)},
  {sqrt(2/3)*cos(pi/3),sqrt(2/3)*cos(pi),sqrt(2/3)*cos(5*pi/3)}}

(Notice the simplification of the fractions in the former, and the square root in the latter.)

It is probably more in the spirit of functional programming to use pattern matches instead of long guard lists where possible. Your first function also has a few overlapping cases that could be eliminated in the interest of brevity:

showFraction _ 0 = error "Division by zero."
showFraction 0 _ = "0"
showFraction n 1 = show n
showFraction n d = show n ++ "/" ++ show d

Another simple change would be to exploit that foldr1 (\acc x -> acc ++ "," ++ x) is simply intercalate ',', which you get from Data.List. In a somewhat similar fashion, you could also replace foldr1 (\acc x -> acc ++ ",\n" ++ x) by concat . intersperse ",\n".

The result would look like follows:

dctRow j n = "{" ++ intercalate ',' [dctElement j x n | x <- [0..n - 1]] ++ "}"
dctMatrix n = "{" ++ concat (intersperse ",\n" [dctRow x n | x <- [0..n - 1]]) ++ "}"

Which in my opinion is more readable than the manual folds.

A more involved change would be to try to get rid of the \$O(n^2)\$ behaviour you will get from overusing (++). The background here is that (++) needs to make a full copy of the first operand in order to append the second one.

A fun functional way of improving this is to replace string concatenation by function composition:

showFraction :: Int -> Int -> String -> String
showFraction _ 0 = error "Division by zero."
showFraction 0 _ = ('0':)
showFraction n 1 = shows n
showFraction n d = shows n . ('/':) . shows d

So instead of a function that constructs a string, this is a function that prepends the string representation to a string passed as parameter. The nice thing about this is that you can simply compose these functions together in order to build bigger strings. As prepending doesn't require copying of the "tail" end in Haskell, this means that every part of the result string will be constructed exactly once!

Here is how to write the folds in this style:

applyInter f = flip (foldr ($)) . intersperse f
dctRow j n = ('{':) . applyInter (',':) [dctElement j x n | x <- [0..n - 1]] . ('}':)

(Realize that flip (foldr ($)) [f,g,h] is simply f . g . h)

Note however that while this indeed has \$O(n)\$ complexity, it is still not very efficient. This is due to GHC probably selecting a bad arity for some of the functions in question, as well as String not being very fast in the first place. For constructing strings fast, it's probably a better idea to use Data.Text and/or a special builder library like blaze-builder.


Parsing command line arguments Usage:

// Usage: dndgenerate /e [emhd] [0-9+]
//          dndgenerate /e d 4 4 5 4
// /e   Generate Encounter. Parameter can be one of
//          e - Easy
//          m - Medium
//          h - Hard
//          d - Deadly
//      As well as a list of heroes by their levels
//
// Example:  dndgenerate /e m 4 4 5 4
//      Generate a medium encounter for three level 4 and one level 5 adventurers.

The code to make it happen:

type DifficultyOption = Easy | Medium | Hard | Deadly

type EncounterOptions = {
    difficulty: DifficultyOption option
    heroes: int list
}

let (|Level|_|) (str: string) =
    let mutable intValue = 0

    if System.Int32.TryParse(str, &intValue)
        then match intValue with
             | x when x < 0 -> None
             | x when x > 20 -> None
             | x -> Some x
        else None

let (|Difficulty|_|) (str: string) =
    match str with
    | "e" | "E" -> Some(Easy)
    | "m" | "M" -> Some(Medium)
    | "h" | "H" -> Some(Hard)
    | "d" | "D" -> Some(Deadly)
    | x -> None

let isComplete (options:EncounterOptions) =
    not <| options.heroes.IsEmpty && options.difficulty.IsSome

type VerboseOption = VerboseOutput | TerseOutput

type MiscOptions = {
    verbose: VerboseOption
}

type GeneratorType =
    | E of EncounterOptions
    | Unknown

type ParseMode = TopLevel | Encounter | Plot | Dungeon | Settlement | Error

type CommandLineOptions = {
    misc: MiscOptions
    parseMode: ParseMode
    generatorType: GeneratorType
}

let parseTopLevel arg miscSoFar =
    match arg with
    | "/v" ->
        let newMiscSoFar = { miscSoFar with verbose = VerboseOutput }
        { misc = newMiscSoFar; parseMode = TopLevel; generatorType = Unknown }

    | "/e" ->
        { misc = miscSoFar; parseMode = Encounter; generatorType = E { difficulty = None; heroes = [] } }

    | x ->
        { misc = miscSoFar; parseMode = Error; generatorType = Unknown }

let parseEncounter arg miscSoFar encounterGenerator =
    match arg with
    | Level x ->
        let builder' = { encounterGenerator with heroes = x :: encounterGenerator.heroes }
        { misc = miscSoFar; parseMode = Encounter; generatorType = E builder' }

    | Difficulty x ->
        let builder' = { encounterGenerator with difficulty = Some x }
        { misc = miscSoFar; parseMode = Encounter; generatorType = E builder' }

    | _ ->
        { misc = miscSoFar; parseMode = Error; generatorType = E encounterGenerator }

let foldFunction state element =
    match state with
    | { misc = m; parseMode = TopLevel } ->
        parseTopLevel element m

    | { misc = m; parseMode = Encounter; generatorType = E(g) } ->
        parseEncounter element m g

    | { parseMode = Error } ->
        state

    | { misc = m; parseMode = p; generatorType = g } ->
        printfn "Unexpected constellation of %A %A %A" m p g
        state

let disableIfIncomplete commandLineOptions =
    match commandLineOptions.parseMode with
    | Error ->
        commandLineOptions

    | _ ->
        match commandLineOptions.generatorType with
        | E(encounter) when isComplete encounter ->
            commandLineOptions

        | Unknown -> commandLineOptions

        | _ -> { commandLineOptions with parseMode = Error }

let parseCommandLine args =
    let defaultOptions = {
        verbose = TerseOutput
    }

    let initialFoldState =
        { misc = defaultOptions; parseMode = TopLevel; generatorType = Unknown }

    let finalFoldState = args |> List.fold foldFunction initialFoldState

    disableIfIncomplete finalFoldState

Based on code from Scott Wlaschin's Parsing command line arguments but extended to include argument groups and error handling. Purposefully avoided FParsec because I'm new to F# and wanted to solve it vanilla-style first.

I am also new to F#, so I have just 2 small annotations:

The function that parses the string to Int32 can be simplified:

match System.Int32.TryParse(str) with
    | (true, x) when x >= 0 && x <= 20 -> Some x
    | _ -> None

The last case of the function parseTopLevel should be _ -> instead of x -> because the value is not used ('_' expresses exactly that)


Erlang handling errors in concurrent programs I have two tasks:

  Write a function that starts and monitors several worker processes. If any of the worker processes dies abnormally, restart it

Here is the code that I built:

proc() ->
    receive
        p -> exit("I need to die")
    end.

start_and_monitor(0) ->
    spawn_monitor(proc()),
    receive
        {'DOWN',_,process,_,_} -> spawn_monitor(proc())
    end;
start_and_monitor(Int) ->

    spawn_monitor(proc()),
    start_and_monitor(Int - 1).

  Write a function that starts and monitors several worker processes. If any of the worker processes dies abnormally, kill all the worker processes and restart them all.

Here I thought that instead of monitoring all of the process I could link all the small processes and monitor a major process that is linked to all of them. Here is the code:

start_and_monitor_but_kill(Int) ->
{Pid,Ref} = spawn_monitor(start_monitor_kill(Int)),
receive
    {'DOWN', Ref, process, _, _} -> start_and_monitor_but_kill(Int)
end.

start_monitor_kill(0) ->
    spawn_link(proc());
start_monitor_kill(Int) ->
    spawn_link(proc()),
    start_monitor_kill(Int-1).

Is there any way that I can improve my code? Am I using all the erlang primitives correctly ? Any criticism is highly appreciated.

Also I am very curious if I used the primitives correctly. For example I used the monitor process without giving a ref. Is this acceptable in this case?

In your code you're calling spawn_monitor/1 like this:

spawn_monitor(proc()),

where proc/0 is a local function, but this doesn't do what you think it does. First it calls proc/0, which blocks in a receive until it gets a message. Normally it would return the value of receive, but your receive calls exit/1 so there's no return. So, what happens is that the first call into proc/0 blocks until it receives a message, at which point it exits, and since it was running not in a spawned process but in the calling process — the process where the caller is running — the caller exits too. Nothing ever gets spawned or monitored. (This same problem exists in your second code example too.)

What spawn_monitor/1 wants is a function, so you should be calling it like this:

spawn_monitor(fun proc/0),

If you make that change everywhere, then the code works, but there's one other thing: your start_and_monitor(0) function clause should not be calling spawn_monitor before calling receive, otherwise Int+1 rather than Int processes will be spawned and monitored.

As for the second code example, monitors and processes are cheap, so there's no point in trying to bundle them together into a single monitoring point.

And finally, you might consider solving this problem not with monitors but rather with links. A monitor allows a process to watch an unrelated process, but if one process is spawning another, then they're related, so links are a viable approach.