texts: Sum of Absolute Differences algorithm implementation

texts:
Those unfamiliar with that algorithm can have a deeper look here, in a few words, there are two arrays where you subtract each element ar1[0][0]-ar2[0][0] and add that result using the absolute values. My implementation is this:

#include <stdio.h>
#include <stdlib.h>

#define LEN(arr) ((int) (sizeof (arr) / sizeof (arr)[0]))
int calSad(int templ[3][3], int image[3][3]);

int main()
{
    int tempImage[3][3] = {};

    int tem[3][3] = {
            {2, 5, 5},
            {4, 0, 7},
            {7, 5, 9}
    };

    int originalImage[3][5] = {
            {2, 7, 5, 8, 6},
            {1, 7, 4, 2, 7},
            {8, 4, 6, 8, 5}
    };

    int tempSad = 0, sad = 256, Xcoordinate = 0, Ycoordinate = 0;

    int originalImage_row_length = LEN(originalImage);
    int tempImage_row_length = LEN(tempImage);

    int originalImage_col_length = LEN(originalImage[0]);
    int tempImage_col_length = LEN(tempImage[0]);

    int tem_row_length = LEN(tem);
    int temp_col_length = LEN(tem[0]);

    int x, z, i, y, d = 0, q = 0;

    for (x = 0; x <= originalImage_row_length - tempImage_row_length; x++) {
        for (z = 0; z <= originalImage_col_length - tempImage_col_length; z++) {
            for (i = 0; i < tem_row_length; i++) {
                for (y = 0; y < temp_col_length; y++) {
                    tempImage[i][y] = originalImage[x+q][z+d];
                    d = d + 1;
                }
                q = q + 1;
                d = 0;
            }
            q = 0;
            tempSad = calSad(tem, tempImage);
            if (tempSad < sad) {
                sad = tempSad;
                Xcoordinate = x;
                Ycoordinate = z;
            }
        }
    }

    printf("SAD: %d\n", sad);
    printf("X: %d\n", Xcoordinate);
    printf("Y: %d\n", Ycoordinate);

    return 0;
}

int calSad(int templ[3][3], int image[3][3]) {
    int tempSad = 0;

    tempSad = (abs(templ[0][0] - image[0][0])+abs(templ[0][1] - image[0][1])+abs(templ[0][2] - image[0][2])+
               abs(templ[1][0] - image[1][0])+abs(templ[1][1] - image[1][1])+abs(templ[1][2] - image[1][2])+
               abs(templ[2][0] - image[2][0])+abs(templ[2][1] - image[2][1])+abs(templ[2][2] - image[2][2]));

    return tempSad;
}

The arrays are from the wikipedia link above, so I can duplicate the result and see if it works. It seems to work but I want your opinion if you see something wrong or if it doesn't work.


texts: Grouping counts from tables by account ID

texts:
I'm working with this query to get counts from three different tables, and to group the results by account ID:

SELECT accountId , SUM(ApplicantsCount) as ApplicantsCount, SUM(ApprovedCount) as ApprovedCount, SUM(ScreenedCount) as ScreenedCount
FROM (
    SELECT      application.accountId, COUNT(*) ApplicantCount, 0 ApprovedCount, 0 ScreenedCount
    FROM        application
    [accountIdCondition]
    GROUP BY    application.accountId

    UNION

    SELECT      application.accountId, 0, COUNT(*), 0
    FROM        application
    JOIN        termsofapproval ON application.accountId = termsofapproval.accountId
    JOIN        approvaluserjoin ON termsofapproval.id = approvaluserjoin.termsofapprovalId
[accountIdCondition]
    GROUP BY    application.accountId

    UNION

    SELECT      application.accountId, 0, 0, COUNT(*)
    FROM        application
    JOIN        screened
    ON application.id = screened.applicationId
    [accountIdCondition]
    GROUP BY    application.accountId
  ) CountsTable
GROUP BY CountsTable.accountId

However, it runs too slowly, and times out the task handler I'm calling it in. Is there a way I can write this to run faster?


texts:
I was wondering if there was a better way to do this. Would that mean there would need to be no client-side refreshing to show the cookies when they are created?

<?php
class cookieMonster
{
    public static $lastDestroyed;

    public function __construct() {  }

    /**
     * Register a cookie with the browser.
     * @param string $name Name to be given to the cookie
     * @param string $value Value to be put inside the cookie
     * @param int $expire How long the cookie will last, leave at 0 to expire on end of session/when the browser closes
     * @return bool True if cookie is created and false if not
     */
    public function registerCookie($name, $value = '', $expire = 0)
    {
        return setcookie($name, $value, $expire);
    }

    /**
     * Summary of retrieveCookie.
     * @param string $name The name of the cookie to retrieve.
     * @return bool True if found/not empty and false if not.
     */
    public function retrieveCookie($name)
    {
        $return = true;
        isset($_COOKIE[$name]) ?: $return = false;
        !empty($_COOKIE[$name]) ?: $return = false;
        return $return ? $_COOKIE[$name] : $return;
    }

    /**
     * Destroy a cookie variable, this can be undone, but not after a second has been destroyed.
     * @param mixed $name
     * @return bool
     */
    public function destroyCookie($name)
    {
        $return = true;
        isset($_COOKIE[$name]) ?: $return = false;
        !empty($_COOKIE[$name]) ?: $return = false;
        if ($return) :
            static::$lastDestroyed = ["name"=>$name, "value"=>$this->retrieveCookie($name)];
            unset($_COOKIE[$name]); return true;
        else :
            return false;
        endif;
    }

    /**
     * Restores the last destroyed cookie, can only be done for the very last cookie that was destroyed.
     * Does not require a param as the last destroyed is held in the class.
     * @return bool
     */
    public function restoreLastCookie()
    {
        $allow = true;
        static::$lastDestroyed ?: $allow = false;
        return $allow ? $this->registerCookie(static::$lastDestroyed['name'], static::$lastDestroyed['value']) : false;
    }
}


texts: Capping values in a map while keeping one fixed

texts:
I'm working with some Clojurescript code that reacts to user input over three sliders. These sliders get stored in a map, and I need to make sure that the sum of all is <= a max value. Every time a value from the map is modified I have the guarantee that it will be in the [0, max] range, and I must reduce if necessary the others so that the total sum is still <= max.

I implemented it, but as I don't have a lot of experience with Clojure and Clojurescript I'm sure it can be improved. I would like to listen to any comment about making it shorter, more concise, more idiomatic, easier to read, etc. Thanks!

PS: I know that the names of the functions don't make much sense, I'm still in mid development and changing things all the time. alloc stands for allocation.

(def MaxAlloc 100)

(defn verify-alloc
  [alloc fixed-id]
  (let [total (reduce + 0 (vals alloc))]
    (if (<= total MaxAlloc)
      alloc
      (let [others (dissoc alloc fixed-id)]
        (assoc
          (de-alloc (dissoc alloc fixed-id) (- total MaxAlloc))
          fixed-id (get alloc fixed-id)) ) ) ) )

verify-alloc checks if there is an excess, and if so removes the fixed element from the map and calls de-alloc to remove the excess.

(defn de-alloc
  [alloc excess]
  (let [pair (first alloc)
        k (first pair)
        v (second pair)]
    (if (> v excess)
      (assoc alloc k (- v excess))
      (assoc (de-alloc (dissoc alloc k) (- excess v)) k 0) ) ) )

de-alloc works by removing as much excess as it can from the first value in the map, and if there is still some excess value, calls itself recursively removing the 'zeroed' element from the map.

And it would be used like this:

(verify-alloc {:a 0 :b 30 :c 40} :c)
{:a 0, :b 30, :c 40}

(verify-alloc {:a 10 :b 40 :c 70} :a)
{:a 10, :b 20, :c 70}

(verify-alloc {:a 90 :b 40 :c 70} :b)
{:b 40, :a 0, :c 60}

I would also like to change the algorithm so that instead of completely decreasing elements one after the other, it would distribute this decrease in equal parts among the remaining elements. But I could not find my way around it. Ideas?


texts: A command-line utility to solve a system of linear equations

texts:
I was re-checking my answers for a Math paper on my laptop. I needed to verify my solution for a system of linear equations. Unfortunately, I found no quick way to do that. That's why I wrote a (hopefully) simple Python program (using NumPy) to do this job quickly. General comments on the code are appreciated.

linearsolver.py

from sys import argv, exit
from fractions import Fraction
import numpy as np
import string

def solve(A, B, vars=['x', 'y']):
    X = np.linalg.inv(A) * B.transpose()
    values = []
    for item in X:
        values.append(Fraction(item[0, 0]).limit_denominator())
    return dict(zip(vars, values))

def vars(len):
    alph = list(string.ascii_lowercase)
    # x is the 24th alphabet
    start = 23 if len <= 3 else 0
    return list(alph[start:start + len])

def interact():
    print "======================\nLinear Equation Solver\n======================\nHow many equations (and variables) ? ",

    len = int(raw_input())

    # Input the variable names
    vars = []
    print "Enter the variables involved :"
    for i in range(0, len):
        vars.append(raw_input())

    # Input the coefficients
    a = []
    print "Enter the coefficients of the variables in order, for each equation:"
    for i in range(1, len + 1):
        print "-----%d-----" % i
        temp = []
        for i in range(0, len):
            temp.append(float(raw_input()))
        a.append(temp)

    # Input the values they equal to
    print "Enter the constants for the RHS :"
    b = []
    for i in range(0, len):
        b.append(float(raw_input()))

    A = np.matrix(a)
    B = np.matrix(b)
    answer = solve(A, B, vars)
    print_answer(answer)

def print_answer(answer):
    for variable, value in answer.items():
        print "%4s = %4s" % (variable, value)

def main(argv):
    num = len(argv)
    varlist = None
    if num == 1:
        # Only the script name: enter interactive mode
        interact()
        exit()
    elif num == 3:
        script, a, b = argv
    elif num == 4:
        script, a, varlist, b = argv
    else:
        print "Too many arguments."
        sys.exit()

    A = np.matrix(a)
    B = np.matrix(b)

    rows = A.shape[0]
    cols = A.shape[1]

    if rows != cols:
        print "Number of rows must be equal to number of columns."
        exit()

    if varlist is None:
        answer = solve(A, B, vars(rows))
    else:
        answer = solve(A, B, list(varlist))
    print_answer(answer)

if __name__ == '__main__':
    main(argv)

Some example runs:

$ python linearsolver.py "2 5 -9 3; 5 6 -4 2; 3 -4 2 7; 11 7 4 -8" "151 103 16 -32"
   a =    3
   c =  -11
   b =    5
   d =    7
$ python linearsolver.py "5 -11 9; 13 7 -10; -6 5 -8" "gkm" "-125 2 60"
   k =   12
   m =    3
   g =   -4
$ python linearsolver.py
======================
Linear Equation Solver
======================
How many equations (and variables) ?  7
Enter the variables involved :
s
t
u
v
w
x
y
Enter the coefficients of the variables in order, for each equation:
-----1-----
2
-7
3
5
-7
11
8
-----2-----
5
7
-1
9
-6
3
-5
-----3-----
13
11
8
7
4
2
1
-----4-----
12
1
6
5
9
3
11
-----5-----
1
-4
7
-3
9
-2
6
-----6-----
4
1
-6
-3
8
-7
-4
-----7-----
-7
-2
5
1
9
3
-4
Enter the constants for the RHS :
114
-11
-25
-37
4
-91
-50
   s =    5
   u =    8
   t =   -7
   w =   -9
   v =   -6
   y =   -3
   x =    2


texts: Set-uid root program that runs a program as the user "restrict"

texts:
I've written a very short program that is intended to run the program specified in its arguments (argv) as the user named "restrict" (which exists). I want to make sure that there are no subtle bugs in the program, and that the program is as simple as possible.

Is this program doing what I intend?
Can someone use this program to do anything malicious? Assume that anything running as the user "restrict" is not able to do anything malicious, but anything running as the user "root" obviously can.
Can this code be simplified, or (assuming the code is correct) can this code's correctness be made more obvious?

