texts: Simplify Raphael JS code: display text in DIV on click event

texts:
I've been working with the RaphaelJS 'australia map' example that displays text in a DIV when a state is clicked on. However I'm having difficulty working with it to create different events and functions.

I want to be able to duplicate the 'display text' function for two different element onClick events (i.e. have two different buttons (elements) that do the same thing). But the current code is a bit too complicated for me. Can somebody please help me simplify the code that displays the text in a DIV when an element is clicked on.

Any help would be much appreciated - this is what I'm currently working with jsfiddle.

 window.onload = function () {
    var R = Raphael("paper", 532, 500);
    var attr = {
        fill: "#0B0",
        stroke: "#fff",
        "stroke-width": 3,
    };
    var ctx = {};
    ctx.btn_1 = R.path("M 180,130 L 340,130, L 392,212, L 128,212 z").attr(attr);
    ctx.btn_2 = R.path("M 128,212 L 392,212, L 435,280, L 85,280 z").attr(attr);

    var current = null;
    for (var state in ctx) {
        (function (st, state) {
            st[0].style.cursor = "pointer";
            st[0].onmousedown = function () {
                current && (document.getElementById(current).style.display = "");
                st.toFront();
                R.safari();
                document.getElementById(state).style.display = "block";
                current = state;
            };
        })(ctx[state], state);
    }
 };


texts:
I'm trying to build a JavaScript library that does basic financial calculations, such as NPV, IRR, PV, FV, etc. So far I've added the NPV functionality only, and it's passed my test cases. But I want to know if the code overall can be written better.

(function () {
    /*
This library depends on underscore.js
*/
    'use strict';
    var root = this, previousFin = root.Fin, Fin = root.Fin = {}, _ = root._;

    Fin.VERSION = '0.0.1';
    Fin.PRECISION = 4; // floating point precision

    /*
Runs Fin.js in noConflict mode and
returns reference to this Fin object
*/
    Fin.noConflict = function () {
        root.Fin = previousFin;
        return this;
    };

    /*
NPV - Net Present Value
rate = the periodic discount rate
example: If the discount rate is 10% enter 0.1, not 10.
payments = an array or object (keys are the year numbers) of payments
example: [-100, 50, 60] means an initial cash outflow of 100 at time 0,
then cash inflows of 50 at the end of the period one, and 60 at
the end of the period two.
If you pass {0: -100, 2:50}, then the payment at the end of the
year one is assumed to be 0.
*/
    Fin.npv = function (rate, payments, precision) {
        if (isNaN(rate)) {
            /* rate needs to be a number */
            return null;
        }
        if (_.isArray(payments)) {
            /* all elements of the array need to be numbers */
            if (!_.all(payments, function (elem) { return !isNaN(elem); })) {
                return null;
            }
        } else if (_.isObject(payments)) {
            /* all key, value pairs of the object need to be numbers */
            if (!_.all(payments, function (key, value) { return !isNaN(key) && !isNaN(value); })) {
                return null;
            }
        } else {
            /* payment needs to be either an array or an object */
            return null;
        }
        if (typeof (precision) === 'undefined' || isNaN(precision)) {
            precision = this.PRECISION;
        }
        var i, npv = 0;
        for (i in payments) {
            if (payments.hasOwnProperty(i)) {
                npv += payments[i] / Math.pow((1 + rate), i);
            }
        }
        return npv.toFixed(precision);
    };
}).call(this);


texts:
I solved this problem from LeetCode:

  Given a pattern and a string str, find if str follows the same
  pattern.

  Here follow means a full match, such that there is a bijection between
  a letter in pattern and a non-empty word in str

  Examples:

  pattern = "abba", str = "dog cat cat dog" should return true.

  pattern = "abba", str = "dog cat cat fish" should return false.

  pattern = "aaaa", str = "dog cat cat dog" should return false.

  pattern = "abba", str = "dog dog dog dog" should return false.

  Notes:

  You may assume pattern contains only lowercase letters, and str
  contains lowercase letters separated by a single space.

I was able to solve this problem by using a Dictionary to keep track of the relation between the pattern and the str:

public class Solution {
public bool WordPattern(string pattern, string str)
    {
        var result = str.Split(' ').ToList();
        var mapPattern = new Dictionary<char, string>();
        if (result.Count != pattern.Count())
        {
            return false;
        }
        string matchstr;
        int index = 0;
        foreach (var c in pattern)
        {
            if (mapPattern.TryGetValue(pattern[index], out matchstr))
            {
                if (matchstr != result[index])
                {
                    return false;
                }
            }
            else
            {
                if(mapPattern.ContainsValue(result[index]))
                {
                    return false;
                }
                mapPattern.Add(c, result[index]);
            }
            ++index;
        }
        return true;
    }
}

The approach I have currently looks up the Dictionary twice to see if it already exists as a key or as a value in the Dictionary, which I believe would be the reason for slowing this by a significant amount.

Can you determine if I can do away with looking up twice? This solution only runs better than around 36% of the other submissions for this current problem. So, I believe there must be a better and faster way.


texts: Deployment Automatization for docker builds, kubernetes deploys and secret injection

texts:
I've written a small script that automates the tasks I previously did manually for deploying onto our kubernetes clusters and I am quite happy with the results I have, but I do think that what my approach was (building a command and executing it at the end) could probably be improved.

Especially the fn_magic part is something I dont know could be done better.

team="webdev"
project="sick-project"
registry="myfancyregistry"
tagPrefix="$registry/$team/$project"
namespace="webdev-dev"
kubectl="kubectl -n=$namespace"

declare -A NAME_TO_TAGS
declare COMMANDBUILDER
declare -A REPLACEMENTS

# Colors :)
RED='\033[0;31m'
GREEN='\033[0;32m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

