Cookie wrapper in MVC4 I'd like to create a cookie wrapper in my application to help support a DRY approach to coding  common cookie methods, provide IntelliSense for cookie-type properties (keys), and protect against typo-errors when working with cookies from multiple classes and namespaces.

The best structure for this (that I can think of) is to apply a base class like such:

abstract class CookieBase{
   protected HttpRequestBase request;
   protected HttpCookie cookie;
   protected string name;

   public HttpCookie Cookie { }

   public string Name { get; }

   public HttpCookie Get(){ ... }

   protected string GetValue(string key){ ... }

   public bool IsSet(){ ... }

   protected void SetValue(string key, string value){ ... }
}

Then for each cookie-type that inherits the base class define properties for each key that should be stored in the HttpCookie, and define a constructor that accepts the Request object as a parameter and instantiates the Cookie property of the base class.

Any ideas on how I might improve this design, or suggestions to alternative approaches to attaining the goals I stated at the start of this post?

abstract class CookieBase{

Might be just a coding style nitpick, but in C# the scope-opening brace goes on the next line, like this:

abstract class CookieBase
{

Also (and this is possibly just a personal preference), when an access modifier isn't specified, it's public by default. This may or may not be what's intended - the intent is always clearer when the access modifiers are explicit:

public abstract class CookieBase
{

I like that you're using the Base suffix to denote a base/abstract class - seeing FooBase immediately tells me that the class cannot be instantiated directly.

   protected HttpRequestBase request;
   protected HttpCookie cookie;
   protected string name;

protected members should follow the same casing convention as public members - PascalCase:

protected HttpRequestBase Request;
protected HttpCookie Cookie;
protected string Name;

Now, exposing fields is never a recommended approach. You should expose properties, not fields. Hence:

protected HttpRequestBase Request { get; set; }
protected HttpCookie Cookie { get; set; }
protected string Name { get; set; }

Now this causes a naming clash with some other public members:

   public HttpCookie Cookie { }
   public string Name { get; }

The solution would be to make the properties public, with a protected setter (and remove the clashing public members):

public HttpRequestBase Request { get; protected set; }
public HttpCookie Cookie { get; protected set; }
public string Name { get; protected set; }

Having a method called Get is basically a code smell all by itself. I'd get rid of it, its functionality seems to be already implemented in the Cookie property:

  public HttpCookie Get(){ ... }

The rest of your code is not quite reviewable, I'd suggest you first implement it before your post it for peer review:

   protected string GetValue(string key){ ... }

   public bool IsSet(){ ... }

   protected void SetValue(string key, string value){ ... }
}

Is this a good approach? Not sure. abstract classes define abstractions, but your abstract class has nothing that actually warrants being abstract - you have no virtual or abstract members, not even a protected constructor, which leads me to believe that your derived classes might look like this:

public class SomeCookie : CookieBase
{
}

public class AnotherCookie : CookieBase
{
}

...if that's the case, then the base class is probably a bad design and you're probably better off just calling it Cookie and making it a normal class.

If your goal was to define an abstraction, @Malachi's answer is probably accurate - you'd be better off defining these members in some ICookie interface (which the "normal" Cookie class described above could very well be implementing).


Loop through products and return first product that matches criteria I am writing a function which loops through an array of products.  The function needs to return:

the ID of the first product that has an image and is in stock
if no products have an image and are in stock, then return the first product id that has an image
if no products have an image, then return the first product id that is in stock
if no products have an image, and no products are in stock, return the first product id

This is what I have written, and it is working as expected:

function loopThroughProducts($products)
{
    $firstId = $products[0]->id;

    foreach ($products as $product) {
        if ($product->hasImage && $product->inStock) {
            $id = $product->id;
            return $id;
        }
        if ($product->hasImage && empty($firstIdWithImage)) {
            $firstIdWithImage = $product->id;
        }
        if ($product->inStock && empty($firstIdInStock)) {
            $firstIdInStock = $product->id;
        }
    }

    if (!empty($firstIdWithImage)) {
        return $firstIdWithImage;
    }
    if (!empty($firstIdInStock)) {
        return $firstIdInStock;
    }

    return $firstId;
}

Does anyone see a way that I can optimize this loop or simplify the logic?  I dislike using so many sequential if-statements in one function, and there are some minor violations to the DRY principle.

Clean, readable code. But why not use more of PHP's standard array functions? Use the array_search or in_array functions. Or -even more fancy- the array_filter function.


PHP PDO Helper Functions Just recently I've wanted to update the PHP scripts I use to fetch information from a database for an iOS application. I've got around to it today, and I had a few questions that'd I like a second opinion on before I use these scripts.

Will this method of operation work? As in, since the query and connection are in two different try/catch blocks, will the query work differently?
Is this safe against SQL injection?
Can this support multiple/no parameters?
Overall, is this an efficient way of querying a database?

databaseHelper.php

<?php

error_reporting(E_ALL);
ini_set('display errors', 1);

$connection = // redacted
$username = // redacted
$password = // redacted

function initiateConnection() {
    try {
        $dbh = new PDO($connection, $username, $password);
        $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        return $dbh;
    } catch(PDOException $e) {
        return null;
    }
}

function performQuery($connection, $queryString, $parameters) {
    try {
        $query = $connection->prepare($queryString);
        $query->execute($parameters);

        if($sth->rowCount()) {
            $row = $sth->fetchAll(PDO::FETCH_ASSOC);
            return $row;
        } else {
            return null;
        }
    } catch(PDOException $e) {
        return null;
    }
}

?>

This is how I would plan on utilizing these functions:

<?php

include '../php_include/database.php';

$connection = initiateConnection();
if($connection != null) {
    $response = preformQuery($connection, 'SELECT * FROM users WHERE username = ?', 'test') // the username will NOT be hardcoded, it will be found in the $POST variable, this is just for example purposes
    if($response != null) {
        // echo json_encode($response);
    } else {
        // print false
    }
} else {
    // print error message
}

?>

Wrapping PDO: General Approach

Generally, wrapping PDO without actually adding any functionality is not recommended. See for example here, or pretty much any answer on basic PDO wrapper classes.

Because what happens is that you take a class with a pretty nice (and well known) interface, and then reduce the power of that interface (you can only perform FETCH_ASSOC, if you ever need a different fetch type, you would probably add a parameter/method to your script, if you follow my advice below, you will throw exceptions, etc; at some point, your script will be very close in use to PDO, just with different function names, and slightly limited functionality).

Wrapping PDO: Swallowing Exceptions

The biggest drawback of your solution is that you take perfectly fine exception and turn them into null returns. This has two downsides: It makes your calling code ugly (too many != null checks), and it makes it really hard to debug your code, as you just swallowed all the information, eg on why the database connection could not be established, or why the query returned nothing (is there nothing in the database, or is the query completely wrong? nobody knows now).

Wrapping PDO: Error Reporting

Another thing that's a real problem is that you are setting error reporting in this script. This is really something that needs to be controllable (for PDO as well as for PHP), because you want all the error reporting possible in development mode, but none of it in production. If you just set these values in various scripts, it will be really hard to control.

Your Questions

So I would definitely not recommend this approach, but if you want to go forward in this direction:

  Will this method of operation work?

Yes.