The code (compiled with gcc --std=c11):

#include <unistd.h>
int main (int argc, char **argv) {
    setuid(0); // Switch user to root.
    char *start[] = {
        "/usr/bin/sudo", "-u", "restrict", // Switch user to "restrict".
        "--" // End arguments.
    };
    int start_len = (sizeof start) / (sizeof start[0]);
    char *args[start_len+argc];
    char *env[] = {NULL}; // Delete all environment variables.
    int i;
    for (i = 0; i < start_len; ++i)
        args[i] = start[i];
    // Note that argv is null-terminated, so we can go past the end by one.
    // Conveniently, we also want to discard the first argument, so just loop
    // over the arguments as usual, but with an offset of one.
    for (i = 0; i < argc; ++i)
        args[start_len+i] = argv[i+1];
    execve(args[0], args, env);
}

The final binary will be owned by root, and will have the set-uid bit set, and will be executable by users in a particular group.

The ultimate goal is to allow users in a particular group to run any executable as the user "restrict".

Alternatively, is there a better way to accomplish this goal?

See Set-uid root program that runs a program as the user “restrict” (follow-up) for the next iteration of this code.


texts:
I'm trying to implement a HashSet that it's accessed from different thread for querying, adding or deleting elements. It doesn't make sense to use a Dictionary for I got several search keys so I won't get benefited much for the speed provided on querying.

My real problem is when trying to remove several items matching a given definition without locking the List for to long, I use this code right now

   public static void DeleteFromHashSet(string companyId, int deviceId)
   {
        lock (setLock)
        {
            set.RemoveWhere(x => x.CompanyId == companyId && x.y == deviceId);
        }
    }

but this has the problem of locking the access for querying the hashset for the duration of the RemoveWhere, I can change that with a foreach and just lock for each individual item but I wanted to know if there's a better way.

Update:

This is what I finally did, in case it's of some help

    class DeviceLocator
{
    #region  fields

    private HashSet<DeviceLocator> m_deviceList = new HashSet<DeviceLocator>();
    private object setLock = new object();
    private ReaderWriterLockSlim cacheLock = new ReaderWriterLockSlim();

    public  void AddLocator(DeviceLocator locator)
    {
        DeleteLocator(locator);

        cacheLock.EnterWriteLock();

        m_deviceList.Add(locator);

        cacheLock.ExitWriteLock();
    }

    public void AddLocators(IEnumerable<DeviceLocator> locators)
    {
        foreach (DeviceLocator locator in locators)
        {
            AddLocator(locator);
        }
    }

    #endregion Add items

    #region Query items

    public DeviceLocator GetLocator(string serialNumber)
    {
        try
        {
            return ReadSafely(x => x.SerialNumber == serialNumber).Single();
        }
        catch
        {
            throw new LocatorNotFoundException(ExceptionTexts.LocatorNotFoundException, null, ImportanceLevel.Low, m_ID);
        }
    }

    public IEnumerable<DeviceLocator> GetLocatorsFromCompany(string companyId)
    {
        return ReadSafely(x => x.CompanyID == companyId);
    }

    public IEnumerable<string> GetLocatorsStringFromCompany(string companyId)
    {
        return GetLocatorsFromCompany(companyId).Select(y => y.SerialNumber);
    }

    public IEnumerable<DeviceLocator> GetsLocatorBasedOnConnectionType(ConnectionType type)
    {
        return ReadSafely(x => x.ConnectionType == type); ;
    }

    private IEnumerable<DeviceLocator> ReadSafely(Func<DeviceLocator, bool> predicate)
    {
        try
        {
            cacheLock.EnterReadLock();

            var result = m_deviceList.Where(predicate);

            return result;
        }
        catch
        {
            throw;
        }
        finally
        {
            cacheLock.ExitReadLock();
        }
    }

    public  void DeleteLocator(DeviceLocator locator)
    {
        DeleteSafely(x => x.CompanyID == locator.CompanyID && x.SerialNumber == locator.SerialNumber);
    }

    /// <summary>
    /// Removes all locators from given company
    /// </summary>
    /// <param name="companyId"></param>
    public  void DeleteLocator(string serialNumber)
    {
        DeleteSafely(x => x.SerialNumber == serialNumber);
    }

    public  void DeleteLocatorsFromCompany(string companyId)
    {
        DeleteSafely(x => x.CompanyID == companyId);
    }

    private  void DeleteSafely(Predicate<DeviceLocator> predicate)
    {
        try
        {
            cacheLock.EnterWriteLock();

            m_deviceList.RemoveWhere(predicate);
        }
        catch
        {
            throw;
        }
        finally
        {
            cacheLock.ExitWriteLock();
        }
    }
}


texts: Display related images based on text name

texts:
Instead of  "Black and Green" text, We are displaying "Black & Green" images with help of below code.

What we want is this concept should work for all colors, for that one solution is i need to write manual code for hundreds of colors as like below to make it work for all colors. but i think this is wrong way , may be it may impact on performance, is there any better way to handle this ?

Script :

var jQuery = $.noConflict();
jQuery(document).ready(function(){
    var inner = Array();
    inner = jQuery(" .product-options ul.options-list .label>label");
    for (i=0;i<inner.length;i++){
         var classN = inner[i].innerText;
          if (classN=="Black" || classN=="Green"){
               inner.eq(i).addClass(classN);
          }
     }
});

Css for green :

.product-options ul.options-list .label>label.Green
{
     font-weight: normal;
     width: 50px;
     height: 50px;
     border-radius: 50%;
     background-image: url("http://sbdev2.kidsdial.com:81/media/catalog/custom/green.png") !important;
     background-size: cover !important;
     display: block;
     color: transparent;
     padding: 0 !important;
     font-size: 0;
}

Css for black :

.product-options ul.options-list .label>label.Black
{
     font-weight: normal;
     width: 50px;
     height: 50px;
     border-radius: 50%;
     background-image: url("http://sbdev2.kidsdial.com:81/media/catalog/custom/black.png") !important;
     background-size: cover !important;
     display: block;
     color: transparent;
     padding: 0 !important;
     font-size: 0;
}


texts: Implementing class equality/comparison in F#

texts:
I'm working on some book material on classes and interfaces in F#. My example is a latitude/longitude class:

    open System

    type LatLon(latitude : float, longitude : float) =

        member __.Latitude = latitude
        member __.Longitude = longitude

        override this.GetHashCode() =
            hash (this.Latitude, this.Longitude)

        override this.Equals(thatObj) =
            match thatObj with
            | :? LatLon as that ->
                this.Latitude = that.Latitude
                && this.Longitude = that.Longitude
            | _ -> false

        interface IEquatable<LatLon> with
            member this.Equals(that : LatLon) =
                this.Equals(that)

        interface IComparable with
            member this.CompareTo(thatObj) =
                match thatObj with
                | :? LatLon as that ->
                    compare (this.Latitude, this.Longitude) (that.Latitude, that.Longitude)
                | _ ->
                    raise <| ArgumentException("Can't compare instances of different types")

    let landsEnd = LatLon(50.07, -5.72)
    let johnOGroats = LatLon(58.64, -3.07)
    let landsEnd2 = LatLon(50.07, -5.72)

    let demo() =
        // false
        printfn "%b" (landsEnd = johnOGroats)
        // true
        printfn "%b" (landsEnd = landsEnd2)

        // 50.070000, -5.720000
        // 58.640000, -3.070000
        [ landsEnd; johnOGroats; landsEnd2 ]
        |> Set.ofList
        |> Seq.iter (fun ll -> printfn "%f, %f" ll.Latitude ll.Longitude)

By the way, I'm well aware that in this case, a record type would give the necessary structural equality out of the box. But the material I want to cover with this example is specifically about classes.

My main concerns are:

The code works the same if I don't implement IEquatable, as it uses the Equals() override. Is it considered desirable to implement IEquatable anyway, and/or does it have advantages I haven't spotted?
What about the (currently very-lightly-documented) op_Equality? Should that be used as well/instead?
The code works fine (for example Set construction, requiring comparison) if I implement IComparable but not IComparable<'T>. Have I missed out on anything useful by not using IComparable<'T>?

Obviously I'm amenable to any other feedback on the quality/style of this code.

Many thanks!


texts:
I solved this programming challenge:

  Given a 2D board and a word, find if the word exists in the grid.

  The word can be constructed from letters of sequentially adjacent
  cell, where "adjacent" cells are those horizontally or vertically
  neighboring. The same letter cell may not be used more than once.

  For example,

  Given board =

[
  ['A','B','C','E'],
  ['S','F','C','S'],
  ['A','D','E','E']
]

  word = "ABCCED", -> returns true

  word = "SEE", -> returns true

  word = "ABCB", -> returns false

class Solution {
public:
  bool DFS(vector<vector<char>> &board, string word,
           vector<vector<bool>> visited, int i, int j, int curr) {
    if (i < 0 || j < 0 || i >= board.size() || j >= board[0].size()) {
      return false;
    }
    if (visited[i][j] || board[i][j] != word[curr]) {
      return false;
    }
    visited[i][j] = true;
    ++curr;
    if (curr == word.size()) {
      return true;
    }

    return DFS(board, word, visited, i + 1, j, curr) || // Down
           DFS(board, word, visited, i, j + 1, curr) || // Right
           DFS(board, word, visited, i - 1, j, curr) || // Up
           DFS(board, word, visited, i, j - 1, curr);   // Left
  }

  bool exist(vector<vector<char>> &board, string word) {
    for (int i = 0; i < board.size(); ++i) {
      for (int j = 0; j < board[i].size(); ++j) {
        if (word[0] == board[i][j]) {
          vector<vector<bool>> visited(board.size(),
                                       vector<bool>(board[0].size(), false));
          if (DFS(board, word, visited, i, j, 0)) {
            return true;
          }
        }
      }
    }
    return false;
  }
};

My solution ranks at around 2% faster when compared to other solutions with the same language. My main desire from reviews are performance improvements.


texts:
I've just started my journey into functional programming and tried to implement a TicTacToe game Recursively without State in Scala.
What I dislike is the JOptionPane but I don't know if i can solve this more elegantly.
Does anyone know if i can solve this in a more "Scala" like way?

import javax.swing.JOptionPane

import scala.annotation.tailrec

class TicTacToe {
}

object TicTacToe {
  val l1: List[Int] = List(0, 1, 2)
  val l2: List[Int] = List(3, 4, 5)
  val l3: List[Int] = List(6, 7, 8)
  val c1: List[Int] = List(0, 3, 6)
  val c2: List[Int] = List(1, 4, 7)
  val c3: List[Int] = List(2, 5, 8)
  val d1: List[Int] = List(0, 4, 8)
  val d2: List[Int] = List(2, 4, 6)
  val patterns: List[List[Int]] = List(l1, l2, l3, c1, c2, c3, d1, d2)
  val winConditions: List[String] = List("xxx", "ooo")
  val startBoard = Array('#', '#', '#', '#', '#', '#', '#', '#', '#')

  def main(args: Array[String]): Unit = {
    startGame
  }

  def startGame: Unit ={
    @tailrec
    def playGameAt(game: List[Array[Char]], atPosition: Int): Unit = {
      val board: Array[Char] = game.head
      board.update(atPosition, nextPlayer(board))
      printBoard(board)
      if (!isWon(board)) {
        playGameAt(List(board) ++ game, Integer.parseInt(JOptionPane.showInputDialog()))
      }
    }
    playGameAt(List(startBoard), Integer.parseInt(JOptionPane.showInputDialog()))
  }

  def nextPlayer(board: Array[Char]): Char = {
    val turnNumber = board.count(_ == '#')
    if(turnNumber%2 == 0) 'x' else 'o'
  }

  def isWon(board: Array[Char]): Boolean = {
    patterns.foreach(pattern=>{
      val rowValues = pattern.foldLeft("")(_+board(_))
      if (winConditions.contains(rowValues)){
        println("Winner is " + rowValues)
        return true
      }
    })
    false
  }

