texts: Cleaner way to handle double pointer in C++ BST?

texts:
I have an implementation for my first binary search tree in C++. I was wondering if there was some cleaner way to avoid using the double pointer in the way I have my code setup? Such as on one line I have:

(*node)->left = insert(&((*node)->left),value);

Which seems a bit "messy", but it almost seems necessary for the way I have implemented the BST. Maybe I am possibly missing a way I can change the syntax slightly to achieve the same result? I understand that I can have a double pointer as a parameter for my functions, but I have been told that it is not the standard in C++. I have my code posted below, along with how I am testing it.I am trying to prepare for technical interviews so any feedback is welcome.

#include<stdio.h>
#include<stdlib.h>
#include<iostream>
struct Node
{
    int data;
    Node *left, *right;
};

// A utility function to create a new BST node
Node* newNode(int data)
{
    Node *temp =  new Node();
    temp->data = data;
    temp->left = NULL;
    temp->right = NULL;
    return temp;
}

// A utility function to do inorder traversal of BST
void inorder(Node **root)
{
    if (*root != NULL)
    {
        inorder(&((*root)->left));
        printf("%d \n", (*root)->data);
        inorder(&((*root)->right));
    }
}

/* A utility function to insert a new node with given key in BST */
Node* insert(Node** node, int value)
{
    if(*node==NULL){
        return newNode(value);
    }
    if((*node)->data > value){
        (*node)->left = insert(&((*node)->left),value);
    }
    else if((*node)->data < value){
        (*node)->right = insert(&((*node)->right),value);
    }
    return *node;
}

// Driver Program to test above functions
int main()
{
    /* Let us create following BST
              50
           /     \
          30      70
         /  \    /  \
       20   40  60   80 */
    Node *root = NULL;
    root = insert(&root, 50);
    insert(&root, 30);
    insert(&root, 20);
    insert(&root, 40);
    insert(&root, 70);
    insert(&root, 60);
    insert(&root, 80);

    // print inoder traversal of the BST
    inorder(&root);

    return 0;
}

EDIT:
By changing " ** " in the parameters of the function to "*&" was able to make code much easier to read, with the same functionality.

#include<stdio.h>
#include<stdlib.h>
#include<iostream>
struct Node
{
    int data;
    Node *left, *right;
};

// A utility function to create a new BST node
Node* newNode(int data)
{
    Node *temp =  new Node();
    temp->data = data;
    temp->left = NULL;
    temp->right = NULL;
    return temp;
}

// A utility function to do inorder traversal of BST
void inorder(Node *&root)
{
    if (root != NULL)
    {
        inorder(((root)->left));
        printf("%d \n", (root)->data);
        inorder(((root)->right));
    }
}

/* A utility function to insert a new node with given key in BST */
Node* insert(Node*& node, int value)
{
    if(node==NULL){
        return newNode(value);
    }
    if((node)->data > value){
        node->left = insert(((node)->left),value);
    }
    else if((node)->data < value){
        (node)->right = insert(((node)->right),value);
    }
    return node;
}

// Driver Program to test above functions
int main()
{
    /* following BST
              50
           /     \
          30      70
         /  \    /  \
       20   40  60   80 */
    Node *root = NULL;
    root = insert(root, 50);
    insert(root, 30);
    insert(root, 20);
    insert(root, 40);
    insert(root, 70);
    insert(root, 60);
    insert(root, 80);

    // print inoder traversal of the BST
    inorder(root);

    return 0;
}


texts: Asynchronous service that publishes a possibly infinite amount of events

texts:
I want to implement a service that fetches eyetracking events and publishes them to all subscribers of the stream. The whole thing is supposed to run asynchronously, so it doesn't block the UI thread. This is how the service is supposed to be used:

ETStreamService service = new ETStreamService();
service.getObservable().subscribe(e -> ...);
service.start();
doSomeOtherWork();
service.stop();

I implemented a generic version (error handling omitted):

public class ETStreamService<E extends ChronologicComparable<E>> {

    private ETReceiver<E> receiver;
    private AtomicBoolean running;
    private PublishSubject<E> publishSubject;
    private Thread streamThread;

    private class ETStreamRunnable implements Runnable {
        private ETReceiver<E> receiver;
        private AtomicBoolean running;
        private PublishSubject<E> publishSubject;

        public ETStreamRunnable(AtomicBoolean running, ETReceiver<E> receiver, PublishSubject<E> publishSubject) {
            this.receiver = receiver;
            this.running = running;
            this.publishSubject = publishSubject;
        }

        @Override
        public void run() {
            while(running.get()) {
                ETResponse<E> response = receiver.getNext();

                switch(response.getType()) {
                case NEW_DATA:
                    publishSubject.onNext(response.getData());
                    break;
                case NO_NEW_DATA_AVAILABLE:
                    break;
                case SOURCE_DEPLETED:
                    publishSubject.onComplete();
                    running.set(false);
                    break;
                }
            }
        }

    }

    public ETStreamService(ETReceiver<E> receiver) {
        this.receiver = receiver;
        this.running = new AtomicBoolean(false);
        this.publishSubject = PublishSubject.create();
    }

    public void start() {
        running.set(true);
        streamThread = new Thread(new ETStreamRunnable(running, receiver, publishSubject));
        streamThread.start();
    }

    public void stop() {
        running.set(false);
    }

    public void shutdown() {
        running.set(false);
        publishSubject.onComplete();
    }

    public Observable<E> getObservable() {
        return publishSubject;
    }
}

The idea is to run a separate thread, which can be started and stopped through the public interface of the ETStreamService class. The Runnable that is run inside the thread does the fetching and publishing of events. The event stream can be obtained by calling getObservable(). onComplete() is emitted if the ETReceiver has no more elements to receive (finite source, like a list of pre-recorded data), or if the shutdown() method is called (for infinite sources, such as a real eyetracker).

I like the overall design, but i am unsure about the thread safety of it, so it would be nice if someone could review it for me.


texts:
Exercise 7.2 from Python for Informatics:

  Write a program to prompt for a file name, and then read through
  the file and look for lines of the form:

  X-DSPAM-Confidence: 0.8475

  When you encounter a line that starts with “X-DSPAM-Confidence:” pull apart
  the line to extract the floating-point number on the line. Count these lines and then compute the total of the spam confidence values from these lines. When you reach the end of the file, print out the average spam confidence.

Enter the file name: mbox.txt
Average spam confidence: 0.894128046745

Enter the file name: mbox-short.txt
Average spam confidence: 0.750718518519

  Test your file on the mbox.txt and mbox-short.txt files.

My code works. It's a bit more forgiving with the amount of decimals on both input and output, but that's as intended.

What I'm not happy about are the ask_file_name and retrieve_values functions. The first uses a hacky method of input validation (the Path module seems appropriate here, but that would be overkill), the second uses iteration while it shouldn't. Perhaps a reduce  would be more appropriate, or something different altogether.

This is written in modern Python. Which means it's written in Python 3 (3.5.2 to be exact, Python 3.7.x is incoming) and has plenty of docstrings. It should be up to standards, but I'd like to have that verified.

AverageSpamConfidence.py

#! /usr/bin/env python3
# coding: utf-8

# Sample data from http://www.py4inf.com/code/

import re

def ask_file_name():
    """
    Ask user for file name.

    Check for FileNotFound & IsADirectory errors.
    Keyword arguments:
    -
    """
    while True:
        try:
            user_input = input("Enter the file name: ")
            # Is the file there and can we open it?
            with open(user_input, "r") as test_input:
                pass
        except FileNotFoundError:
            print("Input empty or file does not exist.")
            continue
        except IsADirectoryError:
            print("That's not a directory, not a file.")
            continue
        else:
            return user_input

def find_occurences_in_file(file_name):
    """
    Find all occurences in target file.

    Keyword arguments:
    file_name -- name of (and path to) target file (example: mbox.txt)
    """
    with open(file_name, "r") as input_file:
        return re.findall(
            'X-DSPAM-Confidence: 0.[0-9]+', str(input_file.readlines())
        )

def retrieve_values(input_list):
    """
    Return relevant values from list.

    Keyword arguments:
    input_list -- list to results to retrieve values from
    """
    return_list = []
    for line in input_list:
        return_list.append(float(line.split()[-1]))
    return return_list

def average(input_list):
    """
    Calculate average of list provided.

    Keyword arguments:
    input_list -- list of numerical values
    """
    return sum(input_list) / len(input_list)

def main():
    """
    Exercise 7.2 (Python for Informatics, Charles Severance)
    Write a program to prompt for a file name,
    and then read through the file and look for lines of the form:

    X-DSPAM-Confidence: 0.8475

    When you encounter a line that starts with “X-DSPAM-Confidence:” pull apart
    the line to extract the floating-point number on the line.
    Count these lines and then compute the total of the spam confidence values
    from these lines. When you reach the end of the file, print out
    the average spam confidence.
    """
    file_name = ask_file_name()
    occurences = find_occurences_in_file(file_name)
    values = retrieve_values(occurences)
    print(average(values))

if __name__ == '__main__':
    main()


texts:
I don't know if this is exactly refactoring but I recently completed a programming challenge to learn more about Ruby's iterators. However, I feel that the code is extremely "un-Ruby like". Would anyone have any suggestions as to how I could improve it?

numbers = []
binary = []
binary_count = 0

File.open('decimals.txt').each_line do |line|
  numbers.push line.chomp
end

numbers.each do |number|
  binary.push number.to_i.to_s(2)
end

binary.each do |binary_num|
 binary_count += binary_num.count("1")
end

puts binary_count

Yes, I know it's a basic problem. It took me roughly five minutes to complete but it was more about just getting the syntax of the iterators down.


texts: Make a command line application with parameter

texts:
I made a command line application which uses parameters. So I try to make a system like the linux command.
So I have 4 parameters, initialized to a default value, used if wrong or none parameter are given. The user can modify those parameter by calling associate options "-options".

   public static void main(String [] args) {
    String locParameter = "centralOffice";
    String dirResult = "//home//"+System.getProperty("user.name")+"//Documents//ResultMyApp";
    int periodParameter = 24;
    String counterParameter = "ALL";
    int i = 0;

    for (String s: args) {
        switch (s) {
            case "-o":  if (args[i+1].equalsIgnoreCase("remote")){
                            locParameter = "remoteOffice";
                            break;
                        } else if (args[i+1].equalsIgnoreCase("central")){
                            locParameter = "centralOffice";
                            break;
                        } else {
                            System.err.println("Unknow parameter for location, default value: centralOffice");
                            break;
                        }
            case "-p":  dirResult = args[i+1];
                        break;
            case "-kpi": counterParameter = args[i+1].toUpperCase();
                        break;
            case "-t":  try {
                            periodParameter = Integer.parseInt(args[i+1]) ;
                        } catch(NumberFormatException e){
                            System.err.println("Error parsing parameter, default value 24 hours");
                        } finally {
                            break;
                        }
        }
        i++;
    }

    System.out.println("parameter choosed: " + locParameter + ", " + periodParameter + ", " + counterParameter );}

So I am wondering, is this ok? Of course it works but maybe it is not the easiest way to do it or the most optimized code.