  Is this safe against SQL injection?

Yes. (assuming it is used correctly, which means no variable input in the querystring ever; and also assuming that this isn't an issue)

  Can this support multiple/no parameters?

Multiple queries definitely, and I would assume that execute(emtpyArray) is valid, but haven't tested it.

  Overall, is this an efficient way of querying a database?

Performance wise? Sure. Code wise? You don't actually save all that much typing. The PDO instantiation only happens once (and having a method for that seems fine to me), so lets look at the queries:

try {
    $query = $connection->prepare($queryString);
    $query->execute($parameters);
    if($sth->rowCount()) {
        // echo json_encode($sth->fetchAll(PDO::FETCH_ASSOC));
    } else {
        // print false
    }
} catch(PDOException $e) {
    // print error message
}

vs

if($connection != null) {
    $response = preformQuery($connection, 'SELECT * FROM users WHERE username = ?', 'test');
    if($response != null) {
        // echo json_encode($response);
    } else {
        // print false
    }
} else {
    // print error message
}

So with your approach, you basically saved one line.


Is this usage of the dynamic keyword an indicator of a design fault? I feel like I'm likely violating a design principal or two here so I'd appreciate any mistakes or antipatterns being named and pointed out.
I'm attempting to map a system in code which represents a decision tree, so based on the users input would provide them the next choice they can make, then from their input to that the next, and so on.
The response to each choice is either:

Binary Yes/No, so two different possible follow up choices.
1-10 range, so multiple possible follow up choices.

Any choice type can return any other choice type so I've been aiming to have the result for the follow up choice to always be a generic IChoice.
BinaryChoice current = NotifyPersonOrNot();
IChoice next = current.MakeChoice(true); // Binary choice
IChoice next1 = next.MakeChoice(5); // Range choice
IChoice next2 = next1.MakeChoice(3); // Range Choice

An issue I see with my current solution is usage of the dynamic keyword in my IChoice MakeChoice(dynamic answer) function. I used this to avoid having to do a specific cast for the T argument in the Func<T, IChoice> GetNextChoice function that the MakeChoice function calls with it's answer input.
I considered adding a
So the IChoice interface is like so as this is the only function I want to be used.
public interface IChoice
{
    // I feel like having to use dynamic here is a sign of a mistake in the design
    public IChoice MakeChoice(dynamic answer);
}

My base class looks like this
public abstract class Choice<T> : IChoice
{
    public Choice(Func<T, IChoice> getNextChoice)
    {
        GetNextChoice = getNextChoice;
    }

    public Func<T, IChoice> GetNextChoice { get; set; }

    // This seems cleaner than type checking but I'm thinking having to use dynamic indicates a mistake in class design
    public IChoice MakeChoice(dynamic answer)
    {
        return GetNextChoice(answer);
    }
}

And an implementation of the base class is like so, where Choice is given a Type. The RangeChoice version implements Choice<int>
public class BinaryChoice : Choice<bool>
{
    public override ChoiceType ChoiceType => ChoiceType.Binary;

    public BinaryChoice(Func<bool, IChoice> getNextChoice) : base(getNextChoice) { }
}

The idea is that GetNextChoice can be set with the unique logic required to provide correct next choice in the tree.
 private BinaryChoice NotifyPersonOrNot()
    {
        // If we were returning a RangeChoice here we'd have more conditions in the function
        return new BinaryChoice((sendNotification) =>
        {
            if (!sentNotification)
            {
                // This is another BinaryChoice
                return AskAnotherYesNoQuestion();
            }

            // This is a RangeChoice
            return AskRatingQuestion();
        });
    }

I've considered changing the GetNextChoice delegate to Func<object, IChoice> but I would like to avoid the overhead of having to cast from object into the required type when defining each choice. It would preferable to do it once in a single place if it must always happen.
I've looked at adding a abstract ChoiceType enum to the Choice class and handling the type casting in the MakeChoice function but I'm not sure how to do this without explicitly setting a type for the GetNextChoice delegate.

I believe your question is more aimed at a what, where, and when to use the dynamic keyword more than a design philosophy. It just so happens that a good explanation exists here: https://cloudncode.blog/2016/07/12/c-dynamic-keyword-what-why-when/
The short and easy from the link:

There is no compile-time type checking, this means that unless you have 100% confidence in your unit tests (cough) you are running a risk.
The dynamic keyword uses more CPU cycles than your old fashioned statically typed code due to the additional runtime overhead, if performance is important to your project (it normally is) don’t use dynamic.
Common mistakes include returning anonymous types wrapped in the dynamic keyword in public methods. Anonymous types are specific to an assembly, returning them across assembly (via the public methods) will throw an error, even though simple testing will catch this, you now have a public method which you can use only from specific places and that’s just bad design.
It’s a slippery slope, inexperienced developers itching to write something new and trying their best to avoid more classes (this is not necessarily limited to the inexperienced) will start using dynamic more and more if they see it in code, usually I would do a code analysis check for dynamic / add it in code review.

In my personal opinion - These functions are accepting rather simple data types (bool, int). It's more cumbersome on the CPU/Hardware to have a dynamic used than to just use function overloading to accomplish the same task without the needed stress. It is true that this may eliminate the need of type checking but you run a very large risk if these functions are used in uncontrolled events.
Also, your confidence in the data being entered for MakeChoice() or any of the other dynamic parameter functions or functions using dynamic has to be as accurate as the sun coming up tomorrow. Otherwise, you may get runtime errors.
Let me know if this helps - thanks.


Integrating the Ace embeddable code editor for editing HTML, CSS, and JavaScript I am currently implementing the Ace-editor embeddable code editor. In to my application.

I use a div with a certain class(example: editor_js) to render the editor the div also gets a data attribute (data-key) corresponding with the name (example: Site[tagmanager]) of a textarea. The session from the div get stored in the textarea and saved. You can see my complete Javascript code below for all three editors(html, css and Javascript). Everything seems to work, but I feel that there is a lot of room for improvement en optimization. So I was wondering if you could look it over and give me some tips and/or suggestions on how I can improve it and make more maintainable.

The html

<textarea id="editor_js" class="form-control" **name="Site[tagmanager]"** style="display: none;"></textarea>
<div **class="editor_js"** **data-key="Site[tagmanager]"**></div>

The Javascript

$(function () {

//Html editor
ace.require("ace/ext/language_tools");
$('.editor_html').each(function (index) {
    var type = $(this).attr("data-key"); // This is the name of the target textarea
    var textarea = $('textarea[name="' + type + '"]').hide(); // the textare is hidden because the editor is loaded in a div
    ace.require("ace/ext/emmet");
    var editor = ace.edit(this);
    editor.setTheme("ace/theme/chrome");
    editor.getSession().setMode("ace/mode/html");
    editor.getSession().setValue(textarea.val());
    editor.getSession().on('change', function(){
        textarea.val(editor.getSession().getValue());
    });
});

//CSS editor
$('.editor_css').each(function (index) {
    var type = $(this).attr("data-key");
    var textarea = $('textarea[name="' + type + '"]').hide();
    var editor = ace.edit(this);
    editor.setTheme("ace/theme/chrome");
    editor.getSession().setMode("ace/mode/css");
    editor.setOptions({
        enableBasicAutocompletion: true,
        enableSnippets: true,
        enableLiveAutocompletion: true,
    });
    editor.getSession().setValue(textarea.val());
    editor.getSession().on('change', function(){
        textarea.val(editor.getSession().getValue());
    });
});

//javascript editor
$('.editor_js').each(function (index) {
    var type = $(this).attr("data-key");
    var textarea = $('textarea[name="' + type + '"]').hide();
    var editor = ace.edit(this);
    editor.setTheme("ace/theme/chrome");
    editor.getSession().setMode("ace/mode/javascript");
    editor.setOptions({
        enableBasicAutocompletion: true,
        enableSnippets: true,
        enableLiveAutocompletion: true,
    });
    editor.getSession().setValue(textarea.val());
    editor.getSession().on('change', function(){
        textarea.val(editor.getSession().getValue());
    });
});

});

Isolate what varies, and abstract out what's repeated:

$(function () {

ace.require("ace/ext/language_tools");
ace.require("ace/ext/emmet");  // I moved this out of html block, not sure if that matters

//Html editor
var htmlCallback = makeEditorCallback('html', false);
$('.editor_html').each(htmlCallback);

//CSS editor
var cssCallback = makeEditorCallback('css', true);
$('.editor_css').each(cssCallback);

//javascript editor
var jsCallback = makeEditorCallback('javascript', true);
$('.editor_js').each(jsCallback);

function makeEditorCallback(mode, useAutoComplete) {
  return function() {
    var type     = $(this).attr("data-key"),
        textarea = $('textarea[name="' + type + '"]').hide(),
        editor   = ace.edit(this),
        options  = useAutoComplete ?
                   {
                     enableBasicAutocompletion: true,
                     enableSnippets: true,
                     enableLiveAutocompletion: true
                   } : {};
    editor.setTheme("ace/theme/chrome");
    editor.getSession().setMode("ace/mode/" + mode);
    editor.setOptions(options);
    editor.getSession().setValue(textarea.val());
    editor.getSession().on('change', function() {
      textarea.val(editor.getSession().getValue());
    });
  }
}
});

This code is untested, but the basic idea is what's important.  You should be able to make any tweaks or changes that you need.

Also, note that you weren't using the index argument, so I removed it.


Moving a cursor with the keyboard in assembly I am a beginner in assembly. But that didn't stop me from making a simple operating system completely made in assembly. It's very simple and doesn't do much. It's just a proof of concept. I would like to know what I can improve. Any feedback would be great.

bits 16
mov dl, 0 ; Cursor position column
mov dh, 0 ; Cursor position row

; Draw a really simple UI
; Draws a blue background
mov ah, 09h
mov al, 32
mov bl, 10h
mov cx, 1000h
int 10h

; Draws a gray bar
mov ah, 09h
mov al, 32
mov bl, 70h
mov cx, 160d
int 10h

main:
    ; Waits for a key press
    mov ah, 00h
    int 16h

    ; Compare the al register to see what key the user pressed

    ; If the user pressed the 's' key move the cursor down
    cmp al, 115
    je Down

    ; If the user pressed the 'w' key move the cursor up
    cmp al, 119
    je Up

    ; If the user pressed the 'a' key move the cursor left
    cmp al, 97
    je Left

    ; If the user pressed the 'd' key move the cursor right
    cmp al, 100
    je Right

    ; If the user pressed the Space Bar make the background of the   cursor magenta
    cmp al, 32
    je SpaceBar

    ; Jump back to main
    jmp main

    ; Our functions
    SpaceBar:
          mov ah, 09h
          mov bl, 50h
          mov cx, 1d
          int 10h
          jmp main

    Right:
        add dl, 1
        call SetCursor
        jmp main
        ret

    Left:
      sub dl, 1
      call SetCursor
      jmp main
      ret

   Up:
     sub dh, 1
     call SetCursor
     jmp main
     ret

   Down:
      add dh, 1
      call SetCursor
      jmp main
      ret

   SetCursor:
       mov ah, 02h
       mov bh, 00
       int 10h
       ret

 times 510-($-$$) db 0
 dw 0xAA55

Eventually you're going to want to handle other key-presses, correct? You might also want to handle other encoding styles, like EBCDIC, correct?

So, I've never done Assembly before, but these are pretty simple things to design for, and I hope the implementation is correct. First, we want to build a (very large) jump table for ASCII. Essentially, a jump table eliminates all of your comparisons down to exactly one comparison. It's pretty easy to set up:

        goto ascii(al) ; Jump to the line of the character code
ascii:  goto nulInput  ; This would be `0` code input
        goto sohInput  ; This would be `1` code input / Start of Heading
        goto stxInput  ; This would be `2` code input / Start of Text
        ; Add End of Text (3), End of Transmission (4), Enquiry (5)
        ; Acknowledgement (6), Bell (7)
        goto bsInput   ; This would be `8` code input / Backspace
        goto htInput   ; This would be `9` code input / Horizontal Tab
        goto lfInput   ; This would be `A` code input / Line Feed
        ; Add Vertical Tab (B), Form Feed (C)
        goto crInput   ; This would be `D` code input / Carriage return
        ; Shift Out (E), Shift In (F), Data Link Escape (10)
        ; Device Control 1 / XON (11), Device Control 2 (12)
        ; Device Control 3 / XOFF (13), Device Control 4 (14)
        ; Negative Acknowledgement (15), Synchronous Idle (16)
        ; End of Transmission Block (17), Cancel (18), End of Medium (19)
        ; Substitute (1A)
        goto escInput   ; This would be `1B` code input / Escape
        ; File Separator (1C), Group Separator (1D), Record Separator (1E)
        ; Unit Separator (1F)
        goto spacInput  ; This would be `20` code input / Space
        goto exclInput  ; This would be `21` code input / Exclamation Point
        ; In Order:
        ; " # $ % & ' ( ) * + , - . / 0 1 2 3 4 5 6 7 8 9 : ; < = > ?
        ; @ A B C D E F G H I J K L M N O P Q R S T U V W X Y Z [ \ ] ^ _
        ; ` a b c d e f g h i j k l m n o p q r s t u v w x y z { | } ~
        goto delInput   ; This would be `7F` code input / Delete

So you should get the point, go through the ASCII spec line-by-line and put a line for each record in the spec, then a label for each of those lines. For the ones you don't wish to implement yet, simply have a restart label or badCode label that ignores the input.

Once that's done we now know how to implement EBCDIC, just build an EBCDIC jump table.

What you might not realize is that having 128 (because eventually you want to support all codes/keys, right?) cmp statements will cause negative performance because al is compared up to 128 times for each key press, that's a lot. So we build a jump table that might be more work to implement initially, but in the end we'll end up with a much easier to maintain setup, and performance will not degrade. When we call jmp ascii(al), it jumps to the ascii label, then to the line identified by al. Easy stuff.

Regarding your indentation and such, from what I've seen usually assembly is spaced fairly far from the left (8-12 spaces) then all labels go at position 0. This helps keep them in plain sight, since assembly doesn't have 'functions' and such, and there's not a real concept of 'nesting' (you can nest labels, but any label can be accessed from any other location/scope so it doesn't always do any good).


Memory issues with Find Strings Problem on InterviewStreet Here is the code I wrote for the problem at http://www.interviewstreet.com/recruit/challenges/solve/view/4e1491425cf10/4efa210eb70ac where we need to to print the substring at a particular index from the lexicographicaly-sorted union of sets of substrings of the given set of strings...

import itertools
N = int(raw_input())
S = set()
for n in xrange(N):
    W = raw_input()
    L = len(W)
    for l in xrange(1,L+1):
        S=S.union(set(itertools.combinations(W, l)))
        print set(itertools.combinations(W, l))
print S
M = int(raw_input())
S = sorted(list(S))
print S
for m in xrange(M):
    Q = int(raw_input())
    try:
        print "".join(S[Q-1])
    except:
        print "INVALID"

but it gives me a Memory Error meaning that my code takes up more than 256Mb during execution.

I think the culprit is S=S.union(set(itertools.combinations(W, l))), but can't really think of a more efficient method for harvesting a unique set of substrings from the given set of strings...

Can you suggest an optimal alternative?

To successfully pass all test cases you need to implement something more sophisticated like suffix tree. That will allow you to solve this task in O(n) time using O(n) space.


Efficiently determining if a number is prime Is this the most efficient way to find if a number is prime? I can't think of a better way and it seems to run pretty quickly.

    public boolean primes(int num){
    for(int i = 2; i < num; i++){
        if(num % i == 0){
            System.out.println(num + " is not prime");
            return false;
        }
    }
    System.out.println(num + " is prime");
   return true;
}

A faster method would be to skip all even numbers and only try up to the square root of the number.

public static boolean isPrime(int num){
    if ( num > 2 && num%2 == 0 ) {
        System.out.println(num + " is not prime");
        return false;
    }
    int top = (int)Math.sqrt(num) + 1;
    for(int i = 3; i < top; i+=2){
        if(num % i == 0){
            System.out.println(num + " is not prime");
            return false;
        }
    }
    System.out.println(num + " is prime");
    return true;
}


Variable parser for the Hack programming language I am optimizing the variable parser for my programming language, and also trying to make it more readable and concise (precedence: readable and concise > efficient). What is the best way to improve this code and make the best out of each line, and make it easier to understand for contributors?

namespace pro_compiler
{
    /* Handles all the variable declarations */
    public class VarParser : Parser
    {
        public VarParser( )
            : base()
        {
        }

        public string Parse(ref string line)
        {
            CheckVariable(ref line);
            return line;
        }

        public void CheckVariable(ref string line)
        {
            /* Check current line for the "var" keyword */
            if (line.StartsWith("var"))
            {
                string decl = line;
                decl += ';';
                line = decl;
                CheckFunctions(ref line);
            }
        }

        /* check if the var declaration contains any functions
         * e.g var input = readln; */
        public string CheckFunctions(ref string line)
        {
            var words = line.Split(' '); //check wether each word is a function
            line = ""; // clear the current line

            foreach (var word in words)
            {
                string w = word.Trim(); //trim all leading and trailing spaces.

                foreach(var pair in FuncTable.Instance.NormSet)
                {
                    if (w.StartsWith(pair.Key)) // if the word is a function
                    {
                        w = w.Replace(pair.Key, pair.Value + "( )"); // replace it with the C# equivalent
                    }
                }

                w = ((w == words[0]) ? "" : " ") + w; // reinsert trailing and leading spaces
                line += w; // add the words back to the current line
            }

            return line;
        }
    }
}

Also, I have used a lot of the C# standard library methods, since I figured that the people who wrote those have 10 times more skills than me and wrote them as efficiently as possible. Is this good? Or is it better to implement my own string functions?

A few observations...

General

It would be great if you could include a syntax snippets of how a line in your programming language would look so we can test our solutions against the expected output. I had to go to your Google Code project and search for an actual syntax example in your source files
Your parsing functionality is still very rudimentary. (I didn't change that.) It can't yet handle function arguments and it doesn't work if there are no spaces in between words. Also, if there are spaces in front of the variable declaration, the function will not get translated at all  (this I fixed)
It's usually advisable to stick with library functions and not to reinvent the wheel, especially since you have stated that readability trumps efficiency in your scenario. .NET's string functions are mostly fine
There's no need to explicitly specify the default constructor as it (along with it's call to the argument-less constructor of Parser) will be automatically generated by the compiler. Leaving it out means one less thing for your readers and contributors to worry about

Naming issues

According to the comment just above the class definition, VarParser handles all the variable declarations. Although this makes sense, I'd suggest you ponder on finding a more descriptive name, such as VariableDeclarationParser or at least VariableParser
The function name CheckVariable is lacking at best, or misinformation at worst. It tells us it is "checking a variable" but in reality it isn't - it's checking if the current line contains a variable and, if it does, it will process the line - otherwise it will do nothing. An adequate name for that would be ParseLineIfItContainsAVariableDeclaration. Of course we don't use that, but rather we realize that the function needs to be split up to separate the check from the processing, so we choose two names for our new functions:

ContainsVariableDeclaration(string line) will return a bool indicating if we should process the line
ParseLine(string line) will return a string containing the parsed line

FuncTable is a very vague name for your Singleton containing the (also vague) NormSet - consider something like HackToCSharpMapper (or just LanguageMapper) and FunctionMappings or something along those lines instead of NormSet
CheckFunctions doesn't check anything, rather it seems to parse functions. Therefore, name it ParseFunctionsIn(string line)
I'm not saying you should choose the exact names I recommended, just try to think of the name that captures what the function does best and don't imply a function is doing something it doesn't do
Naming is important because it forces us to define what a given function, variable or class should do. When we end up with long names (see example above), we know that our code isn't well-structured and needs to be changed so that we follow the principles of OOP.

  A function should do one thing. It should do it well. It should do it only.
              — Robert C. Martin in Clean Code: A Handbook of Agile Software Craftsmanship

  Comments

Almost all of your comments can be made obsolete by choosing proper names and generally making the code as expressive as possible. IMHO, we should avoid comments that tell us what a particular statement does, rather we should use them only to clarify why we have made an unusal decision.
Or, to put it like Uncle Bob, I view every comment I write as a failure to express myself in code.
So I deleted most of your comments from the refactored version below because the names now stand for themselves, without the need for further clarification.

Dangerous and unusual things

Are you sure there won't be any whitespace before the var keyword? I've added a call to String.TrimStart() to make sure we don't stumble over this edge case
In your class, I see absolutely no reason to pass the line parameter by reference. This should be avoided because it makes your code more unpredictable - one can no longer be sure whether the function has a side effect on the input parameter

CheckFunctions returns a string, but the return value is never used because you rely on the ref parameter - be consistent!

Why are CheckVariable and CheckFunctions public? Too me, it looks like they should only ever be accessed from within that class
What if someone passes in a line that doesn't contain a variable declaration? At the moment, there will be no warning at all, the result will just be the same as the input - I suggest changing your program to throw an ArgumentException if it is not passed a valid declaration

Loops

Your nested foreach loop is unnecessary and bad for performance because it loops over all possibilities. As further investigation of the rest of your source code on Google Code shows, FuncTable.Instance.NormSet is a Dictionary<string,string> and therefore suitable for fast access by key.
Note that in your original code, you kept going through further possible function matches even after you have already replaced the current word with it's C# function!

After quite a bit of refactoring, we arrive at the below solution. If anything needs to be clarified, go ahead and ask.

Refactored example

All methods could have been made static, however I suspect you will change the base class - to which VariableDeclarationParser has no dependency at the moment - to a more useful one that provides a virtual Parse() method that can be overridden.

public class VariableDeclarationParser : Parser
{
    public string Parse(string line)
    {
        if (ContainsVariableDeclaration(line))
        {
            return ParseLine(line);
        }
        throw new ArgumentException("Invalid declaration: " + line);
    }

    private bool ContainsVariableDeclaration(string line)
    {
        return line.TrimStart().StartsWith("var");
    }

    private string ParseLine(string line)
    {
        string parsedLine = string.Empty;
        foreach (string word in line.Split(' '))
        {
            parsedLine += GetFunctionOrVariable(word);
        }
        return parsedLine.TrimEnd() + ";";
    }

    private string GetFunctionOrVariable(string candidate)
    {
        string key = candidate.Trim();
        var mappings = HackToCSharpMapper.Instance.FunctionMappings;
        if (mappings.ContainsKey(key)) return mappings[key] + "() ";
        return candidate + " ";
    }
}

If you're into LINQ, consider this alternative ParseLine function. It's more concise, but it sacrifices some readability - I think the above foreach is the better solution.

private string ParseLine(string line)
{
    string parsedLine = line.Split(' ').Aggregate(
        string.Empty, (parsed, word) => parsed + GetFunctionOrVariable(word));
    return parsedLine.TrimEnd() + ";";
}


Date formatters, lazily instantiated once I would like to create two date formatters only on first call. In Objective-C I would use dispatch_once() but now working in Swift. Am I doing it correctly? My code is based on example that was using class instead of static but it looks like it's Swift 2.0 doesn't support it yet.

class HomeContentItem : NSObject {
    var hideDescription:Bool = false
    var expanded:Bool = true

    var imageURL:String?
    var titleShort:String?
    var textBody:String?
    var sectionName:String?
    var dateString: String?
    var watermarkImage:UIImage?

    var moreTappedAction: ((AnyObject) -> (Void))?
    var sectionNameTappedAction: ((AnyObject) -> (Void))?
    var selectedItemAction: ((AnyObject) -> (Void))?

    static let sameDayFormatter = { (Void) -> NSDateFormatter in
        let formatter = NSDateFormatter()
        formatter.dateFormat = "hh:mm"
        return formatter
        }()

    static let differentDayFormatter = { (Void) -> NSDateFormatter in
        let formatter = NSDateFormatter()
        formatter.dateFormat = "yyyy/MM/dd"
        return formatter
        }()

    func setDate(date:NSDate) {
        if date.isSameDateAs(NSDate()) {
            self.dateString = HomeContentItem.sameDayFormatter.stringFromDate(date)
        } else {
            self.dateString = HomeContentItem.differentDayFormatter.stringFromDate(date)
        }
    }
}

And extention to date:

extension NSDate {
    func isSameDateAs(date : NSDate) -> Bool {
        let firstCalendar = NSCalendar.currentCalendar().components([NSCalendarUnit.Year, NSCalendarUnit.Month, NSCalendarUnit.Day], fromDate: self)
        let secondCalendar = NSCalendar.currentCalendar().components([NSCalendarUnit.Year, NSCalendarUnit.Month, NSCalendarUnit.Day], fromDate: date)
        return (firstCalendar.day == secondCalendar.day &&
            firstCalendar.month == secondCalendar.month &&
            firstCalendar.year == secondCalendar.year)
    }
}

This isn't the way to compare two dates...it violates one of my commandments.  We can & should use NSCalendar's compareDate method:

extension NSDate {
    func isSameDayAs(date: NSDate) -> Bool {
        let calendar = NSCalendar.currentCalendar()
        let dif = calendar.compareDate(self, toDate: date, toUnitGranularity: .DayCalendarUnit)
        return dif = .OrderedSame
    }
}

Moreover, your date formatter methods don't have any business in the view controller.  These make more sense also as NSDate extension methods.  However, creating NSDateFormatters is actually a pretty expensive operation.  We don't want to do it more often than necessary.  So, let's make a struct to handle one formatter per style we want:

extension NSDate {
    private struct Formatters {
        static let timeFormatter = { (Void) -> NSDateFormatter in
            let formatter = NSDateFormatter()
            formatter.dateFormat = "hh:mm"
            return formatter
        }()

        static let yearMonthDayFormatter = { (Void) -> NSDateFormatter in
            let formatter = NSDateFormatter()
            formatter.dateFormat = "yyyy/MM/dd"
            return formatter
        }()
    }

    var timeString: String {
        get {
            return Formatters.timeFormatter.stringFromDate(self)
        }
    }

    var yearMonthDayString: String {
        get {
            return Formatters.yearMonthDayFormatter.stringFromDate(self)
        }
    }
}

Importantly, using this approach makes unit testing (which you should definitely be doing) quite easy.  And, we've put code in places where it makes sense.


Quick sort implemented in Rust First attempt at writing Rust code.  What do you think of the formatting?  I think the type conversions are pretty messy.  How can I make it more idiomatic?

fn quicksort(array: &mut[isize], first: usize, last: usize) {
    if first < last {
        let midpoint = partition(array, first, last);
        quicksort(array, first, midpoint - 1);
        quicksort(array, midpoint + 1, last);
    }
}

fn partition(array: &mut[isize], first: usize, last: usize) -> usize {
    let pivot = array[last];

    let i: isize = first as isize;
    let mut i: isize = i - 1;

    let mut j = first;
    while j < last - 1 {
        if array[j] < pivot {
            i = i + 1;
            let k: usize = i as usize;
            swap(array, k, j);
        }
        j = j + 1;
    }

    let k: isize = i + 1;
    let k: usize = k as usize;
    if array[last] < array[k] {
        swap(array, k, last);
    }
    return k;
}

fn swap(array: &mut[isize], a: usize, b: usize) {
    let temp = array[a];
    array[a] = array[b];
    array[b] = temp;
}

fn main() {
    let mut array = [3, 5, 1, 4, 2];
    quicksort(&mut array, 0, 4);

    println!("{:?}", array);
}

Your implementation is incorrect. It fails for all sorts of inputs, but the simplest is

let mut array = [0, 0];
quicksort(&mut array, 0, 1);

Figuring out how to even call quicksort is overly complicated. Why do I have to pass in these numbers; can't the code figure that out?
Run rustfmt. It will automatically tell you things like:

&mut[T] should be written as &mut [T].

Run clippy.  It will automatically tell you things like:

Not to use return at the end of a function.
That you can use a += b instead of a = a + b
That you've re-implemented slice::swap

Since the code doesn't work, I don't know that the transforms I made preserve the existing behavior. The rest is caveat emptor.

You have redundant type declarations. You don't need to say let x: T = y as T, just let x = y as T.
You also don't often need to specify the type at all, type inference can handle it.
Presumably you converted to an isize because you were subtracting one from zero. Instead, increase the values by one to keep it in the range of a usize. To transform, add one to the initial value of i and subtract one from the usages of i, then remove the casts and simplify the math.

fn partition(array: &mut [isize], first: usize, last: usize) -> usize {
    let pivot = array[last];

    let mut i = first;
    let mut j = first;

    while j < last - 1 {
        if array[j] < pivot {
            array.swap(i, j);
            i += 1;
        }
        j += 1;
    }

    if array[last] < array[i] {
        array.swap(i, last);
    }

    i
}


Reading BER-encoded data I'm trying to read some SNMP packets on my own. So far so good, I was able to put up some functions to write some SNMP TRAP packets as I need them. However, now I need to be able to read them and while my code works, I'm not happy with it.

I'd like to see if any of you could please tell me if there's a better way to do and/or optimize my current code. My binary-fu isn't as good so I'd love if I could get some proposals without bit shifting as that confuses me and could confuse other people I program with.

I've heard and seen SNMP libraries for .NET but it's overkill for what I need to do. Also, I'm not allowed to use external libraries, and so far the code works, I just want to simplify it more and optimize it too, as it'll be used very extensively under high network traffic.

This is my (sample) code:

private void ReadSNMP(byte[] buf, int size)
{
    if (size > 0)
    {
        // IS UNIVERSAL SEQUENCE?
        if (buf[0] == 0x30)
        {
            int iPos = 0;
            int pckSize = ReadSNMPInt(buf, ref iPos);
            int version = ReadSNMPInt(buf, ref iPos);
            String comm = ReadSNMPString(buf, ref iPos);
        }
    }
}

And this is a sample ReadSNMPInt function:

private int ReadSNMPInt(byte[] buf, ref int iPos)
{
    MemoryStream ms = new MemoryStream();

    iPos++;
    if (buf[iPos] > 0x80) // > 80 = BER :(
    {
        if (buf[iPos] == 0x81)
            ms.Write(new byte[] { buf[iPos + 1], 0x00, 0x00, 0x00 }, 0, 4);
        if (buf[iPos] == 0x82)
            ms.Write(new byte[] { buf[iPos + 2], buf[iPos + 1], 0x00, 0x00 }, 0, 4);
        if (buf[iPos] == 0x83)
            ms.Write(new byte[] { buf[iPos + 3], buf[iPos + 2], buf[iPos + 1], 0x00 }, 0, 4);
        if (buf[iPos] == 0x84)
            ms.Write(new byte[] { buf[iPos + 4], buf[iPos + 3], buf[iPos + 2], buf[iPos + 1] }, 0, 4);

        iPos += buf[iPos] - 0x80;
    }
    else
    {
        iPos++;
        ms.Write(new byte[] { buf[iPos], 0x00, 0x00, 0x00 }, 0, 4);
    }

    iPos++;
    return BitConverter.ToInt32(ms.ToArray(), 0);
}

It works, but I noticed that when I needed to make the ReadSNMPString function, it needed kinda the same logic but different. I'm using these docs as reference (they're the best I've found, and so far their documentation helped to make the production code work). Also, replace snmp.htm with ber.htm to find out other links.

I'm trying to find out how to make a generic function to read at least one function for each datatype I need (simple though, only ints and strings) without using such ugly code.

I managed to make a new function now but I feel it can be a bit slower and/or not as optimized as I'd like.

public static class ASN1Int
{
    public static int Read(Stream s)
    {
        int preByte = s.ReadByte();
        if (preByte <= 0x79)
            return s.ReadByte();

        int bSize = preByte - 0x80;

        MemoryStream ms = new MemoryStream();
        using (BinaryWriter b = new BinaryWriter(ms))
        {
            for (int i = 0; i < 4 - bSize; i++)
                b.Write((byte)0x0);
            for (int i = 0; i < bSize; i++)
                b.Write((byte)s.ReadByte());
        }

        byte[] rv = ms.ToArray();
        Array.Reverse(rv, 0, rv.Length);
        return BitConverter.ToInt32(rv, 0);
    }
}

Any ideas are really welcome, and if someone's gonna close this on here please do a bit more research before going trigger-happy on me.

So, based on your update it looks like you've switched to reading from Stream - good decision.

A bit simplified/cleaner approach for reading int is:

public static class ASN1Int
{
    public static int Read(Stream inputStream)
    {
        const int sizeMarker = 0x80; //TODO: name appropriately

        int size = inputStream.ReadByte();

        if (size < sizeMarker)
            return inputStream.ReadByte();

        size -= sizeMarker;
        //TODO: add assertion to make sure size<=4 if needed

        var result = inputStream.ReadByte();

        while (--size > 0)
            result = (result << 8) + inputStream.ReadByte();

        return result;
    }
}


Querying employee schedules in a month I have this code, this code querying employee schedules in a month, in a work unit. If the List<Employee> count are few, the code works great, but if the List<Employee> count are many, the code runs slowly.  How I can optimize this code?

The DataRow is datagrid row containing employee id, name, etc..

await Task.Run(() =>
{
    List<Employee> employees = DatabaseHelper.GetEmployees(unitId, false, false);
    for (int i = 0; i < employees.Count; i++)
    {
        int no = i + 1;
        DataRow row = DataTableJadwal.Rows.Add(no + ".", employees[i].Nama, employees[i].ID);
        DatabaseHelper.GetUserSchedules(ref row, month, year);
    }

    Thread.Sleep(300);
});

public static void GetUserSchedules(ref DataRow row, int month, int year)
{
    using (SqlConnection sqlConn = new SqlConnection(string.Format(constring, UserID, Password, Server, Database)))
    {
        using (SqlCommand sqlComm = new SqlCommand(
            "SELECT Date, Shift FROM ScheduleList WHERE (ID = @ID) AND (MONTH(Date) = @Month) AND (YEAR(Date) = @Year)"
            , sqlConn))
        {
            try
            {
                sqlComm.Parameters.AddWithValue("@ID", row["ID"]);
                sqlComm.Parameters.AddWithValue("@Month", month);
                sqlComm.Parameters.AddWithValue("@Year", year);

                sqlConn.Open();
                using (SqlDataReader sqlReader = sqlComm.ExecuteReader())
                {

                    int totalHour = 0;
                    while (sqlReader.Read())
                    {
                        DateTime dt = (DateTime)sqlReader["Date"];
                        string shift = (string)sqlReader["Shift"];

                        // a user may had 1,2,3 schedule a day
                        string cellText = row[dt.Day.ToString("00")].ToString();
                        if (cellText.Length < 1)
                            cellText = shift;
                        else
                            cellText += "," + shift;

                        // count schedule hour total
                        if (Utilities.FreeScheduleList.IndexOf(shift.ToUpper()) == -1)
                        {
                            if (shift == "M" || shift == "Q")
                                totalHour += 10;
                            else
                                totalHour += 7;
                        }

                        row[dt.Day.ToString("00")] = cellText;
                    }

                    row["Total"] = totalHour;
                }
            }
            catch (Exception ex)
            {
                MessageBoxEx.Show(ex.Message, "GetUserSchedules Error", MessageBoxButton.OK, MessageBoxImage.Stop);
            }
        }
    }
}

I'm going to try to avoid raging about the data table based data access layer because I doubt a random person on the internet is going to change the direction of your project. So, let's look at your SQL query:

SELECT Date,
       Shift
FROM   ScheduleList
WHERE  ID = @ID
  AND  MONTH(Date) = @Month
  AND  YEAR(Date) = @Year

I've removed the extra brackets because they were just adding noise. This query could easily be changed so you could add a covering index to your schedule list table:

SELECT Date,
       Shift
FROM   ScheduleList
WHERE  ID = @ID
  AND  Date > @Date
  AND  Date < DATEADD(MONTH, 1, @Date)

Combined with an index on the Date and Id columns which also includes Shift and your query will be much faster.

CREATE INDEX IX_ScheduleList_Id_Date on your_schema.ScheduleList
(
    Id,
    Date
) INCLUDE (Shift)

I'd be more inclined to do this though:

SELECT Date,
       Shift
FROM   ScheduleList
WHERE  ID = @ID
  AND  Date > @StartDate
  AND  Date < @EndDate

This way you can search for schedule list in any window of time, not just one month at a time.

Having said that, what I'd actually do is return the employee list with their schedules at the same time - SQL is a relational database: it's good at joining related data together.

(SQL typed into browser and I'm rusty so it might not be 100% right).


Reading from a .txt file to a pandas dataframe Having a text file './inputs/dist.txt' as:

     1         1      2.92
     1         2     70.75
     1         3     60.90
     2         1     71.34
     2         2      5.23
     2         3     38.56
     3         1     61.24
     3         2     38.68
     3         3      4.49

I'm reading the text file to store it in a dataframe by doing:

from pandas import DataFrame
import pandas as pd
import os

def get_file_name( path):
    return os.path.basename(path).split(".")[0].strip().lower()

name = get_file_name('./inputs/dist.txt')
with open('./inputs/dist.txt') as f:
    df = DataFrame(0.0, index=[1,2,3], columns=[1,2,3])
    for line in f:
        data = line.strip().split()
        row,column,value = [int(i) if i.isdigit() else float(i) for i in data]
        df.set_value(row,column,value)
m[name] = df

and I end up with a dataframe of the data. I have to read more bigger files that follow this format. Is there a faster way to redo this to improve runtime?

When opening very large files, first concern would be memory availability on your system to avoid swap on slower devices (i.e. disk).

Pandas is shipped with built-in reader methods. For example the pandas.read_table method seems to be a good way to read (also in chunks) a tabular data file.

In the specific case:

import pandas

df = pandas.read_table('./input/dists.txt', delim_whitespace=True, names=('A', 'B', 'C'))

will create a DataFrame objects with column named A made of data of type int64, B of int64 and C of float64.

You can by the way force the dtype giving the related dtype argument to read_table. For example forcing the second column to be float64.

import numpy as np
import pandas

df = pandas.read_table('./input/dists.txt', delim_whitespace=True, names=('A', 'B', 'C'),
                   dtype={'A': np.int64, 'B': np.float64, 'C': np.float64})


Loop through months (1-12) I currently have this monstrosity:

next_period = (((current_month + tax_period_months)-1) % 12) + 1

I want to get the month that is tax_period_months after the current month.

E.g. if tax_period_months=3, and current_month=09 then next_period=12

This works, but has that horrible -1 +1 to stop month 12 becoming 0

Any alternatives?

If that really is all you need to calculate, then it's not too bad.

However, I suspect that you have other date calculations happening in your application.  In that case, why not take advantage of Ruby's Date class?  The >> operator adds months.

require 'date'
next_period = (Date.today >> tax_period_months).month


My code for a LocalBinaryPatern in python is running very slow. Any tips? My code for a LocalBinaryPatern in python is running very slow. I tried optimizing it with tips from online. I'am still getting used to python, and programming in General so any tips are very welcome! Here is the code:
def localbinarypattern(image, radius=2):
    h, w = image.shape
    if radius == 1:
        return 0
    else:
        abase = math.pi/4
        xshift, yshift = [0 for _ in range(8)], [0 for _ in range(8)]

        for i in range(8):
            xshift[i] = - radius * sin(i*abase)
            yshift[i] = radius * cos(i*abase)

        feat = [0 for _ in range(255)]
        lbp = [0 for _ in range(8)]
        base = [1, 2, 4,8, 16, 32, 64, 128]
        for y in (range(radius, (h-radius))):
            for x in (range(radius, (w-radius))):
                lbp = [0 for _ in range(8)]
                for i in range(8):
                    cx = xshift[i]+x
                    cy = yshift[i]+y
                    ry = int(cy+0.5)
                    rx = int(cx + 0.5)

                    if image[ry][rx] > 0:
                        lbp[i] = 1

                bits = 0
                for i in range(8):
                    bits += int(lbp[i]*base[i])

                if bits < 255:
                    feat[bits] += 1

        sum_lbp = 0
        for i in range(len(feat)):
            sum_lbp += feat[i]
        if sum_lbp ==0:
            print ("warning: the sum of LBP feature is zero!\n")
        else:
            for i in range(len(feat)):
                feat[i] /= sum_lbp
        return feat

No else after return
You have code like
if x:
    return 0
else:
    ...

Just drop the else, because you previously already returned. Use else branches only if the code converges again after the two branches, not if you exit the function (raise, return or exit()).
Double Initialization
You have code creating two lists:
        xshift, yshift = [0 for _ in range(8)], [0 for _ in range(8)]

        for i in range(8):
            xshift[i] = - radius * sin(i*abase)
            yshift[i] = radius * cos(i*abase)

You can combine those:
xshift = [-radius * sin(i * abase) for i in range(8)]
xshift = [ radius * cos(i * abase) for i in range(8)]

Further Dead Code

Initialization of h, w at the beginning can be moved down, after checking the radius.
lbp = [0 for _ in range(8)] -- you're doing that once before the loop and then in every iteration.

C-isms in Loop Iteration
It looks like you're used to writing in C (or a similar language) where you can only access an array by index. It shows e.g. in this code:
sum_lbp = 0
for i in range(len(feat)):
    sum_lbp += feat[i]

In Python, you would write this loop like this instead:
sum_lbp = 0
for value in feat:
    sum_lbp += value

An additional minor improvement specific to this case is to write it in one line:
sum_lbp = sum(feat)

Get familiar with the tools Python gives you at hand, they can make your life easier. In this case it's just the sum() function, but also you're not making use of e.g. dictionaries, which could make this code cleaner.
Redundant Parentheses
Here are two redundant pairs of partheses:
for x in (range(radius, (w-radius))):

Same code without them:
for x in range(radius, w - radius):

Redundant Type Conversions
Looking at int(lbp[i]*base[i]), I wonder why you int() the product. Both only contain integers, as far as I can tell.
Off-by-one Error
This code looks suspicious:
feat = [0 for _ in range(255)]
...
bits = 0
for i in range(8):
    bits += int(lbp[i]*base[i])

if bits < 255:
    feat[bits] += 1

Since an octet can take 256 different values, I'd expect feat to have 256 values as well. That way you could eliminate the bits < 255 check. Another way to simplify this is to reuse the sum() function again. Also, base[i] is 1 << i and lbp[i] is either zero or one, so you can also write this lbp[i] << i eliminating base entirely.
Further Redundant Code
Look at the inner loop:
# init `lbp` with zeroes
lbp = [0 for _ in range(8)]
# actually fill `lbp`
for i in range(8):
    ...
    if image[ry][rx] > 0:
        lbp[i] = 1
# compute values from `lbp`
bits = 0
for i in range(8):
    bits += int(lbp[i]*base[i])

This uses too many temporaries. Instead, try this approach:
bits = 0
for i in range(8):
    ...
    if image[ry][rx] > 0:
        bits += 1 << i


Loop Vue2 tag with keyup + modifier and click I have following code but wonder if I can loop it instead of copy-pasting.

calculator.ts

data: function() {
  return {
    calcInput: 'user types some value in input with v-model'
  }
},
template: `
  calc

  del

  clr
`

Pass modifier to v-on:keyup is the hardest part here.
@[loopedItem.key]={loopedItem.method} - doesn't work.
In this case I can see in event listeners for example keyup.enter but it doesn't work.

No.

Or well, maybe you could but I absolutely do not see any reason to do so.

What each <span> has in common:

The same class
They all have a click event and a keyup event

What each <span> has different:

They all have different handlers for what to do on the click/keyup event
They all have listen for different keyup events.

I don't see any benefit in creating a loop from this.

Some things you might want to consider though is:

Have a method that is performed for both click and the keyup event, to not copy-paste code between the different handlers.
Create a component for <span class="calc-button-control">

If you have plenty of more of these <span> elements, creating a component would be the way to go. Then you could have a component to handle the following:

It is a <span> element and applies the calc-button-control class.
It has a method for what to do when clicked or keyup event triggers.

I am not sure how flexible you can make the keyup listener, I don't think you can for example pass :keypress="enter" or similar to have it listen to @keyup.enter so I am not sure if creating a component for all of this does more harm than good.


Program for a speed camera I am doing some online exercises, and I came across this: "Your job is to write a program for a speed camera. For simplicity, ignore the details such as camera, sensors, etc and focus purely on the logic. Write a program that asks the user to enter the speed limit. Once set, the program asks for the speed of a car. If the user enters a value less than the speed limit, program should display Ok on the console. If the value is above the speed limit, the program should calculate the number of demerit points. For every 5km/hr above the speed limit, 1 demerit points should be incurred and displayed on the console. If the number of demerit points is above 12, the program should display License Suspended."

        Console.Write("Speed Limit :");
        int speedLimit = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine("SPEED LIMIT : " + speedLimit);
        Console.WriteLine("***********************");

        Console.Write("Car Speed : ");
        int carSpeed = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine("CAR SPEED : " + carSpeed);
        Console.WriteLine("***********************");
        Console.WriteLine("***********************");

        int demeritPoints = 0;

        if (carSpeed < speedLimit)
        {
            Console.WriteLine("Ok. You are good to go");
        }
        else
        {
            int speedDifference = carSpeed - speedLimit;

            for (int counter = 5; counter <= speedDifference; counter += 1)
            {
                if (counter % 5 == 0)
                {
                    demeritPoints++;
                }
            }
        }
        Console.Write("Demerit Points :");
        Console.WriteLine(demeritPoints);

        if (demeritPoints >= 12)
        {
            Console.WriteLine("Your license is suspended");
        }
        else
        {
            Console.WriteLine("You are not suspened");
        }

Not much to say I think, but here goes:

You're using clear, descriptive variable names, which is good. Such names make code easier to understand, which is especially important when you're working on large, complex projects.
Calculating the number of demerit points can be simplified to int demeritPoints = speedDifference / 5;.
Your code always displays the demerit points and suspension message, but from the requirements it looks like it should only do so when the speed exceeds the limit.
Instead of writing "SPEED LIMIT : " + speedLimit, you can use an interpolated string: $"SPEED LIMIT: {speedLimit}", which makes formatting a little easier.


Serialize data into one byte array using ByteBuffer I have a class in which I am passing certain parameters through the constructor and then using those parameters to make one final byte array with a proper format (header + data):

public final class Frame {
  private final byte addressedCenter;
  private final byte version;
  private final Map<byte[], byte[]> keyDataHolder;
  private final long location;
  private final long locationFrom;
  private final long locationOrigin;
  private final byte partition;
  private final byte copy;

  public Frame(byte addressedCenter, byte version,
      Map<byte[], byte[]> keyDataHolder, long location, long locationFrom,
      long locationOrigin, byte partition, byte copy) {
    this.addressedCenter = addressedCenter;
    this.version = version;
    this.keyDataHolder = keyDataHolder;
    this.location = location;
    this.locationFrom = locationFrom;
    this.locationOrigin = locationOrigin;
    this.partition = partition;
    this.copy = copy;
  }

  public byte[] serialize() {
    // All of the data is embedded in a binary array with fixed maximum size 70000
    ByteBuffer byteBuffer = ByteBuffer.allocate(70000);
    byteBuffer.order(ByteOrder.BIG_ENDIAN);

    int numOfRecords = keyDataHolder.size();
    int bufferUsed = getBufferUsed(keyDataHolder); // 36 + dataSize + 1 + 1 + keyLength + 8 + 2;

    // header layout
    byteBuffer.put(addressedCenter); // byte
    byteBuffer.put(version); // byte
    byteBuffer.putInt(numOfRecords); // int
    byteBuffer.putInt(bufferUsed); // int
    byteBuffer.putLong(location); // long
    byteBuffer.putLong(locationFrom); // long
    byteBuffer.putLong(locationOrigin); // long
    byteBuffer.put(partition); // byte
    byteBuffer.put(copy); // byte

    // now the data layout
    for (Map.Entry<byte[], byte[]> entry : keyDataHolder.entrySet()) {
      byte keyType = 0;
      byte keyLength = (byte) entry.getKey().length;
      byte[] key = entry.getKey();
      byte[] data = entry.getValue();
      short dataSize = (short) data.length;

      ByteBuffer dataBuffer = ByteBuffer.wrap(data);
      long timestamp = 0;

      if (dataSize > 10) {
        timestamp = dataBuffer.getLong(2);
      }

      byteBuffer.put(keyType);
      byteBuffer.put(keyLength);
      byteBuffer.put(key);
      byteBuffer.putLong(timestamp);
      byteBuffer.putShort(dataSize);
      byteBuffer.put(data);
    }
    return byteBuffer.array();
  }

  private int getBufferUsed(final Map<byte[], byte[]> keyDataHolder) {
    int size = 36;
    for (Map.Entry<byte[], byte[]> entry : keyDataHolder.entrySet()) {
      size += 1 + 1 + 8 + 2;
      size += entry.getKey().length;
      size += entry.getValue().length;
    }
    return size;
  }
}

I would like to know if it can be improved in any way. As you can see right now, I am allocating ByteBuffer with predefined size of 70000. Is there a better way by which I can allocate the size I am using while making ByteBuffer instead of using a hardcoded 70000?

A minor aesthetics advice

You can save some typing by using the method chains over ByteBuffer:

private int getBufferCapacity(final Map<byte[], byte[]> keyDataHolder) {
    int size = 36;
    for (Map.Entry<byte[], byte[]> entry : keyDataHolder.entrySet()) {
        size += 1 + 1 + 8 + 2;
        size += entry.getKey().length;
        size += entry.getValue().length;
    }
    return size;
}

public byte[] serialize2() {
    ByteBuffer byteBuffer = ByteBuffer.allocate(getBufferCapacity(keyDataHolder))
            .order(ByteOrder.BIG_ENDIAN);
    // Use chaining:
    byteBuffer.put(addressedCenter)
            .put(version)
            .putInt(keyDataHolder.size())
            .putInt(getBufferUsed(keyDataHolder))
            .putLong(location)
            .putLong(locationFrom)
            .putLong(locationOrigin)
            .put(partition)
            .put(copy);

    for (Map.Entry<byte[], byte[]> entry : keyDataHolder.entrySet()) {
        byte keyType = 0;
        byte[] key = entry.getKey();
        byte[] value = entry.getValue(); // A map mapping is often called a
        // key/value -pair.
        byte keyLength = (byte) key.length;
        short valueLength = (short) value.length;

        ByteBuffer dataBuffer = ByteBuffer.wrap(value);
        // Short cut:
        long timestamp = valueLength > 10 ? dataBuffer.getLong(2) : 0;

        // Chaining:
        byteBuffer.put(keyType)
                .put(keyLength)
                .put(key)
                .putLong(timestamp)
                .putShort(valueLength)
                .put(value);
    }

    return byteBuffer.array();
}

Also, when you deal with maps, the conventional terminology for a mapping is a key/value-pair. For this reason, I would rewrite

byte[] key = entry.getKey();
byte[] data = entry.getValue();

to

byte[] key = entry.getKey();
byte[] value = entry.getValue();

Then, later on in the code, I would change

byte keyLength = (byte) entry.getKey().length;

with

byte keyLength = key.length;

Instead of

long timestamp = 0;

if (dataSize > 10) {
    timestamp = dataBuffer.getLong(2);
}

you can write an one-liner:

long timestamp = valueLength > 10 ? dataBuffer.getLong(2) : 0;

Finally, since you know your file format, you should be able to come up with a function that computes the exact size of the file for particular set of data; call it foo. Now, you would normally do:

ByteBuffer byteBuffer = ByteBuffer.allocate(foo(keyDataHolder));

Hope that helps.


Election vote-counting, result-posting chatbot In preparation for the end of Code Review's 2015 election, I've built a simple bot to get the election votes, run OpenSTV on them, and post the result to a chatroom. I'm using this Python implementation of STV and ManishEarth's ChatExchange.

import getpass
import logging
import os
import time
import urllib
import sys
from subprocess import call

import ChatExchange.chatexchange
from ChatExchange.chatexchange.events import MessageEdited

logging.captureWarnings(True)

class bcolors:
    HEADER = '\033[95m'
    OKBLUE = '\033[94m'
    OKGREEN = '\033[92m'
    WARNING = '\033[93m'
    FAIL = '\033[91m'
    ENDC = '\033[0m'
    BOLD = '\033[1m'
    UNDERLINE = '\033[4m'

logging.basicConfig(level=logging.CRITICAL)

if 'ChatExchangeU' in os.environ:
    email = os.environ['ChatExchangeU']
else:
    email = raw_input("Email: ")
if 'ChatExchangeP' in os.environ:
    password = os.environ['ChatExchangeP']
else:
    password = getpass.getpass("Password: ")
client = ChatExchange.chatexchange.Client('stackexchange.com', email, password)

raw_input(bcolors.BOLD + bcolors.OKGREEN + "Connection good." + bcolors.ENDC + bcolors.BOLD + " [Enter] to proceed getting results for " + sys.argv[1] + " election #" + sys.argv[2] + "..." + bcolors.ENDC)

urllib.urlretrieve ("http://" + sys.argv[1] + "/election/download-result/" + sys.argv[2], "votes.blt")

result = os.popen("python runElection.py MeekSTV votes.blt").read()

os.remove("votes.blt")

result_indented = ""

for string in result.splitlines():
    result_indented = result_indented + "    " + string + "\n"

print result_indented

winners_line = ">" + result_indented.splitlines()[-1]

okay_to_post = raw_input("Okay to post? ")
if okay_to_post.lower() == "y":
    sandbox = client.get_room(sys.argv[3])
    sandbox.send_message(winners_line)
    sandbox.send_message(result_indented, False)

    time.sleep(40)

I run it from the command line like so:

python StackElectChat.py <site> <election number> <chatroom id>

For example, running this:

python StackElectChat.py serverfault.com 2 17251

Would take the results from Server Fault's second election and post it to Chatroom #17251.

Some concerns:

I don't like how I'm doing colors for it (taken from this Stack Overflow answer), is there a built in way?
okay_to_post.lower() seems like a hack - is there a built in way to check for an affirmative answer to a request?
I don't like how I iterate over every line to add code formatting (four spaces) to the chat message

To address your first concern, the way you're doing colors is fine... If you're not running Windows. If you try to use raw ANSI codes like this on windows, you're going to run into some issues. Personally, I'd recommend using the Colorama. It's pretty easy to use. For example, if I wanted to print yellow text with a red background, I'd do this:

from colorama import init, Fore, Back

init()

print(Fore.YELLOW + Back.RED + "Text!")

Secondly, using str.lower on input, isn't really all that hacky, and it's done quite a lot when obtaining user input. In short, it's okay.

Finally, I'm noticing that you're using string concatenation to display variables in a string. The proper way to do this would be to use str.format. Here's how that'd be done:

# Normal str.format without positional or
# named parameters.
print "{} {}".format("Hello", "world")

# str.format with positional parameters (*args)
print "{1} {0}".format("world", "Hello")

# str.format with named parameters (**kwargs)
print "{word1} {word2}".format(word1="Hello", word2="world")


Neatly printing integers interspersed with spaces The next iteration is here.

I have this small method for printing long integers neatly. For example:

neatify(123L)    = "123"
neatify(1234L)   = "1 234"
neatify(12345L)  = "12 345"
.
.
.

The code:

import java.util.Scanner;

public class Main {

    public static String neatify(final long number,
                                 final int groupLength) {
        final String str = Long.toString(number);

        if (groupLength < 1) {
            return str;
        }

        final char[] charArray = str.toCharArray();
        final StringBuilder sb = new StringBuilder();

        for (int i = 0; i < charArray.length; ++i) {
            if (i != 0 && (charArray.length - i) % groupLength == 0) {
                sb.append(' ');
            }

            sb.append(charArray[i]);
        }

        return sb.toString();
    }

    public static String neatify(final long number) {
        return neatify(number, 3);
    }

    public static void main(final String... args) {
        final Scanner scanner = new Scanner(System.in);

        while (scanner.hasNextLong()) {
            System.out.println(neatify(scanner.nextLong()));
        }
    }
}

Usability

do you really need the groupLength? I'm not aware of any number writing scheme where it is fixed, but not 3[*].
on the other hand, the separator is different in a lot of countries. You can see an example for thousands separators here (or on wikipedia). For example, Canada uses , Italy uses ., the US uses ,, and Switzerland uses '. It might be nice to add that as a parameter instead of hardcoding . You can still use  as a default.
your code doesn't deal that well with negative numbers. -123 becomes - 123, and -123456 becomes - 123 456. I would not expect a space after the -.

[*] In India it seems to be written eg as 15,00,000, which doesn't use 3, but which also isn't a fixed length.

Misc

if you start your loop at 1 and prepend sb.append(charArray[0]);, you can save the i != 0 check you perform each time.


Small guessing game in Ruby I'm writing a small guessing game. I'm writing a points calculation algorithm.

I wrote the following, and it works. But I feel like I'm bringing over procedural background into Ruby, or not leveraging Ruby properly.

How would an experienced Ruby programmer approach the problem? You can test the code on TryRuby.com (copy and paste code in the browser interpreter).

# g = guesses
g = [{ id: 1, elmer: 5, roger: 7, outcome: "Roger Win" },{ id: 2, elmer: 5, roger: 1, outcome: "Elmer Win" },{ id: 3, elmer: 4, roger: 8, outcome: "Roger Win" }]
# r = actual results
r = [{ id: 1, elmer: 3, roger: 9, outcome: "Roger Win" },{ id: 2, elmer: 7, roger: 9, outcome: "Roger Win" },{ id: 3, elmer: 4, roger: 8, outcome: "Roger Win" }]
# points table
p = []
# rules: correct outcome = 1 point, perfect match = 5 points.

# Loop over results.
r.each do |result|

  # Loop over guesses.
  g.each do |guess|

    # Make sure we compare corresponding ids.
    # So, compare result 1 to guess 1, r2 to g2, etc....
    if result[:id] == guess[:id]

      # Init a hash to store score
      score = {}

      # Did they guess the correct outcome?
      if result[:outcome] == guess[:outcome]

        # Correct outcome guessed! Make a score hash, give'em a point.
        score[:id]     = result[:id]  # game id
        score[:points] = 1            # point

        # Was it a perfect match?
        if result[:elmer] == guess[:elmer] && result[:roger] == guess[:roger]

          # Perfect match! Give them 4 points.
          # They already got 1 point for guessing the correct outcome.
          score[:points] += 4
        end
      end

      # Add the score to the points table
      p.push(score) unless score.empty?
    end
  end
end

I first propose how to improve your algorithm without changing the data structures.

Your algorithm is quadratic (two nested loops over all the entries). This can be easily avoided because you don't need to loop over all the g array to find the item you need.

If they are not, sort the arrays by the id key, using sort_by:

r.sort_by! { |e| e[:id] }
g.sort_by! { |e| e[:id] }

Then you can use each_with_index:

r.each_with_index { |result, i|
    guess = g[i]

    # compute the score here
}

or, if speed is not an issue (and this does not seem to be the case), you can also zip the arrays together r.zip(g) and iterate on that:

r.zip(g).each { |result, guess|
    # compute the score here
}

If you can modify the data structure I propose some alternatives.

Often when you have a set of objects with an id you use a hash.

# g = guesses
g = {1 => { elmer: 5, roger: 7, outcome: "Roger Win" }, 2 => {elmer: 5, roger: 1, outcome: "Elmer Win" }, 3 => { elmer: 4, roger: 8, outcome: "Roger Win" }}
# r = actual results
r = {1 => { elmer: 3, roger: 9, outcome: "Roger Win" }, 2 => {elmer: 7, roger: 9, outcome: "Roger Win" }, 3 => { elmer: 4, roger: 8, outcome: "Roger Win" }}
# points table
p = {}

# Loop over results.
r.each { |id, result|
  guess = g[id]

  # Init a hash to store score
  score = {}

  # compute the score here
  # ...

  p[id] = score unless score.empty?
}

If the id is a simple incremental integer and you add the entries in r and g in the same order, you can avoid the id at all and use the array indices instead:

# g = guesses
g = [{ elmer: 5, roger: 7, outcome: "Roger Win" }, {elmer: 5, roger: 1, outcome: "Elmer Win" }, { elmer: 4, roger: 8, outcome: "Roger Win" }]
# r = actual results
r = [{ elmer: 3, roger: 9, outcome: "Roger Win" }, {elmer: 7, roger: 9, outcome: "Roger Win" }, { elmer: 4, roger: 8, outcome: "Roger Win" }]
# points table
p = {}

# Loop over results.
r.each_with_index { |result, id|
  guess = g[id]

  # Init a hash to store score
  score = {}

  # compute the score here
  # ...

  p[id] = score unless score.empty?
}

You can create a class to represent each entry of the array (let's call each entry a Match) and then implement the scoring algorithm as a method:

class Match
  attr_accessor :elmer, :roger, :outcome

  def initialize(elmer, roger, outcome)
    @elmer = elmer
    @roger = roger
    @outcome = outcome
  end

  def compare(m)
    score = 0

    score = score + 1 if @outcome == m.outcome
    score = score + 4 if @elmer == m.elmer and @roger == m.roger

    score
  end
end

Example usage:

guess = Match.new(5, 7, "Roger Win")
result = Match.new(3, 9, "Roger Win")
puts guess.compare(result) # => 1

guess = Match.new(5, 1, "Elmer Win")
result = Match.new(7, 9, "Roger Win")
puts guess.compare(result) # => 0

guess = Match.new(5, 7, "Roger Win")
result = Match.new(5, 7, "Roger Win")
puts guess.compare(result) # => 5

puts guess.compare(guess) # => 5

If the string argument just says who is the winner based on the numbers, you can compute it:

class Match
  attr_accessor :elmer, :roger

  def initialize(elmer, roger)
    @elmer = elmer
    @roger = roger
  end

  def outcome
    if @elmer > @roger
      :elmer
    elsif @roger > @elmer
      :roger
    else
      :tie
    end
  end

  def compare(m)
    if @elmer == m.elmer and @roger == m.roger
      5
    elsif outcome == m.outcome
      1
    else
      0
    end
  end
end

Example usage:

guess = Match.new(5, 7)
result = Match.new(3, 9)
puts guess.compare(result) # => 1

guess = Match.new(5, 1)
result = Match.new(7, 9)
puts guess.compare(result) # => 0

guess = Match.new(5, 7)
result = Match.new(5, 7)
puts guess.compare(result) # => 5

puts guess.compare(guess) # => 5

guess = Match.new(2, 2)
result = Match.new(3, 3)
puts guess.compare(result) # => 1

guess = Match.new(2, 2)
result = Match.new(2, 2)
puts guess.compare(result) # => 5


Comparing two almost exact arrays I have two arrays:

$row
$rowTwo

The only difference between these two arrays are the first two keys have slightly different names due problems out of my control.

I'm wondering if there is a cleaner way to do it. Or would it be simply easier to find a way to rename the arrays to match?

        $needUpdate = false;

        if (strcasecmp( $row['Trelease'] , $rowTwo['release'] ) != 0) {
            $needUpdate = true;
        }  else if (strcasecmp( $row['dateTime'] , $rowTwo['date'] ) != 0) {
            $needUpdate = true;
        } else if (strcasecmp( $row['defectID'] , $rowTwo['defectID'] ) != 0) {
            $needUpdate = true;
        } else if (strcasecmp( $row['type'] , $rowTwo['type'] ) != 0) {
            $needUpdate = true;
        } else if (strcasecmp( $row['severity'] , $rowTwo['severity'] ) != 0) {
            $needUpdate = true;
        } else if (strcasecmp( $row['summary'] , $rowTwo['summary'] ) != 0) {
            $needUpdate = true;
        }  else if (strcasecmp( $row['status'] , $rowTwo['status'] ) != 0) {
            $needUpdate = true;
        }  else if (strcasecmp( $row['link'] , $rowTwo['link'] ) != 0) {
            $needUpdate = true;
        }

http://php.net/array_diff

  Compares array1 against one or more other arrays and returns the values in array1 that are not present in any of the other arrays.

// Set the keys matching to the $rowTwo array
$row['release'] = $row['Trelease'];
$row['date'] = $row['dateTime'];

// Unset the original values as we no longer need these
unset($row['Trelease'], $row['dateTime']);

// Compare them:
$difference = array_diff($row, $rowTwo);
$needUpdate = count($difference)!==0;


Implementation of the basic matrix operations for embedded application in C++ I have been developing a control software in C++ and for implementation of the control algorithms I need basic matrix operations like addition, subtraction, multiplication and multiplication by scalar.
Due to the fact that the application is the real time application I need to avoid the dynamic memory allocation so I have decided to exploit the C++ templated class and the nontype parameters
template <class T, uint8_t ROWS, uint8_t COLUMNS>
class Matrix
{
public:
  T array[ROWS][COLUMNS];

  Matrix<T, ROWS, COLUMNS> operator+(const Matrix<T, ROWS, COLUMNS> &m) const
  {
    Matrix<T, ROWS, COLUMNS> result;

    for (uint8_t row = 0; row < ROWS; row++) {
      for (uint8_t column = 0; column < COLUMNS; column++) {
        result.array[row][column] = array[row][column] + m.array[row][column];
      }
    }

    return result;
  }

  Matrix<T, ROWS, COLUMNS> operator-(const Matrix<T, ROWS, COLUMNS> &m) const
  {
    Matrix<T, ROWS, COLUMNS> result;

    for (uint8_t row = 0; row < ROWS; row++) {
      for (uint8_t column = 0; column < COLUMNS; column++) {
        result.array[row][column] = array[row][column] - m.array[row][column];
      }
    }

    return result;
  }

  template <uint8_t N>
  Matrix<T, ROWS, N> operator*(const Matrix<T, COLUMNS, N> &m) const
  {
    Matrix<T, ROWS, N> result;

    for (uint8_t row = 0; row < ROWS; row++) {
      for (uint8_t column = 0; column < N; column++) {
        result.array[row][column] = 0;
        for (uint8_t element = 0; element < COLUMNS; element++) {
          result.array[row][column] +=
              array[row][element] * m.array[element][column];
        }
      }
    }

    return result;
  }

  friend Matrix<T, ROWS, COLUMNS> operator*(double k,
                                            const Matrix<T, ROWS, COLUMNS> &m)
  {
    Matrix<T, ROWS, COLUMNS> result;

    for (uint8_t row = 0; row < ROWS; row++) {
      for (uint8_t column = 0; column < COLUMNS; column++) {
        result.array[row][column] = k * m.array[row][column];
      }
    }

    return result;
  }

  friend Matrix<T, ROWS, COLUMNS> operator*(const Matrix<T, ROWS, COLUMNS> &m,
                                            double k)
  {
    return k*m;
  }
};

I have doubts regarding the decision to have the matrix itself i.e. the array as a public member of the Matrix classes.

I have doubts regarding the decision to have the matrix itself i.e. the array as a public member

I don't like having the array as a public member because it means accessing individual elements looks like a bit strange compared to the other operations.
int main()
{
    Matrix<int, 5, 5>   m1;

    // this looks funny.
    std::cout << m1.array[2][2] << "\n";

    // I would want to access the elements like this:
    std::cout << m1[2][2] << "\n";
}

I would add an operator[] to your class to handle the array access directly.

I need to avoid the dynamic memory

Not using dynamic memory allocation can quite easily make the application much slower. You need to make sure you are not copying whole arrays around when a dynamically allocated resource can be moved around with a single pointer.
  // This operation returns by value.
  // Which means that unless the compiler finds an optimization
  // You need to copy the result out of the function.
  Matrix<T, ROWS, COLUMNS> operator+(const Matrix<T, ROWS, COLUMNS> &m) const

  // Since you used a std::array this means copying all the
  // individual elements from source to destination.

If you had used std::vector (ie. some dynamic memory allocation) then you can move the content out of the function. This means internally you only have to move a single pointer out of the function. For large arrays the difference can be significant (copying thousands of 32 bit values or copying one 32 bit value).
Now "modern" common C++ compiler have some pretty good optimizations but if you are on an embedded platform these optimizations can be spotty, and you would need to validate how good your compiler is and if it can do RVO or NRVO (Return Value Optimization or Named Return Value Optimization).

Side note.
There are some really good optimized matrix libraries out there. Have you tried using one of those.
I am by no means an expert but I have seen the code (a long time ago) where they don't do any of the operations until they actually need the result.
i.e. Matrix Addition/multiplication etc build an expression tree. The expression tree is only evaluated when you try and access an element of the result. This means you can do optimizations on the full expression (like multiplication by an identity can be removed, multiplication by zero can drop a whole sub-tree of the expression etc). This means you only do the operations that actually get you the values you need and don't brute force do all operations.


2 ways to print a half-pyramid I wrote this bit of C that prints a half-pyramid,

   *
  **
 ***
****

Here's the main body:

#include <stdio.h>
#define SIZE 4

void printrow(int threshold);

int main()
{
    int i, threshold;

    for (i = 0; i < SIZE; i++) {
        // threshold slides to the left with each iteration:
        // ===|
        // ==|=
        // =|==
        // |===
        threshold = SIZE - (i+1);

        printrow(threshold);
    }

    return 0;
}

And here are two different implementations of printrow. I'm not sure which is the better of the two.

Version one uses the threshold as a slider that divides the row into two smaller loops:

void printrow(int threshold)
{
    int j;

    for (j = 0; j < threshold; j++)
        printf(" ");

    for (j = threshold; j < SIZE; j++)
        printf("*");

    printf("\n");
}

Version two runs a single loop and each iteration checks its position relative to the threshold when determining which character to print:

void printrow(int threshold)
{
    int j;
    char c;

    for (j = 0; j < SIZE; j++) {
        c = (j < threshold) ? ' ' : '*';
        printf("%c", c);
    }

    printf("\n");
}

This is a very small, simple program, but I'm curious which is the better approach, as I'm sure the same scenario can arise on a larger scale.

I like your version one better - in that you can break it up into even smaller pieces. Split out the printing of repeated characters:

void print_repeat(char c, int n) {
    while (n--) {
        printf("%c", c);
    }
}

So that printing a row just calls that twice:

void print_row(int row_num, int size) {
    print_repeat(' ', size - (row_num + 1));
    print_repeat('*', row_num + 1);
    printf("\n");
}

And printing the whole pyramid just calls that in a loop:

void print_pyramid(int size) {
    int i;
    for (i=0; i<size; ++i) {
        print_row(i, size);
    }
}


Should I Move Methods To A Different Class The following code is part a class called class db_tables. All the other getTbl* methods other than getTblHerd pull information based on the ID of the animal that is passed to them.

My question is while the following code works would it be better to move all the other getTbl methods into the Animal class and pass them the ID stored in the Animal class.

Thanks,

public static ArrayList<Animal> getTblHerd() throws Exception {
    CC_H2 db = new CC_H2();
    db.Connect(Variables.getStrConn(), Variables.getStrUser(),
            Variables.getStrPassword(), "Embedded");
    ResultSet rs = db
            .query("Select HERD_ID FROM tblHerd ORDER BY HERD_ID ASC");

    ArrayList<Animal> alAnimals = new ArrayList<Animal>();

    while (rs.next()) {
        int i = rs.getInt("HERD_ID");
        alAnimals.add(new Animal(i));
    }
    db.Disconnect();
    return alAnimals;
}

public static ArrayList<Note> getTblNotes(int intID) throws Exception {
    CC_H2 db = new CC_H2();
    db.Connect(Variables.getStrConn(), Variables.getStrUser(),
            Variables.getStrPassword(), "Embedded");
    ResultSet rs = db
            .query("Select NOTE_ID FROM tblNotes WHERE NOTE_HERD_ID = "
                    + intID + " ORDER BY Note_Date DESC");

    ArrayList<Note> alNotes = new ArrayList<Note>();

    while (rs.next()) {
        int i = rs.getInt("NOTE_ID");
        alNotes.add(new Note(i));
    }
    db.Disconnect();
    return alNotes;
}

public static ArrayList<Vaccination> getTblVaccination(int intID) throws Exception {
    CC_H2 db = new CC_H2();
    db.Connect(Variables.getStrConn(), Variables.getStrUser(),
            Variables.getStrPassword(), "Embedded");
    ResultSet rs = db
            .query("Select Vac_ID FROM tblVaccination WHERE VAC_HERD_ID = "
                    + intID + " ORDER BY Vac_Date DESC");

    ArrayList<Vaccination> alVaccinations = new ArrayList<Vaccination>();

    while (rs.next()) {
        int i = rs.getInt("VAC_ID");
        alVaccinations.add(new Vaccination(i));
    }
    db.Disconnect();
    return alVaccinations;
}

public static ArrayList<Owner> getTblOwners(int intID) throws Exception {
    CC_H2 db = new CC_H2();
    db.Connect(Variables.getStrConn(), Variables.getStrUser(),
            Variables.getStrPassword(), "Embedded");
    ResultSet rs = db
            .query("Select Owner_ID FROM tblOwners WHERE Owner_ID = "
                    + intID + " ORDER BY Owner_Last_Name ASC");

    ArrayList<Owner> alOwners = new ArrayList<Owner>();

    while (rs.next()) {
        int i = rs.getInt("Owner_ID");
        alOwners.add(new Owner(i));
    }
    db.Disconnect();
    return alOwners;
}

Well, Your code looks good, and your suspicion seems right. I would agree with you. My reasoning is that your objects should be modeled after the problem rather than the data base schema. Here I would say that the other getTbl* methods are actually getters on particular animals. So it makes sense to move them to Animal class and rename the getTbl* methods accordingly, i.e getAnimalVaccinationList.

I would also recommend to refactor all these methods so that the db connect, and processing are in a different method,

public static ArrayList<Integer> runDbQuery(String query, String field) throws DbException {
    try {
      CC_H2 db = new CC_H2();
      db.Connect(Variables.getStrConn(), Variables.getStrUser(),
            Variables.getStrPassword(), "Embedded");
      ResultSet rs = db.query(query);
      ArrayList<Integer> lst = new ArrayList<Integer>();
      while (rs.next()) {
        lst.add(new Vaccination(rs.getInt(field)));
      }
      db.Disconnect();
      return lst;
    } catch(SpecificException e) {
      // Do not throw exception, process the exception and throw
      // some thing relevant to your program.
      throw new DbException(e);
    }
}

and use this in other methods to avoid repetition. I would also recommend moving the getTblHerd to another class - say Herd because it has an independent identity other than db_tables.

Here is an example of using the above method

public static ArrayList<Note> getTblNotes(int intID) throws DbException {
    String query = "Select NOTE_ID FROM tblNotes WHERE NOTE_HERD_ID = "
                    + intID + " ORDER BY Note_Date DESC";

    ArrayList<Note> alNotes = new ArrayList<Note>();
    for (Integer i : runQuery(query, "NOTE_ID")) {
        alNotes.add(new Note(i));
    }
    return alNotes;
}


Best way to get nearest non-zero value from list I have a list of values and I need to, given any arbitrary starting index, find the closest value which is non zero, if the value at the starting index is zero...

Here is what I have:

def getNearestNonZero(start_index):
    mylist = [4,2,6,7,3,0,0,9,4,2,5,8,1,7]
    val = mylist[start_index]
    if val == 0:
        loop_length = 0
        after = mylist[start_index+1:]
        before = mylist[:start_index]
        before =  before[::-1]
        print(before, after)

        if len(before) >= len(after):
            loop_length = len(before)
        else:
            loop_length = len(after)

        for i in range(loop_length):
            if i < len(before):
                before_val = before[i]
            if i < len(after):
                after_val = after[i]

            if before_val > 0:
                return before_val

            if after_val > 0:
                return after_val

    return val

result = getNearestNonZero(6)
print(result)

result = getNearestNonZero(5)
print(result)

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

  9

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

  3

What I do, is I first check to see if the value at the start_index is > 0. If it is, great, return it. If however, the value is zero, we need to find the closest non-zero, with a preference for before, rather than after...

To do this, I split mylist into two separate lists, before and after. If my start index is 6, before will now look like: [4,2,6,7,3,0] and after will look like: [9,4,2,5,8,1,7].

Since I need the closest value to the start_index, I reverse my before list: before = before[::-1]

I then get the length of the longest of the two (before and after).

I then loop and check the value at each index of the two lists. The first one to have a value > 0 is returned and my work is done.

However, this feels very clunky and as if it can be done in a cleaner way.

Does anyone have any recommendations? What is the faster/cleaner/pythonic way for finding the nearest non-zero value in a list, given a starting index?

I really like your idea of splitting the list -- it's very functional! Let's look at optimizing that approach, though.

def nearest_non_zero(lst, idx):
    # note that I parameterized the list. Should make it easier to test.
    # though I'll use [4,2,6,7,3,0,0,9,4,2,5,8,1,7] as in your code for
    # all examples throughout

    if lst[idx] > 0:
        return lst[idx]
        # I find it easier to track early-exit routes through code than
        # to rule everything out. Let's short-circuit if possible!

    before, after = reversed(lst[:idx]), lst[idx+1:]
    # using `reversed` here lets us avoid creating a new list, which
    # is otherwise necessary if we did `(lst[:idx])[::-1]`. Imagine
    # using that on a list with length of ten million. Yikes!

So far I've really only cleaned up a little bit of code, nothing big, but here is where I'll make a decent departure from your original code. Your code does this:

if len(before) >= len(after):
    loop_length = len(before)
else:
    loop_length = len(after)

This is unnecessary, and it forces you to write in the guards inside your for loop to make sure you're not indexing a value outside of the list length. That's too much work. There's a couple better ways, the primary one being itertools.zip_longest.

The builtin zip pulls together two (or more!) lists into one list of tuples. For instance

>>> a = [1, 2, 3]
>>> b = ['a', 'b', 'c']
>>> zip(a, b)
[(1, 'a'), (2, 'b'), (3, 'c')]
>>> zip(b, a)
[('a', 1), ('b', 2), ('c', 3)]

However if you have lists of uneven size, it will only go so far as the shortest list

>>> a = [1, 2]
>>> b = ['a', 'b', 'c']
>>> zip(a, b)
[(1, 'a'), (2, 'b')]  # where's 'c'?!?!

That's not what we want here. We want to zip together every value from both the before and after lists and compare them. That's what itertools.zip_longest does. But of course it needs another value: what should I use to pair with a value that doesn't exist? That's the parameter fillvalue, which by default is None

>>> a = [1, 2]
>>> b = ['a', 'b', 'c']
>>> itertools.zip_longest(a, b)
[(1, 'a'), (2, 'b'), (None, 'c')]  # there's 'c', phew!

>>> a = [1, 2]
>>> b = ['a', 'b', 'c']
>>> itertools.zip_longest(b, a, fillvalue="foobar")
[('a', 1), ('b', 2), ('c', 'foobar')]

That's exactly what we want! In this case we want our fillvalue to explicitly be a failing case (since if the number doesn't really exist we obviously don't want to use it), and our failing case is zero.

After that we compare to zero our "before" value, then our "after" value (to implement that preference for before rather than after), and return either if it's appropriate to do so.

import itertools

for b_val, a_val in itertools.zip_longest(before, after, fillvalue=0):
    if b_val > 0:
        return b_val
    elif a_val > 0:
        return a_val
else:
    # what do you do if you have a list that's all zeroes?

This keeps us from having to deal with any indexing at all, which is common idiomatically in Python. If you have to do for i in range(...): some_list[i], then you're probably doing something wrong!

Our final code, then is:

from itertools import zip_longest

def nearest_non_zero(lst, idx):
    if lst[idx] > 0:
        return lst[idx]
    before, after = lst[:idx], lst[idx+1:]
    for b_val, a_val in zip_longest(reversed(before), after, fillvalue=0):
        # N.B. I applied `reversed` inside `zip_longest` here. This
        # ensures that `before` and `after` are the same type, and that
        # `before + [lst[idx]] + after == lst`.
        if b_val > 0:
            return b_val
        if a_val > 0:
            return a_val
    else:
        return 0  # all zeroes in this list


Wrapper functions for terminal capabilities I've prepared a small C interface so the rest of my program can access relevant system functions.  I am not a C programmer, though - just C++ and D, mainly.  I want to make sure that everything here is "C-ish" before committing the rest of my code to this interface.

This is just a plain old C file, compiled with a C compiler (as opposed to C++).

    /*
     * This file provides functions to interface with
     * low-level terminal properties such as size and
     * input modes.  Functions meant to be accessible
     * to external "user" code begin with "Terminal."
     */

#include <sys/ioctl.h> // For interfacing with the terminal device.
#include <termios.h> // Ditto.
#include <unistd.h> // For the STDIN_FILENO file descriptor macro.

// This is just used internally, and should not be called directly from D code.
struct winsize Size()
{
    struct winsize Size;
    ioctl(STDIN_FILENO, TIOCGWINSZ, &Size);
    return Size;
}

unsigned short int TerminalColumnCount()
{
    return Size().ws_col;
}

unsigned short int TerminalRowCount()
{
    return Size().ws_row;
}

// Used to reset the terminal properties to their original state.
// Again, this is only for internal use.
struct termios BackupProperties;

// Removes terminal input buffering so programs can see typed characters before Enter is pressed.
void TerminalMakeRaw() // I wish I could come up with a better name for this.
{
    tcgetattr(STDIN_FILENO, &BackupProperties);
    struct termios NewProperties;
    cfmakeraw(&NewProperties);
    tcsetattr(STDIN_FILENO, TCSANOW, &NewProperties);
}

void TerminalReset()
{
    tcsetattr(STDIN_FILENO, TCSANOW, &BackupProperties);
}

A few quick comments:

You should declare all internal functions and variables static to avoid polluting the global namespace. (You'd do this in a C++ program as well, but would probably use an unnamed namespace. I'm not sure what the D equivalent is).
Since you have state (implicitly and explicitly via BackupProperties) I'd recommend using an object oriented approach exposing an opaque pointer to maintain it, even if there is only one Terminal instance it's (IMO) a better approach. Otherwise you should at least ensure that TerminalMakeRaw isn't called twice without corresponding calls to TerminalReset.
You should also consider that at some point you'll probably want to have callbacks of some sort to notify the users of your library when/if the window size changes and so on.