texts:
Problem Statement

  You are given a string, S , consisting of lowercase English letters.

  A string is beautiful with respect S to  if it can be derived from S by removing exactly 2 characters.

  Find and print the number of different strings that are beautiful with respect to S.

  Input Format

  A single string of lowercase English letters denoting S.

  Output Format

  Print the number of different strings that are beautiful with respect
  to S.

  Sample Input

  abba

  Sample Output

  4

  Explanation

  The following strings can be derived by removing  characters from S:
  ab, bb, ba, ab, ba, aa and bb.

  This gives us our set of unique beautiful strings, B = {ab, ba, aa,
  bb} as |B| = 4, we print 4

Here is my solution but it's not using dynamic programming. I am not getting any hints about how it can be solved via a DP approach.

function beautifulStrings(str) {
    const res = new Set()

    for (let i = 0; i < str.length - 1; i++) {
        for (let j = i + 1; j < str.length; j++) {
            let s = str.split('')
            s[i] = undefined
            s[j] = undefined
            res.add(s.join(''))
        }
    }

    return res.size
}


texts: Find smallest subset of integers having a given sum

texts:
Write a function that meets the specifications below:

def find_combination(choices, total):

    """
    choices: a non-empty list of ints
    total: a positive int

    Returns result, a array of length len(choices) such that
        * each element of result is 0 or 1
        * sum(result*choices) == total
        * sum(result) is as small as possible
    In case of ties, returns any result that works.
    If there is no result that gives the exact total,
    pick the one that gives sum(result*choices) closest
    to total without going over.
   """

My solution uses a brute force approach, but it is very slow. How can I implement a faster solution?

import itertools
import numpy as np

    def find_combination(choices, total):
        bins = np.array(list(itertools.product([0, 1], repeat=len(choices))))
        combinations = [b for b in bins if sum(choices * b) == total]
        return (min(combinations, key=sum) if combinations else
                max([b for b in bins if sum(choices * b) < total], key=sum))


texts:
I'm learning Racket and have implemented a mutable stack, which is just a bunch of wrappers around an underlying struct containing a size and buffer list (so it's not optimal, in terms of computational complexity). After consulting #racket and reading the first half of Greg Hendershott's Fear of Macros, I was able to write the syntax transformations I wanted for my implementation.