texts:
I've written a function to sort an array that interweaves an arrays values in the way of if you had two separate arrays [1,2,3,4,5] on one side and [6,7,8,9,0] on the other and it becomes [1, 6, 2, 7, 3, 8, 4, 9, 5, 0].

The code works, but I'm wondering how it can be cleaned up and be more performant without the need for three additional arrays and to see if it can be done on the cards array itself.

let data = [1,2,3,4,5,6,7,8,9,0];

const interweave = data => {
  const _data = [];
  const l = data.slice(0, data.length / 2);
  const r = data.slice(data.length / 2, data.length);
  if (l.length === r.length) {
    for (let i = 0; i < l.length; i++) {
      _data.push(l[i], r[i]);
    }
  }
  return _data;
}

interweave(data);


texts: std::lock implementation in C with pthreads

texts:
I messed a little bit with pthreads and needed an alternative to the C++11 function std::lock (2 args are enough), and this is what I came up with:

void lock(pthread_mutex_t* m1, pthread_mutex_t* m2) {
  while(1) {
    pthread_mutex_lock(m1);

    if(pthread_mutex_trylock(m2) == 0) { // if lock succesfull
      break;
    }
    pthread_mutex_unlock(m1);
    sched_yield();
  }
}

It works fine so far.  I am just not sure whether I missed some potential deadlock.

In addition, I am interested if I should do some more error checking.  I am especially not that firm with C-style error checking.


texts: Brainfuck interpreter in JavaScript, take 2

texts:
The previous version is here. This version takes suggestions from that review into account:

brainfuck is now an object instead of a function, and brainfuck.run(source) kicks off the interpreter.
There is no built-in support for multiple interpreter instances, but Object.create(brainfuck) will do the trick.
Stub functions (which throw errors) are provided for the implementation-dependent read and write functions.

This version also addresses the redundancy in the first version by handling loops differently. All loop start and end positions are pre-calculated, so the entire loop is now bypassed when appropriate instead of passing over each operation and no-opping. This also removes the need to keep a stack of loop start positions while the program runs.

Also, this version adds proper exports for AMD script loaders and CJS environments, with a fallback to the global namespace object.

(function(global){

    // Find start and end positions of each loop.
    function findLoops(code) {
        var start;
        var startpoints = {};
        var endpoints = {};
        var stack = [];

        for (var i = 0; i < code.length; i++) {
            if (code[i] == '[') {
                stack.push(i);
            } else if (code[i] == ']') {
                start = stack.pop();
                startpoints[i] = start;
                endpoints[start] = i;
            }
        }

        return { start: startpoints, end: endpoints };
    }

    // Run the brainfuck interpreter.
    function run(source) {
        var brainfuck = this;
        var code = source.replace(/[^-+<>.,[\]]/g, '').split('');  // program code
        var loop = findLoops(code);  // loop start and end positions
        var data = [];  // array of data cells stored by the program code
        var cell = 0;   // index in the data array representing one "cell" of data
        var next = 0;   // index in the code array of the next instruction to run
        var operation = {
            '>': function () { ++cell; },
            '<': function () { --cell; },
            '+': function () { data[cell] = (data[cell] || 0) + 1; },
            '-': function () { data[cell] = (data[cell] || 0) - 1; },
            '.': function () { brainfuck.write(data[cell]); },
            ',': function () { data[cell] = brainfuck.read(); },
            '[': function () { if (!data[cell]) { next = loop.end[next]; } },
            ']': function () { if (data[cell]) { next = loop.start[next]; } }
        };

        while (next < code.length) {
            operation[code[next]]();
            next++;
        }

        if (brainfuck.end) {
            brainfuck.end();
        }
    }

    // Export a module for AMD loaders, CJS environments, or as a global.
    function exportModule(name, module) {
        if (global['define'] && global['define']['amd']) {
            global['define'](module);
        } else if (global['exports']) {
            for (var key in module) if (module.hasOwnProperty(key)) {
                global['exports'][key] = module[key];
            }
        } else {
            global[name] = module;
        }
    }

    // Export brainfuck module.
    exportModule('brainfuck', {
        'run': run,
        'read': function() { throw new Error('"read" function not provided'); },
        'write': function() { throw new Error('"write" function not provided'); }
    });

}(this));

Test it out here. I have no specific concerns at this point, I'm just looking for a general review.


texts: Take actions depending on whether a number is within X percent of another

texts:
Let's say we had a baseline value of 100 and I have a value of X.

If X is 5% or less higher/lower than 100 (95 to 105) then do something. If it's greater than 5% (Less than 95 or more than 105) do something else.

My initial thought was something like the below but it looks quite messy

$diff = 100*0.05;
$lower = 100-$diff;
$higher = 100+$diff;
if ($x >= $lower && $x <= $higher) {
     // Within tolerance
}
if ($X < $lower || $x > $higher) {
     // Outside tolerance
}


texts:
The following code is ran when the user presses a button to generate a log file based on the date selected. The DatePicker has a restrictive selected date range of the last 2 weeks including that same day. If the user leaves the page open for more than one day (very common), they will however be able to generate a log for a day that is too old. I've added this check to ensure that this isn't the case. I'm looking for a review on any part of this code.

[Bindable] private var mGeneratedLog:String;
[Bindable] private var mSelectedDate:Date;
[Bindable] private var mSelectableRange:Object;

private function getUploadMessages():void
{
    //validate range
    var now:Date = new Date();
    var tomorrow:Date = new Date(now.fullYear, now.month, now.date + 1, 0, 0, 0, 0);
    var twoWeeksAgo:Date = new Date(now.fullYear, now.month, now.date - 14, 0, 0, 0, 0);

    //refresh selectable range incase the page has been open too long.
    mSelectableRange = {rangeStart: twoWeeksAgo, rangeEnd: now};

    if (twoWeeksAgo.getTime() >= mSelectedDate.getTime())
    {
        mGeneratedLog = "Selected date is older than 2 weeks of age (Data has been purged).\nLog Not Generated.";
    }
    else if( mSelectedDate.getTime() >= tomorrow.getTime())
    {
        mGeneratedLog = "Selected date has not happened yet (log would be empty).\nLog Not Generated.";
    }
    else
    {
        mGeneratedLog = "Generating...";

        var formatter:DateFormatter = new DateFormatter();
        formatter.formatString = "YYYY-MM-DD JJ:NN:SS.QQQ";

        var lParameters:Object = {date:formatter.format(mSelectedDate)}
        mDatalayer.callStatement("GenerateLog", lParameters);
    }
}


texts:
Problem

Validate if a given string can be interpreted as a decimal or scientific number.

Some examples:

"0" => true
" 0.1 " => true
"abc" => false
"1 a" => false
"2e10" => true
" -90e3   " => true
" 1e" => false
"e3" => false
" 6e-1" => true
" 99e2.5 " => false
"53.5e93" => true
" --6 " => false
"-+3" => false
"95a54e53" => false

Code

I've solved the valid number LeetCode problem using Python re module. If you'd like to review the code and provide any change/improvement recommendations, please do so and I'd really appreciate that.

import re
from typing import Optional

def is_numeric(input_string: Optional[str]) -> bool:
    """
    Returns True for valid numbers and input string can be string or None
    """
    if input_string is None:
        return False

    expression_d_construct = r"^[+-]?(?:\d*\.\d+|\d+\.\d*|\d+)[Ee][+-]?\d+$|^[+-]?(?:\d*\.\d+|\d+\.\d*|\d+)$|^[+-]?\d+$"
    expression_char_class = r"^[+-]?(?:[0-9]*\.[0-9]+|[0-9]+\.[0-9]*|[0-9]+)[Ee][+-]?[0-9]+$|^[+-]?(?:[0-9]*\.[0-9]+|[0-9]+\.[0-9]*|[0-9]+)$|^[+-]?[0-9]+$"

    if re.match(expression_d_construct, input_string.strip()) is not None and re.match(expression_char_class, input_string.strip()) is not None:
        return True
    return False

if __name__ == "__main__":
        # ---------------------------- TEST ---------------------------
    DIVIDER_DASH = '-' * 50
    GREEN_APPLE = '\U0001F34F'
    RED_APPLE = '\U0001F34E'

    test_input_strings = [None, "0  ", "0.1", "abc", "1 a", "2e10", "-90e3",
                          "1e", "e3", "6e-1", "99e2.5", "53.5e93", "--6", "-+3", "95a54e53"]

    count = 0
    for string in test_input_strings:
        print(DIVIDER_DASH)
        if is_numeric(string):
            print(f'{GREEN_APPLE} Test {int(count + 1)}: {string} is a valid number.')
        else:
            print(f'{RED_APPLE} Test {int(count + 1)}: {string} is an invalid number.')
        count += 1

Output

--------------------------------------------------
 Test 1: None is an invalid number.
--------------------------------------------------
 Test 2: 0   is a valid number.
--------------------------------------------------
 Test 3: 0.1 is a valid number.
--------------------------------------------------
 Test 4: abc is an invalid number.
--------------------------------------------------
 Test 5: 1 a is an invalid number.
--------------------------------------------------
 Test 6: 2e10 is a valid number.
--------------------------------------------------
 Test 7: -90e3 is a valid number.
--------------------------------------------------
 Test 8: 1e is an invalid number.
--------------------------------------------------
 Test 9: e3 is an invalid number.
--------------------------------------------------
 Test 10: 6e-1 is a valid number.
--------------------------------------------------
 Test 11: 99e2.5 is an invalid number.
--------------------------------------------------
 Test 12: 53.5e93 is a valid number.
--------------------------------------------------
 Test 13: --6 is an invalid number.
--------------------------------------------------
 Test 14: -+3 is an invalid number.
--------------------------------------------------
 Test 15: 95a54e53 is an invalid number.

RegEx Circuit

jex.im visualizes regular expressions:

RegEx Demo 1

RegEx Demo 2

If you wish to explore the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.

Source

LeetCode Valid Number


texts: Handing focusing and unfocusing of multiple form fields

texts:
Here is a link to my problem

$('#name').focus(function() {
    if ($(this).val() == 'Full Name*')
        $(this).val('');
        }).blur(function() {
    if($(this).val() == '')
        $(this).val('Full Name*');
});
    $('#email').focus(function() {
    if ($(this).val() == 'Email Address*')
        $(this).val('');
        }).blur(function() {
    if($(this).val() == '')
        $(this).val('Email Address*');
});
    $('#subject').focus(function() {
    if ($(this).val() == 'Subject*')
        $(this).val('');
        }).blur(function() {
    if($(this).val() == '')
        $(this).val('Subject*');
});
    $('#msg').focus(function() {
    if ($(this).val() == 'Your Message*')
        $(this).val('');
        }).blur(function() {
    if($(this).val() == '')
        $(this).val('Your Message*');
});

I've been trying to simplify this code, but because of my limited javascript knowledge I haven't been able to achieve this. I'm almost 100% sure that this could be written in much simpler - DRY form.


texts: More efficient way of doing this hide()/show() jQuery

texts:
I currently have the following jQuery code, which does work, but I know there is a better way of doing it without having to repeat myself so much:

Basically, when a button is clicked, I need to show the additional div for that content type and hide the rest. If it's just a Post, then all of the divs are hidden as there is no specific div for the post type.