  def printBoard(board: Array[Char]): Unit = {
    List(l1, l2, l3).foreach(row => println("" + board(row(0)) + board(row(1)) + board(row(2))))
    println("------")
  }
}

New, Improoved but still imperfect version


texts: Java Pong Game Collision between bat and ball

texts:
I have a very simple Pong game that I've built in Java. The code is quite long so I've decided to focus this question on the collision that occurs with the ball and the bat and also the effects in the game. I'm using ACM Graphics package to learn Java so most of the methods are from that package. I want to know how I can improve this checking process and if the way I revert the speed and direction is efficient. I'm also open to any suggestions for the game.

//Setting up variables
static final int WAIT = 50;
static final int MV_AMT = 20;
static final int BATWIDTH = 120;
static final int BATHEIGHT = 20;
static final int WINDOWX = 400;
static final int WINDOWY = 400;
static final int BALLRADIUS = 10;
private int batX = 150, batY = 400; //Starting positions
private int ballX = 160, ballY = 370;
private int ballSpeedX = 2; //the ball speed on the X axis
private int ballSpeedY = -9; //the ball speed on the Y axis

public void run(){
    //... Stuff that runs before the game, ie. draw the sceen etc.

    int currentTime = 0;
    //Do all our stuff here
    while(continueGame){
        //Pause dat loop
        pause(WAIT);
        currentTime = currentTime + WAIT;

        //Up the speed every 5 seconds
        if (currentTime % 5000 == 0) {
            if(ballSpeedY>0)
                ballSpeedY += 2;
            else
                ballSpeedY -= 2;

            if(ballSpeedX>0)
                ballSpeedX += 2;
            else
                ballSpeedX -= 2;
        }

        //Move the ball
        ballX=ballX+ballSpeedX;
        ballY=ballY+ballSpeedY;

        ball.setLocation(ballX, ballY);

        //Check
        checkCollisions();
    }

    //... Stuff that gets done after game over
}

public void checkCollisions(){
    //This method is quite long so I won't be posting it all
    //Just the part the calls the collision method

    //Get the bounds
    GRectangle batBounds = bat.getBounds();
    GRectangle ballBounds = ball.getBounds();

    //Where is the ball?
    ballX = (int)ball.getX();
    ballY = (int)ball.getY();

    //Where is the bat?
    batX = (int)bat.getX();
    batY = (int)bat.getY();

    //Did the bat touch the ball?
    if(batBounds.intersects(ballBounds)){
        batCollision();
    }
}

public void batCollision(){
    if( ballX+BALLRADIUS > batX+(BATWIDTH/2) ){ //Which side of the bat?
        //Which direction is the ball traveling when it hits?
        if(ballSpeedX >> 31 !=0){
            ballSpeedX = ballSpeedX * -1;
        } else {
            ballSpeedX = ballSpeedX;
        }
    } else {
        if(ballSpeedX >> 31 !=0){
            ballSpeedX = ballSpeedX;
        } else {
            ballSpeedX = -ballSpeedX;
        }
    }

    ballSpeedY = -ballSpeedY; //Adjust Y speed
}


texts:
So since I'm just new with learning C (this is the second day now), I'd be very happy if someone could review my code:

what I tried to do is:

create a structure containing a string- and a length-property
I want to create a function, that checks for the length of the string and sets the length property to the result
check, whether the result is correct with comparing to strlen of the original string
print the length of the string

This all works so far. Do you have any hints, what I could do better (or is ugly), what is wrong or where are any risks in my code?

this is my "helloworld.h" header file:

#include <stdio.h>
#include <stdlib.h>

struct SomeStringStruct
{
    char* actual_string;
    int length;
};
void calculate_length(struct SomeStringStruct*);

int get_string_length(char*);

and this is my "helloworld.c" source file:

#include <stdio.h>
#include <stdlib.h>
#include "helloworld.h"

int main(int argc, char* argv[])
{
    char string[] = "This is a test";
    char* ptrString = string;

    printf("strlen ptrString: %lu\n", strlen(ptrString));
    printf("get_string_length ptrString: %lu\n", get_string_length(ptrString));

    return 0;
}

void calculate_length(struct SomeStringStruct* ptrAnyStringStruct)
{
    ptrAnyStringStruct->length = 0;

    while(ptrAnyStringStruct->actual_string[ptrAnyStringStruct->length] != '\0')
        ptrAnyStringStruct->length++;
}

int get_string_length(char* string)
{
    struct SomeStringStruct myString;
    myString.actual_string = string;

    calculate_length(&myString);

    return myString.length;
};


texts:
I've been trying to get into functional programming with javascript and have tried to make some experiments with currying and function composition.

What I've played with so far is a sorter function that sorts object keys either ascending or descending:

const data = [
  { grade: 4, name: 'Zoe'},
  { grade: 3, name: 'River'},
  { grade: 9, name : 'Wash'},
  { grade: 8, name: 'Jayne'},
  { grade: 6, name: 'Inara'}
];

const ascending = (a, b) => a < b;

const descending = (a, b) => a > b;

const compare = fn => key => (a, b) => fn(a[key], b[key]) ? - 1
                                       : fn(b[key], a[key]) ? 1
                                       : 0

const sorter = (order, key) => {
  const orderFn = order === 'asc' ? ascending : descending;

  return compare(orderFn)(key)
}

const sortBy = (order, key) => fn => list => list.sort(fn(order, key))

const sorted = sortBy('asc', 'grade')(sorter)(data)
console.log(sorted)

JSBin link

Being that I'm very much new to functional programming and javascript in general, but looking to improve the quality and readability of my code, how could the program written above be improved?


texts: Generate array with random numbers and search for an element in it

texts:
This is a school project I've written. It works, but I feel it could be done better.

The program generate an array of 1'000 random numbers, and searches for a number typed into console, and displays the index if found.

int inp, zuf, i, num, trig=0;
const int amount = 1000;
int arr[amount];
cout << "Numbers" << endl << "======" << endl << endl;
cout << "Please type in a nuber between 1 and 1000: " << endl;
cin >> inp;
srand(time(NULL));
for (int i = 1; i < amount + 1; i++) {
    zuf = rand();
    zuf = (zuf % amount) + 1;
    arr[i] = zuf;
    num = i;

    if (inp== arr[num] && trig == 0) {
        cout << "The number exists at the position: ";
        trig++;
    }
    if (inp== arr[num]) {
        cout << num << ", ";
        num++;
        trig++;
    }
}

if (trig == 0) cout << "This number doesn't exist." << endl;
else cout << "\b\b." << endl;


texts: Calculate electric field of a charged annulus

texts:
This script calculates the shape of the electric field on a 2D grid perpendicular to a uniformly charged annulus using SciPy's dblquad (tutorial, documentation).

I've chosen a coarse grid and specified a very large relative error epsrel here so that this example will run in about 10 seconds, but I'll be using it on a much finer grid and with much lower specified error.

I'd like to know if there are ways this can be significantly sped up without loss of accuracy, which should be in the 1E-7 neighborhood.

I'll be avoiding pathological points manually, as I've done here by avoiding the z=0 plane. I've left out constants and units to reduce clutter.

def Excalc(r, th):
    x, y, z = r*np.cos(th), r*np.sin(th), 0.0
    return (x0-x) * ((x0-x)**2 + (y0-y)**2 + (z0-z)**2)**-1.5

def Eycalc(r, th):
    x, y, z = r*np.cos(th), r*np.sin(th), 0.0
    return (y0-y) * ((x0-x)**2 + (y0-y)**2 + (z0-z)**2)**-1.5

def Ezcalc(r, th):
    x, y, z = r*np.cos(th), r*np.sin(th), 0.0
    return (z0-z) * ((x0-x)**2 + (y0-y)**2 + (z0-z)**2)**-1.5

import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import dblquad

twopi = 2.*np.pi

# annulus of uniform, unit charge density
rmin, rmax   = 0.8, 1.2
thmin, thmax = 0,   twopi

x = np.arange(-2,    2.1, 0.1)
z = np.arange(-1.55, 1.6, 0.1) # avoid z=0 plane for integration.
X, Z = np.meshgrid(x, z)
s = X.shape

eps = 1E-4
y0  = 0

fields, errors = [], []
for x0, z0 in zip(X.flatten(), Z.flatten()):
    # use of lambda in lieu of function calls https://stackoverflow.com/a/49441680/3904031
    Ex, Exerr  = dblquad(Excalc, thmin, thmax, lambda t: rmin, lambda t: rmax, epsrel=eps)
    Ey, Eyerr  = dblquad(Eycalc, thmin, thmax, lambda t: rmin, lambda t: rmax, epsrel=eps)
    Ez, Ezerr  = dblquad(Ezcalc, thmin, thmax, lambda t: rmin, lambda t: rmax, epsrel=eps)
    fields.append([Ex, Ey, Ez])
    errors.append([Exerr, Eyerr, Ezerr])

Evec = np.stack([np.array(thing).reshape(s) for thing in zip(*fields)])
Emag = np.sqrt((Evec**2).sum(axis=0))

Evecerr = np.stack([np.array(thing).reshape(s) for thing in zip(*errors)])
Emagerr = np.sqrt((Evecerr**2).sum(axis=0))

if True:
    names = 'Ex', 'Ey', 'Ez', 'Emag'
    plt.figure()
    for i, (E, name) in enumerate(zip([e for e in Evec] + [Emag], names)):
        smalls = np.abs(E) < 1E-08
        E[smalls] = 0.     # fudge to keep Ey from showing 1E-14 fields
        plt.subplot(2, 2, i+1)
        plt.imshow(E, origin='lower')
        plt.colorbar()
        plt.title(name, fontsize=16)
    plt.show()

if True:
    names = 'Ex rel error', 'Ey rel error', 'Ez rel error', 'Emag rel error'
    plt.figure()
    for i, (err, name) in enumerate(zip([er for er in Evecerr] + [Emagerr], names)):
        plt.subplot(2, 2, i+1)
        plt.imshow(err/E, origin='lower')
        plt.colorbar()
        plt.title(name, fontsize=16)
    plt.show()


texts: Armstrong numbers in a given range using Java 8 (Follow Up)

texts:
Previous Question: Armstrong numbers in a given range using Java 8

Updated program for getting all Armstrong Numbers between 1 and 10_000_000 as per the suggestions in this answer.

public class ArmstrongNumbers {

    public static void main(String[] args) {
        IntStream.range(1, 10_000_000)
                .filter((n) -> {
                    int size = Integer.toString(n).length();
                    return Integer.toString(n)
                            .chars()
                            .map(d -> d - '0')
                            .mapToDouble(v -> Math.pow(v, size))
                            .sum() == n;
                }).forEach(System.out::println);
    }

}

Output:

1
2
3
4
5
6
7
8
9
153
370
371
407
1634
8208
9474
54748
92727
93084
548834
1741725
4210818
9800817
9926315

Comments:

Was able to replace the while loop with a stream.
Code isn't shorter but is more readable.

Can this program be made even shorter? Any other suggestions also welcome.


texts:
I've implemented CTR mode by myself (only decryption for now), using only AES built-in functions from pycrypto. It means that I'm not supposed to use mode=AES.MODE_CTR. However, I know that using AES.MODE_CTR would be more simple, but I'm doing this as a learning experience.

Is it a safe AES CTR??

(non-parallel version)

from Crypto.Cipher import AES

from Crypto.Cipher import AES

ciphers = ["69dda8455c7dd4254bf353b773304eec0ec7702330098ce7f7520d1cbbb20fc3" + \
    "88d1b0adb5054dbd7370849dbf0b88d393f252e764f1f5f7ad97ef79d59ce29f5f51eeca32eabedd9afa9329",      \
    "770b80259ec33beb2561358a9f2dc617e46218c0a53cbeca695ae45faa8952aa" + \
    "0e311bde9d4e01726d3184c34451"]

key     = "36f18357be4dbd77f050515c73fcf9f2"

