texts: How can I improve the design of this serialization mechanism?

texts:
I'm working on caching library which is intended to work with all types of values.

Values are represented as instances of value_type: value_type holds a std::vector<char> for the raw data, and a uint32_t flags integer value which is used to indicate the format of the stored data.

I would like to make it easy for the users of the library and provided a serialize() method that would convert a C++ type to a value_type so that instead of writing:

// In the line below, serialization::string is an integer constant
value_type value(serialization::string, "My string");

People could just write:

value_type value = serialize("My string");

And somehow the serialize() method would "guess" that the associated integer flag is serialization::string.

I would also make it possible for an user to register his own types and conversions into the serialization mechanism.

I came up with the following code:

/**
 * \brief A default serializer type.
 * \tparam Type The type to serialize.
 */
template <typename Type>
struct serializer {};

/**
 * \brief The base serializer type.
 * \tparam Type The serialized type.
 * \tparam Flags The flags.
 *
 * Derive from this type to enable a new serialization.
 */
template <typename Type, value_type::flags_type Flags>
struct base_serializer
{
    /**
     * \brief The type supported by the serializer.
     */
    typedef Type type;

    /**
     * \brief The flags.
     */
    static const value_type::flags_type flags = Flags;

    static value_type serialize(const type& value)
    {
        return value_type(flags, serializer<type>::serialize_data(value));
    }

    /**
     * \brief Deserialize a value.
     * \param value The value.
     * \return The deserialized value.
     */
    static Type deserialize(const value_type& value)
    {
        if (value.flags() != flags)
        {
            throw boost::system::system_error(serialization::error::invalid_types, serialization::serialization_category(), "deserialization failed");
        }

        return serializer<type>::deserialize_data(value.data());
    }
};

/**
 * \brief Serialize a value.
 * \tparam Type The type.
 * \param value The value.
 * \return The serialized value.
 */
template <typename Type>
value_type serialize(const Type& value) { return serializer<Type>::serialize(value); }

/**
 * \brief Deserialize a value.
 * \tparam Type The type.
 * \param value The value.
 * \return The deserialized value.
 */
template <typename Type>
Type deserialize(const value_type& value) { return serializer<Type>::deserialize(value); }

/**
 * \brief A const char* serializer.
 */
template <>
struct serializer<const char*> : public base_serializer<const char*, serialization::string>
{
    static std::vector<char> serialize_data(type value)
    {
        return std::vector<char>(value, value + strlen(value));
    }
};

/**
 * \brief An overload.
 * \param value A C-string.
 * \return The serialized value.
 */
value_type serialize(const char* value) { return serializer<const char*>::serialize(value); }

/**
 * \brief A std::string serializer.
 */
template <>
struct serializer<std::string> : public base_serializer<std::string, serialization::string>
{
    static std::vector<char> serialize_data(type value)
    {
        return std::vector<char>(value.begin(), value.end());
    }

    static type deserialize_data(const std::vector<char>& value)
    {
        return type(value.begin(), value.end());
    }
};

Do you guys see any improvement ?

Thank you.


texts: Finding unpaired number in an odd length Array of integers

texts:
codility OddOccurrencesInArray:

A non-empty array A consisting of N integers is given. The array contains an odd number of elements, and each element of the array can be paired with another element that has the same value, except for one element that is left unpaired.
For example, in array A such that:
  A[0] = 9  A[1] = 3  A[2] = 9
  A[3] = 3  A[4] = 9  A[5] = 7  A[6] = 9
    • the elements at indexes 0 and 2 have value 9,
    • the elements at indexes 1 and 3 have value 3,
    • the elements at indexes 4 and 6 have value 9,
    • the element at index 5 has value 7 and is unpaired.
Write a function:
     class Solution { public int solution(int[] A); }
that, given an array A consisting of N integers fulfilling the above conditions,
returns the value of the unpaired element.

class Solution {

    public int solution(int[] A) {

        final int len = A.length;

        Arrays.sort(A);

        for (int i = 0; i < len ;) {
            int counter = 1;
            int current = A[i];

            while ((i < len - 1) && (current == A[++i])) {
                counter++;
            }

            if (counter % 2 == 1) {
                return current;
            }
        }
        return -1;
    }
}

Could this code be bettered in terms of time complexity or code quality?


texts:
I've come up with this small function to make user submitted strings safe for MySQL. I'd be grateful if someone could point out any security holes in this. I've tested it out, and it happily replaces quotes and the like. The only issue I can see is the lack of escaping ampersands, but this shouldn't matter right?

$keywords = array("delete from", "drop table", ";", "=");
$safeKeywords = array("delete&nbsp;from", "drop&nbsp;table", "&#59;", "&#61;");

function dbSanitise($field)
{
    global $keywords, $safeKeywords;

    $sanitised = str_ireplace($keywords, $safeKeywords, $field);
    $sanitised = htmlentities($sanitised, ENT_QUOTES);
    $sanitised = mysql_real_escape_string($sanitised);

    return $sanitised;
}

Putting this string into the function above:

Hello world delete from DELETE FROM ; = " ' ''

Yields this:

Hello world delete&amp;nbsp&amp;#59;from delete&amp;nbsp&amp;#59;from &amp;#59; &amp;#61; &quot; &#039; &#039;&#039;

Which I can only see as being perfectly acceptable for a MySQL insert operation.

If I'm wrong, do let me know! Thanks for any help.