The HTML looks like this:

  <button id="btn-post" class="btn btn btn-primary active" type="button">Post</button>
  <button id="btn-game" class="btn btn btn-primary" type="button">Game</button>
  <button id="btn-video" class="btn btn btn-primary" type="button">Video</button>
  <button id="btn-giveaway" class="btn btn btn-primary" type="button">Giveaway</button>

game stuff

video stuff

giveaway stuff

What's the more efficient way of writing that jQuery?


texts: Replacing consecutive equal elements in a list with a new element

texts:
In the code below I will replace all consecutive equal elements in a list with a new element. In this case I have chosen the new element to simply be the concatenation of all the equal elements, but I want the code to remain adaptable to other situations.

I have the following example:

  Input: ["a", "a", "b", "c", "d", "d", "d", "e", "f", "f", "f", "f", "g", "g"]
  Output: ["aa", "b", "c", "ddd", "e", "ffff", "gg"]

I furthermore want to perform this replacement in a single-pass, meaning in \$\mathcal{O}(n)\$ time complexity and also with \$\mathcal{O}(1)\$ storage complexity.

In the code below I have implemented a solution to this problem, I believe it still satisfies \$\mathcal{O}(n)\$ but I'm not exactly sure because it also iterates back through the list to remove the elements.

private static void replaceConsecutiveEqualElements(final List<String> list) {
    ListIterator<String> listIterator = list.listIterator();
    String previousElement = null;
    int consecutiveMatches = 1;

    // Loop through list
    while (listIterator.hasNext()) {
        String element = listIterator.next();
        String newElement = null;

        if (element.equals(previousElement)) {
            consecutiveMatches++;
        }
        else {
            // Replace consecutive elements with new element
            if (consecutiveMatches >= 2) {
                listIterator.previous();
                for (int i = 0; i < consecutiveMatches; i++) {
                    listIterator.previous();
                    listIterator.remove();
                }
                newElement = String.join("", Collections.nCopies(consecutiveMatches, previousElement));
                listIterator.add(newElement);
            }
            consecutiveMatches = 1;
        }

        previousElement = (newElement == null) ? element : newElement;
    }

    // Special case for last element
    // Replace consecutive elements with new element
    if (consecutiveMatches >= 2) {
        for (int i = 0; i < consecutiveMatches; i++) {
            listIterator.previous();
            listIterator.remove();
        }
        String newElement = String.join("", Collections.nCopies(consecutiveMatches, previousElement));
        listIterator.add(newElement);
    }
}

Called like:

List<String> data = new ArrayList<>(Arrays.asList("a", "a", "b", "c", "d", "d", "d", "e", "f", "f", "f", "f", "g", "g"));
replaceConsecutiveEqualElements(data);

I'm not happy at all with this code and am looking for feedback.

I have also decided to implement this in a functional programming language, in my case Clojure, though I have removed the time and storage complexity constraints.

(defn replace-consecutive-equal [seq]
  (->> seq
       (partition-by identity)
       (map (partial apply str))))