class IVCounter(object):
    def __init__(self, value):
    self.value = value

    def increment(self):
        # Add the counter value to IV
        newIV = hex(int(self.value.encode('hex'), 16) + 1)

        # Cut the negligible part of the string
        self.value = newIV[2:len(newIV) - 1].decode('hex') # for not L strings remove $ - 1 $
        return self.value

    def __repr__(self):
        self.increment()
        return self.value

    def string(self):
        return self.value

class CTR():
    def __init__(self, k):
        self.key = k.decode('hex')

    def __strxor(self, a, b):     # xor two strings of different lengths
        if len(a) > len(b):
            return "".join([chr(ord(x) ^ ord(y)) for (x, y) in zip(a[:len(b)], b)])
        else:
            return "".join([chr(ord(x) ^ ord(y)) for (x, y) in zip(a, b[:len(a)])])

    def __split_len(self, seq, lenght):
        return [seq[i:i+lenght] for i in range(0, len(seq), lenght)]

    def __AESencryptor(self, cipher):
        encryptor = AES.new(self.key, AES.MODE_ECB)
        return encryptor.encrypt(cipher)

    def decrypt(self, cipher):
        # Split the CT into blocks of 16 bytes
        blocks = self.__split_len(cipher.decode('hex'), 16)

        # Takes the initiator vector
        self.IV = IVCounter(blocks[0])
        blocks.remove(blocks[0])

        # Message block
        msg = []

        # Decrypt
        for b in blocks:
            aes = self.__AESencryptor(self.IV.string())
            msg.append(self.__strxor(b, aes))

            self.IV.increment()

        return ''.join(msg)

def main():
    decryptor = CTR(key)
    for c in ciphers:
        print 'msg = ' + decryptor.decrypt(c)

if __name__ == '__main__':
    main()

This code was supposed to do the same that the code below:

import Crypto.Util.Counter
ctr_e = Crypto.Util.Counter.new(128, initial_value=long(IV.encode('hex'), 16))
decryptor = AES.new(key.decode('hex'), AES.MODE_CTR, counter=ctr_e)
print decryptor.decrypt(''.join(blocks))


texts:
An endpoint that my application interacts with allows you to specify which fields are returned in the JSON result. My application will then map the JSON to a POJO using Jackson. Quite often I add more fields in one place and forget to add it in the other which results in problems. I wrote a unit test to help make the process easier but I feel like there could be room for improvements.

Here's what I have so far:

private static final String[] POTENTIAL_FIELDS = new String[] { "field1", "field2" };

@Test
public void checkFields() {
    // get all constant fields
    Set<String> constantFields = Arrays.stream(POTENTIAL_FIELDS)
            .map(String::toLowerCase)
            .collect(Collectors.toSet());

    // get all private fields
    Set<String> reflectFields = Arrays.stream(FieldsModel.class.getDeclaredFields())
            .filter((field) -> !Modifier.isStatic(field.getModifiers()))
            .map(field -> field.getName().toLowerCase())
            .collect(Collectors.toSet());

    Set<String> symmetricDifference = Sets.symmetricDifference(constantFields, reflectFields);

    // check if there's a difference
    if (!symmetricDifference.isEmpty()) {
        Assert.fail(String.format("Difference: %s\n", String.join(",", symmetricDifference)));
    }
}

private static class FieldsModel {
    private int field1;
    private String field2;
}

The only non-standard imports are FieldsModel which is what the name suggests, and Sets which is from Guava (com.google.coom.collect.Sets). Here is a direct link to the method I used.


texts:
I have written a solution of a Mars Rover problem in C++ using OOP, but I am not fully satisfied with the design.
What changes can I make to improve the design?

Problem description is:

  A rover’s position and location is represented by a combination of x and y co-ordinates and a letter representing one of the four cardinal compass points. The plateau is divided up into a grid to simplify navigation. An example position might be 0, 0, N, which means the rover is in the bottom left corner and facing North.

  In order to control a rover , NASA sends a simple string of letters. The possible letters are ‘L’, ‘R’ and ‘M’. ‘L’ and ‘R’ makes the rover spin 90 degrees left or right respectively, without moving from its current spot. ‘M’ means move forward one grid point, and maintain the same heading.

#include<iostream>
#include<string>
#include<fstream>
using namespace std;

class Rover{

int x;
int y;
char orientation ;

public :

Rover();
Rover( int , int , char );
void rotateLeft();
void rotateRight();
void movePosition();
void displayPosition();

};

Rover :: Rover()
{
x =0;
y =0;
orientation = 'N';

}

Rover :: Rover ( int positionX , int positionY , char Orientation )
{
x= positionX;
y= positionY;

orientation = Orientation ;
}

void Rover::  displayPosition()
{
cout<<x<<" "<<y<<" "<<orientation;
}

void Rover :: rotateLeft()
{
 if(orientation=='N')
 orientation= 'W';
 else if(orientation=='W')
 orientation='S';
 else if(orientation=='S')
 orientation='E';
 else if(orientation=='E')
 orientation='N';

}

void Rover :: rotateRight()
{
 if(orientation=='N')
 orientation= 'E';
 else if(orientation=='W')
 orientation='N';
 else if(orientation=='S')
 orientation='W';
 else if(orientation=='E')
 orientation='S';

}

void Rover ::movePosition()
{
 if(orientation=='N')
    y++;
 else if(orientation=='W')
    x--;
 else if(orientation=='S')
    y--;
 else if(orientation=='E')
    x++;
}

int main()
{

int x,y; char orient ;
cin>>x>>y>>orient;
Rover firstRover(x,y,orient);

firstRover.displayPosition();

string roverMovement;
cin>>roverMovement;

for(int i=0 ; i < roverMovement.size() ; i++  )
{

     if(roverMovement[i]=='L')
     firstRover.rotateLeft();

     else if(roverMovement[i]=='R')
     firstRover.rotateRight();

     else
     firstRover.movePosition();
}

firstRover.displayPosition();

return 0;
}

How the design of this code can be improved?


texts: Own implementation of Euclid sub algorithm in Lisp

texts:
(defun euclid-sub-wrapper (a b)
    (euclid-sub (abs a) (abs b)))

(defun euclid-sub (a b)
    (if (eq a b)
        a
        (if (> a b)
            (euclid-sub (- a b) b)
            (euclid-sub a (- b a)))))

The above code is an implementation of the Euclid subtraction algorithm to find the greatest common divisor in lisp (Common Lisp). To make the algorithm work for negative numbers I had to use this wrapper function but I wonder if there is another way to do everything in one function. I do like to keep the recursion and although I could just call (abs a) and (abs b) every time I do a recursive step it is only needed once (and therefor somewhat redundant), so I don't really like that either.

If there isn't a way to fix this, could someone maybe give me a better name for the wrapper function and / or the function it is wrapping. Any help would be greatly appreciated.


texts: Code Improvement/Insight: Should I have approached these functions differently? Animations using Javascript

texts:
This code works as it is intended. What I seek is a feedback on the quality of my code. Where should I have written it differently or how should have I approached instead of the way that I have?

These functions will be moved to a separate file to be used on other pages as well. My goal is to have this code reusable as well.

I tried using onMouseOver={ani.bind(this)}

I've also tried let element = ani() but received undefined

<img className="gPic" src={img['roofRepair1'].src} alt={img['roofRepair1'].alt} id="special" onMouseOver={ani} onMouseLeave={revani}/>

//Function anime: Anime.js

function ani(p){
    let element = p.target.id
    anime({
        targets: '#'+ element,
        scale: 2,
    })
    return element;
}

function revani(p){
    let element = p.target.id
    anime({
        targets:'#'+ element,
        scale: 1
    })
}


texts: Counting the number of domino tilings for a rectangular grid

texts:
A domino tiling of a grid is a tiling of the grid using domino pieces. Below is a C++ program to count the number of possible tilings of a grid of a given size.

The program constructs the board row by row, representing each row as a string. In each row, d represents the top half of a domino pointing downwards, u represent the bottom half of a domino pointing upwards, r represents the left half of a domino pointing to the right, and l represents the right half of a domino pointing to the left.

#include <iostream>
#include <vector>
#include <map>

using namespace std;

class DominoTilingCounter {
    int height, width;
    bool done;
    int tilingCount;

    map<string, vector<string>> dictionary;

    vector<string> firstRow(int width) {
        vector<string> prev;

        prev.push_back("d");
        prev.push_back("r");

        for (int col = 1; col < width; col++) {
            vector<string> next;

            while (!prev.empty()) {
                string candidate = prev.back();
                prev.pop_back();

                switch (candidate.back()) {
                case 'd':
                case 'l':
                    next.push_back(candidate + 'd');
                    if (col != width - 1)
                        next.push_back(candidate + 'r');
                    break;
                case 'r':
                    next.push_back(candidate + 'l');
                    break;
                }
            }

            prev = next;
        }

        return prev;
    }

    vector<string> nextRows(const string& row) {
        if (dictionary.find(row) != dictionary.end())
            return dictionary[row];

        vector<string> prev;

        if (row.front() == 'd')
            prev.push_back("u");
        else {
            prev.push_back("d");
            if(row.length() > 1)
                prev.push_back("r");
        }

        for (int col = 1; col < row.length(); col++) {
            vector<string> next;

            while (!prev.empty()) {
                string candidate = prev.back();
                prev.pop_back();

                switch (row[col]) {
                case 'd':
                    if (candidate[col - 1] != 'r')
                        next.push_back(candidate + 'u');
                    break;
                case 'u':
                case 'r':
                case 'l':
                    if (candidate[col - 1] == 'r')
                        next.push_back(candidate + 'l');
                    else {
                        next.push_back(candidate + 'd');
                        if (col != row.length() - 1)
                            next.push_back(candidate + 'r');
                    }
                }
            }

            prev = next;
        }

        return prev;
    }

    int countTiling(int height, int width, const string& previousRow, int currentRow) {
        if (currentRow == height) {
            for (char cell : previousRow)
                if (cell == 'd')
                    return 0;
            return 1;
        }

        int count = 0;

        vector<string> rows;

        if (currentRow == 0)
            rows = firstRow(width);
        else
            rows = nextRows(previousRow);

        for (string row : rows)
            count += countTiling(height, width, row, currentRow + 1);

        return count;
    }

public:
    DominoTilingCounter(int height, int width) : height(height), width(width) {
        if (height <= 0 || width <= 0 || height * width % 2) {
            tilingCount = 0;
            done = true;
        }
    }

    int count() {
        if (!done) {
            tilingCount = countTiling(height, width, "", 0);
            done = true;
        }

        return tilingCount;
    }
};

int main() {
    DominoTilingCounter tc(4, 7);

    cout << tc.count() << endl;

    return 0;
}


texts:
I wrote this Data Explorer query (reproduced below) some time ago that helped identify posts containing potential spelling/punctuation errors and earned me a Copy Editor badge on Anime.SE.

SELECT DISTINCT PostTypes.Name AS [Post Type],
                Posts.Score AS [Post Score],
                Posts.Id AS [Post Link],
                Posts.LastActivityDate AS [Last Activity]