(module stack racket
  (module stack-implementation racket
    (struct stack (size buffer) #:mutable)

    ;; size :: stack -> integer
    (define (size stack) (stack-size stack))

    ;; non-empty-stack? :: stack -> boolean
    (define (non-empty-stack? stack)
      (and
        (stack? stack)
        (positive? (stack-size stack))))

    ;; push! :: stack -> any (new item) -> integer (size)
    (define (push! stack item)
      (set-stack-buffer! stack
        (append (list item) (stack-buffer stack)))

      (set-stack-size! stack (+ (stack-size stack) 1))

      (stack-size stack))

    ;; pop! :: (non-empty) stack -> any (head)
    (define (pop! stack)
      (let ([head (car (stack-buffer stack))]
            [tail (cdr (stack-buffer stack))])

        (set-stack-buffer! stack tail)
        (set-stack-size! stack (- (stack-size stack) 1))

        head))

    ;; make
    (define-syntax-rule (make name)
      (define name (stack 0 '())))

    (provide make
             stack?
             (contract-out
               [size  (-> stack?            integer?)]
               [push! (-> stack? any/c      integer?)]
               [pop!  (-> non-empty-stack?  any)])))

  (require 'stack-implementation
           (for-syntax racket/syntax))

  ;; make-stack
  ;  Defines a stack under the specified symbol <name>
  ;  Plus defines <name>-size, <name>-empty?, <name>-push! and <name>-pop!
  (define-syntax (make-stack stx)
    (syntax-case stx ()
      [(_ name)
        (with-syntax ([(size-fn empty-fn push-fn pop-fn)
                       (map (lambda (fn) (format-id stx "~a-~a" #'name fn))
                            '("size" "empty?" "push!" "pop!"))])
          #'(begin
              (make name)
              (define (size-fn)      (size name))
              (define (empty-fn)     (zero? (size-fn)))
              (define (push-fn item) (push! name item))
              (define (pop-fn)       (pop!  name))))]))

  (provide make-stack
           stack?))

I'm completely new to Racket and Lisp, so I'm guessing there are many improvements I can make here (e.g., the duplication in the macro where I define the helper function IDs), besides using a better underlying data structure.


texts: Calculating the nth prime number for huge BigIntegers

texts:
I wrote this simple class for calculating the nth prime:

package generator;

import java.math.BigInteger;

public class SimplePrimeNumberGenerator implements PrimeNumberGenerator {

    private static final BigInteger MINUS_ONE = BigInteger.valueOf(-1);
    private static final BigInteger ZERO = BigInteger.ZERO;
    private static final BigInteger ONE = BigInteger.ONE;
    private static final BigInteger TWO = BigInteger.valueOf(2);
    private static final BigInteger THREE = BigInteger.valueOf(3);
    private static final BigInteger SIX = BigInteger.valueOf(6);
    private static final BigInteger EIGHT = BigInteger.valueOf(8);

    @Override
    public BigInteger calculateNthPrimeNumber(BigInteger n) {
        if (n.compareTo(ZERO) <= 0) {
            throw new NumberFormatException(
                    "Can not calculate nth prime number for n=" + n);
        }
        BigInteger candidate, count;
        for (candidate = TWO, count = ZERO; count.compareTo(n) == -1; candidate = candidate
                .add(ONE)) {
            if (isPrime(candidate)) {
                count = count.add(ONE);
            }
        }
        return candidate.add(MINUS_ONE);
    }

    /*
     * Performs a simple primality test on the input parameter.
     */
    private static boolean isPrime(BigInteger candidate) {

        if (candidate.isProbablePrime(2)) {
            if (candidate.compareTo(TWO) == -1) {
                return false;
            }
            if (candidate.equals(TWO) || candidate.equals(THREE)) {
                return true;
            }
            if (candidate.mod(TWO).equals(ZERO)
                    || candidate.mod(THREE).equals(ZERO)) {
                return false;
            }
            BigInteger sqrtCandidate = sqrt(candidate).add(ONE);
            for (BigInteger i = SIX; i.compareTo(sqrtCandidate) <= 0; i = i
                    .add(SIX)) {
                if (candidate.mod(i.add(MINUS_ONE)).equals(ZERO)
                        || candidate.mod(i.add(ONE)).equals(ZERO)) {
                    return false;
                }
            }
            return true;
        } else {
            return false;
        }
    }

    /*
     * Derived from:
     * http://faruk.akgul.org/blog/javas-missing-algorithm-biginteger-sqrt/
     */
    private static BigInteger sqrt(BigInteger n) {
        BigInteger a = ONE;
        BigInteger b = n.shiftRight(5).add(EIGHT);
        while (b.compareTo(a) >= 0) {
            BigInteger mid = new BigInteger(a.add(b).shiftRight(1).toString());
            if (mid.multiply(mid).compareTo(n) > 0) {
                b = mid.subtract(ONE);
            } else {
                a = mid.add(ONE);
            }
        }
        return a.subtract(ONE);
    }
}

It scales reasonably well for five-digit-numbers n, but I need really large prime numbers (which is why I went with BigInteger in the first place). How can I achieve reasonable performance (one prime in less than five seconds) for calculating, say, the 10.000.000.000th prime number?


texts: Activating items in some randomized arrays

texts:
I've got a list with about 120 items in IE and I have some items I want to activate. I compare, build and randomize some Arrays on the fly. The for loop in the run() function is really slow, and i tried to add a setTimeout(), like i've read somewhere on stackoverflow.

It does not seem to improve the performance, and if the requested list of items to be activated is too large, IE starts to give the slow script error.

Can i optimize this to something that'll work?

for(index = 0; index < 120; index++){
            wrapper.tempSlot.push(index);
}
Array.prototype.shuffle = function shuffle(){
    var tempSlot;
    var randomNumber;
    for(var i =0; i != this.length; i++){
        randomNumber = Math.floor(Math.random() * this.length);
        tempSlot = this[i];
        this[i] = this[randomNumber];
        this[randomNumber] = tempSlot;
    }
}

Array.prototype.compare = function(testArr) {
    if (this.length != testArr.length) return false;

    for (var i = 0; i < testArr.length; i++) {
        if (this[i].compare) {
            if (!this[i].compare(testArr[i])) return false;
        }
        if (this[i] !== testArr[i]) return false;
    }
    return true;
}

function checkAgainstEl(val){
    val = $($item.select).eq(val).data('personid')
    return val in oc([array, with, to, be, activated, numbers]);
}

var index = 0;
var length = wall.globals.highlight.selection.length;
var run = function(){
    for(;index < length; index++){

        wrapper.tempSlot.shuffle();
        var pop     = wrapper.tempSlot.pop();
        var value   = wall.globals.highlight.selection[index];
        var newItem = $('#wallItem' + value);

        wrapper.objectsStr = wrapper.objectsStr + '#wallItem' + value + ', ';

        while(checkAgainstEl(pop)){
            wrapper.tempSlot.shuffle()
            pop = wrapper.tempSlot.pop();
        }

        beforeItem  = $($item.select).eq(pop);

        newItem.insertBefore(beforeItem);
        $($container.select).append(beforeItem);

        if (index + 1 < length && index % 5 == 0) {
                setTimeout(run, 25);
            }
    }
}
run();


texts:
I have made a Python program that can perform some prime number functions. For example, it can produce an endless output of sequential primes. I am looking for ways to make it faster and cleaner. When I was making it, I had a huge amount of trouble using generators, I don't know why, and what the problems were, because I made it long ago, so I had to stick to for loops and class variables in the end.

class Maths():
    prime = [2]
    squares = []
    primenum = 3
    sqrnum = 1
    fermat_number_true = 0
    fermat_number_false = 1

    def prime_generator(self):
        while True:
            if self.is_prime(self.primenum):
                self.prime.append(self.primenum)
                self.primenum += 2
                return self.primenum - 2
            self.primenum += 2

    def is_prime(self, num):
        for divisor in self.prime:
            quotient = num / divisor
            if quotient == int(quotient):
                return False
        return True

    def square_generator(self):
        while True:
            self.sqrnum += 1
            return (self.sqrnum - 1) * (self.sqrnum - 1)

    def square_output(self):
        while True:
            print(self.square_generator())

    def prime_output(self):
        while True:
            print(self.prime_generator())

    def prime_on_enter(self):
        while True:
            input()
            print(self.next_prime())

    def square_on_enter(self):
        while True:
            input()
            print(self.next_square())

    def next_prime(self):
        return self.prime_generator()

    def next_square(self):
        return self.square_generator()

    def next_fermat(self):
        while True:
            prime = self.next_prime()
            try:
                while self.squares[-1] < prime:
                    self.squares.append(self.next_square())
            except IndexError: self.squares.append(self.next_square())
            if self.isfermat_alg2(prime):
                self.fermat_number_true += 1
                return True, prime
            else:
                self.fermat_number_false += 1
                return False, prime
    def next_fermatf(self):
        true, num = self.next_fermat()
        if true:
            print("%d\t\t%f" % (num, (self.fermat_number_true / (self.fermat_number_false + self.fermat_number_true)) * 100))
        else:
            print("%d\tX\t%f" % (num, (self.fermat_number_true / (self.fermat_number_false + self.fermat_number_true)) * 100))

    def fermat(self):
        while True: self.next_fermatf()

    def isfermat_alg1(self, num, squares):
        for square in squares:
            if num > square:
                difference = num - square
                if difference in squares:
                    return True
        else:
            return False

    def isfermat_alg2(self, num):
        return bool(num % 4 == 1)

def main(): mathsobj.prime_output()

mathsobj = Maths()

if __name__ == '__main__':
    main()


texts:
I wanted to consolidate solutions to disparate problems into a single program. I am worried that there is a interface, command pattern, or dictionary solution to what will become a massive switch statement here.  However, the main in this program is essentially a meta-program which would switch between the miniature programs that it links to.

static void Main(string[] args)
{
    int eulerNumber;

    Console.WriteLine("Please enter the number of the Problem you want to solve.");

    while (!int.TryParse(Console.ReadLine(), out eulerNumber))
    {
        Console.WriteLine("Please enter a valid number.");
        Console.WriteLine();
        Console.WriteLine("Please enter the number of the Problem you want to solve.");
    }
    switch (eulerNumber)
    {
        case 1:
        //solve problem 1.
        break;

        case 2:
        //solve problem 2.
        break;
        case 3:
        //solve problem 3.

        break;
        etc. etc. etc.
    }
}

This is not an elegant solution, but it seems to mirror the situation quite well, as I see it.

Should I scratch this approach?  It seems to me to violate OCP but at the same time, it isn't chaotic, and isn't that much to keep track of, - just tack one more case onto the end, create a new class, and another problem is functional.  Should I look into some other structure to make it easier to modify?


texts: The efficiency and options of my PNG sequence JS class

texts:
I have built a JavaScript PNG sequence engine that allows for playing, pausing and stopping and a time change event. I am asking for genuine opinions if the code is actually good. Its ONLY for the iDevice range (not for desktop browsers or anything) and here is the code and a link to the gist if you wanted to edit it for examples.

Hope its as good as I think it is!

/**
 * @param slides ~ Array (ARRAY) of image locations
 * @param duration ~ Number - in milliseconds how long to run for
 * @param element ~ jQuery object - The <img> tag to change the src of.
 * @returns void
 *
 * @example
 *  <img src="#" id="sequence" data-loop="true" data-autoplay="true" />
 *  <script>var vid = new PNGSequence(tiffanyCrystal, 4, $('#sequence'));</script>
 */
var PNGSequence = function (slides, duration, element) {
    this.slides = slides;
    this.NSlides = slides.length;
    this.duration = duration;
    this.interval = (this.duration * 1000) / this.NSlides;
    this.element = element;
    this.index = 0;
    this.loop = this.element.data('loop') == true;
    this.autoplay = this.element.data('autoplay') == true;

    var inter;

    this.interGo = function () {
        var self = this;
        return setTimeout(function () {
            // Update the image
            element.attr({
                "src": slides[self.index]
            });

            // Increase the index
            self.index++;

            // Call the onTimeChange event
            if (self.hasOwnProperty('onTimeChange')) {
                if (self.onTimeChange) {
                    self.onTimeChange.call(self, self.index, self.NSlides);
                }
            }

            // Check if its the end of the animation
            if (self.index > self.NSlides) {
                // If we're not looping, clear the interval
                if (!self.loop) {
                    clearTimout(inter);
                } else {
                    // If we're looping then start the loop from the beginning
                    self.index = 0;
                    self.play();
                }
                return;
            }

            //Fire the timeout again
            self.interGo();
        }, this.interval);
    };

    /**
     * Pauses the sequence
     */
    this.pause = function () {
        clearTimout(inter);
        return this.index;
    };

    /**
     * Plays the sequence from last known point
     */
    this.play = function () {
        return inter = this.interGo();
    };

    /**
     * Stops the sequence and sets the pointer
     * at the beginning again
     */
    this.stop = function () {
        clearTimout(inter);
        this.index = 0;
        return 0;
    };

    this.onTimeChange = function () {
        return this;
    };

    if (this.autoplay) {
        inter = this.interGo();
    }

    return this;
};

And here is the link to the gist https://gist.github.com/3360011


texts:
Thats my method to test:

   public LessonplannerRequest GetWeeklyLessonplanner(int schoolyearId)
        {
            Schoolyear schoolyear = _unitOfWork.SchoolyearRepository.GetById(schoolyearId);
            DayOfWeek firstDayOfWeek = schoolyear.FirstDayOfWeek;

            DateTime currentDate = DateTime.Now.Date;
            DateTime startDateOfWeek = _dateService.GetFirstDateOfWeek(currentDate, firstDayOfWeek);
            DateTime endDateOfWeek = _dateService.GetLastDateOfWeek(currentDate, firstDayOfWeek);

            var periods = _unitOfWork.PeriodRepository.GetWeeklyPeriods(schoolyearId, startDateOfWeek, endDateOfWeek );
            var weeks = _dateService.GetAllWeekStartingDays(startDateOfWeek, endDateOfWeek, firstDayOfWeek);
            var request = new LessonplannerRequest
            {
                 Periods = periods,
                 Weeks = weeks,
            };

            return request;
        }

Thats my unit test:

 // Arrange
            Mock<IUnitOfWork> unitOfWorkMock = new Mock<IUnitOfWork>();
            Mock<IDateService> dateServiceMock = new Mock<IDateService>();
            Mock<TLPContext> contextMock = new Mock<TLPContext>();
            Mock<IGenericRepository<Schoolyear>> schoolyearRepositoryMock = new Mock<IGenericRepository<Schoolyear>>();
            Mock<ILessonplannerRepository> lessonplannerRepoMock = new Mock<ILessonplannerRepository>();

            int schoolyearId = 1;
            DateTime start = new DateTime(2010, 1, 1);
            DateTime end = new DateTime(2010, 1, 2);

            unitOfWorkMock.Setup(s => s.SchoolyearRepository).Returns(schoolyearRepositoryMock.Object);
            unitOfWorkMock.Setup(s => s.PeriodRepository).Returns(lessonplannerRepoMock.Object);
            dateServiceMock.Setup(s => s.GetFirstDateOfWeek(DateTime.Now.Date, DayOfWeek.Sunday)).Returns(start);
            dateServiceMock.Setup(s => s.GetLastDateOfWeek(DateTime.Now.Date, DayOfWeek.Sunday)).Returns(end);
            schoolyearRepositoryMock.Setup(s => s.GetById(schoolyearId)).Returns(new Schoolyear() { FirstDayOfWeek = DayOfWeek.Sunday });

            ILessonplannerService service = new LessonplannerService(unitOfWorkMock.Object, dateServiceMock.Object);

            // Act
            LessonplannerRequest request = service.GetWeeklyLessonplanner(schoolyearId);

            // Assert
            dateServiceMock.Verify(d => d.GetFirstDateOfWeek(DateTime.Now.Date, DayOfWeek.Sunday));
            dateServiceMock.Verify(d => d.GetLastDateOfWeek(DateTime.Now.Date, DayOfWeek.Sunday));
            lessonplannerRepoMock.Verify(d => d.GetWeeklyPeriods(schoolyearId, start, end));

            Assert.That(request.Periods, Is.Empty);
            Assert.That(request.Weeks, Is.Empty);

In my method to test all calls to a repository or dateService are already unit tested itself thus I am mocking them not to have an integration test...

I ask myself wether my assertion for empty lists make sense. And If not what would you test. Actually in this method everything is already tested just the creation of the LessonplannerRequest is not tested...


texts: Better way to query and pass the elements to conditional operator in Javascript

texts:
I have the following function which has the required functionality. Is there any way that I can reduce the code but have the same functionality?

addClickEventListeners = () => {
  let multipleChoiceQuestionButtons = document.querySelectorAll('[name="multiple_choice"]');
  let trueFalseQuestionButtons = document.querySelectorAll('[name="true_false"]');
  let multipleChoiceMultiAnswersQuestionButtons = document.querySelectorAll('[name="multi_answers"]');
  if (multipleChoiceQuestionButtons.length > 0) {
    multipleChoiceQuestionButtons.forEach((button) => {
      button.addEventListener('click', someFunction, false);
    });
  } else if (trueFalseQuestionButtons.length > 0) {
    trueFalseQuestionButtons.forEach((button) => {
      button.addEventListener('click', someFunction, false);
    });
  } else if (multipleChoiceMultiAnswersQuestionButtons.length > 0) {
    multipleChoiceMultiAnswersQuestionButtons.forEach((button) => {
      button.addEventListener('click', someFunction, false);
    });
  }
};


texts: In 8-puzzle finding nr of steps moving a tile to the right place

texts:
In 8-puzzle I want to count the number of moves it would take to move a specific tile to it's goal place. The problem is my method for this is >100 lines long which is obviously way too much. I'll only include part of that method that counts steps to move the piece to the right row if the goal row is higher. It gives the idea, it is probably hard to read even with that piece of it only, I did comment profusely though.

To further illustrate what the code does - for state {{0,2,3},{4,1,6},{7,8,5}} the count of steps for moving the 1 tile to first spot would be 5:

    2  3       2     3        2  1  3        2  1  3          1  3       1     3
 4  1  6   =>  4  1  6   =>   4     6   =>      4  6   =>  2  4  6   =>  2  4  6
 7  8  5       7  8  5        7  8  5        7  8  5       7  8  5       7  8  5

And for the code ( or bits and pieces of it):

    // Finding the nr of steps it would take to move tile to it's goal place
public int countSteps(int tileNr) {
    int steps = 0;
    int[] goal = findGoal(tileNr);
    int[] current = findTile(tileNr);
    int[] empty = findTile(0);
    GameState copy = new GameState(this);
    while (goal[0] != current[0] && goal[1] != current[1]) {
        // If the tile needs to be moved upwards (row coord is smaller in
        // goal)
        if (goal[0] < current[0]) {
            if (empty[0] == current[0] - 1 && empty[1] == current[1]) {
                // If empty above current tile, switch them
                steps++;
                current = empty;
                empty[0]++;
            } // Else have to move the empty tile to above current
            else if (empty[1] == current[1]) {
                if (empty[0] < current[0] - 1) {
                    // If empty too high in the right column, move empty
                    // tile down
                    steps++;
                    empty[0]++;
                }
                if (empty[0] > current[0]) {
                    // If empty below current, move out from that that
                    // column
                    steps++;
                    if (empty[1] < 2)
                        empty[1]++;

                    else
                        empty[1]--;
                }
            } else if (empty[0] == current[0]) {
                if (empty[1] < current[1]) {
                    // If empty to the right in right row
                    // move to the left
                    steps++;
                    empty[1]++;
                }
                if (empty[1] > current[1]) {
                    // If empty to the left in right row move to the right
                    // column
                    steps++;
                    empty[1]--;
                }

            }
        }
    }
    return steps;
}

// Finding coords for the tile in goal state
public int[] findGoal(int tileNr) {
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) {
            if (goalState[i][j] == tileNr)
                return new int[] { i, j };
        }
    }
    return new int[] { -1, -1 };
}

// Finding coords for the tile in current state
public int[] findTile(int tileNr) {
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) {
            if (state[i][j] == tileNr)
                return new int[] { i, j };
        }
    }
    return new int[] { -1, -1 };
}


texts:
This question has a follow up question:
  Binary Search Tree insert while keeping track of parent for node to be added - iteration 2

I am implementing a red black tree for fun and am wondering how I should modify my basic BST insert. Note: this happens before the red black tree rules are applied, it just finds the correct place within the tree to add the node, places it, sets references, value and defaults the color to RED. I am mainly struggling to see if there may be a better way to tack on the parent reference for the newly added node. The implementation I have here looks ahead one step with a NULL check where a BST insert that does not need to track the parent would not need.

struct node * bstInsert(struct node *n, int x) {

  if (n != NULL) {

    int cmp = (n->val < x) ? -1 : (n->val > x);

    if (cmp == -1) {

      if (n->left == NULL) {
        n->left = createAChild(n, n->left, x);
      } else {
        bstInsert(n->left, x);
      }

    } else if (cmp > 0) {

      if (n->right == NULL) {
        n->right = createAChild(n, n->right, x);
      } else {
        bstInsert(n->right, x);
      }

    }

  }

  return n;
}

struct node * createAChild(struct node *par, struct node *n, int x) {

  n = malloc(
    sizeof(struct node)
  );
  n->parent = par;
  n->left = n->right = NULL;
  n->val = x;
  n->color = RED;

  return n;

}

Is there a cleaner solution to setting the parent reference for the node to be added?


texts: Monte-Carlo method to estimate Pi runs slower in multiple threads, than in single thread

texts:
I'm learning Scala, and I wrote a program to estimate the value of Pi. When I'm using multiple threads, it takes 5-6 times longer to calculate the same iterations. I wrote a similar program in Java, with plain old threads, and with ExecutorService , and the results are the same.

Why is this the case?

(I have 4 cores in my processor, and during the multithreading calculation, the processor usage goes up to 100%.)

import java.util.Random
import java.util.concurrent.Executors
import java.util.concurrent.Callable

object Main {
  def main(args: Array[String]): Unit = {
    println("Calculating PI using the Monte-Carlo method")
    val n = 10000000
    evaluatePiCalculator(new SimplePiCalculator(n))
    evaluatePiCalculator(new ThreadedPiCalculator(n))
  }
  def evaluatePiCalculator(calc: PiCalculator) = {
    val pi = time { calc.calculate() }
    println(pi)
    val d = Math.abs(Math.PI - pi)
    println(d)
  }
  def time[R](block: => R): R = {
    val t0 = System.nanoTime()
    val result = block // call-by-name
    val t1 = System.nanoTime()
    val tdiff = t1 - t0
    println("Elapsed time: " + tdiff + "ns" + " " + (tdiff / 1000000) + "ms")
    result
  }
}
object Circle {
  class Point(val x: Double, val y: Double) {
    def isInside: Boolean = Math.sqrt(x * x + y * y) < 1.0
  }
  val random = new Random()
  private def randomPoint(): Point = {
    def generate() = random.nextDouble() * 2 - 1
    new Point(generate(), generate())
  }
  def tryToHit(): Boolean = randomPoint().isInside
}

abstract class PiCalculator() {
  def calculate(): Double
}

class SimplePiCalculator(n: Int) extends PiCalculator with Callable[Int] {
  override def call(): Int = calculateHits()
  def calculateHits(): Int = {
    var hits = 0
    for (i <- 1 to n) {
      if (Circle.tryToHit()) hits += 1
    }
    hits
  }
  def calculate(): Double = 4.0 * calculateHits / n
}
class ThreadedPiCalculator(n: Int) extends PiCalculator {
  val threads = 4
  val pool = Executors.newFixedThreadPool(threads)

  def calculate(): Double = {
    val f1 = pool.submit(new SimplePiCalculator(n / threads))
    val f2 = pool.submit(new SimplePiCalculator(n / threads))
    val f3 = pool.submit(new SimplePiCalculator(n / threads))
    val f4 = pool.submit(new SimplePiCalculator(n / threads))

    val (h1, h2, h3, h4) = (f1.get, f2.get, f3.get, f4.get)
    pool.shutdown()
    4.0 * (h1 + h2 + h3 + h4) / n
  }
}

Here are the results of the run:

Calculating PI using the Monte-Carlo method
Elapsed time: 473156580ns 473ms
3.1405192
0.0010734535897931607
Elapsed time: 3413799647ns 3413ms
3.1424036
8.109464102070696E-4

Update:

If I change the Circle object to a class, and create an instance inside of  SimplePiCalculator, and use that instance to calculate the hits, the expected performance discrepancy disappears. The calculation takes half the time of the single threaded implementation.

So the cause of this was using a common object from multiple threads.

However, when I tried to apply the same with the Java solution (i.e. change the tryToHit method from static to instance call), it did not work.

Can I ask, how to debug multithreaded code? What are the tools, methods, guidelines? How to determine the cause of slowdowns?


texts:
I just implemented my memcpy function without any previous lookup.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void * copy ( void * destination, const void * source, size_t num )
{
    if ((destination != NULL) && (source != NULL))
    {
        unsigned int *dst = destination;
        const unsigned int *src = source;

        unsigned int blocks = num/sizeof(unsigned int);
        unsigned int left = num%sizeof(unsigned int);

        while(blocks--){
            *dst++ = *src++;
        }

        if (left){
            unsigned char *cdst = (unsigned char *)dst;
            const unsigned char *csrc = (const unsigned char *)src;

            while(left--)
                *cdst++ = *csrc++;
        }

    }

    return destination;
}

When looking at other memcpy implementations I find some differences:

unaligned address not handled
use of long instead unsigned int

Now what I didn't understand is point number 2. As far I know int will always be CPU WORD size i.e for 16bit it will be 2bytes and 32bit it will be 4bytes. But for long it must be 32bit minimum.


texts: Functions to count vowels and consonants in strings

texts:
I am coming to a problem where I am  writing a function that accepts a pointer to a C-string as its argument. The function should count the number of vowels appearing in the string and return that number. Then, I am writing another function that accepts a pointer to a C-string as its argument. This function should count the number of consonants appearing in the string and return that number.

Am I violating any of the following restrictions?

No global variables
No labels or go-to statements
No infinite loops, examples include: for(;;), while(1), while(true), do{//code}while(1);
No break statements to exit loops

Here is my code:

#include<iostream>

using namespace std;

//Function prototypes
int Vowel_count( char *str);

int Consonant_count(char *str);

 int main()

    {

     char String[30];

     char choice;

     int Nvowels,Nconsonant;

     //Input a string

     cout<<"Enter a string:";

     cin.getline(String ,30);

     do

     {

     //Displaying Menu

     cout<<"\nMENU"<<endl;

     cout<<" (A) Count the number of vowels in the string"<<endl;

     cout<<" (B) Count the number of Consonants in the string"<<endl;

     cout<<" (C) Count both the vowels and consonants in the string"<<endl;

     cout<<" (D) Enter another string"<<endl;

     cout<<" (E) Exit program"<<endl;

     //Inputting choice

      cout<<"Enter choice";

     cin>>choice;

     switch(choice)

     {

     case 'A':
     //Function call to get number of Vowels

               Nvowels=Vowel_count(String);
                cout<<"Number of vowels is:"<<Nvowels<<endl;

              break;

     case 'B':
     //Function call to get number of consonants

                Nconsonant=Consonant_count(String);

                //Outputting number of Consonants

               cout<<"Number of Consonants is:"<<Nconsonant<<endl;

                 break;

     case 'C':
     //Function call to get number of Vowels

                Nvowels=Vowel_count(String);

                //Function call to get number of consonants

                Nconsonant=Consonant_count(String);

              //Outputting Both Vowels and Consonants

              cout<<"Number of vowels is:"<<Nvowels<<endl;

                   cout<<"Number of Consonants is:"<<Nconsonant<<endl;

                 break;

     case 'D': //Inputting another string

                 cout<<"Enter another String:";

                 fflush(stdin);

                 cin.getline(String ,30);

                 break;

     case 'E': exit(0);

                  break;

     }//End of Switch

     }while(choice !='E');//End Do while

    //Pause system for a while

     system("pause");

}//End main

//Function Definitions

int Vowel_count( char *str)

{

   int count=0;//Local variable

   //Checks for all characters in C-string

   while(*str!='\0')

   {

    if(*str=='a'||*str=='e'||*str=='i'||*str=='o'||*str=='u')

         count++;

         str++;

   }//End While

//Returns count value to function call

   return count;

}//End of Vowel_count

int Consonant_count(char *str)

{

int count=0;

    //Checks for all characters in C-string

     while(*str!='\0')

     { //Checks for consonants

     if(*str!='a'&&*str!='e'&&*str!='i'&&*str!='o'&&*str!='u')

          count++;

        str++;

     }//End While

     //Returns count value to function call

     return count;

}


texts: Does this generic query follow good OOP standards?

texts:
I am trying to convert over to MySQLi and wanted expert advice.  Is the enclosed code 100% OOP.  Also, how secure is the code against attacks?  I know nothing is 100% secure, but how good/safe is it?  How and what can I make better?  This is just a generic query as I wanted to get a basic model setup.

<?php
define ('DB_HOST', 'localhost');                       //  Host name
define ('DB_USER', 'root');                            //  Mysql username
define ('DB_PASSWORD', 'password');                    //  Mysql password
define ('DB_NAME', 'database');                        //  Database name

// New Connection
$mysqli = new mysqli(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME);

require("dbcon.php");  // This is actually the code above in a separate file that I have included here for checking.

$query = "SELECT id, username, firstname FROM users WHERE firstname=?";

if ($stmt = $mysqli->prepare($query))
{
   // Bind the variables
   $firstname = $_POST[first_name];

   // Bind parameters  s - String, b - Boolean, i - Integer etc
   $stmt->bind_param("s", $firstname);
   // Execute it
   $stmt->execute();
   // Store it for num rows
   $stmt->store_result();
   $num_rows = $stmt->num_rows;
   // Assign blank variables
   $id = "";
   $username = "";
   $firstname = "";
   // Bind the result and retrieve the data
   $stmt->bind_result($id, $username, $firstname);
      if(($num_rows) > 0)
      {
         while($stmt->fetch())
         {
            echo $id;
            echo "
";
            echo $username;
            echo "
";
            echo $password;
            echo "
";
            echo "Number of rows: ", $num_rows;
            echo "
";
            echo "
";
         }
      }
      else
      {
         echo "No records";
      }
   // Close the statement
   $stmt->close();
}
// Close connection
$mysqli->close();
?>


texts:
I was wondering, beyond the standard improvements that this needs, is there a more "clever" way of solving this problem?

The problem is to translate letters into digits without changing the format of the original string. The conversion is based on the international standard letter/number mapping on phones (i.e. where ABC is 2, DEF is 3, ..., PQRS is 7, TUV is 8, and WXYZ is 9).

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

        System.out.print("Enter a string: ");
        String s = input.nextLine();

        System.out.println(getNumbers(s));
    }

    public static String getNumbers(String s) {
        String result = new String();

        //Read and append s onto result
        for (int i = 0; i < s.length(); i++) {
            if (Character.isLetter(s.charAt(i))) {
            result += getNumber(Character.toUpperCase(s.charAt(i)));
            }
            else {
                result += s.charAt(i);
            }
        }
        return result;
    }

    public static int getNumber(char upperCaseLetter) {
        int number = ((upperCaseLetter - 'A') / 3) + 2;
        if (number < 7) {
            return number;
        }
        else if (upperCaseLetter - 'A' < 20) {
            return 7;
        }
        else if (upperCaseLetter - 'A' < 23) {
            return 8;
        }
        else {
            return 9;
        }
    }
}


texts: My first implementation of a client/server application

texts:
Well, it's 2 applications really. Each one does its own stuff on the front-end. It's the networking that I'm most concerned about.

The Server starts listening for connections on the specified port as soon as it starts up. When clients connect, it accepts, serves and boots them in turn (or rather that's the idea but I think there's a flaw in what I've got here).

The server is multithreaded to handle requests on new threads so as to avoid locking its UI while it works.

public void StartListening()
{
    TcpListener Svr = null;

    Int32 Port = 13000;
    IPAddress LocalAddress = IPAddress.Parse("127.0.0.1");

    Svr = new TcpListener(LocalAddress, Port);

    Svr.Start();

    Byte[] Buffer = new Byte[1024];

    Task.Run(() =>
    {
        while (true)
        {
            TcpClient Client = Svr.AcceptTcpClient();
            NetworkStream Stream = Client.GetStream();

            byte[] Response = HandleClientData(Stream, Buffer, Client);

            Stream.Write(Response, 0, Response.Length);

            Client.Close();
        }
    });
}

The function that reads and works with the data HandleClientData(NetworkStream, byte[], TcpClient) looks like this:

private byte[] HandleClientData(NetworkStream stream, Byte[] buffer, TcpClient client)
{
    int i;

    byte[] value = null;

    while ((i = stream.Read(buffer, 0, buffer.Length)) != 0)
    {
        string ClientData = Encoding.ASCII.GetString(buffer, 0, i);

        // do stuff with the client data and send a response
        value = ...;
    }
return value;
}

The Client is much the same, except its not listening for connections. It's only job is to send requests to the server and display the result that the server sends back:

public class _TcpClient
{
    public const string Server = "127.0.0.1";
    public const int Port = 13000;

    public string SendData(string data)
    {
        try
        {
            string Response = String.Empty;
            using (TcpClient Client = new TcpClient())
            {
                Client.Connect(Server, Port);

                using (NetworkStream Stream = new NetworkStream(Client.Client))
                {
                    Stream.Write(Encoding.ASCII.GetBytes(data), 0, 256);

                    int ByteRead = 0;
                    byte[] Buffer = new Byte[256];

                    while (ByteRead > 0)
                    {
                        ByteRead = Stream.Read(Buffer, 0, 256);
                        Response += Encoding.ASCII.GetString(Buffer, 0, ByteRead);
                    }
                }
            }

            return Response;
        }
        catch (Exception ex)
        {
            return String.Format("ERR,{0}", ex.Message);
        }
    }
}

To keep things simple, all comms between client and server send and receive delimited strings which are read by each component and handled in a particular way for each.

Is this a fairly decent implementation or a client/server program? How can I improve this or make it more functional?


texts: Definite Integral Approximation using the Trapezoidal Method

texts:
I wrote a program to calculate the value of Definite Integral of a function from a to b. It used the trapezoidal approximation method where the function area is divided into 'n' trapeziums and area of each is added.

def calculate_area(f, a, b, n):
    # Trapezoidal approximation: divide area of function into n trapeziums and add areas.
    # Large n value means better approximation

    # Finds the value of a definite integral from lower_lim (a) to upper_lim (b)
    # integral f(x) from lower_lim to upper_lim is =
    # 0.5 * w * ( f(a) + f(b) ) + <----- part_1
    # w * SUMMATION(x varies from 1 to n-1): f(a + x * w) <----- part_2
    # where w = (b - a) / n

    w = (b - a) / float(n)
    part_1 = 0.5 * w * ( f(a) + f(b) )
    part_2 = 0
    for x in range(1, n):
        part_2 += f(a + x * w)
    part_2 *= w
    total_area = part_1 + part_2
    return total_area

For example, this can be used to calculate the area of a circle (or \$\pi\$ if the radius of the circle is 1):

  Consider the circle \$x^2 + y^2 = 1\$

  Area of this circle = \$\pi\$

  Expressed as a function of x is: f(x) = (1 - x^2) ^ 0.5

  Integrating this from 0 to 1 gives us a quarter of a circle whose
  area is \$\frac\pi  4\$ (or the approximate value if we use approximate integration).

  On multiplying 4, we get the value of \$\pi\$.

  Pass in the following as arguments :

f = lambda x: (1 - x**2) ** 0.5; a = 0; b = 1

Now I face the following issues:

Code is not very Pythonic.
Code is not very efficient and fast.
For better precision of PI value, the value of n must be increased. Python doesn't comply when n takes higher values (say 100 million). n = 10 million worked and I got a value of PI that was accurate upto 8 digits after the decimal.
I feel that using floating point like datatypes which provide higher precision will increase precision of PI value. Correct me if I'm wrong.

I know that this is a very poor method of approximating the value of \$\pi\$ (this is the best I could come up with high school level knowledge). Let me know when I'm going to reach the limits. That is, when I will no longer be able to get noticeably more precise value of \$\pi\$.


texts: Turn On/Off Functions to speed things up

texts:
I have these two macros that are like my Yin & Yang. They turn off and on functions in excel so my macros calculate quicker.

I call on in the beginning and one at the end.

Is there anything I can do or add to these to make them better?

Private Sub TurnOffFunctions()

    Application.ScreenUpdating = False
    Application.DisplayStatusBar = False
    Application.Calculation = xlCalculationManual
    Application.EnableEvents = False

End Sub

Private Sub TurnOnFunctions()

    Application.ScreenUpdating = True
    Application.DisplayStatusBar = True
    Application.Calculation = xlCalculationAutomatic
    Application.EnableEvents = True

End Sub


texts: C# approach to prevent null references in strings

texts:
My insight here is that it's usually not useful to distinguish between null and empty strings. Sometimes it is, but usually not. Usually I like to assign my strings as empty if they would have been null.

var lastName = Request.Params["lastName"] ?? ""

Thus I had the idea of a struct which would wrap a real string, internally coalesce it to "", prevent all manner of null references, provide "less dangerous" versions of common string operations, yet still be compatible with strings.

This is an incomplete listing--I just wanted to get feedback on the idea. Please let me know why this is awesome, mediocre, or just plain terrible!

//with normal string
public void WriteName(string name)
{
    if(name != null && name.Length > 30)
    { name = name.Substring(0,30); }

    Console.WriteLine(name);
}

//with safestring
public void WriteName(SafeString name)
{
    Console.WriteLine(name.ReduceTo(30));
}

Below is the SafeString struct:

/// <summary>
/// Struct wrapper for a string, to prevent null references when you
///  don't care to distinguish between `null` and empty strings.
/// Has implicit conversions to & from string
/// </summary>
public struct SafeString : IEquatable<SafeString>, IEquatable<string>
{
    /*
      The wrapped string value.
      This will be properly initialized only if the constructor is called.
      It's possible to create a struct with `default(SafeString)`
        or by calling the parameterless ctor, `new SafeString()`
      C#6 will allow us to define a parameterless ctor,
        but there is still the issue of `default(SafeString)` which does not call any ctor.
      Thus when we wish to use the value of `_theString`,
        we need to either to check for null or funnel access through a helper
    */
    private string _theString;

    public SafeString(string s)
    {
        _theString = s ?? "";
    }

    public override string ToString()
    {
        //perform initialization in case this was created without using the ctor
        return _theString ?? (_theString = "");
    }

    public int Length { get { return ToString().Length; } }

    //safe substring method -- so you don't get an error when asking for a substring
    //   longer than the original
    public SafeString SubString(int start, int length)
    {
        if (start < 0)
        {
            start = 0;
        }
        if (length <= 0)
        {
            return "";
        }

        var over = Math.Max((start + length) - Length, 0);
        length = length - over;

        return ToString().Substring(start, length);
    }

    //shorthand for SubString(0,length), for when you wish to cut a string down to size
    public SafeString ReduceTo(int length)
    {
        if (length > Length)
        {
            return this;
        }
        return SubString(0, length);
    }

    public bool IsEmpty { get { return string.IsNullOrEmpty(_theString); } }
    public bool IsWhitespace { get { return string.IsNullOrWhiteSpace(_theString); } }

    public static implicit operator string(SafeString ss)
    {
        return ss.ToString();
    }

    public static implicit operator SafeString(string s)
    {
        return new SafeString(s);
    }

    public override int GetHashCode()
    {
        return ToString().GetHashCode();
    }

    public override bool Equals(object obj)
    {
        if (obj is SafeString)
        {
            return Equals((SafeString) obj);
        }
        if (obj is string)
        {
            return Equals((string) obj);
        }

        return false;
    }

    public bool Equals(SafeString other)
    {
        return ToString() == other.ToString();
    }

    public bool Equals(string other)
    {
        if (other == null)
        {
            return ToString() == ""; //we are never 'null'
        }
        return other == ToString();
    }
}


texts: Concatenating prefix of one array with the reversed suffix of another array

texts:
Given two arrays and two indices, I need to concatenate the prefix of the first array and the reversed prefix of the second array.

For example:

// Input
arr1 = [1,2,3,4,5,6,7,8,9];
arr2 = [10,11,12,13,14,15];
ind1 = 6;
ind2 = 3;

// Output
arr = [1,2,3,4,5,6,12,11,10];

I have implemented two different functions for this purpose:

function func1(arr1,arr2,ind1,ind2)
{
    let arr = [];
    for (let n = 0; n <= ind1; n++)
        arr.push(arr1[n]);
    for (let n = ind2; n >= 0; n--)
        arr.push(arr2[n]);
    return arr;
}

function func2(arr1,arr2,ind1,ind2)
{
    return arr1.slice(0, ind1 + 1).concat(arr2.slice(0, ind2 + 1).reverse());
}

And now I would like determine which one of them is better, using this performance analysis:

function measure(func,arr1,arr2,ind1,ind2)
{
    let t0 = performance.now();
    arr = func(arr1,arr2,ind1,ind2);
    let t1 = performance.now();
    return t1 - t0;
}

results = '';

for (let len = 10; len <= 120; len += 10)
{
    let func1Count = 0;
    let func2Count = 0;
    for (let i=0; i<1000000; i++)
    {
        let arr1 = new Array(len);
        let arr2 = new Array(len);
        let ind1 = Math.floor(Math.random()*len);
        let ind2 = Math.floor(Math.random()*len);
        func1Count += measure(func1,arr1,arr2,ind1,ind2);
        func2Count += measure(func2,arr1,arr2,ind1,ind2);
    }
    if (func1Count < func2Count)
        results += 'len='+len+': func1 is better ('+func1Count+' vs '+func2Count+')\n';
    else
        results += 'len='+len+': func2 is better ('+func1Count+' vs '+func2Count+')\n';
}

alert(results);

The test above indicates that the first function is better if the array length is (approximately) 80 or less, and that the second function is better otherwise.

I would like to ensure the correctness of my performance analysis.

In addition, I should note that this code will eventually run on server side (i.e., NodeJS), but I am testing it on client side (i.e., a browser). So if this method is fundamentally wrong (i.e., testing a server-side code over a client-side platform), then I would be happy to be notified.


texts: Singleton SpinLock: Making Random Thread-Safe

texts:
Is this a valid and safe use of .NET's System.Threading.SpinLock?

  Why am I doing this?

  Random's public methods are not thread-safe. I could be calling from
  any thread which I do not know until run-time; they are from the
  Thread Pool, and it could be called fairly frequently (up to a hundred
  times a second), so I would rather not create a new Random object each
  time.

public static class SingleRandom
{
    private static Random random;
    private static SpinLock spinLock;

    static SingleRandom()
    {
        random = new Random();
        spinLock = new SpinLock();
    }

    public static int Next()
    {
        bool gotLock = false;
        spinLock.Enter(ref gotLock);
        int rv = random.Next();
        if(gotLock)
            spinLock.Exit(false); // ASSUMPTION not IA64, TODO what if ARM?
        return rv;
    }

    public static int Next(int min, int max)
    {
        bool gotLock = false;
        spinLock.Enter(ref gotLock);
        int rv = random.Next(min, max);
        if (gotLock)
            spinLock.Exit(false); // ASSUMPTION not IA64, TODO what if ARM?
        return rv;
    }

    public static double NextDouble()
    {
        bool gotLock = false;
        spinLock.Enter(ref gotLock);
        double rv = random.NextDouble();
        if (gotLock)
            spinLock.Exit(false); // ASSUMPTION not IA64, TODO what if ARM?
        return rv;
    }
}


texts: The fastest way to import and edit data in R

texts:
So I want to import and edit a huge amount of data. I have a file with multiple data sets from time series that are chronologically ordered. Now I want to open them and edit to have a final dataset where the files are edited and ordered.

The code looks like this but it is taking some time to load the data:

setwd <-("C:/Users/D60378/Desktop/DATA")
path_data <- 'test'
files_data <- list.files(path_data)
length(files_data)
for (i in 1:length(files_data)){
 # use intermediary path if nested dir
tempPath <- file.path(getwd(), path_data, files_data[i])
  # name of the dataser
   name <- gsub('-', '_', substr(files_data[i], start = 0, stop =     (nchar(files_data[i])-4)))
   print(name)
     df <- read.csv(tempPath, skip=5, header=FALSE, sep = ';', dec = ',') #sheet 1 is the
   # column names
   df_names <- read.csv(tempPath, skip=4, nrows=1, header=FALSE, sep = ';', dec=',')
   dfnames_test_MS7 <- c()
   for (i in 1:length(df_names)){
     print(as.character(df_names[[i]]))
    dfnames_test_MS7[i] <- as.character(df_names[[i]])
   }
   dfnames_test_MS7[1] <- "DateTime"
   for (i in 1:length(dfnames_test_MS7)){
     dfnames_test_MS7[i] <- gsub(' ', '_', dfnames_test_MS7[i])
   }
  dfnames_test_MS7

   names(df) <- dfnames_test_MS7
   assign(name, df)
}


texts: How to make my backtraching sudoku solving algorithm in Python faster?

texts:
I wrote a backtracking Sudoku solving algorithm in Python.
It solves a 2D array like this (zero means "empty field"):

[
  [7, 0, 0, 0, 0, 9, 0, 0, 3],
  [0, 9, 0, 1, 0, 0, 8, 0, 0],
  [0, 1, 0, 0, 0, 7, 0, 0, 0],
  [0, 3, 0, 4, 0, 0, 0, 8, 0],
  [6, 0, 0, 0, 8, 0, 0, 0, 1],
  [0, 7, 0, 0, 0, 2, 0, 3, 0],
  [0, 0, 0, 5, 0, 0, 0, 1, 0],
  [0, 0, 4, 0, 0, 3, 0, 9, 0],
  [5, 0, 0, 7, 0, 0, 0, 0, 2],
]

like this:

[
  [7, 5, 8, 2, 4, 9, 1, 6, 3],
  [4, 9, 3, 1, 5, 6, 8, 2, 7],
  [2, 1, 6, 8, 3, 7, 4, 5, 9],
  [9, 3, 5, 4, 7, 1, 2, 8, 6],
  [6, 4, 2, 3, 8, 5, 9, 7, 1],
  [8, 7, 1, 9, 6, 2, 5, 3, 4],
  [3, 2, 7, 5, 9, 4, 6, 1, 8],
  [1, 8, 4, 6, 2, 3, 7, 9, 5],
  [5, 6, 9, 7, 1, 8, 3, 4, 2]
]

But for "hard" Sudokus (where there are a lot of zeros at the beginning), it's quite slow. It takes the algorithm around 9 seconds to solve the Sudoku above. That's a lot better then what I startet with (90 seconds), but still slow.

I think that the "deepcopy" can somehow be improved/replaced (because it is executed 103.073 times in the example below), but my basic approaches were slower..

I heard of 0.01 second C/C++ solutions but I'm not sure if those are backtracking algorithms of some kind of mathematical solution...

This is my whole algorithm with 2 example Sudokus:

from copy import deepcopy

def is_sol_row(mat,row,val):
  m = len(mat)
  for i in range(m):
    if mat[row][i] == val:
      return False
  return True

def is_sol_col(mat,col,val):
  m = len(mat)
  for i in range(m):
    if mat[i][col] == val:
      return False
  return True

def is_sol_block(mat,row,col,val):
  rainbow = [0,0,0,3,3,3,6,6,6]
  i = rainbow[row]
  j = rainbow[col]
  elements = {
    mat[i + 0][j + 0], mat[i + 1][j + 0], mat[i + 2][j + 0],
    mat[i + 0][j + 1], mat[i + 1][j + 1], mat[i + 2][j + 1],
    mat[i + 0][j + 2], mat[i + 1][j + 2], mat[i + 2][j + 2],
  }
  if val in elements:
    return False
  return True

def is_sol(mat,row,col,val):
  return is_sol_row(mat,row,val) and is_sol_col(mat,col,val) and is_sol_block(mat,row,col,val)

def findAllZeroIndizes(mat):
  m = len(mat)
  indizes = []
  for i in range(m):
    for j in range(m):
      if mat[i][j] == 0:
        indizes.append((i,j))
  return indizes

def sudoku(mat):
  q = [(mat,0)]
  zeroIndizes = findAllZeroIndizes(mat)
  while q:
    t,numSolvedIndizes = q.pop()
    if numSolvedIndizes == len(zeroIndizes):
      return t
    else:
      i,j = zeroIndizes[numSolvedIndizes]
      for k in range(1,10):
        if is_sol(t,i,j,k):
          newt = deepcopy(t)
          newt[i][j] = k
          q.append((newt,numSolvedIndizes+1))
  return False

mat = [
  [7, 0, 0, 0, 0, 9, 0, 0, 3],
  [0, 9, 0, 1, 0, 0, 8, 0, 0],
  [0, 1, 0, 0, 0, 7, 0, 0, 0],

  [0, 3, 0, 4, 0, 0, 0, 8, 0],
  [6, 0, 0, 0, 8, 0, 0, 0, 1],
  [0, 7, 0, 0, 0, 2, 0, 3, 0],

  [0, 0, 0, 5, 0, 0, 0, 1, 0],
  [0, 0, 4, 0, 0, 3, 0, 9, 0],
  [5, 0, 0, 7, 0, 0, 0, 0, 2],
]

# mat = [
#   [3, 0, 6, 5, 0, 8, 4, 0, 0],
#   [5, 2, 0, 0, 0, 0, 0, 0, 0],
#   [0, 8, 7, 0, 0, 0, 0, 3, 1],
#   [0, 0, 3, 0, 1, 0, 0, 8, 0],
#   [9, 0, 0, 8, 6, 3, 0, 0, 5],
#   [0, 5, 0, 0, 9, 0, 6, 0, 0],
#   [1, 3, 0, 0, 0, 0, 2, 5, 0],
#   [0, 0, 0, 0, 0, 0, 0, 7, 4],
#   [0, 0, 5, 2, 0, 6, 3, 0, 0]
# ]

print(sudoku(mat))


texts:
Today, my project was to make a matrix in my web browser. It is really slow, so help with optimizing it would be nice. It runs slow on my PC, yet alone my iPod 4 which this is going to be for.

    <title>Matrix</title>

     hi hi

You can try it out here. ANY speed improvements would greatly help!


texts:
I've created a small tool that fetches and stores the newest self-posts from a specific subreddit. The posts are stored in a redis store.

I'm going to write another couple of applications at a future date that will read from the redis store. I will want to be able to pick from the stored posts at random.

This is one of my first forays into writing something that's useful to me in rust, so I'd love some feedback.

#[macro_use]
extern crate serde_derive;

extern crate reqwest;
extern crate serde;
extern crate serde_json;
extern crate redis;

use redis::PipelineCommands;

#[derive(Deserialize)]
struct RedditResponse {
    data: Data,
}

#[derive(Deserialize)]
struct Data {
    children: Vec<Post>,
}

#[derive(Deserialize)]
struct Post {
    data: PostData,
}

#[derive(Deserialize)]
struct PostData {
    id: String,
    is_self: bool,
    title: String,
}

fn main() {
    let self_posts = match get_posts(20) {
        Ok(v) => v,
        Err(e) => panic!("Failed to fetch new posts: {:?}", e),
    };

    let redis_client = match redis::Client::open("redis://127.0.0.1") {
        Ok(c) => c,
        Err(e) => panic!("Unable to create the store client: {:?}", e),
    };

    let redis_conn = match redis_client.get_connection() {
        Ok(c) => c,
        Err(e) => panic!("Unable to retrieve the connection to the store: {:?}", e),
    };

    match add_posts_to_store(redis_conn, self_posts) {
        Ok(n) => println!("Stored {} posts.", n),
        Err(e) => panic!("Could not store posts: {:?}", e),
    };
}

fn get_posts(num: usize) -> reqwest::Result<Vec<Post>> {
    let url = format!("https://www.reddit.com/r/dota2/new.json?sort=new&limit={}", num);
    let posts: RedditResponse = reqwest::get(&url)?.json()?;

    Ok(
        posts.data.children
            .into_iter()
            .filter(|p| p.data.is_self)
            .collect::<Vec<Post>>()
    )
}

fn add_posts_to_store(store: redis::Connection, posts: Vec<Post>) -> redis::RedisResult<usize> {
    let mut pipe = redis::pipe();

    for p in &posts {
        pipe.set(&p.data.id, &p.data.title).ignore();
    }

    pipe.query(&store)?;

    Ok(posts.len())
}


texts:
Overview

I am designing one api that will be integration with another system, however I stumbled upon one code which I know it can be improved but I don't know how to do it properly.

Code

    [HttpPost]
    [Route("Reserve")]
    public IHttpActionResult Reserve([FromUri]ReserveData reserveData, [FromBody]BetsData bet)
    {
        var result = new ReserveResponse();
        // Question 1.
        if (reserveData == null || !IsDataForReserveValid(reserveData))
        {
            // Question 2.
            return Ok(_responseStringBuilder.BuildWrongRequestResponse().Create());
        }
        // Question 3.
        if (!_customerService.CheckIfCustomerExists(reserveData.cust_id))
        {
            return Ok(_responseStringBuilder.BuildCustomerNotFoundResponse().Create());
        }
        if (_customerService.IsCustomerRestricted(reserveData.cust_id))
        {
            return Ok(_responseStringBuilder.BuildRestrictedCustomerResponse().Create());
        }
        if (!_reserveService.ReserveAmount(reserveData.cust_id, reserveData.amount))
        {
            return Ok(_responseStringBuilder.BuildInsufficientFundsResponse().Create());
        }

        if (bet != null)
        {

        }

        _reserveService.InsertReserve(reserveData);
        return Ok(_responseStringBuilder.BuildNoErrorsResponse().Create());
    }

Requirements

This is simple action that should return Ok with string in its response content.

Questions

Is there any better what of checking for valid input? I've created
hierarchy of methods validating input of each action in this
controller(because most of the input for different actions is actually repeating) as
private methods in the controller.
I've created string builder pattern and I build each time my request with needed properties. Is this the best way?
There is some business logic which I've put in the controller, but I am not sure if it should be in the service layer or not Should I leave it like that or invoke single method from a service which does all the logic by itself there and simply returns result to me if there are errors or not?

Example response would be:
...(some data)
error_code=NoErrors\r\n
error_message=There were no errors\r\n


texts:
Any suggestions on cleaning up this code:

 public override bool Validate(Control control, object value)
    {
      bool res = false;
      string str = string.Empty;

      try
      {
        if (((string)value).Length > 0)
          str = value.ToString();
      }
      catch (Exception e)
      {
        res = false;
        this.ErrorText = "Bad values " + e.Message;
        this.ErrorType = ErrorType.Critical;
      }

      //Is it empty?
      if (String.IsNullOrEmpty(str))
      {
        res = false;
        this.ErrorType = ErrorType.Critical;
      }

      Regex RegNrShortRegexDarm = new Regex(@"([F][A][D][-][Z]\d{3})");
      Regex RegNrLongRegexDarm = new Regex(@"([F][A][D][-][Z]\d{3}[-][0-9]+$)");
      Regex RegNrShortRegexBrust = new Regex(@"([F][A][B][-][Z]\d{3})");
      Regex RegNrLongRegexBrust = new Regex(@"([F][A][B][-][Z]\d{3}[-][0-9]+$)");

      if (selectedItem == Constants.Item1)
      {
        this.ErrorText = "The correct form is: FAD-Zxxx oder FAD-Zxxx-x !";

        //has the form FAD-Zxxx
        if (RegNrShortRegexDarm.IsMatch(str) && str.Length == 8)
        {
          // Number is valid
          res = true;
        }

        //has the form FAD-Zxxx-x
        if (RegNrLongRegexDarm.IsMatch(str) && str.Length >= 10 && str.Length <= 12)
        {
          // Number is valid
          res = true;
        }
      }
      else if (selectedItem == Constants.Item2)
      {
        this.ErrorText = "The correct form is: FAB-Zxxx oder FAB-Zxxx-x !";

        //has the form FAB-Zxxx
        if (RegNrShortRegexBrust.IsMatch(str) && str.Length == 8)
        {
          // Number is valid
          res = true;
        }

        //has the form FAB-Zxxx-x
        if (RegNrLongRegexBrust.IsMatch(str) && str.Length >= 10 && str.Length <= 12)
        {
          // Number is valid
          res = true;
        }
      }

      return res;
    }

Later Edit:

I've reached the following solution:

public override bool Validate(Control control, object value)
{
  var str = value as string;
  var letter = (selectedItem == Constants.Item1) ? "D" : "B";
  var errText = String.Format("The correct form is: FA{0}-Zxxx or FA{0}-Zxxx-x !", letter);

  if (string.IsNullOrWhiteSpace(str))
  {
    this.ErrorType = ErrorType.Critical;
    this.ErrorText = errText;
    return false;
  }

  string regExString = String.Format(@"FA{0}-Z\d{{3}}", letter);
  Regex shortRegEx = new Regex(regExString);
  Regex longRegEx = new Regex(regExString + @"-\d+$");

  bool isMatch = ((shortRegEx.IsMatch(str) && IsValidShortLength(str)) || (longRegEx.IsMatch(str) && IsValidLongLength(str)));

  if (!isMatch)
  {
    this.ErrorText = errText;
  }
  return isMatch;

}

private static bool IsValidShortLength(string str)
{
  return str.Length == 8;
}

private static bool IsValidLongLength(string str)
{
  return (str.Length >= 10 && str.Length <= 12);
}


texts: Replacing all occurrences of a substring in a string without using regex

texts:
Problem Statement:

  Given two strings, base and remove, return a version of the base
  string where all instances of the remove string have been removed (not
  case sensitive). You may assume that the remove string is length 1 or
  more. Remove only non-overlapping instances, so with "xxx" removing
  "xx" leaves "x".

withoutString("Hello there", "llo") → "He there"

withoutString("Hello there", "e") → "Hllo thr"

withoutString("Hello there", "x") → "Hello there"

Please feel free to review the code below:

public String withoutString(String base, String remove) {
   final int rLen = remove.length();
   final int bLen = base.length();
   String op      = "";

   for(int i = 0; i < bLen;)
   {
        if( !(i + rLen > bLen) && base.substring(i, i + rLen).equalsIgnoreCase(remove) )
        {
            i += rLen;
            continue;
        }
        op += base.substring(i, i + 1);
        i++;
   }

   return op;

}


texts:
Within my app i have a UIButton (avatar button which shows a profileVC) within a UICollectionView this button shows up in about 4-5 other views. I'm currently adding the target within cellForItemAtIndexPath in each view controller and pushing the view from a public function pushNewViews. I was wondering if they was a better way to do this? (less repetition)

    class ShotsViewController: UIViewController{
    //CollectionView
        override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
            let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell2", forIndexPath: indexPath) as!  mainCell
            cell.userImg.addTarget(self, action: #selector(ShotsViewController.showProfileView(_:)), forControlEvents: .TouchUpInside)
    }
//Target Func
    func showProfileView(sender: AnimatableButton) {
    let profileUser = shots[sender.tag].user
    pushNewViews.showProfileViewController(profileUser, navigation: navigationController!, storyboard: storyboard!)
}

}

class pushNewViews{
    class func showProfileViewController(user: User, navigation: UINavigationController, storyboard: UIStoryboard){
        let vc = storyboard.instantiateViewControllerWithIdentifier("profileView") as! ProfileViewController
        vc.user = user
        navigation.pushViewController(vc, animated: true)
    }
}


texts: Java helper function to round a number to the specified number of decimal places

texts:
The function I need:

  Rounds a double to the specified number of decimal places

I figured this would be a part of java.lang.math, but inexplicably it doesn't have a round function that returns a double. Thus, my proposed solution is to add my own round function in a MathEx class.

/**
 * Holds generic math functions to extend the capabilities of the java.lang.Math class
 */
public class MathEx {

    /**
     * Rounds a double to the specified number of decimal places using the ubiquitous "half up" rounding method
     * @param numberToRound The number to be rounded
     * @param numberOfDecimals The number of decimals to include in the rounded number
     * @return The rounded number
     */
    public static double round(double numberToRound, int numberOfDecimals) {

        return new BigDecimal(numberToRound)
                    .setScale(numberOfDecimals, BigDecimal.ROUND_HALF_UP)
                    .doubleValue();
    }
}

I'd appreciate feedback on the overall strategy, the Javadoc comments, and the naming conventions.


texts:
I'm writing a "IP2host" resolver. Basically all it does is a NSLookup and output's all domain's on the IP. I'm trying to run this on a world scan that's 40M+ lines of IP's.

I have used basic threading but just wondering if I could do anything better to make my code more efficient.

#! python !#
import requests, sys, os, re, getopt, threading

ips = open(sys.argv[1], "r").readlines()

class ip2host(threading.Thread):
    def __init__ (self, ip):
        threading.Thread.__init__(self)
        self.ip = ip.rstrip("\n")
    def run(self):
        try:
            url = "http://ip-www.net/" + self.ip
            response = requests.get(url, timeout=10)
            text =  response.content
            sites = re.findall('">(.*?)</a>', text)
            for w in sites:
                if "You are using" in w: sites.remove(w)
            for w in sites:
                if "Google Chrome" in w: sites.remove(w)
            for w in sites:
                if "Tweet" in w: sites.remove(w)
            for w in sites:
                if "wa-com.com" in w: sites.remove(w)
            for site in sites:
                print site
                os.system("echo "+site+" >>output.txt")
        except:
            pass

print "Starting scan...\n"
for ip in ips:
    try:
        scan = ip2host(ip)
        scan.start()
        time.sleep(0.05)
    except:
        pass

I appreciate all input and replies. I'm just trying to learn.


texts:
I have written a (recursive) deep clone method for ES/JS-objects. It seems to work fine, but maybe I'm missing things. Please, feel free to comment!
Note: the method will not clone cyclic structures. If it should be somehow necessary to be able to clone such structures, maybe Crockfords cycle.js can be used - but it will mangle the structure.

initializeObjCloner();
const log = Logger();
// initial object
const test1 = {
  foo: [1, 2 ,3],
  bar: { foo: {bar: 5}, foobar: "foobar", bar2: {bar3: {foo: 42}} },
};
// clone it
const test2 = Object.clone(test1);
// change a few props to demonstrate
// test2 not being a reference to test1
test2.bar.foo.foobar = "barfoo";
test2.bar.bar2.bar3.foo = 43;
test2.foo = test2.foo.map(v => v + 10);
test2.test2Only = "not in test1";
log (`**Test1:`, test1, `\n**Test2:`, test2);

// error on cyclic structures
const c = {hello: "world"};
c.recycled = c;
log(`\n${Object.clone(c)}`);

function initializeObjCloner() {
  const isImmutable = val =>
    val === null ||
    val === undefined ||
    [String, Boolean, Number].find(V => val.constructor === V);
  const isObject = obj =>
    (obj.constructor !== Date &&
    JSON.stringify(obj) === "{}") ||
    Object.keys(obj).length;
  const cloneArr = arr => arr.reduce( (acc, value) =>
    [...acc, isObject(value) ? cloneObj(value) : value], []);
  const isCyclic = obj => {
    try {
      JSON.stringify(obj);
    } catch(err) {
      return err.message;
    }
    return null;
  };
  // --------------------------
  // The actual cloning method
  // --------------------------
  const cloneObj = (obj) => {
    const cyclic = isCyclic(obj);
    return cyclic ?
      `Object.clone error: Cyclic structures can not be cloned, sorry.` :
      Object.keys(obj).length === 0 ? obj :
        Object.entries(obj)
        .reduce( (acc, [key, value]) => ( {
            ...acc,
            [key]:
              value instanceof Array
              ? cloneArr(value) :
                !isImmutable(value) && isObject(value)
                  ? cloneObj(value)
                  : value && value.constructor
                    ? new value.constructor(value)
                    : value } ),  {} );
  };
  Object.clone = cloneObj;
}

function Logger() {
  const report =
    document.querySelector("#report") ||
    document.body.insertAdjacentElement(
      "beforeend",
      Object.assign(document.createElement("pre"), { id: "report" })
    );
  return (...args) =>
    args.forEach(
      arg =>
        (report.textContent +=
          (arg instanceof Object ? JSON.stringify(arg, null, 2) : arg) + "\n")
    );
}
body {
  font: normal 12px/15px verdana, arial, sans-serif;
  margin: 2rem;
}

if readability is an issue, cloneObj may also be written as:
function cloneObj(obj) {
  if (Object.keys(obj).length < 1) { return obj; }

  if (obj.constructor === Date) {
    return new Date(obj);
  }

  if (obj.constructor === Array) {
    return cloneArr(obj);
  }

  let newObj = {};

  for ( let [key, value] of Object.entries(obj) ) {
    if (!isImmutable(value) && isObject(value)) {
      newObj[key] = cloneObj(value);
    }

    if (!newObj[key] && value && value.constructor) {
      newObj[key] = new value.constructor(value);
    }

    if (!newObj[key]) {
      newObj[key] = value;
    }
  }
  return newObj;
};


texts: Sorting of nested categories inside a Common Table Expression

texts:
I have a PostgreSQL database which contains (among other things) the following table definition:

CREATE TABLE al_categories
(
  id serial NOT NULL,
  name character varying(400) NOT NULL,
  banner text,
  parent_id integer NOT NULL,
  display_order integer NOT NULL,
  se_name character varying(100) NOT NULL, -- This is what WordPress calls a "slug"
  is_active boolean NOT NULL
  CONSTRAINT al_categories_pkey PRIMARY KEY (id)
)

This creates a category hierarchy stored using adjacency lists.  Top-level categories are stored with parent_id set to 0.

One requirement that we have is to retrieve a list of all of the category IDs, along with the full textual path from the top of the order.  To get this data, I have written a view which executes the following Common Table Expression:

WITH RECURSIVE cats AS (
    SELECT
        id,
        name,
        CAST(name AS varchar(1000)) AS path_name,
        0 AS parent_id,
        1 AS level_indicator,
        display_order::INT8 * 1000000000000 AS global_sort,
        1000000000000 / 1000 AS sort_part_upto,
        is_active
    FROM al_categories
    WHERE parent_id = 0
UNION
    SELECT
        c1.id,
        c1.name,
        CAST(c0.path_name || ' / ' || c1.name AS varchar(1000)) AS path_name,
        c0.id AS parent_id,
        c0.level_indicator + 1 AS level_indicator,
        c0.global_sort + (display_order::INT8 * sort_part_upto) AS global_sort,
        c0.sort_part_upto / 1000 AS sort_part_upto,
        c1.is_active
    FROM al_categories AS c1
        INNER JOIN cats AS c0
        ON c1.parent_id = c0.id
)
SELECT id, name, path_name, parent_id, level_indicator, global_sort
FROM cats
ORDER BY global_sort, path_name

As you can see, one of the requirements is that the data is sorted using the display_order columns from all of the categories, such that each category's global_sort number is also based on the display_order of its parent.

I feel like the global_sort is a big mess, and there has got to be a better way to do it.  Is the way I am doing it a good way, or is there a better way to write this recursive query?

An example dataset (simplified from http://comfortfirst.com/) is here, and an example of the returned data from the view is here.


texts:
I am working on a simple Texas Hold'Em dealing simulator. I am new to Python and was hoping to get some advice on my use of classes here. I feel like I am not using them as efficiently as possible, especially when dealing out the player cards. Specifically, I feel like the def deal(self, n_players) could be simplified instead of using playercard1 and playercard2, and deleting the items from the "deck".

from random import shuffle

class TexasHoldem:
    #create deck
    def __init__(self):
        values = ['Ace', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King']
        suites = ['Heart', 'Spade', 'Club', 'Diamond']
        self.deck = [j + " " + i for j in values for i in suites]

    #shuffle deck
    def shuffle(self):
        shuffle(self.deck)

    #deal for players
    def deal(self, n_players):
        count = 0
        #card 1 list (will be shuffled, delt 'around the table' as if a real stack)
        playercard1 = list()
        while count < n_players:
            card1 = self.deck[count]
            playercard1.append(card1)
            count += 1

        #remove cards from deck that were delt
        for i in playercard1:
            self.deck.remove(i)

         count = 0
         #card 2 list
         playercard2 = list()
         while count < n_players:
             card2 = self.deck[count]
             playercard2.append(card2)
             count += 1

         #remove cards from deck delt for 2nd card
         for i in playercard2:
             self.deck.remove(i)

        #merge cards of playercard1 and playercard2 into set
        self.playerhand = zip(playercard1, playercard2)

    #define the flop
    def flop(self):
        #burn a card
        del self.deck[0]
        #lay down three
        self.flopcards = self.deck[0:3]
        #delete flop from deck
        for i in self.flopcards:
            self.deck.remove(i)

    #same as flop for turn and river
    def turn(self):
        del self.deck[0]
        self.turncard = self.deck[0:1]

        for i in self.turncard:
            self.deck.remove(i)

    def river(self):
        del self.deck[0]
        self.rivercard = self.deck[0:1]

        for i in self.rivercard:
            self.deck.remove(i)

#create instance of Cards class
c = TexasHoldem()
#shuffle for this instance
c.shuffle()

#deal for n players
c.deal(9)

print 'Player Hands:'
for i in c.playerhand:
    print i

#flop
c.flop()
print 'Flop:'
print c.flopcards

#turn
c.turn()
print 'Turn:'
print c.turncard

#river
print 'River:'
c.river()
print c.rivercard


texts: Node.js building a JSON restful web api structure

texts:
I am building a JSON restful web api in Node.js and so far I only got the main structure, however I am not 100% sure I am doing this correct from scratch, I still have to get used to the fact that Node.js is event driven.

Directory structure:

1. main.js
2. modules
  a. router.js
  b. config.js
  c. routes.js

1. main.js - contains the main entry point - node main.js
2. modules - folder that contains all the modules.

2a. router.js - contains "singleton" class module that will handle routing.

var Router = function(routes){
    this.routes = routes;

    Router.route = function(){
        console.log('routing from singleton router...');
    };

    return Router;
};

module.exports = Router;

2b. config.js - contains the global configuration.

exports.config = {
    port: 9090
};

2c. routes.js - contains the global routing schema, the router module will get the module injected (from main.js)

exports.routes = {
    'POST /users': { 'controller': 'users', 'action': 'create' },
    'GET /users': { 'controller': 'users', 'action': 'getSelf' },
    'GET /users/:uid/posts/:pid': { 'controller': 'users', 'action': 'getPostsFromUser' }
};

This is the structure so far, I am planning to extend it to this directory structure:

1. main.js
2. modules
  a. router.js
  b. config.js
  c. routes.js
  d. loader.js (model loader, connection pool etc.)
  e. validator.js (validates input)
  d. controller.js (main controller, how to inherit from this? through inheritance?)
3. controllers - contains controllers
4. models - contains models

How to handle connection pooling in the structure? Would it be an idea to create a "registry" class, I come from a PHP background and that is how I would share objects, instead of dependency injection.

sample registry.js

var Registry = function(){
    this.data = {};

    Registry.push = function(key, value){
        return this.data[key] = value;
    };

    Registry.pull = function(key){
        return this.data[key];
    }

    return Registry;
};

module.exports = Registry;

As I said, I am kinda new to Node.js and I want to make sure I get it right from scratch.

If you got any suggestions, comments, tips I really appreciate your help and time.


texts:
I was working on a project recently that had a good amount of business logic associated with status codes.   To better understand the flow of logic in the domain layer, I created an enum representation of the statuses and overloaded the equality operator in the status domain model to check against the enum.

Is this good practice, or does this an unnecessary abstraction?  Also seeing if I should implement the GetHashCode() and Equal() methods or perhaps just make them just return

() => throw new InvalidOperationException();

Implementation

public class StatusDm
{

    public StatusDm() { }
    public StatusDm(Models.Database.Status status)
    {
        Id = status.Id;
        Name = status.Name;
    }
    public int Id { get; set; }
    public string Name { get; set; }

    public void DatabaseTransfer(ref Models.Database.Status status)
    {
        status.Name = Name;
    }
    public static bool operator ==(StatusDm domainStatus, Models.Constants.StatusEnum status)
    {
        return domainStatus?.Id == (int)status;
    }

    public static bool operator !=(StatusDm domainStatus, Models.Constants.StatusEnum status)
    {
        return !(domainStatus?.Id == (int)status);
    }
}

Usage

if(individual.StatusModel == StatusEnum.Submitted || individual.StatusModel == StatusEnum.Disqualified)
{
    ...
}

Appreciate any feedback or critic. Thanks!

Edit:  There was a question in regards to how it would normally be done in this application.  Here was the evolution of the usage statement

First Implementation

if (storedIndividual.Status == (int)IndividualStatus.InProgress &&
    (individual.StatusModel.Id == (int)IndividualStatus.Submitted ||
        individual.StatusModel.Id == (int)IndividualStatus.Disqualified))

{
    SetFinishedIndividualFormValues(ref individual);
    if (individual.StatusModel.Id == (int)IndividualStatus.Submitted)
    {
        SendSubmittedFileEmail(individual);
    }
}
else if (individual.StatusModel.Id != (int)IndividualStatus.Disqualified)
{
    SendStatusChange(individual);
}

Revised Implementation

private void HandleStatusChanges(Models.Database.Individual storedIndividual, ref Models.Domain.IndividualDm individual)
{
    if (storedIndividual.Status == (int)IndividualStatus.InProgress &&
        (individual.Status == IndividualStatus.Submitted ||
            individual.Status == IndividualStatus.Disqualified))
    {
        SetFinishedIndividualFormValues(ref individual);
        if (individual.Status == IndividualStatus.Submitted)
        {
            SendSubmittedFileEmail(individual);
        }
    }
    else if (individual.Status != IndividualStatus.Disqualified)
    {
        SendStatusChange(individual);
    }
}


texts:
I have a website that retrieves time data from any given location on the world live.

I wanted to be able to automatically change the time and not deal with the hassle of local client times.

It's fairly simple, but since I'm not that good with JS, I'd like to know if there is anything I could improve about it?

Suggestions are welcome!

(function() {
    "use strict";

    var LiveTime = {
        rawOffset: null,
        dstOffset: null,
        timeoutId: null,

        setOffset: function(raw, dst) {
            LiveTime.rawOffset = raw * 1000;

            if (typeof dst !== "undefined") {
                LiveTime.dstOffset = dst * 1000;
            }
        },

        start: function() {
            LiveTime.timeoutId = (function increment() {
                var now = new Date();
                var now = new Date(
                    now.getUTCFullYear(),
                    now.getUTCMonth(),
                    now.getUTCDate(),
                    now.getUTCHours(),
                    now.getUTCMinutes(),
                    now.getUTCSeconds(),
                    now.getUTCMilliseconds()
                );

                now.setTime(now.valueOf() + LiveTime.rawOffset + LiveTime.dstOffset);

                var element = document.getElementById("current-time");
                element.innerHTML = ("0" + now.getHours()).slice(-2) + ":"
                                  + ("0" + now.getMinutes()).slice(-2) + ":"
                                  + ("0" + now.getSeconds()).slice(-2);

                LiveTime.timeoutId = setTimeout(increment, 50);
            })();
        },

        stop: function() {
            clearTimeout(LiveTime.timeoutId);
        }
    }

    //usage example
    LiveTime.start();

    //simulate new location after 5 seconds
    setTimeout(function() {
        LiveTime.setOffset(-9 * 3600, 3600); //alaska
   }, 5000);

    //stop the time after 5 more seconds
    setTimeout(function() {
        LiveTime.stop();
   }, 10000);
})();


texts: Multithread resource producer and consumer algorithm

texts:
I have made a little example of a code that stores frames of a camera in a buffer that runs in a separate thread and another thread can consume it. Is this model efficient?

//isEmpty_buffer is an atomic<bool>
//Mat is a opencv Matrix of pixels
//Max buffersize is 1000
//Camera mutex is a shared_timed_mutex

Mat Camera::get_last()
{
    while (isEmpty_buffer.load()) {

    }

    shared_lock<shared_timed_mutex> lock(camera_mutex);

    Mat ret = buffer.back().clone();
    buffer.front().release();
    buffer.pop();

    if (buffer.empty()) {
        isEmpty_buffer.store(true);
    }

    return ret;
}

void Camera::add_frame(Mat &frame)
{
    lock_guard<shared_timed_mutex> lock(camera_mutex);

    if(buffer.size() < MAX_BUFFER_SIZE){
        buffer.push(frame.clone());
        isEmpty_buffer.store(false);
    } else{
        cout << "Buffer at limit!" << endl;
    }

}


texts:
using XNA and C# I built a game as a tutorial, but I have since added functionality to allow the player to move around on a world map which requires the camera to "move"  but I no longer like the look of the if statements.

is there some way that I can clean this up?

private static Rectangle scrollArea = new Rectangle(150, 150, 500, 300);

private void repositionCamera(GameTime gameTime, Vector2 moveAngle)
{
    float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;
    float moveScale = playerSpeed * elapsed;

    if ((playerSprite.ScreenRectangle.X < scrollArea.X) && (moveAngle.X < 0))
    {
        Camera.Move(new Vector2(moveAngle.X, 0) * moveScale);
    }

    if ((playerSprite.ScreenRectangle.Right > scrollArea.Right) && (moveAngle.X > 0))
    {
        Camera.Move(new Vector2(moveAngle.X, 0) * moveScale);
    }

    if ((playerSprite.ScreenRectangle.Y < scrollArea.Y) && (moveAngle.Y < 0))
    {
        Camera.Move(new Vector2(0, moveAngle.Y) * moveScale);
    }

    if ((playerSprite.ScreenRectangle.Bottom > scrollArea.Bottom) && (moveAngle.Y > 0))
    {
        Camera.Move(new Vector2(0, moveAngle.Y) * moveScale);
    }
}


texts: Django query to find all items without a FK relationship except for excluded list

texts:
I have a Book model and an Author model that has a FK relationship to Book (I realize that it should be the other way around, but I had to change the names of the real items to Book and Author for proprietary reasons.)  Related name on this relationship is authors.

I am trying to find all Books that do not have an Author or Authors, except for an exclude list of tuples called BOOKS_WITH_NO_AUTHORS that is about 25 items long and unlikely to grow much.  The pair of items in the tuples are unique together.  I can change this list of tuples to a dictionary or other format if that is helpful.

Everything works but it is very slow.  The database of books and authors is large.

BOOKS_WITH_NO_AUTHORS = [(1979, "ABC123"), (1928, "DEF456")]

def missing_author(request):

    excluded_books = [Book.objects.get(publish_year=book[0], book_num=book[1]).book_id
                      for book in BOOKS_WITH_NO_AUTHORS]

    books_missing_authors = Book.objects. \
        filter(authors=None). \
        exclude(book_id__in=excluded_books). \
        order_by('publish_year')

    return render(request,
                  'missing_author.html',
                  {"data": books_missing_authors})


texts: A kind of function factory within react component

texts:
In the app that works only for training purposes I have a React component that serves(among others) as an 'event catcher' for all events that happen on its rendered children. It contains (at the time being, besides other stuff) eight expressions similar to the following:
  const debouncedFetchSingleBook = useCallback(
    // using lodash debounce()
    debounce(target => {
      const button = target.closest("button");

      // Catch event target.  In this case, it is fetchSinglebook.
      fetchSingleBook(redirect, button.dataset.content, true);
    }, 200),
    [fetchSingleBook]
  );

The duty of such the expression is to
return a callback that debounces and executes an event action fired on button pressing.
I tried to write a function that would take actual function as argument and return what described above, in order to keep code DRY. So, here is what I have written:
const useCreateDebouncedCallback=(fn)=>{

  const result = useCallback(
    debounce(target => {
      const button = target.closest("button");
      fn(button.dataset.content);
    }, 200),
    [fn]
  );

  return result;
}

That is defined above component self where it is called, in the same file. Basically, it works(no error, task done).
My question is whether:
It conforms to React standards?
Are there any possible failures in the code that do not expose themselves immediately?
This is my first custom React Hook. Any help would be appreciated.


texts: Window-size-dependent navigation menu with animation effects

texts:
Other people will be looking at this jquery code and i'm not an expert with jQuery so im asking. How can i make this jQuery code shorter, more efficient, and easier to read?

/*
HEADER NAVIGATION
*/
/* navigation tabs click highlight */
$(".header-main-tabs").click(function() {
$(".header-main-tabs").removeClass("header-tab-selected");
$(this).addClass("header-tab-selected");
});
/* drop menu hide and show for desktop */
$(".header-main-tabs").hover(function() {
$(this).children(".header-drop-menu").toggleClass("show-drop-menu-hover");
});

/* search input hide and show when search icon is pressed */
$("#search-icon-container span").click(function() {
$(this).toggleClass("fa-times");
$("#search-input-container").fadeToggle("fast");
});

/* mobile navigation */
/* show mobile tabs when toggle nav mobile button is clicked and when browser width is      over 990px */
/* toggle mobile navigation when nav button is clicked */
$("#toggle-mobile-nav").click(function() {
$("#nav-tabs-list").slideToggle();
$("#toggle-mobile-nav").toggleClass("toggle-mobile-nav-clicked");
});

var browserWidth = $(window).width();

$(window).resize(function() {
browserWidth = $(window).width();
if (browserWidth > 990) {
    $("#nav-tabs-list").show();
}
 });

$('#nav-tabs-list li').click(function() {
if (browserWidth <= 990) {
    $('#nav-tabs-list').slideUp();
}
});

/* always show drop menu when on mobile version (when browser width is below 960px) */
$(document).ready(function() {
fadeMobile();
});

$(window).resize(function() {
  fadeMobile();
});

function fadeMobile() {
  browserWidth = $(window).width();
  if (browserWidth < 990) {
$("#nav-tabs-list").hide();
    $('.header-drop-menu').show();
    $("#toggle-mobile-nav").removeClass("toggle-mobile-nav-clicked");
      }
    }


texts:
I have written this code which basically sorts the array using bubble sort, however, I feel it is not very readable. Please let me know me how I can improve this code.

public class BubbleSort {

    public static void main(String[] args) {

        int arr[] = new int[] { 4, 1, 8, 5, 2, 0, 4, 3, 7, 9 };

        for (int i : arr) {
            System.out.print(i + " ");
        }

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

            }

        }
        System.out.println();
        System.out.println("Sorted array");
        for (int i : arr) {
            System.out.print(i + " ");
        }
    }

}


texts:
I know something about pointers, but I'm trying to check my knowledge on a sample.  Can somebody check if my code is good?  I don't think that I should use pointers in these structs.

The second question is: Can I use a for loop like this?

for(DLList* i=first; i!=0; i=i->next)

Is it correct?

struct Node
{
    int id;
    int dist;
    Node* prev;
    vector<Edge*> edges;
};

struct Edge
{
    int length;
    Node* to;
};

struct DLList
{
    DLList *next;
    DLList *prev;
    Node* val;
};

struct DList
{
    DLList *first,*last;

    DList()
    {
        first = 0;
        last = 0;
    }

    DLList* add(Node* n)
    {
        DLList *newNode = new DLList;
        if(first == 0)
        {
            newNode->val = n;
            newNode->next = 0;
            newNode->prev=0;
            first =  newNode;
            last = newNode;
        }
        else
        {
            newNode->val = n;
            newNode->next = 0;
            newNode->prev=last;
            last = newNode;
            last->next=newNode;
        }
        return last;
    }

    void removeFirst()
    {
        if(first!=0)
        {
            first = first->next;
            if(first != 0)
            {
                first->prev = 0;
            }
        }
    }

    void remove(DLList* e)
    {
        if(e==0)
        {
            return;
        }
        else if(e==first)
        {
            removeFirst();
        }
        else if(e==last)
        {
            last = last->prev;
            last -> next = 0;
        }
        else
        {
            e->prev->next = e->next;
            e->next->prev = e->prev;
        }
    }

    void remove(Node* n)
    {
        if(first == 0)
        {
            return;
        }
        if(n==first->val)
        {
            removeFirst();
        }
        else if(n==last->val)
        {
            last = last->prev;
            last->next = 0;
        }
        else
        {
            for(DLList* i=first; i!=0; i=i->next)
            {
                if(n==i->val)
                {
                    i->prev->next = i->next;
                    i->next->prev = i->prev;
                    break;
                }
            }
        }
    }

    bool isEmpty()
    {
        return first == 0;
    }

};


texts:
Im running a photocontest and making a list of winners with one winner each day. My loop is running very slow. It seams to be the toList() that is time consuming. Any suggestions on how to make it run faster?

foreach (var date in dates)
        {

            var voteList = _images.Select(image => new ImageWinnerVotes
                                                   {
                                                       ID = image.ID,
                                                       Image = image.ImagePath,
                                                       Thumbnail = image.ThumbnailImagePath,
                                                       Title = image.Name,
                                                       Url = GetFriendlyUrl(image.ID),
                                                       Date = image.CreatedDate,
                                                       WinnerDateString = date.Date.ToString("dd/MM"),
                                                       WinnerDate = date.Date,
                                                       TotalVotes =
                                                           (votes.Where(vote => vote.ItemId == image.ID)).Count(),
                                                       Name = image.Fields["Name"].ToString(),
                                                       Votes =
                                                           (votes.Where(
                                                               vote =>
                                                               vote.ItemId == image.ID &&
                                                               vote.Date.DayOfYear == date.Date.DayOfYear)).Count()
                                                   }).ToList();

            voteList = voteList.OrderByDescending(v => v.Votes).ToList();

            var j = 0;
            var findingWinner = true;

            while(findingWinner)
            {
                var inWinnersList = false;
                if (winnersList.Count() != 0)
                {
                    if(!winnersList.Contains(voteList.ElementAt(j)))
                    {
                        winnersList.Add(voteList.ElementAt(j));
                        findingWinner = false;
                    }
                }
                else
                {
                    winnersList.Add(voteList.ElementAt(j));
                    findingWinner = false;
                }

                j++;
            }

        }


texts: Display A Random Tic-Tac-Toe Board Using Java Swing

texts:
This is the problem:

(Game: display a tic-tac-toe board) Display a frame that contains nine labels. A label may display an image icon for X or and image icon for O. What to display is randomly decided. Use the Math.random() method to generate an integer 0 or 1, which corresponds to displaying an X or O image icon. These images are in the files x.gif and o.gif)

My code seems to do what the problem asks, and the output is practically the same as the example (minus the borders). However, without the solutions for odd-numbered exercises, I can't imagine what an "ideal" implementation of this problem would look like. For example, is it good practice to use arrays in the way that I did?

Here is my solution:

import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;

public class DisplayTicTacToe extends JFrame {
public DisplayTicTacToe() {
    setLayout(new GridLayout(0, 3));

    ImageIcon[] display = new ImageIcon[3];
    display[0] = new ImageIcon("image/o.gif");
    display[1] = new ImageIcon("image/x.gif");
    display[2] = new ImageIcon("Empty Icon");
    for (int i = 0; i < 9; i++) {
        JLabel jlb = new JLabel(display[(int)(Math.random() * 3)]);
        jlb.setBorder(new LineBorder(Color.BLACK, 1));
        add(jlb);
    }
}

public static void main(String[] args) {
    DisplayTicTacToe frame = new DisplayTicTacToe();
    frame.pack();
    frame.setTitle("Display TicTacToe");
    frame.setLocationRelativeTo(null);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
}
}


texts:
I am trying to search account table by providing a search string. I am building a query based in different conditions and then adding the returned records in a list.

The functionality is working correctly but I want to know how an below method be further optimized.

    public PageReference search(){
    clear();
    runningUserId = Userinfo.getUserId();
    String searchquery;
    Boolean existUser = AccSearchAccess__c.getValues(runningUserId) !=null? true : false;
    if(existUser){
        searchquery='Select  Name,Id,AccessLevel__c FROM Account where Name like \'%'+accountName+'%\'';
    }
    else{
        set<id> accountIds = new set<id>();
        List<WMAccess__c> wmaLst = [Select id,Account__c from WMAccess__c where WM_User__c = : UserInfo.getUserId()];
        for(WMAccess__c wm : wmaLst){
            accountIds.add(wm.Account__c);
        }
        if(!accountIds.isEmpty()){
            searchquery='Select  Name,Id,AccessLevel__c FROM Account where Name like \'%'+accountName+'%\' AND id IN:accountIds';
        }
    }

    accList= Database.query(searchquery);
    if(accList.size()>0)
        for(Account acc : accList){
            AccountWrapper aw = new AccountWrapper(acc, false);
            aw.accountId = acc.id;
            aw.accountName = acc.Name;
            aw.accountAccess = acc.AccessLevel__c;
            accountsList.add(aw);
        }
    return null;
}