texts: Rails Grape API Endpoint optional params validation in update

texts:
I have the following rails grape api endpoint in the users resource:

    desc 'updates a user'
    params do
      optional :first_name, type: String
      optional :active, type: Boolean
      optional :second_name, type: String
      optional :rating, type: Integer
      requires :id, type: Integer
    end
    put ':id' do
      user = User.find_or_create_by(id: params[:id])
      user.name = params[:name] if params[:name].present?
      user.active = params[:active] if params[:active].present?
      user.second_name = params[:second_name] if params[:second_name].present?
      user.rating = params[:rating] if params[:actratingve].present?
      user.save!
    end

Any nicer way to update model without asking per line if the param is present?


texts:
I need something akin to C++'s shared_ptr. Essentially I need an IDisposable item that I can ensure is cleaned up as soon as possible once all references have been removed, but this resource will be shared between many classes.

I don't allow passing in of a an already existing object as it's an easy way to know that the item I'm using isn't being hasn't already been disposed.

Unfortunately I can't think of a way to prevent the user of Item from disposing the underlying item, but as this is to go into my own program I'm not too concerned about that because it intuitively makes sense to not dispose something within a wrapper, provided every class that needs the item uses the wrapper and not just the contained item.

I simply want to know if anyone can see any potential issues with this solution besides what's mentioned.

public class SharedDisposable<T> : IDisposable where T : class, IDisposable {
    static SharedDisposable(){
        instances = new Dictionary<T, List<SharedDisposable<T>>>();
    }

    public SharedDisposable(SharedDisposable<T> share) {
        Item = share.Item;
        instances[Item].Add(this);
    }
    public SharedDisposable(object[] ctorArgs = null) {
        if(ctorArgs == null)
            ctorArgs = new object[] { };

        var ctor = typeof(SharedDisposable<T>).GetConstructor(ctorArgs.Select(a => a.GetType()).ToArray());
        Item = (T)ctor.Invoke(ctorArgs);
        instances[Item] = new List<SharedDisposable<T>>() { this };
    }
    public SharedDisposable(KeyValuePair<Type, object>[] ctorArgs) {
        var ctor = typeof(SharedDisposable<T>).GetConstructor(ctorArgs.Select(a => a.Key).ToArray());
        Item = (T)ctor.Invoke(ctorArgs.Select(a => a.Value).ToArray());
        instances[Item] = new List<SharedDisposable<T>>() { this };
    }

    public void Dispose() {
        var instanceList = instances[Item];
        instanceList.Remove(this);
        if(instances.Count == 0) {
            instances.Remove(Item);
            Item.Dispose();
        }
    }

    public T Item { get; }
    static Dictionary<T, List<SharedDisposable<T>>> instances;
}

Example usage:

class MainForm : Form {
    public MainForm(){
        InitializeComponent();

        Port = new SharedDisposable<SerialPort>("COM5", 9600);
    }
    public MainForm(SharedDisposable<SerialPort> share){
        InitializeComponent();

        if(share == null)
            throw new ArgumentNullException(nameof(share))
        Port = new SharedDisposable<SerialPort>(share);
    }

    public void BtnDevice1Info_Click(object sender, EventArgs e){
        new Device1InfoForm(Port).Show();
    }
    public void BtnDevice2Info_Click(object sender, EventArgs e){
        new Device2InfoForm(Port).Show();
    }

    override Dispose(bool disposing){
        if(disposing){
            Port.Dispose();
        }
        base.Dispose(disposing);
    }

    private SharedDisposable<SerialPort> Port { get; }
}

In my application I actually have a Modbus interface instead of serial port but I just realised the way the constructor is setup won't allow me to use the Modbus API because the Modbus API uses factories instead of constructors, so I'll need to adjust it for that.
But that API should be able to queue messages to be sent out one at a time, preventing any conflicts on the serial port while also allowing multiple forms or even applications to use the same serial port. In order to make this happen I need multiple forms to be able to share a disposable resource, but none of them to clean it up unless they're the last holder of that resource.


texts: Refactoring and condensing a Javascript function with many repeat conditions, strings, and variables

texts:
I have this function which is pretty easy to read and works just fine. I'm looking to advance my coding abilities by writing more concise code, though.

Does anyone know of an elegant way to condense this down? Any pointers very much appreciated! Thank you!

var $_GET = {};

document.location.search.replace(/\??(?:([^=]+)=([^&]*)&?)/g, function () {
    function decode(s) {
        return decodeURIComponent(s.split("+").join(" "));
    }

    $_GET[decode(arguments[1])] = decode(arguments[2]);
});

function create_filter_input($name, $termname) {
    var $input = '<input class="query-input" type="hidden" value="' + $termname + '" name="' + $name + '" />';
    return $input;
}

area = $_GET["area"],
type = $_GET["property_type"],
style = $_GET["style"],
feature = $_GET["feature"],

if(area || type || style || feature) {
    if(area) {
        areainput = create_filter_input('area',area);
        $filterTerms.append(areainput);
    }

    if(type) {
        typeinput = create_filter_input('property_type',type);
        $filterTerms.append(typeinput);
    }

    if(style) {
        styleinput = create_filter_input('style',style);
        $filterTerms.append(styleinput);
    }

    if(feature) {
        featureinput = create_filter_input('feature',feature);
        $filterTerms.append(featureinput);
    }
}

This is my current solution based on your answers! I think it's pretty concise. Let me know what you think! thanks again.

function create_filter_input($name, $termname, $filterterms) {
    if($termname) {
        var $input = '<input class="query-input" type="hidden" value="' + $termname + '" name="' + $name + '" />';
        $filterterms.append($input);
    }
}

create_filter_input('area',area,$filterTerms);
create_filter_input('property_type',type,$filterTerms);
create_filter_input('style',style,$filterTerms);
create_filter_input('feature',feature,$filterTerms);


texts: Lexer function to handle the '/' character

texts:
I'm writing a toy compiler, which is in a very early stage of development.  The lexer contains the following block of code:

    let consumeChar (state: LexerState) =
        match state.CurrentChar() with
        | End -> state
        | _   -> { state with Offset = state.Offset + 1u }

    let tryConsume (ch: char) (state: LexerState) =
        if state.CurrentChar() = Regular ch
        then Success <| consumeChar state
        else Failure state

    // ...

    let onForwardSlash() =
        let onUnterminatedMLComment = ...

        state |> consumeChar
              // Line comment
              |> tryConsume '/'
              |> andThenSuccess (consumeToEndOfLine >> lexToken)
              // Multiline comment
              |> orElse (tryConsume '*'
                         >> andThen (consumeTo "*/"
                                     >> andThenSuccess lexToken
                                     >> orElseSuccess onUnterminatedMLComment))
              // Just a forward slash
              |> orElseSuccess (LexingResult.T (Punctuator Slash) start)

Where andThen, orElse and friends are defined like this:

type TryResult<'fail, 'res> =
    | Failure of 'fail
    | Success of 'res

let orElse next tryResult =
    match tryResult with
    | Success res  -> Success res
    | Failure cont -> next cont

let andThen next tryResult =
    match tryResult with
    | Success cont -> next cont
    | Failure fail -> Failure fail

let orElseSuccess f tryResult =
    match tryResult with
    | Success res  -> Success res
    | Failure cont -> Success <| f cont

let andThenSuccess f tryResult = ...

I arrived at this code "naturally" while trying to reduce duplication in the previous version. And the current version is shorter and seems less noisy indeed.

A little later, I stumbled across a blog post which discourages point-free style of programming.
And my code seems to be in a style quite similar to point-free. So it got me thinking. Briefly looking through the sources of FAKE, Paket, Suave, and FSharp compiler itself, they seem to keep function composition usage to a minimum.

Hence the question: Is the onForwardSlash function's code abusing function composition/point-free style?

(I know about FsLexxYacc and FParsec. This question is about code style, not implementing a lexer)


texts:
In this question I answered with this Linq. While it does what I was looking for, I am not sure how easy the linq queries are for others to follow. So I am looking for feedback on formating, what comments would be helpful and other alternative approaches to moving through the children records.

    private void UpdateGridFromSourceHierarchy(int depth, IEnumerable<SourceFile> list)
    {

        //Get the initial set of sourcefiles
        var sourceFiles = list
            .SelectMany(current => current.getInvocations()
                                .Select(invocation => new {current = (SourceFile) null, invocation}))
            .ToList() //This ensures that getInvocations is only called once for each sourcefile
            .GroupBy(x => x.current, x => x.invocation);

        for (var currentDepth = 0; currentDepth <= depth; currentDepth++)
        {
            foreach (var currentGroup in sourceFiles)
            {
                int sourceFileCount = currentGroup.Count();
                int counter = 0;

                foreach (var invocation in currentGroup)
                {
                    /*
                     * Generalized grid code goes here
                     * In my code it was a call to:
                     * UpdateGridPosition(currentGroup,invocation,counter);
                     */
                    counter++;
                }
            }

            //Select the current sub source files
            sourceFiles = sourceFiles.SelectMany(current => current.Select(invocation => invocation))
                //Get all of the invocations paired with the new current level of source files
                .SelectMany(newCurrent => newCurrent.getInvocations()
                                     .Select(invocation => new { newCurrent, invocation }))
                //Group them so that we can loop through each set of invocations seperately
                .ToList().GroupBy(x => x.newCurrent, x => x.invocation);
        }
    }


texts: spaghetti code for lunch: refactoring a bunch of fields that always get initialized

texts:
blah - not even sure if that is the correct way to say it. Basically I have this

public class XmlAccess
{
    public XmlAccess() { }

    public string ApplicationPath = "";

    public string DBServer = ConfigurationManager.AppSettings["DB2_Server"];
    public string DBName = ConfigurationManager.AppSettings["DB2_Database"];
    public string DBLogIn = ConfigurationManager.AppSettings["DB2_User"];
}

