texts: Setting the Owner property on a modal dialog in WPF/MVVM using a Func

texts:
I'm looking to solve the problem of setting the Owner property on modal dialogs in WPF, while using IoC and MVVM patterns. I've seen (and written) all sorts of hacks.

To illustrate the problem, here's a naive example of a window with a viewmodel containing an ICommand which prompts the user. It works by having the view set vm.Owner = this, and then the viewmodel using Owner later in a MessageBox when the command is called.

public partial class MyWindow : Window
{
    private readonly MyWindowViewModel vm;

    public MyWindow(MyWindowViewModel vm)
    {
        InitializeComponent();
        DataContext = vm;
        vm.Owner = this;
    }
}

public class MyWindowViewModel
{
    private readonly RelayCommand<object> fooCommand;

    public ICommand FooCommand => fooCommand;
    public Window Owner { get; set; }

    public MyWindowViewModel()
    {
        fooCommand = new RelayCommand<object>(OnFooCommand);
    }

    private void OnFooCommand(object obj)
    {
        if (MessageBox.Show(Owner, "Are you sure?", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
        {
            // ...
        }
    }
}

This works, but the ViewModel is doing View-related things like opening message boxes, and knowing who owns it.

Here's an example that abstracts the dialog into a Func, which is set in the constructor of the Window.

public partial class MyWindow : Window
{
    private readonly MyWindowViewModel vm;

    public MyWindow(MyWindowViewModel vm)
    {
        InitializeComponent();
        DataContext = vm;
        vm.OkCancelBox = OkCancelBox;
    }

    private MessageBoxResult OkCancelBox(string text)
    {
        return MessageBox.Show(this, text, "Confirm", MessageBoxButton.OKCancel, MessageBoxImage.Question);
    }
}

public class MyWindowViewModel
{
    private readonly RelayCommand<object> fooCommand;

    public ICommand FooCommand => fooCommand;
    public Func<string, MessageBoxResult> OkCancelBox { get; set; } = s => throw new NotImplementedException();

    public MyWindowViewModel()
    {
        fooCommand = new RelayCommand<object>(OnFooCommand);
    }

    private void OnFooCommand(object obj)
    {
        if (OkCancelBox("Are you sure?") == MessageBoxResult.OK)
        {
            // ...
        }
    }
}

This feels better, now my ViewModel calls OkCancelBox and gets back a MessageBoxResult, without knowing anything about the View. If you "forget" to set OkCancelBox, you'll get a NotImplementedException. In a test, I can trivially set the Func to simulate the user clicking "OK":

vm.OkCancelBox = s => MessageBoxResult.OK;

Still, I'm not sure I like it.

There are other solutions like passing in (or service-locating) an IMessageBoxService, but I don't fully understand how you can specify the owner of a dialog without the ViewModel knowing who owns it.

Any thoughts on my implementation using Func<string, MessageBoxResult>?


texts: Optimized MySQL query with complex calculation

texts:
I am trying to pick 3 providers with the highest calculated score based on my algorithm, to recommend them to a user.

The recommendation algorithm takes into account a few things. Most are static values, but the one that is dynamic is the physical distance from the user (based on lat/lng). Since each user's location is different, I can't cache the distance in the DB.

I also need to limit the results to a) providers in a certain category (the WHERE ... IN clause), and b) providers that the user has not already added (the WHERE ... NOT IN clause)

Finally I order by score descending limit 3. Here is the query I am running. {$algorithm} is just a complex equation, {$categories} is a comma-separated list

SELECT `id`,
    {$algorithhm} AS `score`
    FROM `provider`
    WHERE `id` IN (
        SELECT `provider_id`
        FROM `provider_categories`
        WHERE `category_id` IN ( {$categories} )
    )
    AND `id` NOT IN (
        SELECT `provider_id`
        FROM `users_provider`
        WHERE `user_id` = {$current_user->id}
    )
    ORDER BY `score` DESC
    LIMIT 3

I have indexes on every column name you see here. There are only about 13,000 provider records in the database, yet the query takes about .04 seconds on average, which seems pretty slow to me. Back when there were 1,500 providers, it only took .003 seconds. Since I'm hoping to one day have hundreds of thousands, obviously this is a growing concern.

What can I do to speed this query up?

EXPLAIN tells me this:

   type             table                 type             key    ref          rows    Extra
1  PRIMARY          provider              ALL              NULL   NULL         12880   Using where; using filesort
3  DEPENDENT SUBQ   users_provider        eq_ref           PRI    const, func  1       Using where; using index
2  DEPENDENT SUBQ   provider_categories   index_subquery   PRI    func         1       Using index; using where

Edit

One thought I had was to limit it to providers within an X mile radius. But since the dynamic part of the algorithm is the distance calculation, I would still need to calculate the distance for every provider up front, so that doesn't really help. Maybe instead of a circular radius, I could check within a square lat/lng boundary, since those columns are indexed and the distance wouldn't need to be calculated... just thinking out loud. The main problem with this is that the geocoordinate to mile conversion is very different near the equator vs. near the poles.


texts:
When you were a little kid, was indiscriminately flicking light switches super fun? I know it was for me. Let's tap into that and try to recall that feeling with today's challenge.
Imagine a row of N light switches, each attached to a light bulb. All the bulbs are off to start with. You are going to release your inner child so they can run back and forth along this row of light switches, flipping bunches of switches from on to off or vice versa. The challenge will be to figure out the state of the lights after this fun happens.

The input will have two parts. First, the number of switches/bulbs (N) is specified. On the remaining lines, there will be pairs of integers indicating ranges of switches that your inner child toggles as they run back and forth. These ranges are inclusive (both their end points, along with everything between them is included), and the positions of switches are zero-indexed (so the possible positions range from 0 to N-1).

#include <iostream>
#include <vector>
#include <stdexcept>

class lights;

void ifBiggerSwitch(unsigned&, unsigned&);
std::ostream &print(std::ostream&, lights&);

class lights {
public:
    friend std::ostream &print(std::ostream&, lights&);

    lights() = default;
    lights(unsigned ammount) { setLights(ammount); }

    void setLights(unsigned ammount) { lightsOn.assign(ammount, false); }
    void switchLights(unsigned num1, unsigned num2);
private:
    std::vector<bool> lightsOn;
};

void lights::switchLights(unsigned num1, unsigned num2) {
    ifBiggerSwitch(num1, num2);
    ++num2;
    for (auto beg = lightsOn.begin() + num1; beg != lightsOn.begin() + num2; ++beg) {
        *beg = !*beg;
    }
}

// Non member functions

void ifBiggerSwitch(unsigned &num1, unsigned &num2) {
    if (num1 > num2) {
        unsigned tempNum1 = num1;
        num1 = num2;
        num2 = tempNum1;
    }
}

std::ostream &print(std::ostream &os, lights &light) {
    for (auto c : light.lightsOn)
        os << c << " ";
    return os;
}


texts: Find the number of times that the difference of array values are equal to the number

texts:
I wrote the following code to answer this, but I am wondering if there is any better approach.

For example

If the following array is given:

{10,21,34,45,56}

we should find the differentiate of each number with other values of the array and in case it is equals to 11 should increment the counter.

10-21=-11
10-34=-24
10-45=-35
10-56=-46
21-10=11     <
21-34=-13
21-45=-24
21-56=-35
34-10=24
34-21=13
34-45=-11
34-56=-22
45-10=35
45-21=24
45-34=11   <<
45-56=-11
56-10=46
56-21=35
56-34=22
56-45=11   <<<

Code

List<Integer> a = new ArrayList<Integer>();
       a.add(10);
       a.add(21);
       a.add(34);
       a.add(45);
       a.add(56);
      int number = 11;
      int counter = 0;
       for(int i=0;i<a.size();i++){
           for(int j=0;j<a.size();j++){
               if(j!=i){
                   int t = a.get(i) - a.get(j);
                   if(t == number){
                       System.err.println(a.get(i) +"-"+ a.get(j) + "=" + t);
                       counter++;
                   }
               }
           }
       }
       System.err.println(counter);
    }

Output

The application is correctly showing the results but I am wondering if there is any other approach to the above solution.

21-10=11
45-34=11
56-45=11
3


texts: Efficiency of Recursive Checkers Legal Move Generator

texts:
I'm implementing a checkers engine for a scientific experiment. I found out through profiling that this is one of the functions that takes up a lot of time. I'm not looking for an in-depth analysis, because I don't expect you to dive super deep into my code.

Just: are there any obvious inefficiencies here? Like, is it slow to do those starting for loops (dx, dy) just for 2 values each?

def captures(self, (py, px), piece, board, captured=[], start=None):
    """ Return a list of possible capture moves for given piece in a
        checkers game.

        :param (py, px): location of piece on the board
        :param piece: piece type (BLACK/WHITE|MAN/KING)
        :param board: the 2D board matrix
        :param captured: list of already-captured pieces (can't jump twice)
        :param start: from where this capture chain started.
        """
    if start is None:
        start = (py, px)
    # Look for capture moves
    for dx in [-1, 1]:
        for dy in [-1, 1]:
            dist = 1
            while True:
                jx, jy = px + dist * dx, py + dist * dy # Jumped square
                # Check if piece at jx, jy:
                if not (0 <= jx < 8 and 0 <= jy < 8):
                    break
                if board[jy, jx] != EMPTY:
                    tx, ty = px + (dist + 1) * dx, py + (dist + 1) * dy # Target square
                    # Check if it can be captured:
                    if ((0 <= tx < 8 and 0 <= ty < 8) and
                        ((ty, tx) == start or board[ty, tx] == EMPTY) and
                        (jy, jx) not in captured and
                        ((piece & WHITE) and (board[jy, jx] & BLACK) or
                         (piece & BLACK) and (board[jy, jx] & WHITE))
                        ):
                        # Normal pieces cannot continue capturing after reaching last row
                        if not piece & KING and (piece & WHITE and ty == 0 or piece & BLACK and ty == 7):
                            yield (NUMBERING[py, px], NUMBERING[ty, tx])
                        else:
                            for sequence in self.captures((ty, tx), piece, board, captured + [(jy, jx)], start):
                                yield (NUMBERING[py, px],) + sequence
                    break
                else:
                    if piece & MAN:
                        break
                dist += 1
    yield (NUMBERING[py, px],)


texts:
According to Rosetta Code:

The Chaos Game is a method of generating the attractor of an iterated
function system (IFS). One of the best-known and simplest examples
creates a fractal, using a polygon and an initial point selected at
random.
Task
Play the Chaos Game using the corners of an equilateral triangle
as the reference points. Add a starting point at random (preferably
inside the triangle). Then add the next point halfway between the
starting point and one of the reference points. This reference point
is chosen at random.
After a sufficient number of iterations, the image of a Sierpinski
Triangle should emerge.

Here is my solution in Python:
"""This module performs the Chaos Game."""

from random import choice
from PIL import Image

def midpoint(p1, p2):
    """
    Takes 2 points and calculates the midpoint.
    Args:
        p1 (real, real): A point in space.
        p2 (real, real): Another point in space.
    Returns:
        (real, real): The midpoint between p1 and p2.
    """
    return (p1[0] + p2[0]) / 2, (p1[1] + p2[1]) / 2

def translate(point, screen_size):
    """
    Takes a point and converts it to the appropriate coordinate system.
    Note that PIL uses upper left as 0, we want the center.
    Args:
        point (real, real): A point in space.
        screen_size (int): Size of an N x N screen.
    Returns:
        (real, real): Translated point for Pillow coordinate system.
    """
    return point[0] + screen_size / 2, point[1] + screen_size / 2