texts:
I asked another question the other day and decided to rewrite the code with some of the suggestions given and add functionality (instead of reading from a console I'm reading directly from a file) the code works.

Looking at it, I think the nested for loop on the encode function doesn't look that good. I tried using std::transform like the comment on the code. It worked when I used the console just to read a line, now with vectors couldn't make it work.

// Ceaser Cipher implementation

#include <iostream>
#include <string>
#include <algorithm>
#include <fstream>
#include <vector>

std::vector<std::string> encode(const std::vector<std::string> &str, int shift)
{
    std::vector<std::string> tempMsg;

    for (std::string lines : str)
    {
        // std::transform(lines.cbegin(), lines.cend(), std::back_inserter(tempMsg), [&](char ch) -> char
        for (char &ch : lines)
        {
            if (ch == 'z' || ch == 'Z')
            {
                ch -= 25;
            }
            else if (isspace(ch)) {
                ch = ' ';
            }
            else
            {
                ch += shift;
            }
        }
        tempMsg.push_back(lines);
    }

    return tempMsg;
}

std::vector<std::string> decode(const std::vector<std::string> &str, int shift)
{
    return encode(str, -1 * shift);
}

int main(int argc, char *argv[])
{
    int choice;
    std::cout << "What do you want to do? 1.Encrypt, 2.Decrypt: ";
    std::cin >> choice;

    int key;
    std::cout << "Enter desired shift: ";
    std::cin >> key;

    std::ifstream inFile("testfile.txt");
    if (!(inFile.is_open()))
    {
        std::cout << "There was a problem with the file!";
        std::exit(EXIT_FAILURE); // ExitProcess() if windows especific.
    }

    std::vector<std::string> finalResult;

    std::string line;
    std::vector<std::string> lines;

    while (std::getline(inFile, line))
    {
        lines.push_back(line);
    }
    inFile.close();

    if (choice == 1)
    {
        auto result = encode(lines, key);
        finalResult = result;
    }

    else if (choice == 2)
    {
        auto result = decode(lines, key);
        finalResult = result;
    }
    else
    {
        std::cout << "Wrong option, exiting!";
        std::exit(EXIT_FAILURE);
    }

    std::ofstream outFile("testfile.txt");
    for (auto i = finalResult.begin(); i != finalResult.end(); ++i)
    {
        outFile << *i << '\n';
    }
    outFile.close();

    std::exit(EXIT_SUCCESS);
}


texts: Jquery Selector optimization for multiple clicks

texts:
I have multiple inputs that each one has an increment and decrement button

The buttons will be pressed multiple times so i am looking to optimize my selector:

So should i keep the first one (which selects by attribute) or the second? Or anything more optimized.

$("[data-id-col="+thisID+"]")

$("input:tel#"+thisID+")

$("body").on('click','.incButton',e=>{
    let thisID = e.currentTarget.getAttribute("d-id");
    let colInput = $("[data-id-col="+thisID+"]");
    colInput.val( parseInt( colInput.val())+1);
    colInput.change();
});

Html:

Input

<div class="handle-counter" id="handleCounter3">
    <input type="tel" data-id-col="8900" id="qty_inputCol" class="qty_col">
</div>

Button

<button type="button" d-id="8888" class="btn btn-primary btn-block inc"></button>

https://learn.jquery.com/performance/optimize-selectors/


texts: Intersection of N lists, or of an N-d array

texts:
I often find myself having to do np.intersect1d() multiple times because I need to find the intersection of a number of list like or array like things. So I ended up creating a function for it. Though, if possible I'd like to simplify / and or speed up the code for when the input becomes rather large.

def overlap(splits):
    uniques = {item: 0 for item in list(set([i for x in splits for i in x]))}
    for idx in range(len(splits)):
        for val in list(set(splits[idx])):
            if val in uniques.keys():
                uniques[val] += 1
    intersection = np.array([x for x in uniques.keys() if uniques[x] == len(splits)])
    return intersection


texts: Print the number of subarrays of an array having negative sums

texts:
Problem statement: Given an array of N integers, find and print its number of negative subarrays (i.e sub arrays having negative summation) on a new line.

My code: Taking order of 3 time. How can I improve my java code?

    import java.util.Scanner;
     public class NegativeSumOfArray {
        public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int N = in.nextInt(); //Taking size of an array
        int[] arr = new int[N];
        for(int i=0;i<N;i++){
            arr[i] = in.nextInt(); // Taking content of the array.
        }
        // Counting number of sub arrays whose summation is negative.
        int sum=0,count=0;
        for(int i=1,k,j;i<=N;i++){
            for(k=1;k<=N-i+1;k++){
                for(j=0;j<i;j++){
                    sum += arr[j+k-1];
                }
                if(sum<0)
                    count++;
                sum = 0;
            }
        }
        System.out.print(count);
        in.close();
    }
}


texts:
I have the input image in, and the mask image lev (which label each pixel as a number from 1 to nlevels, nlevels=4). I need to get image out, which from each region in==lev will be replaced by its average value.

Here is my brute force approach.  I'm wondering if there is any better way of doing it.

Mat ACA::global_average(Mat in, const Mat &lev)
{
    // in: CV_32F
    // lev: CV_32S
    int M=in.rows;
    int N=in.cols;

    in.convertTo(in, CV_32FC3);

    // vector holds average value for each category
    vector<float> count(nlevels,0);
    vector<Vec3f> average(nlevels);

    int pixlev;
    for (int i=0; i < M; i++)
        for (int j=0; j < N; j++)
        {
            pixlev = lev.at<int>(i,j);
            assert (pixlev<nlevels);

            average[pixlev] += in.at<Vec3f>(i,j);
            count[pixlev]++;
        }

    for (int i=0; i<nlevels; i++)
        average[i] /=count[i];

    Mat out=Mat::zeros(M,N,CV_32FC3);
    for (int i=0; i<M; i++)
        for (int j=0; j<N; j++)
        {
            pixlev = lev.at<int>(i,j);
            out.at<Vec3f>(i,j)=average[pixlev];
        }
    return out;
}

P/S:

Here is an example.

Input Image:

Mask image, it is basically a matrix labelling the pixels into one of 4 categories

Output picture is the average of input image, for each category of pixels. For example, at first I find all pixels has category 1, find their average, and replace all those pixels by the average value.


texts: find the index of subarray from a parent array

texts:
Are there any improvements that can be made on the below code, especially in terms of memory and time? I feel bad about setting found = false in every iteration of the for loop.

public static void main(String[] args) {
    System.out.println(getSubArrayIndex(new int[]{2,3,4,2,2,3,5,5,4,2,3,4}, new int[]{2,3,4}));
}

static int getSubArrayIndex(int[] parentArr, int[] subArr) {
    boolean found = false;
    for (int i = 0; i <= parentArr.length - subArr.length; i++) {
        if(parentArr[i] == subArr[0]){
            for(int j = 1 ; j < subArr.length ; j++){
                if(!(parentArr[i+j] == subArr[j])){
                    found = false;
                    break;
                }
                else{
                    found = true;
                }
            }
        }
        if(found)
            return i;
    }
    return -1;
}


texts:
I just stated learning Rust (again...), here is a short bit of code I wrote:

#![allow(non_snake_case)]

/**
 * takes a 2D Vec and returns a 90° rotated version
 */
pub fn createRotated90(arr: &Vec<Vec<bool>>) -> Vec<Vec<bool>> {
    let newWidth = arr[0].len();
    let newHeight = arr.len();
    let mut newRetArr = createNewFilled2DVec(newWidth as u8, newHeight as u8, false);

    forEachXY(
        newHeight as u8,
        newWidth as u8,
        &mut |x: u8, y: u8| newRetArr[y as usize][newHeight - x as usize - 1] = arr[x as usize][y as usize]
    );

    newRetArr
}

pub fn createNewFilled2DVec<T: std::clone::Clone>(width: u8, height: u8, filler: T) -> Vec<Vec<T>> {
    vec![vec![filler; height as usize]; width as usize]
}

pub fn forEachXY<F: FnMut(u8, u8)>(width: u8, height: u8, mut func: F) {
    let mut x: u8 = 0;
    let mut y: u8 = 0;

    while x < width {
        while y < height {
            func(x, y);

            y += 1;
        }

        x += 1;
    }
}

I am hoping for some general suggestion on how to improve my "Rusting".
Some points I noticed:

a lot of as usize
It seems Rust doesn't want me to use "normal" for loops (see forEachXY)
I am using Vec's instead of arrays, even though they don't change in size


texts:
I've written a implementation of a merge sort in Python. It seems correct and I have tested it with this:

l = list(range(1000))
random.shuffle(l) # random.shuffle is in-place
mergesort(l) == list(range(1000)) # returns True

# Stable sort
cards = list(itertools.product(range(4), range(13)))
random.shuffle(cards)
cards = mergesort(cards, key=lambda x: x[1]) # Sort by rank
cards = mergesort(cards, key=lambda x: x[0]) # Sort by suit
cards == list(itertools.product(range(4), range(13))) # returns True

I've also tested its performance, comparing it to sorted and the merge sort implementation in rosetta code:

rl = list(range(100))
random.shuffle(rl)

%timeit sorted(rl)
# 100000 loops, best of 3: 11.3 µs per loop

%timeit mergesort(rl) # My code
# 1000 loops, best of 3: 376 µs per loop

%timeit rcmerge_sort(rl) # From rosetta code
# 1000 loops, best of 3: 350 µs per loop

I'm looking for any suggestions on how to improve this code. I suspect there is a better way to do the mergelist function, particularly in how I tried to avoid code duplication like:

if top_a <= top_b:
    nl.append(top_a)
    try:
        top_a = next(it_a)
    except:
        ...
else:
    # duplicates above code

In my code I placed the iterators and first values in a list, then use the variable k as index, but this leads to hacks like abs(k-1) and placing magic numbers 0 and 1 in the code.

def mergesort(l, key=None):
    # Split the list into sublists of length 1
    sublists = [[x] for x in l]

    while len(sublists) > 1:
        new_sublists = []

        # Create a generator that yields two sublists at a time
        sublists_pairs = ((sublists[2*x], sublists[2*x+1])
                          for x in range(len(sublists)//2))

        for a, b in sublists_pairs:
            new_sublists.append(mergelist(a, b, key))

        # If the length is odd, then there is one sublist that is not merged
        if len(sublists) % 2 != 0:
            new_sublists.append(sublists[-1])

        sublists = new_sublists

    return new_sublists[0]

def mergelist(a, b, key=None):

    nl = []

    # Iterators that yield values from a and b
    its = iter(a), iter(b)

    # The top of both lists
    tops = [next(it) for it in its]

    while True:
        # Determine the iterator that the next element should be taken from
        if key:
            k = 0 if key(tops[0]) <= key(tops[1]) else 1
        else:
            k = 0 if tops[0] <= tops[1] else 1
        nl.append(tops[k])

        try:
            # Update the top of the iterator
            tops[k] = next(its[k])
        except StopIteration:
            # Unless the iterator is empty, in which case get the rest of
            # the values from the other iterator
            # abs(k-1) is similar to (0 if k == 1 else 1)
            nl.append(tops[abs(k-1)])
            for e in its[abs(k-1)]:
                nl.append(e)

            return nl


texts: Run query and insert the result to another table

texts:
import csv
import logging
import itertools
from random import choice
from string import ascii_lowercase
from collections import namedtuple
from tempfile import NamedTemporaryFile

DELIMITER = '\t'
ENCODING = 'utf-8'

def get_random_cursor_name(length=7):
    return ''.join(choice(ascii_lowercase) for i in range(length))

def extract_table(conn, query, itersize=2000, use_named_cursor=True):
    """
    :type conn: psycopg2.connection
    :param conn: connection object returned by psycopg2.connect.

    :type query: string
    :param query: SQL query string.

    :type itersize: int
    :param itersize: If itersize == -1, then fetchall, else fetchmany(itersize)

    :type use_named_cursor: boolean
    :param use_named_cursor: If true, then use server side cursor, else client side cursor.
    """

    if use_named_cursor:
        cursor_name = get_random_cursor_name()
        with conn.cursor(cursor_name) as cursor:
            cursor.itersize = 2000 if itersize == -1 else itersize
            cursor.execute(query)
            row = cursor.fetchone()

            header = [desc[0] for desc in cursor.description]
            Row = namedtuple('Row', header)

            yield Row(*row)
            for row in cursor:
                yield Row(*row)
    else:
        with conn.cursor() as cursor:
            cursor.execute(query)
            header = [desc[0] for desc in cursor.description]
            Row = namedtuple('Row', header)
            if itersize == -1:
                rows = cursor.fetchall()
            else:
                cursor.arraysize = itersize
                rows = itertools.chain.from_iterable(iter(cursor.fetchmany, []))

            for row in rows:
                yield Row(*row)

def copy_table(src_conn, dst_conn, src_query, dst_table_name, use_named_cursor=False, truncate_table=False):
    """
    Run query and import result to another database.

    We use null="" in copy_from, because csv library dumps None as "" (empty string).

    :type src_conn: psycopg2.connection
    :param src_conn: Source database connection.

    :type dst_conn: psycopg2.connection
    :param dst_conn: Destination database connection.

    :type src_query: string
    :param src_query: Query to be executed on source database.

    :type dst_table_name: string
    :param dst_table_name: Table name in destination database.
    """
    rows = extract_table(src_conn, src_query, use_named_cursor=use_named_cursor)
    with NamedTemporaryFile('w+t', encoding=ENCODING, newline='') as fp, dst_conn.cursor() as cursor:
        logging.info("Writing result to a temporary file.")
        csv.writer(fp, delimiter=DELIMITER).writerows(rows)
        fp.flush()
        fp.seek(0)

        if truncate_table:
            logging.info("Truncating {}.".format(dst_table_name))
            cursor.execute('TRUNCATE {};'.format(dst_table_name))
        logging.info("Copying result to {}".format(dst_table_name))
        cursor.copy_from(file=fp, table=dst_table_name, sep=DELIMITER, null="")
    dst_conn.commit()

This code, in particular copy_table, is used to run a query, write the result to a temporary CSV file and copy the result to a table.

An example of the usage is as follows:

Let's say you want to copy a subset of the table public.my_table in DB1 to DB2.

import psycopg2
import credentials

src_conn = psycopg2.connect(
    database=credentials.DB1_DB,
    user=credentials.DB1_USER,
    password=credentials.DB1_PASS,
    host=credentials.DB1_HOST,
    port=credentials.DB1_PORT
)

dst_conn = psycopg2.connect(
    database=credentials.DB2_DB,
    user=credentials.DB2_USER,
    password=credentials.DB2_PASS,
    host=credentials.DB2_HOST,
    port=credentials.DB2_PORT
)

query = 'SELECT * FROM public.my_table where product_count > 200'

copy_table(src_conn, dst_conn, src_query=query, dst_table_name='public.my_table_subset')

How could I write this code to be more Pythonic?

Note that I'm using Python 3.5.


texts: Translating sentences with an API wrapper

texts:
I've written a wrapper for this handy Yandex Translate API. I am pretty happy with is as it works just fine and the translations are accurate, even translations of entire sentences. However, I am curious if there is a better way to put the wrapper together, what would you do differently and what could be improved? I'll take any remarks there is.

import requests
from requests.exceptions import ConnectionError

class YandexException(Exception):
    """Common API wrapper exception."""
    pass

class Yandex:
    """YandexTranslate API wrapper."""

    API_VERSION = 'v1.5'
    URL = 'https://translate.yandex.net/api/v1.5/tr.json/'

    def __init__(self, api_key):
        """Use an API key provided by Yandex.
        To obtain a key, visit https://translate.yandex.com/developers
        """
        self.api_key = api_key
        self._session = requests.Session()

    @property
    def supported_languages(self):
        """Return a dictionary of currently supported languages.
        All languages are represented using ISO 639-1 language codes.
        """
        payload = {
            'ui': 'en',
            'key': self.api_key
        }
        try:
            response = self._session.get(self.URL + 'getLangs', params=payload)
            if response.status_code != 200:
                raise YandexException(response.json())
            return response.json().get('langs')
        except ConnectionError:
            raise YandexException('API unavailable')

    def _get_translate_direction(self, source, target):
        """Raise an exception if source and target language are not currently
        supported by the Yandex Translate API.
        """
        if source and target in self.supported_languages:
            return '{}-{}'.format(source, target)
        if source is None and target in self.supported_languages:
            return target
        raise YandexException('language direction not supported')

    def translate(self, text, target='en', source=None):
        """Return translated text.

        Translated text may be inaccurate if source language is not specified.
        This is because the API will try to detect source language, if the
        relevant argument is None.

        Text will be translated to English by default.

        Only use ISO 639-1 language codes with this method.
        """
        translate_direction = self._get_translate_direction(source, target)
        payload = {
            'text': text,
            'format': 'plain',
            'lang': translate_direction,
            'key': self.api_key
        }
        try:
            response = self._session.post(self.URL + 'translate', data=payload)
            if response.status_code != 200:
                raise YandexException(response.json())
            return response.json().get('text')[0]
        except ConnectionError:
            raise YandexException('API unavailable')

    def detect_language(self, text):
        """Return language of passed in text as a ISO 639-1 language code."""
        payload = {
            'text': text,
            'format': 'plain',
            'key': self.api_key
        }
        try:
            response = self._session.post(self.URL + 'detect', data=payload)
            if response.status_code != 200:
                raise YandexException(response.json())
            return response.json().get('lang')
        except ConnectionError:
            raise YandexException('API unavailable')

if __name__ == '__main__':
    t = Yandex(api_key)
    print(t.translate('Piękne jest lepsze niż brzydsze'))
    # => Beautiful is better than ugly


texts:
I have this version comparison function in java.

Any cleaner way to write this without all the nested 'if' statements?

Note that the suggestions must be in Java code only.

@Override
public int compareTo(Version o)
{
    int result = this.major.compareTo(o.major);
    if (result == 0)
    {
        result = this.minor.compareTo(o.minor);
        if (result == 0)
        {
            result = this.minor2.compareTo(o.minor2);
            if (result == 0)
            {
                result = this.suffix.compareTo(o.suffix);
            }
        }
    }

    return result;
}

Edit:

Just to be clear on the 'type' of the fields of the Version class:

Integer major, minor, minor2;
String suffix;


texts: More elegant way to construct the S3 path name with given options

texts:
I have a method that generates the S3 key prefix according to the provided args. However, my gut feeling is that this method is not as elegant as it should be, maybe I just don't have an eye for it. Care to instruct me on how to make this little bit less sketchy?

private String generateFullQualifiedS3KeyPrefix(DataStream dataStream, Options options) {
    String environmentName, applicationName, streamName = applicationName = environmentName = null;
    if (dataStream != null) {
        environmentName = dataStream.getEnvironmentName();
        applicationName = dataStream.getApplicationName();
        streamName = dataStream.getStreamName();
    }
    String year, month, date, groupById = date = month = year = null;
    if (options != null) {
        year = String.valueOf(options.getYear());
        month = String.format("%02d", options.getMonth());
        date = String.format("%02d", options.getDate());
        groupById = options.getGroupById();
    }

    String[] arr = new String[]{environmentName, applicationName, streamName, groupById, year, month, date};
    StringJoiner filePath = new StringJoiner("/");
    for (int i = 0; i < arr.length; i++) {
        if (arr[i] == null) {
            break;
        }
        filePath.add(arr[i]);
    }
    return filePath.toString() + "/";
}


texts:
I wrote the following code to permute the characters of a string assuming there is no repeated character.

I also want to make sure the space complexity of this algorithm is \$O(n*n!)\$: There are \$n!\$ recursive calls, for each of these calls, I copy a string of size \$n\$. Am I right?

Time complexity: \$O(n!)\$: \$n!\$ recursive calls

Is it possible to make it more efficient?

  public static void permute(String str, String prefix){
    if (str.length() == 0) System.out.println(prefix);

    for (int i = 0; i < str.length(); i++){
      String c = Character.toString(str.charAt(i));
      String rest = str.substring(0, i) + str.substring(i+1);
      permute(rest, prefix + c);
    }

  }


texts: canonical pattern for transactional library state manipulation

texts:
In golang I am finding that there is a definite pressure in the language itself and built-in libraries to do things in a canonical way.  Please can someone critically look at these two ways I am considering using to provide transactional synchronisation of state manipulation within a library and provide me with some feedback.

All state manipulation functions of the library (i.e. all but a couple helper functions) would use this pattern and there would be over a dozen non-trivial functions that require transactional operation.  Method 1 is what I would usually have done in C# but the official golang blog almost seems to be implying this is an anti-pattern.

Method 1 - C# lock pattern https://play.golang.org/p/XS14fM_XUg

gobyexample.com/mutexes

package main

import (
    "fmt"
    "sync"
)

type ILibraryState interface {
    DoSomething(arg int) error
}

type LibraryState struct {
    lock *sync.Mutex
    // Some private state
}

func (l *LibraryState) DoSomething(arg int) error {
    // Do some arg check

    // Transactional synchronisation
    l.lock.Lock()
    defer l.lock.Unlock()

    // Do something
    fmt.Println("Hello, playground")
    return nil;
}

func NewLibrary() ILibraryState {
    lib := LibraryState{}
    lib.lock = &sync.Mutex{}
    return &lib
}

func main() {
    l := NewLibrary()
    l.DoSomething(5)
}

Method 2 - Hidden goroutine and single command queue https://play.golang.org/p/3vWQJDswJm

http://gobyexample.com/stateful-goroutines
http://blog.golang.org/share-memory-by-communicating
http://blog.golang.org/advanced-go-concurrency-patterns

package main

import (
    "fmt"
)

type ILibraryState interface {
    DoSomething(arg int) error
}

type LibraryState struct {
    command  chan (interface{})
    response chan (interface{})
    // Some private state
}

type commandDoSomething struct {
    arg int
}

func (l *LibraryState) DoSomething(arg int) error {
    // Do some arg check

    // Perform operation transactionally
    l.command <- commandDoSomething{arg}
    res := <-l.response
    if res == nil {
        return nil
    }
    return res.(error)
}

func (l *LibraryState) reallyDoSomething(arg int) {
    // Do something
    fmt.Println("Hello, playground")
    var err error = nil
    l.response <- err
}

func (l *LibraryState) processCommands() {
    for {
        switch c := (<-l.command).(type) {

        case commandDoSomething:
            l.reallyDoSomething(c.arg)
        }
    }
}

func NewLibrary() ILibraryState {
    lib := LibraryState{}
    lib.command = make(chan (interface{}))
    lib.response = make(chan (interface{}))
    go lib.processCommands()
    return &lib
}

func main() {
    l := NewLibrary()
    l.DoSomething(5)
}


texts: Return list with numbers of color occurrences in another list

texts:
I'm solving "mastermind game" problem from CIS haskell course. Here is the link to assignment pdf if someone is interested.

List of possible colors is defined like this:

data Peg = Red | Green | Blue | Yellow | Orange | Purple
     deriving (Show, Eq, Ord)
type Code = [Peg]
colors :: [Peg]
colors = [Red, Green, Blue, Yellow, Orange, Purple]

And I had to write a function that will take a list with color guesses and return the occurrence count for each available color in the form of a list.

countColors :: Code -> [Int]
countColors a        = map (\(x,y) -> length $ filter (x==) y) combo
      where combo    = zip colors (take 6 $ repeat a)

It works fine but I'd like to know if there is better/more expressive way to write it (using most basic available functions).

I'm not sure what's good practice in Haskell; that is my main problem. I have tried to write in point free notation at first but it looked overly complicated.

My worry is that code is not clear enough. I like to have code that is as obvious as possible.

Here are test cases in case it helps:

countColors [Red, Blue, Yellow, Purple] == [1, 0, 1, 1, 0, 1]
countColors [Green, Blue, Green, Orange] == [0, 2, 1, 0, 1, 0]


texts: Sending periodic heartbeats, wondering if there are any timer bugs

texts:
What?

heartbeatjs is a small light weight library that helps you run periodic heartbeat functions and detects timeouts when they occur by launching events.

It was mainly designed for tcp/ip connections, but you can use it with any protocol you want as it designed to be generic.

Project

The project page, with examples and documentation can be  seen here:

https://fl4m3ph03n1x.github.io/heartbeatjs/index.html

Code

This library is mostly a collection of getters and setters mixed with some timers. I would like a second opinion regarding the code and any possible bugs one may find, as I am about to release the next version next week.

const isFunction = require("lodash.isfunction");

const DEFAULT_TIMEOUT = 5000;
const DEFAULT_INTERVAL = 3000;

const heartBeatFactory = () => {

    let interval = DEFAULT_INTERVAL,
        timeout = DEFAULT_TIMEOUT,
        ping,
        pong,
        timer,
        lastHeartbeatTime,
        timeoutTimer,
        hasStarted = false;

    const events = {
        timeout: () => {}
    };

    const hasTimedOut = () =>
        Date.now() - lastHeartbeatTime > timeout;

    const getBeatInterval = () => interval;

    const setBeatInterval = newInterval => {
        if(isNaN(newInterval))
            throw new TypeError(`${newInterval} must be a Number.`);

        interval = newInterval;
    };

    const getBeatTimeout = () => timeout;

    const setBeatTimeout = newTimeout => {
        if(isNaN(newTimeout))
            throw new TypeError(`${newTimeout} must be a Number.`);

        timeout = newTimeout;
        clearTimeout(timeoutTimer);
        timeoutTimer = setTimeout(events.timeout, getBeatTimeout());
    };

    const getPing = () => ping;

    const setPing = newPing => {
        ping = newPing;
    };

    const getPong = () => pong;

    const setPong = newPong => {
        pong = newPong;
    };

    const receivedPong = () => {
        lastHeartbeatTime = Date.now();
        clearTimeout(timeoutTimer);
        timeoutTimer = setTimeout(events.timeout, getBeatTimeout());
    };

    const stop = () => {
        lastHeartbeatTime = undefined;
        clearInterval(timer);
        timer = undefined;
        clearTimeout(timeoutTimer);
        timeoutTimer = undefined;
    };

    const start = fn => {
        if (!isFunction(fn))
            throw new TypeError(`${fn} must be a function.`);

        hasStarted = true;
        lastHeartbeatTime = Date.now();
        timer = setInterval(fn, getBeatInterval());
        timeoutTimer = setTimeout(events.timeout, getBeatTimeout());
    };

    const onTimeout = fn => {
        if (!isFunction(fn))
            throw new TypeError(`${fn} must be a function.`);

        events.timeout = fn;
    };

    const isBeating = () => timer !== undefined;

    const reset = () => {
        if (isBeating())
            stop();

        if( hasStarted ){
            setBeatInterval(DEFAULT_INTERVAL);
            setBeatTimeout(DEFAULT_TIMEOUT);
            ping = undefined;
            pong = undefined;
            onTimeout(() => {});
        }
    };

    return Object.freeze({
        getBeatInterval,
        setBeatInterval,
        getBeatTimeout,
        setBeatTimeout,
        hasTimedOut,
        getPing,
        setPing,
        getPong,
        receivedPong,
        setPong,
        stop,
        start,
        reset,
        isBeating,
        onTimeout
    });
};

module.exports = heartBeatFactory;


texts:
I've built an anagram solver in Python 2.7. It goes through a text file with over 100,000 words and checks if any permutations of the input matches the line. It works great, except it is very slow. I've tried making the text file a list with each line as a list item, but the text file is too big to do that. This is the text file that I am using (it's saved on my flash drive).

# import permutations module
from itertools import permutations as prm

num_of_cases = int(raw_input("Input number of words needed to be unscrambled: "))
# take input
counter = 1
while counter <= num_of_cases:
   scrambled_word = list(str(raw_input("Input scrambled word: ")))

# empty lists that will be appended to later
   prm_list = []
   possible_words = []

# takes each permutation of the input and puts in a list
   for i in prm(scrambled_word):
      prm_list.append("".join(i))

   def check(x, y):

   # open list of words
      dictionary = file('E:\MRP\Text_Files\dictionary.txt')

      # check each line in the dictionary against each item
      # in the list of permutations and add it to another empty list if it's a match
      for line in dictionary:
         for i in x:
            if i+'\n' == line:
               y.append(i)

   check(prm_list, possible_words)

# delete duplicates
   possible_words = list(set(possible_words))

# print out possible words
   if len(possible_words) == 0:
      print "No matches found"
   else:
      for i in possible_words:
         print "Possible Word for Scrambled Word #" + str(counter) + ": " + i

# add to the counter
   counter+=1

If you test it out you can see that is very slow, especially as the words get larger. Is there anything I can do to improve the performance of this program?


texts: Quicksort using uniform_int_distribution to select the pivot

texts:
I have not used C++ for a while. Could you please tell me if my usage of the <random> module is correct? I am not sure if I need to be creating a new instance of uniform_int_distribution on each recursive call. I am not sure that I should be seeding the generator on each recursive call. I suspect these two actions need to happen somewhere outside but I do not know.

Other improvements are also welcome, of course.

#include <random>
#include <iterator>

using generator = std::mt19937;

template<typename iterator>
void quicksort(iterator fst, iterator lst) {
    if (fst >= lst) {return;}

    generator g(42);

    auto i = fst, j = lst;
    auto rval = std::uniform_int_distribution<>(0, std::distance(i, j));

    auto pivot = *(fst + rval(g));

    while (i <= j) {
        for (; *i < pivot; i++);
        for (; pivot < *j; j--);

        if (i <= j) {
            std::swap(*i++, *j--);
        }
    }
    quicksort(fst, j);
    quicksort(i, lst);
}

template<typename iterator>
void qsort(iterator begin, iterator end) {
    if (begin == end) {return;}
    quicksort(begin, end - 1);
}


texts: Looping through cells and deleting column

texts:
A quick description of what I want:

Loop through a particular cell row and it's columns
If any cell contains 0, then delete the entire column

So let's say 4,4 was 0, then delete that column (D)

My code works but takes a while

Dim lColumn As Long
Dim iCntr As Long
lColumn = 120
For iCntr = lColumn To 4 Step -1
If Cells(4, iCntr) = 0 Then
Columns(iCntr).Delete
End If
Next

Surely there is a faster way to do this.


texts: Simple word translator taking advantage of Wikipedia

texts:
This is my first Clojure script (simple word translator based on Wikipedia), and I guess there are things which could be simplified / done more idiomatic way. Specifically, I wonder if get-translations couldn't be done better (it produces map lang code => term form regexp sequence).

(ns wiki-translate
   (:require [clojure.contrib.http.agent :as h])
   (:require [clojure.contrib.string :as s])
   (:import (java.net URLDecoder URLEncoder))
)

(defn url-decode
  ([text] (URLDecoder/decode text "UTF-8"))
)

(defn url-encode
  ([text] (URLEncoder/encode text "UTF-8"))
)

(defn get-url
  ([lg term] (str "http://" lg ".wikipedia.org/wiki/" (url-encode term)))
)

(defn fetch-url
  ([url] (h/string (h/http-agent url)))
)

(defn get-translations
  ([cnt]  (apply sorted-map (flatten (for  [s (re-seq #"interwiki-([^\"]+).*wiki\/([^\"]+)\".*/a>" cnt)] [(s 1) (s 2)]))))
)

(defn translate
   ([term src-lg tgt-lg] (
    let [translations (get-translations (fetch-url (get-url src-lg term)))]
      (if (contains?  translations tgt-lg) (s/replace-str  "_" " " (url-decode (get translations tgt-lg))) "<NOT FOUND>")))
)

(defn prompt-read
  ([] (prompt-read ""))
  ([prompt] (print (format "%s: " prompt)) (flush ) (read-line))
)

(defn prompt-translate
  ([] (let [src-lg (prompt-read "Source language (en, fr, de ...)") tgt-lg (prompt-read "Target language  (en, fr, de ...)") term (prompt-read "Term to translate")]
  (println (str "\"" term "\" translated from " src-lg " to " tgt-lg " : " (translate term src-lg tgt-lg)))))
)

(while true (prompt-translate))


texts: Displaying a random poem from a database

texts:
I'm new to web development, and I'm constantly torn between good code and bad code. I was wondering if you could help me improve my following code and see if I'm doing it right in terms of how I use it on the line by line basis: - t code checks to see if a cookie exists if it doesnt exist it sets a cookie to last for 23 hours and 30 minutes after the cookie is set it pulls a random poem from a database using and and sets it on page to be displayed if the user visits the page more than once and the cookie is set no data will be retrieved and leave old data till the cookie expires -

<?php

if (@!$_COOKIE['true']){
    setcookie('true','true',time()+86100);

    $timeCheck = date('H:i', strtotime('23:30:00'));

    $currentTime = date('H:i', time());
    if ($currentTime >= $timeCheck){
            require_once 'upload/mysqlserver/login.php';

    $query = "SELECT * FROM poems";
    $queryRun = mysql_query($query);
     if ($queryRun = mysql_query($query)){
                // getting data
                if (mysql_num_rows($queryRun)== NULL){
                   echo "No poems in DataBase";
                }else{
                    $randNum = mysql_num_rows($queryRun);
                    $maxNum = rand(1, $randNum);

                    $query2 = "SELECT poem_name, poem, author, time_posted FROM poems WHERE id=$maxNum";
                    $queryRun2 = mysql_query($query2);

                        $row = mysql_fetch_assoc($queryRun2);
                        $poemName = $row['poem_name'];
                        $poem = $row['poem'];
                        $author = $row['author'];
                        $time_posted = $row['time_posted'];

                        $PoTDset = $poemSet = "

Poem name:

".$poemName ."

"
                        ."
Poem:

"."
".$poem."

"
                        ."
Author:
 ".$author."
"
                        ."
Posted on:
".$time_posted."

";

                        $handle = fopen('navigation/PoTD/setPoTD.php', 'w');
                        fwrite($handle, "<?php"."\n"."return ".'"'.$PoTDset.'"'."\n".";\n?>");
                        @fclose($handle);

                 }
            }
        }
}

$pageTemp->content .= include_once "navigation/PoTD/setPoTD.php";
?>


texts:
# Comment: You can iterate through any number of Enumerables in lockstep

e = {
  numbers:   1..10,
  letters:   %w(a b c d e f g h i j),
  notes:     %w(do re mi fa so la ti do),
  phonetic:  %w(alpha bravo charlie delta echo),
  rainbow:   %w(red orange yellow green blue indigo violet)
}

# Titles
puts e.keys.map(&:capitalize).join(" ")

# Values
e.first[1].zip(*e.values[1..-1]) do |layer|
  layer.zip(e.keys) do |node|
    print node[0].to_s.rjust(node[1].length), " "
  end
  puts
end

This code produces the following output:

Numbers Letters Notes Phonetic Rainbow
      1       a    do    alpha     red
      2       b    re    bravo  orange
      3       c    mi  charlie  yellow
      4       d    fa    delta   green
      5       e    so     echo    blue
      6       f    la           indigo
      7       g    ti           violet
      8       h    do
      9       i
     10       j

I want to tighten up that double loop at the bottom. Can I get rid of the puts that I am using to have each table row on its own line?


texts:
when we need to add some javascript code to html, where we have to put it?

What is the best practice:

in line:

<script type="text/javascript">document.write(new Date().getFullYear())</script>

or centralized:

<header><script type=text/javascript> document.getelementbyid('someid').innerhtml='date'.....</script></header>


texts:
Is there a more succinct way to write code like this that has a lot of sharing between branches of the case statement?

(This is the main part of my solution to one of the Round 1 problems of the Facebook Hacker Cup 2012. The round is over.)

type Memoizable a = a -> a

recoveries :: Int -> Memoizable (String -> Int)
recoveries m = go
  where go self ('0':_) = 0
        go self [] = 1
        go self ss = flip rem 0xfaceb00c $ case analysis ss of
          HasMany
            | cValid -> cCase + bCase + aCase
            | bValid -> bCase + aCase
            | aValid -> aCase
          Has2
            | bValid -> bCase + aCase
            | aValid -> aCase
          Has1
            | aValid -> aCase
          _
            | otherwise -> 0
          where a = digitToInt (first ss)
                b = a * 10 + digitToInt (second ss)
                c = b * 10 + digitToInt (third ss)
                aValid = a <= m
                bValid = b <= m
                cValid = c <= m
                aCase = self (drop 1 ss)
                bCase = self (drop 2 ss)
                cCase = self (drop 3 ss)

-- not to be confused with functions of same name from Control.Arrow
first (x:_) = x
second (_:x:_) = x
third (_:_:x:_) = x

data Analysis = Empty | Has1 | Has2 | HasMany

-- a dumb little function to help with safety and sharing
analysis :: [a] -> Analysis
analysis [] = Empty
analysis [_] = Has1
analysis [_,_] = Has2
analysis _ = HasMany


texts:
I need to filter projects using a searchbar, it should filter all properties of the projects with a few exceptions. It's working, but it's extremely slow, where can I make optimizations?
The "_" is from the library underscore.js

    <form>

            <input type="text" ng-model="searchText" class="form-control" placeholder="Suche..."/>

    </form>

       {{customer}}

Here's the filter:

.filter('searchProjects', ($rootScope, $filter) => {
    return (projects, query) => {
        if (projects) {
            var passFilter = projects.filter(p => {
                let backUpContacts = false;
                if (p) {

                    //If project has customer and customer has references, don't search in all of them
                    if (p.kunde && p.kunde.contacts) {
                        backUpContacts = p.kunde.contacts.concat([]);
                        //Only leave the selected Reference Contact in Customer's Contacts for Search
                        p.kunde.contacts = p.kunde.contacts.filter(contact => p.reference === contact.id);
                    }

                    //Search also for project leaders that have to be found first
                    let projectLeaders = [];
                    $rootScope.profiles.forEach(profile => {
                        profile.projects.forEach(role => {
                            if (role.project === p.id) {
                                let projectRole = role.masterData['Projektrolle'];
                                if (projectRole && ~projectRole.indexOf(864)) {
                                    projectLeaders.push(profile.firstName + " " + profile.lastName);
                                }
                            }
                        });
                    });
                    p["projectLeaders"] = projectLeaders;
                }
                let pContain = _.contains($filter('filter')(projects, query), p);
                delete p["projectLeaders"];
                if (backUpContacts) {
                    p.kunde.contacts = backUpContacts;
                }
                return pContain;
            });
            return passFilter;
        }
    };
})


texts: IUnitTest, INonCopyable, and IMapKey mixins

texts:
I am creating a boiler-plate namespace that will allow me to ensure proper coding practices are followed and avoid gotchas.

Looking over my code below; can you see any "no-no's" or gotchas? Can you also provide advice on anything I should do differently or add?

#ifndef PROJECT_INTERFACES_H_
#define PROJECT_INTERFACES_H_

// Ensure proper coding conventions are followed
namespace ProjectInterfaces
{
    class IUnitTest
    {
        protected:
            friend class RegressionTest;
            virtual bool unitTest() const = 0;
    };

    template <class T>
    class INonCopyable
    {
        protected:
            INonCopyable() { }
            ~INonCopyable() { }

        private:
            INonCopyable(const INonCopyable& iNoCopy);              // =  delete;  C++11
            INonCopyable& operator=(const INonCopyable& iNoCopy);   // =  delete;
            INonCopyable(INonCopyable&& iNoCopy);                   // = default;
            INonCopyable& operator=(INonCopyable&& iNoCopy);        // = default;
    };

    template <typename T>
    class IMapKey
    {
        public:
            virtual bool operator<(const T& other) const = 0;
    };
}

#endif // PROJECT_INTERFACES_H_

Code usage:

// Should these use virtual inheritence?
class MyClass : private INonCopyable<MyClass>, public IUnitTest, public IMapKey<MyClass>
{
  public:
      MyClass(const int& value) : value_(value)
      {

      }

      virtual bool operator<(const MyClass& other) const override
      {
          return value_ < other.value_;
      }

      const int getValue() const
      {
          return value_;
      }

  protected:
      virtual bool unitTest() const override
      {
          // ...
          return true;
      }

  private:
      int value_;
};


texts:
I would like to transform the input
elems = [a, b, c]
terms = [t1, t2]

@spec contains?(term, elem) :: boolean
def contains?(term, elem), do: #implementation

to either of
%{t1 => [a, b], t2 => [c]}

or
%{t1 => [a], t2 => [b, c]}

where
t1 |> contains?(a) #=> true
t1 |> contains?(b) #=> true
t1 |> contains?(c) #=> false

t2 |> contains?(a) #=> false
t2 |> contains?(b) #=> true
t2 |> contains?(c) #=> true

My current solution is as follows
defmodule Test do
  def contains?(term, elem) do
    elem in term
  end

  def test do
    elems = [1,2,3]
    terms = [[1,2], [2,3]]

    elems
    |> Enum.into(%{}, fn elem ->
      {elem,
       terms |> Enum.find(&contains?(&1, elem))}
    end)
    |> reverse_map()
  end

  defp reverse_map(map, reversed \\ %{})
  defp reverse_map(map, reversed) when map_size(map) == 0, do: reversed

  defp reverse_map(map, reversed) do
    [key | _] = Map.keys(map)
    {value, map} = Map.pop!(map, key)
    reversed = Map.update(reversed, value, [key], &[key | &1])
    reverse_map(map, reversed)
  end
end

With this solution I'm generating the map
%{a => t1, b => t1, c => t2}

then reversing it and collecting collisions in a list.
But I feel this intermediate map is unnecessary and a solution could exist without it.
In addition I'm not sure my implementation of reverse_map is as elegant as it could be.


texts:
I am doing a lot of stuff with JavaScript and jQuery lately, but am not heading for clean code too much, as I am usually writing userscripts or small applications for myself.

Recently, a community I am part of announced that it will change their supported BB-Codes, as the tabmenu BB-Code had a possible safety issue. By now, hundreds of posts have been done with tabmenus and a lot of users were complaining that editing all these posts will take forever.

As I am a guy who likes to automate as much stuff as possible, I took the task and developed a small application that changes posts with the tabmenu BB-Code into a format that is supported by the forum.

Here are two examples of what the application does:

Original BB-Code:

[tabmenu]
[tab=Tab1]Tab1 Text
[tab=Tab2]Tab2 Text
[/tabmenu]

Note: tabmenu has a closing tag, tab does not and will contain all text until the next tab or until the closing [/tabmenu].

Result:

[h]Tab1[/h]Tab1 Text
[h]Tab2[/h]Tab2 Text

h turn into headlines, just as in HTML and force a linebreak.

As the tabmenu does not only support tabs, but also subtabs, here is the second example:

Original BB-Code:

[tabmenu]
[tab=Tab1]
[subtab=Subtab11]Subtab11 Text
[subtab=Subtab12]Subtab12 Text
[tab=Tab2]
[subtab=Subtab21]Subtab21 Text
[/tabmenu]

Note: If you have subtabs in you tabmenu, you can't write text into tab areas. Apart from that subtabs behave like tabs when getting their content.

Result:

[h]Tab1[/h]
[spoiler=Subtab11]Subtab11 Text
[/spoiler][spoiler=Subtab12]Subtab12 Text
[/spoiler][h]Tab2[/h]
[spoiler=Subtab21]Subtab21 Text
[/spoiler]

tabs are still being replaced with h. The behavior for subtabs is a bit different though. Here my application is taking the title from the subtab, turning it into a spoiler-Tag (not comparable with the spoiler-codes of Stack Exchange, the spoiler-BB-Code is more like an accordion) and placing the content of the subtab between the opening spoiler-Tag and the closing one.

$(function () {
    $('#buttonGenerate').on('click', function () {
        // The format of titles can be like this: [tab=Title], [tab="Title"] & [tab='Title']
        // the user can choose the format with this checkbox
        var bbFormat = $('input[name=bbCodeFormat]:checked').val();
        var titleTemplate;
        var regexTab;
        var regexSubTab;

        switch (bbFormat) {
            // Depending on which format was chosen, different regex patterns are used
            case '1':
            // Format: [tab=Title], allows certain special chars in the title
                regexTab = /\[tab=((\w|[ äöüÄÖÜ,.\-;:_#'+*!"§$%&/()=?ß^°])*)\]/g;
                regexSubTab = /\[subtab=((\w|[ äöüÄÖÜ,.\-;:_#'+*!"§$%&/()=?ß^°])*)\]((.|\s)+?((?=\[subtab)|(?=\[\/tabmenu)|(?=\[tab)))/g;
                titleTemplate = '###';
                break;
            // Format: [tab="Title"] allows any special chars in the title
            case '2':
                regexTab = /\[tab="((.| )*)"\]/g;
                regexSubTab = /\[subtab="((.| )*)"\]((.|\s)+?((?=\[subtab)|(?=\[\/tabmenu)|(?=\[tab)))/g;
                titleTemplate = '"###"';
                break;
            // Format: [tab='Title'] allows any special chars in the title
            case '3':
                regexTab = /\[tab='((.| )*)'\]/g;
                regexSubTab = /\[subtab='((.| )*)'\]((.|\s)+?((?=\[subtab)|(?=\[\/tabmenu)|(?=\[tab)))/g;
                titleTemplate = "'###'";
                break;
        }

        // Gather original BB-Code from textarea
        var input = $('#inputArea').val();

        // Replace the tabmenu BB-Code via Regex
        input = input.replace(regexSubTab, '[spoiler=' + titleTemplate.replace('###', '$1') + ']$3[/spoiler]');
        input = input.replace(regexTab, '[h]$1[/h]');
        input = input.replace('[tabmenu]', '').replace('[/tabmenu]', '');
        $('#outputArea').val(input.trim());
    });
});


texts: Finding the length of shortest transformation sequence from start to end

texts:
Please treat this as a interview at a top tech firm, and share your thoughts on how you think I did. Be honest, and leave no stone unturned.

  Problem:

  Given two words (start and end), and a dictionary, find the length of
  shortest transformation sequence from start to end, such that:

  Only one letter can be changed at a time.  Each intermediate word must
  exist in the dictionary

  For example,

  Given:

  start = "hit"
  end = "cog"
  dict = ["hot","dot","dog","lot","log"]

  As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" ->
  "cog", return its length 5.

  Note:

  Return 0 if there is no such transformation sequence.
  All words have the same length.
  All words contain only lowercase alphabetic characters.

Time Complexity: \$O(n^2)\$ (please confirm)

Space complexity: \$O(n)\$

My code:

   private static int ladderLength(String start, String end, HashSet<String> dict) {
        Deque<String> wordSearch = new ArrayDeque<>();
        Deque<Integer> lengthCount = new ArrayDeque<>();
        wordSearch.add(start);
        lengthCount.add(1);
        while(!wordSearch.isEmpty()){
            String analyzing  = wordSearch.poll();
            int curCount = lengthCount.poll();
            if(analyzing.equals(end)){
                return curCount;
            }
            for(int j = 0; j < analyzing.length(); j++){
                for(char i = 'a'; i <= 'z'; i++){
                    char[] possibleMatch = analyzing.toCharArray();
                    possibleMatch[j] = i;
                    String checkMatch = new String(possibleMatch);
                    if(dict.contains(checkMatch)){
                        dict.remove(checkMatch);
                        lengthCount.add(curCount + 1);
                        wordSearch.add(checkMatch);
                    }
                }
            }
        }
        return 0;
   }


texts:
This is a JUnit asserts for this function:

    assertEquals(0, obj.generateListSize(0));
    assertEquals(1, obj.generateListSize(1));
    assertEquals(1, obj.generateListSize(2));
    assertEquals(3, obj.generateListSize(3));
    assertEquals(3, obj.generateListSize(4));
    assertEquals(5, obj.generateListSize(5));
    assertEquals(5, obj.generateListSize(6));
    assertEquals(7, obj.generateListSize(7));
    assertEquals(7, obj.generateListSize(8));
    assertEquals(7, obj.generateListSize(9));
    assertEquals(10, obj.generateListSize(10));
    assertEquals(10, obj.generateListSize(11));
    assertEquals(10, obj.generateListSize(12));

and this is my implementation:

public int generateListSize(int listSize) {
        int result;
        if (listSize < 1) {
            result = 0;
        } else if (7 < listSize && listSize < 10) {
            result = 7;
        } else if (10 <= listSize) {
            result = 10;
        } else if (listSize % 2 == 0) {
            result = listSize - 1;
        } else {
            result = listSize;
        }
        return result;
    }

This function is use to truncate list to 1,3,5,7,10 elements.
When list has 8 elements then return is 7.


texts:
I have written some jQuery which validates a group of drop downs.  It checks the text value selected in all the drop downs (first three characters), and if there is a duplicate, it warns the user.

This code seems quite messy, I was wondering if anyone would like to attempt to refactor this.  Tips for improvement are welcome.

Here is the link to the Fiddle.

My main function:

          function validateTeam(section) {
          //array for storing selected nationalities:
          var $selectionArr = [];

          $('#' + section + '> .form-group select').each(function () {

              //strip the selected text:
              var $optText = $(this).find('option:selected').text().substr(0, 3);

              if ($optText.length == 3) {
                  $selectionArr.push($optText);
              }
          });

          //unique array of nationalities:
          var result = [];

          $.each($selectionArr, function (index, value) {
              if ($.inArray(value, result) == -1) {
                  result.push(value);

                  if (result.length == 5) {
                      $('#warning').removeClass('label-danger').addClass('label-success').text('Thank you - your selection is valid!');
                  } else {
                      $('#warning').text('');
                  }

              } else {
                  //console.log(value);
                  $('#warning').addClass('label-danger').text('Warning! You have selected more than one players from the same nation (' + value + ')');
              }
          });
      };


texts:
I need to print (or store) all diagonals of a matrix. This includes the main diagonal ( { (i,i) | i = 1, 2, ... min(m,n) } ). Then all super and sub diagonals.

For example:

 1  2  3  4
 5  6  7  8
 9 10 11 12
13 14 15 16

The diagonals should be (order doesn't matter):

[
    [1, 6, 11, 16],
    [2, 7, 12],
    [5, 10, 15],
    [3, 8],
    [9, 14],
    [4],
    [13]
]

I believe I have a decent solution, but if there's a simpler / more efficient way to do this let me know. Input is assumed to be a list of lists as a NumPy array already has some methods to do this.

def print_diags(Matrix):
    m, n = len(Matrix), len(Matrix[0])
    for offset in range(min(m,n)):
        diag_upper = [row[i + offset]
                      for i, row in enumerate(Matrix)
                      if 0 <= i + offset < n]
        if offset != 0:
            diag_lower = [row[i - offset]
                      for i, row in enumerate(matrix)
                      if 0 <= i - offset < m]
            print(diag_upper, diag_lower)
        else:
            print(diag_upper)


texts: Getting all the UTC "day stamps" between 2 dates

texts:
I need to get every UTC day stamp in yyyy-MM-dd format (e.g. "2015-07-02") between any two arbitrary Date fields.

My first attempt is this:

public static Set<String> getUTCDayStringsBetween(Date startDt, Date endDt) {
    if (!startDt.before(endDt)) {
        throw new IllegalArgumentException("Start date (" + startDt + ") must be before end date (" + endDt + ")");
    }
    final TimeZone UTC = TimeZone.getTimeZone("UTC");
    final Calendar c = Calendar.getInstance();
    final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    sdf.setTimeZone(UTC);
    final Set<String> dayStrings = new LinkedHashSet<>();

    c.setTime(startDt);
    while (true) {
        dayStrings.add(sdf.format(c.getTime()));
        c.add(Calendar.DATE, 1);//add 1 day
        if (c.getTime().after(endDt)) {
            //reached the end of our range. set time to the endDt and get the final day string
            c.setTime(endDt);
            dayStrings.add(sdf.format(c.getTime()));
            break;
        }
    }
    return dayStrings;
}

It seems to work, but I'm wondering if there is a more efficient way to do it (aside from using external time libraries like Joda.).
Also, is there anything I'm glossing over in terms of handling time zones and day-light-savings changes appropriately.


texts: Making sure a block of code takes at least 5 seconds to execute

texts:
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?


texts:
Over the past couple of days I have been working on a super-basic text editor with Tkinter.

It can:

Open new files
Open files (general)
Save files

Obviously you can edit any file you open or make. This is very similar to this question, though I did not see that until I checked for duplicates of this question.

I did not use classes.

from Tkinter import *
import sys, os
import tkMessageBox
import error_mes
main = Tk()
#Variables that are globally needed
file_input = "" #whats put into the text box
_FILE_= "" #File the user wants to open; readapt to be synonymous with save?
open_a_file = "" #will be the entry field for opening a file
target = ""
new_file_ = ""
new_file_name = ""
isnewfile = "no"
def get_from_text():
    global file_input
    try:
        file_input = my_text_box.get("1.0", END)
        print file_input
    except:
        file_input = 'UHOH'
        print file_input

def save(): #This function can definitely be improved
    global file_input, target, _FILE_, my_text_box, new_file_name
    try:
        file_input = my_text_box.get("1.0", END)
        target = open(_FILE_, "r+w")
        target.truncate()
        target.write(file_input)
    except:
        file_input = my_text_box.get("1.0", END)
        target = open(new_file_name, "r+w")
        target.truncate()
        target.write(file_input)

def exit_application():
    sys.exit(0)

def menu_open_file():
    global _FILE_, open_a_file, save, my_text_box
    try:
        open_a_file = Entry()
        open_a_file.grid(row = 3, column = 0)
        open_a_file.insert(0, "Path to File to Open")
        #save.grid_forget()
        Button(main, text = "Click to Open", command = get_file).grid(row = 4,
                                                                    column = 0)
    except:
        error_mes.error()

def get_file():
    global _FILE_, open_a_file, my_text_box
    try:
        _FILE_ = open_a_file.get()
        target = open(_FILE_, "r+w")
        opened_file = target.read()
        try:
            my_text_box.insert(INSERT, opened_file)
        except:
            error_mes.error()
    except:
        error_mes.error()

def new_file():
    global new_file_, my_text_box
    my_text_box.delete("1.0", END)
    try:
        new_file_ = Entry()
        new_file_.grid(row = 3, column = 0)
        Button(main, text = "Click to Save", command = save_new_file).grid(row = 4,
                                                                    column = 0)
    except:
        error_mes.error()

def save_new_file():
    global new_file_, new_file_name, my_text_box, target
    new_file_name = new_file_.get()
    target = open(new_file_name, "w")
    target.write(my_text_box.get("1.0", END))

my_text_box = Text(main, bg = "black", fg = "white", insertbackground = "white",
                                                                tabs = ("1c"))
my_text_box.grid(row = 0, column = 0)
#The Menu
menu = Menu(main)
main.config(menu = menu)
filemenu = Menu(menu)
menu.add_cascade(label = "File", menu = filemenu)
filemenu.add_command(label = "New...", command = new_file)
filemenu.add_command(label = "Open...", command = menu_open_file)
filemenu.add_command(label = "Save", command = save)
filemenu.add_separator()
filemenu.add_command(label = "Exit", command = exit_application)
main.mainloop()

This code works fine in Linux, but when testing in Windows, the save command throws an error for some reason, but aside from that it works fine in both OSes.

My questions are:

How can my style be improved?
Is the code understandable? Did I use acceptable variable and function names?
Building off of that, are the FILE, FILE_, new_file etc, variables confusing?
Are classes necessary with a small program like this? Should I think about rewriting the code using object oriented programming if I want to add more features (such as syntax highlighting, python console, preset formats, etc)
Any suggested edits that would make my code either easier to read or more efficient?


texts:
I'm trying to create a function to return a DataTable with the results of a MySQL query where the program doesn't know the names of the queried columns until run-time.

How can I improve the readability of this function? Is concatenating strings like this an appropriate way to generate MySQL queries?

public static DataTable Entries(string db, string user, string dtStart, string dtEnd = "yyyy-MM-dd HH:mm:ss", List<string[]> column = null)
    {
            string mysqlTimestamp = "yyyy-MM-dd HH:mm:ss";
            string cmd = string.Format("SELECT * FROM `{0}`.`{1}_table` WHERE ", db, user);

            if (dtEnd != mysqlTimestamp)
            {
                cmd += "`Timestamp` >= @dtStart AND `Timestamp` <= @dtEnd";
            }
            else {
                cmd += "`Timestamp` = @dtStart";
            }

            if (column != null)
            {
                cmd += " AND";

                string colQuery = " `{0}` = @{0}";
                for (int i = 0; i < column.Count(); i++)
                {
                    cmd += string.Format(colQuery, column[i]);
                    if (i != column.Count() - 1) { cmd += " AND"; }
                }
            }

            var data = new DataSet();
            using (var MySql = Query.Connection(Session.Current.Username, Session.Current.Database))
            {
                MySql.Open();
                using (var MySqlCmd = new MySqlCommand(cmd, MySql))
                {
                    MySqlCmd.Parameters.AddWithValue("@dtstart", dtStart);
                    MySqlCmd.Parameters.AddWithValue("@dtEnd", dtEnd);
                    if (column != null)
                    {
                        foreach (string[] col in column)
                        {
                            MySqlCmd.Parameters.AddWithValue("@" + col[0], col[1]);
                        }
                    }

                    using (var Adapter = new MySqlDataAdapter(MySqlCmd))
                    {
                        Adapter.Fill(data);
                    }
                }
            }
            return data.Tables[0];
        }
    }

Results in the string:

SELECT * FROM `db`.`someuser_table` WHERE `Timestamp` >= @dtStart AND `Timestamp` <= @dtEnd AND `Column1` = @Column1 AND `Column3` = @Column3

or

SELECT * FROM `db`.`someuser_table` WHERE `Timestamp` >= @dtStart

and anything in between.


texts:
I couldn't quickly find Java code with googling to make serialized Json easier to read (this is a debugging library, obviously implementation code wouldn't use this as it's just more characters). This is not intended to be viewed in a web browser, this is intended for console output mostly.  I'm fairly new to Json (that's probably why I don't know where to look for this), is there a use case that my code is missing?

public class JsonWhitespace {
    public static String toWhiteSpace(String noWhite) {
        StringBuilder sb = new StringBuilder();

        int tabCount = 0;
        boolean inArray = false;

        for(char c : noWhite.toCharArray()) {
            if (c == '{') {
                sb.append(c);
                sb.append(System.lineSeparator());
                tabCount++;
                printTabs(sb, tabCount);
            } else if(c == '}') {
                sb.append(System.lineSeparator());
                tabCount--;
                printTabs(sb, tabCount);
                sb.append(c);
            } else if(c == ',') {
                sb.append(c);
                if (!inArray) {
                    sb.append(System.lineSeparator());
                    printTabs(sb, tabCount);
                }
            } else if (c == '[') {
                sb.append(c);
                inArray = true;
            } else if (c == ']') {
                sb.append(c);
                inArray = false;
            } else {
                sb.append(c);
            }
        }

        return sb.toString();
    }

    private static void printTabs(StringBuilder sb, int tabCount) {
        for(int i = 0; i < tabCount; i++) {
            sb.append('\t');
        }
    }
}


texts: Using d3.drag() to enable dragging on an SVG group

texts:
I'm using the following function to enable dragging on an SVG group.

var dragcontainer = d3.drag()
                        .on("start", function () { })
                        .on("drag", function (d, i) {

                            this.x = this.x || 0;
                            this.y = this.y || 0;

                            this.x += d3.event.dx;
                            this.y += d3.event.dy;
                            d3.select(this).attr("transform", "translate(" + this.x + "," + this.y + ")");

                        })
                        .on("end", function () {});

d3.select("#svg-group-id").call(dragcontainer);

Is there a better (simpler) way to achieve this than manually updating the translate destination?


texts: Realizing a SQL ResultSet into a Map in Scala

texts:
I am trying to realize a java.sql.ResultSet into a map, in Scala.

import java.sql.{ResultSet, ResultSetMetaData}

class DbRow extends java.util.HashMap[java.lang.String, Object] {
}

object freeFunctions {

  def realize(queryResult: ResultSet): Vector[DbRow] = {
    val md = queryResult.getMetaData
    val colNames = for (i <- 1 to md.getColumnCount) yield md.getColumnName(i)
    var rows: Vector[DbRow] = Vector.empty
    while (queryResult.next()) {
      val row = new DbRow
      for (n <- colNames) {
        row.put(n, queryResult.getObject(n))
      }
      rows = rows :+ row
    }
    rows
  }

}

I feel this could (should) be less verbose. If while/yield comprehensions existed, or some
comprehension for create a map. The client code needs a java map for now, but if an elegant
enough solution can produce a Scala map, I could convert it.


texts: Multi jQuery Sliders, Help me write this in better code

texts:
I have three sliders with different min, max values, everything is working fine from following the tutorials on the jQuery UI website.

$("#yield").slider({
    range: true,
    min: 15.2,
    max: 308,
    step: 0.3,
    values: [75.8, 241.4],

    slide: function (event, ui) {
        $("#yield-value").val(ui.values[0] + " - " + ui.values[1]);
    }
});
$("#yield-value").val($("#yield").slider("values", 0) + " - " + $("#yield").slider("values", 1));

$("#tensile").slider({
    range: true,
    min: 37.7,
    max: 345,
    step: 0.3,
    values: [81.2, 243.3],

    slide: function (event, ui) {
        $("#tensile-value").val(ui.values[0] + " - " + ui.values[1]);
    }
});
$("#tensile-value").val($("#tensile").slider("values", 0) + " - " + $("#tensile").slider("values", 1));

$("#elongation").slider({
    range: true,
    min: 1.0,
    max: 77,
    step: 0.1,
    values: [14.5, 43.2],

    slide: function (event, ui) {
        $("#elongation-value").val(ui.values[0] + " - " + ui.values[1]);
    }
});
$("#elongation-value").val($("#elongation").slider("values", 0) + " - " + $("#elongation").slider("values", 1));

here is my working fiddle here - http://jsfiddle.net/barrycorrigan/Sqg8A/1/

My problem is that I think my jQuery is written badly for multiple sliders.

Can anyone help me write this code better. Because there is only 3 sliders in the example but on the actual client website there is still 10 to go.

Any help to make my code cleaner somehow would be greatly appreciated.


texts:
I've got the following code where:

$urlParams is the school year from 7 to 11
$Comms['Overall'] is the total amount of "commendations" a student has

This code iterates through the numbers based on the school year to determine which "award" a student has got.

Is there a better way to write this code?

if($urlParams['y'] == 7){
    if((300 <= $Comms['Overall']) && ($Comms['Overall'] <= 599)){ $Award = "Bronze"; }
    elseif((600 <= $Comms['Overall']) && ($Comms['Overall'] <= 899)){ $Award = "Silver"; }
    elseif((900 <= $Comms['Overall']) && ($Comms['Overall'] <= 1199)){ $Award = "Gold"; }
    elseif((1200 <= $Comms['Overall']) && ($Comms['Overall'] <= 1499)){ $Award = "Platinum"; }
    elseif($Comms['Overall'] >= 1500){$Award = "Diamond";}
}

elseif($urlParams['y'] == 8){
    if((250 <= $Comms['Overall']) && ($Comms['Overall'] <= 549)){ $Award = "Bronze"; }
    elseif((550 <= $Comms['Overall']) && ($Comms['Overall'] <= 849)){ $Award = "Silver"; }
    elseif((850 <= $Comms['Overall']) && ($Comms['Overall'] <= 1099)){ $Award = "Gold"; }
    elseif((1100 <= $Comms['Overall']) && ($Comms['Overall'] <= 1299)){ $Award = "Platinum"; }
    elseif($Comms['Overall'] >= 1300){ $Award = "Diamond"; }
}

elseif($urlParams['y'] == 9){
    if((200 <= $Comms['Overall']) && ($Comms['Overall'] <= 449)){ $Award = "Bronze"; }
    elseif((450 <= $Comms['Overall']) && ($Comms['Overall'] <= 699)){ $Award = "Silver"; }
    elseif((700 <= $Comms['Overall']) && ($Comms['Overall'] <= 899)){ $Award = "Gold"; }
    elseif((900 <= $Comms['Overall']) && ($Comms['Overall'] <= 1099)){ $Award = "Platinum"; }
    elseif($Comms['Overall'] >= 1100){ $Award = "Diamond"; }
}

elseif($urlParams['y'] == 10){
    if((150 <= $Comms['Overall']) && ($Comms['Overall'] <= 399)){ $Award = "Bronze"; }
    elseif((400 <= $Comms['Overall']) && ($Comms['Overall'] <= 599)){ $Award = "Silver"; }
    elseif((600 <= $Comms['Overall']) && ($Comms['Overall'] <= 799)){ $Award = "Gold"; }
    elseif((800 <= $Comms['Overall']) && ($Comms['Overall'] <= 999)){ $Award = "Platinum"; }
    elseif($Comms['Overall'] >= 1000){ $Award = "Diamond"; }
}

elseif($urlParams['y'] == 11){
    if((150 <= $Comms['Overall']) && ($Comms['Overall'] <= 299)){ $Award = "Bronze"; }
    elseif((300 <= $Comms['Overall']) && ($Comms['Overall'] <= 499)){ $Award = "Silver"; }
    elseif((500 <= $Comms['Overall']) && ($Comms['Overall'] <= 699)){ $Award = "Gold"; }
    elseif((700 <= $Comms['Overall']) && ($Comms['Overall'] <= 849)){ $Award = "Platinum"; }
    elseif($Comms['Overall'] >= 850){ $Award = "Diamond"; }
 }


texts:
I am implementing RSA algorithm in C++ and here's my design(code structure).

keygen.h

namespace rsa{
    class keygen{
        public:
        //Constructor
        keygen(size);
        //Generate keys
        void generate();
        //Getters
        char* gete(){ return xyz; }
        ..
        ..
        ..

        private:
        //initializes bignums
        void initall();
        //Private Member variables goes here
   }
}

prime.h

namespace rsa{
    //First 100 primes
    unsigned int primes[]={2,3,5,7,11.....541};

    //MillarRabin Primality
    bool isPrime(mpz_t, unsigned short);
    //Get Random Prime
    void getPrime(mpz_t, mpz_t)
}

endec.h

namespace rsa{
    //Encryption
    const char* encryption(const char* text, const char* n, const char* e);
    //Decryption
    const char* decryption(const char* cipher, const char* n, const char* d);
}

Is this a good design? How can I make it better? I want to improve the structure or the overall design, that's why dint post any code. Things like naming standards, using classes wherever applicable, standard function signature and similar is what I'm looking for.


texts: Optimizing Perl script which looks for world-writable files

texts:
A script which scans a local filesystem and writes to a file a list of world-writable files found on the filesystem.

I ran it on a server with a couple terabytes of storage; not all of it used. In fact, only 195GB have been used. I'm not sure how many files there are, though.

The script takes 23 minutes to run. Is there something I can do to make it run faster?

#!/usr/bin/perl

use warnings;
use strict;
use Fcntl ':mode';
use File::Find;
no warnings 'File::Find';
no warnings 'uninitialized';

my $dir = "/var/log/tivoli/";
my $mtab = "/etc/mtab";
my $permFile = "world_writable_w_files.txt";
my $tmpFile = "world_writable_files.tmp";
my $exclude = "/usr/local/etc/world_writable_excludes.txt";
my $root = "/";
my (%excludes, %devNums);
my ($regExcld, $errHeader);

# Create an array of the file stats for "/"
my @rootStats = stat($root);

# Compile a list of mountpoints that need to be scanned
my @mounts;

open MT, "<${mtab}" or die "Cannot open ${mtab}, $!";

# We only want the local mountpoints
while (<MT>) {
  if ($_ =~ /ext[34]/) {
    my @line = split;
    push(@mounts, $line[1]);
  }
}

close MT;

# Build a hash of each mountpoint's device number for future comparison
foreach (@mounts) {
  my @stats = stat($_);
  $devNums{$stats[0]} = $_;
}

# Build a hash from /usr/local/etc/world_writables_excludes.txt
if ((! -e $exclude) || (-z $exclude)) {
  $errHeader = <<HEADER;
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!!                                                  !!
!! /usr/local/etc/world_writable_excludes.txt is    !!
!! is missing or empty. This report includes        !!
!! every world-writable file including those which  !!
!! are expected and should be excluded.             !!
!!                                                  !!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

HEADER

} else {
  open XCLD, "<${exclude}" or die "Cannot open ${exclude}, $!\n";
  while (<XCLD>) {
    chomp;
    $excludes{$_} = 1;
}

sub wanted {
  # Is it excluded from the report...
  return if (exists $excludes{$File::Find::name});

  # ...in a basic directory, ...
  return if $File::Find::dir =~ /sys|proc|dev/;

  # ...a regular file, ...
  return unless -f;

  # ...local, ...
  my @dirStats = stat($File::Find::name);
  return if (exists $devNums{$dirStats[0]});

  # ...and world writable?
  return unless (((stat)[2] & S_IWUSR) && ((stat)[2] & S_IWGRP) && ((stat)[2] & S_IWOTH));

  # If so, add the file to the list of world writable files
  print(WWFILE "$File::Find::name\n");

}

# Create the output file path if it doesn't already exist.
mkdir($dir or die "Cannot execute mkdir on ${dir}, $!") unless (-d $dir);

# Create our filehandle for writing our findings
open WWFILE, ">${dir}${tmpFile}" or die "Cannot open ${dir}${tmpFile}, $!";
print(WWFILE "${errHeader}") if ($errHeader);

find(\&wanted, @mounts);

close WWFILE;

# If no world-writable files have been found ${tmpFile} should be zero-size;
# Delete it so Tivoli won't alert
if (-z "${dir}${tmpFile}") {
  unlink "${dir}${tmpFile}";

} else {
  rename("${dir}${tmpFile}","${dir}${permFile}") or die "Cannot rename file ${dir}${tmpFile}, $!";

}


texts: Genetic algorithm for Clever Algorithms project

texts:
I wrote a bunch of Ruby code for a book project I've just finished. One criticism is that it is fine code but not very "ruby like". I agree my style was simplified for communication reasons, and although it's procedural code, it still feels "ruby-like" to me.

For the representative example below, any ideas on making it more "Ruby like"?

# Genetic Algorithm in the Ruby Programming Language

# The Clever Algorithms Project: http://www.CleverAlgorithms.com
# (c) Copyright 2010 Jason Brownlee. Some Rights Reserved.
# This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 2.5 Australia License.

def onemax(bitstring)
  sum = 0
  bitstring.size.times {|i| sum+=1 if bitstring[i].chr=='1'}
  return sum
end

def random_bitstring(num_bits)
  return (0...num_bits).inject(""){|s,i| s<<((rand<0.5) ? "1" : "0")}
end

def binary_tournament(pop)
  i, j = rand(pop.size), rand(pop.size)
  j = rand(pop.size) while j==i
  return (pop[i][:fitness] > pop[j][:fitness]) ? pop[i] : pop[j]
end

def point_mutation(bitstring, rate=1.0/bitstring.size)
  child = ""
   bitstring.size.times do |i|
     bit = bitstring[i].chr
     child << ((rand()<rate) ? ((bit=='1') ? "0" : "1") : bit)
  end
  return child
end

def crossover(parent1, parent2, rate)
  return ""+parent1 if rand()>=rate
  point = 1 + rand(parent1.size-2)
  return parent1[0...point]+parent2[point...(parent1.size)]
end

def reproduce(selected, pop_size, p_cross, p_mutation)
  children = []
  selected.each_with_index do |p1, i|
    p2 = (i.modulo(2)==0) ? selected[i+1] : selected[i-1]
    p2 = selected[0] if i == selected.size-1
    child = {}
    child[:bitstring] = crossover(p1[:bitstring], p2[:bitstring], p_cross)
    child[:bitstring] = point_mutation(child[:bitstring], p_mutation)
    children << child
    break if children.size >= pop_size
  end
  return children
end

def search(max_gens, num_bits, pop_size, p_crossover, p_mutation)
  population = Array.new(pop_size) do |i|
    {:bitstring=>random_bitstring(num_bits)}
  end
  population.each{|c| c[:fitness] = onemax(c[:bitstring])}
  best = population.sort{|x,y| y[:fitness] <=> x[:fitness]}.first
  max_gens.times do |gen|
    selected = Array.new(pop_size){|i| binary_tournament(population)}
    children = reproduce(selected, pop_size, p_crossover, p_mutation)
    children.each{|c| c[:fitness] = onemax(c[:bitstring])}
    children.sort!{|x,y| y[:fitness] <=> x[:fitness]}
    best = children.first if children.first[:fitness] >= best[:fitness]
    population = children
    puts " > gen #{gen}, best: #{best[:fitness]}, #{best[:bitstring]}"
    break if best[:fitness] == num_bits
  end
  return best
end

if __FILE__ == $0
  # problem configuration
  num_bits = 64
  # algorithm configuration
  max_gens = 100
  pop_size = 100
  p_crossover = 0.98
  p_mutation = 1.0/num_bits
  # execute the algorithm
  best = search(max_gens, num_bits, pop_size, p_crossover, p_mutation)
  puts "done! Solution: f=#{best[:fitness]}, s=#{best[:bitstring]}"
end


texts: Replacing characters in a Java string using iteration and recursion

texts:
I am new to the whole Data Structures thing and I want to get better at writing efficient code. So, I have been practicing some problem sets. The questions is - Replace characters in a string using iteration and recursion approach. I am still learning the whole recursion approach. But I tried to design an algorithm using the divide and conquer approach. I would like to know if there is any where I can fix my code and make it better.

I wrote the code using both approaches. Iteration and Recursion. I will be really thankful if I can get valuable pointers to improve my code and make it more efficient.

public class MainClass {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

         String text = "Hello World !"
                + "Hello";

         if(!text.isEmpty())
         {
         //Method 1 Iteration approach
         System.out.println("Replacing Characters using Iteration Approach");
         System.out.println(replace(text,'o','s'));

         //Method 2 Recursion approach
         char [] temp = new char[text.length()];
         temp = text.toCharArray();

        recursiveapproach(temp,0,temp.length,'o','s');
        System.out.println("Replacing characters using Recursion Approach");
        System.out.print(String.valueOf(temp));
         }

        else
        {
            System.out.println("Empty String");
        }

    }

    public static String replace(String str, char ch,char r)
    {
        char[] c = new char [str.length()]; // O(1);

            c = str.toCharArray(); //assuming it to be O(1)
            for(int i=0;i<c.length;i++)//O(n)
            {
                if(ch==c[i]) // O(1)
                {
                    c[i] = r; // O(1)
                }
            }

            //for(int i=0;i<c.length;i++)
                //System.out.print(c[i] + "\t");

        String s = String.valueOf(c); //// O(1)

        return s; //// O(1)

        // Time complexity is O(n) for the above code.

    }

     public static void replacechar(char[] a,int start,char c,char r)
        {

            if(a[start]== c)
            {
                a[start] = r;

            }
        }
        public static void recursiveapproach(char[] a,int start,int end,char c,char r)
        {

            int mid;

          int s = a.length-1;

            if(start<end)
            {
                mid = start + (end - start)/2;

                recursiveapproach(a,start,mid,c,r);

                recursiveapproach(a,mid+1,end,c,r);

            }

                if(start==end && start<=s)
                {

                replacechar(a,start,c,r);

                }

        }

}


texts:
This is an attempt at a fast "document distance" implementation in C++. For reference, I found this problem in MIT's OpenCourseware 6.006 algorithms course.

A quick look at the callgrind output shows that my performance killers are, in order:

the transfrom call in formatToken
Constructing inputString in wordOccurences
Indexing into the unordered_map (calling operator[])
reading from the stringstream in order to split the string

Here's the code:

#include <algorithm>
#include <fstream>
#include <functional>
#include <iostream>
#include <iterator>
#include <sstream>
#include <string>
#include <unordered_map>

using namespace std;

string const g_source      = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz1234567890";
string const g_destination = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";

bool containsKey(unordered_map<string, int> const &wordMap, string const &key)
{
    return wordMap.find(key) != wordMap.end();
}

template <typename ForwardIterator>
unordered_map<char, char> translationTable(
    ForwardIterator first,
    ForwardIterator last,
    ForwardIterator dFirst)
{
    unordered_map<char, char> table;

    for(; first != last; ++first, ++dFirst) {
        table[*dFirst] = *first;
    }

    return table;
}

void formatToken(string &rawString)
{
    static unordered_map<char, char> charTranslationTable = translationTable(
        g_source.begin(),
        g_source.end(),
        g_destination.begin());

    transform(
        rawString.begin(),
        rawString.end(),
        rawString.begin(),
        [](char c) { char ret = charTranslationTable[c]; return ret ? ret : ' '; });
}

unordered_map<string, int> wordOccurences(ifstream &is)
{
    unordered_map<string, int> result;
    string inputString{istreambuf_iterator<char>(is), istreambuf_iterator<char>()};
    formatToken(inputString);

    istringstream stream(inputString);
    string token;

    while (stream) {
        stream >> token;
        result[token] += 1;
    }

    return result;
}

double documentMagnitude(unordered_map<string, int> const &document)
{
    double magnitude = 0.0;

    for (auto const &word : document) {
        magnitude += double(word.second * word.second);
    }

    return sqrt(magnitude);
}

int main(int argc, char *argv[])
{
    string filename1 = arg[1];
    string filename2 = arg[2];

    ifstream file1(filename1);
    ifstream file2(filename2);

    unordered_map<string, int> document1 = wordOccurences(file1);
    unordered_map<string, int> document2 = wordOccurences(file2);

    double magnitude1 = documentMagnitude(document1);
    double magnitude2 = documentMagnitude(document2);

    double innerProduct = 0.0;

    for (auto const &word : document2) {
        if (containsKey(document1, word.first)) {
            innerProduct += double(word.second * document1[word.first]);
        }
    }

    double cosAngle = innerProduct / magnitude1 / magnitude2;

    cout << "Distance: " << acos(cosAngle) << '\n';
}

I'm running at speeds comparable to the CPython implementation from the aforementioned course. If I try to pre-allocate the string size to the stream-size, I get less than 1% improvement in performance.


texts: Fill an array of objects with some default object

texts:
I have an array of objects. Whatever may be the size of this array, I need to ensure the size of the array as n using a default object.

 function fillRemaining(arr, n) {
        var defaultObject = {'id' : 0, 'name' : ''};
        var temp = 0;
        while(arr.length + temp < n ) {
           var template = $.extend({}, defaultObject);
           template.id = new Date().getTime();
           arr.push(defaultObject);
           temp++;
        }
    }

Is there a better method of doing it?


texts: Outputting the names of cars, without repetitions, with the number of occurrences in order of decreasing repetitions

texts:
A short while ago, I have submitted a coding exercise to a
potential employer. The response came back the next
morning and you can guess what it was from the subject
of this post.

I am not totally at loss, but I need another programmer's
perspective. Is there anything that jumps out?

The idea of the exercise is simple: I'm given an input file with
names of cars, one per line,  possibly repeated and in no
particular order.

The program should output the same names, except with no
repetitions, the number of occurrences listed next to each
car, and in order of decreasing repetitions.

Example:

Honda\n Audi\n Honda\n -> Honda 2 \n Audi 1\n

#include <iostream>
#include <fstream>
#include <string>
#include <map>
#include <algorithm>
#include <cctype>

using namespace std;

// helper functions ///////////////////////////////////////

// reads lines from instream
void collect_lines(istream &in, map<string, int> &lines);

// given lines->num_occurs map, reverses mapping
void reorg_by_count(map<string, int> &lines,
                    multimap<int, string> &bycount);
///////////////////////////////////////////////////////////

int main(int ac, char* av[])
{
    istream *in;
    map<string, int> *lines = new map<string, int>();
    multimap<int, string> *lines_by_count = new multimap<int, string>();

    if (ac < 2)
    {
        in = &cin;
    }
    else
    {
        in = new ifstream(av[1]);
    }

    if (!in->good()) return 1;

    collect_lines(*in, *lines);
    reorg_by_count(*lines, *lines_by_count);

    if (in != &cin)
          {
        ((ifstream *)in)->close();
        delete in;
    }

    cout << "=====================\n\n";

    multimap<int, string>::reverse_iterator it
        = lines_by_count->rbegin();

    for (; it != lines_by_count->rend(); it++)
    {
        cout << it->second << " " << it->first << '\n';
    }

    delete lines;
    delete lines_by_count;

    return 0;
}

// Read the instream line by line, until EOF.
// Trim initial space. Empty lines skipped
void collect_lines(istream &in, map<string, int> &lines)
{
    string tmp;

    while (in.good())
    {
        getline(in, tmp);

        int i = 0;

        // trim initial space (also skips empty strings)
        for (i = 0; i < tmp.length() && !isalnum(tmp[i]); i++);
        if (i >= tmp.length()) continue;
        tmp = tmp.substr(i);

        for (i = 0; i < tmp.length(); i++)
        {
            if (!isalnum(tmp[i]))
            {
                tmp[i] = ' ';
            }

            // thus, HoNdA == Honda
            if (i == 0)
            {
                tmp[i] = toupper(tmp[i]);
            }
            else
            {
                tmp[i] = tolower(tmp[i]);
            }
        }

        // and record       the counts
        if (lines.count(tmp) == 0)
        {
            lines[tmp] = 0;
        }

        lines[tmp]++;
    }
}

// given lines->num_occurs map, reverses mapping
void reorg_by_count(map<string, int> &lines,
                                                                                multimap<int, string> &bycount)
{
    map<string, int>::iterator it = lines.begin();

    for (; it != lines.end(); it++)
    {
      bycount.insert(pair<int, string>(it->second, it->first));
    }
}


texts:
I've written some code to brute-force enumerate the solution space of nonogram puzzles up to a certain size. It does a good job up to the first ~4 billion puzzles, but I run out of disk space to store any bigger collection of the solution space set.

Because of some incredibly interesting patterns within the encoded set of solvable instances, I'd appreciate my code being reviewed for correctness. This is an NP-complete problem, but shows self-similarity and self-affinity in the solution space with the current implementation. Please, help me shoot down this idea as quickly as possible -- I'd like to regain a productive life :)

Here's how the code is supposed to work. It outputs an XYZ point cloud of the nonogram solution space given a puzzle's maximum width, great for visualization.

The code generates all the possible permutations of an arbitrarily sized boolean image. Each permutation is a puzzle solution to at least one, if not many, boolean image input pairs. The input pairs are "projections" of the solution from each lattice direction, while having the same axis-constrained continuous runs of set bits. The only difference between solution and input is very subtle: the unset padding between contiguous runs is flexible along an axis.

Here's an example pairing of inputs and solution. Note that the pictured top-right solution may not be unique for the given input images, and the given input images don't necessarily construct only that solution. It's merely an example of the "nonogram property."

You'll notice in the code I have a peculiar encoding of the inputs and solutions as integers, essentially a traversal of the image's cells converted to a bitstring. This encoding is chosen as a visualization convenience, and I've attained similar patterns with different traversal orders. The main goal with the encoding is to reduce dimensionality for plotting with a one-to-one correspondence of images to integers, avoiding the problem of colliding identifiers.

I'm including a montage of the first four iterations as subsets of the solution space shadow. The full shadow is essentially a look-up table for an NP oracle, so seeing patterns here could have remarkable consequences. Arranged from left to right are tables scaled to a common 512x512 resolution -- 4, 256, 262144, and 4294967296 puzzles accounted for, respectively. Each black pixel represents an input pair with no solution, white says a solution exists.

from sys import argv
from itertools import product, chain, groupby
from functools import partial
from multiprocessing import Pool

def indices(width):
    for a in range(width):
        for b in range(a+1):
            yield (b, a)
        for b in reversed(range(a)):
            yield (a, b)

def encode(matrix, width):
    return sum(1<<i for i, bit
               in enumerate(matrix[i][j] for i, j in indices(width))
               if bit)

def count_runs(row):
    return [sum(group) for key, group in groupby(row) if key]

def flex(solution, width):
    counts = list(map(count_runs, solution))
    for matrix in product((False, True), repeat=width**2):
        candidate = list(zip(*[iter(matrix)]*width))
        if list(map(count_runs, candidate)) == counts:
            yield candidate

def nonogram_solutions(solution, width):
    xy = solution
    yx = list(zip(*solution))
    enc_sol = encode(solution, width)
    return [(encode(xy, width), encode(yx, width), enc_sol)
            for xy, yx in product(flex(xy, width), flex(yx, width))]

def main(width):
    pool = Pool()
    sol_matrices = (list(zip(*[iter(matrix)]*width)) for matrix
                    in product((False, True), repeat=width**2))
    nonograms = partial(nonogram_solutions, width=width)
    solutions = pool.imap_unordered(nonograms, sol_matrices, 1)
    pool.close()
    for xy, yx, solution in chain.from_iterable(solutions):
        print(solution, xy, yx)
    pool.join()

if __name__ == "__main__":
    main(int(argv[1]))