FROM Posts
INNER JOIN PostTypes
ON Posts.PostTypeId = PostTypes.Id
INNER JOIN Users
ON Posts.OwnerUserId = Users.Id
INNER JOIN PostHistory
ON Posts.Id = PostHistory.PostId
WHERE Posts.Score > 0 AND -- Low quality posts are probably not worth salvaging
      Posts.ClosedDate IS NULL AND
      Users.Reputation < 4000 AND -- Posts by trusted users are exempt from editing (that is the theory anyway)
      (
          (
              Posts.PostTypeId IN (1, 3) AND
              Posts.Id <> ALL (
                  SELECT DISTINCT PostId
                  FROM PostHistory
                  WHERE PostId = PostHistory.PostId AND
                        PostHistoryTypeId IN (14, 15)
                  GROUP BY PostId
                  HAVING COUNT(PostHistoryTypeId) % 2 = 1
              )
          ) OR -- Locked posts can't be edited
          (
              Posts.PostTypeId IN (2, 3) AND
              Posts.ParentId <> ALL (
                  SELECT DISTINCT PostId
                  FROM PostHistory
                  WHERE PostId = Posts.ParentId AND
                        PostHistoryTypeId IN (14, 15)
                  GROUP BY PostId
                  HAVING COUNT(PostHistoryTypeId) % 2 = 1
              )
          ) OR
          Posts.PostTypeId IN (4, 5)
      ) AND
      (
          (
              Posts.Title NOT LIKE '%?' AND
              (
                  LOWER(Posts.Title) LIKE 'is %' OR
                  LOWER(Posts.Title) LIKE 'are %' OR
                  LOWER(Posts.Title) LIKE 'do[en ]%' OR
                  LOWER(Posts.Title) LIKE '%wh[aeoy]%' OR
                  LOWER(Posts.Title) LIKE '%how%'
              )
          ) OR
          (
              Posts.Title LIKE '[abcdefghijklmnopqrstuvwxyz]%' OR
              Posts.Title LIKE '%[ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz]([ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrtuvwxyz]%' OR
              Posts.Title LIKE '%[ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrtuvwxyz])[ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz]%' OR
              Posts.Title LIKE '%[ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz],[ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz]%' OR
              Posts.Title LIKE '% i[ '']%'
          ) OR
          (
              Posts.Body LIKE '[abcdefghijklmnopqrstuvwxyz]%' OR
              Posts.Body LIKE '%[ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz]([ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrtuvwxyz]%' OR
              Posts.Body LIKE '%[ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrtuvwxyz])[ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz]%' OR
              Posts.Body LIKE '%[ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz],[ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz]%' OR
              Posts.Body LIKE '% i[ '']%'
          )
      )
ORDER BY Posts.LastActivityDate DESC

Is there any way to speed this up and, more importantly, simplify the query expression? Especially the part where I list the letters of the alphabet in both upper and lower cases, because I think in SQL, [A-Za-z] doesn't give what I want.


texts:
I'd like to know if I'm doing profile configuration in the wrong place or in the wrong way.

I'm following the Onion Architecture, so that restricts the direction of my dependencies towards the center.

Core

My domain model and AutoMapper facade:

namespace Core.Domain
{
    public class MyModel
    {
        // model stuff
    }
}

namespace Core.Services
{
    public interface IMapper
    {
        object Map(object source, Type sourceType, Type destinationType);
    }
}

Infrastructure

AutoMapper facade implementation:

namespace Infrastructure.Mapping
{
    public class Mapper : IMapper
    {
        private readonly IMappingEngine _mappingEngine;

        public Mapper(IMappingEngine mappingEngine)
        {
            _mappingEngine = mappingEngine;
        }

        public object Map(object source, Type sourceType, Type destinationType)
        {
            return _mappingEngine.Map(source, sourceType, destinationType);
        }
    }
}

UI

This is my controller and view model. I'm using the AutoMapper via a filter, following this example.

namespace UI.Controllers
{
    public class HomeController : Controller
    {
        [AutoMap(typeof(MyModel), typeof(MyViewModel))]
        public ActionResult Index()
        {
            var myItem = _myRepository.GetById(0);
            return View(myItem);
        }
    }
}

namespace UI.ViewModels
{
    public class MyViewModel
    {
        // view stuff
    }
}

Dependency Resolution

This is where I have my doubts:

namespace DependencyResolution
{
    public class MappingModule : NinjectModule
    {
        public override void Load()
        {
            Mapper.Initialize(cfg => cfg.AddProfile(new MyProfile()));
            Bind<IMappingEngine>().ToMethod(ctx => Mapper.Engine);
            Bind<IMapper>().To<Mapping.Mapper>();

            Kernel.BindFilter<AutoMapFilter>(FilterScope.Controller, 0)
                  .WhenActionMethodHas<AutoMapAttribute>()
                  .WithConstructorArgumentFromActionAttribute<AutoMapAttribute>("sourceType", att => att.SourceType)
                  .WithConstructorArgumentFromActionAttribute<AutoMapAttribute>("destType", att => att.DestType);
        }
    }

    public class MyProfile : Profile
    {
        protected override void Configure()
        {
            Mapper.CreateMap<MyModel, MyViewModel>().ForMember(...);
        }
    }
}

Questions

Is the way I bind to AutoMapper wrong?
Is this the wrong place for the profile (keep in mind the dependency restriction)?

In the ideal world I would have placed

Mapper.CreateMap<MyModel, MyViewModel>().ForMember(...)

in Global.asax, but how do I expose CreateMap without referencing AutoMapper?

Is there anything else you have noticed?


texts: An enum that has situationally invalid entries

texts:
Is it considered bad style to have that BOTH value in the Direction enum? Problems can arise from BOTH being present, for example when trying to build a procedural UI for the Car class, it (the generator) would see the setTurnSignal(Direction) method and create a way for the user to give it a Direction, but it would suggest all values, of which one is illegal.

Conversely, not having BOTH causes issue with the getBlinkerStatus() as it is no longer able to indicate that both are on. There are a couple ways I could address that issue, such as creating more blinker getters, but that  or switching form an enum to bit based values and building masks for them.

enum Direction{
    LEFT, RIGHT, BOTH, NONE;
}

class Car{
    Direction turnSignal;
    boolean hazards;

    void setTurnSignal(Direction direction){
        if(Direction.BOTH.equals(direction)){
            throw new IllegalArgumentException("Turn signal cannot be set to the given direction: " + direction);
        }else{
            turnSignal = direction;
        }
    }

    Direction getBlinkerStatus(){
        if(hazards){
            return Direction.BOTH;
        }else{
            return turnSignal;
        }
    }


texts:
The idea is to have a heading for each date returned by the query.  This could be any number of dates.  I dynamically altered the #table which is ugly but there is no other way.

Ultimately I would like to reduce the amount of cursors but I'm not sure if it is possible.  This is using the Northwind database on SQL Server 2000 (I know, its lifecycle has ended).

  USE Northwind

  DECLARE @startdate DATETIME, @enddate DATETIME, @sql VARCHAR(1000)
  SELECT @startdate = '1998-01-01', @enddate = '1998-06-01'

  DROP TABLE #OUTPUT
  DROP TABLE #TEMP

  CREATE TABLE #OUTPUT
  (
    product VARCHAR(50)
  )

  SELECT o.orderdate, p.ProductName
  INTO #TEMP
  FROM [Northwind].[dbo].[Orders] o
  join [order details] od ON od.orderid = o.orderid
  join Products p on p.ProductID = od.ProductID
  WHERE o.OrderDate >= @startdate AND o.OrderDate < @enddate

  --Cursor storage variables
  DECLARE @prod VARCHAR(30), @orderdate VARCHAR(20), @cnt AS INT
  --

  --Add date column headings
  DECLARE CUR1 CURSOR LOCAL FOR
    SELECT DISTINCT(CONVERT(VARCHAR, orderdate, 101)) FROM #TEMP

  OPEN CUR1
  FETCH NEXT FROM CUR1 INTO @orderdate

  WHILE @@FETCH_STATUS = 0
  BEGIN
    EXEC('ALTER TABLE #OUTPUT ADD [' + @orderdate + '] VARCHAR(20) DEFAULT 0')
    FETCH NEXT FROM CUR1 INTO @orderdate
  END
  --

  --Add left column containing list of products
  INSERT INTO #OUTPUT (product)
  SELECT DISTINCT(productname) FROM #TEMP
  --

  --Update all rows setting the approriate date column to the count
  DECLARE CUR2 CURSOR LOCAL FOR
    SELECT CONVERT(VARCHAR, orderdate, 101), productname, COUNT(*) as cnt
    FROM #TEMP
    GROUP BY CONVERT(VARCHAR, orderdate, 101), productname

  OPEN CUR2

  FETCH NEXT FROM CUR2 INTO @orderdate, @prod, @cnt