def image_rep(point, img_size):
    """
    Returns a representation of the point that can be used by Pillow.
    Args:
        point (real, real): A point in space.
        img_size (int): The size of an N x N image
    """
    # Convert the point to the correct coordinate system.
    translated = translate((point[0], point[1]), img_size)
    # Make it an integer so Pillow can use it.
    return int(translated[0]), int(translated[1])

def play_chaos(guiders, seed, img, steps=1000):
    """
    Play the Chaos Game:
    1. Have a collection of n (ordered) "guider" points.
    2. Start with a random seed some where on the screen.
    3. Roll die that has n sides
    4. Make a new point that is halfway between the appropriate gudier and the
       previous point.
    5. Repeat the game from the new point
    Args:
        guiders ([(real, real)]): List of guider points
        seed (real, real): Initial seed, be sure to be within the screens range
        img (Image): Image to write spiral to.
        steps (int): The amount of times the process is repeated.
        (default: 1000)
    """
    prev_point = seed
    for _ in range(steps):
        # Select the next guider to move closer to
        guider = choice(guiders)
        new_point = midpoint(prev_point, guider)
        img.putpixel(image_rep(new_point, img.size[0]), 1)
        prev_point = new_point

def main():
    """
    Main method, start of the program. Creates an image and populates it with
    chaos.
    """
    IMAGE_SIZE = 300, 300
    img = Image.new('1', IMAGE_SIZE)
    SEED = (0.0, 0.0)
    GUIDERS = [(-100.0, -100.0),
               (100.0, -100.0),
               (0.0, 100.0)]
    play_chaos(GUIDERS, SEED, img)
    img.save('chaos.png')

if __name__ == '__main__':
    main()


texts:
I'm working on a grammar for the Visual Basic for Applications (VBA) programming language.  I've discovered a way to make assertions about how a parse tree should be generated by using the Antlr ToStringTree method.

My method is this:

Create a parser and give it a code snippet.
Obtain the parse tree result and turn it into a string using ToStringTree.
Perform a string comparison ignoring whitespace.

What I'm thinking though, is that I may be a little too prescriptive in the final step.  As an example, I'm working through the valid identifier use cases in my unit tests:

public class ModuleStatementTests
{
    private readonly List<string> ambiguousIdentifiers = new List<string>()
    {
        "Access",
        "Alias",
        "Append",
        "Base",
        "Binary",
        "ClassInit",
        "ClassTerm",
        "CLngLng",
        "Compare",
        "Database",
        "DefLngLng",
        "Error",
        "Explicit",
        "Lib",
        "Line",
        "LongLong",
        "Mid",
        "MidB",
        "Module",
        "Object",
        "Output",
        "Property",
        "PtrSafe",
        "Random",
        "Read",
        "Reset",
        "Step",
        "Text",
        "Width"
    };

    [Fact]
    public void CanParseAmbiguousIdentifierInVariableDeclaration()
    {
        const string variableDeclarationTemplate = "Dim {0} As String";
        const string expectedVariableDeclaration =
                        "(variableDeclaration Dim (variableDclList (variableDcl (untypedVariableDcl (identifier {0}) (asClause (asType As (typeSpec (typeExpression (builtInType (reservedTypeIdentifier String))))))))))";

        CanParseAllAmbiguousIdentifiers(variableDeclarationTemplate, expectedVariableDeclaration, p => p.variableDeclaration());
    }

    private void CanParseAllAmbiguousIdentifiers(string sourceTemplate, string expectedOutputTemplate, Func<VbaParser, ParserRuleContext> rule)
    {
        foreach (var id in ambiguousIdentifiers)
        {
            var source = string.Format(sourceTemplate, id);
            var expectedTree = string.Format(expectedOutputTemplate, id);

            CanParseSource(source, expectedTree, rule);
        }
    }

    private static void CanParseSource(string source, string expectedTree, Func<VbaParser, ParserRuleContext> rule)
    {
        var parser = VbaCompilerHelper.BuildVbaParser(source);

        var result = rule(parser);

        Assert.Null(result.exception);
        ParseTreeHelper.TreesAreEqual(expectedTree, result.ToStringTree(parser));
    }
}

internal static class ParseTreeHelper
{
    internal static void TreesAreEqual(string expected, string actual)
    {
        if (expected == null || actual == null)
        {
            Assert.True(false, "Expected and/or Actual are null.");
        }
        var filteredExpected = RemoveWhiteSpace(expected);
        var filteredActual = RemoveWhiteSpace(actual);
        Assert.Equal(filteredExpected, filteredActual);
    }

    private static string RemoveWhiteSpace(string input)
    {
        // the final \\t replacement is necessary because antlr seems to add it to the ToStringTree method.
        return input.Replace("\t", "").Replace(" ", "").Replace("\\t", "");
    }
}

My concern is that I'm being very prescriptive in my expectations for the test in specifying the entire parse tree output (in string form).  I've already broken a lot of unit tests, just refactoring my grammar, which should not have broken these tests (semantically at least).  It means I have to alter my tests as much as my grammar making them highly coupled.

The purpose of this test is to see whether the grammar will accept any of the ambiguous identifiers, not so much the rest of the parse tree structure.  This example is relatively simple, when a more complex snippet is used, the parse tree string gets crazy real quick!

PS: I've elided a bunch of code and if I've missed anything relevant to understanding this, let me know and I'll update.  The full source is in the link earlier as well.


texts: Using a class for reading config from files

texts:
The goal of my current piece of work is to read from a global config file all the settings and then from the local file only those settings that a user has chosen.

Firstly I wrote a function but then I needed a class. It's my first working class in Python, and I ask if you can kindly note its defects. Although it works, I think it can for sure be written more correctly and concisely.

Here's all the beginning:

# files to be read from
cmd_parameter = "config_1.cfg"
cmd_parameter_global = "global.cfg"

if len(sys.argv) == 2:
    cmd_parameter = sys.argv[1]
else:
    print("Error: there should be one argument after program name - config file name")
    exit(-1)

config_file = []
config_file_global = []

# reading user's config file
try:
    with open(cmd_parameter, 'r') as config_file_name:
        config_file = config_file_name.readlines()
except FileNotFoundError:
    print("File '", sys.argv[1], "' not exists or not available")
    exit(-1)

# reading global config file
try:
    with open(cmd_parameter_global, 'r') as config_file_global_name:
        config_file_global = config_file_global_name.readlines()
except FileNotFoundError:
    print("Global configuration file '", cmd_parameter_global, "' not exists or not available")
    exit(-1)

# parsing config file, reading values from it to list and matching parameters with a given argument
# parameters in config file should start with <conf_key_split1>, value should be separated from parameter by <conf_key_split2>
config_param_user = []
config_value_user = []
config_param_global = []
config_value_global = []
config = ""
conf_key_split1 = '.'
conf_key_split2 = '='
conf_key_split3 = ','

# reading user's config file
for line in config_file:
    if line.startswith(conf_key_split1):
        line = line.rstrip().split(conf_key_split1)
        line = line[1]

        line = line.rstrip().split(conf_key_split2)
        config_param_user.append(line[0])
        config_value_user.append(line[1])

# reading global config file
for line in config_file_global:
    if line.startswith(conf_key_split1):
        line = line.rstrip().split(conf_key_split1)
        line = line[1]

        line = line.rstrip().split(conf_key_split2)
        config_param_global.append(line[0])
        config_value_global.append(line[1])

And here is the class itself:

# class for reading config from user's and global config file the list of params names list and the list of values
class configFromFile():
    def config_from_file_userfile(self, param):
        index = config_param_user.index(param)
        if config_value_user[index]:
            config_value = config_value_user[index]
        else:
            print('The value of the parameter "', param, '" was not found in', cmd_parameter)
            exit(-1)

        return config_value

    def config_from_file_global(self, param):
        index = config_param_global.index(param)
        if config_value_global[index]:
            config_value = config_value_global[index]
        else:
            print('The value of the parameter "', param, '" was not found in', cmd_parameter_global)
            exit(-1)

        return config_value

    def main(self, param):
        if param in config_param_global:
            config = self.config_from_file_global(param)
        elif param in config_param_user:
            config = self.config_from_file_userfile(param)
        else:
            print('The parameter "', param, '" was not found in', cmd_parameter, 'and in', cmd_parameter_global)
            exit(-1)

        return config

Usage:

names = configFromFile().main('names')


texts: Inserting large amounts data into Excel spreadsheet

texts:
I have a VSTO Excel Add-In which is used to retrieve data from another application and insert it into an Excel worksheet. Due to the potential for lots of pieces of data to be inserted into a spreadsheet, performance is a concern. Potentially thousands of rows could be inserted.

Here is the method which inserts data into an Excel spreadsheet.

Note: Using Microsoft.Office.Interop.Excel

private Worksheet Worksheet { get { return Globals.ThisAddIn.Application.ActiveSheet; } }
private Range Cells { get { return Globals.ThisAddIn.Application.ActiveSheet.Cells; } }

private void PopulateCurrentWorksheet(ReportData data, int columnIndex, int rowIndex)
{
    if (data == null)
        throw new ArgumentNullException("No valid ReportData available");

    // NOTE: Excel uses indexing that starts at 1
    if (columnIndex == 0)
        columnIndex = 1;

    if (rowIndex == 0)
        rowIndex = 1;

    int startingRowIndex = rowIndex;

    foreach (ReportColumn column in data.Columns)
    {
        Cells[columnIndex][rowIndex].Value = column.ColumnName;
        Cells[columnIndex][rowIndex].Font.Bold = true; // put the header in bold
        for (int i = 0; i < column.ColumnData.Length; i++)
        {
            rowIndex++; // move down a cell to the next row
            Cells[columnIndex][rowIndex] = column.ColumnData.ElementAt(i);
        }
        rowIndex = startingRowIndex;
        columnIndex++; // move right a cell to the next column
    }

    Worksheet.Columns.AutoFit();
}

Below is the ReportData class (and associated ReportColumn class) which holds data retrieved from an external application to be inserted into a worksheet

public class ReportData
{
    public ReportData(IEnumerable<ReportColumn> columns)
    {
        Columns = columns ?? throw new ArgumentNullException("No valid columns available");
    }

    public IEnumerable<ReportColumn> Columns { get; set; }
}

public class ReportColumn
{
    public ReportColumn(string columnName, object[] columnData)
    {
        ColumnName = columnName;
        ColumnData = columnData;
    }

    public string ColumnName { get; set; }
    public object[] ColumnData { get; set; }
}

When trying to insert data into a worksheet which results in over 100k rows, there is a significant performance hit. Is there anyway I could improve the code to make it faster? Any other advice is welcomed too.


texts: Finding all plurals in an array of Strings

texts:
I'm looking for feedback on this here code. Is readability an issue? Is it good to mess with all these data types in Java (e.g. strings and Chars and using .equals() and != to compare data from different data types), or is there an easier way to do it? And in general, how can I improve this code?

  Write a method named allPlural that accepts an array of strings as a
  parameter and returns true only if every string in the array is a
  plural word, and false otherwise. For this problem a plural word is
  defined as any string that ends with the letter S, case-insensitively.
  The empty string "" is not considered a plural word, but the
  single-letter string "s" or "S" is. Your method should return true if
  passed an empty array (one with 0 elements).

   public static boolean allPlural(String[] words){
        for (String s : words) {
            // blank string is not plural
            if (s.equals("")) {
                return false;
            }
            // if the strings in the array don't have an s on the end, return false
            if (Character.toUpperCase(s.charAt(s.length()-1)) != 'S') {
                return false;
            }
        }
        return true;
    }