I am trying to create some seams for some unit tests and have pulled out a lot of interfaces which is great but I have this thing (code above) trying to initialize all these fields (that's just a sample - it goes on and on...) when it fires up. Anyone have any suggestions as to how to refactor this? I have never had to do this sort of major refactor of "old code" but I am sure others have. The way it is handling those variables is silly and untestable but I am not sure what to do about it and it's holding me up.


texts:
I am building an ASP.NET MVC 5 application and, for reasons which are irrelevant at this point, I am attempting to build my own means of authenticating users. I'm still very new to programming, especially to this sort of thing, and I realize that what looks fine to me may be full of problems. Thus, I present my code, simplified for demonstration purposes, for review.

The Contact model:

public class Contact
{
    [Key]
    public int ContactID { get; set; }

    [Required]
    public string Email { get; set; }

    [Required]
    public string Password { get; set; }
}

The Login action:

[HttpPost]
public ActionResult Login(Contact contact)
{
    bool validEmail = db.Contacts.Any(x => x.Email == contact.Email);

    if (!validEmail)
    {
        return RedirectToAction("Login");
    }

    string password = db.Contacts.Where(x => x.Email == loginForm.Email)
                                 .Select(x => x.Password)
                                 .Single();

    bool passwordMatches = Crypto.VerifyHashedPassword(password, loginForm.Password);

    if (!passwordMatches)
    {
        return RedirectToAction("Login");
    }

    string authId = Guid.NewGuid().ToString();

    Session["AuthID"] = authId;

    var cookie = new HttpCookie("AuthID");
    cookie.Value = authId;
    Response.Cookies.Add(cookie);

    return RedirectToAction("Private");
}

Actions that require the user to be logged in will look like this:

public ActionResult Private()
{
    try
    {
        if (Request.Cookies["AuthID"].Value == Session["AuthID"].ToString())
        {
            return View();
        }
        else
        {
            return RedirectToAction("Index");
        }
    }
    catch
    {
        return RedirectToAction("Index");
    }
}

I feel like this is probably really bad. However, every "solution" I find seems overly complex and/or lacking any documentation that would allow me to make sense of it.

All I want is to make sure the user has a valid username and password before they place an order or update their account. Will my code do that securely?


texts: Brainfuck interpreter (with emphasis on robustness)

texts:
While writing a review of @MotokoKusanagi's Brainfuck interpreter, I decided to write my own implementation to illustrate a few points.  In particular, I'd like it to be robust to malformed programs, and reasonably efficient (short of JITting the Brainfuck code).

Please point out any deficiencies you might find in this implementation.

#include <fcntl.h>
#include <libgen.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <unistd.h>

typedef struct {
    char *begin,            // Pointer to beginning of program
         *end,              // Pointer just beyond the end of the program
         **jumps;           // Pointer to jump table
} program;

/**
 * Fills in p.jumps, the jump table.  For each '[' or ']' character
 * in the code, the pointer at the corresponding offset in p.jumps
 * is set to the matching ']' or '[' (or NULL if it is mismatched).
 * This function calls itself recursively to handle nesting.
 */
static char *build_jump_table(program p, char *begin) {
    char *c = begin;
    while (c < p.end) {
        ptrdiff_t i = c - p.begin;
        switch (*c) {
          case '[':
            p.jumps[i] = NULL;      // In case no matching ']' is ever found
            p.jumps[i] = c = build_jump_table(p, c + 1);
            if (!c) return NULL;    // Error: no closing bracket
            break;
          case ']':
            p.jumps[i] = (begin > p.begin) ?
                begin - 1 :         // Normal case
                NULL;               // Error: no opening bracket
            return c;
        }
        c++;
    }
    return NULL;
}

/**
 * Loads the program from the specified path.  On failure, all members of
 * the returned program will be NULL, and errno is set.
 */
program load_program(const char *path) {
    const program FAILURE = { .begin = NULL, .end = NULL, .jumps = NULL };
    int fd;
    struct stat stat_buf;
    if ( -1 == (fd = open(path, O_RDONLY)) ||
         -1 == fstat(fd, &stat_buf) ) {
        return FAILURE;
    }
    int size = stat_buf.st_size;
    char *text = malloc(size);
    if ( (text == NULL) || (size != read(fd, text, size)) ) {
        free(text);
        close(fd);
        return FAILURE;
    }
    close(fd);
    program p = { .begin = text, .end = text + size, .jumps = malloc(size) };
    if (p.jumps == NULL) {
        free(text);
        return FAILURE;
    }
    build_jump_table(p, p.begin);
    return p;
}

void free_program(program p) {
    free(p.jumps);
    free(p.begin);
}

int execute_program(program p) {
    unsigned char mem[30000] = { 0 };
    unsigned char *ptr = mem;
    char *ip = p.begin;
    while (ip < p.end) {
        ptrdiff_t i = ip - p.begin;
        switch (*ip) {
            case '<': if (--ptr < mem) return i + 1;                    break;
            case '>': if (++ptr >= mem + sizeof mem) return i + 1;      break;
            case '-': (*ptr)--;                                         break;
            case '+': (*ptr)++;                                         break;
            case '.': putchar(*ptr); fflush(stdout);                    break;
            case ',': *ptr = getchar();                                 break;
            case '[': if (!*ptr) ip = p.jumps[i];                       break;
            case ']': if ( *ptr) ip = p.jumps[i];                       break;
        }
        if (!ip++) {
            return i + 1;
        }
    }
    return 0;
}

void usage(FILE *f, char *argv[]) {
    fprintf(f, "Usage: %s PROGRAM.bf\n", basename(argv[0]));
}

int main(int argc, char *argv[]) {
    if (argc <= 1) {
        usage(stderr, argv);
        return 1;
    }
    program prog = load_program(argv[1]);
    if (!prog.begin) {
        perror("Error: Could not load program");
        return 2;
    }
    int error_offset = execute_program(prog);
    if (error_offset > 0) {
        fprintf(stderr, "Error at offset %d\n", error_offset);
    }
    free_program(prog);
}


texts: Handling an openFileDialog in the View of my MVP WinForms project

texts:
I have a WinForms project in which I am trying to implement the Passive View MVP pattern (meaning no business logic in my Views). Each form is a concrete View with an IView interface to which a Presenter is connected.

I do think i should handle some UI related logic in my View because I am otherwise adding needless complexity to try to handle this in the Presenter. Therefore, I have created a simple function in my View class which validates the result from the file dialog. I did not put this logic in the event handler of the button press because I wanted to avoid duplicate code since I have three of these buttons.

Please let me know if you think this is an appropriate way to implement this. I have posted the function, and the event (I have three button_Click events that each use this function) that utilizes this function below.

Button event that uses the GetFileName function:

// Gets the filename and fires the compliance standard adding event.
private void newComplianceStandardButton_Click(object sender, EventArgs e)
{
    string fileName = GetFileName();

    if (fileName != null)
    {
        AddingComplianceStandard?.Invoke(this, fileName);
    }

    Close();
}

Function that checks the dialog result and returns the filename:

// Opens the openfile dialog and checks the result. If the result is OK, the form is closed and the filename is returned.
public string GetFileName()
{
    DialogResult result = openFileDialog1.ShowDialog();
    string fileName = openFileDialog1.FileName;

    if (result == DialogResult.OK &&
        (Path.GetExtension(openFileDialog1.FileName) == ".txt" || Path.GetExtension(openFileDialog1.FileName) == ".csv"))
    {
        Close();
        return fileName;
    }
    else
    {
        MessageBox.Show("You have selected a file with an illegal extension. Please try again and select a *.txt or a *.csv file");
        return null;
    }
}


texts: Using Wreq and Lens libraries to query Prosper for account info

texts:
I am trying to create a program to manage my Prosper investments for me as an intro to Haskell project.  I created a post a few weeks ago for some of the simpler backend calculations: Recommend Next Note Purchase

Now I've started working on the web APIs in order to retrieve my account information from Prosper. Though it may not look it, the code below has already undergone some major refactoring to attempt to bring it to slightly readable.

This is my first attempt at any RESTful service interaction, JSON parsing, and usage of Lens.  I have a few areas of this code I would really appreciate some feedback.

I feel like I really went overboard with the let bindings, but I couldn't figure out how to break up some absurdly long lines in another way.
All my maybeXXX functions.  I needed them to operate on the Maybe typeclass in the way I was expecting, but I feel like there is a more elegant use of Monads that could avoid these auxiliary functions.
The creation of the MResult type was done just to parse the response body of the web API.  There must be a way to use Lens to extract that field and parse it as a list of Note directly.

Any other feedback on the general structure or style of the code is greatly appreciated.

{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DeriveGeneric #-}

import Prosper
import Network.Wreq
import Control.Lens
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy.Internal as BL
import qualified Data.Text as T
import Data.Text.Encoding
import Data.Aeson
import Data.Aeson.Lens
import GHC.Generics

data Note = Note {
    loan_number :: Int,
    prosper_rating :: T.Text
    } deriving (Generic, Show)
instance FromJSON Note

data MResult = MResult {
    result :: [Note]
    } deriving (Generic, Show)
instance FromJSON MResult

-- String Constants
prosperAddress = "https://api.prosper.com/v1/"
authTarget = "security/oauth/token"
accountTarget = "accounts/prosper/"
notesTarget = "notes/"
clientID = "cicicicici"
clientSecret = "ssssssssssssssss"
userID = "uuuuuuuuuu"
password = "pppppppppp"

body :: BS.ByteString
body =  strToBS $
            "grant_type=password" ++
            "&client_id=" ++ clientID ++
            "&client_secret=" ++ clientSecret ++
            "&username=" ++ userID ++
            "&password=" ++ password
    where strToBS = encodeUtf8 . T.pack

-- Retrives the OAuth2 token from the Prosper server
oauthToken :: IO T.Text
oauthToken = do
    let opts = defaults & header "Accept" .~ ["application/json"]
                        & header "Content-type" .~ ["application/x-www-    form-urlencoded"]
    resp <- postWith opts (prosperAddress ++ authTarget) body
    return $ resp ^. responseBody . key "access_token" . _String

-- Performs a GET request to the provided target using the provided OAuth     token
getTarget target token = do
    let tokenStr = encodeUtf8 $ T.append "bearer " token
    let opts = defaults & header "Authorization" .~ [tokenStr]
    getWith opts (prosperAddress ++ target)

-- Retrives the list of currently owned notes from Prosper
-- Note: The query responses are paginated to 25 results per response
getNotesList :: T.Text -> Int -> IO [T.Text]
getNotesList token offset = do
    let target = notesTarget ++ "?offset=" ++ (show offset)
    resp <- getTarget target token
    let r =  fmap result (decode $ resp ^. responseBody :: Maybe MResult)
    let notes = fmap (map prosper_rating) r
    if (maybeLength notes) /= 25 then
        maybeReturn notes
        else do
            restOfNotes <- getNotesList token (offset+25)
            return $ maybeAppend notes restOfNotes

maybeLength Nothing = 0
maybeLength (Just xs) = length xs

maybeReturn Nothing = return []
maybeReturn (Just xs) = return xs

maybeAppend :: Maybe [a] -> [a] -> [a]
maybeAppend Nothing xs = xs
maybeAppend (Just ys) xs = ys ++ xs

main = do
    token <- oauthToken
    notes <- getNotesList token 0
    print $ recommendNote notes [0,0,0.2,0.2,0.25,0.30,0.05]


texts:
I wrote a function that allow me to read a binary file using 3 blocks what ever the length of file.

I've decided to divide the length of my file into 3:

  block 1: ______________

  block 2: ______________

  block 3: ____

As you can see, this is almost the length of the 3 blocks that I will have using my function.

(What is important for me is to read all characters in my file)

vector< vector<char> >  ReadByBlock(string fileName){

ifstream is (fileName, ifstream::binary);

if (is) {
is.seekg (0, is.end);
int length = is.tellg();
is.seekg (0, is.beg);

cout << "Reading " << length << " characters... "<<endl;
const int bloc = 1+length/3;
vector< vector<char> > vect (3,vector<char>(bloc,0));      // create vector of 3 vector of(1+length/3) chars with value 0

    for(size_t j=0;j<3;++j)
    {
        is.read(&vect[j][0], bloc);
        for(size_t i=0;i<bloc;++i)
            cout << " buf ["<<j<<","<<i<<"]: "<<vect[j][i] << endl;
    }

 return vect;}}

Because I'm beginner in the world C++ and because I'm thinking about Java while programming my function, I want to know if it is an efficient function that respects the rules of C++ as well the structure of coding using C++.


texts: Rotate every letter in string by K places

texts:
The challenge:
Given a string S and a fixed number K, rotate every letter in S by K places (if reach the end of the alphabet, go back to the beginning). Letters should remain the same case. Symbols should remain unencrypted.

Constraints:
K is between 0 and 100. S is a valid ASCII string without spaces, between 1 and 100 letters long.

Input:
The first line contains an integer, N , which is the length of the unencrypted string.
The second line contains the unencrypted string, S.
The third line contains the integer encryption key, K, which is the number of letters to rotate.

I'd appreciate any comments and suggestions as to how my code can be improved.

var lowerString = "abcdefghijklmnopqrstuvwxyz";
var lower = lowerString.split("");

var upperString = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var upper = upperString.split("");

function main() {
    var n = parseInt(readLine());
    var s = readLine();
    var k = parseInt(readLine());

    printCipher(s, k);
}

function printCipher(str, key){
    var newStr = "";
    str.split("").forEach(function(elem, index){
        var changedItem = cipher(elem, key);
        newStr += changedItem;
    });
    console.log(newStr);
}

function cipher(item, key){
    var arrToUse = null;
    if(lower.indexOf(item) >= 0){
        arrToUse = lower;
    }
    else if (upper.indexOf(item) >= 0){
        arrToUse = upper;
    }
    if(arrToUse !== null){
        var pos = arrToUse.indexOf(item);
        var newPos = getCipherPosition(pos, key);
        return arrToUse[newPos];
    }
    return item;
}

function getCipherPosition(pos, key){
    const ALPHA_COUNT = 26;
    if(key > ALPHA_COUNT){
        key = key % ALPHA_COUNT;
    }

    if(pos + key >= ALPHA_COUNT){
       return key + pos - ALPHA_COUNT;
    }
    return key + pos;
}


texts: Passing Array into Unmanaged Code for Modification

texts:
I have an array allocated in C# which I am passing into unmanaged code to be modified. The following code works, but I am not sure if there are any other more 'correct' or 'efficient' methods that I am not aware of.

Code.c

extern "C" {
    class MyObject
    {
    public:
        int32_t X;
    };

    __declspec(dllexport) void ArrayTest(MyObject* a, int length);

    void ArrayTest(MyObject* a, int length)
    {
        for (int i = 0; i < length; i++)
        {
            a[i].X = i + 1;
        }
    }
}

Code.cs

class Program
{
    [StructLayout(LayoutKind.Sequential)]
    public struct MyObject
    {
        public Int32 X;
    }

    [DllImport(@"MyDll.dll", CallingConvention = CallingConvention.Cdecl)]
    public extern static void ArrayTest(IntPtr objects, int length);

    static void Main(string[] args)
    {
        var objects = new MyObject[3];

        var handle = GCHandle.Alloc(objects, GCHandleType.Pinned);
        var ptr = GCHandle.ToIntPtr(handle);

        ArrayTest(ptr, objects.Length);

        for (int i = 0; i < objects.Length; i++)
        {
            var offset = Marshal.SizeOf<MyObject>() * i;

            objects[i] = Marshal.PtrToStructure<MyObject>(IntPtr.Add(ptr, offset));
        }
    }
}


texts:
This is a follow up for C++ Fast Fourier transform . I did end up changing the algorithm slightly to reduce the memory usage.
#include <vector>
#include <iostream>
#include <complex>
#include <cmath>
#include <algorithm>

#define N 1048576 // Problem size, must be a power of 2
#define PI 3.14159265358979323846

typedef std::vector<std::complex<double>> complexVec;

/*
Calculates the N'th roots of unity.
*/
complexVec rootsOfUnityCalculator() {
    complexVec table;
    table.resize(N);

    for (size_t k = 0; k < N; k++) {
        table[k] = std::complex<double>(std::cos(-2.0 * PI * k / N), std::sin(-2.0 * PI * k / N));
    }

    return table;
}

/*
Permutes an input vector of size length - a power of 2 - according
to the bit reversal permutation.

TESTED: SUCCESS
*/
void bitReversal(complexVec& input) {
    std::vector<size_t> permutation;
    permutation.resize(N);

    permutation[0] = 0;
    size_t k = 2;

    // Calculating the permutation according to recursive relation
    while (k <= N) {
        for (size_t j = 0; j < k / 2; j++) {
            permutation[j] *= 2; // permutation_k(j) = 2 * permutation_(k/2)(j)
            permutation[j + k / 2] = permutation[j] + 1; // permutation_k(j + k/2) = 2 * permutation_(k/2)(j) + 1
        }
        k *= 2;
    }

    // Permute the input
    for (size_t j = 0; j < N; j++) {
        if (j < permutation[j]) {
            std::swap(input[j], input[ permutation[j] ]);
        }
    }
}

void unorderedFFT(complexVec& input, const complexVec& table) {
    size_t k = 2;

    while (k <= N) {
        for (size_t r = 0; r < N / k; r++) {
            for (size_t j = 0; j < k / 2; j++) {
                std::complex<double> plusMinus = input[r * k + j + k / 2] * table[N / k * j]; // omega_k^j = (omega_N^(N/k))^j = omega_N^(Nj/k)
                input[r * k + j + k / 2] = input[r * k + j] - plusMinus;
                input[r * k + j] += plusMinus;
            }
        }

        k *= 2;
    }
}

/*
Calculates the FFT

TESTED: SUCCESS
*/
void FFT(complexVec& input, const complexVec& table) {
    bitReversal(input);
    unorderedFFT(input, table);
}

// Prints array of N complex numbers
void printArray(complexVec& array) {
    for (size_t k = 0; k < N - 1; k++) {
        std::cout << array[k] << ", ";
    }

    std::cout << array[N - 1] << std::endl;
}

int main() {
    complexVec input;
    input.resize(N);

    // Initialize the input to all 0, 1, ..., N
    for (size_t k = 0; k < N; k++) {
        input[k] = std::complex<double>(k, 0.0);
    }

    const complexVec table = rootsOfUnityCalculator();

    FFT(input, table);
}


texts:
I'm trying to get this to run faster, even marginally so. Right now to update 470 rows it takes about 90 seconds. It works, but I know there are better ways. I understand calls to Spreadsheet API are slow, and batching getRanges and setValues would speed things up, but doesn't seem obvious given the brief bit I know.
function setDates() {

var app = SpreadsheetApp;
var ssData = app.getActiveSpreadsheet().getSheetByName("Data");

//Calculates due dates based on entered dates in column D
  for (var i=4; i<=ssData.getLastRow(); i++)  {                                     //cycles through all 18 pilots
    for(var j=0; j<25; j++) {                                                       //cycles through an individuals' 25 training items
    var dateCompleted = new Date(ssData.getRange(i+j,4).getValue());                //date of training completed
    var interval = ssData.getRange(i+j,5).getValue();                               //interval in months between date complete and date due
    var monthCompleted = dateCompleted.getMonth();
    var yearCompleted = dateCompleted.getFullYear();

      if (!isNaN(parseFloat(yearCompleted)) && !isNaN(interval)) {                  //checks to see if vars year and interval are numbers
      var dateDue = new Date(dateCompleted.setMonth((monthCompleted + interval)));  //date of training due
      var yearDue = dateDue.getFullYear();
      var monthDue = dateDue.getMonth();
      dateDue = new Date(yearDue, monthDue+1, 0);
      ssData.getRange(i+j,6).setValue(new Date(dateDue));                           //sets dateDue in column F
      }
    }
    i = i + 25;
  }
}


texts: Convert between date/time and time-stamp without using standard library routines

texts:
I am trying to implement two simple convertors: date/time to time-stamp and vice-versa, without any dependencies on time library routines (such as localtime, mktime, etc, mainly due to the fact that some of them are not thread-safe).

I have the following date/time structure:

typedef struct
{
    unsigned char second; // 0-59
    unsigned char minute; // 0-59
    unsigned char hour;   // 0-23
    unsigned char day;    // 1-31
    unsigned char month;  // 1-12
    unsigned char year;   // 0-99 (representing 2000-2099)
}
date_time_t;

I would like to have a second opinion on the following conversion routines (given a legal input):

static unsigned short days[4][12] =
{
    {   0,  31,  60,  91, 121, 152, 182, 213, 244, 274, 305, 335},
    { 366, 397, 425, 456, 486, 517, 547, 578, 609, 639, 670, 700},
    { 731, 762, 790, 821, 851, 882, 912, 943, 974,1004,1035,1065},
    {1096,1127,1155,1186,1216,1247,1277,1308,1339,1369,1400,1430},
};

unsigned int date_time_to_epoch(date_time_t* date_time)
{
    unsigned int second = date_time->second;  // 0-59
    unsigned int minute = date_time->minute;  // 0-59
    unsigned int hour   = date_time->hour;    // 0-23
    unsigned int day    = date_time->day-1;   // 0-30
    unsigned int month  = date_time->month-1; // 0-11
    unsigned int year   = date_time->year;    // 0-99
    return (((year/4*(365*4+1)+days[year%4][month]+day)*24+hour)*60+minute)*60+second;
}

void epoch_to_date_time(date_time_t* date_time,unsigned int epoch)
{
    date_time->second = epoch%60; epoch /= 60;
    date_time->minute = epoch%60; epoch /= 60;
    date_time->hour   = epoch%24; epoch /= 24;

    unsigned int years = epoch/(365*4+1)*4; epoch %= 365*4+1;

    unsigned int year;
    for (year=3; year>0; year--)
    {
        if (epoch >= days[year][0])
            break;
    }

    unsigned int month;
    for (month=11; month>0; month--)
    {
        if (epoch >= days[year][month])
            break;
    }

    date_time->year  = years+year;
    date_time->month = month+1;
    date_time->day   = epoch-days[year][month]+1;
}

I have tested this on an extensive amount of legal input (between 01/01/2000 and 31/12/2099). Any constructive comments would be appreciated (performance improvement suggestions, readability, etc).


texts: Permutations with repetitions algorithm in R

texts:
Given a string of length n, print all permutation of the given string.

The code bellow generates all permutations (with repetitions) for the given string and stores them in object res. Could you suggest ways to make the code faster (or a completely different algorithm written in R)? (For the "ABRACADABRA" word it takes more than 9 minutes to complete)

#############################################################
word <- "ABRACADABRA"
#############################################################

vec <- unlist(strsplit(word,""))
charTable <- sort(table(vec),decreasing = TRUE)
totChars  <- sum(charTable)

combTable <-choose(c(totChars,totChars-cumsum(charTable)),charTable)
combTable <-combTable[combTable>0]
names(combTable) <- names(charTable)
totCombs <- prod(combTable)

# initialize res
res <- data.frame(matrix(rep(NA,totCombs*totChars),ncol=totChars))

for(i in 1:length(combTable)){
  totRows <- prod(combTable[1:i])
  copyRows <- prod(combTable[1:(i-1)])

  if (totRows>copyRows){
    tmp <- res[1:copyRows,]
    for(j in 1:(combTable[i]-1)){
      res[(j*copyRows+1):((j+1)*copyRows),] <- tmp
    }
  }

  tmpCombs <- t(combn(ifelse(i>1,totChars-cumsum(charTable)[i-1],totChars), charTable[i]))
  letr <- names(charTable)[i]

  if(i==1){
    for(k in 1:totRows){
      res[k,tmpCombs[k,]] <- letr
    }
  } else if (i>1 & totRows==copyRows){
    for(k in 1:totRows){
      res[k,is.na(res[k,])][tmpCombs[1,]] <- letr
    }
  } else{
    grpRows <- prod(combTable[1:(i-1)])

    for(k in 1 : combTable[i]){
      for(m in ((k-1)*grpRows+1):((k)*grpRows)){
        res[m,is.na(res[m,])][tmpCombs[k,]] <- letr
      }
    }
  }
}


texts:
I am about a month into learning Java and I'm just looking for some comments on my code.  Specifically, I would like to know if I'm being as efficient as I can be.  This is the most complex thing I've come up with so far (that works) and I wanted some feedback on my developing coding style.

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    double numOne, numTwo, numThree, negativeB,
            discriminant, divisor, sqRtDisc, dividendPlus,
            dividendMinus;

    System.out.println("Enter the value for A: ");
    numOne = sc.nextFloat();

    System.out.println("Enter the value for B: ");
    numTwo = sc.nextFloat();

    System.out.println("Enter the value for C: ");
    numThree = sc.nextFloat();

    negativeB = -numTwo;
    discriminant = (numTwo * numTwo) - 4 * numOne * numThree;
    divisor = 2 * numOne;
    sqRtDisc = Math.sqrt(discriminant);

    System.out.println(" ");

    if (sqRtDisc > 0) {
        dividendPlus = ((negativeB + sqRtDisc) / divisor);
        dividendMinus = ((negativeB - sqRtDisc) / divisor);

        System.out.println("x = " + dividendPlus);
        System.out.println("x = " + dividendMinus);
    } else {
        System.out.println("x = " + (negativeB / divisor) + " + "
                + (Math.sqrt(-discriminant) / divisor) + "i");
        System.out.println("x = " + (negativeB / divisor) + " - "
                + (Math.sqrt(-discriminant) / divisor) + "i");
        System.out.println(" ");
    }

}


texts:
This is "homework" from a Swift course, which I'm currently taking. A mockup and the image-assets are provided by the instructor. We are supposed to create the layout and to write some appropriate code.

Here's the code of my ViewController:

import UIKit

class ViewController: UIViewController {
    // MARK: Outlets
    @IBOutlet weak var nameText: UITextField!
    @IBOutlet weak var sizeText: UITextField!
    @IBOutlet weak var weightText: UITextField!

    @IBAction func clickHereButton(_ sender: UIButton) {
        let name = nameText.text!
        let size = Double(sizeText.text!)!
        let weight = Double(weightText.text!)!

        let bmi = weight / pow(size, 2)
        let bmiRounded = (round(bmi * 10) / 10)
        print(bmiRounded)

        let uac = UIAlertController(title: "BMI for \(name)", message: "Your Body-Mass-Index is \(bmiRounded)", preferredStyle: .alert)
        uac.addAction(UIAlertAction(title: "Okay", style: .default))
        self.present(uac, animated: true, completion: nil)
    }
}

What are your thoughts about my implementation? What would you have done differently and why?


texts:
Is there any way to make this work faster?

Here is my sample code in vb.net. This adds a point on a chart at mouse position but it is quite slow.

Private Sub Chart2_MouseMove(sender As Object, e As MouseEventArgs) Handles Chart2.MouseMove

Dim coord() As Double = GetAxisValuesFromMouse(e.X, e.Y)
Dim test As Series
Try
    Chart2.Series.RemoveAt(1)
Catch ex As Exception
End Try

Dim pt As New DataPoint
pt.XValue = coord(0)
pt.YValues(0) = coord(1)

test = New Series
Chart2.Series.Add(test)
Chart2.Series(test.Name).ChartType = SeriesChartType.Point
Chart2.Series(test.Name).Points.Add(pt)

End Sub

Function returns the coordinates of x and y axis at mouse position.

Private Function GetAxisValuesFromMouse(x As Integer, y As Integer) As Double()

Dim coord(1) As Double
Dim chartArea = Chart2.ChartAreas(0)
coord(0) = chartArea.AxisX.PixelPositionToValue(x)
coord(1) = chartArea.AxisY.PixelPositionToValue(y)
Return coord

End Function

Result:


texts: Basic abstract graph implementation in Java

texts:
I am trying to write a graph implementation in Java. I would appreciate it if someone can please review the code for me and give constructive feedback.

import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;

public class Graph {
    private int V;  // Number of vertices

    private int E;  // Number of edges

    private HashMap<Integer, LinkedList<Integer>> adj;  // adjacency list

    Graph() {
        adj = new HashMap<>();
    }

    /**
     * Returns the number of vertices
     * @return Number of vertices in the graph
     */
    public int vertices() {
        return this.V;
    }

    /**
     * Number of edges in the graph
     * @return Returns the number of edges in the graph
     */
    public int edges() {
        return this.E;
    }

    public void addEdge(int v, int w) {
        if(adj.containsKey(v)) {
            adj.get(v).add(w);
            ++E;
        } else if(adj.containsKey(w)) {
            adj.get(w).add(v);
            ++E;
        } else {
            LinkedList<Integer> llOne = new LinkedList<>();
            LinkedList<Integer> llTwo = new LinkedList<>();
            llTwo.add(v);
            llOne.add(w);
            adj.put(v, llOne);
            adj.put(w, llTwo);
            ++V; ++E;
        }
    }

    @Override
    public String toString() {
        StringBuilder returnString = new StringBuilder();
        for (int key : adj.keySet()) {
            returnString.append(key).append(": ");
            LinkedList<Integer> nodesList = adj.get(key);
            returnString.append(Arrays.toString(nodesList.toArray()));
        }
        return returnString.toString();
    }
}


texts:
I'm new to C++ and am following up on: A simple multithreaded FileLogger in C++
I am curious to know if I implemented his ideas correctly, if there are further improvements to the code and whether it's (still) correct.
FileLoggerThread.h
#pragma once
#include <string>
#include <fstream>
#include <mutex>
#include <deque>
#include <condition_variable>
#include <filesystem>

class FileLoggerThread
{
public:
    explicit FileLoggerThread(std::filesystem::path filePath);
    ~FileLoggerThread();                            // makes code more easily unit testable (unit tests can otherwise be in an infinite loop)

    void log(const std::string &msg);

    FileLoggerThread(const FileLoggerThread&) = delete;
    FileLoggerThread& operator=(const FileLoggerThread&) = delete;

private:
    void writeToFile();

    std::deque<std::string> mMessages;              // accessed by log (any thread) and writeToFile (the writer thread)
    std::ofstream mOutputFile;                      // only accessible by writeToFile

    // thread internal resources
    std::mutex mMessagesMutex;                      // lock/unlock this each time messages is pushed or popped
    std::condition_variable mThreadScheduler;       // log needs to wake up writeToFile
    bool mIsRunning;                                // if set to false then the writer thread stops
};

FileLoggerThread.cpp
#include "FileLoggerThread.h"
#include <thread>

FileLoggerThread::FileLoggerThread(std::filesystem::path filePath) : mOutputFile {filePath}, mIsRunning {true} {
    std::thread t(&FileLoggerThread::writeToFile, this);
    t.detach();
}

void FileLoggerThread::writeToFile() {
    while (mIsRunning) {
        std::deque<std::string> localMessages;
        std::unique_lock<std::mutex> writerLock {mMessagesMutex};
        mThreadScheduler.wait(writerLock, [&]{ return !mMessages.empty() || !mIsRunning;});
        localMessages.swap(mMessages);
        writerLock.unlock();

        for (const auto& message : localMessages) {
            mOutputFile << message << std::endl;
        }
    }
}

void FileLoggerThread::log(const std::string &msg) {
    std::unique_lock loggerLock(mMessagesMutex);
    mMessages.emplace_back(msg);
    loggerLock.unlock();
    mThreadScheduler.notify_one(); // done for performance reasons, see: https://youtu.be/F6Ipn7gCOsY?t=2205
}

FileLoggerThread::~FileLoggerThread() {
    mIsRunning = false;
    mThreadScheduler.notify_one();
}


texts:
I created a wordsearch puzzle generator in C#. It's not a playable game, and it doesn't solve puzzles.

Find the entire codebase here: https://repl.it/@blonkm/wordsearch

I would like to optimize it so the puzzles can be as small as possible, with as much overlapping words as possible.

Currently I just move around words at random until they fit:

  public void Solve() {
    foreach (Word w in candidate.words) {
      int n = 0;
      bool done = false;
      while (!done) {
        double f = board.Fitness(w);
        if (w.errors == 0) {
          done = true;
          Log.Post(w + " can be placed");
          this.score += f;
          this.percentageSolved++;
          board.PlaceWord(w);
        }
        else
          board.Reposition(w);
        if (n > maxIterations) {
          Log.Post(w + " cannot be placed");
          this.score = 0.0;
          done = true;
        }
        n++;
      }
    }
    this.percentageSolved /= candidate.words.Count;
  }

What would be an efficient and effective method?

Also, any improvements on code quality, organization and performance are welcome.


texts: Scroll listener - about code style guidelines and standards

texts:
I'm an upstart, been only professionally programming for a bit less than 2 years, mainly in Java as I am currently working as an Android developer.

I often find myself thinking about how to improve the readability and maintainability of my code, and establish some style guidelines, for the project that I am working on, but also in general. On this project, I am using git and expect to have a few more developers joining me in the near future, and would like to keep our code style as readable/consistent/easily maintainable as possible. I have the (rare, I'm told) opportunity to establish some guidelines and create some configuration files for the code formatting which would then be used team-wide and keep things consistent.

I guess I want to:

keep the lines relatively short, preferably less than 80 characters (e.g. coding on an ultrabook with a 14 inch display with excessively long lines is not fun)
avoid refactoring variable/method names resulting in misalignment of method parameters
keep chained method calls readable
keep complex logical conditions readable
keep the list of implemented interfaces readable
Any other suggestions?

I have some ideas on how to accomplish this, but would like to hear if there's something that I can improve. Here's an example of a method which features points 2, 3, 4:

@Override
public void onScroll(
    AbsListView view,
    int firstVisibleItem,
    int visibleItemCount,
    int totalItemCount
) {
    super.onScroll(
        view,
        firstVisibleItem,
        visibleItemCount,
        totalItemCount
    );
    if(mUpdateFixedHeader &&
       !(
           mAdapter.isFiltered() &&
           mAdapter.isEmpty()
       ) &&
       mDateHeader != null
    ) {
       mDateHeaderTextView.setText(
           mDateHeaderLabel.concat(
              ((MeetsListAdapter) mAdapter)
                  .getSectionForPosition(firstVisibleItem)
           )
       );
    }
}

I'm not too sure about the way I've chained the logical conditions here, and I wanted to have the opening curly braces in a new lines but felt it makes the whole thing very disjointed. I would do it for the opening braces of a class though.

And, for a class declaration example, for a class that implements several interfaces, I'm thinking something along the lines of this (point 5):

public abstract class AbstractListFragment<T>
    extends
        AbstractFragment
    implements
        OnItemClickListener,
        OnScrollListener,
        SearchListener
{
    ...
}

Looking forward to your thoughts/suggestions!


texts: Computing the standard deviation of a Number array in Java - follow-up

texts:
(See the first and initial iteration.)

Now I make only one pass over the data in order to compute the standard deviation of the input Numbers, and that's how:

\begin{align}
\sum_{i = 1}^n (x_i - \mu)^2 &= \sum_{i = 1}^n (x_i^2 - 2\mu x_i + \mu^2) \\
                             &= \sum_{i = 1}^n x_i^2 - 2\mu \sum_{i = 1}^n x_i + n \mu^2 \\
                             &= \sum_{i = 1}^n x_i^2 - 2 \Bigg( \frac{\sum_{i = 1}^n x_i}{n} \Bigg) \sum_{i = 1}^n x_i + n \Bigg( \frac{\sum_{i = 1}^n x_i}{n} \Bigg)^2 \\
                             &= \sum_{i = 1}^n x_i^2 - 2 \Bigg( \frac{\sum_{i = 1}^n x_i}{n} \Bigg) \sum_{i = 1}^n x_i + \frac{1}{n}\Bigg( \sum_{i = 1}^n x_i \Bigg)^2 \\
                             &= \sum_{i = 1}^n x_i^2 - \frac{2}{n} \Bigg( \sum_{i = 1}^n x_i \Bigg) \sum_{i = 1}^n x_i + \frac{1}{n}\Bigg( \sum_{i = 1}^n x_i \Bigg)^2 \\
                             &= \sum_{i = 1}^n x_i^2 - \frac{2}{n} \Bigg( \sum_{i = 1}^n x_i \Bigg)^2 + \frac{1}{n}\Bigg( \sum_{i = 1}^n x_i \Bigg)^2 \\
                             &= \sum_{i = 1}^n x_i^2 - \frac{1}{n} \Bigg( \sum_{i = 1}^n x_i \Bigg)^2.
\end{align}

My code is as follows:

StandardDeviation.java:

package net.coderodde.util;

import java.util.Arrays;
import java.util.Collection;
import java.util.Objects;
import java.util.function.Consumer;

public final class StandardDeviation {

    public static double computeStandardDeviation(final Number... array) {
        Objects.requireNonNull(array, "The input number array is null.");

        if (array.length == 0) {
            return Double.NaN;
        }

        MyConsumer myConsumer = new MyConsumer();

        Arrays.stream(array)
              .map(Number::doubleValue)
              .forEach(myConsumer);

        int n = array.length;
        double sum = myConsumer.getSum();
        double sumOfSquares = myConsumer.getSumOfSquares();
        double intermediate = sumOfSquares - sum * sum / n;

        return Math.sqrt(intermediate / (n - 1));
    }

    public static double
            computeStandardDeviation(final Collection<Number> collection) {
        Objects.requireNonNull(collection,
                               "The input number collection is null");
        return computeStandardDeviation(
                collection.toArray(new Number[collection.size()]));
    }

    private StandardDeviation() {}

    private static final class MyConsumer implements Consumer<Double> {

        private double sum;
        private double sumOfSquares;

        @Override
        public void accept(Double t) {
            sum += t;
            sumOfSquares += t * t;
        }

        double getSum() {
            return sum;
        }

        double getSumOfSquares() {
            return sumOfSquares;
        }
    }

    public static void main(String[] args) {
        // Mix 'em all!
        double sd = computeStandardDeviation(Arrays.asList((byte) 1,
                                                           (short) 2,
                                                           3,
                                                           4L,
                                                           5.0f,
                                                           6.0));
        System.out.println(sd);
    }
}

Any critique much appreciated.


texts: Bitmasking and searching consecutive 1's

texts:
I have written code to count the continuous ones in an array or you can use binary string for convenience. Any solution using the binary string is acceptable.

My Solution is:

#include<bits/stdc++.h>
using namespace std;
#define MAX 100000
int main()
{
  int n,q,k,count;
  string str;
  cin>>n>>q>>k;
  bitset<MAX>s,c;
  //inserting bits in array
  for(int i=0;i<n;i++)
  {
    int temp;
    cin>>temp;
    s[i]=temp;
   }
   cin>>str;
  for(int i=0;i<q;i++)
  {
     //making duplicate bitset
     c=s;
     if(str[i]=='?')
      {
         count=0;
         while(c!=0)
         {
            //using bitmask to count maximum no of continuous 1's-O(1's bit)
            c=(c&(c<<1));
            count++;
          }
      if(count>k)
         cout<<k<<"\n";
      else
         cout<<count<<"\n";
   }
   else
   {
       //shifting each bit to right and updating first bit with previous last
      // bit
       bool lb=s[n-1];
       s=s>>1;
       s[n-1]=lb;
    }
  }
}


texts: VBA Data dump code using transpose and timeline duplication

texts:
The below code ran in 2:26 which is way too slow especially as it's only 1/3rd of the total (the remaining 2/3rd does something very similar just on different sections).  Is there something I can do to speed this up?  RangeCount = 625 and TimelineCount = 156 which are obviously large numbers (total is around 100k rows) but when RangeCount was 200 (30k rows) the code ran in 3 seconds...not sure why it's gone so slow now.
Link to sample: https://drive.google.com/file/d/1QHHtWad6_giWETZcAKw8-Qaq7Y6JJ4NX/view?usp=sharing
Edit: I believe I have discovered the issue - the table in Dash Data was an Excel table.  I changed it from being an Excel table to just normal cells and it ran the whole code in 4 seconds.  Can someone explain to me why the table is so slow or how I could improve the speed of it, please??
Sub copy_to_dash_data()

Dim i, j As Integer
Dim wsCalcs As Worksheet
Dim wsDashData As Worksheet
Dim LastRow As Long
Dim LastCol As Long
Dim FirstRow As Long
Dim RangeCount As Long
Dim TimelineCount As Long
Dim LastCell As Long
Dim PasteCell As Long
Dim InvoiceDetailsColumnCount As Long
Dim NamedRange As Range
Dim StartTime As Double
Dim TimeElapsed As String

'timer calculation

StartTime = Timer

'set calcs to manual, disable user events and disable screen updating

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

'setup sheet names for easy reference

Set wsCalcs = ThisWorkbook.Sheets("Calcs")
Set wsDashData = ThisWorkbook.Sheets("Dash Data")

'find last row and column of Dash Data and clear contents

LastRow = wsDashData.Cells(Rows.Count, 1).End(xlUp).Row
LastCol = Application.Match("P&L Amount", wsDashData.Rows(1), 0)

wsDashData.Range(Cells(2, 1).Address, Cells(LastRow, LastCol).Address).ClearContents

'count the number of rows in the first Calc block and the timeline block

FirstRow = wsCalcs.Range(Names("Invoice_Details")).Row
LastRow = wsCalcs.Range(Names("Invoice_Details")).Rows.Count + FirstRow - 1
RangeCount = wsCalcs.Range(Names("Invoice_Details")).Rows.Count - 1

TimelineCount = wsCalcs.Range(Names("Months_and_Years_Timeline")).Columns.Count - 1

'month start, month end and year rows from Calcs values transfer to Dash Data a number of times equal to the number of rows in the Calc block (e.g. number of invoices)

PasteCell = Application.Match("Month Start", wsDashData.Rows(1), 0)

For i = 1 To RangeCount
    wsDashData.Range(Cells(2 + (TimelineCount * (i - 1)), PasteCell).Address, Cells(1 + (TimelineCount * i), PasteCell + 2).Address) = _
        Application.Transpose(wsCalcs.Range(Names("Months_and_Years_Timeline")))
Next i

'enable events and screen updating

Application.ScreenUpdating = True
Application.EnableEvents = True
Calculate

'code complete!

TimeElapsed = Format((Timer - StartTime) / 86400, "hh:mm:ss")
MsgBox ("Code complete in " & TimeElapsed), vbInformation

End Sub


texts:
Got caught up with this morning's C++ question.
So I thought I would have a go.

SO here is my attempt at printing the first 1001 primes.

#include <iostream>
#include <vector>
#include <cmath>

bool isPrime(std::size_t num, std::vector<std::size_t> const& primes)
{
    std::size_t max = std::sqrt(num);
    for(auto const& prime: primes)
    {
        if (prime > max) {
            return true;
        }
        if (num % prime == 0)
        {
            return false;
        }
    }
    return true;
}

std::size_t sieve(std::size_t size, std::vector<std::size_t>& results)
{
    // primeCandidates holds 0/1 for each potential prime candidate.
    // The index represents the potential prime (index * 2 + 1)
    // This allows us to ignore all factors of 2
    // max is one past the highest prime candidate we can test for and store in primeCandidates
    std::size_t const           max = size * 2 + 1;
    std::vector<std::size_t>    primeCandidates(size, 1);

    // Add some default well know primes.
    results.push_back(2);
    results.push_back(3);

    // We will use the technique of incrementing by 2 then 4 then 2 then 4
    // This means skip all factors of 2 and 3 automatically.
    std::size_t       inc = 2;
    std::size_t loop = 5;
    for(; loop < max; loop += inc, inc = 6 - inc) {
        std::size_t index = loop/2;

        // If we find a candidate that is valid then add it to results.
        if (primeCandidates[index]) {
            results.push_back(loop);

            // Now strain out all factors of the prime we just found.
            for(; index < primeCandidates.size(); index += loop) {
                primeCandidates[index] = 0;
            }
        }
    }
    return loop;
}

int main()
{
    std::size_t constexpr   primeRequired   = 1001;
    std::size_t constexpr   siveStartSize   = 1000;

    std::vector<std::size_t>    result;
    result.reserve(primeRequired);

    // Use the Sieve of Eratosthenes to get a basic set of primes.
    std::size_t next = sieve(siveStartSize, result);

    // Want to re-use the 2/4/2/4 increment pattern
    // So work out the correct start point and increment value.
    std::size_t inc  = next % 6 == 5 ? 2 : 4;

    // We now use brute force checking each number against all the primes
    // that we have already found.
    for(; result.size() <= primeRequired; next += inc, inc  = 6 - inc) {
        if (isPrime(next, result)) {
            result.emplace_back(next);
        }
    }

    // Print out the primes we have found
    for(auto val: result) {
        std::cout << val << " ";
    }
    std::cout << "\n";
}


texts:
The problem is here, the solutions are here. I don't see a solution like mine (maybe the 4th), it seems to work though.

-- ---------------------------
-- 18 (**) Extract a slice from a list (idx start from 1)

slice _      _ 0 = []
slice (x:xs) 1 k = x : slice xs 1 (k-1)
slice (x:xs) i k = slice xs (i-1) (k-1)

I tried testing it with QuickCheck against the drop/take solution, but it gives up because of the very restrictive conditions (1 <= i <= k <= len xs) and I don't want to get deeper in testing right now.

Is this good Haskell code? Am I forgetting any edge case? (...should I suggest it on the solutions wiki?)


texts:
I'm making a game in Java with LWJGL and I just implemented jumping. I don't really think the code is particularly well written or very efficient. Here is the code of my Camera class:

public void startJump(float height, float land){
    jumpHeight = height;
    jumpLand = land;
    if(!falling && !jumping)
        jumping = true;
}

private void jump(){ // called every frame
    if(jumping){
        if(y >= -jumpHeight){
            y -= jumpSpeed;
        }else{
            jumping = false;
            falling = true;
        }
    }

    if(falling){
        if(y <= -jumpLand){
            y += jumpSpeed;
        }else{
            jumping = false;
            falling = false;
        }
    }
}

If someone knows a cleaner or more efficient method please tell me!

EDIT:

I was thinking of using jumping and !jumping but this introduces a bug where if the jump key is held down then the player hovers in the air so unless your making a jet-pack use jumping and falling.


texts: Append the contents of latest Stackage nightly build to the global cabal config file

texts:
I've made the following python script to to append the contents of the latest Stackage nightly build to the global cabal config file (instead of going to the site, copying the page and appending it manually...). I would appreciate your feedback:

"""
Appends the latest stackage nightly sources from Stackage(http://www.stackage.org/nightly)
to your global cabal config file

It also makes two backups: one of the appended file and one of the unappended file

Stackage(http://www.stackage.org/) is a stable source of Haskell packages
"""

import requests
import shutil
from os.path import expanduser
from os.path import join

cabal_config_path = expanduser('~/.cabal/config')
stackage_nightly_url = 'https://www.stackage.org/nightly/cabal.config?global=true'

def write_cabal_config_backup(filename):
    """
    Writes a backup of the current global cabal config file in the ~/.cabal directory
    """
    shutil.copyfile(cabal_config_path,
        join(expanduser('~/.cabal'), filename))

def unappend_stackage():
    """
    Unappend stackage sources from the global cabal config file. Be careful that
    the sources must be at the end of the file, or this function will delete things
    that you don't want it to.
    """
    def unappended_cabal_config():
        # Searches for the string 'Stackage' and returns a list made of the lines
        # of the file from there up, excluding the 'Stackage' line and everything below.
        with open(cabal_config_path) as f:
            cabal_config = f.readlines()
            for i in range(len(cabal_config)):
                if 'Stackage' in cabal_config[i]:
                    return cabal_config[:i]
        return cabal_config
    def write_unappended_cabal_config():
        cabal_config = unappended_cabal_config()
        with open(cabal_config_path, 'wt') as f:
            for line in cabal_config:
                f.write(line)
    write_unappended_cabal_config()

def append_stackage_nightly():
    """
    Appends stackage nightly sources to the global cabal config file
    """
    def get_stackage_nightly():
        r = requests.get(stackage_nightly_url)
        if r.status_code == 200:
            return r.text
    stackage_nightly = get_stackage_nightly()
    if stackage_nightly:
        with open(cabal_config_path, 'a') as f:
            f.write(stackage_nightly)

if __name__ == '__main__':
    write_cabal_config_backup('config_backup_appended')
    unappend_stackage()
    write_cabal_config_backup('config_backup_unappended')
    append_stackage_nightly()


texts: Given an arbitrarily large file containing integers, return the largest N numbers, highest first

texts:
I've written a top_n program in Ruby, which does pretty much exactly what the title says, as part of a coding exercise. I'm trying to learn about how to sort efficiently (i.e. deciding the best sorting algorithm and implementing them or their variations), to manage memory efficiently, and know whether I'm using the right language/constructs/ideas to tackle a sorting problem.

What I'm looking for is advice on the algorithm and the code in general. I feel it can be done MUCH, MUCH better (i.e. I'm doing splits and casting to integers... my intuition tells me something could be better).

I'd really appreciate if someone gave me some pointers on how could I improve this little program. Thanks in advance.

require 'set'

class File
  def self.tail(path, n = 10)
    result = File.open(path, 'r') do |file|
      buffer_size = 512
      line_count = 0

      file.seek(0, IO::SEEK_END)

      offset = file.pos

      while line_count <= n && offset > 0
       to_read = if (offset - buffer_size) < 0
                   offset
                 else
                   buffer_size
                 end

       file.seek(offset - to_read)

       data = file.read(to_read)

       data.reverse.each_char do |c|
         if line_count > n
           offset += 1
           break
         end

         offset -= 1

         if c == "\n"
           line_count += 1
         end
       end
      end

      file.seek(offset)
      file.read
    end

    result
  end

  def each_chunk(chunk_size)
    yield read(chunk_size) until eof?
  end
end

def top_n(filename, n = 100)
  pre_sorted_chunks = Dir[".#{filename}_sorted_chunk_*"]

  if pre_sorted_chunks.empty?
    build_pre_sorted_chunks_for(filename)
  end

  top = SortedSet.new

  # This reference takes ±0.141 seconds.
  # pre_sorted_chunks.each do |file|
  #   top << `tail -n #{n} #{file}`.strip.split.map(&:to_i)
  # end

  # This takes ±0.130 seconds. A little better.
  tasks = pre_sorted_chunks.map do |chunk_file_path|
    Thread.new(chunk_file_path) do |file_path|
      top << File.tail(file_path, n).strip.split.map(&:to_i)
    end
  end

  tasks.each(&:join)

  top.max(n)
end

# Current impl. takes ±5m. A lot of time.
def build_pre_sorted_chunks_for(filename)
  File.open(filename) do |file|
    n = 0

    # Chunks of 500MB.
    file.each_chunk(1024 ** 2 * 500) do |chunk|
      numbers = chunk.split.map(&:to_i)

      sorted_set = SortedSet.new(numbers)
      sorted_set = sorted_set.to_a.join("\n")

      File.open(".#{filename}_sorted_chunk_#{n}", 'w') do |f|
        f.write(sorted_set)
      end

      n += 1
    end
  end
end

unless ARGV.empty?
  filename = ARGV[0]
  n = ARGV[1].to_i

  puts top_n(filename, n)
else
  puts "Please provide a filename and a N value to calculate the top N."
end

I've used this method to create a file with random numbers:

def generate_random_number_file(n = 15_000_000)
  require 'set'

  randoms = Set.new

  loop do
    randoms << rand(n)
    break if randoms.size >= n
  end

  File.open('randos.txt', 'w') do |file|
    random_list = randoms.to_a.join("\n")
    file.write(random_list)
  end
end


texts: Implementing internationalization functionality for online English lessons

texts:
My website purpose is to sell online English lessons to people in Europe. It is crucial that my site is multilingual.

Overview

I am using HMVC modules to organize my site and my website has four main user areas:

Frontend (public access)
Student area (login protected)
Teacher zone (login protected)
My administration panel

The areas that need multilang functionality are the frontend and student area.

Here is what I am doing

I am storing a user's language choice in a session variable called "language".

The default session language is set to English in the template module (which renders HTML templates for the frontend, teacher zone, student area etc..) __constructor() like this:

/**
 * handles the default language for the template
 */
public function __construct()
{
    parent::__construct();
    // set language
    if ($this->session->userdata('language') === null) {
        $this->session->set_userdata('language', 'english');
    }
}

So when someone requests my home page I call the templates controller and the frontend method.

/**
 * the public frontend
 * @param array $data
 * @return html
 */
public function frontend($data)
{
    // get template language
    $this->lang->load('frontend/frontend', $this->session->userdata('language'));

    // load template
    $this->load->model('time/Time_Model');
    $this->load->view('frontend_template', $data);
}

My language translations are of course in the application->language folder... here is how I have it structured:

As for the actual implementation of the language switcher, I have a drop-down menu with my different language options:

So when a user selects 'Français' for example, they get redirected to base_url/language/switch_language/french controller that looks like this:

class Language extends MX_Controller
{
    /**
     * url: /language/switch_language
     * @param string $language
     */
    public function switch_language($language)
    {
        $this->session->set_userdata('language', $language);
        redirect($_SERVER['HTTP_REFERER']);
    }
}

This just sets the user language session variable and redirects to the last URL page they were on.

In the language files (suffixed with _lang.php) there is just one variable ($lang) which has a huge array of language translation key => value pairs:

// overview
$lang['book_overview'] = "Overview";
$lang['book_course_title'] = "Course";
$lang['book_duration_of_each_class'] = "Duration of Each Class";
$lang['book_minutes'] = "Minutes";
$lang['book_number_of_classes'] = "Number of Classes";
$lang['book_order_key'] = "Order Key";

To echo out the language string I simply replace the sentence with this code:

<?php echo $this->lang->line('book_duration_of_each_class'); ?>

Because there is actually quite a bit of language that needs to be translated (e.g. footer, form validation, actual content and paragraphs, menus, blurbs) I was thinking of splitting up the translations to different files such as frontend/footer_lang.php, frontend/header_lang.php etc... and then including them all into a master "frontend_lang.php"... is that a good idea? Are there any potential pitfalls to my implementation?


texts: C# to Access SQL query based on UI controls

texts:
I have a WPF application (using MVVM pattern) that allows users to perform a search for a record/records based on their selection choices and entries into the different UI controls (TextBox, CheckBox, RadioButton, DatePicker, TimerPicker,etc).  It does this by retrieving information from an Access database.

I have an Access query method in my AccessWorker class that looks like this (note that this is simplified a bit, because I can't post everything I have):

public DataSet GetRecords(string customQuery = "")
{
    var data = new DataSet();

    try
    {
        using (var con = new OleDbConnection(ConnectionString))
        {
            string queryString = "SELECT * FROM Records " + customQuery;

            using (var da = new OleDbDataAdapter(queryString, con))
            {
                da.Fill(data, "Records");
            }
        }
    }
    catch (Exception e)
    {
        ExceptionLogger.Record(e.Message);
    }

    return data;
}

As you can see, I pass a custom query argument to this method in a form of a string.  I construct this query string using a StringBuilder in my ViewModel and then I pass it to GetRecords() method.  Here's the GetQueryString() method that does the string building:

private string GetQueryString()
{
    var query = new StringBuilder();

    if (!String.IsNullOrWhiteSpace(RecNumber))
    {
        query.Append("Record_Number = '" + RecNumber + "'");
    }

    if (!String.IsNullOrWhiteSpace(EmployeeId))
    {
        if (!String.IsNullOrWhiteSpace(query.ToString()))
        {
            query.Append(" AND ");
        }

        query.Append("Employee_ID LIKE '%" + EmployeeId + "%'");
    }

    if (!String.IsNullOrWhiteSpace(Location))
    {
        if (!String.IsNullOrWhiteSpace(query.ToString()))
        {
            query.Append(" AND ");
        }

        query.Append("Location LIKE '%" + Location + "%'");
    }

    if (!String.IsNullOrWhiteSpace(FirstName))
    {
        if (!String.IsNullOrWhiteSpace(query.ToString()))
        {
            query.Append(" AND ");
        }

        query.Append("First_Name LIKE '%" + FirstName + "%'");
    }

    if (!String.IsNullOrWhiteSpace(LastName))
    {
        if (!String.IsNullOrWhiteSpace(query.ToString()))
        {
            query.Append(" AND ");
        }

        query.Append("Last_Name LIKE '%" + LastName + "%'");
    }

    //...and so on...
    return String.Format("WHERE {0}", query.ToString());
}

The above method is severely shortened here so that I wouldn't have to post a very long wall of code, but I'm dealing with 25 different controls and so there could be a condition for everyone of them that would have to be part of this query string.  The method itself, as you can imagine, is rather too large by anyone's standard.  When I took a C++ class in college, my instructor told me that if I can help it, I should keep my methods no longer than what I can see on the screen.  I'm bowing my head in shame... heh

I don't believe that this is the most elegant way of accomplishing this task.  Unfortunately, I haven't come up with a better approach.  I do my best at trying to learn new patterns every day, but I've been programming for under a year and a half, so any guidance would be greatly appreciated.

By the way, based on some of the comments, I have to clear up that I'm using properties that are bound to control, not controls' values....


texts: Grabs 10 bytes and converts it into a hex formatted string

texts:
I'm working on some code right now where the goal is to take in a byte stream and grab the data from the body of a message. The data is 10 bytes long and is meant to be translated into hex. Specifically, the 10 bytes coming in look like 01000200030004000500 or 01010201030104010501 (with implied 0x in front of each).

The code does this, but in my opinion it's not very pretty, so I was hoping to get help in improving both my own code and learning about a more effective way of grabbing an "uneven" amount of bytes (i.e. not the size of a data type for an easy memcpy). I've seen suggestions for using an array, but I wasn't sure if memcopying or endianness changes would complicate its use.

case MyMessage:
{
  std::string s;
  unsigned int i,j;
  // bytes are of type unsigned char*
  // each hex value is 4 bits
  memcpy(&i, bytes, sizeof(i)); // Bytes 0, 1, 2, 3
  i = ntohl(i); // 01000200 or 01010201

  memcpy(&j, bytes + 4, sizeof(j)); // Bytes 4, 5, 6, 7
  j = ntohl(j); // 03000400 or 03010401

  unsigned short k;
  memcpy(&k, bytes + 8, sizeof(k)); // Bytes 8, 9
  k = ntohs(k); // 0500 or 0501

  std::ostringstream iS, jS, kS;
  iS << std::hex << (i);
  s += "0" + iS.str(); // Have to shove "0" at front when dropped

  jS << std::hex << (j);
  s += "0" + jS.str();

  kS << std::hex << (k);
  s += "0" + kS.str();

  // In my actual code, these strings are constants
  if (s == "01000200030004000500")
  {
      s = "Off";
  }

  else if (s == "01010201030104010501")
  {
      s = "On";
  }

  else
  {
      s = "ERROR";
  }

  return s;
}


texts:
I am starting out in Haskell and thought I would try to make a function that got the index (nth) from the end of the list.

So getNthFromEnd 5 [1..10] would equal 5

The code I have so far is

getNthFromEnd :: Int -> [a] -> a
getNthFromEnd _ [] = error "Empty list given"
getNthFromEnd nth list
    | listLength < nth = error $ "List length must be greater than " ++ show nth
    | listLength == nth = head list
    | listLength >= nth = list !! (listLength - nth - 1)
    where listLength = length list
getNthFromEnd _ _ = error "Unknown exception occurred"

The code works as intended as far as I can tell, but seeing as though I am just getting to know Haskell I thought your suggestions on how this code could be cleaned up or refactored to make better use of FP concepts would be invaluable to my learning of Haskell and the FP paradigm overall.


texts: Cleaning up memory after loading Access DB into a datagrid

texts:
I wrote an app that pulls a MS Access DB into a DataTable and then displays it into a WPF datagrid. The dialog window has a search button which calls on a class that does the DB work.

The methods in play of the search window:

private void ExitBtn_Click(object sender, MouseButtonEventArgs e)
{
    quoteheaders.Dispose();
    GC.Collect();
    Close();
}
private void TitleBar_DblClick(object sender, MouseButtonEventArgs e)
{
    if (this.WindowState == WindowState.Normal) { this.WindowState = WindowState.Maximized; return; }
    if (this.WindowState == WindowState.Maximized) { this.WindowState = WindowState.Normal; return; }
}
private void TitleBar_Click(object sender, MouseButtonEventArgs e)
{
    if (e.ChangedButton == MouseButton.Left) { DragMove(); }
}
private Task<DataTable> Poll_QuoteHeader()
{
    return Task.Run(() => SQLinterface.FindQuoteID(dbPath));
}
private async void SearchBtn_Click(object sender, RoutedEventArgs e)
{
    quoteheaders = SQLinterface.FindQuoteID(dbPath);
    quoteheaders = await Poll_QuoteHeader();
    foundQuotes.ItemsSource = quoteheaders.AsDataView();
}

The class that talks to the database:

namespace QuoteClient
{
    class SQLinterface
    {
    public DataTable FindServer()
    {
        DataTable SQLservers = new DataTable();
        SqlDataSourceEnumerator SQLinstances = SqlDataSourceEnumerator.Instance;
        SQLservers = SQLinstances.GetDataSources();
        return SQLservers;
    }
    public DataTable FindQuoteID(string dbPath)
    {
        using(DataTable quoteID = new DataTable())
            {
            using (OleDbConnection quoteIDconn = new OleDbConnection(dbPath))
            {
                OleDbDataAdapter quoteIDadapter = new OleDbDataAdapter("SELECT * FROM DocumentHeaders", quoteIDconn);
                quoteIDadapter.Fill(quoteID);
                return quoteID;
            }
        }
    }
}
}

I'm bringing this here because I would like to know if it is OK to use GC.Collect() in this case. The app works fine without forcing a collection, but increases in memory every time the window is opened and search button is clicked. I am undecided on whether this is an actual leak or just the GC taking its time to cleanup.

So in short is there a better way to ensure that the memory that is used for filling the data table is disposed of? (I dispose of them either via using or .Dispose() )

Should I just leave the collection call since I know that when this window is closed nothing that was in use is needed anymore?

Or am I doing something wrong all around?


texts:
I have a pretty interesting problem that I'm trying to solve, and I am kind of stuck.

I want to count the triplets of distinct combinations a, b, c, that are smaller than LIMIThave the following properties:

a >= b, a >= c, and let's note m = a + b (a, b are integer)
a and m are the smallest 2 numbers in a Pythagorean triplet (a^2 + m^2 = x^2). m can be bigger than a, but a has to be larger than b or c

Here is the code I have so far. First, I generate all Pythagorean tripplets (of which I only use the first 2). The smallest one should be under the limit, but the largest one can be above the limit.

LIMIT = 10
pyt = {}

for m in xrange(1, LIMIT):
    for n in xrange(m + 1, LIMIT):
        k = 1
        a = n ** 2 - m ** 2
        b = 2 * m * n
        if (m - n) % 2 == 0 or gcd(m, n) != 1:
            continue

        while True:
            temp_a = a * k
            temp_b = b * k
            max_pyt = max(temp_a, temp_b)
            min_pyt = min(temp_a, temp_b)
            # I only need the minimum to be smaller than the LIMIT
            # but the maximum can't be larger than 2*LIMIT (check below)
            if min_pyt > LIMIT:
                break
            pyt[min_pyt, max_pyt] = 1
            k += 1

Once I have them, I just loop through them, and count the possible combinations that can be generated.

For example:

# pythagorean numbers: 6, 8 => (6^2 + 8^2 = 10^2)
# we can generate the numbers:
# 1, 5, 8 | 2, 4, 8 | 3, 3, 8 (when decomposing 6)
# 6, 2, 6 | 6, 3, 5 | 6, 4, 4 (when decomposing 8, although 6, 1, 7 are not good, the largest of the 3 needs to be a member of the Pythagorean triplet )

counter = 0
print pyt
for a, b in pyt:
    # if half of b is bigger than the limit, just continue
    temp = b // 2
    if temp >= LIMIT:
        continue
    elif b < LIMIT:
        # a is smaller than b, so any unordered combination of numbers with the sum a
        # will be good (4 = 1 + 3 or 4 = 2 + 2, 5 = 1 + 4, 5 = 2 + 3 - ie // works)
        counter += (a // 2)

    # at this point we know that temp (half of b) is not higher than the limit
    # and if it's less than a, there are combinations to be counted
    if temp <= a:
        # with the limit 10, we can have the following situation:
        # a = 8, b = 15, so we can count the set (8, 8, 7)
        counter += (a - temp) #
        if (a - temp) % 2 == 0:
            counter += 1

I hope I explained it well enough. The script seems to be working with lower values, but when going to higher numbers, I'm starting to miss things in limit situations, but I can't figure out what.

For example, with LIMIT = 99 I should be getting 1975, but I get 1943. Any ideas what I could be missing ? Any hint is more than welcome.

Also, since I'm still learning python, I wouldn't mind some tips on how to improve my code, and follow python coding standards.

Edit: The gcd function is from the fractions module (from fractions import gcd)


texts: Root finding using bisection method in Python

texts:
This code below is supposed to calculate the root of a function using bisection method. I am a newbie to Python, so  I do not know how to raise errors. Also, I would like to have a general review on this algorithm design, where I could have optimised, utilised some tricks or any sort of improvements. I feel like I am really not using the full funcionality of Python somehow.

Any comments on how to write a succinct code is appreciated. Thanks.

"""
Program to find root of a function using bisection method
"""
import sys
import math

def is_equal(a,b):
    return abs(b-a) < sys.float_info.epsilon

def bisection(f, a, b, TOL=0.01, MAX_ITER=100):
    """
    f is the cost function, [a,b] is the initial bracket,
    TOL is tolerance, MAX_ITER is maximum iteration.
    """
    f_a = f(a)
    f_b = f(b)

    iter = 0
    while iter < MAX_ITER:
        c = (a+b)/2
        f_c = f(c)

        if math.isclose(f_c,0.0,abs_tol=1.0E-6) or abs(b-a)/2<TOL:
            return (c, iter)
        else:
            if f_a * f_c < 0:
                b = c
                f_b = f_c
            else:
                a = c
                f_a = f_c
            iter = iter + 1
    return None

def func(x):
    """
    The cost function: f(x) = cos(x) - x
    """
    return math.cos(x) - x

root, iter = bisection(func, -1, 1, TOL=1.0E-6)
print("Iteration = ", iter)
print("root = ", root, ", func(x) = ", func(root))


texts: Performance of speech enhancement code for Android app

texts:
I wrote a speech enhancement code for an Android App. The algorithm runs on 256 size frames of voice samples. On my PC the code runs per about 5ms per frame, while on my Nexsus 5 it more like 50ms per frame, making the speech enhancement on a 30sec long recording run for over two minutes. On my PC, enhancing the whole audio file takes under a minute. I am looking to improve run time anywhere I can. I am attaching the code that runs per frame which is where I see biggest increase in run time.

for(int j = 0; j < Consts.NUM_OF_CLUSTERS; j++)
{
    tmp_log_h=0;
    for(int k = 0; k < Consts.SIZE_OF_SEMPELS_IN_CHUNCK; k++)
    {

        f_X = (1/FastMath.sqrt(2*FastMath.PI*sigmaSqr.get(j).get(k)))*FastMath.exp(-(FastMath.pow(NoisySignal[k] - mue.get(j).get(k),2))/(2*sigmaSqr.get(j).get(k)));// equation (3)
        F_X=(0.500 + 0.5*Erf.erf((NoisySignal[k] - mue.get(j).get(k))/(FastMath.sqrt(2*sigmaSqr.get(j).get(k)))));// equation (6)

        if(j==0)
        {
            g_pdf_Y[k]=1/FastMath.sqrt(2*FastMath.PI*Noise_sigmaSqr.get(k))*FastMath.exp(-(FastMath.pow(NoisySignal[k] - Noise_mu.get(k),2))/(2*Noise_sigmaSqr.get(k)));// equation (4)
            G_cdf_Y[k]=(0.500 + 0.5*Erf.erf((NoisySignal[k] - Noise_mu.get(k))/(FastMath.sqrt(2*Noise_sigmaSqr.get(k)))));// equation (5)
        }

        tmp_R_samples = (f_X/F_X);// equation (12.5)

        if(j==0)
        {
            R_noise[k]=g_pdf_Y[k]/G_cdf_Y[k]; // equation (12.5)
        }

        Roe[j][k] = 1/(1 + (R_noise[k]/tmp_R_samples));
        X_hat[j][k] = NoisySignal[k]*Roe[j][k]+ (mue.get(j).get(k))*(1 - Roe[j][k]) - (sigmaSqr.get(j).get(k))*((f_X*R_noise[k])/(f_X + F_X*R_noise[k]));
        tmp_h_first=(f_X*G_cdf_Y[k] + F_X*g_pdf_Y[k]);// equation (7.5)
        tmp_log_h += FastMath.log(tmp_h_first); // equation (7.5)
    }

    Log_h_second[j]=tmp_log_h;
    Log_h_final_vecotr[j]=FastMath.log(c.get(j)) + Log_h_second[j];
}

Double maxVi = MathHelpers.findMax(Log_h_final_vecotr);

double sumExp = 0.0;

for(int j = 0; j < Consts.NUM_OF_CLUSTERS; j++)
{
    sumExp +=(FastMath.exp(Log_h_final_vecotr[j] - maxVi));// equation (18)
    System.out.println(sumExp);
}

Log_h_final = maxVi + FastMath.log(sumExp);

for(int j = 0; j < Consts.NUM_OF_CLUSTERS; j++)
{
    Log_q[j]=FastMath.log(c.get(j)) + Log_h_second[j] - Log_h_final;
    q[j]=(FastMath.exp(Log_q[j]));// equation (10)
}

for(int k = 0; k < Consts.SIZE_OF_SEMPELS_IN_CHUNCK; k++)
{
    Double temp_X_estimate = 0.0;

    for(int j = 0; j < Consts.NUM_OF_CLUSTERS; j++)
    {
        temp_X_estimate += (X_hat[j][k]*q[j]);
    }

    X_estimate[k]=temp_X_estimate;// equation (9)
}


texts: Combining values corresponding to the same key

texts:
What the following code does is:

The key field is column0 (where sometimes there could be single key, and sometimes keys separated by comma).

The rest of the columns are also either single or comma separated.  But based on the single key value from column0, the goal is to collect all the values as a set in the rest of the columns.

import sys
import csv

dict={}

def getVal(k):
  try:
    v = dict[k]
  except:
    v= None
  return v

# First read as a line and first transformation separates first column
# and stores into a table with key,value (where value is the remaining)
for line in sys.stdin:
  line = line.strip()
  row = line.split('\t')
  l = len(row)
  keyvalues = row[0]
  items = keyvalues.split(",")
  for item in items:
    key = item
    value=[]
    for i in range(1, l):
       value.append(row[i].split(","))
    if getVal(key) == None:
      dict[key] = value
    else:
      prevval = dict[key]
      cols = len(prevval)
      newvalue=[]
      newlist = []
      for j in range(0,cols):
        newlist = prevval[j]+value[j]
        newset = set(newlist)
        newvalue.append(list(newset))
      dict[key] = newvalue

for k,v in dict.items():
   rowstr = k+"\t"
   ncols = len(v)
   for items in v:
     cols=""
     for item in items:
       cols +=item+","
     cols = cols[0:len(cols)-1]
     rowstr += cols+"\t"
   print rowstr

Sample input

3,15,75 1635,1762   878 3425    121,122,123
15  1762    871 3475    121,125,126
3   1585,1590,5192  882,832,841 3200,3211   120,121,122,123,124

I'm getting the results correctly as expected, but I would like to know any improvements to make on the code.


texts: Recursively generating flat XML elements from hierarchical data structure

texts:
My class has a method that does some stuff, and then wants to recursively operate on some data. Specifically, I'm generating an XML report whose output includes a flat list of elements derived from a hierarchical data structure.

Example Input (a Score)

{'wrapper':True, 'sub_scores':[
  {'wrapper':True, 'sub_scores':[
    {'wrapper':False, 'name':'count-objects', 'result':'pass', 'sub_scores':[]},
    {'wrapper':False, 'name':'find-object', 'result':'pass', 'sub_scores':[
      {'wrapper':False, 'name':'measure.x', 'result':'pass', 'sub_scores':[]},
      {'wrapper':False, 'name':'measure.y', 'result':'pass', 'sub_scores':[]},
    ]},
    {'wrapper':False, 'name':'find-object', 'result':'fail', 'sub_scores':[
      {'wrapper':False, 'name':'measure.x', 'result':'skip', 'sub_scores':[]},
      {'wrapper':False, 'name':'measure.y', 'result':'skip', 'sub_scores':[]},
    ]}
  ]}
]}

Desired Output

<report user="foo" time="1234">
  <summary tests="7" pass="4" fail="1" skip="2"/>
  <results file="foo.bin" />
  <samples>
    <sample name="count-objects" result="pass" />
    <sample name="find-object" result="pass" />
    <sample name="measure.x" result="pass" />
    <sample name="measure.y" result="pass" />
    <sample name="find-object" result="fail" />
    <sample name="measure.x" result="skip" />
    <sample name="measure.y" result="skip" />
  </samples>
</report>

In JavaScript or Lua I would create a helper function within my method that does the recursion. In Ruby I would create a lambda or proc that does the recursion. Is the 'right' way to do this in Python to create a helper static function? Or is there a better way to keep the original method self-contained, perhaps allowing closures over local variables?

class Scorer:
    def generate_report(self, score):
        r = etree.Element('report', {'user': getpass.getuser(), 'time': timestamp()})
        etree.SubElement(r, 'summary', {'tests': score.total(), 'pass': score.passed(),
                                        'skip': score.passed(), 'fail': score.failed()})
        etree.SubElement(r, 'results', {'file': self.results_path})
        samples = etree.SubElement(r, 'samples')
        Scorer._add_score_to_samples(samples, score)
        return r

    @staticmethod
    def _add_score_to_samples(samples, score):
        # Some scores are wrappers that should not be included in output
        if not score.wrapper:
            etree.SubElement(samples, 'sample', score.report_attr() )
        for s in score.sub_scores:
            Scorer._add_score_to_samples(samples, s)

I dislike 'polluting' my class with a private static method just to help out a specific method. However, if this is considered Pythonic, I'll happily continue down this path.


texts: Find the corresponding closing parenthesis

texts:
Problem:

  "Sometimes (when I nest them (my parentheticals) too much (like this
  (and this))) they get confusing."

Write a function that, given a sentence like the one above, along with the position of an opening parenthesis, finds the corresponding closing parenthesis. For the above input string and position 10 the algorithm should output 76.

After some trial and error I am able to come up with an algorithm.

function findClosingBracketMatchIndex(str, pos) {
  let openBracketCount = 0;
  let givenBracketPosition = -1;
  let index = -1;
  for (let i = 0; i < str.length; i++) {
    let char = str[i];
    if (char === '(') {
      openBracketCount++;
      if (i === pos) {
        givenBracketPosition = openBracketCount;
      }
    } else if (char === ')') {
      if (openBracketCount === givenBracketPosition) {
        index = i;
        break;
      }
      openBracketCount--;
    }
  }
  return index;
}

console.log(findClosingBracketMatchIndex('a (bc)', 2)); // 5
console.log(findClosingBracketMatchIndex('a (b ())', 2)); // 7
console.log(findClosingBracketMatchIndex('a (b ())', 5)); // 6
console.log(findClosingBracketMatchIndex('(a (b ()))', 0)); //9

Expert advice:

Apart from code review I would like to know if there are some tips to check the correctness of such algorithms, including off-by one error and conditions.


texts: ViewModel constructor with many parameters

texts:
I have some ViewModels that have a lot of parameters like this one:

public class ProductsMainViewModel : NotificationObject, IActiveAware, ...
{
    public ProductsMainViewModel(IProductRepository productRepository, IWarehouseRepository warehouseRepository, IUnitOfMeasureRepository unitOfMeasureRepository,
            IProductCategoryRepository productCategoryRepository, IProductPriceRepository productPriceRepository, IPriceLevelRepository priceLevelRepository,
            ICodingRepository codingRepository, ICategoryRepository categoryRepository, IDialogService dialogService, Logging.ILoggerFacade logger, IRegionManager regionManager,
            IJsonSerializer jsonSerializer, ICodeService codeService, IEventAggregator eventAggregator)
    {
        // ...
    }
}

(All repositories have the same instance of IUnitOfWork)
Instantiating this is done by IUnityContainer, But there are some dialogs that get called in this ViewModel:

            var viewModel = new ProductViewModel(_warehouseRepository, _unitOfMeasureRepository,
                _productCategoryRepository, _priceLevelRepository, _productPriceRepository, _codingRepository, _dialogService, _codeService, _jsonSerializer);

            var result = _dialogService.ShowDialog("ProductWindow", viewModel);
            if (result == true)
            {
                 // ...
            }

that their repositories must have the same IUnitOfWork of the current ViewModel. So I decided to pass parameters manually. I found it a good idea to "not reference any IoC container" in my ViewModel in here.

  The benefit of this approach is that the ViewModel doesn't have any
  knowledge of the (Unity) container.  Also, in terms of understanding
  the application design the dependencies of the ViewModel are easy to
  see since they are in the constructor.

Well, any ideas on how to reduce the number of parameters? Any particular design pattern?

Is it a good idea to create a 'IFooRepositoriesContext' and put related repositories in it?


texts:
Follow up of this question

Changes:

The pop_min function now panics if the tree is empty.
Moved the size attribute to the Tree struct.
Applied most of the suggestions given by the answers.
Added some other functions.
Refactored some functions.
Moved everything to the same file.

extern crate itertools;
use itertools::Unfold;
use std::cmp::Ordering;

pub fn permutation(size: u32, m: u32) -> Box<Iterator<Item = u32>> {
    let mut tree = Tree::new(1, size);
    let x = Unfold::new(1, move |a| {
        *a = (*a + m - 2) % tree.size + 1;
        Some(tree.pop_rank(*a))
    });
    Box::new(x.take(size as usize))
}

#[derive(Debug)]
struct Node {
    data: u32,
    left: Tree,
    right: Tree,
}

#[derive(Debug)]
struct Tree {
    size: u32,
    root: Option<Box<Node>>,
}

impl Tree {
    fn new(from: u32, to: u32) -> Tree {
        if from > to {
            return Tree { root: None, size: 0, };
        }
        let mid = from + (to - from) / 2;
        let node = Node {
            data: mid,
            left: Tree::new(from, mid - 1),
            right: Tree::new(mid + 1, to),
        };

        Tree {
            size: 1 + node.left.size + node.right.size,
            root: Some(Box::new(node)),
        }
    }

    fn find_rank(&mut self, rank: u32) -> &mut Tree {
        let r = self.root
                    .as_mut()
                    .expect("rank out of range")
                    .left
                    .size + 1;

        self.size -= 1;
        match rank.cmp(&r) {
            Ordering::Equal => self,
            Ordering::Less => self.as_mut().left.find_rank(rank),
            Ordering::Greater => self.as_mut().right.find_rank(rank - r),
        }
    }

    fn as_mut(&mut self) -> &mut Box<Node> {
        self.root.as_mut().unwrap()
    }

    fn as_ref(&self) -> &Box<Node> {
        self.root.as_ref().unwrap()
    }

    fn empty(&self) -> bool {
        self.root.is_none()
    }

    fn delete_node(&mut self) {
        *self = self.root
                    .take()
                    .map(|mut x| {
                        if x.left.empty() {
                            x.right
                        } else if x.right.empty() {
                            x.left
                        } else {
                            x.data = x.right.pop_min();
                            Tree {
                                root: Some(x),
                                size: self.size,
                            }
                        }
                    })
                    .expect("Can't delete None");
    }

    fn pop_min(&mut self) -> u32 {

        if self.empty() {
            panic!("underflow");
        }

        if self.as_ref().left.empty() {
            let data = self.as_ref().data;
            *self = self.root.take().unwrap().right;
            data
        } else {
            self.size -= 1;
            self.as_mut().left.pop_min()
        }
    }

    fn pop_rank(&mut self, rank: u32) -> u32 {
        let ranked = self.find_rank(rank);
        let data = ranked.as_ref().data;
        ranked.delete_node();
        data
    }
}


texts:
At this moment I'm reading an XmlNodeList into a ListItemCollection one node at a time using a foreach:

foreach (XmlNode node in authCompXml.SelectNodes("//Code"))
{
    CompaniesList.Items.Add(new ListItem(node.InnerText));
}

How can this be improved, such as without the aforementioned foreach?


texts: Storing icons statically as strings in custom class

texts:
I have a class that I call "Icons"

Icons.h

#import <Foundation/Foundation.h>

@interface Icons : NSObject

+ (UIImage *) someIcon;
+ (UIImage *) someOtherIcon;

+ (NSString *)imageToNSString:(UIImage *)image;
+ (UIImage *)stringToUIImage:(NSString *)string;

@end

Icons.m

#import "Icons.h"

@implementation Icons

+ (UIImage *) someIcon {
    return [self stringToUIImage:[self someIconStr]];
}
+ (UIImage *) menuLines {
    return [self stringToUIImage:[self someOtherIconStr]];
}

+ (NSString *)imageToNSString:(UIImage *)image {
    NSData *data = UIImagePNGRepresentation(image);
    return [data base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
}

+ (UIImage *)stringToUIImage:(NSString *)string {
    NSData *data = [[NSData alloc]initWithBase64EncodedString:string options:NSDataBase64DecodingIgnoreUnknownCharacters];
    return [UIImage imageWithData:data];
}

+ (NSString *) someIconStr {
    return @"iVBORw0KGgoAAAANSUhEUgAAABYAAAAoCAYAAAD6xArmAAAACXBIWXMAABYlAAAWJQFJUiTwAAAAHGlET1QAAAACAAAAAAAAABQAAAAoAAAAFAAAABQAAAB5EsHiAAAAAEVJREFUSA1iYKAimDhxYjwIU9FIBgaQgZMmTfoPwlOmTJGniuHIhlLNxaOGwiNqNEypkwlGk9RokoIUfaM5ijo5Clh9AAAAAP//ksWFvgAAAEFJREFUY5g4cWL8pEmT/oMwiM1ATTBqONbQHA2W0WDBGgJYBUdTy2iwYA0BrILDI7VMmTJFHqv3yBUEBQsIg/QDAJNpcv6v+k1ZAAAAAElFTkSuQmCC";
}

+ (NSString *) someOtherIconStr {
    return @"iVBORw0KGgoAAAANSUhEUgAAADIAAAAKCAYAAAD2Fg1xAAAACXBIWXMAABYlAAAWJQFJUiTwAAAAHGlET1QAAAACAAAAAAAAAAUAAAAoAAAABQAAAAUAAACZxAe6RgAAAGVJREFUOBFiYACCmTNn8k+ePLl+0qRJ74H4PxS/B4mB5EkFA2Ye0MHnkTwA8wiYBsmR6pEBMQ8U6rg8ARMHqSHWMwNmHtCxyMkJJTZgHgGpIdYjA2YekmNxeQIsToxHQHljoMwDAAAA//+psxowAAAAWUlEQVRjmDRp0n9iMAMRYObMmfzEmAVSQ4RxDCSZBzT0PRGWvyfGYpCaATNv8uTJ9YQ8AlJDrEcG1Dyg5edxeQYkR6wnYOoG1DxoSCIns/cgMZjjSKXpbR4A1NvIaZrhxd8AAAAASUVORK5CYII=";
}

This way, whenever I need to add an icon to a button or whatever, it's

UIButton * btn;
[btn setImage:[Icons someIcon] forControlState:UIControlStateNormal];

It doesn't seem like a big fix, but here's the main reasons I do it.

Easy To Use Same Icon Library Across Projects
No misspelled image errors
No need to create image file keys
Changing an icon quickly updates all iterations across project

 Questions

Anyone else using something similar to this?
Should I store the image strings statically as opposed to returning them via method as is now?
Any other thoughts?


texts:
I have a method that checks if a date is correct or not, which returns a boolean if it is or not. In the method, I first check the format, then the date by using the function checkdate, then I check that time is of the format His.

/**
  * Function that checks the format, date, and time of a given timestamp.
  * @author : somar
  * @param string $date timestamp ex: 20161230154523
  * @return boolean resultat de check
  */
public function validateDate($date)
{
    if (preg_match("/^(((\d{4}((0[13578]|1[02])(0[1-9]|[12]\d|3[01])|(0[13456789]|1[012])(0[1-9]|[12]\d|30)|02(0[1-9]|1\d|2[0-8])))|((\d{2}[02468][048]|\d{2}[13579][26]))0229)){0,8}$/", substr($date, 0, 8))) {
        $formatCheck = true ;
    } else {
        $formatCheck = false ;
    }
    $dateCheck = checkdate(substr($date, 4, 2), substr($date, 6, 2), substr($date, 0, 4));
    $timeCheck = substr($date, 8, 2) <= 23 && substr($date, 10, 2) <= 59 && substr($date, 12, 2) <= 59;
    if ($dateCheck == true && $timeCheck == true && $formatCheck == true) {
        return true;
    } else {
        return false;
    }
}

I want to improve the performance, by reducing the amount of function calls and by using less checking instructions. Moreover, PHP prefers to not use regex, and I don't know how a workaround.