  WHILE @@FETCH_STATUS = 0
  BEGIN
    SELECT @sql = 'UPDATE #OUTPUT set [' + @orderDate + '] =  [' + @orderdate + '] + ' + CAST(@cnt AS VARCHAR) + '  WHERE LTRIM(RTRIM(product)) = ''' + LTRIM(RTRIM(REPLACE(@prod, '''', ''))) + ''' '
    EXEC(@sql)
    PRINT @sql
    FETCH NEXT FROM CUR2 INTO @orderdate, @prod, @cnt
  END

  SELECT * FROM #OUTPUT

The result should look like this:

product           01/01/1998    01/02/1998
Alice Mutton           0            2
Aniseed Syrup          3            1
Boston Crab Meat       1            2


texts: How to remove redundancy in code when alternating between methods?

texts:
Alright, so I've been tasked with recreating the game of pig dice in Java, however the issue that im having with creating a method that switches back and fourth between pc and user is that there's a lot of redundancy with calling methods with different parameters.

How would I be able to condense this alternating code?

if (coin.equals("heads")) {
    if (currentPlayer.equals(pcName)) {
        pcPoints = roll2Dices(kb, random, currentPlayer, pcPoints, userName, pcName, round);
        currentPlayer = userName;
    } else if (currentPlayer.equals(userName)) {
        userPoints = roll2Dices(kb, random, currentPlayer, userPoints, userName, pcName, round);
        currentPlayer = pcName;
    }
} else if (coin.equals("tails")) {
    if (currentPlayer.equals(userName)) {
        userPoints = roll2Dices(kb, random, currentPlayer, userPoints, userName, pcName, round);
        currentPlayer = pcName;
    } else if (currentPlayer.equals(pcName)) {
        pcPoints = roll2Dices(kb, random, currentPlayer, pcPoints, userName, pcName, round);
        currentPlayer = userName;
    }
}


texts: Simple lock-free queue - multiple producers, single consumer

texts:
I have a simple lock-free queue, which supports multiple producers, but only one consumer. It is based on a constant-sized ring buffer and stores only pointers to a class and not actual instances. Also it uses pre-C++11 and GCC-specific functions.

Is is implemented properly or does it have a data race? I only care that it works properly on x64/x86 Linux.

// header
class LockFreeQueue {
 public:
  LockFreeQueue(unsigned long size);
  ~LockFreeQueue();

  bool Enqueue(Element* element);
  bool Dequeue(Element** element);
  bool Peek(Element** element);
  unsigned long Size();

private:
  unsigned long size_;
  volatile Element** elements_;
  volatile unsigned long idx_r_; // index of read
  volatile unsigned long idx_w_; // index of write
  volatile unsigned long idx_w_cas_;
};

// impl
LockFreeQueue::LockFreeQueue(unsigned long size) {
  size_ = size;
  idx_r_ = 0;
  idx_w_ = 0;
  idx_w_cas_ = 0;
  elements_ = (volatile Element**)(new Element*[size]);
}

LockFreeQueue::~LockFreeQueue() {
  delete[] elements_;
}

bool LockFreeQueue::Enqueue(Element* element) {
  while (true) {
    unsigned long prev_idx_w = idx_w_cas_;
    unsigned long next_idx_w = (prev_idx_w + 1) % size_;
    if (next_idx_w == idx_r_) return false;
    if (__sync_bool_compare_and_swap(&idx_w_cas_, prev_idx_w, next_idx_w)) {
      elements_[prev_idx_w] = element;
      while (!__sync_bool_compare_and_swap(&idx_w_, prev_idx_w, next_idx_w)) {}
      break;
    }
  }
  return true;
}

bool LockFreeQueue::Dequeue(Element** element) {
  if (idx_r_ == idx_w_) return false;
  unsigned long next_idx_r = (idx_r_ + 1) % size_;
  *element = (Element*) elements_[idx_r_];
  idx_r_ = next_idx_r;
  return true;
}

bool LockFreeQueue::Peek(Element** element) {
  if (idx_r_ == idx_w_) return false;
  *element = (Element*) elements_[idx_r_];
  return true;
}

unsigned long LockFreeQueue::Size() {
  if (idx_w_ >= idx_r_) return idx_w_ - idx_r_;
  return size_ - idx_r_ + idx_w_;
}

Note that I don't have any tests for the code. It also was written by someone else I cannot reach.

I know that volatile alone does not guarantee correctness, but I wonder if is sufficient together with CAS.

EDIT:

Usage in existing code goes like this:

Producer thread (x4):

LockFreeQueue* theQueue = ...

while (true) {
  Element* element = new Element();
  // do some short work
  //
  while(!theQueue->Enqueue(element)) {}
}

Consumer thread:

LockFreeQueue* theQueue = ...

while (true) {
  Element* element;
  if (theQueue->Dequeue(&element)) {
    // do some work with the element
    //
    delete element;
  }
}


texts:
So I was doing something which creates an airplane with an actual airline code, number, airplane type and so on.
The airline code and airplane type are stored in a txt file so I can add more later to my leisure... but the code I came up with to get a random line is extremely messy. Is there a better way? I searched all over stackexchange but it all seemed quite complex for little files which will have only (if ever) a couple dozen lines of content.

public String generate() {

    int totalLines = 0;
    File file = new File("icaocodes.txt");

    BufferedReader br = null;

    try {
        br = new BufferedReader(new FileReader(file));

        while ((br.readLine()) != null) {
            totalLines++;
        }
        br.close();

        br = new BufferedReader(new FileReader(file));

        Random random = new Random();
        int randomInt = random.nextInt(totalLines);
        int count=0;
        String icaocode;
        while ( (icaocode = br.readLine()) != null) {
            if (count == randomInt) {
                br.close();
                return icaocode;
            }
            count++;
        }
         br.close();

    } catch (FileNotFoundException e) {
        System.out.println("File not found: " + file.toString());
    } catch (IOException e) {
        System.out.println("Unable to read file: " + file.toString());
    }

    return "Puppies";

}


texts:
I'm working on a simple text based adventure game. I've just finished working on the character creation portion. The code works perfectly fine when run, but I would just like to get some feedback to ensure that it checks off from a professional and efficient standpoint.

The values of the materials, weapons, and spells are representing the amount of damage points each does for further and future calculations with the characters stats later in the game.

The code itself essentially allows you to input a characters name. Then, the strength, stamina, and intellect is randomly generated so that your character build is different at the beginning of each game. Then, once that has finished, the code takes into account the weapon type, the material of the weapon, the spell type and adds additional damage based on the players stats.

I would just like to know if there is a better way of writing my code to make it look cleaner, or if there possibly any concerns that might cause me issues down the road when I add more functionality to the game. Seeing as I am a beginner to C++, I am not incredibly great at determining whether my code is optimal or not.

#include <iostream>
#include <string>
#include <ctime>

using namespace std;

/* Materials Structure */

typedef struct materials {
    int wood = 1, oak = 2, maple = 3, ash = 4, bronze = 2, iron = 3, steel = 4, mithril = 5, dragon = 6;
};

/* Weapon Structure */

typedef struct weapons {
    int dagger = 2, sword = 3, axe = 4, mace = 5, bow = 3, arrows = 2;
} weapons;

/* Spell Structure */

typedef struct spells {
    int fire = 4, frost = 6, dark = 8, chaos = 10;
} spells;

/* Character Structure */

typedef struct character {
    string name;
    int health = 100, mana = 100, strength, stamina, intellect, weaponAttack, spellAttack, souls = 0;
    spells spell;
    weapons weapon;
    materials material;
} character;

/* Function Declaration */

character characterCreation(string name);
void printInfo(character createChar);

/* Main Function */

int main() {
    string characterName;
    cout << "Please input character name: ";
    cin >> characterName;

    srand(time(NULL));
    character player = characterCreation(characterName);
    printInfo(player);

    system("pause");
    return 0;
}

/* Function Definition */

character characterCreation(string name) {
    character createChar;
    createChar.name = name;
    createChar.strength = rand() % 5 + 5;
    createChar.stamina = rand() % 5 + 5;
    createChar.intellect = rand() % 5 + 5;
    createChar.health += 2 * createChar.stamina;
    createChar.mana += 3 * createChar.intellect;
    createChar.weaponAttack = (createChar.weapon.dagger * createChar.material.bronze) + (2 * createChar.strength);
    createChar.spellAttack = (createChar.spell.fire + (createChar.intellect * 2));
    return createChar;
}

void printInfo(character createChar) {
    cout << createChar.name << endl;
    cout << createChar.health << endl;
    cout << createChar.mana << endl;
    cout << createChar.strength << endl;
    cout << createChar.stamina << endl;
    cout << createChar.intellect << endl;
    cout << createChar.weaponAttack << endl;
    cout << createChar.spellAttack << endl;
    cout << createChar.souls << endl;
}


texts: Converting an integer to Greek and Roman numerals

texts:
Yesterday I posted a question about converting an integer to it's Roman Numeral equivalent. Apparently you guys liked it and gave me some good advice, so I decided to take all your advice, and go a step further, it will now not only convert to Roman  but will now also convert to Greek numerals.

I would like some critique on this project that I'm continuing.

# <~~ coding=utf-8 ~~>
import argparse

opts = argparse.ArgumentParser()
opts.add_argument("-g", "--greek", type=int,
                  help="Convert to Medieval Numerals")
opts.add_argument("-r", "--roman", type=int,
                  help="Convert to Roman Numerals")
args = opts.parse_args()

ROMAN_NUMERAL_TABLE = (
    ("~M", 1000000), ("~D", 500000), ("~C", 100000),
    ("~L", 50000), ("~X", 10000), ("~V", 5000),  # "~" indicates a Macron
    ("M", 1000), ("CM", 900), ("D", 500),
    ("CD", 400), ("C", 100),  ("XC", 90),
    ("L", 50),   ("XL", 40),  ("X", 10),
    ("IX", 9),   ("V", 5),    ("IV", 4),
    ("I", 1)
)

GREEK_NUMERAL_TABLE = (
    ("α", 1), ("β", 2), ("γ", 3),
    ("δ", 4), ("ε", 5), ("Ϝ", 6),
    ("ζ", 7), ("η", 8), ("θ", 9),
    ("ι", 10), ("κ", 20), ("λ", 30),
    ("μ", 40), ("ν", 50), ("ξ", 60),
    ("ο", 70), ("π", 80), ("ϙ", 90),
    ("ρ", 100), ("σ", 200), ("τ", 300),
    ("υ", 400), ("φ", 500), ("χ", 600),
    ("ψ", 700), ("ω", 800), ("ϡ", 900),
    ("α", 1000), ("β", 2000), ("γ", 3000),
    ("δ", 4000), ("ε", 5000), ("ϛ", 6000),
    ("ζ", 7000), ("η", 8000), ("θ", 9000)  # The Greeks weren't very creative
)

def convert_init(number, convert_to=None):
    """ Convert a number to a numeral, Greek or Roman
    >>> print(convert_init(45, convert_to=GREEK_NUMERAL_TABLE))
    ϜϜϜϜϜϜϜγ
    >>> print(convert_init(45, convert_to=ROMAN_NUMERAL_TABLE))
    XLV """
    display_numerals = []

    for numeral, value in sorted(convert_to)[::-1]:  # sort the list from largest to least
        count = number // value
        number -= count * value
        display_numerals.append(numeral * count)

    return ''.join(display_numerals)

if __name__ == '__main__':
    if args.greek:
        data = convert_init(int(args.greek), convert_to=GREEK_NUMERAL_TABLE)
        with open("greek_numerals.txt", "a+") as file_data:
            file_data.write(data)  # Write it to a file

    elif args.roman:
        data = convert_init(int(args.roman), convert_to=ROMAN_NUMERAL_TABLE)
        with open("roman_numerals.txt", "a+") as file_data:
            file_data.write(data)

    else:
        raise NotImplementedError("{} is not implemented yet".format(args))

Key points I would like to focus on, of course critique the whole program.

I used writing to a file because when if I output it to the console I get an IO error, basically an encoding error. Does this have to do with my computer or with the program?
Would there be a way for me to condense the two tuples down into one and still convert correctly?


texts: Compile-time Lagrange polynomials in C++

texts:
I have implemented Lagrange polynomials, i.e.

\$l_j(x) := \prod_{\begin{smallmatrix}0\le m\le k\\ m\neq j\end{smallmatrix}}\frac{x-x_m}{x_j-x_m} = \frac{(x-x_0)}{(x_j-x_0)} \cdots \frac{(x-x_{j-1})}{(x_j-x_{j-1})} \frac{(x-x_{j+1})}{(x_j-x_{j+1})} \cdots \frac{(x-x_k)}{(x_j-x_k)}\$

where the product is supposed to be expanded at compile time. The \$x_m\$ are chosen to be evenly spaced on the interval \$[-1, 1]\$.

I've used boost fusion for this, mainly because it seemed (and turned out to be) helpful, but I'm not entirely sure if it's the best choice (out of the multiple TMP libraries in boost and elsewhere).

Generally, I'm new to such an extensive use of types and templates, so general advice in this regard is appreciated. And now, without further ado:

#include <iostream>

#include <boost/fusion/sequence.hpp>
#include <boost/fusion/include/accumulate.hpp>

namespace fusion = boost::fusion;

template <int Order, int NodeId>
struct Location
{
    static constexpr double coord = 2.0 * NodeId / Order - 1.0;
};

template <class BaseNode, class OtherNode>
struct Term
{
    static double F(double x)
    {
        return (x - OtherNode::coord) / (BaseNode::coord - OtherNode::coord);
    }
};

template <int Order, int BaseNodeId, int NodeCounter = Order>
struct RemainingNodes
{
    using tail = typename RemainingNodes<Order, BaseNodeId, NodeCounter - 1>::list;
    using currentNode = Location<Order, NodeCounter>;
    using full =
        typename fusion::result_of::as_vector<typename fusion::result_of::push_back<tail, currentNode>::type>::type;
    using list = typename std::conditional<BaseNodeId == NodeCounter, tail, full>::type;
};

template <int Order, int BaseNodeId>
struct RemainingNodes<Order, BaseNodeId, 0>
{
    using list = typename boost::fusion::vector<Location<Order, 0>>;
};

template <int Order>
struct RemainingNodes<Order, 0, 0>
{
    using list = typename boost::fusion::vector<>;
};

template <class BaseNode>
struct GetTerm
{
    template <class OtherNode>
    Term<BaseNode, OtherNode> operator()(OtherNode);
};

template <int Order, int BaseNodeId>
struct Terms
{
    using Nodes = typename RemainingNodes<Order, BaseNodeId>::list;
    using BaseNode = Location<Order, BaseNodeId>;
    using transformed_list = typename fusion::result_of::transform<Nodes, GetTerm<BaseNode>>::type;
    using value = typename fusion::result_of::as_vector<transformed_list>::type;
};

struct evaluate
{
    double _x;

    evaluate(double x)
        : _x(x)
    {
    }

    template <class _Term>
    double operator()(double product, const _Term&) const
    {
        return product * _Term::F(_x);
    }
};

template <int Order, int BaseNodeId>
struct LagrangePolynomial
{
    using _Terms = Terms<Order, BaseNodeId>;

    static double F(double x)
    {
        return boost::fusion::accumulate(typename _Terms::value(), 1.0, evaluate(x));
    }
};

int main()
{
    using secondOrder0 = LagrangePolynomial<2, 0>;

    std::cout << "2nd order Lagrange polynomial of 1st node, evaluated at -1, 0, 0.5, 1: ";
    std::cout << secondOrder0::F(-1.0) << " " << secondOrder0::F(0.0) << " " << secondOrder0::F(0.5) << " "
              << secondOrder0::F(1.0) << std::endl;

    return 0;
}


texts: Golang async but sequential enqueue with buffered channel

texts:
The objective of this program is to call enqueue sequentially with multiple URLs, and never block, fetching the URLs asynchronously, but on the order they were entered.

In other words: keep calling enqueue to add urls to a buffered channel (queue) (possibly with a specific callback), and consume one by one in the order they where entered in the queue. I used WaitGroup to prevent the go program from immediately exiting, but I feel I'm not taking advantage of the buffered channel at all.

package main

import (
    "fmt"
    "net/http"
    "sync"
)

type callback func(url string, res *http.Response, err error)

type callbackRequest struct {
    cb  callback
    url string
}

var queue = make(chan callbackRequest, 1)
var wg sync.WaitGroup

func worker() {
    for {
        req := <-queue
        fmt.Println("processing", req.url)
        res, err := http.Get(req.url)
        req.cb(req.url, res, err)
    }

}

func enqueue(url string) {
    fmt.Println("enqueue", url)
    cb := func(url string, res *http.Response, err error) {
        if err != nil {
            fmt.Println("error")
        }
        fmt.Println(url, res.Status)
        wg.Done()
    }
    cbReq := callbackRequest{url: url, cb: cb}
    wg.Add(1)
    go func(cbr callbackRequest) {
        queue <- cbReq
    }(cbReq)
}

func main() {
    go worker()
    enqueue("http://google.com")
    enqueue("http://reddit.com")
    enqueue("http://yahoo.com")
    enqueue("http://bing.com")
    enqueue("http://google.com")
    enqueue("http://yahoo.com")
    enqueue("http://reddit.com")
    enqueue("http://bing.com")
    enqueue("http://google.com")

    wg.Wait()
}

Output:

$ go run enqueue/main.go
enqueue http://google.com
enqueue http://reddit.com
enqueue http://yahoo.com
enqueue http://bing.com
enqueue http://google.com
enqueue http://yahoo.com
enqueue http://reddit.com
enqueue http://bing.com
enqueue http://google.com
processing http://google.com
http://google.com 200 OK
processing http://reddit.com
http://reddit.com 200 OK
processing http://yahoo.com
http://yahoo.com 200 OK
processing http://bing.com
http://bing.com 200 OK
processing http://google.com
http://google.com 200 OK
processing http://yahoo.com
http://yahoo.com 504 Gateway Timeout
processing http://reddit.com
http://reddit.com 200 OK
processing http://bing.com
http://bing.com 200 OK
processing http://google.com
http://google.com 200 OK


texts: Update column based on input variable in stored procedure

texts:
The purpose of the below code is to update a column based on the name of the field name sent from the .NET code. This allows one piece of code to handle multiple rows when a user is only adding/updating one at a time.

I have been using Stored Procedures for a while but normally just Add/Update but not using variable field names. All tips appreciated.

USE DB
GO
/****** Object:  StoredProcedure [dbo].[spActionUpdateOldestDate]    Script Date: 04/02/2014 14:24:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[spUpdateViaFieldName]

-- spActionUpdateOldestDate '1234','date','field'
-- Add the parameters for the stored procedure here
@AlphaNumbericalRef nvarchar(50)
,@vValue nvarchar(MAX)
 ,@vFieldName varchar(MAX)

AS
BEGIN

-- add selection for courseID etc.. here
Execute ('UPDATE [TblActionsOldest] SET ' + @vFieldName + ' = ''' + @vValue + ''' WHERE RefID = ''' + @AlphaNumbericalRef+ '''')

END


texts: Implementation of arbitrary-precision integer addition

texts:
Implementation:

string Add(string a,string b)
{
    int maxLen = Math.Max(a.Length,b.Length);
    a = a.PadLeft(maxLen+1,'0');
    b = b.PadLeft(maxLen+1,'0');

    int[] arr1 = a.Select(x => int.Parse(x.ToString())).ToArray();
    int[] arr2 = b.Select(x => int.Parse(x.ToString())).ToArray();
    int[] sum = new int[arr1.Length];

    int carry = 0;
    for(int i = sum.Length-1;i >= 0;i--)
    {
        int total = arr1[i] + arr2[i] + carry;
        sum[i] = total % 10;
        if(total > 9) carry = 1;
        else carry = 0;
    }
    return string.Join("",sum.SkipWhile(x => x == 0));
}

Example:

void Main()
{
    string a = "12121213213213902139210903";
    string b = "1213212222132132113";
    Console.WriteLine(Add(a,b)); // 12121214426426124271343016
}

How can I improve this implementation?


texts:
The interview question was to traverse a tree into a list.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication2
{
    public class TreeToList
    {
        public TreeToList()
        {

            //            0
            //        2         4
            //     6    8          10
            TreeNode root = new TreeNode(0);
            root.Left = new TreeNode(2);
            root.Right = new TreeNode(4);
            root.Left.Left = new TreeNode(6);
            root.Left.Right = new TreeNode(8);
            root.Right.Right = new TreeNode(10);

            List<int> res = ConvertTreeToList(root);

        }

        //pre-order 0 2 4
        //in-order 2 0 4
        //post-order 2 4 0

        private List<int> ConvertTreeToList(TreeNode root)
        {
            List<int> res = new List<int>();
            if (root != null)
            {
                res.Add(root.Index);
            }
            else
            {
                return null;
            }
            if(root.Left != null)
            {
                res.AddRange(ConvertTreeToList(root.Left));
            }
            if(root.Right != null)
            {
                res.AddRange(ConvertTreeToList(root.Right));
            }
            return res;
        }
    }
}

My output is:

0,2, 6, 8, 4, 10


texts: window.innerWidth - workaround for when it returns the wrong value

texts:
Some JavaScript libraries relies on window innerWidth and innerHeight to do their calculations
window.innerWidth is not 100% reliable, which may lead to bugs
matchMedia().matches is 100% accurate but it returns a boolean value
come around: use matchMedia to verify window.innerWidth value; if it returns false use matchMedia to do a binary search until it finds the correct value

I faced that issue with some libs that relies on window.innerWidth. In cases where I had some media queries the return value of window.innerWidth used by the library would be off and that library would have issues with incorrect value.

I've seen that matchMedia().matches always return the correct value, but it returns a boolean value, not the width value. I've not seen a solution so far for that (maybe some of you know a better solution?), so I came up with a solution using matchMedia.

I created a function getCorrectDimension that performs a binary search around the window innerWidth (or innerHeight) to find the correct value if its value is wrong as you can see below:

const binarySearch = dim => function bin(start, end) {
    const guess = Math.floor((start + end)/2)

    // this checks if we have the correct value, if not it will keep calling itself until there's a match
    if(window.matchMedia(`(${dim}: ${guess}px)`).matches) {
        return guess
    }

    // since it is not a match, then we need to recalibrate the range and call again.
    // for that we check the boolean value using with min-width (height) rule.
    return window.matchMedia(`(min-${dim}: ${guess}px)`).matches
        ? bin(guess, end)
        : bin(start, guess)
}

const getCorrectDimension = (dim = 'width', range = 300) => {
    if(dim !== 'width' && dim !== 'height') {
        throw Error('`getCorrectDimension` accepts "width" or "height" as parameter')
    }

    let prop = 'inner' + dim.charAt(0).toUpperCase() + dim.slice(1)

    // here checks if the window.innerWidth or Height it's the correct one
    if(window.matchMedia(`(${dim}: ${window[prop]}px)`).matches) {
        return window[prop]
    }

    // here, since the value is wrong we use binarySearch to find its correct value
    const start = window[prop] - range >= 0 ? window[prop] - range : 0
    const end = window[prop] + range

    return binarySearch(dim)(start, end)

}


texts:
I have the following code to create a table for overall percentages and the past 30 day percentages.  I would like to add this to a Shiny app I'm making, but I feel there is a simpler or shorter way to create this code/table than what I have, which would work better in Shiny.  I'm not asking for the Shiny code, just a way to reduce the code I have.

a$FAIL<-ifelse(a$OPERATION_STATUS %in% "FAIL", 1, 0)
cc<-as.data.frame((table(a$CRIT_CODE))) #Dataframe with frequency of each crit code
cf<-aggregate(FAIL~CRIT_CODE,a,sum) #Total number of fails based on crit codes
cc<-cbind(cc[,],cf[,2])
names(cc)<-c("CRIT_CODE", "Freq", "FAIL") #Change column names
cc<-transform(cc, Percent=FAIL/Freq*100)

last30<-a[which(a$DATE>=(Sys.Date()-30)),]
last<-as.data.frame((table(last30$CRIT_CODE))) #Dataframe with frequency ofeach crit code
lastfails<-aggregate(FAIL~CRIT_CODE,last30,sum) #Total number of fails based on crit codes
last<-cbind(last[,],lastfails[,2])
names(last)<-c("CRIT_CODE", "Freq", "FAIL") #Change column names
last<-transform(last, Percent=FAIL/Freq*100)

rates<-merge(cc[,c(1,4)], last[,c(1,4)], by="CRIT_CODE")
rates$Percent.x<-round(rates$Percent.x, 2)
rates$Percent.y<-round(rates$Percent.y, 2)
library(gridExtra)
grid.table(rates, rows=NULL, cols=c("Area", "Overall Percent", "30 Day Percent"))

Sample Data

Data <- data.frame(
  DATE=sample(seq.Date(as.Date("2018-01-01"), as.Date("2018-06-15"), "days"), 15),
  OPERATION_STATUS=sample(c("PASS","FAIL"), 15, replace=TRUE),
  CRIT_CODE=sample(c("A", "B", "C"), 15, replace=TRUE)
)


texts: Angular/bootstrap radio button directive

texts:
I found creating radio buttons in my application a bit of a hassle in terms of having to configure the HTML to do what I wanted when the user clicks/unclicks the items etc.

I figured reducing it to a directive was the best way to simplify things.

The functionality I want is:

Be able to pass in a list of items that are displayed as radio button options
Be able to specify which item is checked by default
Can be displayed as a horizontal or vertical list
Have the option to make the buttons unselectable (i.e. clicking them again will uncheck the item)
The controller knows which value is checked.
The controller executes a function when the checked value changes
The controller can change which item is checked

Here is a working plunker.

Here is an example usage of the directive:

<dwj-radio-group
    dwj-items = "items"
    dwj-changefn = "changeFn"
    dwj-unselectable = "true"
    dwj-align = "vertical"
    dwj-boundvalue = "foo"
    >
</dwj-radio-group>

Here is the directive code:

var radioDirective = app.directive('dwjRadioGroup', function($compile, $templateCache ) {

    var getTemplate = function(item){
        var template = 'ERROR';
        console.log(item);
        switch (item){
        case 'horizontal':
            template = $templateCache.get("radio-group-horizontal.html");
            break;
        case 'vertical':
            template = $templateCache.get("radio-group-vertical.html");
            break;
        }

        return template;
    };

    return {
        scope : {
            items : '=dwjItems',
            changeFn : '=dwjChangefn',
            selectedItem: "=dwjBoundvalue",
            unselectable: "=dwjUnselectable",
            align:          "=dwjAlign"

        },

        link : function(scope, element, attrs) {

            scope.unselectable =scope.unselectable === 'true';                          //default false
            scope.align = scope.align === "vertical"? "vertical": "horizontal";         //default horizontal

            //http://onehungrymind.com/angularjs-dynamic-templates/
            var content = getTemplate(scope.align);
            console.log(content);
            element.html(content);
            $compile(element.contents())(scope);

            scope.changeItem = function(x){
                if (scope.unselectable && x === scope.selectedItem){
                    scope.selectedItem = null;
                }
                else{
                    scope.selectedItem = x;
                }

                scope.changeFn(scope.selectedItem);
            };
        }
    };
});

Currently, from what I can see, the directive does everything I want it to.

I'm looking for feedback on my use of the directive:

Are my naming conventions correct?
Am I using the directive scope binding correctly?
Is using $templateCache and $compile a good way to do this, or is there a much simpler way to do it?
Is there anything completely broken that I'm missing?


texts:
I have been writing PHP programs in the MVC pattern for quite some time. But I am not sure if I am doing it right.

For instance, I have this PHP file that prints results in XML, and I put this file in 'model':

header("Content-Type: text/xml");
echo '<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<response>
';

# Set object property/ variable.
$post = $connection->arrayToObject($_POST,$property_overloading = true);
//print_r($post);

# Assuming no error.
$error = false;

# Get the required field and put them in an array.
$array_required = is_array($post->required)? $post->required : explode(' ',$post->required);

# Get title
if (!$post->title)
{
    if(in_array('title', $array_required))
    {
        $error = true;
        echo '<error elementid="title" message="TITLE - Please entitle this album." />';
    }
}

# Get description
if ($post->description)
{
    if(in_array('description', $array_required))
    {
        $error = true;
        echo '<error elementid="description" message="DESCRIPTION - Please enter something." />';
    }
}
else
{
    # Ceck if there is a line break, if the match is found, replace it with an empty space.
    if (preg_match("/\n/", $post->description))
    {
        $post->description = preg_replace("/\n/is", " ", $post->description);
    }
}

# Get hide
if(!$post->hide) $post->hide = 0;
    else $post->hide = 1;

# Print general error message.
if ($error) echo '<errorgeneral message="Please amend the error above." />';

# check if no more errors
if (!$error)
{
    $sql = "
    UPDATE album
    SET
        title = ?,
        description = ?,
        hide = ?
    WHERE album_id = ?
    ";

    # use the instantiated db connection object from the initiator.php, to process the query.
    $result = $connection->executeSQL($sql,array(
        $post->title,
        $post->description,
        $post->hide,
        $post->album_id
    ));

    # Must convert all special characters to XML.
    # http://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references
    echo '<result message="Updated." itemid="'.$post->album_id.'" itemtitle="'.htmlspecialchars($post->title).'" itemdescription="'.htmlspecialchars($post->description).'" itemcategory="album"/>';
}

echo '</response>';

So, which part of it should be in the controller, and which should be in the model, helper, or view?


texts:
I need array to store elements, but I don't want to make memory allocations at runtime. So I reuse elements. Some fields are never changes so as I reuse elements I need to assign those fields just once.

This is what I wrote, only sceleton, need to add "errors test" etc, but enough to demonstrate the idea:

public sealed class ResizeableArray<T> where T : class, new()
{

    // made public to use in "foreach", but better to be private
    public T[] array;
    public int Count { get; private set; }

    public ResizeableArray(uint maxLength = 128)
    {
        if (maxLength <= 0) throw new ArgumentOutOfRangeException("maxLength");
        array = new T[maxLength];
        for (int i = 0; i < maxLength; i++)
        {
            array[i] = new T();
        }
        Count = 0;
    }

    public T this[int key]
    {
        get { return array[key]; }
    }

    public void Clear()
    {
        Count = 0;
    }

    public T Add()
    {
        return array[Count++];
    }

    public void RemoveRange(int index, int count)
    {
        var newSize = Count - count;
        for (int i = index; i < newSize; i++)
        {
            array[i] = array[i + count];
        }
        Count = newSize;
    }

    public void RemoveAt(int index)
    {
        throw new NotImplementedException();
    }

}

Usage is simple, for example

var element = array.Add();
// configure, assign only "mutable" fields
element.field1 = value1;
element.field2 = value2;

What do you think? Is it good class or you can suggest something better?

upd posting final version I use in production. I think this class can be usefull if you constantly need to reconfigure some array. It's probably will be faster no to allocate new object over and over (but need to measure). Also it's probably less error prone to have always the same instance of the object.

public sealed class ResizeableArray<T> where T : class, new()
{
    private T[] array;
    public int Count { get; private set; }

    public ResizeableArray(uint maxLength = 128)
    {
        if (maxLength <= 0) throw new ArgumentOutOfRangeException("maxLength");
        array = new T[maxLength];
        for (int i = 0; i < maxLength; i++)
        {
            array[i] = new T();
        }
        MaxLength = maxLength;
        Count = 0;
    }

    public uint MaxLength { get; private set; }

    public T this[int key]
    {
        get { return array[key]; }
    }

    public void Clear()
    {
        Count = 0;
    }

    public T Add()
    {
        return array[Count++];
    }

    // sloooow. don't use it
    public T InsertAt0()
    {
        var zeroOrder = array[Count];
        for (int i = Count; i > 0; i--)
        {
            array[i] = array[i - 1];
        }
        array[0] = zeroOrder;
        return zeroOrder;
    }

}


texts:
There have been multiple discussions on caching http-requests with RXJS. In this question/proposal I want to propose a custom rxjs-operator (non-pure) to provide caching:

const cacheHttp = (cacheKey: string, cacheStorage: any) => (source: Observable<any>) => {
  if (!cacheStorage[cacheKey]) {
    cacheStorage[cacheKey] = source.pipe(
      shareReplay(1)
    );
  }
  return cacheStorage[cacheKey];
};

This operator is not pure, as it modifies one of its arguments (cacheStorage).

This operator could be used like this:

public cachedItems = {};

public getDataForItem$(itemId: string) {
    return this.http.get('/item/' + itemId).pipe(
        cacheHttp(itemId, this.cachedItems),
        shareReplay(1)
    );
}

The client could then call this multiple times without causing superfluous http-requests:

// the following two subscriptions cause http-requests
this.itemService.getDataForItem('firstItem').subscribe((val) => console.log(val));
this.itemService.getDataForItem('secondItem').subscribe((val) => console.log(val));

// all further subscriptions would not cause any additional http-requests
this.itemService.getDataForItem('firstItem').subscribe((val) => console.log(val));
this.itemService.getDataForItem('secondItem').subscribe((val) => console.log(val));
this.itemService.getDataForItem('firstItem').subscribe((val) => console.log(val));
this.itemService.getDataForItem('secondItem').subscribe((val) => console.log(val));

// this subscription would again cause an http-request:
this.itemService.getDataForItem('thirdItem').subscribe((val) => console.log(val));

Is this an acceptable approach to solving the "cache-for-different-requests-problem"? Is there possibly a memory-leak or are there any leaked subscriptions? Is it ok to have side-effects on a provided argument?


texts: Work out if a string is "fieldname" or "tablename.fieldname", and assign variables

texts:
Is there a neater way to write this code?

    var table, field, dbFieldEntries;
    var s = 'one.two';
    // The DB field is always the first parameter
    dbFieldEntries = s.split( '.' );
    if( dbFieldEntries.length === 1 ){
      field = dbEntryEntries[ 0 ];
    } else {
      table = dbEntryEntries[ 0 ];
      field = dbEntryEntries[ 1 ];
    }

Basically, s can be either something or something.other.
If it's something, then table is undefined and field is something; it it's something.other, then table is something and field is other.


texts: Generating all unlabeled trees with up to n nodes

texts:
I want to visualize all unlabeled trees with \$n\$ or fewer nodes, not just count them.

First idea/attempt: Take a list of all \$n-1\$ node trees, then append a new leaf to every tree in every way to get a new list of \$n\$ node trees. Clearly, this new list will contain a lot of isomorphic duplicates. To fix this, we start adding the \$n\$ trees to a new list, and doing so only if they are not isomorphic to any of the trees in the new list. Since graph isomorphism problem is not known to be solvable in polynomial time, this makes the entire process even more horrible performance wise, because this process will do a lot of such checks.

My question is if this can be done more efficiently, or in a better way?

The python code implementing this idea/attempt using networkX and pyplot:

""" trees of order N or less will be generated """
N = 9

import networkx as nx

""" return copy of graph with newNode node appended to toNode node """
def leaf_copy(graph, newNode, toNode):
    g = nx.Graph.copy(graph)
    g.add_node(newNode)
    g.add_edge(newNode,toNode)
    return g

from networkx.algorithms import isomorphism

""" get all n+1 node cases out of all n node cases in prevTreeList """
def genNextTreeList(prevTreeList):
    """ one node case """
    if prevTreeList == None or prevTreeList == []:
        g = nx.Graph()
        g.add_node(1)
        return [g]

    """ new loads of n+1 graphs by all possible list appendations """
    """ this will include loads of isomprhic duplicates... """
    nextTreeList = []
    for g in prevTreeList:
        v = len(g.nodes())+1
        for node in g.nodes():
            nextTreeList.append(leaf_copy(g,v,node))

    """ remove isomorphic duplicates """
    """ it will check every graph to be added with all added graphs for isomorphism... """
    nextTreeListClean = []
    for g in nextTreeList:
        isomorphic = False
        for clean_g in nextTreeListClean:
            i = isomorphism.GraphMatcher(g,clean_g)
            if i.is_isomorphic():
                isomorphic = True
                break
        if not isomorphic:
            nextTreeListClean.append(g)
    return nextTreeListClean

import matplotlib.pyplot as plt

if __name__ == "__main__":

    print(0, "\t", 1)

    G = []
    figure = 0
    for n in range(N):
        G = genNextTreeList(G)

        """ print the number of examples to check if the code is working properly """
        print(n+1, "\t", len(G))

        """ draw and save the plots """
        for g in G:
            figure += 1
            fig = plt.figure(figure)
            plt.title(str(n+1)+'.'+str(G.index(g)+1))
            nx.draw(g, with_labels=False)
            plt.figure(figure).savefig('plot'+str(figure)+'.png',bbox_inches='tight',dpi=100)
            plt.close(fig)


texts: Network arithmetic, finding the next host for the given

texts:
Disclaimer: It's literally the second time I write in Haskell.

The purpose of this module is to provide some basic operations with IP addresses (and networks).

At the moment I only implemented the successor operation, that returns a next address in the range if it exists.

Eg: for 192.168.1.1 in 192.168.1.0/24 it would return Maybe 192.168.1.1

And for 192.168.1.255 (which is the last valid IP address in the given network) it would return Nothing.

module Main where

import Data.IP (IPv4, AddrRange(addr), fromIPv4, toIPv4, isMatchedTo, makeAddrRange)
import Data.Bits (shiftL, shiftR, (.|.), (.&.))
import Data.List (foldl')
import Text.Read (readMaybe)
import qualified Safe as S

parse :: String -> Maybe IPv4
parse = readMaybe

toInt :: IPv4 -> Int
toInt i = foldl' accum 0 (fromIPv4 i)
    where accum a v = (a `shiftL` 8) .|. v

fromInt :: Int -> IPv4
fromInt i = toIPv4 $ map (\s -> (i `shiftR` s) .&. 0xff) [24, 16, 8, 0]

addressesInNetwork :: AddrRange IPv4 -> [IPv4]
addressesInNetwork i = takeWhile (`isMatchedTo` i) adds
    where net = toInt $ addr i
          adds = map (\s -> fromInt $ net + s) [0..]

successor :: Int -> IPv4 -> Maybe IPv4
successor r a = S.headMay $ dropWhile (<= a) $ addressesInNetwork $ makeAddrRange a r

net24 :: IPv4 -> Maybe IPv4
net24 = successor 24

main::IO()
main = print $ parse "192.168.1.201" >>= net24

What I don't like: it just looks terrible. I look on it and see Perl, not Haskell.

Have I done something idiomatically wrong or my sense of beauty is broken?


texts:
I wrote a simple script to retrieve the logs from my website, and place them in a subdirectory called logs. It fetches the logs using sftp. I would like help with the error handling. I'm sure that there are errors I did not see, and I would like to make it so that it fails gracefully.

#!/bin/bash
# gets the logs

# Location to place downloaded logs
PlaceLogs=./logs
# ssh connection to sftp files from
SSHLocation=hjsblog
# Location and pattern of logs
GetLogs=../logs/access*

#######################################
#######################################

CWD=$(pwd)

# move to get location
if [ "$(ls -A $PlaceLogs)" ]
then
    echo $PlaceLogs is not empty
    return
fi
mkdir -p $PlaceLogs
cd $PlaceLogs

# perform the get operation
sftp $SSHLocation << EOF
cd $(dirname $GetLogs)
get $(basename $GetLogs)
EOF

# uncompress files
bunzip2 *.bz2

# return to script dir
cd $CWD


texts:
I have the following code that given an array, returns the reversed version of the array, reverse portions of the array.

For example

selReverse([1,2,3,4,5,6], 2)
//=> [2,1, 4,3, 6,5]

function selReverse(array, length) {
  console.log(array)
  var resultArray = [];
    for (var i = 0, j=array.length ; i < j; i += length) {
      resultArray.push.apply(resultArray, array.slice(i, i+length).reverse());
    }
  return resultArray;
}

This code passes the tests, but apparently, it's too slow. Is there a way to optimize it?