texts: Scraping table contents from a webpage using vba with selenium

texts:
My script is able to harvest full contents of a table from a webpage with javascript encrypted using vba in combination with selenium. The table has got a drop-down option from where the full contents can be selected by hitting "all". The table has got 300 rows of data which spread 7 column across. There are around seven steps to traverse to reach the destination page. It takes a while to parse them all. Just run it, sit back and relax until the browser is closed. It works perfectly. I could not manage to create the script with explicit wait cause I doubt there is any option in vba. Here is the working code.

Sub Table_Data()

Dim driver As New WebDriver
Dim posts As Object, post As Object, t_data As Object

With driver
    .Start "chrome", "http://apps.tga.gov.au/Prod/devices"
    .get "/daen-entry.aspx"
    .FindElementById("disclaimer-accept").Click
    .Wait 3000
    .FindElementById("medicine-name").SendKeys ("pump")
    .Wait 10000
    .FindElementByClass("medicines-check-all").Click
    .Wait 3000
    .FindElementById("submit-button").Click
    .Wait 5000
    .FindElementById("ctl00_body_MedicineSummaryControl_cmbPageSelection").Click
    .Wait 5000
    .FindElementByXPath("//option[@value='all']").Click
    .Wait 5000
End With

For Each posts In driver.FindElementsByXPath("//table[contains(@class,'daen-report')]")
    For Each post In posts.FindElementsByXPath(".//tr")
        For Each t_data In post.FindElementsByXPath(".//td[@class='row-odd']|.//td")
        y = y + 1
        Cells(x, y) = t_data.Text
        Next t_data
        x = x + 1
        y = 0
    Next post
Next posts
End Sub


texts: Pass pointer data across multiple functions

texts:
I would like review on the following dynamic memory allocation process and suggestions on whether there are any memory leaks. Following code is not real code in use, but I'm trying to understand concepts of memory allocations and de-allocation in different ways.

class ObjMapData
{
private:
//Header Info fields to describe each object actual data type, total elements of actual data type, and lot more describing the object common fields
int itsDataTypeID; // 1 to 20+, each represent one type of data being used
int itsDataType; // 1 to 8, which could be UINT8, INT8, UINT16, INT16, UINT32, INT32
int itsDataSize; // 1 or 2 or 4 bytes
int itsTotalElements; // original data type elements, but not the total bytes of the binary file
//...... other common header information
// body data, (actual data could be UINT8, INT8, UINT16, INT16, UINT32, INT32 type)
char* itsMapData; // size = itsTotalElements*itsDataSize; type cast to various actual data types later to access/populate the data
........
public:
ObjMapData();
ObjMapData& operator = (const ObjMapData& objMyMap);
ObjMapData(const ObjMapData& objMyMap);
~ObjMapData(){if(itsMapData!= NULL) delete[] itsMapData;}
//Following two functions are used to allocate/free memory within the scope of the object so that it can be re-used again for a different data type object
ClearMemory() {if(itsMapData!= NULL) {delete[] itsMapData; itsMapData= NULL}}
void AllocateMemory( unsigned long  nSizeInBytes = 0)
{
if(itsMapData!= NULL)   {delete[] itsMapData; itsMapData= NULL;}
itsMapData= new (std::nothrow) INT8[nSizeInBytes];
}
.......
void SetMapData(char* ptrData) { itsMapData = ptrData;} // or should I use char*&ptrData??
char* GetMapData() const { return itsMapData;}
}

Now can I do the following without any memory leaks?

//There are 30+ functions like Function1() to populate the map data of different type of maps using different sources of input data or algorithms
bool Function1(ObjMapData& objMyMap)
{
//populate the ptrData with some data values using many different ways
int* ptrData = new int[1000]; // usually a variable from binary file header

......................
objMyMap.SetMapData((char*)ptrData);
//don't want to delete the memory yet as this map will be used along with map objects to create a new mapdata
return true;
}

bool Function2(ObjMapData& objMyMap)
{
int* ptrData = (int*) objMyMap.GetMapData();
//do some work such as writing updated data and then write into a binary file
}

bool Function3(ObjMapData& objMyMap)
{
//populate the data using different method for different map data types
//there could be 30+ other functions like Function1() to populate the map data
bool bStatus = Function1(objMyMap);

int* ptrData = (int*)objMyMap.GetMapData();
//update the map data by modifying ptrData variable
..........
objMyMap.SetMapData((char*)ptrData); // Do I need to set again or member pointer get updated automatically?
bStatus = Function2(objMyMap); // write data to a binary file
objMyMap.ClearMemory(); // not real code  in use, but for understanding the concept
bStatus = Function1(objMyMap); // re-allocate memory and assign a new Map Data
short* ptrData2 = (short*) objMyMap.GetMapData();
//update the map data using ptrData variable
objMyMap.SetMapData((char*)ptrData2); // Do I need to set again or member pointer get updated automatically?
return true
}
int main()
{
ObjMapData objMyMap;
bool bStatus = Function3(objMyMap);
short* ptrData = (short*)objMyMap.GetMapData();
//do something with ptrData
//default destructor of objMyMap can take care of the allocated memory cleanup
return 0;
}


texts: Setting global environment vars from Python or Bash

texts:
#!/usr/bin/env python

from os import environ, path, name as os_name, getuid
from sys import exit
from fileinput import input

update_environ = lambda: environ.update(dict(env.split('=')
                                        for env in
                                        open('/etc/environment', 'r').readlines()))

if os_name != 'nt' and getuid() != 0:
    print "Rerun {0} as `sudo`".format(__file__)
    exit(1)

def custom_vars(e_vars):
    if not path.isfile('custom_vars.txt'):
        return e_vars
    with open('custom_vars.txt', 'r') as f:
        for line in f.readline():
            var = line.split()
            e_vars[var[0]] = var[1]

def append_environment(e_vars):
    for line in input('/etc/environment', inplace=True):
        var, _, val = line.partition('=')
        nline = '{var}={val}'.format(var=var, val=e_vars.pop(var, val))
        if nline and nline != '=' and nline != '\n' and nline != '=\n':
            print nline  # inplace editing

    if e_vars:
        lines = filter(lambda l: l != '=\n' and nline != '\n',
                       ['{var}={val}\n'.format(var=k, val=e_vars[k])
                        for k in e_vars])
        with open('/etc/environment', 'a') as f:
            f.writelines(lines)

if __name__ == '__main__':
    environment_vars = {'NOM_REPOS': path.join(path.expanduser("~"), 'NOM'),
                        'NOM_API': path.join('/var', 'www')}

    environment_vars = custom_vars(environment_vars)
    append_environment(environment_vars)

I have written a similar script in Bash; with identical functionality:

#!/usr/bin/env bash

sudo sed -i "/^NOM*/d" /etc/environment
for i in `env | grep NOM | cut -f1 -d=`; do
    unset "$i";
done

function set_var()
{
    VAR="$1"
    VAL="$2"

    sudo sed -i "/^$VAR/d" /etc/environment
    printf "$VAR=$VAL\n" | sudo tee -a /etc/environment > /dev/null

    # make the variable available for use in this script and custom_env_vars.sh
    export "$VAR=$VAL"
}

set_var NOM_REPOS "$HOME/NOM"
set_var NOM_API /var/www

if [ -f custom_env_vars.sh ]; then
    . ./custom_env_vars.sh
else
    echo "You can set custom environment variables in 'custom_env_vars.sh'"
fi


texts: Creating a searchable collection of rooms

texts:
I'm trying to learn C++ again, trying to do all the "modern" stuff (e.g., avoid pointers in favor of references) and I found that I have some trouble understanding how references and lifetimes work. I'm using clang with -std=c++11.

I want to have a RAII-class, RoomList that basically wraps a map<int, Room>. On construction of RoomList, it will create all the Rooms (imagine loading them from a data file or so) and the map, and on destruction it should free the map and all Rooms.

This code works, but I don't fully understand all of it (I've done a lot of "randomly trying stuff" to get it to work). (GIST is here)

The Room class:

class Room {
public:
  explicit Room(int id, const std::string& name) : m_id(id), m_name(name) {}
  const std::string& GetName() const { return m_name; }
  const int& GetEnterCount() const { return m_enterCount; };
  void OnEnter() { ++m_enterCount; }
private:
  std::string m_name; // should this be const?
  int m_id; // should this be const?
  int m_enterCount = 0;
};

The RoomList class:

class RoomList {
public:
  RoomList();
  ~RoomList() = default; // Is this needed? Rule of three?
  RoomList(const RoomList&) = delete; // Don't want copies
  RoomList& operator=(RoomList const&) = delete;
  const Room& GetRoom(int index);
private:
  // Should this be <int, Room> or <int, Room&>?
  std::map<int, Room> m_rooms;
};

RoomList::RoomList() {
  // Read all the rooms, e.g., from a data file
  // What is the lifetime of the Room I'm creating?
  // Room doesn't have copy or move ctors
  // Also, I'm not initializing m_rooms - what is its lifetime?
  m_rooms.emplace(0, Room(0, "Start Room"));
}

// Returning a reference to const Room - no one should be able to modify Room, except by calling room.OnEnter()
// room.OnEnter() should modify the Room inside the map (Individual Rooms are basically Singletons)
const Room& RoomList::GetRoom(int index) {
  auto result = m_rooms.find(index);
  if(result != m_rooms.end())
  {
    // result is a local var - is result->second valid after return?
    return result->second;
  }

  // Considering Optional<Room>
  // https://github.com/akrzemi1/Optional/
  throw "Invalid Index";
}

main.cpp:

int main() {
  RoomList rooms;
  auto room = rooms.GetRoom(0);
  std::cout << "Name: " << room.GetName() << std::endl;
  return 0;
}

I left some comments, but basically the things I'm confused about:

I'm not initializing the m_rooms map - will it be default initialized to live as long as the rooms variable in main.cpp is in scope?
I have a map of Rooms, but I want to return Room references. Will returning a Room have any negative side effects? (e.g., is there some automatic creation of a wrapper object or even a copy of Room going on?)
Is result->second even still valid after a return? result is a local variable that should die when the function ends, but I'm returning what second points to, so that should be good?
Would I need to implement ~RoomList to make sure all the Rooms are freed? Or does std::map::emplace own the constructed Room?
If I wanted to return something by value, how would I need to allocate it? For example, imagine I've added this to Room, wouldn't I return a stack-allocated variable?

This code works, but I think it shouldn't:

class Room {
public:
  // ...
  std::string GetRoomDescription();
}

std::string Room::GetRoomDescription()
{
  // What's the lifetime of "result"?
  // In C, this would be stack-allocated and dead
  // when the function returns.
  std::stringstream result;
  result << "ID: " << m_id << " - Name: " << m_name;
  return result.str();
}

// main.cpp
std::cout << "Room: " << room.GetRoomDescription() << std::endl;


texts:
This is my implementation of an .NET ValidationAttribute to validate a string against a JSON schema. The JSON schema file is stored within the application as an embedded resource and is referenced by passing its fully qualified name in the constructor.

A couple of things I'm not 100% about:

Returning ValidationResult as opposed to throwing exceptions in certain circumstances - couldn't quite decide what the best approach was.
How I'm composing the error messages

Can anybody find fault with this implementation?