function setReplacements() {
  while IFS= read -r line
  do
    [ -z "$line" ] && continue
    key=${line%%=*}
    value=${line#*=}
    REPLACEMENTS[$key]=$value
  done < "${BASH_SOURCE%/*}/secrets"
}

function buildAndPush() {
  function fn_magic() {
    local dockerfile=$1
    local name=$2
    local context=$3
    local tag=$(tar cf - --exclude='node_modules' $context | sha1sum | grep -o "\w*")
    NAME_TO_TAGS["$name"]="$tag"
    local output=$(docker images $tagPrefix/$project-$name:$tag | awk '{print $2}' | sed 1,1d)
    printf "SHA1 for ${CYAN}$name${NC} is ${YELLOW}$tag${NC}.\n"
    if [[ "$output" ]]; then
      printf "Skipping building ${CYAN}$name${NC} because image already exists locally.\n"
      COMMANDBUILDER="$COMMANDBUILDER && printf \"Pushing ${CYAN}$name${NC}.\n\" && docker push $tagPrefix/$project-$name:$tag"
      return
    fi
    COMMANDBUILDER="$COMMANDBUILDER && printf \"Building ${CYAN}$name${NC}.\n\" && docker build -f dockerfiles/$dockerfile.dockerfile -t $tagPrefix/$project-$name:$tag $context"
    COMMANDBUILDER="$COMMANDBUILDER && printf \"Pushing ${CYAN}$name${NC}.\n\" && docker push $tagPrefix/$project-$name:$tag"
    return
  }
  local calls=(
    "fn_magic ReactNginx frontend ./frontend"
    "fn_magic DockerfileNode backend ./backend"
  )

  for call in "${calls[@]}"; do
    eval $call
  done
}

function deploy() {
  local deployName="$1"
  local tag="$2"

  local filter=""
  REPLACEMENTS[TAG]="$tag"
  for key in "${!REPLACEMENTS[@]}"; do
    local REPLACE=$(echo ${REPLACEMENTS[$key]} | sed -e 's/\\/\\\\/g; s/\//\\\//g; s/&/\\\&/g')
    filter="$filter | sed \"s/{{$key}}/$REPLACE/g\""
  done

  COMMANDBUILDER="$COMMANDBUILDER && cat "${BASH_SOURCE%/*}/$deployName.yaml" $filter | $kubectl apply -f -"
}

setReplacements
buildAndPush
for name in "${!NAME_TO_TAGS[@]}"; do
  deploy $name ${NAME_TO_TAGS[$name]}
done
COMMANDBUILDER="echo $COMMANDBUILDER"
eval "$COMMANDBUILDER"


texts: Wrapping postback functions to call custom code at execution

texts:
Here is my solution for this stackoverflow question.

It is designed to return an onbeforeunload message when the user leaves the page (excluding postbacks). It does this by logging a timestamp each time a .NET control causes a postback (either full or partial using update panels). When this happens, if allowedWaitTime has elapsed, amessage will be returned.

Are there any best or better practices missing from this code and does anyone have an opinion on my style (albeit a small sample)?

(function ($) {

    if (typeof $ !== 'function') {
        throw new Error('jQuery required');
    }

    /* The time in milliseconds to allow between a function call and
       showing the onbeforeunload message. */
    var allowedWaitTime = 100,

        timeStamp = new Date().getTime(),

        // Each function to override
        baseFuncs = {
            __doPostBack: this.__doPostBack,
            WebForm_DoPostBackWithOptions: this.WebForm_DoPostBackWithOptions
        };

    // Set timeStamp when each baseFunc is called
    for (var baseFunc in baseFuncs) {
        (function (func) {
            this[func] = function () {
                var baseFunc = baseFuncs[func];
                timeStamp = new Date().getTime();
                if (typeof baseFunc === 'function') {
                    baseFunc.apply(arguments.callee, arguments);
                }
            }
        })(baseFunc);
    }

    /* Form submit buttons don't call __doPostBack so we'll set timeStamp
       manually on click. */
    $('input[type="submit"]').click(function () {
        timeStamp = new Date().getTime();
    });

    $(this).on('beforeunload', function (e) {

        // Only return string if allowedWaitTime has elapsed
        if (e.timeStamp - timeStamp > allowedWaitTime) {
            return 'message';
        }
    });
}).call(window, jQuery);


texts: Data marshaling wrapper for a TCP server

texts:
After a lot of research, I created this wrapper which I think fits very well to my needs. My project is a TCP server and I will be using this wrapper every time the server receives a packet. Basically, the wrapper will work marshaling raw byte[] into higher-level representation of the data as marshalable structs.

What do you think about this wrapper? Any hint on how I can improve it? I'm very concerned about performance.

public static class MyMarshal
{
    /// <summary>
    /// Marshals a raw buffer to a given marshalable struct.
    /// </summary>
    public static unsafe T GetStructure<T>(byte[] buffer) where T : struct
    {
        fixed (byte* bufferPin = buffer)
        {
            return (T)Marshal.PtrToStructure(new IntPtr(bufferPin), typeof(T));
        }
    }

    /// <summary>
    /// Marshals a given T instance into a raw buffer.
    /// </summary>
    public static unsafe byte[] GetBytes<T>(T obj) where T : struct
    {
        byte[] rawBuffer = new byte[Marshal.SizeOf(obj)];

        fixed (byte* rawBufferPin = rawBuffer)
        {
            Marshal.StructureToPtr<T>(obj, new IntPtr(rawBufferPin), false);
        }

        return rawBuffer;
    }

    /// <summary>
    /// Crates a zero-initialized marshaled instance of T
    /// </summary>
    public static unsafe T CreateEmpty<T>() where T : struct
    {
        int typeSize = Marshal.SizeOf(typeof(T));

        byte* rawBuffer = stackalloc byte[typeSize];

        for (int i = 0; i < typeSize; i++)
            rawBuffer[i] = 0;

        T zeroInited = (T)Marshal.PtrToStructure(new IntPtr(rawBuffer), typeof(T));

        return zeroInited;
    }
}

Summing up, the wrapper have 3 methods:

GetStructure (used right after I receive any valid packet to get the respective structure)
GetBytes (used when I want to send a packet to a client, converts a given struct value to a raw buffer to be send to the client)
CreateEmpty (used to create a zero-initialized instance of a given struct. This method is used when I have complex structures with non-blittable arrays, etc. The goal of this method is to have a generic zero-initializer method even to non-blittable structs - those with non-blittable arrays and/or strings).

I want to raise another questions too:

What do you think about this mixed use of unsafe code and the Marshal class? Is there any problem on using that way?
In the method MyMarshal.CreateEmpty, what do you think about the stackalloc usage? Some structures that will be initialized with this method will be a little big (usually something between 100 and 1024 bytes). Is there any downside or danger of allocating this length in the stack several times per seconds? I'm expecting to process something around 5k packet per second.

Also, he TCP server will work asynchronously using the async/await pattern, so I don't expect to deal with shared stated and other common problems to a multi-threaded application.


texts: Method or helper function to return objects from EntityFramework with Linq

texts:
The following code reads from Microsoft EntityFramework 6.0 domain model and returns the single view_patient object. The view_patient object is defined in the backend database and uploaded to the .edmx model of EF.

I am new to EF, but it seems there should be a better way--(better means less typing)-- of going from model to object without the intermediary anonymous data transfer object. As I have a couple hundred of these procedures to write (all within a WCF service), is there a better way of doing this? Or perhaps a "generic" method that will allow going directly from Link-to-entity to output of objects?

A note towards naming convention:
The classes are coming directly from Npgsql 3.0.5 EntityFramework interface -- which in turn is being read directly from PostgreSQL 9.5 database. I can not seem to get either EF or Npgsql to return PascalCase from the PostgreSQL database which is case-insensitive and, without adding quotes to all names, returns only lowercase names for tables, stored procedures, and columns.

Note #2: When not going through the intermediate DTO, I get the following error:

  The entity or complex type 'chaosModel.view_patient' cannot be
  constructed in a LINQ to Entities query.

(Using .NET 4.5)

  // testing the setup
    public view_patient Test(string cpatient)
    {
        using (var ctx = new chaosEntities())
        {

            var q = (from patient in ctx.patients
                     join chart in ctx.charts on patient.chart_recid equals chart.recid
                     where patient.cpatient == cpatient
                     select new
                     {
                         birthdate = patient.birthdate,
                         chart_number = chart.chart_number,
                         chart_recid = chart.recid,
                         city = patient.city,
                         cpatient = patient.cpatient,
                         donotsee = chart.donotsee,
                         firstname = patient.firstname,
                         groupid = chart.groupid,
                         lastname = patient.lastname,
                         mailbox = patient.mailbox,
                         mi = patient.mi,
                         patient_recid = patient.recid,
                         phone = patient.phone,
                         selfpay = chart.selfpay,
                         cashonly = chart.cashonly,
                         sex = patient.sex,
                         ssn = patient.ssn,
                         state = patient.state,
                         street = patient.street,
                         zipcode = patient.zipcode
                     });

            var r = (from c in q.AsEnumerable()
                     select new view_patient
                     {
                         birthdate = c.birthdate.ToShortDateString(),
                         chart_number = c.chart_number,
                         chart_recid = c.chart_recid,
                         city = c.city,
                         cpatient = c.cpatient,
                         donotsee = c.donotsee,
                         firstname = c.firstname,
                         groupid = c.groupid,
                         lastname = c.lastname,
                         mailbox = c.mailbox,
                         mi = c.mi,
                         patient_recid = c.patient_recid,
                         phone = c.phone,
                         selfpay = c.selfpay,
                         cashonly = c.cashonly,
                         sex = c.sex,
                         ssn = c.ssn,
                         state = c.state,
                         street = c.street,
                         zipcode = c.zipcode
                     }).SingleOrDefault();

            return r;
        }
    }


texts: Simplifying these methods for iterating through object and modifying string fields

texts:
I have this method (consisting of three methods) that I need to use for looking through objects that are going to be serializes and logged as json objects.
a bit of intro (not necessary to read)
The initial problem was that I noticed that sometimes I would receive data in objects from external api's that would contain personal sensitive data i.e social security numbers. I would still like to log these objets though, I just want to sanitize the social sec numbers away, and I also would like to have some method that could this for object with any kind of internal structure, such that I could reuse it, and would'nt need to rewrite a new sanitization method for each log.
The problem
So now I wanted these methods that could look into objects of any type, and sanitize all the string fields, such that the strings would look the same, but for any string field with a social security number of the type 123456-7891, should be replaced with XXXXXX-XXXX.
public static void DoitNow(object obj)
{
    Queue<PropertyInfo> properties = new Queue<PropertyInfo>(obj.GetType().GetProperties());
    while (properties.Count != 0)
    {
        PropertyInfo property = properties.Dequeue();

        if (property.GetValue(obj) is string)
        {
            string stringField = property.GetValue(obj).ToString();

            String sanitizedField = sanitizeSensitiveString(stringField);
            property.SetValue(obj, sanitizedField);

        }
        else if (property.GetValue(obj) is IList)
        {
            IList y = (IList)property.GetValue(obj);

            if (y.Count != 0)
            {
                if (y[0] is string)
                {
                    for (int i = 0; i < y.Count; i++)
                        y[i] = sanitizeSensitiveString((string)y[i]);
                }
                else if (IsNested(y[0]))
                {
                    for (int i = 0; i < y.Count; i++)
                    {
                        DoitNow(y[i]);
                    }
                }
            }
        }
        else if (IsNested(property.GetValue(obj)))
        {
            var l = property.GetValue(obj);

            DoitNow(l);
        }
    }
}

public static string sanitizeSensitiveString(string sensitiveString)
{
    return Regex.Replace(sensitiveString, @"\d{6}-?\d{4}[0-9]*", " XXXXXX-XXXX ");
}

public static bool IsNested(object value)
{
    Type t = value.GetType();
    if (t.IsPrimitive || value is string)
    {
        return false;
    }
    FieldInfo[] fields = t.GetFields(BindingFlags.NonPublic |
                                     BindingFlags.Public |
                                     BindingFlags.Instance);
    if (fields.Any())
    {
        return true;
    }
    return false;
}

Now, the method DoitNow is the core method here, it takes any object as a parameter, and uses projection to look through all the properties of it. If a field is a string field, we use the method sanitizeSensitiveString to sanitize the string. If a property is itself a object (I use the method isNested to determine this) I will call the method recursively on it. If a property is a List type, I look into the list and sanitize if it contains strings, and recurse if it contains complex objects.
I would like to get some tips on my IsNested method, am I using projection right? In general am I using projection In a way that makes sense to access the fields and modify them?
Also, In order to be able to operate with many list types, I use the IList interface, however this has led me to using for-loops in a way that I find very un-elegant, can I replace some of my loops with some functional type function calls? I also use if (list.count != 0) to test if a list is empty, I just find this plain stupid.
Any other optimizations are welcomed!


texts:
int number;
DateTime dateTime;

using (var oracleConnection = new OracleConnection(ConnectionString))
using (var oracleCommand = oracleConnection.CreateCommand())
{
    oracleConnection.Open();

    oracleCommand.CommandText = "SELECT * FROM FROM MY_TABLE";

    using (var reader = oracleCommand.ExecuteReader())
    {
       while (reader.Read())
       {
          number = reader.GetInt32(0);
          dateTime = reader.GetDateTime(1);
       }
    }
}

Which is a better way to avoid the calls such as reader.GetInt32(0)?

This way is too hard to read.  A better way would be something like reader.GetInt32("ID") or reader.GetDateTime("Begin"), where ID and Begin are column names.

Or should I use enums?


texts:
I'm creating a robust bubble sort for VBA when sorting stored arrays in VBA. Mostly this would be used when an array is stored in a single cell with a delimiter. Otherwise, one could just sort on the sheet during intake.

I'm trying to make this as robust as I can so it can be used as a tool rather than just continually rewriting it for each task when I need it. It can sort ascending or descending, the intention being that one may be able to use it to get minimums, maximums and medians.

I'd like to make it able to sort alphabetically, but right now it only sorts numbers. I mention this because I'd like to refactor the procedure that turns the variant array (hence the area with extra white space) into the double array, but I can't figure out an optimal way to do that without sending copies of arrays around, so it's just sitting in the TestBubbleSorting procedure right now. Any suggestions on that refactoring would be awesome.

Also, if the bubble sort method isn't the most robust sort algorithm to be using, I'd love to know that so I can try again.

Example input would be something like this

3
7,3,5
15,20,40
300,550,137

Option Explicit
Public Sub TestBubbleSorting()
    Const DELIMITER As String = ","
    Dim targetSheet As Worksheet
    Set targetSheet = ActiveSheet
    Dim numberOfArrays As Long
    numberOfArrays = targetSheet.Cells(1, 1)
    Dim rawArray As Variant
    Dim arrayToSort() As Double
    Dim targetRow As Long
    Dim targetElement As Long
    Dim numberOfElements As Long
    Dim inputValue As String
    Dim outputValue As String

    For targetRow = 2 To numberOfArrays + 1
        inputValue = targetSheet.Cells(targetRow, 1)
        If Replace(inputValue, DELIMITER, vbNullString) = vbNullString Then GoTo NextIteration

        rawArray = GetArrayFromCell(inputValue, DELIMITER)

        numberOfElements = UBound(rawArray) + 1
        ReDim arrayToSort(1 To numberOfElements)
        For targetElement = 0 To numberOfElements - 1
            arrayToSort(targetElement + 1) = CDbl(rawArray(targetElement))
        Next

        BubbleSortNumbers arrayToSort(), True

        For targetElement = 1 To numberOfElements - 1
            outputValue = outputValue & arrayToSort(targetElement) & DELIMITER
        Next
        outputValue = outputValue & arrayToSort(numberOfElements)
        targetSheet.Cells(targetRow, 2) = outputValue
        outputValue = vbNullString
NextIteration:
    Next
End Sub

Private Function GetArrayFromCell(ByVal inputValue As String, ByVal DELIMITER As String) As Variant
    GetArrayFromCell = Split(inputValue, DELIMITER)
End Function

Private Sub BubbleSortNumbers(ByRef arrayToSort() As Double, Optional ByVal sortAscending As Boolean = True)
    Dim temporaryHigher As Double
    Dim temporaryLower As Double
    Dim targetElement As Long
    Dim exchangeMade As Boolean
    If sortAscending Then
        Do
            exchangeMade = False
            For targetElement = 1 To UBound(arrayToSort) - 1
                If arrayToSort(targetElement) > arrayToSort(targetElement + 1) Then
                    exchangeMade = True
                    temporaryHigher = arrayToSort(targetElement)
                    arrayToSort(targetElement) = arrayToSort(targetElement + 1)
                    arrayToSort(targetElement + 1) = temporaryHigher
                End If
            Next targetElement
        Loop While exchangeMade
    Else
         Do
            exchangeMade = False
            For targetElement = UBound(arrayToSort) To 2 Step -1
                If arrayToSort(targetElement) > arrayToSort(targetElement - 1) Then
                    exchangeMade = True
                    temporaryLower = arrayToSort(targetElement)
                    arrayToSort(targetElement) = arrayToSort(targetElement - 1)
                    arrayToSort(targetElement - 1) = temporaryLower
                End If
            Next targetElement
        Loop While exchangeMade
    End If
End Sub


texts:
As in many teams, me and my coworkers are putting ticket number into beginning of each commit message. If your branches are starting with ticket number it is easy to create prepare-commit-msg hook to automate this action, and since I'm a front-end deveoper, I decided to write it as a nodejs script. Look at what I came up with and tell me how to make it better if you will.

#.git/hooks/prepare-commit-msg

#!/usr/bin/env node

const fs = require('fs')
const { exec } = require('child_process')

const COMMIT_EDITMSG = process.argv[2]

exec('git symbolic-ref --short HEAD', (err, stdout) => {
    if (err) throw err

    fs.readFile(
        COMMIT_EDITMSG,
        'utf8',
        (err, message) => {
            if (err) throw err

            fs.writeFile(
                COMMIT_EDITMSG,
                `${stdout.replace(/(-|_).*/, '')} ${message}`.replace(/\n/, ''),
                err => {
                    if (err) throw err
                }
            )
        }
    )
})


texts: Next lexicographic permutation of a list

texts:
I began learning Haskell last week.  I wrote the following to get the next lexicographic permutation of a list.  It works perfectly but I feel like I'm just writing a c# method.  My long list of where commands just feels like an imperative approach.  I would appreciate any feedback if this solution is indeed the way most people would write something like this in haskell:

-- Finds the end of a list that is monotonically decreasing (swap)
-- Pivot is the index just before it. (pivot)
-- exchanges the smallest value > pivot in swap with pivot
-- reverses the swap with the pivot in it, and concatenates the new permutation
nextPerm :: (Ord a,Num a) => [a] -> [a]
nextPerm [] = []
nextPerm a = if pivotIndex == (-1) then a
             else prePivot ++ [swapVal] ++ swapWithPivot
             where
                 swap = foldl (\acc x -> if x<=(last acc) then acc ++ [x] else [x]) [(-1)] a
                 pivotIndex = (length a) - (length swap) - 1
                 prePivot = take pivotIndex a
                 pivotVal = a !! pivotIndex
                 swapVal = foldl1 (\acc x -> if x > pivotVal then x else acc) swap
                 swapWithPivot = insert pivotVal $ delete swapVal $ reverse swap


texts:
def as_size( s )
  prefix = %W(TiB GiB MiB KiB B)
  s = s.to_f
  i = prefix.length - 1
  while s > 512 && i > 0
    s /= 1024
    i -= 1
  end
  ("%#{s > 9 ? 'd' : '.1f'} #{prefix[i]}" % s).gsub /\.0/, ''
end

I'd like a clean and fast code to convert raw file size to human-readable format. Any hints?

Update (faster format):

def as_size( s )
  prefix = %W(TiB GiB MiB KiB B)
  s = s.to_f
  i = prefix.length - 1
  while s > 512 && i > 0
    s /= 1024
    i -= 1
  end
  ((s > 9 || s.modulo(1) < 0.1 ? '%d' : '%.1f') % s) + ' ' + prefix[i]
end

Update (freeze the constant):

PREFIX = %W(TiB GiB MiB KiB B).freeze

def as_size( s )
  s = s.to_f
  i = PREFIX.length - 1
  while s > 512 && i > 0
    i -= 1
    s /= 1024
  end
  ((s > 9 || s.modulo(1) < 0.1 ? '%d' : '%.1f') % s) + ' ' + PREFIX[i]
end


texts: File presence check for an automated workflow

texts:
I am working on a script for an automated workflow. It expects a CSV and a disk image to be present in the directory that is supplied as args.input.

I want to check for and handle every possible scenario: no CSV, no disk image, too many CSVs, too many disk images, and any possible combination thereto.

I've written the below, which works, and seems to be human readable, but it just seems incredibly excessive and verbose – is there any way I can make this more compact, yet still retain its legibility?

# CONFORMANCE CHECKS
def check_conformance():
    csv = glob.glob(args.input+'*.csv')
    disk_image = glob.glob(args.input+'*.E01')

    if len(csv) == 1:
        does_csv_exist = os.path.isfile(csv[0])
    elif len(csv) < 1:
        does_csv_exist = False
    elif len(csv) > 1:
        does_csv_exist = "too many CSVs!"
    if len(disk_image) == 1:
        does_E01_exist = os.path.isfile(disk_image[0])
    elif len(disk_image) < 1:
        does_E01_exist = False
    elif len(disk_image) > 1:
        does_E01_exist = "too many Disk Images!"
    if len(disk_image) > 1 and len(csv) > 1:
        does_csv_exist = "too many CSVs!"
        does_E01_exist = "too many disk images!"
        return (False, does_csv_exist, does_E01_exist,)
    if does_E01_exist is True and does_csv_exist is True:
        return True
    elif does_E01_exist is True and does_csv_exist is False:
        return (False, "CSV is missing")
    elif does_E01_exist is False and does_csv_exist is True:
        return (False, "E01 disk image is missing")
    elif does_E01_exist is False and does_csv_exist is False:
        return (False, "E01 disk image AND csv are missing")
    elif does_csv_exist is not True and does_csv_exist is not False:
        return (False, does_csv_exist)
    elif does_E01_exist is not True and does_E01_exist is not False:
        return (False, does_E01_exist)


texts: Does this code actually give a valid representation of how quick a system is?

texts:
So I wrote this code a while ago as a way of seeing how many times it could compute a simple sum in a second (one tick). I was wondering if this gives me valid results or is in fact giving me bogus ones.

from datetime import datetime
from datetime import timedelta

start_time = datetime.now()

def millis():
   dt = datetime.now() - start_time
   ms = (dt.days * 24 * 60 * 60 + dt.seconds) * 1000 + dt.microseconds / 1000.0
   return ms
def tickscheck(start):
    x = 0
    count = 0
    while millis() - start < 1000:
        x = 4+5
        #counting up
        count = count + 1

    print("It Took " + str(count) + " Counts\nOver " + str(millis()- start) + "ticks")

running = True
while(running == True):
    tickscheck(millis())
    restart = input("Do You Want Restart?")
    restart = restart.lower()
    if restart in ("yes", "y", "ok", "sure", ""):
        print("Restarting")
    else:
        print("closing Down")
        running = False


texts:
I'm a bit confused if saving the information to session code below, belongs in the controller action as shown below or should it be part of my Model?

I would add that I have other controller methods that will read this session value later.

public ActionResult AddFriend(FriendsContext viewModel)
{
    if (!ModelState.IsValid)
    {
        return View(viewModel);
    }

    // Start - Confused if the code block below belongs in Controller?

    Friend friend = new Friend();
    friend.FirstName = viewModel.FirstName;
    friend.LastName = viewModel.LastName;
    friend.Email = viewModel.UserEmail;

    httpContext.Session["latest-friend"] = friend;

    // End Confusion

    return RedirectToAction("Home");
}

I thought about adding a static utility class in my Model which does something like below, but it just seems stupid to add 2 lines of code in another file.

public static void SaveLatestFriend(Friend friend, HttpContextBase httpContext)
{
    httpContext.Session["latest-friend"] = friend;
}

public static Friend GetLatestFriend(HttpContextBase httpContext)
{
    return httpContext.Session["latest-friend"] as Friend;
}


texts: Improving Speed of VBA Code - Copy/paste two sets of variable, Excel does a calculation, returns a value then copy/paste the output value

texts:
I am attaching the code here. I am very new to VBA and trying to do a complex calculation using Macro. Please help me improve the speed of the attached code. The code works fine and produces the end output. The program is intended to do the following. I am calling the below two subs after data is filled in the sheet.
Copy and paste two sets of variable in two specified cell
Excel does a complex calculation using FILTER command & other INDEX and MATCH Formulas
Copy and paste the output to a location
This is required to done 1500 times for two sets of data. Present execution time is 10 minutes.
Sub CF_Amb_Pr_NG()
Dim intX As Integer
Dim copyRng As String
X = 43
For X = 40 To 1539
    Sheets("CC_NG_APr").Select
    Range("C2").Select
    Application.CutCopyMode = False
    ActiveCell.FormulaR1C1 = "=R" & X & "C2"
    Range("C3").Select
    Application.CutCopyMode = False
    ActiveCell.FormulaR1C1 = "=R" & X & "C3"
    Range("E2").Select
    Selection.Copy
    Let copyRng = "D" & X
    Range(copyRng).Select
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
Next X
End Sub

Sub CF_RH_NG()
Dim intX As Integer
Dim copyRng As String
X = 33
For X = 32 To 1531
    Sheets("CC_NG_RH").Select
    Range("C2").Select
    Application.CutCopyMode = False
    ActiveCell.FormulaR1C1 = "=R" & X & "C2"
    Range("C3").Select
    Application.CutCopyMode = False
    ActiveCell.FormulaR1C1 = "=R" & X & "C3"
    Range("E2").Select
    Selection.Copy
    Let copyRng = "D" & X
    Range(copyRng).Select
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
Next X
End Sub

Attached screenshot of sheet in formula mode to explain what exactly is going on in E2 based on the values fed in C2 & C3. Basis the value entered in C2 & C3, formula to be chosen to calculate E2 is chosen and final value is shown. I need to get value in E2 for 3000 sets of data in C2 & C3
Thanks a lot for helping !


texts: Toggling only a single class as active in a list with vanilla JS or CSS

texts:
Every time I toggle active class in a list (to dynamically change DOM content) I find that I always go to this approach to check and clear which class is active. I'm still fairly new to using pure javascript so I'm wondering if there is a better, simpler approach?

It feels like having to run a second function to clear out all active classes seems grunty.

I've included an example of how I do it.

var specialNav = document.getElementById("special-nav");

if (specialNav) {
  var navItems = specialNav.getElementsByTagName('li');
  var i;
  for (i = 0; i < navItems.length; i++) {
    navItems[i].addEventListener("click", function() {
      if (!this.classList.contains('active')) {
        clearActives(navItems);
        this.classList.toggle('active');
      }
    });
  }
}

function clearActives(classlist) {
  if (classlist) {
    for (i = 0; i < classlist.length; i++) {
      classlist[i].classList.remove('active');
    }
  }
}
.active {
  color: red
}

li {
  cursor: pointer;
}

 1

2

3

4


texts:
Elsewhere, there was a question about finding an elegant solution to a particular problem, and the following solution was presented.

I'm curious whether this solution is elegant from the perspective of easy to understand for a Ruby programmer (which I am no longer).

merged_file = File.open("merge_out.txt", "w")

files = ARGV.map { |filename| File.open( filename, "r") }

lines = files.map { |file| file.gets }

while lines.any?
    next_line = lines.compact.min
    file_id = lines.index( next_line )
    merged_file.print next_line
    lines[ file_id ] = files[ file_id ].gets
end

The question is not whether it is efficient, but just "how long does it take a Ruby programmer to understand what this does?"


texts:
I try to write a function which calculates the check digit for shipping label based on the algorithm provided by GS1
http://www.gs1.org/how-calculate-check-digit-manually

Version 1: my first try

public static int GetGTINCheckDigitV1(string code)
{
    int sum = 0;
    for (int i = 0; i < code.Length; i++)
    {
        int n = int.Parse(code.Substring(code.Length - 1 - i, 1));
        sum += i % 2 == 0 ? n * 3 : n;
    }

    return sum % 10 == 0 ? 0 : 10 - sum % 10;
}

Version 2: using Reverse()

public static int GetGTINCheckDigitV2(string code)
{
    int sum = 0;
    var list = code.Reverse().ToArray();

    for (int i = 0; i < list.Length; i++)
    {
        int n = (int)Char.GetNumericValue(list[i]);
        sum += i % 2 == 0 ? n * 3 : n;
    }

    return sum % 10 == 0 ? 0 : 10 - sum % 10;
}

Version 3: using lambda

public static int GetGTINCheckDigitV3(string code)
{
    var sum = code.Reverse().Select((c, i) => (int)char.GetNumericValue(c) * (i % 2 == 0 ? 3 : 1)).Sum();
    return (10 - sum % 10) % 10;
}

Is there anything I can improve this function or any concern?


texts: Extract unique words from given text and group by letter count

texts:
The task is for training go-lang. The idea is to extract unique words sorted and grouped by length. Might be useful in learning new words. The program uses command line argument assuming it's a file to read; reads from stdin if no arguments were given.

package main

import (
    "bufio"
    "fmt"
    "os"
    "regexp"
    "sort"
    "strings"
)

type words = map[string]struct{}
type groupedWords = map[int]words

// Checks for fatal errors.
// If non nil error passed program will be terminated
func check(e error) {
    if e != nil {
        panic(e)
    }
}

// Reads data from bufio.Reader and returns
// a map of grouped unique words: key is letters count, value is map of words
func getGroupedWords(reader *bufio.Reader) groupedWords {

    groupedWords := make(groupedWords)

    re, err := regexp.Compile("[^a-zA-Z]")
    check(err)
    for {
        str, err := reader.ReadString(' ')
        str = strings.ToLower(strings.TrimSpace(str))
        if !re.MatchString(str) {
            val, exists := groupedWords[len(str)]
            if !exists {
                groupedWords[len(str)] = words{str: struct{}{}}
            } else {
                val[str] = struct{}{}
            }

        }

        if err != nil {
            break
        }
    }

    delete(groupedWords, 0)
    return groupedWords

}

// Extracts sorted slice of keys from words
func getSortedKeysWord(w words) []string {
    list := make([]string, len(w))

    i := 0
    for word := range w {
        list[i] = word
        i++
    }

    sort.Strings(list)
    return list
}

// Extracts sorted slice of letters count from groupedWords
func getSortedKeysGroupedWord(gw groupedWords) []int {
    list := make([]int, len(gw))

    i := 0
    for lettersCnt := range gw {
        list[i] = lettersCnt
        i++
    }

    sort.Ints(list)
    return list
}

func main() {
    var reader *bufio.Reader
    args := os.Args
    if len(args) == 1 {
        reader = bufio.NewReader(os.Stdin)
    } else {
        file, err := os.Open(args[1])
        check(err)
        reader = bufio.NewReader(file)
    }

    groupedWords := getGroupedWords(reader)

    lettersCntList := getSortedKeysGroupedWord(groupedWords)
    for _, lettersCnt := range lettersCntList {
        list := getSortedKeysWord(groupedWords[lettersCnt])
        fmt.Print(lettersCnt, "(", len(list), "):\t")
        for _, word := range list {
            fmt.Print(word, " ")
        }

        fmt.Println()
    }

}

usage

echo "The unary notation can be abbreviated by introducing different symbols for certain new values. " | go run extract_words.go

should give

2(2):   be by
3(3):   can for new
5(1):   unary
7(2):   certain symbols
8(1):   notation
9(1):   different
11(2):  abbreviated introducing


texts:
I need to optimize the below code, as much as possible in:

using less resources as possible
being as fast as possible

What the code does is simple, it splits the string by words and only if a word is equal or bigger than 40 characters it will add spaces every X characters to the word that was too big:

<?php

$text = "more text here 00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.1% more text here!";

foreach (explode(" ", $text) as $word)
{
    if (strlen($word) >= 40)
    {
        $word = wordwrap($word, 8, " ", true);
    }
    $result[] = $word;
}
$data = implode(" ", $result);
echo $data;

Live DEMO

Is there anything that could be improved in this already simple code?


texts:
I have created a GNUMake building system for pandoc. It has grown quite a bit, I wonder if I can optimize it further. Would it be possible, for instance, that it only runs a target if the output hasn't changed since last run?

.DEFAULT_GOAL := pdf

INPUTDIR=$(CURDIR)/source
OUTPUTDIR=$(CURDIR)/output
STYLEDIR=$(CURDIR)/style
NAME = $(notdir $(shell basename "$(CURDIR)"))

FILFILES = $(wildcard style/*.py)

FILTER := $(foreach FILFILES, $(FILFILES), --filter $(FILFILES))
TEXFLAGS = --filter pandoc-crossref --filter pandoc-citeproc $(FILTER) --latex-engine=xelatex

ifeq ($(shell test -e "$(STYLEDIR)/template.tex" && echo -n yes),yes)
    TEXTEMPLATE = "--template=$(STYLEDIR)/template.tex"
endif

ifeq ($(shell test -e "$(STYLEDIR)/reference.docx" && echo -n yes),yes)
    DOCXTEMPLATE = "--reference-docx=$(STYLEDIR)/reference.docx"
endif

help:

    @echo '                                                                       '
    @echo 'Makefile for automated typography using pandoc.                         '
    @echo 'Version 1.0                        '
    @echo '                                                                       '
    @echo 'Usage:                                                                 '
    @echo '   make prepare    first time use, setting the directories     '
    @echo '   make html       generate a web version             '
    @echo '   make pdf        generate a PDF file             '
    @echo '   make docx       generate a Docx file            '
    @echo '   make tex        generate a Latex file               '
    @echo '   make beamer     generate a beamer presentation              '
    @echo '   make all        generate all files                 '
    @echo '   make update     update the makefile to last version       '
    @echo '   make            will fallback to PDF               '
    @echo '                                                                       '
    @echo 'It implies some directories in the filesystem: source, output and style'
    @echo 'It also implies that the bibliography will be defined via the yaml     '
    @echo '                                                                       '
    @echo 'Depends on pandoc-citeproc and pandoc-crossref                         '
    @echo 'Get local templates with: pandoc -D latex/html/etc                     '
    @echo '                                                                       '

all : tex docx html epub pdf

pdf:
    pandoc "$(INPUTDIR)/"*.md \
    -o "$(OUTPUTDIR)/$(NAME).pdf" \
    $(TEXTEMPLATE) \
    $(TEXFLAGS) 2>pandoc.log
    xdg-open "$(OUTPUTDIR)/$(NAME).pdf"

tex:
    pandoc "$(INPUTDIR)"/*.md \
    --filter pandoc-crossref \
    --filter pandoc-citeproc \
    -o "$(OUTPUTDIR)/$(NAME).tex" \
    --latex-engine=xelatex

docx:
    pandoc "$(INPUTDIR)"/*.md \
    --filter pandoc-crossref \
    --filter pandoc-citeproc \
    $(DOCXTEMPLATE) \
    --toc \
    -o "$(OUTPUTDIR)/$(NAME).docx"

html:
    pandoc "$(INPUTDIR)"/*.md \
    -o "$(OUTPUTDIR)/$(NAME).html" \
    --include-in-header="$(STYLEDIR)/style.css" \
    -t html5 \
    --toc \
    --standalone \
    --filter pandoc-crossref \
    --filter pandoc-citeproc \
    --number-sections
    rm -rf "$(OUTPUTDIR)/source"
    mkdir "$(OUTPUTDIR)/source"
    cp -r "$(INPUTDIR)/figures" "$(OUTPUTDIR)/source/figures"

epub:
    pandoc "$(INPUTDIR)"/*.md \
    -o "$(OUTPUTDIR)/$(NAME).epub" \
    --toc \
    --standalone \
    --filter pandoc-crossref \
    --filter pandoc-citeproc
    rm -rf "$(OUTPUTDIR)/source"
    mkdir "$(OUTPUTDIR)/source"
    cp -r "$(INPUTDIR)/figures" "$(OUTPUTDIR)/source/figures"

beamer:
    pandoc "$(INPUTDIR)/"*.md \
    -t beamer \
    -o "$(OUTPUTDIR)/$(NAME).pdf" \
    $(TEXTEMPLATE) \
    $(TEXFLAGS) 2>pandoc.log
    xdg-open "$(OUTPUTDIR)/$(NAME).pdf"

prepare:
    mkdir "output"
    mkdir "source"
    mkdir "style"

update:
    wget http://tiny.cc/mighty_make -O Makefile

clean:
    rm -f "$(OUTPUTDIR)/" *.md *.html *.pdf *.tex *.docx

.PHONY: help pdf docx html tex clean


texts:
I'm playing around with some ideas about how to read aggregates from events.

From a high-level view I would love to have this:

class Apply ev ag where
  apply :: ag -> ev -> ag

which to define how an Event ev should change an Aggregate ag if there is an instance of this class for the pair (if there is none then the aggregate should ignore the event).

If you look at the code below it's not hard at all to do it (please forgive me the anti-pattern with the Event list there).

My problem starts when I want the events all serialized - or better: once I want them deserialized and applied again (to be honest: I don't care about the representations at all - but it should be possible to fold an aggregate from a heterogeneous list/stream of serialized events of course).

What I don't like about my solution is this ugly bit of boiler-plate:

instance DeserializableFor Person where
  tryDeserialize (tn, sn)
    | tn == typeOf (SetName "") = Just (App (read sn :: SetName))
    | tn == typeOf (SetAge 0) = Just (App (read sn :: SetAge))
    | otherwise = Nothing

which could probably be generated using TH but I would prefer a direct solution.

Any suggestions?

{-# LANGUAGE MultiParamTypeClasses, ExistentialQuantification #-}
{-# LANGUAGE DeriveDataTypeable #-}

module Test where

import Data.Data
import Data.Maybe (catMaybes)

class Apply ev ag where
  apply :: ag -> ev -> ag

data Applicable a = forall e . (Show e, Read e, Typeable e, Apply e a) => App e

type Events a = [Applicable a]

fold :: Events a -> a -> a
fold [] a = a
fold ((App e):es) a = fold es $ apply a e

-----------------------------------------
-- nasty solution

serialize :: Events a -> [(TypeRep, String)]
serialize = map (\ (App e) -> (typeOf e, show e))

-- is there a way to get something like this from the `Apply` contexts?
class DeserializableFor a where
  tryDeserialize :: (TypeRep, String) -> Maybe (Applicable a)

-- because THIS is really ugly
instance DeserializableFor Person where
  tryDeserialize (tn, sn)
    | tn == typeOf (SetName "") = Just (App (read sn :: SetName))
    | tn == typeOf (SetAge 0) = Just (App (read sn :: SetAge))
    | otherwise = Nothing

deserialize :: DeserializableFor a => [(TypeRep, String)] -> Events a
deserialize = catMaybes . map tryDeserialize

--------------------------------------------------------
-- Example

data SetName = SetName String
  deriving (Show, Read, Typeable)

data SetAge = SetAge Int
  deriving (Show, Read, Typeable)

data SomeOtherEvent = SomeOtherEvent
  deriving (Show, Read, Typeable)

data Person = Person { name :: String, age :: Int }
  deriving Show

nobody :: Person
nobody = Person "" 0

instance Apply SetName Person where
  apply p (SetName n) = p { name = n }

instance Apply SetAge Person where
  apply p (SetAge a) = p { age = a }

events :: Events Person
events = [App (SetName "Mr.Wrong"), App (SetAge 42)]

serialized :: [(TypeRep, String)]
serialized = (typeOf SomeOtherEvent, show SomeOtherEvent) : serialize events

person :: Person -- is `Person {name = "Mr.Wrong", age = 42}`
person = fold (deserialize serialized) nobody


texts: Uint8Array indexOf method that allows to search for byte sequences

texts:
Uint8Array.prototype.indexOfMulti = function(searchElements, fromIndex) {
    fromIndex = fromIndex || 0;

    var index = Array.prototype.indexOf.call(this, searchElements[0], fromIndex);
    if(searchElements.length === 1 || index === -1) {
        // Not found or no other elements to check
        return index;
    }

    for(var i = index, j = 0; j < searchElements.length && i < this.length; i++, j++) {
        if(this[i] !== searchElements[j]) {
            return this.indexOfMulti(searchElements, index + 1);
        }
    }

    return (i === index + searchElements.length) ? index : -1;
};

It works fine but I wonder if I missed any important case or if anyone sees a way to optimize this.


texts: Managing many exceptions in Erlang cowboy without deeply nested trees

texts:
In my cowboy (Erlang) application, I have a handler called projects_from_json. This takes a JSON POST request as input and should create a database entry from this. Then, it should respond with a success message or the correct error message to the user.

I started with two exceptions that could occur (simplified):

projects_from_json(Req=#{method := <<"POST">>}, State) ->
    {ok, ReqBody, Req2} = cowboy_req:read_body(Req),
    try
        Name = parse_json(ReqBody),
        % Continuation of happy path
        db:create_project(Name)
    catch
        error:{badkey, Key} ->
            % return error message about invalid JSON
            % [<<"Key \"">>, Key, <<"\" does not exist in passed data">>]
        throw:duplicate ->
            % return error message about duplicate name
            % [<<"A project with name \"">>, Name, <<"\" already exists">>]
    end

Already in this case, this did not work, because Name is not safe in the second catch clause (since it comes from the try clause and could potentially be unset). I also could not move the call of db:create_project(Name) outside of the try, because then again Name would not be safe to be used.

Since there were some more exceptions and errors to be handled, I ended up with a very deeply nested situation (follows below).

My first idea would be to move stuff into own functions, but most of the code is error handling and as far as I know I can only handle the error by returning a tuple from the projects_from_json handler.

So here follows my nested mess. In total, I currently want to handle three error situations:

InvalidValue: The project name sent by the user contains invalid characters
DuplicateValue:  A project with the same name already exists
MissingKey: User did not supply all required keys

Code:

projects_from_json(Req=#{method := <<"POST">>}, State) ->
    {ok, ReqBody, Req2} = cowboy_req:read_body(Req),
    try
        Name = project_name(ReqBody),

        case validate_project_name(Name) of
            invalid ->
                molehill_respond:respond_error(<<"InvalidValue">>,
                    <<"The project name can only consist of ASCII characters and numbers, and dash in the middle of the word.">>,
                    400, Req2, State);
            ok ->
                {ok, Conn} = moledb:connect_from_config(),

                try
                    moledb:create_project(Conn, Name),
                    Data = prepare_project_json(Name),
                    molehill_respond:respond_status(Data, 201, Req2, State)
                catch
                    throw:duplicate_element ->
                        molehill_respond:respond_error(<<"DuplicateValue">>,
                            erlang:iolist_to_binary(
                                [<<"A project with name \"">>, Name, <<"\" already exists">>]),
                            409, Req2, State)
                end
        end
    catch
        error:{badkey, Key} ->
            molehill_respond:respond_error(
                <<"MissingKey">>,
                erlang:iolist_to_binary(
                    [<<"Key \"">>, Key, <<"\" does not exist in passed data">>]),
                400, Req2, State)
    end.

Is it possible to restructure this to a clean form where all possible errors are on a similar indentation level at the end of the function?

molehill_respond is a helper module I wrote to simplify the creation of my JSON return messages, moledb is a helper module that executes all the SQL queries.


texts:
I am working on optimizing a Wator program. I have a specific question about code, if you are familiar with it. There is a function which takes most of the time. I need your help to improve this particular part of the code.

 // find all neighbouring cells of the given position that contain an animal of the given type
public int GetNeighbors(Type type, Point position) {

  int neighborIndex;
  int i, j;

  // counter for the number of cells of the correct type
  neighborIndex = 0;
  // look up
  i = position.X;
  j = (position.Y + Height-1)%Height;
  // if we look for empty cells (null) we don't have to check the type using instanceOf
  if ((type == null) && (Grid[i, j] == null)) {
    neighbors[neighborIndex] = new Point(i, j);
    neighborIndex++;
  } else if ((type != null) && (type.IsInstanceOfType(Grid[i, j]))) {
    // using instanceOf to check if the type of the animal on grid cell (i/j) is either a shark of a fish
    // animals that moved in this iteration onto the given cell are not considered
    // because the simulation runs in discrete time steps
    if ((Grid[i, j] != null) && (!Grid[i, j].Moved)) {
      neighbors[neighborIndex] = new Point(i, j);
      neighborIndex++;
    }
  }
  // look right
  i = (position.X + 1) % Width;
  j = position.Y;
  if ((type == null) && (Grid[i, j] == null)) {
    neighbors[neighborIndex] = new Point(i, j);
    neighborIndex++;
  } else if ((type != null) && (type.IsInstanceOfType(Grid[i, j]))) {
    if ((Grid[i, j] != null) && (!Grid[i, j].Moved)) {
      neighbors[neighborIndex] = new Point(i, j);
      neighborIndex++;
    }
  }
  // look down
  i = position.X;
  j = (position.Y + 1) % Height;
  if ((type == null) && (Grid[i, j] == null)) {
    neighbors[neighborIndex] = new Point(i, j);
    neighborIndex++;
  } else if ((type != null) && (type.IsInstanceOfType(Grid[i, j]))) {
    if ((Grid[i, j] != null) && (!Grid[i, j].Moved)) {
      neighbors[neighborIndex] = new Point(i, j);
      neighborIndex++;
    }
  }
  // look left
  i = (position.X + Width - 1) % Width;
  j = position.Y;
  if ((type == null) && (Grid[i, j] == null)) {
    neighbors[neighborIndex] = new Point(i, j);
    neighborIndex++;
  } else if ((type != null) && (type.IsInstanceOfType(Grid[i, j]))) {
    if ((Grid[i, j] != null) && (!Grid[i, j].Moved)) {
      neighbors[neighborIndex] = new Point(i, j);
      neighborIndex++;
    }
  }

        return neighborIndex;
    }


texts: Sending AT commands via switch case in Arduino

texts:
Is this the proper use for switch case? I am looking to make a simple utility for reporting back Wireless AP info, Baud Rate, and Mode of a ESP8266 module.

When the program loads it gives the user a small menu of option and based on the input of the user (1,2 or 3) it will run the associated AT command stored as a variable in the code.

Will this work as is? Or am I missing something to send the command and get the data back?

void loop() {

if (Serial.available() > 0) {
input = Serial.read();
Serial.flush();

switch (input) {
  case '1':
      Serial.println(baud);
      break;

   case '2':
      Serial.println(wap);
      break;

   case '3':
      Serial.println(amode);
      break;

   default:
      Serial.print("'");
      Serial.print((char)input);
      Serial.println("' is not a command!");
}
 }
}

The baud, wap, and amode commands are setup as follows:

const char* wap = "AT+CWLAP";
const char* baud = "AT+CIOBAUD";
const char* amode = "AT+CWMODE";


texts:
I solved the following problem:

  Let's consider the following situation. You've invited a lot of children to a celebration party, and you want to entertain them and also teach them something in the process. You are going to hire a few teachers and divide the children into groups and assign a teacher to each of the groups. This teacher will work with this group through the whole party.

  But you know that for a teacher to work with a group of children efficiently children of that group should be of relatively the same age. More specifically age of any two children in the same group should differ by at most, one year.

  Also, you want to minimize the number of groups. Because you want to hire fewer teachers, and spend the money on presents and other kinds of entertainment for the children. So, you need to divide children into the minimum possible number of groups. Such that the age of any two children in any group differs by at most one year.

import java.io.*;
import java.util.*;

public class ChildrenGroup{

  static int getGroups(float[] children) {

    int lastChild = children.length;
    int currentChild=1;
    int startingPoint=0;
    int groups=0;

    while(currentChild<lastChild){

        if(children[currentChild]-children[startingPoint]>1){
            startingPoint=currentChild ;
            groups++;
        }

        if(currentChild==lastChild-1){
            groups++;
        }
        currentChild++;
    }

    return groups;
  }

  public static void main(String[] args) {

    Scanner in = new Scanner(System.in);

    int n = in.nextInt();
    float[] children = new float[n];

    for (int i = 0; i < n; i++) {
        children[i] = in.nextFloat();
    }

    System.out.println(getGroups(children));

  }
}

Sample input 1:

7
2.5 3.2 3.5 4.0 4.8 5.2 6.0

Output 1:

3

Sample input 2:

3
2.1 4.5 6.7

Output 2:

3

What's your thoughts on the solution?


texts:
This is my implementation using the dreadful !!:

import Data.Char (chr, ord, toUpper)

-- A bit of self documentation help
type Key = String
type Msg = String

key :: Key
key = "TSTING"
msg :: Msg
msg = "I'm not even mad... This is impressive!"

-- | Checks if character is valid for encoding
isValid :: Char -> Bool
isValid c = let cUp = toUpper c :: Char
             in 'A' <= cUp && cUp <= 'Z'

-- | Given 'key' & 'msg' generate a list of [Maybe Int] indices
-- to map 'msg' from 'key', skipping invalid characters
toIdx :: Key -> Msg -> [Maybe Int]
toIdx k m = map (flip mod keyN <$>) $ toIdx_ 0 m
  where keyN = length k :: Int
        toIdx_ :: Int -> Msg -> [Maybe Int]
        toIdx_ _ "" = []
        toIdx_ acc (c:cs)
          | isValid c = Just acc : toIdx_ (acc + 1) cs
          | otherwise = Nothing : toIdx_ acc cs

-- | Given 'key' & 'msg' generate a list of numbers representing
-- the amount to shift 'msg' characters based on 'key'
toShifts :: Key -> Msg -> [Int]
toShifts k m = map toKey (toIdx k m)
  where kUp = map toUpper k :: Key
        toKey :: Maybe Int -> Int
        toKey Nothing  = 0
        toKey (Just x) = ord (kUp!!x) - ord 'A'

-- | Given 'by' & 'c', shift the Char 'c' by amount 'by'. 'by' can be both
-- positive & negative as well as 0.
shift :: Int -> Char -> Char
shift by c
  | isValid c && c >= 'a' = shift_ $ ord 'a'
  | isValid c && c >= 'A' = shift_ $ ord 'A'
  | otherwise = c
  where cONorm    = ord (toUpper c) - ord 'A' :: Int
        azN       = ord 'Z' - ord 'A' :: Int
        shift_ :: Int -> Char
        shift_ aO = chr $ aO + mod (by + cONorm) azN

-- Encode & decode a message using the given key.
vigenere, unVigenere :: Key -> Msg -> Msg
vigenere   k m = zipWith shift (toShifts k m) m
unVigenere k m = zipWith shift (map negate $ toShifts k m) m

I found that the most "annoying" thing when coming from background such as Python is to be able to keep track of things, for example when figuring out how to convert valid characters into usable positions to be then mapped with the key. That thing took me half a day to figure out!

How would you do it? Or is there some "standard" way of working with these sort of things? I'm referring particularly to toIdx & toIdx_, had to use toIdx_ to accumulate the indices with acc in this list of Maybe Int in order to correctly map valid Chars with key.

Of course, I wouldn't have it any other way but have an algorithm which takes any String input and creates an encoded String with preserved upper/lower-case and non-valid (out of ASCII alphabet) Chars.


texts:
Object-oriented program for a calorie counter sporting polymorphic
methods for both genders.

Principles to adhere to:

Uniform Access Principle
Polymorphism
Dependency inversion principle through the Factory Method pattern
Single responsibility principle

Concerns for future extension:

BPM curve for exercise acts of longer duration, can this be transparently added?

Other concerns:

Unit prefixes for names, e.g. weight_kg, exercise_duration_min. Are these bad?
Overengineered? Yes, I'm not going to argue against that; we don't have more than one method in our classes which eliminates the need to have them at all. Assuming we had more than one method, however, is it still overdone?
Are any of the principles I claimed to follow not followed or properly followed? Especially thinking of the Factory Method pattern.

By the way, the formula for calculating calories burned doesn't seem to be right, but that doesn't really matter for our purposes.

# oo-calorie_counter.py
from abc import ABC, abstractmethod

def main():
    """Setup and initialization.
    """
    person_attributes = get_person_attributes()
    person = PersonFactory.make_person(person_attributes)

    print("You've burnt approximately {0} calories".format(round(person.calories_burned, 1)))

def get_person_attributes():
    """Prompts a user for their details
    """
    person_attributes = {
        'gender': input('Your gender: '),
        'weight_kg': int(input('Your weight in Kg: ')),
        'age': int(input('Your age: ')),
        'bpm': int(input('Your heart rate: ')),
        'exercise_duration_min': int(input('Your your exercise duration in minutes: '))
    }

    return person_attributes

class PersonFactory:
    @staticmethod
    def make_person(person_attributes):
        """
        Instantiate the proper a person of proper gender based on the provided attributes.
        Args:
            person_attributes: A dictionary containing the keys:
            ('gender', 'age, 'weight_kg', exercise_duration_min, bpm)

        """
        gender = person_attributes['gender']
        del person_attributes['gender']

        if gender.lower() == 'male':
            return Male(**person_attributes)
        elif gender.lower() == 'female':
            return Female(**person_attributes)
        else:
            raise RuntimeError('Unknown gender')

class Person(ABC):
    def __init__(self, weight_kg, bpm, age, exercise_duration_min):
        self.weight_kg = weight_kg
        self.age = age
        self.bpm = bpm
        self.exercise_duration_min = exercise_duration_min

    @property
    @abstractmethod
    def calories_burned(self):
        raise NotImplementedError

class Male(Person):
    @property
    def calories_burned(self):
        return ((self.age * 0.2017) - (self.weight_kg * 0.09036) + (self.bpm * 0.6309) - 55.0969) * self.exercise_duration_min / 4.184

class Female(Person):
    @property
    def calories_burned(self):
        return ((self.age * 0.074) - (self.weight_kg * 0.05741) + (self.bpm * 0.4472) - 20.4022) * self.exercise_duration_min / 4.184

if __name__ == '__main__':
    main()


texts:
My objective is to take a string as input and determine if it is a palindrome. I'm wondering how I could improve this code (efficiency, bugs, etc). I'm relatively new to Java so I'm expecting that my code will contain some errors.

import java.util.Scanner;

    /**
     * Created by Adam on 6/5/2015.
     */
    public class Reversal {
        public static void main(String args[]) {
            String word = "";
            String reversed = "";
            Scanner in = new Scanner(System.in);
            System.out.println("Please enter the string: ");
            word = in.nextLine();
            int length = word.length();
            for(int i = length; i > 0; i--) {
                reversed += word.charAt(i-1);
            }
            if(removeSpace(word).compareTo(removeSpace(reversed)) == 0) {
                System.out.println("The string " + word + " is a palindrome");
            }
            else {
                System.out.println("The string " + word + " is not a palindrome");
            }
        }

        private static String removeSpace(String aword) {
         String buffer = "";
            for(int i = 0; i < aword.length(); i++)   {
             if(!(String.valueOf(aword.charAt(i)).compareTo(" ") == 0)) {
                 buffer += aword.charAt(i);
             }
         }
            return buffer;
        }
    }


texts: Find two numbers that add up to a given total, from a formatted string

texts:
The full challenge from codeeval.com can be viewed here.

  Input

  Your program should accept as its first argument a filename. This file
  will contain a comma separated list of sorted numbers and then the sum
  'X', separated by semicolon. Ignore all empty lines. If no pair
  exists, print the string NULL.

  Output

  Print out the pairs of numbers that equal to the sum X. The pairs
  should themselves be printed in sorted order i.e the first number of
  each pair should be in ascending order.

I am writing a program to solve the above conditions. It currently works, however I believe it can be optimized to run better. This challenge is unique, since it requires you to work with a String for input, and to output a specifically formatted String as well. The problem with this is memory efficiency, as I have to convert this String to a String array, and then further convert it to a workable int array.

I am a student developer, and I don't have much experience, so any tips and tricks would be helpful.

Java

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

public class SomeClass {
    public static void main(String[] gras) {
        String line = "1,2,3,4,5;6"; //replace string with test case

        //code
        String[] j = line.split(";")[0].split(",");
        int[] input = new int[j.length];
        for (int i = 0; i < j.length; i++) {
            input[i] = Integer.parseInt(j[i]);
        }
        Arrays.sort(input);
        int k = Integer.parseInt(line.split(";")[1]);
        // Modified Algorithm
        Map<Integer, Integer> paers = new HashMap<Integer, Integer>();
        boolean d = false;
        for (int i = input.length - 1; i >= 0; i--) {
            paers.put(k - input[i], input[i]);
        }
        for (int i = 0; i < input.length; i++) {
            if (paers.containsKey(input[i]) && paers.get(input[i]) > input[i]) {
                if (d) {
                    System.out.print(";");
                }
                d = true;
                System.out.print(input[i] + "," + paers.get(input[i]));
            }
        }
        if (!d) System.out.println("NULL"); else System.out.println("");
    }
}

As far as what I've tried, this is my final product. I changed my solution from using a naive \$O(n^2)\$ algorithm to this \$O(3n)\$ algorithm. Again, my terminology might be off, I'm just figuring this stuff out. Also, the code is tested and working.


texts:
I have created a little program to search a set of folders holding documents scanned.

The folder structure is as follows:

  c:\images\year\month\date\documenttype\firstpartofdocumentNo.\

  the year folder contains years from 2005 - 2015

  the month folder contains the months of the year (Obviously) same with
  date

  the documenttype folder can contain between 1 and 5 folders

  the firstpartofdocumentno. can contain between 1 and 3 folders

The code I am using at the moment is:

CompName = Environment.MachineName

TicketNo = TxtTicketNo.Text

If CompName = "Comp1" Then
    ImageDir = "C:\Images\"
Else
    ImageDir = "\\Comp2\Images\"
End If

For Each DirYear As String In Directory.GetDirectories(ImageDir)
    Dim YearInfo As New DirectoryInfo(DirYear)

    For Each DirMonth As String In Directory.GetDirectories(DirYear)
        Dim MonthInfo As New DirectoryInfo(DirMonth)

        For Each DirDate As String In Directory.GetDirectories(DirMonth)
            Dim DateInfo As New DirectoryInfo(DirDate)

            For Each DirType As String In Directory.GetDirectories(DirDate)
                Dim TypeInfo As New DirectoryInfo(DirType)

                For Each DirStart As String In Directory.GetDirectories(DirType)
                    Dim StartInfo As New DirectoryInfo(DirStart)

                    MainDirectory = ImageDir & YearInfo.Name & "\" & MonthInfo.Name & "\" & DateInfo.Name & "\" & TypeInfo.Name & "\" & StartInfo.Name & "\"
                                                                                For Each Ticket As String In Directory.GetFiles(MainDirectory, TicketNo & "*")
                        LstFiles.Items.Add(Ticket)
                    Next

                Next

             Next

        Next
    Next
   Next

I have a textbox on the form which is used to enter the last four numbers of the ticketno and then this code runs when the button is clicked.

The problem is it can take up to five minutes to search, so I was wondering if there is a way to optimize this code to speed it up a bit or does this sound about right for searching that many folders.


texts:
I'm writing a WCF service for validating password and getting company ID for the clients that requests the services. The service runs on a server locally as a windows service, which sends queries to the database and returns the appropriate info back to the client.

I'd first like some comments on how the overall design looks like as I'm going to be adding more operations but wanted to avoid any situations where I have to rewrite them all just in case if I'm headed the wrong direction.

I have a specific question regarding the stability of this service. In case if the operation somehow fails on the server's end, such as an exception being thrown because the server couldn't connect to a database.

Where should I handle the exception? Should I wrap my methods in try catch statements on the service methods or where the call is being made (client)?
What can I do to increase the stability of this service? Under any circumstances, I cannot allow the service to shut down aside from the user intentionally doing so.

These are probably trivial questions but I'd like some guidance on this matter. Thank you.

namespace TopwareOutlookSyncService
{
    [ServiceContract]
    public interface ITopwareOutlookSyncService
    {
        [OperationContract]
        bool IsPasswordValid(string password);

        [OperationContract]
        string GetCompanyID(string userID);
    }
    public class TopwareOutlookSyncService : ITopwareOutlookSyncService
    {
        private SqlConnection con;
        public void ConnectDB()
        {
            if (!IsDBConnected())
            {
                con = new SqlConnection("user id=nexol;" +
                                           "password=;server=666.666.666.666;" +
                                           "database=hell; " +
                                           "connection timeout=15");
                con.Open();
            }
        }

        public bool IsDBConnected()
        {
            return (con != null && con.State == ConnectionState.Open);
        }

        public bool IsPasswordValid(string userID, string password)
        {
            if (!IsDBConnected())
                ConnectDB();
            bool isPasswordValid = false;

            string sql = "SELECT USER_PW FROM HELL.GRP_USER WHERE USER_ID = '" + userID + "'";
            string encryptedPassword = PasswordTable.GetEncryptedString(password);
            SqlCommand command = new SqlCommand(sql, con);
            SqlDataReader reader = command.ExecuteReader();

            while (reader.Read())
            {
                if (reader["USER_PW"].ToString() == encryptedPassword)
                {
                    isPasswordValid = true;
                    break;
                }
            }

            reader.Close();
            con.Close();
            return isPasswordValid;
        }

        public string GetCompanyID(string userID)
        {
            if (!IsDBConnected())
                ConnectDB();
            string companyID = String.Empty;
            string sql = "SELECT COM_CD FROM HELL.GRP_USER WHERE USER_ID = '" + userID + "'";
            SqlCommand command = new SqlCommand(sql, con);
            SqlDataReader reader = command.ExecuteReader();

            while (reader.Read())
            {
                companyID = reader["COM_CD"].ToString();
            }

            reader.Close();
            con.Close();
            return companyID;
        }
    }
}


texts:
I'm learning about threading support in C++. I've got a basic understanding of thread-pools and why creating and destroying threads on some systems can be expensive. As far as I'm aware C++11 doesn't have any built in support for worker/background threads. std::thread is only designed to perform one task which you set in the constructor; it then destroys the thread after the task is complete.

At the moment I have no use for a fully fledged thread-pool but I would like to be able to reuse a thread for different tasks after I create it. I've created a simple class that will accept any function or method wrapped in a lambda and will then execute it exactly once. The reusable thread object should not destruct until the work function is fully complete.

This is the implementation:

class Reusable_Thread
{
    public:
        Reusable_Thread()
            : m_thread_pause(true), m_thread_quit(false),
              m_thread(&Reusable_Thread::thread_worker, this)
        { }

        ~Reusable_Thread()
        {
            m_thread_quit = true;
            m_thread.join();
        }

        bool get_readiness() const { return m_thread_pause; }

        bool set_work(const std::function<void()>& work_func)
        {
            if (get_readiness())
            {
                m_work_func = work_func;
                return true;
            }
            else
            {
                return false;
            }
        }

    private:
        std::atomic<bool> m_thread_pause;
        std::atomic<bool> m_thread_quit;
        std::thread m_thread;
        std::function<void()> m_work_func;

        void thread_worker()
        {
            while (!m_thread_quit)
            {
                if (!m_thread_pause)
                {
                    m_work_func();
                    m_thread_pause = true;
                }
            }
        }
};

And this is some example usage:

int main()
{
    Reusable_Thread thread;

    auto f1 = [&] () { /* do some work */ };
    thread.set_work(f1);

    while (thread.get_readiness() == false)
    {
        // do some other stuff
    }

    // set some new work
    auto f2 = [&] () { /* do some new work */ };
    thread.set_work(f2);

    // maybe call f1 again, depends if f2 has finished yet
    if (!thread.set_work(f1))
    {
        // thread too busy to call f1, call it on the main thread
        f1();
    }

    // thread won't destruct until work has finished
    return 0;
}

Are there any problems with implementing a reusable thread this way?


texts: A more functional try...catch construct in Java

texts:
I saw a question on Stack Overflow asking for a review of a custom try...catch construct that made use of Optionals, and got the idea to try writing my own version. Mine doesn't use Optionals though. Each supplied catch handler is expected to return a value.

I realized about half way through writing this that this is probably an awful idea that should never be used d in the real world for various reasons. I haven't written Java in a few years though, and I'm curious what can be improved.

Example of use:

Integer i =
        new Try<>(()-> Integer.parseInt("f"))
                  .catching(NumberFormatException.class, (e)-> 2)
                  .catching(IllegalStateException.class, (e) -> 3)
                  .andFinally(()-> System.out.println("Finally!"));

// Finally!

Integer j =
        new Try<>(()-> Integer.parseInt("1"))
                  .catching(NumberFormatException.class, (e) -> 2)
                  .execute();

System.out.println(i); // 2
System.out.println(j); // 1

Basically how it works is the Try object can have catching methods chained on it that register handlers. When an exception is thrown, it looks for a corresponding handler, and calls it, returning the returned value. If no handler is found, it rethrows the exception.

Major problems:

The need for .class is unfortunate. I couldn't think of how else to have the caller indicate the class of exception to be caught though.
Non-exception classes can be registered, although it will have no effect other than the minimal memory and CPU usage.
The need for execute when andFinally isn't used. I can't see how the class would know that all catches have been added though.
The need for new is unfortunate too. I figured I could take a page from Scala and create a static method that acts as a constructor, but then I'd need to do something like Try.tryMethod to reference it, which isn't a whole lot better.
The check in andFinally seems like it's unnecessary. Unless someone does something bizarre like:

Try t = new Try<>(() -> null);
t.andFinally(() -> {});
t.andFinally(() -> {});

It shouldn't be possible to add multiple finally blocks. I'm not sure to what extent I should stop the user from doing stupid things. I could make the object immutable, but again, I'm not sure if that's necessary.

Since this is basically just exercise code, I'd love to anything at all that could be improved here. This is the first Java I've really written in a few years, so I'm sure there's lots that can be improved.

import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
import java.util.function.Supplier;

public class Try<T> {
    private Supplier<T> tryExpr;
    private Map<Class, Function<Exception, T>> handlers = new HashMap<>();
    private Runnable finallyExpr;

    public Try(Supplier<T> tryExpr) {
        this.tryExpr = tryExpr;
    }

    public Try<T> catching(Class ex, Function<Exception, T> handler) {
        if(handlers.containsKey(ex)) {
            throw new IllegalStateException("exception " + ex.getSimpleName() + " has already been caught");

        } else {
            handlers.put(ex, handler);

            return this;
        }
    }

    public T execute() {
        try {
            return tryExpr.get();

        } catch (Exception e) {
            if(handlers.containsKey(e.getClass())) {
                Function<Exception, T> handler = handlers.get(e.getClass());

                return handler.apply(e);

            } else {
                throw e;
            }

        } finally {
            if(finallyExpr != null) {
                finallyExpr.run();
            }
        }
    }

    public T andFinally (Runnable newFinallyExpr) {
       if (finallyExpr == null) {
           finallyExpr = newFinallyExpr;

       } else {
           throw new IllegalStateException("Cannot have multiple finally expressions");
       }

       return execute();
    }

}


texts:
I have written a python function that outputs scatter plots using Matplotlib after processing the data a little. It works but it's painfully slow. I was wondering if anybody had any suggestions as to how I can improve the efficiency of this function or whether its slow just because it's processing a lot of data (a 30x43 element Pandas data frame).

def scatter_x_yi(self,filtered_data,x_parameter):
    '''
   takes some prefiltered data (len(x) by len(Y)) and the name of a
    data column (x_parameter), plots it against every other column (yi)
    '''
    PE=Parameter_Estimation_Tools() #custom class
    number_of_full_subplots=len(filtered_data)/16
    remainder=len(filtered_data)-(number_of_full_subplots*16)-1
    os.path.dirname(str(filtered_data))
    '''
    some code for isolating the x parameter column
    and all the y's (yi)
    '''
    yi=[]
    for i in range(len(filtered_data)):
        if filtered_data[i].name!=x_parameter:
            yi.append(filtered_data[i])
    '''
    code for plotting the scatter plots (43 in total)
    using matplotlib in 'units' of 4 by 4, then plotting
    the remainder in a last figure

    '''
    try:
        for i in range(len(filtered_data)):
            for j in range(number_of_full_subplots+1):
                fig=plt.figure(j)
                txt = fig.suptitle('{} , {} of {}'.format(str(x_parameter),str(j),str(number_of_full_subplots)),fontsize='18')
                txt.set_text('{} , {} of {}'.format(str(x_parameter),str(j),str(number_of_full_subplots)))
                for k in range(16):
                    plt.subplot(4,4,k)
                    PE.scatter_x_y(filtered_data,x_parameter,yi[16*j+k].name)
                    plt.subplots_adjust(wspace=0.2, hspace=0.25,top=0.9)
            mng=plt.get_current_fig_manager()
            mng.window.showMaximized()
            plt.ioff()
            fig.savefig(str(j)+'.png',bbox_inches='tight',orientation='landscape')
            plt.close(fig)
            plt.ion()
    except IndexError:
        for i in range(len(filtered_data)-remainder,len(filtered_data)-1):
            PE.scatter_x_y(filtered_data,x_parameter,yi[i].name)
            plt.subplots_adjust(wspace=0.2, hspace=0.25,top=0.9)
            mng=plt.get_current_fig_manager()
            mng.window.showMaximized()
            plt.ioff()
            fig.savefig('2.png',bbox_inches='tight',orientation='landscape')
            plt.close(fig)
            plt.ion()
        print '{} has been plotted against all other parameters'.format(x_parameter)


texts:
I'm navigating to a view. I have an EventDateTime property which I want to set to DateTime.Today unless the navigation is coming from MyCustomView

This is what I've come with so far. It's working, but I find this really ugly:

public void OnNavigatedTo(NavigationParameters parameters)
{
    if (parameters != null)
    {
        if (!parameters.ContainsKey(PARAM_NAVIGATEDFROM)) // If there is parameter PARAM_NAVIGATEDFROM, then the navigation doesn't come from MyCustomView
        {
            EventDateTime = DateTime.Today;
        }
        else if (parameters[PARAM_NAVIGATEDFROM] != typeof(MyCustomViewModel)) // If there is a parameter PARAM_NAVIGATEDFROM but not with the specific value, the navigation doesn't come from MyCustomView
        {
            EventDateTime = DateTime.Today;
        }
    }
    else // If there are no parameters at all, the navigation is not coming from MyCustomView either
    {
        EventDateTime = DateTime.Today;
    }
}

Any ideas how I can improve this Code? Maybe even with another approach instead of putting the Code into the OnNavigatedTo() method?


texts: Selecting the number of working days minus weekend days and UK bank holidays

texts:
I am fairly new to coding TSQL script and am looking for some second view on my script.
The goal here is to to pull in some data and amongst that data to show a field with a counting the number of working days since the order date only (i.e. minus weekend days and UK bank holidays). The SELECT script below is working as expected in that it shows results and is therefore calling the fn_WorkDays function. What would be helpful is to have a second glance of the function itself as a double check/review. The last part of the function is looking at a date field of a table that contains all of the bank holidays.

I think the script is working okay as I have checked a few going back to January, so I'm looking to get the double check to highlight any unforeseen potential errors or even code improvements.

SELECT
cir.[PW Number] AS PWNum
--Get the correct number of working dayts since the order date by using the fn_WorkDays function
,CONVERT(VARCHAR(10),singleended2.dbo.fn_WorkDays(cir.[Install Date], GETDATE()),103) AS NumberOfDaysSinceOrderDate
,CONVERT(VARCHAR(10), ISNULL(cir.[Install Date],'01/01/1900'),103) AS  OrderDate--Get the order dates
,ISNULL(cirRep.CurrentStage, 'Not Set') AS CurrentStage
,cir.[ID] as CircuitID
FROM Quotebase.dbo.Circuits cir
    LEFT JOIN Quotebase.dbo.CircuitReports cirRep ON Cir.[PW Number] = CirRep.PWNumber
WHERE Cir.Status='New Circuit Order'
ORDER BY Cir.[PW Number]

Here is the function script that is called:

ALTER FUNCTION dbo.fn_WorkDays (@StartDate AS DATETIME, @EndDate AS DATETIME)
--Define the output data type.
RETURNS INT
AS
--Calculate the RETURN of the function.
BEGIN
    RETURN (
     SELECT
        (DATEDIFF(dd,@StartDate, @EndDate)+1)--Start with total number of days including weekends +1 Includes the day run
        -(DATEDIFF(wk,@StartDate, @EndDate)*2)--Subtact 2 days for each full weekend
        -(CASE WHEN DATENAME(dw, @StartDate) = 'Sunday' --If StartDate is a Sunday, Subtract 1
            THEN 1
            ELSE 0
        END)
        -(CASE WHEN DATENAME(dw, @EndDate) = 'Saturday'--If EndDate is a Saturday, Subtract 1
            THEN 1
            ELSE 0
        END)
        --Now check if there are any bank holidays between the start and end and remove that amount
        - (SELECT COUNT(ivm.[Date])
          FROM [EUROPEVUK386].[InvoiceManagement].[dbo].[tblBankHolidays] ivm
          WHERE ivm.[Date] BETWEEN @StartDate AND @EndDate)
          --WHERE ivm.[Date] BETWEEN '2006-04-14' AND '2006-05-29')
)
 END
GO


texts: Efficiently remove duplicate elements from the list

texts:
I have a legacy code in which ids List has some duplicate value coming and this method is being called from lot of difference places as of now -
public async Task<List<T>> Execute<T>(IList<int> ids, Policy policy, Func<CancellationToken, int, Task<T>> mapperFunc) where T : class
{
    var holder = new List<Task<T>>(ids.Count);
    var removeNull = new List<T>(ids.Count);
    for (int i = 0; i < ids.Count; i++)
    {
        var id = ids[i];
        holder.Add(ProcessData(policy, ct => mapperFunc(ct, id)));
    }

    var responses = await Task.WhenAll(holder);
    for (int i = 0; i < responses.Length; i++)
    {
        var response = responses[i];
        if (response != null)
        {
            removeNull.Add(response);
        }
    }
    return removeNull;
}

I am trying to change above method such that I can remove duplicate stuff from ids list so I came up with below code which does that but I wanted to see if there is any better way we can write below code?
public async Task<List<T>> Execute<T>(IList<int> ids, Policy policy, Func<CancellationToken, int, Task<T>> mapperFunc) where T : class
{
    var noDupsList = new HashSet<int>(ids).ToList();
    var holder = new List<Task<T>>(noDupsList.Count);
    var removeNull = new List<T>(noDupsList.Count);
    for (int i = 0; i < noDupsList.Count; i++)
    {
        var id = noDupsList[i];
        holder.Add(ProcessData(policy, ct => mapperFunc(ct, id)));
    }

    var responses = await Task.WhenAll(holder);
    for (int i = 0; i < responses.Length; i++)
    {
        var response = responses[i];
        if (response != null)
        {
            removeNull.Add(response);
        }
    }
    return removeNull;
}

Update
Seeing the answer that came I thought it's good idea to mention how my actual code is - This is how my original code is :
public async Task<List<T>> Execute<T>(IList<int> ids, Policy policy, Func<CancellationToken, int, Task<T>> mapperFunc, string logMessage) where T : class
{
    var noDupsList = new HashSet<int>(ids).ToList();
    var holder = new List<Task<T>>(noDupsList.Count);
    var removeNull = new List<T>(noDupsList.Count);
    using (var logMetric = new LogMetric(_logger, TITLE, "DatabaseCall"))
    {
        logMetric.Message = logMessage;
        for (int i = 0; i < noDupsList.Count; i++)
        {
            var id = noDupsList[i];
            holder.Add(ProcessData(policy, ct => mapperFunc(ct, id)));
        }

        var responses = await Task.WhenAll(holder);
        for (int i = 0; i < responses.Length; i++)
        {
            var response = responses[i];
            if (response != null)
            {
                removeNull.Add(response);
            }
        }
        logMetric.StatusCode = (removeNull.Count == 0) ? 204 : 200;
    }
    return removeNull;
}


texts: Keyboard handler for moving in four directions

texts:
I'm having trouble deciding if I should leave the default: break; in the switch statement or not. It does kinda show intent, i.e. that most keys are not handled, but it's also effectively useless code. I feel like it's clear enough anyway, but maybe being explicit is better?

function handleKeyDownEvent(event) {
    switch (event.keyCode) {
        case 87: // w
            player.dy = -50
            break
        case 65: // a
            player.dx = -50
            break
        case 83: // s
            player.dy = 50
            break
        case 68: // d
            player.dx = 50
            break
        default:
            break
    }
}

Maps seem to be the preferred way of doing this, instead of a switch statement. How does the movement map work with the corresponding handleKeyUpEvent which works the same way, except that it zeroes the dx or dy values?

Should I keep the default: break; or not?


texts:
The problem

Project Euler: 35 is stated in the following way

  Circular primes

  Problem 35

  The number, 197, is called a circular prime because all rotations of
  the digits: 197, 971, and 719, are themselves prime.

  There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31,
  37, 71, 73, 79, and 97.

  How many circular primes are there below one million?

My attempt

I solved this question some time ago, and have now come back to it because I saw it pop up a few times here on CR. I wanted to over-engineer the problem and instead of finding the circular primes under a million I wanted to find them under some crazy big number.

It is not terribly quick, but uses that all circular primes above a million are repunit primes with a prime number of digits.

I included two different ways of checking whether a number (or in this case a list of numbers) is a circular prime. I use the following

def is_circular_2(p):
    for i in range(len(p)):
        if not isprime(int(''.join(map(str, p[i:]+p[:i])))):
            return False
    return True

However after some quick googling, the following seem to be the "preferred" way

def lst_2_int(lst):
    return int(''.join(map(str, lst)))

def is_circular(p):
    return all(isprime(lst_2_int(p[i:]+p[:i])) for i in range(len(p)))

However after some light speedtests using timeit, this version is a tad slower. As many other answers do I cycle through the products of the odd integers [1, 3, 7, 9] since no prime can end in an even integer, or 5.

I do not bother saving the primes or non primes already found. Is it "worth" it? isprime from the primefac libary already seems quite fast. To find the really big circular primes I iterate over the repunit primes. Eg primes only consisting of 1`s. No need to check if it is circular. I also used the small increase that a repunit number is prime if and only if it contains a prime number of digits.

Looking for any sort of general comments on my code. Not sure if my code can be improved speedwise, but comments there are appreciated as well.

The code

from primefac import isprime, primes
from itertools import product  # cartesian product

'''
Circular primes
Project Euler: Problem 35

The number, 197, is called a circular prime because all rotations of the digits: 197, 971, and 719, are themselves prime.

There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97.

How many circular primes are there below one million?
'''

def lst_2_int(lst):
    return int(''.join(map(str, lst)))

def is_circular(p):
    return all(isprime(lst_2_int(p[i:]+p[:i])) for i in range(len(p)))

def is_circular_2(p):
    for i in range(len(p)):
        if not isprime(lst_2_int(p[i:]+p[:i])):
            return False
    return True

def repunit(k):
    return (10**k-1)//9

def find_circular_primes_under(digits):

    if type(digits) != int or digits <= 0:
        raise ValueError(
            "Error: power needs to be a positive integer, 10^input")

    circular_lst = []
    # Circular primes under 10
    total = 0
    for k in xrange(10):
        if isprime(k):
            circular_lst.append(k)

    # Circular primes under 10^6
    for k in xrange(2, min(digits+1, 7)):
        for combo in product([1, 3, 7, 9], repeat=k):
            if is_circular_2(list(combo)):
                circular_lst.append(lst_2_int(combo))

    # All circular primes over 10^6 are repunit primes (1...1 where ... =
    # index)
    if digits > 6:
        prime_lst = primes(digits+1)
        # All repunit primes have a prime number of digits
        for prim in prime_lst[3::]:
            if isprime(repunit(prim)):
                circular_lst.append('1 ... 1 ['+str(prim)+']')
    return circular_lst

if __name__ == '__main__':

    circular_primes = find_circular_primes_under(400)
    for prim in circular_primes:
        print prim
    print "Found a total of", len(circular_primes), 'circular primes.'


texts: Writing huge 2D vectors to text file too slow

texts:
I have 10 large (34 million cell) 2D gridded vectors storing doubles. When written they are over 200 MB in size. I use an ofstream object to write them to a text file (.csv format), one element at a time, using two for loops (one for my rows, one for my columns). They take way to long to write. Is there a faster way to write from these vectors?

(I am using Visual Studio 2012.)

// Resizing of vectors
flowDirGrid.resize(rows, std::vector<double>(cols, NODATA));

// Do some processing
....

// Outputting processed data
ofstream outfile3("FlowDir.dat");
if(!outfile3.good())
    return;

for(int i=0; i<rows; i++)
    {
        for (int j=0; j<cols; j++)
        {
            if(elevation[i][j]!=NODATA)
                outfile3 << flowDirGrid[i][j]<<" ";
            else
                outfile3 << NODATA<<" ";
        }
        outfile3 << std::endl;
    }

outfile3.close();


texts:
I made a simple Mastermind clone and I'd just like some tips on what I could do better/different solutions for what I have already coded. If you're wondering what mastermind is, there are, for the original, 6 different colors and 4 different holes. I decided to make this since I had made mastermind in other things so I thought it would be a good starter project in C#.

static void Main(string[] args)
    {
        Random GenRandom = new Random();
        int t = 0, r, c1 = GenRandom.Next(1, 6), c2 = GenRandom.Next(1, 6), c3 = GenRandom.Next(1, 6), c4 = GenRandom.Next(1, 6);
        bool w = false;
        string Input, Code = Convert.ToString(c1); Code += c2; Code += c3; Code += c4;
        while (t != 8) {
            t++;
        Unepic:
            Console.Clear();
            Console.WriteLine("You have {0} turn(s) left.",9-t);
            Console.WriteLine("Guess the code E.g 1561: ");
            Input = Console.ReadLine();
            if (Input.Length != 4) goto Unepic; // Checks if input is 4 characters long
            try { Convert.ToInt16(Input); Convert.ToString(Input); } catch (FormatException) { goto Unepic; } // Checks if input is only numbers
            if (Input == Code) { w = true; goto End; }; // Checks if you've won
            if (Input.Contains("0") || Input.Contains("7") || Input.Contains("8") || Input.Contains("9")) { goto Unepic; } // Checks if it has any digits that are 0 or above 7
            r = -1;
            while (r != 3)
            {
                r++;
                if (Input[r] == Code[r]) Console.Write(1); else Console.Write(0); // Checks if a digit of the input is equal to a digit of the code
            }
            Console.WriteLine();
            Console.Write("Press any key to continue.");
            Console.ReadKey(true);
        }
        End:;
        Console.Clear();
        if (w == true) { Console.WriteLine("You won! The code you guessed was {0}.", Code); } else { Console.WriteLine("You lost! The code you couldnt guess was {0}.",Code); };
        Console.ReadKey(true);


texts:
The following code is aimed to establish a WSL based LAMP environment.

This is instead XAMPP or WAMPP based LAMP environment which doesn't allow Bash.

The script includes a cat heredocument called "AWSM" (Apache Webapp Substrate Maker) that is used to make an Apache conf file for the app, as well as a mySQL user and DB with the same name (you can then run it with your domain as an argument (for example, the domain of the actual site your run in WSL as a test version):

/etc/apache2/sites-available/awsm example-1.com example-2.com example-3.com

I would like to have your opinion on the entire code as I might lack some security there (maybe I must delete OpenSSH, do some other stuff).

apt-get update -y && apt-get upgrade tree zip unzip lamp-server^ phpmyadmin -y
a2enmod mcrypt ; a2enmod mbstring ; a2enmod rewrite ; a2enmod deflate ; a2enmod headers; a2enmod expires

cat <<-AWSM > /etc/apache2/sites-available/awsm
    #!/bin/sh
    for domain; do
      cat <<-EOF > /etc/apache2/sites-available/${domain}.conf
          <VirtualHost *:80>
              DocumentRoot "/var/www/html/${domain}"
              ServerName "${domain}"
              <Directory "/var/www/html/${domain}">
              Options +SymLinksIfOwnerMatch
              Require all granted
              </Directory>
              ServerAlias www.${domain}
          </VirtualHost>
      EOF
      a2ensite "${domain}"
    done
    systemctl restart apache2.service
    echo "Please enter password for user ${domain}: "; read -s waps
    mysql -u root -p <<-MYSQL
        create user "${domain}"@"localhost" identified by "${waps}";
        create database ${domain};
        GRANT ALL PRIVILEGES ON ${domain}.* TO ${domain}@localhost;
    MYSQL
AWSM
chmod +x /etc/apache2/sites-available/awsm

Update

I should clarify that I don't have XAMPP/WAMP or even individual Apache or PHP on Windows outside of WSL; I aim to have only 1 LAMP stack in my Windows, inside WSL.

Besides having a fully functional WSL LAMP stack on Windows, the end state is to be able to access it from localhost in any Windows browser so I could easily test the sites and access PHPmyadmin locally.

Also, anyone is more than welcome to contribute directly in Github