(println (replace-consecutive-equal '("a", "a", "b", "c", "d", "d", "d", "e", "f", "f", "f", "f", "g", "g")))

The Clojure code roughly performs the following steps:

Take the input: ["a", "a", "b", "c", "d", "d", "d", "e", "f", "f", "f", "f", "g", "g"]
Partition it by the identify function: [["a", "a"], ["b"], ["c"], ["d", "d", "d"], ["e"], ["f", "f", "f", "f"], ["g", "g"]]
Apply the str function on the elements of the inner lists via a map on the outer list, the str function effectively joins strings: ["aa", "b", "c", "ddd", "e", "ffff", "gg"]

As you can see this would have made the implementation a whole lot easier, unfortunately this is not possible due to the listed constraints.

Note: I am aware that this may be a case of premature optimization, but I feel that it is important to know how to implement such an algorithm efficiently.


texts:
First time working with html 5 so far. Am I using my markup correctly thus far?
Semantically correct that is?

    <!doctype html>

    <title>Salon Sociel | Hair-Nails-Unisex</title>
    <meta charset="utf-8">
    <link rel="stylesheet" href="style/main.css">

Salon Sociel

Hair-Nails-Unisex

Home

About

Services

Products

Portfolio

Contact

Friends

Welcome to Our Salon Sociel

featured

Keratin

footer


texts: Finding points with the shortest distance

texts:
This takes in a user specified number of points then finds the two points with the shortest distance.

import java.util.Scanner;
import java.lang.Math;

public class FindNearestPoints
{
    public static void main(String[] args)
    {
        Scanner scan = new Scanner(System.in);

        System.out.print("Enter the number of points: ");
        final int numOfPoints = scan.nextInt();

        double[][] points = new double[numOfPoints][2];
        double shortestDistance=0;
        double distance=0;
        String closestPoint1="";
        String closestPoint2="";

        //enter x,y coords into the ix2 table points[][]
        for (int i=0; i<numOfPoints; i++)
        {
                System.out.print("Enter point x" + i + ": ");
                points[i][0] = scan.nextDouble();
                System.out.print("Enter point y" + i + ": ");
                points[i][1] = scan.nextDouble();
        }

        //get the distance between the point in the ith row and the (m+1)th row
        //and check if it's shorter than the distance between 0th and 1st
        for (int i=0; i<numOfPoints; i++)
        {
            //use m=i rather than 0 to avoid duplicate computations
            for (int m=i; m<numOfPoints-1;m++)
            {
                double dx = points[i][0] - points[m+1][0];
                double dy = points[i][1] - points[m+1][1];
                distance = Math.sqrt(dx*dx + dy*dy);

                //set shortestDistance and closestPoints to the first iteration
                if (m == 0 && i == 0)
                {
                    shortestDistance = distance;
                    closestPoint1 = "(" + points[0][0] + "," + points[0][1] + ")";
                    closestPoint2 = "(" + points[1][0] + "," + points[1][1] + ")";
                }
                //then check if any further iterations have shorter distances
                else if (distance < shortestDistance)
                {
                    shortestDistance = distance;
                    closestPoint1 = "(" + points[i][0] + "," + points[i][1] + ")";
                    closestPoint2 = "(" + points[m+1][0] + "," + points[m+1][1] + ")";
                }
            }
        }
        System.out.println("The shortest distance is: " + shortestDistance);
        System.out.println("The closest points are " + closestPoint1 + " and " + closestPoint2);
    }
}


texts: Method for formatting a decimal number in Python using the given maximum number of digits and decimal places

texts:
The question itself should be fairly self-explanatory. My method takes in value, max_digits, and decimal_places, and returns a formatted decimal number string. The code:

from decimal import Decimal, ROUND_DOWN

def format_to_decimal_string(value, max_digits, decimal_places):
    """Formats a decimal number to the given number of decimal places.

    Notes:
        - If the decimal number is equal to zero, the absolute of the decimal
        number is formatted and returned to remove the minus sign. See the
        first doctest for an example.
        - If the number of digits in the rounded up decimal number exceeds the
        `max_digits`, the method tries to return the rounded down version. See
        the second doctest for an example.

    Doctests:
        >>> format_to_decimal_string('-0.000', 4, 2)
        '0.00'
        >>> format_to_decimal_string('99.999999', 4, 2)
        '99.99'
        >>> format_to_decimal_string('99.999999', 5, 2)
        '100.00'
        >>> format_to_decimal_string('420.2108', 5, 0)
        '420'
        >>> format_to_decimal_string('foo', 4, 2)
        Traceback (most recent call last):
            ...
        TypeError: The value 'foo' is not a valid decimal number.
        >>> format_to_decimal_string('120.411', 4, 2)
        Traceback (most recent call last):
            ...
        ValueError: After formatting, the number of digits in the value
        '120.41' is 5, which exceeds the maximum number of digits of 4.
    """
    try:
        decimal_number = Decimal(str(value))
    except:
        raise TypeError(
            'The value \'{}\' is not a valid decimal number.'.format(value)
        )

    if decimal_number == 0:
        return str(abs(decimal_number).quantize(
            Decimal(10) ** -decimal_places)
        )

    rounded_up = decimal_number.quantize(Decimal(10) ** -decimal_places)
    if not len(rounded_up.as_tuple().digits) > max_digits:
        return str(rounded_up)

    rounded_down = decimal_number.quantize(
        Decimal(10) ** -decimal_places,
        rounding=ROUND_DOWN
    )
    rounded_down_digits_length = len(rounded_down.as_tuple().digits)
    if not rounded_down_digits_length > max_digits:
        return str(rounded_down)
    else:
        raise ValueError(
            'After formatting, the number of digits in the value \'{}\' is ' \
            '{}, which exceeds the maximum number of digits of {}.'.format(
                rounded_down, rounded_down_digits_length, max_digits
            )
        )

Please assume that max_digits, and decimal_places will always be positive integers, and max_digits is greater than decimal_places, because these are coming from my database, so no validation is required for these arguments.

The comments should also be self explanatory. We only want to round up if the rounding up does not exceed the given maximum number of digits. Would really appreciate a review of this method.


texts:
I wrote a function, scan_ps(), for scanning /proc, to replace a combination of popen() and ps(1).

scan_ps() scans /proc, calling filter() on each /proc/[pid]. Entries for which filter() returns nonzero are stored in strings allocated via malloc(3), and collected in array ps_list. If /proc/[pid]/cmdline is empty, the entry will not be stored. And return value is the count of entries.

But I wonder that I have to add or remove some corner-case handlings for read(), malloc(), or realloc().

int scan_ps(struct my_proc ***ptr, int (*filter)(const struct my_proc *)) {
    DIR * dirp;
    struct dirent * dp;
    int count = 0;
    pid_t pid;
    char path[MAX_LEN_STR], buf[MAX_LEN_STR];
    int fd, n;
    unsigned int size = 16;
    struct my_proc ** ps_list, ** ps_list2;
    struct my_proc * current_ps;

    dirp = opendir("/proc");
    if (NULL==dirp)
        return -1;

    ps_list = malloc(sizeof(struct my_proc *)*size);
    if (ps_list==NULL) {
        printf("%s: malloc failed(ps_list)\n",__func__);
        goto failed_closedir;
    }

    while (NULL != (dp = readdir(dirp))) {
        pid = atoi(dp->d_name);
        if (0 == pid)
            continue;
        snprintf(path, sizeof(path), "/proc/%u/cmdline", pid);
        fd = open(path, O_RDONLY);
        if (fd < 0) {
            printf("%s: failed to open() (%d)\n",__func__, errno);
            continue;
        }
        n = read(fd, buf, MAX_LEN_STR);
        if (0 == n) {
            // cmdline is empty. maybe kernel process.
            printf("%s: pid:%u cmdline is empty!\n",__func__, pid);
            close(fd);
            continue;
        }
        n = (MAX_LEN_STR - 1) > n ? n : (MAX_LEN_STR - 1);
        buf[n] = '\0';
        close(fd);

        current_ps = malloc(sizeof(struct my_proc));
        if (current_ps==NULL) {
            printf("%s: malloc failed\n",__func__);
            goto failed_ps_list;
        }
        current_ps->pid = pid;
        strncpy_v2(current_ps->cmdline, buf, MAX_LEN_STR);
        if ( !filter(current_ps) ) {
            printf("%s: let it go. currnet_ps\n", __func__);
            free(current_ps);
            continue;
        }
        // prepare ps_list
        if (count!=0 && (count%16)==0) {
            size += 16;
            ps_list2 = realloc(ps_list, sizeof(struct my_proc *)*size);
            if (ps_list2==NULL) {
                printf("%s: malloc failed(ps_list2)\n",__func__);
                goto failed;
            }
            ps_list = ps_list2;
        }
        ps_list[count++] = current_ps;
    }
    closedir(dirp);
    *ptr = ps_list;
    return count;
failed:
    free(current_ps);
failed_ps_list:
    while(count--) {
        free(ps_list[count]);
    }
    free(ps_list);
failed_closedir:
    closedir(dirp);
    return -1;
}

scan_ps() works with below code.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <fcntl.h>
#include <errno.h>
#define FALSE               (0)
#define TRUE                (!FALSE)
#define MAX_LEN_STR         256

struct my_proc {
    pid_t pid;
    char cmdline[256];
};

int true_filter(const struct my_proc * a) {
    return TRUE;
}

char *strncpy_v2(char *dest, char *src, unsigned int size){
    if (size==0) return dest;
    dest[--size] = '\0';
    return strncpy(dest, src, size);
}

int main(){
    int n;
    struct my_proc ** ps_list;
    n = scan_ps(&ps_list, true_filter);
    if (n<0) {
        printf("%s: n=%d something wrong!\n", __func__, n);
        return -1;
    }
    printf("%s: n=%d\n", __func__, n);
    while (n--) {
        printf("%s: %u, %s\n", __func__, ps_list[n]->pid, ps_list[n]->cmdline);
        free(ps_list[n]);
    }
    free(ps_list);
    return 0;
}


texts:
I attempted to implement a Monoid' instance for a function a -> b.

class Monoid' a where
    mempty  :: a -> a
    mappend :: a -> a -> a

instance Monoid' (a -> b) where
    mempty  f   = f
    mappend f g = g . f

Please critique it for correctness and style.

In addition, I'm curious how mappend should be implemented. Should f or g be applied first?


texts:
I have a function in python where I want the reverse complement of a DNA string.

This is what I have now:

def inversComplement(input):
    output = ''
    for letter in input:
        letter = letter.upper()

        if letter == 'A':
            output += 'T'
        elif letter == 'T':
            output += 'A'
        elif letter == 'G':
            output += 'C'
        else:
            output += 'G'

    return(output[::-1])

I was thinking of using the string.replace() method. But the problem was that if I use this the T-> A would be changed afterwards with the A -> T replacement

    string.replace('A','T').replace('T','A').replace('G','C').replace('C','G')


texts: Monitor room repository for livedata changes and update views

texts:
I have built a quiz app. It is my first project so the purpose is to learn app development at this stage.
There are two key things which I am wondering how to do better (the app is fully functional).
1: Livedata / flow / room
I have the following data class
@Entity
data class SavedScores(
    @PrimaryKey(autoGenerate = true) var id: Int,
    var difficulty: String?,
    var sumtype: String?,
    var questioncount: Int?,
    var answeredcorrectly: Int?
)

I have the following DAO query
@Query("SELECT COUNT(*) from SavedScores WHERE difficulty = :DIFFICULTY AND questioncount = :QuestionCount AND answeredcorrectly =:QuestionCount")
    fun GetWinsByDifficulty(DIFFICULTY: String,QuestionCount:Int):Flow<Int>

This is where I start writing a LOT of code and wonder if there are better ways to be letting the data flow. In my room repository I am then calling every instance of that query that I require for a statistics page
val easy5: Flow<Int> = savedScoresDao.GetWinsByDifficulty("Easy", 5)
    val easy10: Flow<Int> = savedScoresDao.GetWinsByDifficulty("Easy", 10)
    val easy15: Flow<Int> = savedScoresDao.GetWinsByDifficulty("Easy", 15)
    val easy20: Flow<Int> = savedScoresDao.GetWinsByDifficulty("Easy", 20)
    val easy30: Flow<Int> = savedScoresDao.GetWinsByDifficulty("Easy", 30)

Then I have my view model
val easy5: LiveData<Int> = repository.easy5.asLiveData()
    val easy10: LiveData<Int> = repository.easy10.asLiveData()
    val easy15: LiveData<Int> = repository.easy15.asLiveData()
    val easy20: LiveData<Int> = repository.easy20.asLiveData()
    val easy30: LiveData<Int> = repository.easy30.asLiveData()

And finally my observer and view setter;
savedScoresViewModel.easy5.observe(this) { newValue ->
            tv_easy5.text = newValue.toString()
            setView(tv_easy5,newValue)
        }
        savedScoresViewModel.easy10.observe(this) { newValue ->
            tv_easy10.text = newValue.toString()
            setView(tv_easy10,newValue)
        }
        savedScoresViewModel.easy15.observe(this) { newValue ->
            tv_easy15.text = newValue.toString()
            setView(tv_easy15,newValue)
        }
        savedScoresViewModel.easy20.observe(this) { newValue ->
            tv_easy20.text = newValue.toString()
            setView(tv_easy20,newValue)
        }
        savedScoresViewModel.easy30.observe(this) { newValue ->
            tv_easy30.text = newValue.toString()
            setView(tv_easy30,newValue)
        }
private fun setView(view:TextView,value:Int){
        if (value == 0){view.setBackgroundResource(R.drawable.somewrong_icon)
        } else {
            if (view.text.toString().toInt()==0){
                view.setBackgroundResource(R.drawable.somewrong_icon)
            } else {view.setBackgroundResource(R.drawable.allcorrect_icon)}
        }
    }

The reality is that currently I have 4 levels of difficulty so for each level I am repeating the above. I also 9 different sum types and have even more queries running to capture that information. Is there a simpler way to code each individual query without having to write so many lines of code? Is it bad practise having so many observers?
2: The second aspect to this is my views. Currently to show all of this data I have a huge amount of views. Whilst I have used recycler view in one part of my app (showing a history of games) I dont see how I can use it for this one as I have so many standalone queries to monitor i.e. I get a count and show just that count. Every new item is a standalone query response rather than a list of them
I appreciate this might end of being quite broad but after all this is about improving code not fixing a problem. I understand therefore if responses tend to focus on one element
I am happy to share more of my code as well but didnt want to load it all if not needed


texts:
How could I improve the following code that runs a simple linear regression using matrix algebra?  I import a .csv file (link here) called 'cdd.ny.csv', and perform the matrix calculations that solve for the coefficients (intercept and regressor) of Y = XB (i.e.,  $(X'X)^{-1}X'Y$):

import numpy
from numpy import *
import csv

df1 = csv.reader(open('cdd.ny.csv', 'rb'),delimiter=',')
tmp = list(df1)
b = numpy.array(tmp).astype('string')
b1 = b[1:,3:5]
b2 = numpy.array(b1).astype('float')

nrow = b1.shape[0]
intercept = ones( (nrow,1), dtype=int16 )

b3 = empty( (nrow,1), dtype = float )

i = 0
while i < nrow:
    b3[i,0] = b2[i,0]
    i = i + 1

X = numpy.concatenate((intercept, b3), axis=1)
X = matrix(X)

Y = b2[:,1]
Y = matrix(Y).T

m1 = dot(X.T,X).I
m2 = dot(X.T,Y)

beta = m1*m2

print beta

#[[-7.62101913]
# [ 0.5937734 ]]

To check my answer:

numpy.linalg.lstsq(X,Y)


texts: Handling keyup events with throttle or debounce in Javascript/jQuery

texts:
In my web application, there is a search input field, and when the user empties all of the text inside the input field, there is an API call made for a default-list of results, which are displayed in a dropdown right underneath the input field.

I'm using the keyup event to try to capture when the user will have completed deleting text, but I've not been able to re-create the desired behavior without using setTimeout().  I've been told to use a throttle or debounce method (no third party modules or plugins, although plain jQuery is ok).

Could someone please give me some advice on how to recreate this code without using setTimeout?  I've been on this for a couple days no with no luck, any help is appreciated!

(function () {
  var desktopInput = document.getElementById('someId');
  var desktopResults = document.getElementsByClassName('someClass')[0];

  function getSuggestedSearchResults(cb) {
    $.ajax({
      url: url,
      data: {},
      timeout: REQ_TIMEOUT,
      xhrFields: {
        withCredentials: true
      },
      success: function (data) {
        cb(data);
      }
    });
  }

  function handleEmptyInputDesktop() {
    if (desktopInput.value === '') {
      setTimeout(function () {
        getSuggestedSearchResults(function (data) {
          var model = transformResults(data);
          var results = nunjucks.render('_fullscreenSearchResults', {
            results: model,
            source: 'suggested'
          });
          desktopResults.innerHTML = results;
        });
      }, 500);
    }
  }

  function init() {
    desktopInput.addEventListener('keyup', handleEmptyInputDesktop);
  }

  init();
})();

Without the setTimeout(), the dropdown menu will disappear if the key isn't pressed long enough on the first stroke that deletes all the text.

I've omitted some extraneous code from this snippet, but I'm happy to give more details if you like.


texts:
Description

Given a class, return all its subclasses (recursively).
As you can see I've eliminated recursion using a stack.

What I want reviewed

Is there a better way to do this?
How can I make this code more generic and easier to use?
Is it pythonic?
Better way to eliminate recursion?

Code

def all_subclasses(cls):

    if cls == type:
        raise ValueError("Invalid class - 'type' is not a class")

    subclasses = set()

    stack = []
    try:
        immediate_subclasses = cls.__subclasses__()
    except (TypeError, AttributeError) as ex:
        raise ValueError("Invalid class" + repr(cls)) from ex

    for subclass in immediate_subclasses:
        stack.append(subclass)

    while stack:
        sub = stack.pop()
        subclasses.add(sub)
        try:
            sub_subclasses = sub.__subclasses__()
        except (TypeError, AttributeError) as _:
           continue
        if sub_subclasses:
            stack.extend(sub_subclasses)

    return list(subclasses)

Tests

import unittest

from class_util import all_subclasses

def names(classes):
    return sorted([cls.__name__ for cls in classes])

class A:
    @classmethod
    def all_subclasses(cls):
        return all_subclasses(cls)

class B(A):
    pass

class C(B):
    pass

class D(C):
    pass

class E(C):
    pass

class F(E, C):
    pass

class AllSublassesTestCase(unittest.TestCase):
    def test_nested_classes(self):
        self.assertEqual(names(A.all_subclasses()), ["B", "C", "D", "E", "F"])

    def test_work_with_buitins(self):
        self.assertTrue(names(all_subclasses(dict)))
        self.assertTrue(names(all_subclasses(tuple)))
        self.assertTrue(names(all_subclasses(list)))

    def test_value_error_is_raised_on_invalid_classes(self):
        self.assertRaises(ValueError, all_subclasses, type)
        self.assertRaises(ValueError, all_subclasses, "")
        self.assertRaises(ValueError, all_subclasses, None)
        self.assertRaises(ValueError, all_subclasses, [])

if __name__ == "__main__":
    unittest.main()


texts: Memoized implementation of change-making algorithm

texts:
Recently, I wrote a simple program to solve the change-making problem. Rather than the tabular dynamic programming solution (described in the link), I tried to write a solution that uses memoization.

usd = [25, 10, 5, 1]

def make_change(W, denoms=usd):
    """
    Solves the change-making problem where W is
    a given amount of money and denoms
    is a list of the denominations available

    >>> make_change(6,[3,1])
    (3, 3)
    """

    d = {}

    def inner(W, sol):
        if W == 0:
            return sol

        if W in d:
            return d[W]

        tmp = []
        for coin in denoms:
            w = W - coin

            if w >= 0:
                tmp.append(inner(w, sol + (coin,)))

        d[W] = min(tmp, key=lambda x : len(x))
        return d[W]
    return inner(W, tuple())

if __name__ == "__main__":
    import doctest
    doctest.testmod()

I'm wondering if there's a better way I should be doing the memoization (i.e. a decorator):

def memoize(f):
    d = {}
    def inner(args):
        if args not in d:
            d[args] = f(*args)
        return d[args]
    return inner

The above code caches the arguments so they don't get recomputed in future computations. Here, however, I think we only want to cache the solution for a given W, and I'm not sure a general purpose decorator like the one above is necessarily correct.


texts:
I need someone review my sharedPreference class , which better to create sharedpreference with constant name MyPREFERENCES like this , or like they I do in class

SharedPreferences sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);

Editor editor = sharedpreferences.edit();
editor.putString("key", "value");
editor.commit();

my class

public class SharedPreferencesManager {

        private Context context;
        private SharedPreferences prefs;

        public SharedPreferencesManager(Context context) {
            this.context = context;
        }

        public void writeIntoPreferences(String[] names, String[] values) {
            Editor editor = getSharedPreferences().edit();
            for (int i = 0; i < names.length; i++) {
                editor.putString(names[i], values[i]);
            }
            editor.commit();
        }

        public String readPreference(String name, String defaultValue) {
            return getSharedPreferences().getString(name, defaultValue);
        }

        public void clearPreference(String[] names) {
            Editor editor = getSharedPreferences().edit();
            for (int i = 0; i < names.length; i++) {
                editor.putString(names[i], "");
            }
            editor.commit();
        }

        public void clearAll() {
            Editor editor = getSharedPreferences().edit();
            editor.clear();
            editor.commit();
        }

        private SharedPreferences getSharedPreferences() {
            if (prefs == null) {
                prefs = context.getSharedPreferences(Constants.PREFERENCES, Context.MODE_PRIVATE);
            }
            return prefs;
        }
    }


texts: JavaScript modular framework for a large web-site

texts:
In my ASP.NET MVC project I simply inserted <script></script> into my views - it caused code duplications and spaghetti code.

Now, I have decided to switch to modular JS and have implemented the following mechanism:

ALL actions are only executed through the framework and its modules - whether it is a view or object behavior, date-to-string converter or websocket connection
every module exposes exports functions, which can be called by anybody, including other modules
all functions including exports and init are called within a sandboxed context, which includes both objects specific for the module and objects, injected by a framework (currently, I am implementing the mechanism to "hide" / disallow non-context methods within a module)

Framework object with the only register function:

window.kibfw = {
    register: function(name, module) {
        if (!name || !module.init)
            throw new Error('Could not load a module ' + name);

        if (name === 'register')
            throw new Error('Module cannot have name "register" which is reserved');

        if (this[name])
            throw new Error('Module ' + name + ' is already registered.');

        module.context = module.context || {};

        /* Here, inject the required context objects (jQuery, libraries etc.) */
        module.context.$ = window.jQuery;
        module.context.kibfw = window.kibfw;

        try {
            module.init.apply(module.context, arguments);
        } catch(e) {
            throw new Error('Error during module initialization: ' + e.message + '\n' + e.stackTrace);
        }

        var moduleExports = (this[name] = {});
        for (var exportFnName in module.exports) {
            if (!module.exports.hasOwnProperty(exportFnName))
                continue;

            moduleExports[exportFnName] = (function (exportFn) {
                return function() {
                    try {
                        exportFn.apply(module.context, arguments);
                    } catch (e) {
                        throw new Error('Module: ' + name + '. Error during method invocation: ' + e.message + '\n' + e.stackTrace);
                    }
                };
            })(module.exports[exportFnName]);
        }
    }
};

Example module:

kibfw.register('decorator', {
  init: function () {
    this.$decorateItems = this.$('input');
  },
  context: {
    $decorateItems: undefined
  },
  exports: {
    setColor: function (color) {
      this.$decorateItems.css('color', color);
    }
  }
});

// Usage:
$("button").click(function() {
    kibfw.decorator.setColor($(this).attr('data-color'));
});

JSFiddle demonstration

How do you think, would it be useful and scalable?
Which problems can I stumble upon while using this approach?


texts:
This is my current RowDataBound function.  I think this functionality is a bit horrrendous really and it winds up with an extreme amount of LINQ SQL queries being passed around (which makes for big server load etc).

What I'm wondering is, is there any way that I could pull all the data in the first select statement, put it somewhere, and then have the fields in the templatefields bind back to this instead of running a query for every single row?

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {

        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            HiddenField hidField = (HiddenField)e.Row.FindControl("dbID");
            Table tbldetails = new Table();
            TableHeaderRow tblheaderrow = new TableHeaderRow();
            TableHeaderCell tblheadercell = new TableHeaderCell();
            tblheadercell.Text = "Details";
            tblheaderrow.Cells.Add(tblheadercell);
            tbldetails.CssClass = "table";
            int rowID = Convert.ToInt32(hidField.Value);
            Panel pnl = (Panel)e.Row.FindControl("deviceDetails");
            bool altField = false;

            var query = (from q in db.GetTable<priceData>()
                         where q.ID == rowID
                         select q).FirstOrDefault();
            var values = typeof(priceData)
                .GetProperties()
                .Select(p => p.GetValue(query, null))
                .ToArray();

            foreach (var value in values)
            {
                TableCell cell = new TableCell();
                TableRow tr = new TableRow();
                cell.Text = value.ToString();
                tr.Cells.Add(cell);
                tbldetails.Rows.Add(tr);
            }
            pnl.Controls.Add(tbldetails);
        }

EDIT

To explain myself a bit better, what I have is a GridView with rows that are expandable. In the expandable row under datarow (which lives in a TemplateField) I want to put all the data from the datarow in the sqldatasource. To me, this means I would have to have a collection of some sort to iterate through, to add to the template field. That said I could be totally wrong and I could be going about this the wrong way. Am I just totally barking up the wrong tree?


texts: Reducing steps for long addition program

texts:
This is a program that I wrote to add two numbers together that are too large for the C language to store.  It stores the numbers as strings instead and processes one digit at a time. But I suspect that the program could be done in fewer steps.  In what ways can I reduce the size of my program?  Where am I taking more steps than necessary?

#include <stdio.h>
#include <string.h>

int main()
{
    char *a = "1490438498359508";
    char *b = "1575390843059845";
    char *sum = "";
    char str[15] = "";
    char src[512];
    int carry = 0;
    int alength = strlen(a);
    int blength = strlen(b);
    int n;
    int i;
    int c, d;

    for (n=1; n<blength+1; n++) {
        int c=0, d=0;
        i = 0;
        c = a[alength-n]-48;
        d = b[blength-n]-48;
        i = c+d;
        if (carry == 1) {
            i=i+1;
        }
        if (i > 9) {
            i = i-10;
            carry=1;
        } else {
            carry=0;
        }
        int aInt = i;
        char str[15] = "";
        sprintf(str, "%d", aInt);
        strcat(src, str);

    }
    int nlength = strlen(src);
    int x;
    for (x=0; x<nlength+1; x++) {
        printf("%c", src[nlength-x]);
    }
    printf("\n");
    return 0;
}


texts: Validating that a Java program has two equal-length arguments

texts:
I'm writing a small almost one method Java class for a job application and the advice given was to write it as though it was a piece of commercial software.

The processResult method needs two string arguments of equal length. I thought the best thing to do is check that the args has at least 2 items, then inside the processResult method check that the strings have the same length.

I am unsure about throwing a generic exception in my main method and then later using the try/catch statement. Is this a good practice to do? Would it be better practice to handle these as part of one try catch? Are custom Exceptions a good way to go for this type of problem?

Here is what I have at the moment.

public class Task {
    public static void main(String[] args) throws Exception {
        if (args.length < 2) {
            throw new Exception("Need 2 string arguments");
        }

        try {
            int result = processResult(args[0], args[1]);
            System.out.println(result);
        } catch (IllegalArgumentException e) {
            System.err.println(e.getMessage());
        }
    }

    private static boolean lengthsEqual(String a, String b) {
        return Integer.compare(a.length(), b.length()) == 0;
    }

    private static int processResult(String inputOne, String inputTwo) {
        if (!lengthsEqual(inputOne, inputTwo) {
            throw new IllegalArgumentException("Strings must be the same length");
        }

        // method logic

        return 0;
    }

}


texts: Generic method to split provided collection into smaller collections

texts:
First time writing a generic method here.  Input a List<T> and an int value and output a List<List<T>> with each member List<T> of the provided int input.

No doubt there are easier / less verbose ways of handling this via LINQ but I wanted to try my hand with a generic method.  Please let me know of any ways that I could improve this method.

static List<List<T>> SplitIntoChunks<T>(List<T> fullBatch, int chunkSize)
{
    if (chunkSize <= 0)
    {
        throw new ArgumentOutOfRangeException("Chunk size cannot be less than or equal to zero.");
    }

    if (fullBatch == null)
    {
        throw new ArgumentNullException("Input to be split cannot be null.");
    }

    int numOfChunks = fullBatch.Count / chunkSize;

    //handles uneven number of items within the full batch to ensure none at the end are missed
    if (fullBatch.Count % chunkSize > 0)
    {
        numOfChunks++;
    }

    int cellCounter = 0;

    List<List<T>> splitChunks = new List<List<T>>();

    for (int chunkNum = 0; chunkNum < numOfChunks; chunkNum++)
    {
        var chunk = new List<T>();
        for (int index = 0; index < chunkSize; index++)
        {
            if (index < fullBatch.Count)
            {
                chunk.Add(fullBatch[index]);
                cellCounter++;
            }
        }
        splitChunks.Add(chunk);
    }

    return splitChunks;
}


texts: Project Euler #4 - finding the largest palindrome from the product of two n-digit numbers

texts:
Project Euler Problem #4: "A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.

Find the largest palindrome made from the product of two 3-digit numbers."

The code works well enough until trying to find the largest palindrome of two eight digit numbers. I found a similar question in C++, but there are some differences:

The main function takes two integers to determine the number of digits of the factors used to produce the products. This allows us to find the largest palindrome for a two digit number and a five digit number or two eight digit numbers.
Two for loops then create the multiplicand and multiplier. I think this could be done better.
The outer for loop iterates over the multiplicand to decrement it each time the inner for loop has completed.
The inner for loop iterates over the multiplier so that inside this loop every possible product from the multiplicand and multiplier are evaluated. This is where I think the largest gains from optimization will come from. I don't think that every product needs to be produced or evaluated to find the largest palindrome nor do I think it requires an inner/outer loop to do so.
The product is then turned into a string so that the first and last values can be compared for equality.
If they are equal the comparison repeats again after removing the compared values until three or less values are left where the first and last values are equal.
The product is then stored as the largest result if it is greater than the previous result.
Finally, the result is returned after all the loops have finished.

I am interested in finding ways to optimize this code.

console.log(largestPalindromeOfTwoFactors(8, 8));
function largestPalindromeOfTwoFactors(multiplicand, multiplier{//Accepts the number of digits of the multipland and the number of digits of         the multiplier
        var  multiplicandString = "";
        var multiplierString = "";
    for(var i = 0; i < multiplicand; i++){
         multiplicandString = multiplicandString.concat(""+9); // 9, 99, 999
    }
    for(var j = 0; j < multiplier; j++){
         multiplierString = multiplierString.concat(""+9); // 9, 99, 999
    }
    var product = 0;
    var result = 0;
    multiplicand = parseInt(multiplicandString); //999, 998...
    for(multiplicand;  multiplicand > 0; multiplicand--){ //Loop 999 times
       multiplier = parseInt(multiplierString); //999, 998...
       for(multiplier; multiplier > 0; multiplier--){//Loop 998001 times
          product = multiplicand * multiplier; //999*999,999*998...998*999,998*998...
          var stringProduct = (''+product);// 90909
          var strLength = stringProduct.length; //Make sure not to modify actual string
          for(strLength; strLength >= 1; strLength--){ //For the length of string
            if( stringProduct[0] == stringProduct[stringProduct.length-1]) //If 90909: 9==9, 090:0==0, 9:9==9
            {
              if(stringProduct.length <= 3){//allow for 090
                if(product > result){ //if product is larger than existing result replace it with new larger number
                  result = product;
                }
              }
              stringProduct = stringProduct.slice(1, -1);//take off the first and last numbers
            }
          }
        }
    }
  return result;
}


texts: Combining two arrays using nested foreach loops

texts:
I have the following arrays:

Array  (db_values)
(
[0] => Array
    (
        [system_name] => object_car_brand
        [value] => Alfa Romeo
        [id] => 136
    )

[1] => Array
    (
        [system_name] => object_car_model
        [value] => Spider
        [id] => 137
    )

)
Array (db_attributes)
(
[0] => Array
    (
        [id] => 105
        [system_name] => object_car_brand
    )

[1] => Array
    (
        [id] => 106
        [system_name] => object_car_model
    )

)

I combine these two using the following code:

       foreach($db_attributes as $db_attribute){
            foreach($db_values as $db_value){
                if($db_value["system_name"] === $db_attribute["system_name"]){
                    $update[$db_attribute["id"]] = $db_value["value"];
                }

            }

        }

I do not think that this is the most resource friendly way of doing it, is there a better way?


texts: malloc in main() or malloc in another function: allocating memory for a struct and its members

texts:
When initializing a struct in C, we can allocate memory inside the main function or within another function and return a pointer to the newly created struct. This first example shows the latter; memory is allocated in Buffer_create and a pointer is returned:

#include <stdio.h>
#include "buffer.h"

int main(int argc, char *argv[])
{
    struct Buffer *tx_buffer = Buffer_create(8);

    Buffer_destroy(tx_buffer);

    return 0;
}

And this one shows how all memory allocations can be done within the main function:

#include <stdio.h>
#include "buffer.h"

int main(int argc, char *argv[])
{
    uint8_t *ptr_rx_buffer = malloc(sizeof(uint8_t)*8);
    struct Buffer *rx_buffer = malloc(sizeof(struct Buffer));
    Buffer2_create(rx_buffer, ptr_rx_buffer, 8);

    Buffer2_destroy(rx_buffer);

    return 0;
}

And here are the contents of the header file buffer.h:

#ifndef _buffer_h
#define _buffer_h

#include <stdint.h>
#include <stdlib.h>

struct Buffer {
    uint8_t *buffer;
    size_t size;
};

struct Buffer *Buffer_create(size_t size);

void Buffer_destroy(struct Buffer *who);

void Buffer2_create(struct Buffer *who, uint8_t *buffer, size_t size);

void Buffer2_destroy(struct Buffer *who);

#endif

And buffer.c:

#include <stdint.h>
#include <assert.h>
#include <stdlib.h>
#include "buffer.h"

struct Buffer *Buffer_create(size_t size)
{
    struct Buffer *who = malloc(sizeof(struct Buffer));
    assert(who != NULL);

    who->buffer = malloc(sizeof(uint8_t)*size);
    who->size = size;

    return who;
}

void Buffer_destroy(struct Buffer *who)
{
    assert(who != NULL);
    free(who->buffer);
    free(who);
}

void Buffer2_create(struct Buffer *who, uint8_t *buffer, size_t size)
{
    assert(who != NULL);

    who->buffer = buffer;
    who->size = size;
}

void Buffer2_destroy(struct Buffer *who)
{
    assert(who != NULL);
    free(who->buffer);
    free(who);
}

The Result

Both approaches work and the executable files for both end up being the same size.

My Question

Will either of these approaches result in memory leaks or poor performance?


texts:
I have read the code reviews on this website: this one and this one

So creating the pool in itself might not be that difficult, I'm more worried about the client closing the connection or the connection not being given back to the pool.

So I have tried to implement this answer.

public interface Connection {
    Object read();
    void close();
    void rollback();
}

public class ConnectionImpl implements Connection{
    public ConnectionImpl(String connectionString) {
    }

    @Override
    public Object read() {
        return null;
    }

    @Override
    public void close() {
        // do stuff to close the connection
    }

    @Override
    public void rollback() {
        // do stuff to go back to a valid state
    }
}

/**
 * This will wrap the connectionImpl and make sure the client doesn't close the connection himself, it will instead release it
 */
public class ConnectionWrapper implements Connection {
    private Connection m_connection;
    private ConnectionPool connectionPool;

    public ConnectionWrapper(Connection connection, ConnectionPool connectionPool) {
        m_connection = connection;
    }

    @Override
    public Object read() {
        return m_connection.read();
    }

    @Override
    public void close() {
        connectionPool.release(m_connection);
    }

    @Override
    public void rollback() {
        m_connection.rollback();
    }

    @Override
    protected void finalize() throws Throwable {
        try{
            close();
        }finally {
            super.finalize();
        }
    }
}

public class ConnectionPool {
    private BlockingQueue<Connection> m_connections;
    private List<Connection> m_usedConnections;

    private int m_maxConnectionNumber;
    private String m_connectionString;

    private AtomicInteger m_currentConnectionNumber;

    public ConnectionPool(int maxConnectionNumber, String connectionString) {
        m_connections = new ArrayBlockingQueue<>(maxConnectionNumber);
        m_usedConnections = new ArrayList<>();
        m_maxConnectionNumber = maxConnectionNumber;
        m_connectionString = connectionString;
        m_currentConnectionNumber = new AtomicInteger(0);
    }

    public Connection get() throws InterruptedException {
        createNewConnectionIfNecessary();

        Connection connection = m_connections.take();
        m_usedConnections.add(connection);

        return connection;
    }

    public void release(Connection connection) {
        int usedConnectionIndex = m_usedConnections.indexOf(connection);
        if (usedConnectionIndex == -1) {
            return;
        }

        connection.rollback();
        m_usedConnections.remove(usedConnectionIndex);
        m_connections.offer(connection);
    }

    private void createNewConnectionIfNecessary() {
        synchronized(m_connections) {
            if (m_connections.isEmpty() && m_currentConnectionNumber.get() < m_maxConnectionNumber) {
                Connection connection = new ConnectionImpl(m_connectionString);
                ConnectionWrapper connectionWrapper = new ConnectionWrapper(connection,this);
                m_connections.add(connectionWrapper);
                m_currentConnectionNumber.getAndIncrement();
            }
        }
    }
}

So, few questions:

is my implementation thread-safe?
Is there any other way my implementation could result in not releasing the connection?
I know that the finalize method might not be called, resulting in a Connection leaking. Is there any way to prevent this?
In general, any other advice?


texts:
I'm a complete beginner, but I'd like to learn how to program. I really started 2 weeks ago.

So I tried the common exercise, aka the multiplication table, but I tried to add little things I learnt recently in order to challenge myself, like functions, tables and pointers even if it's useless here.

The code works well, but I have some warnings when compiling, and I don't know why, like *pointSize = NULL;

Besides, I'm sure my code could be cleaned up, so I'd like you to tell me how I can improve it.

Here's the result:

How long this table should be ? (0 - 50) 5

       |    1  |    2  |    3  |    4  |    5  |
================================================
    1  I    1  |    2  |    3  |    4  |    5  |
-------+-------+-------+-------+-------+-------+
    2  I    2  |    4  |    6  |    8  |   10  |
-------+-------+-------+-------+-------+-------+
    3  I    3  |    6  |    9  |   12  |   15  |
-------+-------+-------+-------+-------+-------+
    4  I    4  |    8  |   12  |   16  |   20  |
-------+-------+-------+-------+-------+-------+
    5  I    5  |   10  |   15  |   20  |   25  |
-------+-------+-------+-------+-------+-------+

/* Multiplication table */

#include <stdio.h>
short tableSize; // Number of multipliers
short question (short *pointSize); // Ask user how many multipliers
void error(short nbUser); // Cherck error
void multTable(); // The table

void main ()
{
    short i = 1, nbMultipliers;
    question(&nbMultipliers);
    error(nbMultipliers);
    tableSize = nbMultipliers;

    /* header */
    printf("       |");
    for (i = 1; i <= tableSize; i++)
    {
        printf("  %3u  |", i);
    }
    printf("\n");

    for (i = 1; i <= (tableSize + 1); i++)
    {
        printf ("========");
    }
    printf("\n");
   /* end header */

    multTable(); // the table
}

/* Ask user how many multipliers */
short question (short *pointSize)
{
    *pointSize = NULL;

    printf("How long this table should be ? (0 - 50) ");
    scanf("%u", pointSize);
    printf("\n");
}

void error (short nbUser)
{
    if (nbUser < 0 || nbUser > 50)
    {
        printf("Error : you must enter a number between 0 and 50");
    }
}

/* end Ask user how many multipliers */

void multTable()
{
    short i = 1, j = 1;
    short line[50] = {0};

    for (j = 1; j <= tableSize; j++)
    {
        printf("  %3u  I", j);
        for (i = 1; i <= tableSize; i++)
        {
            line[i] = i*j;
            printf ("  %3u  |", line[i]);
        }
        printf("\n");
        for (i = 1; i <= (tableSize + 1); i++)
        {
            printf ("-------+");
        }
        printf("\n");
    }

}


texts: Retrieve Internet explorer proxy settings from the registry

texts:
I just re-wrote a library to easily retrieve the proxy settings of Internet Explorer (self answered SO question: https://stackoverflow.com/q/41764614/3207406).

Git repository

GoDoc (with an example)

package ieproxy

import (
    "os"
    "strings"
    "sync"

    "golang.org/x/sys/windows/registry"
)

// StaticProxyConf containes the Windows configuration for static proxy
type StaticProxyConf struct {
    // Is the proxy active?
    Active bool
    // Proxy address for each scheme (http, https)
    // "" (empty string) is the fallback proxy
    Protocols map[string]string
    // Addresses not to be browsed via the proxy (comma-separated, like linux)
    NoProxy string
}

// AutomaticProxyConf contains the Windows configuration for automatic proxy
type AutomaticProxyConf struct {
    URL string // url of the .pac file
}

// WindowsProxyConf gathers the Windows configuration for proxy
type WindowsProxyConf struct {
    Static    StaticProxyConf    // static configuration
    Automatic AutomaticProxyConf // automatic configuration
}

type regeditValues struct {
    ProxyServer   string
    ProxyOverride string
    ProxyEnable   uint64
    AutoConfigURL string
}

var once sync.Once
var windowsProxyConf WindowsProxyConf

// GetConf retrieves the proxy configuration from the Windows Regedit
func getConf() WindowsProxyConf {
    once.Do(parseRegedit)
    return windowsProxyConf
}

// OverrideEnvWithStaticProxy writes new values to the
// http_proxy, https_proxy and no_proxy environment variables.
// The values are taken from the Windows Regedit (should be called in init() function)
func overrideEnvWithStaticProxy() {
    conf := getConf()
    if conf.Static.Active {
        for _, scheme := range []string{"http", "https"} {
            url, ok := conf.Static.Protocols[scheme]
            if !ok {
                url, ok = conf.Static.Protocols[""] // fallback conf
            }
            if ok {
                os.Setenv(scheme+"_proxy", url)
            }
        }
        if conf.Static.NoProxy != "" {
            os.Setenv("no_proxy", conf.Static.NoProxy)
        }
    }
}

func parseRegedit() {
    regedit, _ := readRegedit()

    protocol := make(map[string]string)
    for _, s := range strings.Split(regedit.ProxyServer, ";") {
        if s == "" {
            continue
        }
        pair := strings.SplitN(s, "=", 2)
        if len(pair) > 1 {
            protocol[pair[0]] = pair[1]
        } else {
            protocol[""] = pair[0]
        }
    }

    windowsProxyConf.Static = StaticProxyConf{
        Active:    regedit.ProxyEnable > 0,
        Protocols: protocol,
        NoProxy:   strings.Replace(regedit.ProxyOverride, ";", ",", -1), // to match linux style
    }
    windowsProxyConf.Automatic = AutomaticProxyConf{
        URL: regedit.AutoConfigURL,
    }
}

func readRegedit() (values regeditValues, err error) {
    k, err := registry.OpenKey(registry.CURRENT_USER, `Software\Microsoft\Windows\CurrentVersion\Internet Settings`, registry.QUERY_VALUE)
    if err != nil {
        return
    }
    defer k.Close()

    values.ProxyServer, _, err = k.GetStringValue("ProxyServer")
    if err != nil && err != registry.ErrNotExist {
        return
    }
    values.ProxyOverride, _, err = k.GetStringValue("ProxyOverride")
    if err != nil && err != registry.ErrNotExist {
        return
    }

    values.ProxyEnable, _, err = k.GetIntegerValue("ProxyEnable")
    if err != nil && err != registry.ErrNotExist {
        return
    }

    values.AutoConfigURL, _, err = k.GetStringValue("AutoConfigURL")
    if err != nil && err != registry.ErrNotExist {
        return
    }
    err = nil
    return
}

I'm interested to know if the "go-style" can be improved and any other suggestions!


texts:
problem statement: using React and Redux build an interest calculator that, given a principal, rate of annual interest, and number of years, will display the total principal plus interest using the formula
TOTAL = principal * (1 + (rate * years))
Any feedback welcome on the style, approach, etc.
<!doctype html>


texts: The stocks problem - find the biggest profit that can be made

texts:
The Stocks Problem: Given an array of n integers representing the
  price of a stock over the course of n days, determine the maximum
  profit you can make if you can buy and sell exactly 1 stock over these
  n days.

My solution is using the same approach as the merge sort algorithm. It is implemented using Java. I am looking for harsh feedback including advice on function names, layout, formating etc..

public static void main (String[] args) {
    // A few basic tests
    System.out.println(stocks(new Integer[]{1, 2, 3, 8, 5}) + " - should be 7");
    System.out.println(stocks(new Integer[]{100, -1000, 3, 8, -1, 9, -2000}) + " - should be 1009");
    System.out.println(stocks(new Integer[]{-3000, -1000, 3, 8, -1, 9, 2000}) + " - should be 5000");
    System.out.println(stocks(new Integer[]{-3000, 1001, 5001, -2000, 2000,  5000}) + " - should be 8001");
    System.out.println(stocks(new Integer[]{-3000, 1001, 5000, -2000, 2000,  5001}) + " - should be 8001");
    System.out.println(stocks(new Integer[]{-3000, 1001, 4000, -2000, 2000,  5000}) + " - should be 8000");
}

public static int stocks(Integer[] stocks) {
    // Calculate max and minimum value
    Integer[] maxmin = splitAndMerge(stocks);

    // Biggest stock is difference between max and min value (considering time)
    return maxmin[1] - maxmin[0];
}

public static  Integer[] merge(Integer[] leftMinMax, Integer[] rightMinMax) {
    // Finding the biggest min max combination between the 4 values.
    if (rightMinMax[1] - Math.min(rightMinMax[0], leftMinMax[0])
            > Math.max(rightMinMax[1], leftMinMax[1]) - leftMinMax[0]) {
        return new Integer[] {Math.min(rightMinMax[0], leftMinMax[0]), rightMinMax[1]};
    } else {
        return new Integer[] {leftMinMax[0], Math.max(rightMinMax[1], leftMinMax[1])};
    }
}

public static Integer[] splitAndMerge(Integer[] arr) {
    // Split array into two parts
    int split = arr.length / 2;
    Integer[] arrLeft = Arrays.copyOfRange(arr, 0, split);
    Integer[] arrRight = Arrays.copyOfRange(arr, split, arr.length);

    // Compute left and right - then return merged solution
    return  merge(left(arrLeft), right(arrRight));
}

public static Integer[] left(Integer[] left) {
    if (left.length == 1) {
        return new Integer[]{left[0], left[0]};
    } else if (left.length == 2) {
        return new Integer[]{Math.min(left[0], left[1]), left[1]};
    } else {
        return splitAndMerge(left);
    }
}

public static Integer[] right(Integer[] right) {
    if (right.length == 1) {
        return new Integer[]{right[0], right[0]};
    } else if (right.length == 2) {
            return new Integer[]{right[0], Math.max(right[1], right[0])};
    } else {
        return splitAndMerge(right);
    }
}

Also it should be noted that Math.max() - Math.min() cannot be used since the the min value could have occurred before the max value, which doesn't make sense given the scenario of selling stocks.


texts:
I have a requirement to capture a string in a specific format of * [Numeric Digits] *. This is how I have done right now but I think it would be faster with Regular Expressions. I don't have a lot of experience with RegEx, so please help me optimize this code using RegEx.

if (string.IsNullOrEmpty(BarcodeScan) && e.KeyChar.ToString() == "*")
    BarcodeScan = e.KeyChar.ToString();
else
{
    if (BarcodeScan.StartsWith("*"))
    {
        if (int.TryParse(e.KeyChar.ToString(), out i))
            BarcodeScan += i.ToString();

        else if (e.KeyChar.ToString() == "*")
        {
            BarcodeScan += "*";
            ArticleID = BarcodeScan.Substring(1, BarcodeScan.Length - 2);
        }
        else
            BarcodeScan = string.Empty;
     }
}

The above code is written in KeyPress event so I have to capture the string as the user is doing the input. Basically the first * means that the user has started entering Article ID and I keep on capturing numeric digits till he enters another *.

This means that

*2323 is valid but incomplete
*34h is invalid
*343f33 is invalid
*3434hsds3 * is invalid
*3412 * is valid and complete

How do I check for *2323 in regex?  I tried ^\*\d+ but it allows *22f as well.


texts: Python class to manage a table in SQLite

texts:
Module name:    database.py

Code:

import sqlite3

class Database(object):
    """sqlite3 database class that holds testers jobs"""
    DB_LOCATION = "/root/Documents/testerJobSearch/tester_db.sqlite"

    def __init__(self):
        """Initialize db class variables"""
        self.connection = sqlite3.connect(Database.DB_LOCATION)
        self.cur = self.connection.cursor()

    def close(self):
        """close sqlite3 connection"""
        self.connection.close()

    def execute(self, new_data):
        """execute a row of data to current cursor"""
        self.cur.execute(new_data)

    def executemany(self, many_new_data):
        """add many new data to database in one go"""
        self.create_table()
        self.cur.executemany('REPLACE INTO jobs VALUES(?, ?, ?, ?)', many_new_data)

    def create_table(self):
        """create a database table if it does not exist already"""
        self.cur.execute('''CREATE TABLE IF NOT EXISTS jobs(title text, \
                                                            job_id integer PRIMARY KEY,
                                                            company text,
                                                            age integer)''')

    def commit(self):
        """commit changes to database"""
        self.connection.commit()

I have a few questions here:

I named my python module as database.py and my class as Database, which is perhaps not the best way, as they are too generic and somewhat less informative and they are almost identical. Is there a better way to name them?
I exposed the database connection and database cur as instance variables. Is that a good practice?


texts:
I have some jquery that pretty much just runs a small drop-line navigation. Each tab size differs, so i used the same jquery line 5 times to make it look and function the way i wanted it to. I'm sure there is a way to condense it but im not quite a pro. Can anybody help me out a bit? The jquery is below, and here is the site for reference: http://solocreativegroup.com/ed_spa/index.php. Thanks!

here's the code that runs my drop-line nav.

$(document).ready(function() {

$("ul#topnav li.home").hover(function() { //Hover over event on list item
    $(this).css({ 'background' : 'url(images/tab_hobt.png) no-repeat top left'}); //Add background color + image on hovered list item
    $(this).find("span").show(); //Show the subnav
}, function() { //on hover out...
    $(this).css({ 'background' : 'none'}); //Ditch the background
    $(this).find("span").hide(); //Hide the subnav
});

$("ul#topnav li.about").hover(function() {
    $(this).css({ 'background' : 'url(images/tab_hobt.png) no-repeat top left'});
    $(this).find("span").show();
    $('.services a').css({'color':'#ffffff'});
}, function() {
    $(this).css({ 'background' : 'none'});
    $(this).find("span").hide();
    $('.services a').css({'color':'#921d49'});
});

$("ul#topnav li.services").hover(function() {
    $(this).css({ 'background' : 'url(images/tab_services.png) no-repeat top left'});
    $(this).find("span").show();
    $('.services a').css({'color':'#ffffff'});
}, function() {
    $(this).css({ 'background' : 'none'});
    $(this).find("span").hide();
    $('.services a').css({'color':'#921d49'});
});

$("ul#topnav li.testimonial").hover(function() {
    $(this).css({ 'background' : 'url(images/tab_testimonials.png) no-repeat top left'});
    $(this).find("span").show();
}, function() {
    $(this).css({ 'background' : 'none'});
    $(this).find("span").hide();
});

$("ul#topnav li.contact").hover(function() {
    $(this).css({ 'background' : 'url(images/tab_contact.png) no-repeat top left'});
    $(this).find("span").show();
}, function() {
    $(this).css({ 'background' : 'none'});
    $(this).find("span").hide();
});

HTML:

HOME

ABOUT

                PRODUCTS

            SERVICES

                FACIALS
                AGE MANAGEMENT
                MICRODERMABRASION
                SKIN RESURFACING
                ADD IT ON
                WAXING

TESTIMONIALS

CONTACT


texts:
This is a working linked list that will be used as a vector. Instead of using dynamic arrays, I am using a linked list. I would like to see a more concise solution without utilizing the STL.

SimpleVector.h

class SimpleVector
{

public:

    SimpleVector(){
        head = nullptr;
    }
    SimpleVector(const SimpleVector &);
    ~SimpleVector();

    void appendNode(const int value);
    void insertNode(const int value);
    int getElementAt(const int index);
    void displayVect();

private:

    struct Node
    {
        int value;
        Node *next;
    };

    Node *head;

};

Copy constructor implementation

SimpleVector::SimpleVector(const SimpleVector &obj)
{

    Node *oldNodePtr;
    Node *newNodePtr;

    // Initialize head to nullptr incase obj is empty
    this->head = nullptr;

    // Position oldNodePtr to the head of the list.
    oldNodePtr = obj.head;

    if (oldNodePtr != nullptr) {

        // Create new node. This is the first node in the new list
        Node *newNode = new Node;
        newNode->value = oldNodePtr->value;

        // Set head to new node address
        this->head = newNode;

        newNodePtr = newNode;

        oldNodePtr = oldNodePtr->next;

        // While oldNodePtr points to a node, traverse the list.
        while (oldNodePtr->next != nullptr) {

            Node *newNode = new Node;
            newNode->value = oldNodePtr->value;
            newNodePtr->next = newNode;
            newNodePtr = newNodePtr->next;

            oldNodePtr = oldNodePtr->next;
        }

        Node *lastNode = new Node;
        lastNode->value = oldNodePtr->value;
        newNodePtr->next = lastNode;
        lastNode = nullptr;
    }
}


texts: AngularJS directive that manually transcludes content and has isolated scope

texts:
I would like to hear the opinion of more experienced AngularJS developers on whether the following directive is best practice...

I was trying to make to make a directive that will include HTML that:

Can include compiled elements (other directives, like ng-src in the
example below)
Interpolated values ({{ value }})
Can include values/functions from the parent scope without modifying it (i.e. the
directive has isolated scope)

Example usage:

<tag>

{{ url }}

</tag>

Controller and directive implementation:

var testapp = angular.module('testapp', []);

var Ctrl = function($scope) {
    $scope.url = "http://google.com";
    $scope.image = "https://www.google.gr/images/srpr/logo4w.png";
};

testapp.directive('tag', function() {
  return {
    restrict: 'E',
    transclude: true,
    scope: { },
    compile: function compile(tElement, tAttrs, transclude) {
        return function(scope) {
            transclude(scope.$parent, function(clone) {
                tElement.append(clone);
            });
        }
    }
  }
});

Fiddle: http://jsfiddle.net/x5WcB/3/


texts:
I wanted to implement a Timsort in python.

Here's what I've come up with:

from typing import List

RUN = 32

def insertionSort(unsorted: List[int], left: int, right: int) -> None:
    """ Sorts the array using insertion sort """

    for i in range(left + 1, right + 1):
        temp = unsorted[i]
        j = i-1

        while unsorted[j] > temp and j >= left:
            unsorted[j+1] = unsorted[j]
            j -= 1

        unsorted[j+1] = temp

def merge(unsorted: List[int], left: int, middle: int, right: int) -> None:
    """ Merges two sorted arrays """

    len1 = middle - left + 1
    len2 = right - middle

    left_side  = unsorted[left : left + len1]
    right_side = unsorted[middle + 1 : middle + len2 + 1]

    i = j = 0
    k = left

    while i < len1 and j < len2:
        if left_side[i] <= right_side[j]:
            unsorted[k] = left_side[i]
            i += 1
        else:
            unsorted[k] = right_side[j]
            j += 1

        k += 1

    while i < len1:
        unsorted[k] = left_side[i]
        i += 1
        k += 1

    while j < len2:
        unsorted[k] = right_side[j]
        j += 1
        k += 1

def timSort(unsorted: List[int], length: int) -> None:
    """

    Sorts every 'RUN' elements by insertion sort as
            insertion sort is faster for smaller array lengths

    """

    # Sorts every RUN elements using insertion sort
    for i in range(0, length, RUN):
        insertionSort(unsorted, i, min(i + 31, length - 1))

    size = RUN

    # Merges every sorted subarray using Merge Sort
    while size < length:
        left = 0

        while left < length:
            mid = min(left + size - 1, length - 1)
            right = min(left + 2 * size - 1, length - 1)

            merge(unsorted, left, mid, right)

            left += size * 2

        size *= 2

if __name__ == '__main__':
    unsorted = list(map(int, input('Enter space seperated elements: ').split()))
    n = len(unsorted)

    timSort(unsorted, n)

    print('Here\'s the sorted array: ')
    print(*unsorted)

I think it looks good, but I want to make it even better.

PS: What would be the optimal length for RUN?


texts: 3-stack implementation with a single array

texts:
I'm teaching myself data structures and would really appreciate some feedback on my stack implementation.

A couple of things I'm not sure if I should be doing:

creation of the array and pointer using new
style

// Implement 3 stacks with one array
#include <iostream>

class SingleArrayStacks{
    private:
        int stack_size;
        int *array;
        int *pointers;
        int get_top_position(int stack_num){
            return (stack_num * stack_num)  + pointers[stack_num];
        }

    public:
        SingleArrayStacks (int array_size = 100, int num_stacks = 3) {
            array = new int[array_size];
            pointers = new int[num_stacks];
            stack_size =  array_size / num_stacks;
            std::fill_n(pointers, num_stacks, -1);
        }

        ~SingleArrayStacks (){
            delete[] array;
            delete[] pointers;
        }

        void print_stack (int stack_num) const {
            std::cout << "Current stack state: ";
            for (int i = 0; i < sizeof(array); i++) {
                std::cout << array[i];
            }
            std::cout << std::endl;
        }

        bool is_empty(int stack_num) const {
            return pointer[stack_num] == -1;
        }

        void push (int stack_num, int val) {
            if (pointers[stack_num] > stack_size) {
                throw std::runtime_error("Stack is full");
            } else {
                array[get_top_position(stack_num) + 1] = val;
                pointers[stack_num]++;
            }
        }

        int pop(int stack_num){
            if (is_empty(stack_num) {
                throw std::runtime_error("Stack is empty");
            } else {
                int val = array[get_top_position(stack_num)];
                array[get_top_position(stack_num)] = NULL;
                pointers[stack_num]--;
                return val;
            }
        }

        int top(int stack_num){
            if (is_empty(stack_num) {
                throw std::runtime_error("Stack is empty");
            } else {
                return array[get_top_position(stack_num)];
            }
        }
};


texts: Produce an array of strings from a single string

texts:
I have a function that reads a string like this

(AnimalCount+HumanCount)

and the result of this function is an array of strings

[ "(" , "AnimalCount" , "+" , "HumanCount" , ")" ]

Now, I have done 2 functions in order to do this:

The first one to check if a given char is "special" from the input string

function Validate(Character: Char): Boolean;
begin
  Validate:= Character in [',' , '+' , '-' , '*' , '/' , '(' , ')' , '^' ,
                         '[' , ']' , '%' , '&' , '=' , '<' , '>' , ' ' ,
                         '.' , ';' , ':'];
end;

The second one to separate the strings from the input:

function GetToken(Chain:String):ArrayofString;
Var NTokens,i,j:Integer;
begin
  NTokens:=0;
  SetLength(Result,0);
  For i := 1 to Length(Chain) do
    if Validate(Chain[i]) then
      begin
        Inc(NTokens);
        setlength(Result,NTokens+1);
        Result[NTokens]:=Chain[i];
        Inc(NTokens);
      end
    else
      begin
        If Length(Result)<NTokens+1 then
          begin
            setlength(Result,NTokens+1);
            Result[NTokens]:='';
          end;
        Result[NTokens]:=Result[NTokens]+Chain[i];
      end;
end;

Additionally, I had to put this after type to make it work this way:

Arrayofstring = array of String;

This functions are working, but I wonder if there is any way to improve it even further.  I am new to Delphi, so any help would be appreciated.


texts: ES5 class to handle analytics fetching and caching

texts:
This class reads a log file stored on my server, parses it, and returns it. It also caches the data so that subsequent calls to get the analytics data will not have to read from the file. The analytics files will be relatively small, so memory usage is not a concern.

The callback passed to getAnalytics() is expected to accept an error as its first parameter and data as its second parameter.

Suggestions on improvements and cleanups are welcome.

Link to file on GitHub

const fs = require('fs');
const geoip = require('geoip-native');

/**
 * Constructor for an Analytics object.
 * @constructor
 * @param {string} analyticsFile The path to the server analytics log
 */
function Analytics(analyticsFile) {
  this.analyticsFile = analyticsFile;
  this.cache = {};
}

/**
 * Milliseconds in an hour.
 * @const
 * @type {number}
 */
Analytics.CACHE_KEEP_TIME = 3600000;

/**
 * Factory method for an Analytics object.
 * @param {string} analyticsFile The path to the server analytics log
 * @return {Analytics}
 */
Analytics.create = function(analyticsFile) {
  return new Analytics(analyticsFile);
};

/**
 * Fetches analytics on recent site traffic and passes it to a callback.
 * Caches the results for a day.
 * @param {function()} callback The callback function to which the analytics
 *   are passed.
 * @return {?}
 */
Analytics.prototype.getAnalytics = function(callback) {
  /**
   * First check if we have analytics cached. If not, then we should fetch it
   * again.
   */
  var currentTime = (new Date()).getTime();
  if (this.cache.analytics && currentTime < this.cache.expires) {
    return callback(null, this.cache.analytics);
  }
  var context = this;
  fs.readFile(this.analyticsFile, 'utf-8', (error, data) => {
    if (error) {
      return callback(error);
    }
    try {
      data = data.trim().split('\n').map(function(entry) {
        entry = JSON.parse(entry);
        entry.country = geoip.lookup(entry.ip).name;
        return entry;
      });
      context.cache.analytics = data;
      context.cache.expires = currentTime + Analytics.CACHE_KEEP_TIME;
      return callback(null, data);
    } catch (error) {
      return callback(error);
    }
  });
};

/**
 * This line is needed on the server side since this is loaded as a module
 * into the node server.
 */
module.exports = Analytics;


texts:
Here is a simplified implementation to obtain the duplicate words in a text using lambda expressions.

public class FindDuplicateWordsInText {

    public static Set<String> findDuplicateWordsInText(String text) {
        String[] words = text.split(" ");
        Set<String> duplicatesRemovedSet = new HashSet<>();
        Set<String> duplicatesSet = Arrays.stream(words).filter(string -> !duplicatesRemovedSet.add(string))
                .collect(Collectors.toSet());
        return duplicatesSet;
    }
}