[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
public sealed class JsonSchemaAttribute : ValidationAttribute
{
    private const string _errorMessage = "Failed to validate field {0} against JSON schema {1}.";
    private readonly string _schemaName;

    public string SchemaName { get { return _schemaName; } }

    public JsonSchemaAttribute(string schemaName) : base(_errorMessage)
    {
        if (string.IsNullOrWhiteSpace(schemaName))
            throw new ArgumentNullException(schemaName);

        _schemaName = schemaName;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (value == null)
            return new ValidationResult(FormatErrorMessage(validationContext.DisplayName, "The value of the property cannot be null."));

        var jsonString = value as string;

        if (jsonString == null)
            return new ValidationResult(FormatErrorMessage(validationContext.DisplayName, $"Type {value.GetType()} is not supported."));

        var jObject = JObject.Parse(jsonString);

        if (jObject == null)
            return new ValidationResult(FormatErrorMessage(validationContext.DisplayName, "Failed to parse JSON string."));

        var schema = GetJsonSchema(_schemaName);

        if (schema == null)
            return new ValidationResult(FormatErrorMessage(validationContext.DisplayName, "Failed to parse JSON schema."));

        IList<string> validationErrors = new List<string>();
        var result = jObject.IsValid(schema, out validationErrors);

        if (!result)
            return new ValidationResult(FormatErrorMessage(validationContext.DisplayName, string.Join(" ", validationErrors)));

        return ValidationResult.Success;
    }

    public override string FormatErrorMessage(string name)
    {
        return string.Format(CultureInfo.CurrentCulture, ErrorMessageString, name, _schemaName);
    }

    private string FormatErrorMessage(string name, string reason)
    {
        return $"{FormatErrorMessage(name)} {reason}";
    }

    private JSchema GetJsonSchema(string name)
    {
        string result;

        using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(name))
        {
            if (stream == null)
                return null;

            using (var reader = new StreamReader(stream))
            {
                if (reader == null)
                    return null;

                result = reader.ReadToEnd();
            }
        }

        return JSchema.Parse(result);
    }
}


texts:
I've written a basic implementation of a singly linked list in Scala. I would appreciate any feedback and improvements (especially the remove() method, I feel like it could be implemented better).

Node class

class Node[T](data: T, var next: Option[Node[T]] = None) {
  override def toString: String = data.toString
}

Singly linked list implementation:

class SinglyLinkedList[T](var head: Node[T], var size: Int = -1){
  if(size == -1) size = calculateSize

  private def calculateSize: Int = {
    @scala.annotation.tailrec
    def traverse(count: Int, curNode: Option[Node[T]]): Int = curNode match {
      case None => count
      case Some(node) => traverse(count + 1, node.next)
    }
    traverse(0, Some(head))
  }

  override def toString: String = {
    @scala.annotation.tailrec
    def traverse(sb: StringBuilder, curNode: Option[Node[T]]): String = curNode match {
      case None => sb.append("None").toString
      case Some(node) => traverse(sb append (node + " --> "), node.next)
    }
    traverse(new StringBuilder, Some(head))
  }

  def append(d: T): Unit = {
    @scala.annotation.tailrec
    def traverse(curNode: Option[Node[T]]): Unit = curNode.flatMap(_.next) match {
      case None => curNode foreach (_.next = Some(new Node[T](d)))
      case next => traverse(next)
    }
    traverse(Some(head))
    size += 1
  }

  def remove(index: Int): Unit = {
    @scala.annotation.tailrec
    def traverse(elementsRemaining: Int, prevNode: Option[Node[T]], curNode: Option[Node[T]]): Unit = (elementsRemaining, curNode) match {
      case (_, None) => throw new NoSuchElementException
      case (0, n) =>
        if(prevNode.isEmpty) head.next.foreach(head = _)
        else prevNode.foreach(_.next = n.flatMap(_.next))
      case (i, n) => traverse(i - 1, n, n.flatMap(_.next))
    }
    traverse(index, None, Some(head))
    size -= 1
  }
}


texts: Creating number pattern (triangle numbers) in C++ with minimum loops

texts:
We were asked to make a triangular number pattern in C++ with minimum loops:

____1_____
___2__3____
__4__5__6__
7__8__9__10

Code:

#include <iostream>

using namespace std;
int main() {
    int n=0, r=0, i=0;
    cout << "No. of rows: ";
    cin >> r;

    for( n=1; n<=r; n++) {
        for( i=1; i<=r-n; i++) {
            cout << "  ";
        }
        for( i=(n*(n-1)/2)+1; i<=(n*(n+1)/2); i++ ) {
            if( i<10 )
                cout << " " << i << "  ";
            else
                cout << i << "  ";
        }
        cout << "\n";
    }
    return 0;
}

Output:

Here's what I'd like reviewed:

Is it wise to use pattern-generating formulas? For example, for putting value of i in the last loop, I used the formula for the pattern \$1,2,4,7\$... as \$\frac{n*(n-1)}{2}+1\$. Is it efficient? This involves four operations in each iteration, and it's fairly slow.
Is it possible to reduce the number of loops? Is it better to reduce variables or reduce loops?


texts:
Here is a homemade Future class:

class Future:
    """Represent sn asynchronous result.

    Use add_callback to construct a chain of callbacks to be called when the
    Future's result is ready.
    """

    def __init__(self):
        self.callbacks = []
        self._fired = False
        self.result = None

    def add_callback(self, callback):
        """Add a callback.

        Args:
            callback (function): A function taking one variable.
        """
        self.callbacks.append(callback)
        if self._fired:
            self._execute_callbacks(self.result)

    def set_result(self, result=None):
        """Set the initial result of the Future, starting the callback chain.

        Args:
            result: The result of the Future. This result is passed to the first
                callback, and then each callback's result is passed to the next.
        """
        if self._fired == True:
            raise RuntimeError("Cannot fire Future twice")
        self._fired = True
        self._execute_callbacks(result)

    def _execute_callbacks(self, result):
        self.result = result
        while len(self.callbacks):
            cb = self.callbacks.pop(0)
            self.result = cb(self.result)
            if isinstance(self.result, Future):
                self.result.add_callback(self._execute_callbacks)
                break

def call_as_future(func, *args):
    """Call a function, guaranteeing the result is a Future."""
    result = func(*args)
    if isinstance(result, Future):
        return result
    else:
        f = Future()
        f.set_result(result)
        return f

It seems to work (i.e. it passes some basic tests).
However, I'd like review of _execute_callbacks, particularly in the case that a callback returns a Future.

In that case, we chain the outer Future's _execute_callbacks method to the end of the inner Future's list of callbacks. That way, when the inner Future fires, it will eventually pass its result back to the outer Future so the outer Future can keep going. If the inner Future has already fired, then adding a callback invokes that callback immediately (synchronously).

This seems a bit weird because then the inner Future can call the outer Future's _execute_callbacks method before the first call to the outer Future's _execute_callbacks completes!

I think this is ok because chaining _execute_callbacks to the inner Future is the last thing _execute_callbacks does, but I wonder whether there's a funky race condition lurking here.


texts:
#include <iostream>

using std::cout;
using std::endl;

int arr[] = {3,4,2,1,-5,116,31,4,0};

void QuickSort(int start,int end);
int Partition(int start, int end);
void Swap(int * , int *);
void PrintArr();

int main(int argc, char* argv[])
{

    PrintArr();

    QuickSort(0, sizeof(arr)/sizeof(int));

    PrintArr();

    return 0;
}

void QuickSort(int start,int end)
{
    if(start >= end) return;

    int index = Partition(start , end);

    QuickSort(start, index - 1);
    QuickSort(index + 1, end);
}

int Partition(int start, int end)
{
    int index = start;
    int pivot = arr[end-1];
    for(int i = start;i < end - 1;i++)
    {
        if(arr[i] <= pivot)
        {
            Swap(arr + index,arr + i);
            index++;
        }
    }

    Swap(arr + index, arr + end - 1);

    return index;

}

void Swap(int *a , int *b)
{
    if(*a != *b)
    {
        int temp = *a;
        *a = *b;
        *b = temp;
    }
}

void PrintArr()
{
    for(int i = 0;i<sizeof(arr)/sizeof(arr[0]); i++)
        cout<<arr[i] <<" ";

    cout<<endl;
}


texts:
This is my first bit of significant code in Common Lisp, an implementation of insertion sort. Being new to Lisp in general, I'm wondering if this code follows best Lisp practices in regards to program design.

;;; Return a portion of a list
(defun slice (elements from-index to-index)
  (cond
    ((= from-index to-index) nil)
    (t (cons (nth from-index elements) (slice elements (+ from-index 1) to-index)))))

;;; Return a list omitting a portion
(defun splice (elements from-index to-index)
  (append (slice elements 0 from-index) (slice elements to-index (length elements))))

;;; Move element in list to new index, return new list
(defun move (elements from-index to-index)
  (let ((spliced (splice elements from-index (+ from-index 1))))
    (append (slice spliced 0 to-index) (list (nth from-index elements)) (slice spliced to-index (length spliced)))))

;;; Find the determined (via predicate) correct index for an element in a list
(defun find-ordered-index (elements predicate index &optional (key index))
  (cond
    ((or (= index 0) (= key 0)) 0)
    ((funcall predicate (nth (- key 1) elements) (nth index elements)) (find-ordered-index elements predicate index (- key 1)))
    (t key)))

;;; Return sorted list
(defun insertion-sort (elements predicate &optional (index 0))
  (cond
    ((= index (length elements)) elements)
    (t (insertion-sort (move elements index (find-ordered-index elements predicate index)) predicate (+ index 1)))))


texts:
Just started learning C. I hope my code adheres to best practices and idioms

#include <stdio.h>
#include <ctype.h>
#include <time.h>
#include <stdlib.h>
int main(void)
{
int iRandomNum;
int iGuess;
srand(time(NULL));

iRandomNum = (rand() % 10);
printf("Guess a number between 1 and 10:");
scanf("%d", &iGuess);

// isdigit function expects a character so the guess value has to be ascii value of the digit character
iGuess += 48;
if (isdigit(iGuess)){
    iGuess -=48; // change back to the original value for comparison with random number
    if (iGuess == iRandomNum){
        printf("You Guessed Correctly\n");
     }
    else{
        printf("The correct answer was %d\n",iRandomNum);
        printf("You guessed %d\n",iGuess);
     }
 }
 else{
      printf("This is not a digit!\n");
 }
 }


texts:
Problem:

  \$n!\$ means \$n × (n − 1) × ... × 3 × 2 × 1\$

  For example, \$10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800\$, and the sum of the digits in the number \$10!\$ is \$3 + 6 + 2 + 8 + 8 + 0 + 0 = 27\$.

  Find the sum of the digits in the number \$100!\$.

My solution in Clojure:

(reduce + (map (fn[x](Integer. (str x))) (seq (str (apply *' (range 1 101))))))

Questions:

Is there a way to avoid the *' in the factorial bit? (apply *' (range 1 101))
I converted the result of the factorial to a string, then to a sequence, and then mapped an Integer cast to a string cast.  Surely there must be a way to simplify this?


texts:
I came across a piece of code that generates SELECT queries from a template.

The template:

SELECT TOP 1 *
FROM   MRH_0000004 WITH (nolock)
WHERE  MachineRegisterId = ${id}
ORDER  BY UtcTime

When the code has to retrieve multiple records, it generates one large query that gets the union of all individual queries based on the template above.

Example:

SELECT *
FROM   (SELECT TOP 1 *
        FROM   mrh_0000004 WITH (nolock)
        WHERE  machineregisterid = 55
        ORDER  BY utctime) q
UNION ALL
SELECT *
FROM   (SELECT TOP 1 *
        FROM   mrh_0000004 WITH (nolock)
        WHERE  machineregisterid = 56
        ORDER  BY utctime) q
UNION ALL
SELECT *
FROM   (SELECT TOP 1 *
        FROM   mrh_0000004 WITH (nolock)
        WHERE  machineregisterid = 57
        ORDER  BY utctime) q

This is a query that gets the TOP 1 result from each group, without using a GROUP BY clause. These chains can get quite long, resulting in large queries from the client to the server.

Can this query be refactored using GROUP BY?

Table schema:

CREATE TABLE [dbo].[mrh_0000004]
  (
     [machineregisterid] [INT] NOT NULL,
     [utctime]           [DATETIME] NOT NULL,
     [value]             [FLOAT] NOT NULL,
     CONSTRAINT [pk_MRH_0000004] PRIMARY KEY CLUSTERED ( [machineregisterid] ASC
     , [utctime] ASC )
  )


texts: Delete duplicates from unsorted linked list

texts:
E.g: if a linked list contains 2->3->1->3->4 then the result should be 2->3->1->4. Notice that 3 has been eliminated.

This code is attributed to GeeksforGeeks.  I'm looking for code-review, optimizations and best practices.

public class EliminateDuplicateUnsortedLL<T> {

    private Node<T> first;
    private Node<T> last;

    public EliminateDuplicateUnsortedLL(List<T> items) {
        for (T item : items) {
            add(item);
        }
    }

    public void add(T item) {
        Node<T> node = new Node<>(item);
        if (first == null) {
            first = last = node;
        } else {
            last.next = node;
            last = node;
        }
    }

    private static class Node<T> {
        private Node<T> next;
        private T item;

        Node(T item) {
            this.item = item;
        }
    }

    public void eliminateDuplicates() {
        final Set<T> set = new HashSet<T>();
        Node<T> prev = null;
        for (Node<T> x = first; x != null; x = x.next) {
            if (set.contains(x.item)) {
                prev.next = x.next;
            } else {
                set.add(x.item);
                prev = x;
            }
        }
        last = prev;
    }

    public List<T> toList() {
        final List<T> list = new ArrayList<>();

        for (Node<T> x = first; x != null; x = x.next) {
            list.add(x.item);
        }

        return list;
    }

    @Override
    public int hashCode() {
        int hashCode = 1;
        for (Node<T> x = first; x != null; x = x.next)
            hashCode = 31*hashCode +  x.hashCode();
        return hashCode;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        EliminateDuplicateUnsortedLL<T> other = (EliminateDuplicateUnsortedLL<T>) obj;
        Node<T> currentListNode = first;
        Node<T> otherListNode =  other.first;

        while (currentListNode != null && otherListNode != null) {
            if (currentListNode.item != otherListNode.item) return false;
            currentListNode = currentListNode.next;
            otherListNode = otherListNode.next;
        }
        return currentListNode == null && otherListNode == null;
    }
}

Unit tests:

public class EliminateDuplicateUnsortedLLTest {

    @Test
    public void test1() {
        EliminateDuplicateUnsortedLL<Integer> edu1 = new EliminateDuplicateUnsortedLL<Integer>(Arrays.asList(1, 2, 3, 4, 5, 4, 3, 7));
        edu1.eliminateDuplicates();

        EliminateDuplicateUnsortedLL<Integer> eduExpected1 = new EliminateDuplicateUnsortedLL<Integer>(Arrays.asList(1, 2, 3, 4, 5, 7));
        assertEquals(eduExpected1, edu1);
    }

    @Test
    public void test2() {
        EliminateDuplicateUnsortedLL<Integer> edu2 = new EliminateDuplicateUnsortedLL<Integer>(Arrays.asList(7, 2, 5, 10, 4, 2, 9, 10));
        edu2.eliminateDuplicates();

        EliminateDuplicateUnsortedLL<Integer> eduExpected2 = new EliminateDuplicateUnsortedLL<Integer>(Arrays.asList(7, 2, 5, 10, 4, 9));
        assertEquals(eduExpected2, edu2);
    }

    @Test
    public void testAllDuplicates() {
        EliminateDuplicateUnsortedLL<Integer> edu3 = new EliminateDuplicateUnsortedLL<Integer>(Arrays.asList(2, 2, 2, 2, 2));
        edu3.eliminateDuplicates();

        EliminateDuplicateUnsortedLL<Integer> eduExpected3 = new EliminateDuplicateUnsortedLL<Integer>(Arrays.asList(2));
        assertEquals(eduExpected3, edu3);
    }

}


texts: AsyncTask which allows to handle exceptions on UI

texts:
The AsyncTask available in android, gives you the result from doInBackground on the UI thread so that you can update UI according to the result, but exceptions need to be handled inside doInBackground function.

So following is my generic solution to the problem, the main objective here is to allow user to handle exceptions exactly the same way he does when working with synchronous code.

public abstract class AsyncTaskWithThrowable<Params, Progress, Result>  {

    public class ResultHolder<Result> {

        private ResultHolder(Result result) {
            _result = result;
        }

        private ResultHolder(Throwable throwable) {
            _throwable = throwable;
        }

        private Throwable _throwable = null;

        private Result _result;

        public Result getResult() throws Throwable{
            if (_throwable != null) {
                throw _throwable;
            }

            return _result;
        }
    }

    private AsyncTask<Params, Progress, ResultHolder<Result>> _asyncTask = new AsyncTask<Params, Progress, ResultHolder<Result>>() {
        @Override
        protected ResultHolder<Result> doInBackground(Params... params)  {

            try {
                return new ResultHolder<Result>(AsyncTaskWithThrowable.this.doInBackground(params));
            }
            catch (Throwable e) {
                new ResultHolder<Result>(e);
                return null;
            }
        }

        @Override
        protected void onPreExecute() {
            AsyncTaskWithThrowable.this.onPreExecute();
        }

        @Override
        protected void onPostExecute(ResultHolder<Result> result) {
            AsyncTaskWithThrowable.this.onPostExecute(result);
        }

        @Override
        protected void onProgressUpdate(Progress... values) {
            AsyncTaskWithThrowable.this.onProgressUpdate(values);
        }
    };

    public abstract Result doInBackground(Params ... params) throws Throwable;

    protected void onPreExecute() {
    }

    @SuppressWarnings({"UnusedDeclaration"})
    protected void onPostExecute(ResultHolder<Result> resultHolder) {
    }

    @SuppressWarnings({"UnusedDeclaration"})
    protected void onProgressUpdate(Progress... values) {
    }

    public final AsyncTaskWithThrowable<Params, Progress, Result> execute(Params... params) {
         _asyncTask.execute(params);
        return this;
    }
}

And this is how you use it.

new AsyncTaskWithThrowable<Boolean, Void, String>(){

    @Override
    protected String doInBackground(Boolean ...params) {
        if (!params[0]) {
            throw new InvalidParameterException();
        }
        return "result";
    }

    @Override
    protected void onPostExecute(ResultHolder<String> resultHolder) {
        try{
            String result = resultHolder.getResult();
            // Change UI
        }
        catch (InvalidParameterException e) {
            // Change UI
        }
        catch (Throwable e) {
            // I don't like this catch block, but i couldn't find a way to avoid it.
        }
    }
}.execute(false);

The problem I see with it is user is forced to handle Throwable (also doInBackground can throw anything), but I cannot use typed parameter for exception here, as Java doesn't allow to catch it.


texts: Reading in a file and ranking result to output file

texts:
I am reading in a file which consists of scores between two teams.  The team that wins gets 2 points, if the teams tie both teams get one point.  The result is ranked by points and if there is a tie ranked by alphabetic order.  Then this is written to an output file.  Any suggestions to improve the code?

Input file:
Blues 3, Coyotes 0

Output
Blues 2 pts
Coyotes 0 pts

using System;
using System.Collections.Generic;
using System.Linq;

namespace skateboard
{
    class MainClass
    {
        //If team does not exists add to library and award 0 points
        static void DoesTeamExist(Dictionary<string, int> dictionary, string team)
        {
            if (!dictionary.ContainsKey(team))
            {
                dictionary.Add(team, 0);
            }
        }

        //If draw add one point to each team, else awards the winner 2 points
        static void AwardPoints(Dictionary<string, int> dictionary, string teamOne, string teamTwo, int teamOneScore, int teamTwoScore)
        {
            if (teamOneScore == teamTwoScore)
            {
                dictionary[teamOne] += 1;
                dictionary[teamTwo] += 1;
            }
            else if (teamOneScore > teamTwoScore)
            {
                dictionary[teamOne] += 2;
            }
            else
            {
                dictionary[teamTwo] += 2;
            }
        }

        public static void Main(string[] args)
        {

            int counter = 0;
            string line;
            System.IO.StreamReader file =
                new System.IO.StreamReader(@"/Users/aaronmk2/Projects/skateboard/skateboard/sample-input.txt");
            Dictionary<string, int> dictionary = new Dictionary<string, int>();

            while ((line = file.ReadLine()) != null)
            {
                string []lines = line.Split(',');
                string teamOne = lines[0].Substring(0, lines[0].Length - 2);
                int teamOneScore = Convert.ToInt32(lines[0][lines[0].Length - 1] - '0');
                DoesTeamExist(dictionary, teamOne);
                string teamTwo = lines[1].Substring(1, lines[1].Length - 2);
                int teamTwoScore = Convert.ToInt32(lines[1][lines[1].Length - 1] - '0');
                DoesTeamExist(dictionary, teamTwo);
                AwardPoints(dictionary, teamOne, teamTwo, teamOneScore, teamTwoScore);
                counter++;
            }

            file.Close();

            var items = from pair in dictionary
                orderby pair.Value descending, pair.Key ascending
                select pair;

            System.IO.StreamWriter write = new System.IO.StreamWriter(@"/Users/aaronmk2/Projects/skateboard/skateboard/test-output.txt");

            // Display results.
            foreach (KeyValuePair<string, int> pair in items)
            {
                Console.WriteLine("{0}: {1}", pair.Key, pair.Value);
                if (pair.Value == 1)
                {
                    write.WriteLine("{0}: {1} pt", pair.Key, pair.Value);
                }
                else
                {
                    write.WriteLine("{0}: {1} pts", pair.Key, pair.Value);
                }

            }
            write.Close();
        }
    }
}


texts:
Zend framework 1. Physically, the file does not exist, it is created based on database.

Okay so use header?

public function downloadAction()
{
    $id = $this->getRequest()->getParam("id");
    $optin = new Application_Model_Optin();
    //$data = $optin->getCodesFromDownload($id);
    $data = array(
        array('code' => 12345),
        array('code' => 12346),
        array('code' => 12347),
        array('code' => 12348),
        array('code' => 12349)
    );

    header("Content-type: application/x-download");
    header("Content-disposition: attachment; filename=code_" . $id . ".csv");

    foreach($data as $item)
    {
        echo $item['code']."\r\n";
    }
    die;
}


texts: Simple name-drawer using Python and Tkinter

texts:
I am a beginner playing around with Python and Tkinter. I wrote this program to draw random names given the students in my classes. I tried to follow PEP 8, but I was wondering if there are any stylistic problems here and also if there is any way to condense the code without affecting the working of the program (as I've finally gotten it to work like I want it to.)

from random import *
from Tkinter import *

class App:

    def __init__(self, master):
        self.count_s7=0
        self.count_s8=0
        self.count_m10=0
        self.m=[]
        self.frame = Frame(master, height=500, width=500)
        self.frame.grid()
        self.Results = Message(self.frame, text="", width=400, font="Courier, 32")
        self.Results.grid(row=1, column=1)
        self.b1 = Button (self.frame, text = "Get Random Name: Science 7", width=50,
                          command = self.s7_Names, bg="#6ddd58")
        self.b1.grid(row=2, column=1)
        self.b2 = Button (self.frame, text = "Get Random Name: Science 8",width=50,
                       command = self.s8_Names, bg="#75c0d2")
        self.b2.grid(row=3, column=1)
        self.b3 = Button (self.frame, text = "Get Random Name: Math 10",width=50,
                          command = self.m10_Names, bg="#ffb9ec")
        self.b3.grid(row=4, column=1)
        self.Quit = Button (self.frame, text = "Quit", command=self.frame.quit)
        self.Quit.grid (row=5, column=1)

    def get_names(self, roster, i):
        words = roster[i]
        self.Results.config(text=words)

    def draw_names(self, roster, count):
        if count == 0:
            self.mixed = sample(roster, len(roster))
            self.get_names(self.mixed, count)
            count +=1

        elif 0 < count < len(roster):
            self.get_names(roster, count)
            count +=1

        else:
            count = 0
            self.mixed = sample(roster, len(roster))
            self.get_names(self.mixed, self.count)
            self.count_s7 +=1

    def s7_Names(self):
        s7 = ['Name1', 'Name2', 'Name3', 'Name4', 'Name5', 'Name6','Name7',
             'Name 8', 'Name9','Name10', 'Name11','Name12','Naome13']
        self.draw_names(s7, self.count_s7)

    def s8_Names(self):
        s8 = ['Kid1','Kid2','Kid3','Kid4','Kid5','Kid6','Another kid']
        self.draw_names(s8, self.count_s8)

    def m10_Names(self):
        m10 = ['Student1', 'Student2', 'Student3', 'Student4', 'Student5'
              'Student6', 'Student7', 'Student8', 'Student9']
        self.draw_names(m10, self.count_m10)

root=Tk()
root.title("Random Names")
app = App(root)
root.mainloop()
root.destroy()


texts: Fastest way to find and replace inside a large amount of files

texts:
Currently I am looping through dependencies of objects, and I am trying to replace GUID (unity object ID's) inside the files.
Right now I am using the following code, any suggestions for improvement ?

public class SendToThread
{
    public int localID = 0;
    public string oldID;
    public string newID;
    public List<string> dependencyAssetPath = new List<string>();
    public string applicationPath;
}

public void Charlie()
{
    //toUseData is a List<SendToThread>
    for (int i = 0 ; i < toUseData.Count; i++)
    {
        while (toUseData[i].dependencyAssetPath.Count >= 1)
        {
            string[] lines = File.ReadAllLines(toUseData[i].applicationPath + toUseData[i].dependencyAssetPath[0]);

            for (int e = 0; e < lines.Length; e++)
            {
                DebugVoid(lines.Length.ToString());
                lines[e].Replace(toUseData[i].oldID.ToString(), toUseData[i].newID.ToString());

                if (e == lines.Length - 1)
                {
                    DebugVoid(toUseData[i].oldID.ToString() + "  " + toUseData[i].newID.ToString());
                    File.WriteAllLines(toUseData[i].applicationPath + toUseData[i].dependencyAssetPath[i], lines);
                }
            }
            toUseData[i].dependencyAssetPath.RemoveAt(0);
        }
    }
}


texts:
What do you think of my code?  I know it is a little rough around the edges but as of two days ago I had no idea how to use jQuery or JavaScript.

$(document).ready(function () {

var json = {

    "205100": {
        "success": true,
            "data": {
            "type": "game",
                "name": "MasterKin",
                "steam_appid": 9000,
                "required_age": 40,
                "is_free": false,
                "controller_support": "full",
                "dlc": [212894, 212893, 208575, 208570]
        }
    }

};

var game_name = [];
for (var key in json) {
    if (json.hasOwnProperty(key)) {
        var item = json[key];
        game_name.push({
            ItemName: item.data.name //Changing the .name to .dlc or .type will then display that result

        });
    }
}
console.log(game_name);
var tr;
for (var i = 0; i < game_name.length; i++) {
    tr = $('
');
    tr.append("" + game_name[i].ItemName + "	");

    $('table').append(tr);
}
});

        Name


texts: Genetic algorithm in Python that plots its evolution

texts:
After programming in Haskell for a while, I've gotten attached to a functional style.  This is clearly evident in the code for my genetic algorithm.

Could you provide me with some hints as to how I can make this code more pythonic?  By that, I mean provide some method of organisation rather than throwing a bunch of functions around.  Any other recommendations are also welcome.

import copy
import matplotlib.pyplot as pyplot
import random

def create_member(genes):
    return (sum(genes), genes)

def shuffle(pool):
    pool_shuffled = copy.deepcopy(pool)
    random.shuffle(pool_shuffled)
    return pool_shuffled

def calculate_pool_fitness(pool):
    return sum([member[0] for member in pool])

def calculate_member_fitness(member):
    return sum(member[1])

def recalculate_fitneses(pool):
    return [(calculate_member_fitness(member), member[1]) for member in pool]

def select_members_roulette(pool, count):
    selection = []
    while len(selection) < count:
        member = select_member_roulette(pool)
        selection.append(copy.deepcopy(pool[member]))
    return selection

def select_member_roulette(pool):
    drop = random.randint(0, calculate_pool_fitness(pool))
    total_fitness = 0
    for member in range(0, len(pool)):
        total_fitness += pool[member][0]
        if total_fitness >= drop:
            return member

def mutate_gene(gene, rate=1):
    return 1 - gene if random.random() <= rate else gene

def mutate_genes(genes, rate=1):
    return [mutate_gene(gene, rate) for gene in genes]

def mutate_member(member, rate=1):
    return member[0], mutate_genes(member[1], rate)

def mutate_pool(pool, rate=1):
    return [mutate_member(member, rate) for member in pool]

def create_random_gene():
    return random.choice([0, 1])

def create_random_genes(size):
    return [create_random_gene() for _ in range(size)]

def crossover_genes(mother, father, rate=1):
    if random.random() <= rate:
        split = random.randint(1, len(mother))
        daughter = mother[:split] + father[split:]
        son = father[:split] + mother[split:]
    else:
        daughter = copy.deepcopy(mother)
        son = copy.deepcopy(father)
    return daughter, son

def crossover_members(mother, father, rate=1):
    daughter_genes, son_genes = crossover_genes(mother[1], father[1])
    return [(mother[0], daughter_genes), (father[0], son_genes)]

def crossover_pool(pool, rate=1):
    children = []

    # select every two elements for crossover
    for mother, father in zip(pool[::2], pool[1::2]):
        children.extend(crossover_members(mother, father, rate))

    return children

def generate_pool(size, gene_size):
    pool = []
    for member in range(0, size):
        genes = create_random_genes(gene_size)
        pool.append(create_member(genes))
    return pool

def evolve(pool, rate_crossover=0.9, rate_mutation=0.01):
    successors = copy.deepcopy(pool)

    # perform roulette selection whilst keeping best member
    member_alpha = copy.deepcopy(max(successors, key=lambda member: member[0]))
    successors = select_members_roulette(pool, len(pool) - 1)
    successors.append(member_alpha)

    successors = shuffle(successors)
    successors = crossover_pool(successors, rate_crossover)
    successors = mutate_pool(successors, rate_mutation)
    successors = recalculate_fitneses(successors)
    return successors

def main():
    random.seed
    pyplot.figure(figsize=(14, 8), dpi=400)
    axgraph=pyplot.subplot(111)
    pool_size = 50
    gene_size = 50
    generations = 100
    pool = generate_pool(pool_size, gene_size)
    for generation in range(0, generations):
        pool = evolve(pool)
        axgraph.scatter(generation, sum([member[0] for member in pool]))
    pyplot.grid(True)
    pyplot.axis([0, generations, 0, pool_size * gene_size])
    pyplot.savefig('genetic_algorithms.png')

main()

if __name__ == '__main__':
    main()


texts:
I code this function to convert list of dict to a specific string to export last in a row table string field.

#!/usr/bin/env python
# encoding: utf-8
from __future__ import unicode_literals, print_function
import types
import collections
from collections import Iterable

def convert_to_string(input):
    if isinstance(input, dict):
        return "{{{}}}".format(",".join(list("{}:{}".format(convert_to_string(key), convert_to_string(value)) for key, value in input.iteritems())))
    elif isinstance(input, list, tuple):
        return "[{}]".format(",".join(list(convert_to_string(element) for element in input)))
    elif isinstance(input, types.StringTypes):
        if isinstance(input, types.UnicodeType):
            return input
        if isinstance(input, types.StringType):
            return input.encode("utf8")
    elif isinstance(input, types.NoneType):
        return ""
    elif isinstance(input, (types.IntType, types.LongType, types.FloatType)):
        return "{}".format(input)
    else:
        try:
            return "{}".format(input)
        except:
            return "<Undefined>"

data = [[{"1": "pomme", "2": "poiré"}, u"pétrole"], [None, 4], [5.00, 6], 7, Iterable]
print (convert_to_string(data))

That return: in IPython

convert_to_string(data)
Out[18]: u"[[{1:pomme,2:poir\xe9},p\xe9trole],[,4],[5.0,6],7,<class '_abcoll.Iterable'>]"
print(convert_to_string(data))
[[{1:pomme,2:poiré},pétrole],[,4],[5.0,6],7,<class '_abcoll.Iterable'>]

Function work fine but do you know more efficient solution to do that?


texts:
After finishing this article : Lessons From A Review Of JavaScript Code

I was wondering if my namespace

/**
 * The primary namespace object
 * @type {Object}
 * @alias BDDS
 */
if(!window['BDDS']) {
    window['BDDS'] = {};
}

if attached to the window, is this snippet invalid,
according to the following?

  Problem 9

  Problem: The namespacing pattern used is technically invalid.

  Feedback: While namespacing is implemented correctly across the rest
  of the application, the initial check for namespace existence is
  invalid. Here’s what you currently have: 1    if ( !MyNamespace ) { 2
  MyNamespace = { }; 3  }

  The problem is that !MyNamespace will throw a ReferenceError, because
  the MyNamespace variable was never declared. A better pattern would
  take advantage of boolean conversion with an inner variable
  declaration, as follows: 01   if ( !MyNamespace ) { 02      var MyNamespace
  = { }; 03 } 04      05    //or 06 var myNamespace = myNamespace || {}; 07   08    // Although a more efficient way of doing this is: 09   //
  myNamespace || ( myNamespace = {} ); 10   // jsPerf test:
  http://jsperf.com/conditional-assignment 11     12    //or 13 if ( typeof
  MyNamespace == ’undefined’ ) { 14   var MyNamespace = { }; 15 }

  This could, of course, be done in numerous other ways. If you’re
  interested in reading about more namespacing patterns (as well as some
  ideas on namespace extension), I recently wrote “Essential JavaScript
  Namespacing Patterns.” Juriy Zaytsev also has a pretty comprehensive
  post on namespacing patterns.


texts:
Please review this:

class KoolDailyReminderAfterWeek(webapp2.RequestHandler):
    def get(self):
        logging.info('sending reminders')
        timeline = datetime.now () - timedelta (days = 7)
        edge = datetime.now () - timedelta (days = 8)
        ads = Ad.all().filter("published =", True).filter("added <", timeline).filter("url IN", ['www.koolbusiness.com']).filter("added >", edge).fetch(99999)
        for ad in ads:
            logging.info('sending reminder to %s', ad.name)
            if ad.title:
                subject= ad.title
            else:
                subject = 'Reminder'
            message = mail.EmailMessage(sender='Kool Business <info@koolbusiness.com>', subject=subject)
            message.body = """
            Hello!
Now your ad %s has been out for a week. If you already have sold your product you can remove your ad.

Some advice to promote your ad:
Change + Renew the ad and it will be on top of the list. You can also change text and price.
Change the ad if you only want to lower the price or change the ad text
Renew so that the ad will be on top if the list.

Best regards,
Koolbusiness.com
            """  % (ad.key().id(),ad.title)
            message.html = """

            Hello!
Now your ad %s has been out for a week. If you already have sold your product you can remove your ad.

Some advice to promote your ad:
Change + Renew the ad and it will be on top of the list. You can also change text and price.
Change the ad if you only want to lower the price or change the ad text
Renew so that the ad will be on top if the list.

Best regards,
Koolbusiness.com

            """  % (ad.key().id(),ad.title)
            message.to=ad.email
            message.send()
            logging.info('sent email to: ' +ad.email)

YAML

 - description: daily mailout
   url: /report/dailyafterweek
   schedule: every 24 hours

Background


texts: Implementing C++ relational operators generator

texts:
Once you define the < operator, you can have an estimation of how the rest of relational operators behave. I'm trying to implement a way to do that for my classes.

What I want is to define only the < and the rest of the operators to be defaulted implicitly. What I've got so far is this design, which I'll elaborate on further down:

template<typename T>
struct relational
{
    friend bool operator> (T const &lhs, T const &rhs) { return rhs < lhs; }
    friend bool operator==(T const &lhs, T const &rhs) { return !(lhs < rhs || lhs > rhs); }
    friend bool operator!=(T const &lhs, T const &rhs) { return !(rhs == lhs); }
    friend bool operator<=(T const &lhs, T const &rhs) { return !(rhs < lhs); }
    friend bool operator>=(T const &lhs, T const &rhs) { return !(lhs < rhs); }
};

So for a class that implements the < operator it would just take inheriting from relational to have the rest of the operators defaulted.

struct foo : relational<foo>
{
    // implement < operator here
};

Are there any alternative, better designs?
Is there a time bomb in this code?
While trying to use this code with classes that already defined one of { >, ==, !=, <=, >= } I had ambiguity problems. The implementation I opted for (also the one existing in the linked Github repository) is tweaked like so

// inside the relational struct
friend bool operator>(relational const &lhs, relational const &rhs)
{ // functions that involve implicit conversion are less favourable in overload resolution
        return (T const&)rhs < (T const&)lhs;
}

Are my problems over with this trick?

Here's a demo of the code working.


texts: Calling API only once on changing segments

texts:
I am working on a screen which has segmented control and has 3 segments (year value 2019, 18, 17) and what I am doing is that on each segment click I have to reload data inside a tableview (getting data from an API request).

let purchaseResponse = inputs.selectedTab.map { index -> String in
        switch index {
        case 0:
            return "2019"
        case 1:
            return "2018"
        case 2:
            return "2017"
        default:
            return "2019"
        } }
        .distinct()
        .flatMapLatest { year in
            return purchaseService.fetchPurchaseHistory(forYear: year, pageNumber: 1)
        }
        .trackActivity(inputs.indicator)
        .materialize()
        .share()

Right now this is what I have, and it works fine, as you can see I am using the Distinct operator which is like this:

extension Observable where Element: Hashable {

func distinct() -> Observable<Element> {
    var set = Set<Element>()
    return flatMap { element -> Observable<Element> in
        objc_sync_enter(self); defer {objc_sync_exit(self)}
        if set.contains(element) {
            return Observable<Element>.empty()
        } else {
            set.insert(element)
            return Observable<Element>.just(element)
        }
    }
}
}

Can I somehow refactor this, or maybe use builtin operators? The reason to use Distinct was that if the user clicks a segment, next time it shouldn't get data from the API.


texts:
An example of the business rules are here.

Does this code implement those rules correctly?  Note that you will have to derive the rules from the example.

/*
test number from url
9876543217

other valid numbers
5322369835
7089771195
8108876957
4395667779
6983806917

not valid numbers
2790412845

5762696912
*/

declare @inputString as varchar(10) = '2790412845'
, @mathResult as tinyint
, @digitNumber as tinyint = 1
, @isValid as bit = 1
, @checkDigitPosition as tinyint
, @tenthDigit as tinyint;

declare @digits as table (
DigitNumber tinyint
, Digit tinyint
, NewDigit tinyint
);

while @digitNumber <= 10
begin
insert into @digits (
DigitNumber
, Digit
)
select @digitNumber
, cast(substring(@inputString, @digitNumber, 1) as tinyint) digit;

set @digitNumber = @digitNumber + 1;
end
/*
Double 1st, 3rd, 5th, 7th and 9th Digits and take the sum of their digits
*/
-- even numbered digits
update @digits
set NewDigit = Digit
where DigitNumber % 2 = 0;

-- odd numbered digits
update @digits
set NewDigit = cast(left(cast((Digit * 2) as char(2)), 1) as tinyint)
         + cast(right(cast((Digit * 2) as char(2)), 1) as tinyint)
where DigitNumber % 2 = 1;

--add the 1st nine new digits together and take 2nd digit (mod 10)
select @mathResult = result
from
(select sum(NewDigit) % 10 result
from @digits
where DigitNumber <= 9) temp;

select @mathResult w;
select * from @digits;
-- Subtract The Unit Position From Ten

set @checkDigitPosition = 10 - @mathResult;
-- compare this number to the 10th digit
select @tenthDigit = Digit
from
(select Digit
from @digits
where DigitNumber = 10) temp;

select @checkDigitPosition p
, @tenthDigit t
, case when @tenthDigit = @checkDigitPosition then 1 else 0 end isValid;


texts: onSaveInstanceState() - ensuring a call to super instance

texts:
When onSaveInstanceState() is customized it should always call the same method on the super instance first.

I usually write:

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    saveState(outState);
}

private void saveState(Bundle outState) {
    outState.putParcelable("item1", item1);
    outState.putParcelable("item2", item2);
    // ...
    outState.putParcelable("item10", item10);
}

instead of putting all code in the onSaveInstanceState() method, in order not to accidentally skip call of super.onSaveInstanceState() (it is very hard to notice in a large project).

Is it a bad habit?


texts:
I need to draw a grid with some special requirements. My current solution is working but is far away from ideal I guess. Attached you can find the current working solution:

Some of my thoughts which led to the current solution:

self.view.layer.border... is not working for me because I need different colors for different sides of the border. Also the outer cells of the grid would only have half the border of the other cells because their borders add up when positioned right next to each other.
I could draw a container view which draws the right colors and then position the cells with a gap of 1px but this solution also does not look very nice.

The currently used code snippet:

private func drawBorder() {
    //TODO: better way to do it ?
    var edgesToColorDifferently: UIRectEdge = []
    var edgesToDrawBold: UIRectEdge = []
    var defaultEdges: UIRectEdge = .all
    var colorForBoldEdge = Theme.shared.stoneBorderColor
    let lastLocation = self.tackleBoard.boardSize - 1

    if(location.row == 1 || location.row == lastLocation) {
        edgesToColorDifferently.insert(.top)
    }

    if(location.row == 0 || location.row == lastLocation - 1) {
        edgesToColorDifferently.insert(.bottom)
    }

    if(location.column == 1 || location.column == lastLocation) {
        edgesToColorDifferently.insert(.left)
    }

    if(location.column == 0 || location.column == lastLocation - 1) {
        edgesToColorDifferently.insert(.right)
    }

    if(self.tackleBoard.isCornerStone(atLocation: location)) {
        colorForBoldEdge = Theme.shared.alternateStoneBorderColor
        edgesToColorDifferently.insert(.all)
    }

    if(self.location.row == 0) {
        edgesToDrawBold.insert(.top)
    }

    if(self.location.row == lastLocation) {
        edgesToDrawBold.insert(.bottom)
    }

    if(self.location.column == 0) {
        edgesToDrawBold.insert(.left)
    }

    if(self.location.column == lastLocation) {
        edgesToDrawBold.insert(.right)
    }

    defaultEdges.remove(edgesToColorDifferently)
    defaultEdges.remove(edgesToDrawBold)

    self.addBorder([
        Border(edges: defaultEdges),
        Border(edges: edgesToDrawBold, color: colorForBoldEdge, thickness: 1.0),
        Border(edges: edgesToColorDifferently, color: Theme.shared.alternateStoneBorderColor)
    ])
}

addBorder() is a method in an UIView extension which adds a 1px view with the correct height/width/color to the given edge.

I would love to have your opinions on how to improve the drawing process because I know that the current code is not readable at all and is way too complicated for such a basic thing.


texts: JavaScript app to search GitHub using JSON API

texts:
I've written this simple JavaScript application for a homework assignment and I've received feedback saying it could be written better.

Can I get some feedback on how to write this differently?  It works for me and returns the results I need, but I would like some more specific feedback. It was meant to be simple and not meant to require more than 2 hours on it.

The requirements were...

  You can only edit app.js, you cannot touch index.html. jQuery is provided.
  index.html contains two elements: one for the search term and one for the results.
  The results should show as a list with each item in an "owner/name" format.
  When a result is clicked, display an alert with the repo's language, followers, url and description.
  The search term should be cached so duplicate searches do not trigger further requests.
  Solution does not need to support older browsers.

Here are the app.js I submitted and the index.html.

(function(window){
 // Setup the variables for the application
 var search,
 results,
 textFieldValue,
 requestBaseUrl = 'https://api.github.com/legacy/repos/search/';

 // Enable browser caching for the application
 $.ajaxSetup({ cache: true});

 function applyPageStyling(){
  $( "" ).appendTo( "head" );
  setTimeout(function(){alertInstructions();},1000);
 };

 // Alert the user what to do
 function alertInstructions(){
  alert("Please type the term to search GitHub for in the text field and hit the ENTER key.");
 };

 // Function to query the github API
 function gitSearch(){
  // Get the value from the search field
  textFieldValue = $('#search').val();

  // Error handling for search box
  if (textFieldValue == ""){
   alert("Please enter a term to search for");
  }
  else {
   // Make the ajax call with the text field value appended to the url. The callback will
   // output the results or alert the error message
   $("
").appendTo('#results');
   $.getJSON(requestBaseUrl+textFieldValue, function(json, status){})
    // Success then append items to #results div
    .done(function(json){
     $.each(json.repositories, function(i, repositories){
      $("
"+json.repositories[i].owner+" / "+json.repositories[i].name+"
")
       .appendTo('#results ul')
       // Add a little styling, just a little.
       .css({'cursor': 'pointer','list-style-type':'none', 'width':'500px'})
       .hover(
        function(event) {
         $(this).css({'color':'#ffffff'});
        },
        function(event) {
         $(this).css({'color':'#000000'});
        }
       )
       .click(function(event){
        alert("Repo Lanuage is : "+json.repositories[i].language +"\n"+
        "There are "+ json.repositories[i].followers +" followers of this repo.\n"+
        "The URL of the repo is : "+ json.repositories[i].url +"\n"+
        "The description of the repo : "+ json.repositories[i].description);
       });
     });
   })
   // Log the error message
   .fail(function(status){
    console.log(status);
   });
  }
 };

 // Enter key event handler
 $(document).keypress(function(e) {
  if(e.which == 13) {
   gitSearch();
  }
 });
 applyPageStyling();

}(window));
<!DOCTYPE html>

  <meta http-equiv="Content-type" content="text/html; charset=utf-8">
  <title>Search</title>

  <input id="search" type="text"/>


texts: Merging totals from rows with duplicate IDs

texts:
I have the following query which updates the quantity when there are duplicate items and users (there should only ever be 2 duplicates), then deletes the row which doesn't get updated...

UPDATE cart_items t
  JOIN (
    SELECT MinID, b.itemQuantity LatestName
    FROM cart_items b
    JOIN (
      SELECT MIN(id) MinID, MAX(id) MaxID
      FROM cart_items
      GROUP BY account_id, itemNumber
      HAVING COUNT(*) > 1
    ) g ON b.id = g.MaxID
  ) rs ON t.id = rs.MinID
SET t.itemQuantity = t.itemQuantity+LatestName;

DELETE `cart_items`
FROM `cart_items`
LEFT OUTER JOIN (
   SELECT MIN(`id`) as `id`, `account_id`, `itemNumber`
   FROM `cart_items`
   GROUP BY `account_id`, `itemNumber`
) as `KeepRows` ON
   `cart_items`.`id` = `KeepRows`.`id`
WHERE
   `KeepRows`.`id` IS NULL;

However I'm pretty sure this is not the best way to achieve this.

Any suggestions?

Here's the schema for the table:

CREATE TABLE `cart_items` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `account_id` int(11) unsigned NOT NULL,
  `itemNumber` int(11) NOT NULL,
  `itemQuantity` int(11) NOT NULL DEFAULT '1',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=56 DEFAULT CHARSET=utf8;

INSERT INTO `cart_items` (`id`, `account_id`, `itemNumber`, `itemQuantity`)
VALUES
    (54, 10, 49, 1),
    (55, 10, 49, 2);


texts: Comparing hash members to other hash members

texts:
I've written a script that deletes a member of a hash if an array within the has contains all the other elements of another array within the same hash.

It works but it looks a little messy. Is there a better way to do this?

def title_contains_blocks(candidate, titles, index)
  test_group = titles.dup
  test_group.delete_at(index)
  test_group.each do |title|
    return true if true === title[:blocks].all?{|block| candidate[:blocks].include?(block)}
  end

  return false
end

titles = [
  {:blocks => [1,2,3,4,5,6]},
  {:blocks => [1,2,3]},
  {:blocks => [4,5,6]}
]

titles = titles.delete_if.each_with_index {|candidate, index|
  title_contains_blocks(candidate, titles, index)
}

puts titles.inspect
#=> [{:blocks=>[1, 2, 3]}, {:blocks=>[4, 5, 6]}]


texts: Does this image-processing library break the Single Responsibility Principle?

texts:
I'm writing a small library to do some image-processing on GPU for WinRT, however, I'm not sure if such design breaks SRP.

One class loads and saves image, renders and maintains filters - isn't it too much?

Code

public class FilteredImageProvider : IDisposable
{
    public event Action ImageSourceChangedEvent;
    GPUImage currentImage;
    SharpDXRenderer renderer;
    FilterContainer filterContainer;
    ImageGPULoaderFactory loaderFactory;

    public FilteredImageProvider()
    {
        this.renderer = new SharpDXRenderer();
        this.filterContainer = new FilterContainer();
        this.loaderFactory = new ImageGPULoaderFactory();
    }

    public ImageSource Image
    {
        get { return renderer.GetRendererSource(); }
    }

    public async Task LoadFromFile(IStorageFile sourceFile)
    {
        var imageLoader = loaderFactory.GetImageLoader(sourceFile);

        if (currentImage != null)
            currentImage.Dispose();

        currentImage = await imageLoader.LoadImage();
        renderer.Load(currentImage);
        ImageSourceChangedEvent();
    }

    public async Task SaveToFile(IStorageFile destinyFile)
    {
        var imageSaver = loaderFactory.GetImageLoader(destinyFile);
        var deviceManager = renderer.GetDeviceManager();
        await imageSaver.SaveImage(currentImage, deviceManager);
    }

    public void Render()
    {
        var filterCompilator = new FilterCompilator();
        var renderedImage = currentImage.GetImageAsEffect();
        var compiledEffect = filterCompilator.CompileFiltersToEffect(renderedImage, filterContainer);

        renderer.Render(compiledEffect);
    }

    public void AddFilter(IFilter filter)
    {
        filterContainer.AddFilter(filter);
    }

    public void RemoveFilter(IFilter filter)
    {
        filterContainer.RemoveFilter(filter);
    }

    public void Undo()
    {
        filterContainer.Undo();
    }

    public void Redo()
    {
        filterContainer.Redo();
    }

    public void Dispose()
    {
        if (currentImage != null)
            currentImage.Dispose();
        renderer.Dispose();
    }
}


texts:
I have db table Model.

Here is code:

public partial class Logging
{
    public string Imei { get; set; }
    public DateTime CurDateTime { get; set; }
    public Nullable<System.DateTime> GPSDateTime2 { get; set; }
    public Nullable<decimal> Latitude2 { get; set; }
    public Nullable<decimal> Longitude2 { get; set; }
    public int Speed { get; set; }
    public Nullable<int> Datatype { get; set; }
    public int Id { get; set; }

}

I want to calculate a difference

And decided to create View - Model

Here is code:

 public class HeatmapViewModel
{
    public int FirstStartDifference { get; set; }
    public int LastStartDifference { get; set; }
    public int coeff = 2;
    public int Difference;
}

And I decided to make calculations on Repository layer
Here is code:

  public List<HeatmapViewModel> GetStops()
    {
        using (var ctx = new GoogleMapTutorialEntities())
        {
            List<HeatmapViewModel> items = new List<HeatmapViewModel>();

            #region firstitem_calculation
            var firstitem = ctx.Loggings.Where(x => x.Datatype == 2).AsEnumerable().Select(
                x => new Logging
                 {
                     Longitude2 = x.Longitude2,
                     Latitude2 = x.Latitude2,
                     CurDateTime = x.CurDateTime

                 }).FirstOrDefault();

             var midnight = new DateTime(firstitem.CurDateTime.Year, firstitem.CurDateTime.Month, firstitem.CurDateTime.Day, 00, 00, 00);
             TimeSpan difference = (firstitem.CurDateTime - midnight);
             var difference_after_midnight = (int) difference.TotalMinutes;

             items.Add( new HeatmapViewModel
                 {
                     FirstStartDifference = difference_after_midnight
                 });
            #endregion

            #region lastitem_calculation
            var lastItem = ctx.Loggings.Where(x => x.Datatype == 2).AsEnumerable().Select(
                 x => new Logging
                 {
                     Longitude2 = x.Longitude2,
                     Latitude2 = x.Latitude2,
                     CurDateTime = x.CurDateTime

                 }).LastOrDefault();
            var before_midnight = new DateTime(lastItem.CurDateTime.Year, lastItem.CurDateTime.Month, lastItem.CurDateTime.Day, 23, 59, 00);
            TimeSpan difference_before = (before_midnight - lastItem.CurDateTime);
            var difference_before_midnight = (int)difference_before.TotalMinutes;

            items.Add(new HeatmapViewModel
            {
                LastStartDifference = difference_after_midnight
            });

            #endregion
   return items;
         }

    }

And call on Controller just method from repo.

Like this:

 public JsonResult GetStops()
        {
            var stops = repo.GetStops();

            return Json(stops.ToArray(), JsonRequestBehavior.AllowGet);

        }

I want to know if the code on the repository is okay, or can I improve it?


texts:
This solution works, and I like having all the logic after the return.

The main purpose of this function was for use with other functions to return a file list:

outside <exclusion list>
grandparent directory in <inclusion list> and
base filename in <inclusion list>

So I end up using this plus a bunch of map and filter logic with path.sep partitioning:

import * as fs from 'fs';
import * as path from 'path';

function fileList(dir, excludeDirs?) {
    return fs.readdirSync(dir).reduce(function (list, file) {
        const name = path.join(dir, file);
        if (fs.statSync(name).isDirectory()) {
            if (excludeDirs && excludeDirs.length) {
                excludeDirs = excludeDirs.map(d => path.normalize(d));
                const idx = name.indexOf(path.sep);
                const directory = name.slice(0, idx === -1 ? name.length : idx);
                if (excludeDirs.indexOf(directory) !== -1)
                    return list;
            }
            return list.concat(fileList(name, excludeDirs));
        }
        return list.concat([name]);
    }, []);
}

(I originally authored back in January)

I'm curious if there's a more concise solution!


texts:
My function is supposed to essentially give the cartesian product of all the letters in a string with the caveat that you have to give the permutations of every equivalent of each character in a string (capital and lowercase for example). This is what I came up with but I believe it has a time complexity of \$O(n*k^n)\$, \$k\$ being the number of equivalents of each character.

import string
from pprint import pprint

equivs = {x[0]:x for x in list(zip(string.ascii_lowercase,string.ascii_uppercase))}

st = "missifsffs"

def perms(st):
    st = st.lower()
    out = [""]
    for let in st:
        out = [y+x for y in out for x in equivs[let]]
    return out
print(perms("miss")) #['miss', 'misS', 'miSs', 'miSS', 'mIss', 'mIsS', 'mISs', 'mISS', 'Miss', 'MisS', 'MiSs', 'MiSS', 'MIss', 'MIsS', 'MISs', 'MISS']
print(perms("okay")) #['okay', 'okaY', 'okAy', 'okAY', 'oKay', 'oKaY', 'oKAy', 'oKAY', 'Okay', 'OkaY', 'OkAy', 'OkAY', 'OKay', 'OKaY', 'OKAy', 'OKAY']

print(perms(st))


texts: Handling various types of nodes when traversing a DOM tree

texts:
How to minimize the following code using java's features ... looking for some workaround with the switch-case statement

I've seen several question regarding switch-case design pattern / best practices but because I am new to java, I am having difficulties in implementing them.

Here is the code:

protected void readTree(Node node, Branch current)
{
  Element element = null;
  Document document = null;

  if(current instanceof Element)
  {
     element = (Element) current;
  }
  else
  {
     document = (Document) current;
  }

  String nodeVal = node.getNodeValue();
  String nodeName = node.getNodeName();

  switch(node.getNodeType())
  {
  case ELEMENT_NODE:
     readElement(node, current);

     break;

  case PROCESSING_INSTRUCTION_NODE:

     if(current instanceof Element)
     {
        element.addProcessingInstruction(nodeName, nodeVal);
        break;
     }
     document.addProcessingInstruction(nodeName, nodeVal);

     break;

  case COMMENT_NODE:

     if(current instanceof Element)
     {
        element.addComment(nodeVal);
        break;
     }

     document.addComment(nodeVal);

     break;

  case DOCUMENT_TYPE_NODE:

     DocumentType domDocType = (DocumentType) node;

     document.addDocType(domDocType.getName(), domDocType.getPublicId(), domDocType.getSystemId());

     break;

  case TEXT_NODE:
     element.addText(nodeVal);

     break;

  case CDATA_SECTION_NODE:
     element.addCDATA(nodeVal);

     break;

  case ENTITY_REFERENCE_NODE:

     if(node.getFirstChild() != null)
     {
        element.addEntity(nodeName, node.getFirstChild().getNodeValue());
        break;
     }
     element.addEntity(nodeName, "");

     break;

  case ENTITY_NODE:
     element.addEntity(nodeName, nodeVal);

     break;

  default:
     System.out.println("WARNING: Unknown node type: " + node.getNodeType());
  }
}