Computationally efficient way of comparing and merging like object keys Though I can achieve most ends via a series of conditionals and arithmetic, especially when iterating over or comparing arrays I frequently hear of much more efficient implementations.

Hailing from PHP, I am accustomed to having array_merge() accessible; this JS function is different in that key that don't match the first array should be discarded (and generally, I'm using this sort of thing as a way of generating config objects for various parameterized components of a larger project).

I was hoping a serious comp-sci nerd could comment to the efficiency of this implementation of the same in JavaScript, and if it can be improved, explain—even very briefly—what's happening, computationally as it were. I have the intuitive sense that there it a bit-wise operation that could achieve this faster:

function mapConfig(template, cfg) {
    var configured_template = {};
    for (key in cfg) {
        template[key] = key in template ?  cfg[key] : false;
    }
    return template
}

var template = {key1:false, key2:false, key3:false};
var cfg = {key1:true, keyTWO:"puppies", key3:false};

var cfg_obj = mapConfig(template, cfg);
console.log(cfg_obj);

//output >>> {key1:true, key2:false, key3:false}

I appreciate any insights anyone could offer.

Interesting question,

there is no faster approach that I know of, in essence, your approach mimics jQuery's $.extend() source code. Except that your code does not clone parameters which might bring you trouble.

I think your code might be messed up, or you might not understand what it is doing.

This:

var template = {key1:false, key2:false, key3:false};
var cfg = {key1:true, keyTWO:"puppies", key3:false};

var cfg_obj = mapConfig(template, cfg);
console.log(cfg_obj);

is equivalent to this:

var template = {key1:false, key2:false, key3:false};
var cfg = {key1:true, keyTWO:"puppies", key3:false};

mapConfig(template, cfg);
console.log(template);

because you change the provided object itself, which probably is not right in all circumstances. I assume that is why you have configured_template in there ?

Furthermore, it does not seem to make sense to assign false to properties that you want to discard.. It eats up memory for no good reason.

All in all, I would counter propose

function configureTemplate( template, config) {
    var result = {}, key;
    for (key in config) {
        if( key in template ){
          result[key] = config[key];
        }
    }
    return result;
}

Note that you were polluting the global namespace by not declaring key with var.

Personally, I would drop most of the curly braces:

function configureTemplate( template, config) {
    var result = {}, key;
    for (key in config)
        if( key in template )
          result[key] = config[key];
    return result;
}

var template = {key1:false, key2:false, key3:false};
var cfg = {key1:true, keyTWO:"puppies", key3:false};

var cfg_obj = configureTemplate(template, cfg);
console.log(cfg_obj);

On a final note, try not to disemvowel your variables. It makes grokking code needlessly harder.


Is this a good implementation of a simple "Size" value type I have created the value type below to represent the desired size for an image. The Size.Default is used in situations where the image is required in the size it was supplied in, i.e. the image shouldn't be resized.

Is this a good implementation of a value type, especially regarding the IEquatable<T> implementation?

What are your thoughts on the use of the private constructor to create the Default instance?

using System;

public struct Size : IEquatable<Size>
{
    private readonly int _height;
    private readonly int _width;
    private readonly bool _default;

    public static readonly Size Default = new Size(true);

    public int Height
    {
        get { return _height; }
    }

    public int Width
    {
        get { return _width; }
    }

    public bool IsDefault
    {
        get { return _default; }
    }

    private Size(bool isDefault)
    {
        _height = 0;
        _width = 0;
        _default = isDefault;
    }

    public Size(int width, int height)
    {
        _height = height;
        _width = width;
        _default = false;
    }

    public override bool Equals(object obj)
    {
        return this.Equals((Size)obj);
    }

    public bool Equals(Size other)
    {
        if (this._default && other._default)
            return true;

        if (this._default && !other._default)
            return false;

        if (!this._default && other._default)
            return false;

        return this.Width == other.Width && this.Height == other.Height;
    }

    public static bool operator ==(Size left, Size right)
    {
        return left.Equals(right);
    }

    public static bool operator !=(Size left, Size right)
    {
        return !left.Equals(right);
    }

    public static Size Parse(string input)
    {
        var parts = input.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
        if (parts.Length != 2)
            throw new FormatException("Input string was not in a correct format.");

        var x = int.Parse(parts[0]);
        var y = int.Parse(parts[1]);

        return new Size(y, x);
    }
}

I'm not sure what the point is for making a distinction between a size and the default size.  But you shouldn't expose the default value as a field, use a property.  That will give you much more flexibility should you decide to do other things when getting the value.  No need for a backing field, it's a value type and it isn't all that complex.

public static Size Default
{
    get { return new Size(true); }
}

Consider renaming _default to something that would indicate it is a bool.  I'd usually go with something like _isDefault.  You already did that for the constructor parameter and property, I don't know why you didn't do the same for the field.

Your Equals() method should not ever throw exceptions.  What would happen if you passed in something that was not a Size?

public override bool Equals(object other)
{
    if (other is Size)
        return Equals((Size)other);
    return false;
}

Your Equals(Size) method is a little unusual.  You can merge the second and third conditions into a single this._isDefault != other._isDefault.  It might make more sense to combine that test with the tests for width and heights.  And personally, I wouldn't mix accessing fields and properties within a single method, I'd choose one or the other unless the properties had other logic that I needed to be fired.

public bool Equals(Size other)
{
    if (this._isDefault && other._isDefault)
        return true;

    return this._isDefault == other._isDefault &&
           this._width == other._width &&
           this._height == other._height;
}

Any time you override the equals method, you must override the GetHashCode() method too.  Use an implementation something like this:

public override int GetHashCode()
{
    unchecked
    {
        var hashCode = 79;
        hashCode = hashCode * 97 + _isDefault.GetHashCode();
        hashCode = hashCode * 97 + _width.GetHashCode();
        hashCode = hashCode * 97 + _height.GetHashCode();
        return hashCode;
    }
}

While we're on the subject of overriding methods, you should consider overriding the ToString() method as well to return something reasonable.

Your Parse() method should do more validation than that IMHO.  You make the assumption that the input will be a comma separated pair of values.  You check if you have a pair which is good, but you should explicit perform checks to make sure the values are integer numbers (i.e., digits).  It's not as useful receiving a generic format exception coming from the int.Parse() method than if it came from your Parse() method.  On a minor note, use width and height for the local variables and not x and y... that's not what they're representing.


“Proper” Asynchronous implementation I need some opinion if my code below is proper for an async process. This code only reformats text. Please let me know if this implementation is not proper or needs some improvement.

static void Main(string[] args)
{
    Task.Factory.StartNew(() => ReadCharacter("File 1.txt"));
    Task.Factory.StartNew(() => ReadCharacter("File 2.txt"));
    Console.WriteLine("Main Task");
    Console.ReadLine();
}

static void ReadCharacter(string inputFile)
{
    string result;
    using (StreamReader sr = new StreamReader(inputFile))
    using (StreamWriter sw = new StreamWriter(string.Format("C:\\Out--{0}",inputFile)))
    {
        Console.WriteLine("Opening file : {0}", inputFile.ToString());
        while (!sr.EndOfStream)
        {
            result = sr.ReadLine();
            sw.WriteLine(string.Format("{0} --> {1}",result,Task.CurrentId.ToString()));
        }
        Console.WriteLine("Finish {0}", inputFile);
        sr.Close(); sw.Close();
    }
}

Well, you start two Tasks each reading and writing a file but not the same. So basically it should be ok. Some remarks:

Task.Factory.StartNew returns a Task. You probably want to wait until the tasks you have started are finished before you quit from main which you can do with Task.WaitAll. Something along these lines:

var task1 = Task.Factory.StartNew(() => ReadCharacter("File 1.txt"));
var task2 = Task.Factory.StartNew(() => ReadCharacter("File 2.txt"));
Console.WriteLine("Main - waiting for tasks to finish");
Task.WaitAll(task1, task2);
Console.WriteLine("Finished");

Your worker method ReadCharacter writes directly to the console. What happens if you want to run this code in a windows service process where this should be logged instead? So you should pass some kind of ILogger to the method and use that to output the status/log messages.
You hard-code your output directory to C:\. This should really be passed in as destination folder.


Good approach to raise an exception I have class House and module Lockable.  Locking and unlocking House should reflect the real world, so you can't lock twice.

Do you think this is a good approach to using a module and raising an exception?

module Lockable
  attr_reader :locked

  def lock!
    raise StandardError, "Already locked" if @locked == true
    @locked = true
  end

  def unlock!
    raise StandardError, "Already unlocked" if @locked == false
    @locked = false
  end
end

class House
  include Lockable
end

Usage:

house = House.new
house.lock!
house.unlock!
house.unlock! # raise an exception

I would define domain specific error classes like so:

module Lockable
  Error           = Class.new StandardError
  AlreadyLocked   = Class.new Error
  AlreadyUnlocked = Class.new Error

  def lock!
    raise AlreadyLocked if locked?
    @locked = true
  end

  def unlock!
    raise AlreadyUnlocked unless locked?
    @locked = false
  end

  def locked?
    # unless already defined, this assumes an
    # initial unlocked state (!!nil == false)
    !!@locked
  end
end

By having a common ancestor (LockedError), users can simply catch that one if they don't care about the inner state of the lockable object:

begin
  house.lock!
  house.lock!
rescue Lockable::Error
  # meh...
rescue StandardError
  # $! needs handling
end

On the other hand, if I try to lock an already locked lock, the key just won't move (and the lock doesn't blow up in my face). So, a more realistic reflection of the world would be this implementation:

module Lockable
  def lock!
    @locked = true
  end

  def unlock!
    @locked = false
  end
end


Getting and checking value from a mixed object array HTTP endpoint I try to get location data by a external HTTP call. For this API, any part in the data can be missing. Initially I wrote the following code to check whether data.res.accounts[0].contacts[0].location exists:
const getLocation = async () => {
  const data = await fetchLocation();
  if (
    data == null
    data.res == null ||
    data.res.accounts == null ||
    data.res.accounts[0] == null ||
    data.res.accounts[0].contacts == null ||
    data.res.accounts[0].contacts[0] == null ||
    data.res.accounts[0].contacts[0].location == null
  ) {
    return null;
  }
  return data.res.accounts[0].contacts[0].location;
}

I have tried to simplify the mixed object and array code.
One way of doing this is using JavaScript's new conditional operator ?..
For example if they are all objects then I can use something like:
if (data?.res?.account?.contact?.location == null) {
  return null;
}

However my data is mixed with arrays and objects. This is the best I've come up with:
if (
  data?.res?.accounts == null ||
  data.res.accounts[0]?.contacts == null ||
  data.res.accounts[0].contacts[0]?.location == null
) {
  return null;
}

Can I simplify it further?

Optional chaining can be used not only with object property lookup with dot notation, but also with bracket notation, by putting ?. before the [:

const data = { res: {}};
console.log(data?.res?.accounts?.[0]?.contacts?.[0]?.location == null)

Just to be thorough, you can also use optional chaining with function calls:

const data = { res: { }};
console.log(data?.res?.accounts?.[0]?.contacts?.[0].location?.includes?.('foobar'));

const data2 = { res: { accounts: [{ contacts: [{ location: 'foobarbaz' }] }] } };
console.log(data2?.res?.accounts?.[0]?.contacts?.[0].location?.includes?.('foobar'));

const data3 = { res: { accounts: [{ contacts: [{ location: 7 }] }] } };
console.log(data3?.res?.accounts?.[0]?.contacts?.[0].location?.includes?.('foobar'));

That said, having so many nested properties whose existence is uncertain is a bit of a code smell, because any time you want to look something up, you'll have to check the existence of all intermediate properties first. Despite the fact that you can do it concisely with optional chaining nowadays, it's quite a strange data structure. If you have control over fetchLocation, consider if you can refactor it so that fewer intermediate properties may be missing. (For example, if you could change it so that every account has a contacts array, and the array might be empty (but not null nor undefined), that'd be a step in the right direction).
Also, keep in mind that optional chaining is extremely new syntax. If this is going to be running on a public website, make sure to transpile your code down to ES6 or ES5 for production so that those with older browsers can consume your code.
On another note, you might consider using === instead of ==. ESLint rule: eqeqeq. == has some pretty odd behaviors involving type coercion that developers shouldn't be forced to look up in order to be 100% confident of what logic a particular section of code is implementing. For example, you could use ?? instead, to handle cases of undefined or null:
const location = data?.res?.accounts?.[0]?.contacts?.[0]?.location;
return location ?? null;

(Or, if location will always be a non-empty string, you could return location || null, which might be a bit better)
Also, the conditional operator is not in any of the code in your question or this answer. The conditional operator uses syntax of the form:
const resultingExpression = condition ? expression1 : expression2;


Project Euler #6 - Sum square difference I'd like to get the code below reviewed on all aspects, specifically I wonder if it's common usage to use let like this, as currently more computations are done in the let statement than in the rest of the code.

  Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.

problems/problem6.clj

(ns project-euler.problems.problem6
  (:require [project-euler.shared :as shared]))

(defn sum-square-difference [n]
  {:pre [(number? n)]}
  (let [sum-squares (reduce + (map shared/square (range 1 (inc n))))
        square-sum (shared/square (reduce + (range 1 (inc n))))]
    (- square-sum sum-squares)))

(println (sum-square-difference 100))

shared.clj

(ns project-euler.shared
  (:require [clojure.math.numeric-tower :as math]))

(defn square [n]
  {:pre [(number? n)]}
  (math/expt n 2))

As in many of the euler problems, a formula can be derived in whole or part to speed up the runtime.  In this case, the formulas below provide O(1) runtime.  For this example it's trivial, but imagine it's the sum of the squares of the first 1 billion numbers.  Since you are defining your own functions, as I am in my examples, I think it makes sense to provide the most efficient solution so that when these are used in later problems, they won't be a factor affecting performance.

Regarding the use of let, yes, it's often the case that you will bind what you need to in the let binding.  You could actually get by with no let at all, but as I have done below and as you did, I think your code is clearer than if you had inlined everything.

(defn sum-of-squares
  "1^2 + 2^2 + 3^2 ... N^2   ==>   N*(N+1)*(2N+1)/6 "
  [n]
    (/ (* n (+ n 1) (+ 1 (* n 2))) 6))

(defn sum-of-naturals
  "1 + 2 + 3 ... N   ==>   N*(N+1)/2 "
  [n]
  (/ (* n (inc n)) 2))

(defn answer []
  (let [sum (sum-of-naturals 100)
        square-of-sum (* sum sum)
        sum-of-square (sum-of-squares 100)]
    (- square-of-sum sum-of-square)))


Positioning a tooltip relative to various kinds of elements I am trying to simplify the following massive conditional statement but have no idea how to. Does anyone have suggestions for it?

//regular elements use the normal position variables.
var tooltipXPos = xPos;
var tooltipYPos = yPos-$tooltipElement.height()-YOffset;

//individual elements position shifting...
//for sub_link on top
if ($element.is('#uilder') || $element.is('#options')) {
    tooltipYPos = yPos + 35;
}

//expend button after do search in Search page
if ($element.is('#extend')) {
    tooltipXPos = xPos - 240;
}
if ($element.is('#lis')) {
     tooltipXPos = xPos - 295;
     tooltipYPos = yPos - 80;
}

if ($element.is('#count')) {
    tooltipXPos = xPos + 180;
    tooltipYPos = yPos - 90;
}
if ($element.is('label')) {
    tooltipXPos = xPos + 80;
    tooltipYPos = yPos - 90;
}

if ($element.is('#add')) {
    tooltipXPos = xPos -280;
    tooltipYPos = yPos -120;
}

if ($element.is('title_label')) {
    tooltipXPos = xPos + 35;
    tooltipYPos = yPos -75;
}

//assign homework by class button under homework tab..
if ($element.is('#control')) {
    tooltipXPos = xPos -270;
}

//place the tutorial window
$tooltipElement.css({
    position: 'absolute',
    top: tooltipYPos,
    left: tooltipXPos,
    'z-index': 9999
})

Create an array which contains :

the id of element
the offset x
the offset y

then, loop on each element of this array and do a single if.

Something like that (not tested)

var items = [
    {name: '#te_classbuilder', x: -120, y: -0},
    {name: '#lesson-details-extend-button', x: 0, y: 120},
    {name: 'label', x: 100, y: -120}
];

for (var i = 0; i < items.length; i++) {

  var item = items[i];

  if ($element.is(items[i].name) {
    tooltipXPos = xPos + item.x;
    tooltipYPos = yPos + item.y;
  }
}

If you know the key, use a map and don't use a loop in the array, simply get the item of the map using the key.


Perl 6 oneliner to sum up all numbers in a text file The task is to sum up scores mentioned in a text file. Scores are floating point numbers as defined by the regexp float immediately preceded by a * character to distinguish them from other numbers in the text. Scientific notation is not permitted.

Example input

Day 1:
  Task 1: *5 Task 2: *2,8
  Task 3 was the hardest, your score is *-1
…

The expected sum here is 5 + 2.8 - 1 = 6.8.

my $sum = 0;

my regex float {
                 (<[+-]>?)          # opt. sign
                 (\d+)              # whole part
                 [(<[.,]>)(\d*)]?   # opt. fractional part;
                                    #   comma is a valid separator
               }

for slurp.match( / \* <float> /, :g ) {
  my $f = $_<float>;
  # justification for the next line:
  #  +"5," Cannot convert string to number: trailing characters after number
  #  +"5." Cannot convert string to number: radix point must be followed by one or more valid digits
  $sum += +"$f[1]$f[2].$f[4]0"
}

say $sum;

The code works, but it prints out a large number of warning messages

use of uninitialized value of type Any in string context

I would like to hear suggestions how to write this in a more idiomatic Perl.

In addition, I would like to hear how to make it more an one liner since I guess the code might be written with significantly less lines and still be readable.

The warning comes from the fact that the third and fourth capture groups are inside an optional part of the regex.  Therefore, $f[4] might not be defined.

Rather than concatenating the parts of a decomposed number, I suggest taking all of $f[0] and replacing any comma with a period.

my $sum = 0;

my regex float {
                 <[+-]>?          # opt. sign
                 \d+              # whole part
                 [ <[.,]> \d+ ]?  # opt. fractional part
                                      #comma is vaild separator
               }

for slurp.match( / \* <float> /, :g ) {
    $sum += +$_<float>.subst( /','/ , '.' , :g );
}

say $sum;


Count ways to reach the n’th stair I have solved Leetcode climbing-stairs problem which is stated as:

  There are n stairs, a person standing at the bottom wants to reach the
  top. The person can climb either 1 stair or 2 stairs at a time. Count
  the number of ways, the person can reach the top.

I used dynamic programming to solve this like below:

class Solution(object):
    def climbStairs(self, n):
        """
        :type n: int
        :rtype: int
        """
        if n==1:
            return 1
        dp = [0 for i in range(n+1)]
        dp[1] = 1
        dp[2] = 2
        for i in range(3,n+1):
            dp[i] = dp[i-1] + dp[i-2]
        return dp[n]

Is there any improvement of this code?
Is there any alternative way rather than dynamic programming?

Pythonic Ideas

Multiplication with lists

You can create an array of n + 1 zeros using the * operator:

dp = [0] * (n + 1)

Which seems a bit clearer (IMHO) than:

dp = [0 for i in range(n+1)]

General solution with no base case

You could get rid of the base case n == 1 if you do:

def climbStairs(self, n):
    """
    :type n: int
    :rtype: int
    """
    dp = [0] * max(3, n + 1)
    dp[1] = 1
    dp[2] = 2
    for i in range(3,n+1):
        dp[i] = dp[i-1] + dp[i-2]
    return dp[n]

Computing Fibonacci

Your solution is one of the fastest (and most obvious) ways to compute fibonacci with a running time of \$O(n)\$. However, there's a \$O(\log{}n)\$ solution using an interesting property of fibonacci numbers. Here's a proof and an in depth explanation.

Basically if you know F(n) and F(n-1) you can find F(2n) and F(2n-1) following these two formulas:

\begin{aligned}F_{2n-1}&=F_{n}^{2}+F_{n-1}^{2}\\F_{2n}&=(F_{n-1}+F_{n+1})F_{n}\\&=(2F_{n-1}+F_{n})F_{n}.\end{aligned}

Using this, you can double your way to the fibonacci number you need (or recursively half your way down)

def fibonacci(n):
    memo = {
        0: 0,
        1: 1,
        2: 1,
        3: 2
    }
    def recurse(n):
        if not n in memo:
            if n % 2 == 0:
                k = n // 2
                memo[k] = recurse(k)
                memo[k - 1] = recurse(k - 1)
                memo[n] = (2 * memo[k - 1] + memo[k]) * memo[k]
            else:
                k = (n + 1) // 2
                memo[k] = recurse(k)
                memo[k - 1] = recurse(k - 1)
                memo[n] = memo[k]**2 + memo[k -1]**2
        return memo[n]
    return recurse(n)

Note: While the closed form solution is interesting, it's not computationally practical since it requires infinate precision of \$\phi\$.


My first-ever jQuery works, but it's not efficient. Any pointers? I've written my first completely self-written jQuery today. I just used the jQuery docs and I'm reasonably proud I got it to work, and working fine. It's not a very complex problem I'm solving, just an animated UI element, but it are my first steps, and I want to make sure I'm starting off right.

I think it's a lot of code for what I'm trying to achieve, and I'm looking for pointers or tips on how I could improve my code. I'm not at all averse to scrapping all jQuery here and doing it with pure JS either.

jQuery(document).ready(function () {
    event.preventDefault();
    var nav = jQuery(".navigation-menu");
    var button = jQuery(".navigation-title");

    function showNav() {
        nav.show('fast');
        button.removeClass('closed');
        button.addClass('open');
    }

    function hideNav() {
        nav.hide('fast');

        if (button.hasClass('open')) {
            button.removeClass('open');
        }

        button.addClass('closed');
    }

    hideNav();

    button.click(function () {
        if (button.hasClass('closed')) {
            showNav();
        } else if (button.hasClass('open')) {
            hideNav();
        } else if (!button.hasClass('open') || !button.hasClass('closed')) {
            hideNav();
        }
    });
});

Here's the fiddle: http://jsfiddle.net/yeawg/2/

I'm also wondering: am I using event.preventDefault() right?

I found .toggle() in the jQuery docs, and it seemed to me I could use that far better. I changed my code into:

jQuery(document).ready(function(){
    var nav = jQuery(".navigation-menu");
    var button = jQuery(".navigation-title");

    nav.toggle();

    button.click(function(event){
        event.preventDefault();
        nav.toggle('fast');
    });
});

This looks a lot leaner and better readable.


javascript canvas -javascript design I am doing some tests with html5 Canvas object. At the same time I am trying to make my javascript code more modular.  In the following code, where/how should I declare canvas and context, so that it can be shared with other objects?  Please provide general comments/improvements?

Output:

Code:

$( document ).ready(function() {

    var axis = {
        LEFT_INDENT : 100,
        START_WORK_HOUR : 8,
        END_WORK_HOUR : 17,
        HOURS_IN_WORKDAY : 0,
        CANVAS_WIDTH : 0,
        CANVAS_HEIGHT : 0,
        AXIS_SIDE_MARGIN : 20,
        AXIS_TOP_MARGIN : 40,
        AXIS_ORIGIN : new Array(),
        AXIS_RIGHT : 0,
        TICK_INCREMENT :  0,

        setup: function(){

            // assumes that I have <canvas id="myCanvas" width="800" height="300"></canvas>  in the HTML
            this.canvas = document.getElementById('myCanvas');
            this.context = this.canvas.getContext('2d');

            this.HOURS_IN_WORKDAY = this.END_WORK_HOUR - this.START_WORK_HOUR;
            this.CANVAS_WIDTH = this.canvas.width;
            this.CANVAS_HEIGHT = this.canvas.height;

            this.AXIS_ORIGIN = { x: this.AXIS_SIDE_MARGIN,
                            y: this.AXIS_TOP_MARGIN };

            this.AXIS_RIGHT = this.canvas.width-this.AXIS_SIDE_MARGIN;

            this.TICK_INCREMENT = (this.CANVAS_WIDTH-this.LEFT_INDENT-(2*this.AXIS_SIDE_MARGIN))/this.HOURS_IN_WORKDAY;
            this.AXIS_RIGHT = this.canvas.width-this.AXIS_SIDE_MARGIN;
        },

        draw_lines: function(){
            this.context.beginPath();
            this.context.moveTo(this.LEFT_INDENT, this.AXIS_ORIGIN.y);
            this.context.lineTo(this.AXIS_RIGHT,  this.AXIS_ORIGIN.y)
            this.context.stroke();
            this.counter = this.START_WORK_HOUR;

            for(x=this.AXIS_SIDE_MARGIN+this.LEFT_INDENT ; x < this.AXIS_RIGHT ; x = x + this.TICK_INCREMENT){
                // grid lines
                this.context.beginPath();
                this.context.moveTo(x,30);
                this.context.lineTo(x,50)
                this.context.stroke();

                // background line - top to bottom
                this.context.save();
                this.context.fillStyle = "#F0F8FF";
                this.context.beginPath();
                this.context.lineWidth = .1;
                this.context.moveTo(x,30);
                this.context.lineTo(x,this.CANVAS_HEIGHT-20)
                this.context.stroke();
                this.context.restore();

                // text
                this.context.font = "14px Arial";
                this.context.fillStyle = "#011f5b";
                this.counter++;
                this.context.fillText(this.counter+":00",x-7,20);
            }
        }
    }
    axis.setup();
    axis.draw_lines();
});

You can wrap the functionality in an object. You instantiate it with a canvas element and some configuration options.

(function($) {

// config defaults
var defaults = {
    LEFT_INDENT: 100,
    START_WORK_HOUR: 8,
    END_WORK_HOUR: 17,
    AXIS_SIDE_MARGIN: 20,
    AXIS_TOP_MARGIN: 40
};

// constructor
axis = function(canvas, config)
{
    this.config = $.extend({}, defaults, config);
    this.canvas = canvas;

    this.setup();
}

// define prototype functions
axis.prototype.setup = function() {
    this.context = this.canvas.getContext('2d');

    this.HOURS_IN_WORKDAY = this.config.END_WORK_HOUR - this.config.START_WORK_HOUR;
    this.CANVAS_WIDTH = this.canvas.width;
    this.CANVAS_HEIGHT = this.canvas.height;

    this.AXIS_ORIGIN = {
        x: this.config.AXIS_SIDE_MARGIN,
        y: this.config.AXIS_TOP_MARGIN
    };

    this.AXIS_RIGHT = this.canvas.width - this.config.AXIS_SIDE_MARGIN;

    this.TICK_INCREMENT = (this.CANVAS_WIDTH - this.config.LEFT_INDENT - 2*this.config.AXIS_SIDE_MARGIN)) / this.HOURS_IN_WORKDAY;
}

axis.prototype.draw_lines = function() {
    this.context.beginPath();
    this.context.moveTo(this.LEFT_INDENT, this.AXIS_ORIGIN.y);
    this.context.lineTo(this.AXIS_RIGHT,  this.AXIS_ORIGIN.y)
    this.context.stroke();
    this.counter = this.config.START_WORK_HOUR;

    for(x = this.config.AXIS_SIDE_MARGIN + this.config.LEFT_INDENT ; x < this.AXIS_RIGHT ; x = x + this.TICK_INCREMENT) {
        // grid lines
        this.context.beginPath();
        this.context.moveTo(x,30);
        this.context.lineTo(x,50)
        this.context.stroke();

        // background line - top to bottom
        this.context.save();
        this.context.fillStyle = "#F0F8FF";
        this.context.beginPath();
        this.context.lineWidth = .1;
        this.context.moveTo(x,30);
        this.context.lineTo(x, this.CANVAS_HEIGHT - 20)
        this.context.stroke();
        this.context.restore();

        // text
        this.context.font = "14px Arial";
        this.context.fillStyle = "#011f5b";
        this.counter++;
        this.context.fillText(this.counter+":00",x-7,20);
    }
}

}(jQuery));

To use it:

var a = new axis(document.getElementById('myCanvas'), {
     // whatever you want to override
});
a.draw_lines();


Counting words / lines in Ruby I solved this problem in Ruby:

  Write an utility that takes 3 command-line parameters P1, P2 and P3.
  P3 is OPTIONAL (see below) P1 is always a file path/name. P2 can take
  the values:

  “lines”
  “words”
  “find”

  Only P2 is “find”, then P3 is relevant/needed, otherwise it is not.

  So, the utility does the following:

  If P2 is “rows” it says how many lines it has
  If P2 is “words” it says how many words it has (the complete file)
  If P2 is “find” it prints out the lines where P3 is present

My solution looks like this:

#!/usr/bin/env ruby

def print_usage
  puts "Usage: #{$0} <file> words|lines"
  puts "       #{$0} <file> find <what-to-find>"
end

class LineCounter
  # Initialize instance variables
  def initialize
    @line_count = 0
  end
  def process(line)
    @line_count += 1
  end
  def print_result
    puts "#{@line_count} lines"
  end
end

class WordCounter
  # Initialize instance variables
  def initialize
    @word_count = 0
  end
  def process(line)
    @word_count += line.scan(/\w+/).size
  end
  def print_result
    puts "#{@word_count} words"
  end
end

class WordMatcher
  # Initialize instance variables, using constructor parameter
  def initialize(word_to_find)
    @matches = []
    @word_to_find = word_to_find
  end
  def process(line)
    if line.scan(/#{@word_to_find}/).size > 0
      @matches << line
    end
  end
  def print_result
    @matches.each { |line|
      puts line
    }
  end
end

# Main program
if __FILE__ == $PROGRAM_NAME

  processor = nil

  # Try to find a line-processor
  if ARGV.length == 2
    if ARGV[1] == "lines"
      processor = LineCounter.new
    elsif ARGV[1] == "words"
      processor = WordCounter.new
    end
  elsif ARGV.length == 3 && ARGV[1] == "find"
    word_to_find = ARGV[2]
    processor = WordMatcher.new(word_to_find)
  end

  if not processor
    # Print usage and exit if no processor found
    print_usage
    exit 1
  else
    # Process the lines and print result
    File.readlines(ARGV[0]).each { |line|
      processor.process(line)
    }
    processor.print_result
  end

end

My questions are:

Is there a more Ruby-esque way of solving it?
More compact, but still readable / elegant?

It seems checking for correct command-line parameter combinations takes up a lot of space...

Contrast it to the Scala version found here:

https://gist.github.com/anonymous/93a975cb7aba6dae5a91#file-counting-scala

Some notes:

Those counter classes are probably overkill, keep it simple.
Ruby is an OOP language, but it's not necessary to create a bunch of classes  for simple scripts like this.
Idiomatic: if not x -> if !x
Idiomatic: { ... } for one-line blocks, do/end for multi-line.

I'd write:

fail("Usage: #{0} PATH (lines|words|find REGEXP)") unless ARGV.size >= 2
path, mode, optional_regexp = ARGV

open(path) do |fd|
  case mode
  when "lines"
    puts(fd.lines.count)
  when "words"
    puts(fd.lines.map { |line| line.split.size }.reduce(0, :+))
  when "find"
    if optional_regexp
      fd.lines.each { |line| puts(line) if line.match(optional_regexp) }
    else
      fail("mode find requires a REGEXP argument")
    end
  else
    fail("Unknown mode: #{mode}")
  end
end


Counts "islands" of 1s in sea of 0s (2d array matrix) This solution surpassed 100% of submissions for efficiency! My method was to recursively check surrounding values and change any contiguous "land" to "water". Is there a better way to write what I wrote?

  Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.

class Solution {
public int numIslands(char[][] grid) {
    int islands = 0;

    for (int i = 0; i < grid.length; i++) {
        for (int j = 0; j < grid[i].length; j++) {
            if (grid[i][j] == '1') {
                islands++;
                destroyIsland(grid, i, j);
            }
        }
    }

    return islands;
}

public void destroyIsland(char[][] grid, int i, int j) {
    grid[i][j] = '0';
    if (i < grid.length - 1 && grid[i+1][j] == '1') {
        destroyIsland(grid, i+1, j);
    }
    if (i > 0 && grid[i-1][j] == '1') {
        destroyIsland(grid, i-1, j);
    }
    if (j < grid[i].length - 1 && grid[i][j+1] == '1') {
        destroyIsland(grid, i, j+1);
    }
    if (j > 0 && grid[i][j-1] == '1') {
        destroyIsland(grid, i, j-1);
    }
}
}

The code seems correct. The only missing part is

  You may assume all four edges of the grid are all surrounded by water.

which means that numIslands may iterate

    for (int i = 1; i < grid.length - 1; i++) {
        for (int j = 1; j < grid[i].length - 1; j++) {

and do not bother destroyIsland with validating the surroundings.


A simple data class based on an existing collection (Scala) I'm fairly new to Scala and I would like to learn it properly. My current task is to create a type to represent a heap, as seen in interpreters: a mapping from addresses in memory to values stored there.

A heap of that kind is very much like Map, but I would like to hide implementation details and only expose the interface consisting of a few methods, which in pseudo code would be:

* update :: address value -> Heap
* free :: address -> Heap
* alloc :: value -> (Heap, Address)
* addresses :: () -> Set[Address]
* lookup :: address -> [Value]

Here is what I came up with:

trait Heap[T] {

  def update(address: Address, value: T): Heap[T]

  def free(address: Address): Heap[T]

  def alloc(value: T): (Heap[T], Address)

  def addresses(): Set[Address]

  def lookup(address: Address): Option[T]
}

private case class HeapImpl[T](map: Map[Address, T]) extends Heap[T] {
  override def update(address: Address, value: T): Heap[T] = HeapImpl[T](map.updated(address, value))

  override def free(address: Address): Heap[T] = HeapImpl[T](map.removed(address))

  override def alloc(value: T): (Heap[T], Address) = {
    val nextFreeAddress = addresses().maxOption.getOrElse(0) + 1
    (HeapImpl(map.updated(nextFreeAddress, value)), nextFreeAddress)
  }

  override def addresses(): Set[Address] = map.keys.toSet

  override def lookup(address: Address): Option[T] = map.get(address)
}

object Heap {
  def apply[T](): Heap[T] = HeapImpl(Map())
}

I would like to know if this is proper idiomatic Scala or should I approach it differently.

Your code, as posted, doesn't compile because there is no definition for the Address type. However, given the code for nextFreeAddress in the alloc() method, it's pretty obvious that Address can only be type Int, so that's easy to fix.

Also, HeapImpl is private to ... what? A surrounding object I assume, but that's also missing from the posted code so it's a bit unclear. You say you "would like to hide implementation details," which is a good thing, but I don't know that a private implementation class is significantly more hidden than having private members of a public class. Is the implementation class separate because you envision multiple different implementations available to the end user?

It's a bit unusual to have a factory method that takes no parameters except for a type parameter. It wouldn't be difficult to enhance the "constructor" to take optional initial values.

object Heap {
  def apply[T](ts:T*): Heap[T] = HeapImpl(ts.indices.map(x => x -> ts(x)).toMap)
}

Then you can have it both ways:

Heap[Char]()           //res0: Heap[Char] = HeapImpl(Map())
Heap(3L, 5L, 12L, 2L)  //res1: Heap[Long] = HeapImpl(Map(0 -> 3, 1 -> 5, 2 -> 12, 3 -> 2))

(Notice that the REPL has leaked a bit of your implementation detail.)

At first I was confused by the term Heap. Then I re-read the posting and realized that this isn't a heap data structure but is, instead, a chunk of memory for dynamic allocation and requiring memory management.

But your code doesn't actually do any of the things that makes a real heap challenging/interesting: dynamic allocation for heterogeneous data, handle fragmentation, etc. It sort of pretends to be a heap, but not very convincingly (your alloc() doesn't really act like malloc(), calloc(), or realloc()). It's just a thin wrapper around a highly restricted associative array.

So, while I find little to fault in the code, I can't see where it serves much purpose.


mapM for both keys and values of Data.Map I'm writing a monadic parser instance that transforms Data.Map.Map's:

instance (Ord a, FromEDN a, FromEDN b) => FromEDN (M.Map a b) where
    parseEDNv (E.Map m) = mapMmap parseEDNv parseEDN m
    parseEDNv v = typeMismatch "Map" v

Data.Map doesn't provide it's own mapM version like Data.Vector does, so i had to write it from scratch:

mapMmap :: (Ord a2, Monad m) => (a1 -> m a2) -> (b1 -> m b2) -> M.Map a1 b1 -> m (M.Map a2 b2)
mapMmap kf vf m = do
    let pairsIn = M.assocs m
    pairsOut <- mapM fs pairsIn
    return $! M.fromList pairsOut
    where
        fs (k, v) = do
            newK <- kf k
            newV <- vf v
            return (newK, newV)

It works, but very verbose. How to trim into a more succinct INLINEable version without too much black^W monadic magic?

There is keys library which implements

mapWithKeyM_ :: (FoldableWithKey t, Monad m) => (Key t -> a -> m b) -> t a -> m ()

and related functions for Data.Map.

There is also Data.Traversable.mapM, but it only maps over values. Mapping over both keys and values is not a mapM operation because there is Ord constraint.

If you still consider implementing your function yourself, it can be written like this:

import qualified Data.Map as M
import Control.Monad

mapMmap :: (Ord a2, Monad m) =>
   (a1 -> m a2) -> (b1 -> m b2) -> M.Map a1 b1 -> m (M.Map a2 b2)
mapMmap kf vf = liftM M.fromList . mapM fs . M.assocs
    where
    fs (k, v) = liftM2 (,) (kf k) (vf v)


Implement pattern match on FindUsersByName I would like some feedback on the code below. And how would I Implement pattern match on find users in role so that exact match not required?

// MembershipProvider.FindUsersByName
public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords)
{
    MembershipUserCollection users = new MembershipUserCollection();

    try
    {
        Profile.MembershipMapper memberMapper = new MembershipMapper();
        List<Profile.Membership> recs = (List<Profile.Membership>)memberMapper.GetMembershipsByUsername(_memberUtil.GetApplicationId(), usernameToMatch, pageIndex, pageSize, out totalRecords);

        foreach (Profile.Membership rec in recs)
        {
            users.Add(GetUserFromModel(rec, usernameToMatch));
        }
    }
    catch (Exception ex)
    {
        Exception e = CheckEventLog(ex, "FindUsersByName");
        throw e;
    }

    return users;
}

List<Profile.Membership> recs = (List<Profile.Membership>)memberMapper.GetMembershipsByUsername(_memberUtil.GetApplicationId(), usernameToMatch, pageIndex, pageSize, out totalRecords);

I don't understand why is the cast needed here, GetMembershipsByUsername() doesn't sound like a method for which a cast would be necessary.

Also, I think you should consider using var here, especially if you're going to keep the cast, so the type of the variable is clear. (I would probably use var even without the cast, but that's more debatable.)

Exception e = CheckEventLog(ex, "FindUsersByName");
throw e;

I don't see any reason for the (not very well named) variable e here, just throw the exception directly:

throw CheckEventLog(ex, "FindUsersByName");

Also, I think the method name CheckEventLog() could be improved. It's not clear at all that it returns an Exception, or what that exception means.

return users;

I would move this before the end of the try. That way, it's clearer that the method either returns a meaningful result or throws an exception. (And if you changed that later by removing or limiting the throw, you would get a compile error, which I think is a plus.)

Also, doing this means you can move the declaration of the users variable into the try too.


Print a String's even and odd indexes I implemented this method and wanted to get suggestions and or improvements.
The objective of the method is to print the even and odd indexes of Strings contained within an array. Each set of indexes(even and odd) should be seperated by a space.

public static void printEvenOddIndexes(String[] strings){

    for(int i = 0; i < strings.length;i++){
        String word = strings[i];
        ArrayList<Integer> oddIndexes  = new ArrayList<>();
        for(int j= 0; j < word.length();j++){
            if(j % 2 == 0){
                System.out.print(word.charAt(j));
            }else{
                oddIndexes.add(j);
            }
        }
        System.out.print(" ");
        for(Integer index : oddIndexes){
            System.out.print(word.charAt(index));
        }
        System.out.println();
    }
 }

Printing the characters at the even and odd indexes sounds like two similar tasks. So the code for these tasks should look very similar. You can either extract that code to a separate method, or, since it is very simple, just write the code twice.

public static void printEvenOddIndexes(String[] strings) {
    for (String word : strings) {

        for (int i = 0; i < word.length(); i += 2) {
            System.out.print(word.charAt(i));
        }

        System.out.print(" ");

        for (int i = 1; i < word.length(); i += 2) {
            System.out.print(word.charAt(i));
        }

        System.out.println();
    }
 }

The two loops only differ by the starting index. Note the += 2 at the end of the for loop.


Prim's algorithm for finding the minimum spanning tree So I was coding Prim's algorithm for practice and this is what I wrote. It works for finding the weight of the minimum spanning tree (MST) but I'm wondering if the loop I am doing to add the the edges in the frontier to the minheap is optimal.

import heapq
from collections import defaultdict
g = defaultdict(list)
weight = 0
connected = set([])
pq = []

#n is the number of nodes m is the number of edges
n, m = [int(x) for x in raw_input().split(" ")]
#create adjacency list from inputs of the form "vertex1 vertex2 weight"
for _ in xrange(m):
    a, b, w = [int(x) for x in raw_input().split(" ")]
    g[a].append((w, b))
    g[b].append((w, a))

start = int(raw_input())
connected.add(start)
for tup in g[start]:
    heapq.heappush(pq, tup)
while pq:
    w, b = heapq.heappop(pq)
    if b not in connected:
        weight += w
        connected.add(b)
        #by how much does this loop affect the run time of Prims?
        for tup in g[b]:
            heapq.heappush(pq, tup)

print weight

#n is the number of nodes m is the number of edges
n, m = [int(x) for x in raw_input().split(" ")]

well, instead of writing this comment it would be much better to give your variables meaningful and descriptive names, In this way you won't have to read the comment and the variables to know what they are about.

The same applies to g, pq, a.........etc.etc


Walk recursively through dictionaries and return result without using global variable I need to walk through several nested dictionaries in a recursive way and return a value of the type property.

How my code could be improved? Especially, how to do it without a global variable?

field_mapping = {
  "logic_index" : {
    "mappings" : {
      "Patient" : {
        "Diagnosis.Diagnosis_Start_Date" : {
          "full_name" : "Diagnosis.Diagnosis_Start_Date",
          "mapping" : {
            "Diagnosis_Start_Date" : {
              "type" : "date",
              "format" : "strict_date_optional_time||epoch_millis"
            }
          }
        }
      }
    }
  }
}

def get_field_type(mapping):
    ftype = 'string'

    def parse_mapping(mapping):
        global ftype
        for key, item in mapping.iteritems():
            if isinstance(item, dict):
                parse_mapping(item)
            elif key == 'type':
                ftype = item
        return ftype

    ftype = parse_mapping(mapping)
    return ftype

ftype = get_field_type(field_mapping)
print(ftype)

1. Review

There's no docstring, and so it's not clear exactly what this function is intended to compute. In particular, it's not clear what you want to get in these cases:

(a) if there are no items in the data structure with the key "type"?

(b) if there are multiple items in the data structure with the key "type"?

The code you posted raises an exception in case (a):

NameError: name 'ftype' is not defined

and in case (b) it returns the value of the last visited item with that key (which could be any item, since dictionaries may be iterated over in any order).

I'm going to assume that in case (a) you'd actually like to get the default value 'string', and that in case (b) you don't care which value you get and any item with the right key is fine.
The values 'type' and 'string' seem arbitrary, and so it would make sense for them to be parameters to the function.

2. Non-local exit

The problem here is to implement a non-local exit — that is, when you find the value you're after, you want to return all the way up the call stack to the original caller, bypassing all the intermediate calls. This is a job for an exception.

def get_field_type(mapping, key='type', default='string'):
    """Return a value corresponding to the specified key in the (possibly
    nested) mapping. If there is no item with that key, return
    default.

    """
    class Found(Exception):
        pass
    def search(mapping):
        for k, v in mapping.iteritems():
            if isinstance(v, dict):
                search(v)
            elif k == key:
                raise Found(v)
    try:
        search(mapping)
    except Found as exc:
        return exc.args[0]
    else:
        return default

3. Stack of iterators

Alternatively, you could avoid using recursion and instead maintain the current search state using a stack of iterators. Then there's no difficulty: when you find the item you want you can return it immediately.

def get_field_type(mapping, key='type', default='string'):
    """Return a value corresponding to the specified key in the (possibly
    nested) mapping. If there is no item with that key, return
    default.

    """
    stack = [mapping.iteritems()]
    while stack:
        for k, v in stack[-1]:
            if isinstance(v, dict):
                stack.append(v.iteritems())
                break
            elif k == key:
                return v
        else:
            stack.pop()
    return default

(In Python 3 you need to write iter(mapping.items()) instead of mapping.iteritems() and similarly iter(v.items()) instead of v.iteritems().)


Improving Matlab function within big simulation I have a very big Matlab simulation project in my hands, which I wanted to optimize, since I'm running it many times to tune parameters and the like.

Using Matlab's profile I identified one function that is eating up most of my time, specifically the output(i,1) assignment line.

This function is called a LOT, where input is a 10x1 double passed as an argument, and output is also a 10x1 vector.

function output = my_function(input)

a = size(input,1);
output = input*0;
dens = density(input);

% for each i, output(i) is the maximum between output(i+1) and mean(output(i+1:end))
for i = 1:a-1
    output(i,1)= max(mean(dens(i+1:a,1)),dens(i+1,1));
end
output(a,1) = dens(a,1);

end

density() function:

function dens = density(input)

dens = 1000*(1 - (input+288.9414)./(508929.2.*(input+68.12963)).*(input-3.9863).^2);

end

My ideas:

I think vectorization would maybe help to get rid of the loop, but I'm not familiar at all with the technique.
Is there a faster/alternative way to calculate the mean (maybe without Matlab's built-in function call?)

Vectorization

If you look at all the calls to mean, you see that what you are calculating in each loop is a "Cumulative moving average", but in the oposite direction of what one usually would do.

A cumulative moving average can be calculated quite simply using the cumulative sum, cumsum, and dividing by the number of elements. Since you're starting with all elements and up with only one, we need to flip it.

The running mean, (or cumulative moving average) can be calculated like this:

First flip dens upside down
Take the cumulative sum of it
Divide each element by the number of elements counted
Flip it back up

Thus:

running_mean = flipud(cumsum(flipud(dens))./(1:numel(dens)).');

Now, we need to find which element is larger, the cumulative sum, or the original density variable. You are not including the first element of the cumulative sum, and you are appending dens(end) at the end of the vector.

The maximum value of each row of a matrix can be found using max(A,[],2), where the number two represent the second dimension (columns). So, the values we want to use are:

max([running_mean(2:end), dens(2:end)],[],2)

In addition, we need to append the last element, so:

output = [max([running_mean(2:end), dens(2:end)],[],2); dens(end)];

To summarize, the entire operation requires no loops, one call to cumsum, and one call to max. In addition we need to flip it twice, but that takes virtually no time.

In total, your function can be written like this:

function output = my_function(vector)

n = numel(vector);    % numel, not length
output = zeros(n,1)   % prior to R2015b, use: output(n,1) = 0

% Create an anonymous function called density:
density = @(vector) 1000*(1 - (vector+288.9414)./(508929.2.*(vector+68.12963)).*(vector-3.9863).^2);

% Calculate the density:
dens = density(vector);

% Calculate the running mean, and create the final output vector:
running_mean = flipud(cumsum(flipud(dens))./(1:numel(dens)).');
output = [max([running_mean(2:end), dens(2:end)],[],2); dens(end)];

end

Time in Octave shows the improvement, as a function of vector size. For vectors with only ten elements, the execution time is 25% of the original code.

Review of your code:

Don't use input as a variable name! input is used to ask users for a command line input. Using it as a variable name makes the function useless, but will also potentially create strange errors or warnings. (I called it vector in this review. You should pick a more descriptive name)

The same goes with max, mean, length etc. Don't use function names as variable names.
Your input is a vector, so no need to specify that you always want the first column. Use linear indexing instead of subscripts. It's much faster, and you won't mess up the dimensions (oops, it was a column vector, not a row vector).
Don't use size(vector,1), and don't use length(vector), use numel(vector). It's faster and more robust.
You are pre-allocating output. Very good! That's a common bottleneck.
output = vector*0; is clever. Prior to Matlab R2015b zeros(n,1) was actually far from the fastest way to create a vector of zeros! In fact, output(n,1) = 0 was up to 500 times faster! This is because zeros creates a matrix, then fills the elements with zeros, where as the latter just creates a matrix, where the values are zero by default.
In your loop, don't use i as the iterator, it is used for the imaginary unit (sqrt(-1)). It's common to use for instance ii, jj etc.
If your density function is only what you have posted there, then you can simply create an anonymous function inside the main function:

density = @(vector) 1000*(1 - (vector+288.9414)./(508929.2.*(vector+68.12963)).*(vector-3.9863).^2);

Call it like:

dens = density(vector);

Review of reviews:

There are a few things I don't like about the other reviews that I want to point out:

"You don't need to specify that 1 when indexing a vector, MATLAB knows". Many Matlab users use max(A), when they want to find the maximum value of all columns in a matrix. It's much simpler than max(A, [], 1). You might however come into trouble if A has varying number of rows (and matrices often do). Because the moment that matrix has only one row, max(A) will give the maximum value of the entire vector, instead of each (one row) column. This can give you a major headache!
"Why not use length?" Well, in this case, length is much better than size, but numel should still be the preferred choice. length is better than size for two reasons. Using size limits the function to only work on column vectors only, and will fail on row vectors. Second, numel is much faster than length for large vectors, and both are much faster than size for all vectors.
"Don't use the profiler, use tic/toc". True, the profiler includes the time it takes to run itself, but it's still the easiest way to identify bottlenecks. For exact timing however, don't use tic/toc. timeit was introduced in Matlab R2013b, and is much better than tic/toc. If you are using an older version, the function is available at the File Exchange. tic/toc is also dangerous, because it will reset the timer if tic is called inside another function. Have a look at this question on SO from three years ago.


Create a stack implementation that handles the multi thread scenario MyStack.h

@interface MyStack : NSObject

- (id)pop;
- (void)pushObject:(id)object;

@end

MyStack.m

@interface MyStack ()

@property (atomic) NSMutableArray *stackArray;

@end

@implementation MyStack

- (instancetype)init {
    self = [super init];
    if (self != nil)
    {
        _stackArray = [NSMutableArray new];
    }
    return self;
}

- (id)pop {
    id obj = nil; // can return statements be part of critical sections themselves?
    @synchronized(self) {
        if ([self.stackArray count] != 0) {
            obj = [self.stackArray lastObject];
            self.stackArray = [[self.stackArray mutableCopy] removeLastObject];
        }
    }
    return obj;
}

- (void)pushObject:(id)object {
    @synchronized(self) {
        [self.stackArray addObject:object];
    }
}

@end

This is very easy to read and well written. As far as I can tell, it accomplishes your goal in a very straightforward way, and should be very easy to maintain going forward.
Does It Do Enough?
Overall, it's a very simple class. Are you sure there aren't any additional things it should do? I know in the past, I've needed to check the size of a stack (see how many items are on it). So a -count method might be in order. And maybe an -isEmpty method (though a caller could just check if count is 0.) Also, sometimes it is desirable to get the top object without popping it off. Many stack implementations have a -top method to do that.
You might also want to offer some additional initializers similar to the other Cocoa containers. Maybe things like -initWithCapacity:, -initWithStack:, and if you're feeling ambitious, -initWithObjects:.
Error Handling
In the -pop method you check to see if there are any items on the stack, and if so, return the top item after removing it from the stack. In general a caller should be informed if they are trying to pop a stack with no items on it. While you do return nil it might be better to raise an exception in that case, similar to how an NSArray will raise an exception if you try to get an object at an index that does not exist.


Weaving rows of numbers I want to write a cleaner version of this code. It's about two different rows consisting of numbers that have to be weaved. I have already asked this question at this link, but I have translated my code in English so that it's maybe easier to help me improve it.

It's for an assignment for a course I'm currently following:

Traveler, if riches are to be achieved, the solution only has to be weaved.
5,4 4,5 8,7
Weave 6,3 3,2 9,6 4,3
Weave 7,6
Weave 9,8
Weave 5,5 7,8 6,5 6,4

I have to start with the coordinates on the first row, weave the coordinates of the second row through the first row, then weave the coordinates of the third row through the resulting row etc. Note, if two rows of unequal length have to be woven, the two rows are woven as far as possible. After the elements of the shortest row have been exhausted, the row is completed by adding the remaining elements of the longest row.

The input is this (my code already returns the desired output):

5,4 4,5 8,7=6,3 3,2 9,6 4,3=7,6=9,8=5,5 7,8 6,5 6,4

The output has to be like this:

6,4
6,5
10,8
8,8
8,6
7,5
7,3
7,4
5,5
4,2
9,7
10,6
5,3

Coordinate.py

class Coordinate:
    def __init__(self, x_coord, y_coord):
        self.x_coord = x_coord
        self.y_coord = y_coord

    def calculate_new_coord(self):
        self.x_coord += 1
        self.y_coord += 0
        return self.x_coord, self.y_coord

CoordinateRow.py

class CoordinateRow:
    def __init__(self, row):
        self.row = row

    def append(self, coord):
        self.row += [coord]

    def extend(self, row):
        for coordinate in row:
            self.row += [coordinate]

    def weave(self, weaveRow):
        result = CoordinateRow([])
        for i in range(len(self.row)):
            if i < len(self.row):
                result.append(self.row[i])
            if i < len(weaveRow.row):
                result.append(weaveRow.row[i])
        if len(weaveRow.row) > len(self.row):       #Als 2e rij(te weaven door 1e rij) groter dan 1e rij(bestaande rij)
            result.extend(weaveRow.row[len(self.row):])  #voeg het verschil toe aan result
        return result

Excerpt of the main code

file_input = file.read()
strip_file = file_input.strip()
splits_file = strip_file.split("=")

from Coordinate import Coordinate
from CoordinateRow import CoordinateRow

def get_weaved_rows(splits_bestand):
    rows = []
    for i in range(len(splits_bestand)):
        rows += [CoordinateRow(splits_bestand[i].split())]
    previous_row = rows[0]

    for row in rows[1:]:
        previous_row = previous_row.weave(row)
    return previous_row

def get_new_coordinates(weaved_rows):
    for coordinate in weaved_rows.row:
        current_coordinates = Coordinate(int(coordinate[0]), int(coordinate[2])) #coordinaat x[0] en y[2] worden int(x,y)
        new_coordinates = current_coordinates.calculate_new_coord() #coordinaten (x,y) na verwerking
        print '%d,%d' %(new_coordinates[0], new_coordinates[1])

weaved_rows = get_weaved_rows(splits_file)
get_new_coordinates(weaved_rows)

There are some things, which can be improved.

For one, the weave method can be rewritten using itertools, see this SO post for examples.
The idea is to combine elements via iterators (with function similar to zip - see izip_longest), chain and filter out Nones, which were possibly added from missing counterparts.

Then, this pattern:

rows = []
for i in range(len(splits_bestand)):
    rows += [CoordinateRow(splits_bestand[i].split())]

can be replaced with more compact comprehension:

rows = [CoordinateRow(sb.split()) for sb in splits_bestand]

Also, Python list has extend method, which can be used directly in .extend method, like: self.row.extend(row). Similarly for append method. If you will need those at all after using itertools.

Code for previous raw can also be easily rewritten with itertools. Left as an exercise.


Joomla PHP Template Logic I'm in the process of building some templates for Joomla, and although it all works as desired, I can't help thinking that there has to be a more elegant way to do this in PHP than my current approach. For the record, I'm still reasonably new to PHP!

Using collapsible module positions, I need to assign various CSS classes to a div depending on how many modules are published on a particular row. The code I wrote is below;

    if (($footer1 != "0") && ($footer2 == "0") && ($footer3 == "0")) {
    $footerWidth = 'full';
    }
    elseif (($footer1 == "0") && ($footer2 != "0") && ($footer3 == "0")) {
    $footerWidth = 'full';
    }
    elseif (($footer1 == "0") && ($footer2 == "0") && ($footer3 != "0")) {
    $footerWidth = 'full';
    }
    elseif (($footer1 != "0") && ($footer2 != "0") && ($footer3 == "0")) {
    $footerWidth = 'one_half';
    }
    elseif (($footer1 != "0") && ($footer2 == "0") && ($footer3 != "0")) {
    $footerWidth = 'one_half';
    }
    elseif (($footer1 == "0") && ($footer2 != "0") && ($footer3 != "0")) {
    $footerWidth = 'one_half';
    }
    else {
    $footerWidth = 'one_third';
    }

I then use the following code in the template itself to check for modules published;

    <?php if ($footer1 > 0) : ?>
                <div class="<?php echo htmlspecialchars($footerWidth); ?>">
                    <jdoc:include type="modules" name="footer1" style="html5" />

    <?php endif; ?>
    <?php if ($footer2 > 0) : ?>
                <div class="<?php echo htmlspecialchars($footerWidth); ?>">
                    <jdoc:include type="modules" name="footer2" style="html5" />

    <?php endif; ?>
    <?php if ($footer3 > 0) : ?>
                <div class="<?php echo htmlspecialchars($footerWidth); ?>">
                    <jdoc:include type="modules" name="footer3" style="html5" />

    <?php endif; ?>

Can anyone suggest / recommend a better approach? It just seems like a lot of code for a simple function.

Something somewhat confusing is the comparison to of each $footer# to the string '0' then later comparing it to greater than integer 0.  This is practically the definition of weakly typed languages.  If you know what $footer# variables actually contain you might be able to simplify this, but here is a fully functioning replacement to the first code block.

One could simplify this a bit, but the core concepts are there.  '0' casts to False, and True casts to 1.  There are plenty of other ways to accomplish the same thing, especially if you have significantly more incoming $footer#'s, or if they are stored in something iteratable like an array.

//$footer1 = '10';
//$footer2 = '-5';
//$footer3 = '0';

$footer1Bool = (bool) $footer1;
$footer2Bool = (bool) $footer2;
$footer3Bool = (bool) $footer3;

$footer1Int = (int) $footer1Bool;
$footer2Int = (int) $footer2Bool;
$footer3Int = (int) $footer3Bool;

$footerCombined = $footer1Int + $footer2Int + $footer3Int;

if ( $footerCombined >= 3 ) {
    $footerWidth = 'one_third';
} else if ( $footerCombined == 2 ) {
    $footerWidth = 'one_half';
} else {
    $footerWidth = 'full';
}


Deserializing response to correct type I use this method to get either Customer or Account. The server will determine which type it is.

The response will have a property "Type": "Customer" or "Type": "Account".

I first deserialize to Client (supertype) to check the Type property. Then deserialize to either Customer or Account.

public async Task<Models.Entities.Client> GetClient(int clientId)
{
    var getClientRequest = new RestRequest("client/details", Method.GET);
    getClientRequest.AddQueryParameter("ClientId", clientId);

    var jsonResponse = await _requestService.DoRequest(getClientRequest);

    var client = JsonConvert.DeserializeObject<Models.Entities.Client>(jsonResponse);

    switch (client.Type)
    {
        case ClientKind.Account:
            var account = JsonConvert.DeserializeObject<Account>(jsonResponse)
            return account;
        default:
            var customer = JsonConvert.DeserializeObject<Customer>(jsonResponse);
            return customer;
    }
}

Example responses:

{
    "ClientId": 1,
    "Type": "Account",
    "Name": "Company Inc."
}

{
    "ClientId": 2,
    "Type": "Customer",
    "Name":
    {
        "First": "John",
        "Last": "Smith"
    },
    "DateOfBirth": "1960-12-01"
}

DTOs:

public class Client
{
    public int ClientId { get; set; }
    public ClientType Type { get; set; }
}

public class Account : Client
{
    public string Name { get; set; }
}

public class Customer : Client
{
    public PersonalName Name { get; set; }
    public DateTime DateOfBirth { get; set; }
}

Your code could be rewritten:

var settings = new JsonSerializerSettings {
     TypeNameHandling = TypeNameHandling.All,
     SerializationBinder = knownTypesBinder // <- see security risk below
};
var client = JsonConvert.DeserializeObject<Models.Entities.Client>(jsonResponse);
return client; // <- strongly-typed

Make sure both server and client use the settings
If you have declared  public ClientType Type { get; set; } just to enable two-phase serialisation (base entity - concrete entity), you should remove it from the code.
The two-phase serialisation hack can be replaced with a strongly-typed serialisation using TypeNameHandling = TypeNameHandling.All. Example

As suggested in the comments, we need to address the security aspect also. Hence, knownTypesBinder is used to mitigate a security risk.

// based on https://www.newtonsoft.com/json/help/html/SerializeSerializationBinder.htm
var knownTypesBinder = new KnownTypesBinder
{
    KnownTypes = new List<Type> { typeof(Customer), typeof(Account) }
};

public class KnownTypesBinder : ISerializationBinder
{
    public IList<Type> KnownTypes { get; set; }

    public Type BindToType(string assemblyName, string typeName)
    {
        return KnownTypes.SingleOrDefault(t => t.Name == typeName);
    }

    public void BindToName(Type serializedType, out string assemblyName,
        out string typeName)
    {
        assemblyName = null;
        typeName = serializedType.Name;
    }
}


Fizzbuzz in C for console I imagine I get a minuscule performance improvement by doing the %3 as a branch off the %5 rather than the other way round or as an if '%15'. Am I correct about that? (I know there is no practical difference)

#include <stdio.h>

///Write a program that prints the numbers from 1 to 100.
///But for multiples of three print "Fizz" instead of the number and for the multiples of five print "Buzz".
///For numbers which are multiples of both three and five print "FizzBuzz".
int main()
{
    int a=1;
    while (a<101)
    {
        if (a%5==0)
        {
            if (a%3==0)
            {
                printf("FizzBuzz\n");
            }
            else
            {
                printf("Buzz\n");
            }
        }
        else if(a%3==0)
        {
            printf("Fizz\n");
        }
        else
        {
            printf("%d\n",a);
        }
        a++;
    }
return 0;
}

I have my doubts that any method is significantly faster than another given the sink-hole of time that printf() is, but here is another approach

#define FB "FizzBuzz\n"
#define F "Fizz\n"
#define B "Buzz\n"
#define N "%d\n"

int main(void) {
  static const char *fmt[15] = {
      FB, N, N, F, N, B, F, N, N, F, B, N, F, N, N };
  for (int a = 1; a <= 100; a++) {
    printf(fmt[a % 15], a);
  }
  return 0;
}


disable other default row- Entity framework I have a table that name is Store  , In Store Table , just one row can IsDefault=true at time . when I insert new Row , I check If user selected IsDefault , I  update other row whice isDefault=true . I use this code :

public AddStatus Add(AddStoreViewModel storeViewModel)
    {
        if (Exists(storeViewModel.Name)) return AddStatus.Exists;
        var storeModel = Mapper.Map(storeViewModel, new StoreEntity.Store());
        if (storeModel.IsDefault)
        {
            var defaultStore = GetDefault();
            if (defaultStore != null)
            {
                defaultStore.IsDefault = false;
                _uow.MarkAsBaseChanged(defaultStore); // update
            }
        }
        _uow.MarkAsBaseAdded(storeModel);
        return AddStatus.Successfull;
    }

and in controller I call Above Method like belowe and Call SaveAllChanges :

 _storeService.Add(storeViewModel);
 await _uow.SaveChangesAsync();

and  MarkAsBaseChange like belowe :

  public void MarkAsBaseChanged<TEntity>(TEntity entity) where TEntity : BaseEntity
    {
        Entry(entity).Entity.Action = Enums.AuditAction.Update;
}

is this code ok ?

Does _uow.MarkAsBaseChanged() primarily hide EF's SaveChanges()?
If so, make a new version that can take an array of objeects.

You would want both objects saved with one command to ensure the transaction. As it ia nw, if storeModel fails you no longer have a default store.


First try Caesar Cipher I've recently begun to teach myself to code. One simple project that I wanted to do was create a Caesar cipher that works well. Now that I feel I've accomplished that task, I'd like to know how I'm doing with overall code quality. Here's the code.

import java.util.Scanner;

public class Encryptor
{
    private char[] upperCase = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
    private char[] lowerCase = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
    private char oneChar;
    private String encryptedString = "";
    private int counter;

    public String encryptString(String input, int offset)
    {
        for (counter = 0; counter < input.length(); counter++)
        {
            oneChar = input.charAt(counter);

            boolean moveOn = false;
            int i = 0;

            //get a single character

            while (!moveOn)
            {
                if (i > 26)
                {
                    encryptedString += oneChar;
                    moveOn = true;
                }
                //remainder keeps me from going over array length
                else if (oneChar == upperCase[i%26])
                {
                    encryptedString += upperCase[(i+offset)%26];
                    moveOn = true;
                }
                else if (oneChar == lowerCase[i%26])
                {
                    encryptedString += lowerCase[(i+offset)%26];
                    moveOn = true;
                }
                else
                {
                    i++;
                }
            }
        }
        return encryptedString;
    }
}

public class Main
{
    public static void main (String[] args)
    {
        String inText = "";
        String encryptedText = "";
        int offset = 0;
        String choice;

        Scanner input = new Scanner(System.in);

        System.out.println("Enter something to encrypt or decrypt");
        inText = input.nextLine();

        System.out.println("Would you like to encrypt your message, or decrypt your message? Please type in encrypt or decrypt.");
        choice = input.next();

        System.out.println("How many letters over should the program shift everything? Enter numbers only.");
        offset = input.nextInt();

        Encryptor encrypt = new Encryptor();
        if (choice.equalsIgnoreCase("encrypt") || choice.equalsIgnoreCase("e"))
        {
            encryptedText = encrypt.encryptString(inText, offset);
        }
        else if (choice.equalsIgnoreCase("decrypt") || choice.equalsIgnoreCase("d"))
        {
            offset = 26 - offset;
            encryptedText = encrypt.encryptString(inText, offset);
        }
        System.out.printf("Your message is %s", encryptedText);

        }

    input.close();

    }
}

What do you think of it in terms of overall readability? And for a first attempt, how'd you rank it?

EDIT: Adding in some more questions that occurred overnight.

What things in this make you cringe/confused/ need to be improved?
I noticed that during decryption, if the offset goes below 0, I get an index out of range error. For example, if some joker decides to offset more than 26, say 27, the offset becomes -1. This is then subtracted and ran through the remainder and comes out negative. A negative value in an array is an error. I can't simply do the absolute value of the number either as the way my code and arrays are set out, -1%26 would not be 1%26, rather -1%26 should be equivalent to 25.

It would seem that you are restricting yourself to English alphabet, when there is no need for that. All that Caesar cipher does, is adding some constant (usually called key) to each character. Decoding then may be done by subtracting that very key from each encoded character. All in all, I had this in mind:

public class Encryptor {

    public static String encryptString(String input, int key) {
        StringBuilder sb = new StringBuilder(input.length());

        for (char c : input.toCharArray()) {
            sb.append((char)(c + key));
        }

        return sb.toString();
    }

    public static String decryptString(String input, int key) {
        return encryptString(input, -key);
    }
}

Also, using StringBuilder
will improve the performance of your cipher: when you do

char c = '?';
myString += c;

a new String is created which runs in linear time as it needs to copy the character content. However, appending to a StringBuilder of a known size runs in constant time.

I run your program, and it does not cipher the white-space. This makes breaking your cipher easier as the attacker will see clearly the lengths of words. Instead, cipher any character in the input string.


proper structure of classes using interface classes Given the following two interfaces what would the proper way to set up the two actual classes?

public interface IPortfolio
{
    string FirstName { get; set; }
    string LastName { get; set; }
    string Name { get; set; }
    int Id { get; set; }
    List<IDocument> Documents { get; set; }
}
public interface IDocument
{
    string ExtensionType { get; set; }
    int Id { get; set; }
    DateTime? DateFiled { get; set; }
    int? Size { get; set; }
    int? SortOrder { get; set; }
}

The actual classes:

 public class Portfolio : IPortfolio
{
    public Portfolio()
    {
        Documents = new List<IDocument>();
    }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Name { get; set; }
    public int Id { get; set; }
    public List<IDocument> Documents { get; set; }
}

public class Document : IDocument
{
     public Document()
     {
       Pages = new List<IPage>();
     }
     public string ExtensionType { get; set; }
     public int Id { get; set; }
     public DateTime? DateFiled { get; set; }
     public int? Size { get; set; }
     public List<IPage> Pages { get; set; }
     public int? SortOrder { get; set; }
}

When using the code above I get an error about not being able to implicitly convert List<Document> to List<IDocument>

This is a learning project to understand the concept of Interfaces and how they should best be used.

There no such thing like an interface class (term used in initial version of post). You have interfaces and classes implementing the interfaces.

I don't see any List<Document> in your code, but If you have defined the list as List<IDocument>, you must stick to this definition. You cannot assign it a List<Document>. But you can add Document objects to this list.

Generally two types T<A> and T<B> are not assignment compatible, even if A and B are assignment compatible. An exception is when the in or out keywords are used in generic interfaces. But this can only be done if the generic type occurs exclusively as input or exclusively as output as explained in Variance in C#.NET 4.0 Covariance and Contravariance.

I would convert the list properties Documents and Pages to getter-only properties.

public interface IPortfolio
{
    string FirstName { get; set; }
    string LastName { get; set; }
    string Name { get; set; }
    int Id { get; set; }
    List<IDocument> Documents { get; }
}

And create the class like this

public class Portfolio : IPortfolio
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Name { get; set; }
    public int Id { get; set; }
    public List<IDocument> Documents { get; } = new List<IDocument>();
}

This makes the Documents property read-only. The list itself remains read/write.

var portfolio = new Portfolio();
portfolio.Documents.Add(new Document());


Normal distribution array function I have a function that produce an array with values that are Gaussian (normal) distribution. If you plot the values on a graph, it would look something like this:

Is there any way to improve on the code?

private static IComparable[] NonUniformDistributionsGaussian(int startNumber,int arraySize)
    {
        IComparable [] arr = new IComparable[arraySize];
        Double[] intervals = { ((1.00 / 6.00) * arraySize), ((2.00 / 6.00) * arraySize),
                                 ((3.00 / 6.00) * arraySize),((4.00 / 6.00) * arraySize),
                                 ((5.00 / 6.00) * arraySize), ((6.00 / 6.00) * arraySize) };

        for (var i = 0; i < arraySize; i++)
        {

            if (i <= (int)intervals[0])
            {
                startNumber = startNumber + 1;
            }

            else if ( i <= (int)intervals[1])
            {
                 startNumber = startNumber  + 2;
            }
            else if (i <= (int)intervals[2])
            {
                startNumber = startNumber + 3;
            }
            else if (i <= (int)intervals[3])
            {
                startNumber = startNumber - 3;
            }
            else if (i <= (int)intervals[4])
            {
                startNumber = startNumber - 3;
            }
            else
            {
                 startNumber = startNumber  - 2;
            }
            arr[i] = startNumber;
        }
        return arr;
    }

As the conditions of the if statements only depending on some fixed numbers and the arraysize input parameter these values can be precalculated.

int oneThirdArraySize = (int)((1.00 / 3.00) * arraySize);

and then used in the loop like

for (var i = 0; i < arraySize; i++)
{

    if (i <= oneThirdArraySize)
    {
        startNumber = startNumber + 1;
        arr[i] = startNumber;
    }
    // and so on
}

By precalculation of the right side values of the if conditions outside of the loop you can speed this up because right now you do these calculation up to two times for every iteration.

But we can do better because you are using some magic numbers here which we can hide behind some meaningful const variables.

private static const double oneThird = 1d / 3d;
private static const double twoThird = 2d / 3d;

In this way the calculations need to be changed to

int oneThirdArraySize = (int)(oneThird * arraySize);


If height param is not number - then log and set to default I am creating a class with a constructor and instead of double handling, I thought I would use a one line conditional and if the class property is not set correctly then console.log out a message.

I want to know if there is a cleaner implementation for the following height property as at the moment I don't think readability is overly terrific.

This is basically what I have:

class Example1 {
  constructor(height) {
    this.defaultHeight = 100;

    this.height = !isNaN(height) ? height : (() => {
      console.log("That was not a number >> " + height);
      return this.defaultHeight
    })();

  }
}

//////////////////////////////////////////////////////////////////////
console.log("init example 1 w/ height of 0")
var example1 = new Example1(0);
console.log("example1.height is ", example1.height);
console.log("init example 2 w/ height of 'bob'")
var example2 = new Example1("bob");
console.log("example2.height is ", example2.height);

I usually only use ternaries if I can keep my code clean and at the same time keep the ternary under 2-3 lines. That's just me, but I would make a few small changes to increase readability.

class Example1 {
  constructor(height) {
    this.defaultHeight = 100;

    this.height = typeof height === 'number' ? height :
      (() => {
        console.log(height, 'is not a number');
        return this.defaultHeight;
      })();

  }
}


String comparison using pointers This piece of code works fine. But I'm wondering if it can be done in a more efficient way. More specifically, this part (*(s1 + i)) if it possible to force it to sequence through entire array character by character via pointer, for example, *s1++.

My task to do this function compareStrings without index array []:

int  compareStrings(const char  *s1, const char  *s2)
{
    int i = 0, answer;
    //  i - to sequence through array of characters
    // pointer to character string1 and character string2
    while (*(s1 + i) == *(s2 + i) && *(s1 + i) != '\0'&& *(s2 + i) != '\0')
    {
        i++;
    }

    if ( *(s1 + i) < *(s2 + i) )
        answer = -1;               /* s1 < s2  */
    else if ( *(s1 + i) == *(s2 + i) )
            answer = 0;                 /* s1 == s2 */
        else
            answer = 1;                 /* s1 > s2  */

        return answer;

But I want to change it to s1++ and s2++ instead of *(s1 + i) and *(s2 + i). I've tried to implement this idea with pining an extra pointer to the beginning but I've failed.

int  compareStrings(const char  *s1, const char  *s2)
{
  int answer;
  char **i = s1, **j = s2;
  // i to sequence through array of characters
  while (*(i++) == *(j++) && *(i++) != '\0'&& *(j++) != '\0');

  if (*i < *j)
      answer = -1;               /* s1 < s2  */
  else if (*i == *j)
      answer = 0;                 /* s1 == s2 */
  else
      answer = 1;                 /* s1 > s2  */

  return answer;
}

You don't need pointers to character pointers at all:

int str_cmp(const char* s1, const char* s2)
{
    while (*s1 != '\0' && *s1 == *s2)
    {
        ++s1;
        ++s2;
    }

    if (*s1 == *s2)
    {
        return 0;
    }

    return *s1 < *s2 ? -1 : 1;
}

Also, there is a bug in your second implementation: it returns 1 on compareStrings("hello", "helloo"), when the correct result is -1.

Hope that helps.


Optimize ineffiecient Jquery - UX list to grid view I am fairly new to jQuery and I am making a new search results page. In this snippet I am switching from a grid to list view and vice versa. Can anyone suggest a cleaner method of performing this change? I did try using a variable to minimize all my (this) calls but I couldn't get them to work. Any help would be much appreciated.

JS

    $('.btn.grid').click(function() {
      if (!$(this).hasClass("active")) {
        $(this).addClass("active");
        $('.results-wrapper .grid_12').removeClass("grid_12").addClass("grid_3");
        $('.wrapper .results').addClass("grid-view-active");
        if ($(".btn.list").hasClass("active")) {
          $(".btn.list").removeClass("active");
          $('.wrapper .results').removeClass("list-view-active");
        }
      }
    });
    $('.btn.list').click(function() {
      if (!$(this).hasClass("active")) {
        $(this).addClass("active");
        $('.results-wrapper .grid_3').removeClass("grid_3").addClass("grid_12");
        $('.wrapper .results').addClass("list-view-active");
        if ($(".btn.grid").hasClass("active")) {
          $(".btn.grid").removeClass("active");
          $('.wrapper .results').removeClass("grid-view-active");
        }
      }
    });

HTML

grid
list

Title

Title

Title

Title

Title

Title

Title

Title

Title

Title

CSS

.btn {
  background: #ccc;
  cursor: pointer;
  display: inline-block;
  height: 35px;
  width: 35px;
}
.btn.active {
  background: red;
}
li {
  float: left;
  height: 200px;
  width: 200px;
}
li img {
  max-width: 100%;
  max-height: 100%;
}
.grid_3 {
  width: 25%;
}
.grid_12 {
  width: 100%;
}

You can simply use JS to toggle a list class. In CSS, you can simply override the style to either display block (item per row, list style), or display inline-block (several items side-by-side per row, grid style).

A simple demo here:

JS:

$('.btn.grid').click(function (event) {
    event.preventDefault();
    $('.results').addClass('grid');
});
$('.btn.list').click(function (event) {
    event.preventDefault();
    $('.results').removeClass('grid');
});

CSS:

/* default list mode */
.results li{
    padding: 0;
    margin: 0;
    display : block;
}

/* grid mode */
.results.grid li{
    display:inline-block;
    width: 100px;
}

.results img{
    display:block;
    width: 100%;
}


Small method for saving student attendance var studentRepo = new StudentRepository();
int gradeParaleloId = Convert.ToInt32(cmbGradeParalelo.SelectedValue);
var students = studentRepo.FindAllStudentsFromGradeParalelo(gradeParaleloId);

int year = DateTime.Now.Year;
int month = Convert.ToInt32(cmbMes.SelectedIndex) + 1;
AttendanceRepository attendanceRepo = new AttendanceRepository();

for (int i = 0; i < students.Count; i++)
{
    for (int j = 1; j < dataGridView1.Columns.Count; j++)
    {
        DateTime date = new DateTime(year, month, j);

        var student = students[i];
        var attendance = attendanceRepo.FindAttendance(student.StudentId, date);

        if (attendance == null)
        {
            attendance = new Data.Repositories.Attendance();
            attendanceRepo.Add(attendance);
        }

        attendance.StudentId = student.StudentId;
        attendance.DateOfAttendance = date;
        attendance.Attended = dataGridView1[j, i].Value.ToString();
    }
}

attendanceRepo.SaveChanges();

My main thorn in the side is that for each day in the month, I have to query the database, and see if a record already exists in the DB for that day and student.

The upside is that I'm putting each attendance in the datacontext and only pushing the save at the very end as a transaction of sorts.

So I'm not inserting on every day for every student. Imagine for a class of 40 students. That's an easy \$40 * 30 = 1200\$ queries on the spot.

Is there some way for me to streamline this? I'm more concerned about this line:

var attendance = attendanceRepo.FindAttendance(student.StudentId, date);

First of all, minor beef. I'd reccommend that you change your index names to be more descriptive, particularly the inner one. For instance you could make your repo query

DateTime date = new DateTime(year, month, **day**);

Much more readable. When an index has a name, name it.

If you're having performance issues, try separating out the queries. In psuedocode:

foreach day in month
   get students_with_records from database

   foreach student in the_class
      if student NOT in students_with_records
         add record

This method will put the search through the student records on the client...it should be faster, since you will only have one query per day rather than one query per day per student. You really should profile the app and see if it's an issue, though.


Matrix Transpose in Golang I have write a normal programm "Transpose the matrix" in go. Suppose input are always correct. I also read the article An Efficient Matrix Transpose in CUDA C/C++. So I keen to know how I can use Go-routines or another efficient way to problem in go way

package main

import (
    "fmt"
)

func main() {
    a := [][]int{{1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4}}
    r := transpose(a)
    fmt.Println(r)
}

func transpose(a [][]int) [][]int {
    newArr := make([][]int, len(a))
    for i := 0; i < len(a); i++ {
        for j := 0; j < len(a[0]); j++ {
            newArr[j] = append(newArr[j], a[i][j])
        }
    }

    return newArr
}

In Go, measure performance. Run benchmarks using the Go testing package.

For example,

$ go test transpose_test.go -bench=. -benchmem
BenchmarkTranspose-4       2471407    473 ns/op    320 B/op    13 allocs/op
BenchmarkTransposeOpt-4    9023720    136 ns/op    224 B/op     2 allocs/op
$

As you can see, minimizing allocations is important. Efficient memory cache usage probably helps too.

transpose_test.go:

package main

import "testing"

func transpose(a [][]int) [][]int {
    newArr := make([][]int, len(a))
    for i := 0; i < len(a); i++ {
        for j := 0; j < len(a[0]); j++ {
            newArr[j] = append(newArr[j], a[i][j])
        }
    }
    return newArr
}

func BenchmarkTranspose(b *testing.B) {
    a := [][]int{{1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4}}
    b.ResetTimer()
    for N := 0; N < b.N; N++ {
        _ = transpose(a)
    }
}

func NewMatrix(d2, d1 int) [][]int {
    a := make([]int, d2*d1)
    m := make([][]int, d2)
    lo, hi := 0, d1
    for i := range m {
        m[i] = a[lo:hi:hi]
        lo, hi = hi, hi+d1
    }
    return m
}

func transposeOpt(a [][]int) [][]int {
    b := NewMatrix(len(a[0]), len(a))
    for i := 0; i < len(b); i++ {
        c := b[i]
        for j := 0; j < len(c); j++ {
            c[j] = a[j][i]
        }
    }
    return b
}

func BenchmarkTransposeOpt(b *testing.B) {
    a := [][]int{{1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4}}
    b.ResetTimer()
    for N := 0; N < b.N; N++ {
        _ = transposeOpt(a)
    }
}

Goroutines have overhead. For a small task (4 x 4 matrix), the overhead may outweigh any gains.

Let's look at a 1920 x 1080 matrix (the size of an FHD display).

For this type of problem, we examine the optimized transpose function (transposeOpt) and see if it can be subdivided into smaller, concurrent pieces. For example, by row (transposeRow), or the number of available CPUs (transposeCPU).

$ go test goroutine_test.go -bench=. -benchmem
BenchmarkTranspose-4       37   31848320 ns/op   63354443 B/op   15121 allocs/op
BenchmarkTransposeOpt-4   202    5921065 ns/op   16616065 B/op       2 allocs/op
BenchmarkTransposeRow-4   229    5307156 ns/op   16616159 B/op       3 allocs/op
BenchmarkTransposeCPU-4   360    3347992 ns/op   16616083 B/op       3 allocs/op
$

A row is still a small task. Twice the number of CPUs amortizes the goroutine overhead over a number of rows.  By any measure -- CPU, memory, allocations -- transposeCPU is considerably more efficient than the original transpose for a 1920 x 1080 matrix.

func NewMatrix(d2, d1 int) [][]int {
    a := make([]int, d2*d1)
    m := make([][]int, d2)
    lo, hi := 0, d1
    for i := range m {
        m[i] = a[lo:hi:hi]
        lo, hi = hi, hi+d1
    }
    return m
}

var numCPU = runtime.NumCPU()

func transposeCPU(a [][]int) [][]int {
    b := NewMatrix(len(a[0]), len(a))
    var wg sync.WaitGroup
    n := 2 * numCPU
    stride := (len(b) + n - 1) / n
    for lo := 0; lo < len(b); lo += stride {
        hi := lo + stride
        if hi > len(b) {
            hi = len(b)
        }
        wg.Add(1)
        go func(b [][]int) {
            defer wg.Done()
            for i := 0; i < len(b); i++ {
                c := b[i]
                for j := 0; j < len(c); j++ {
                    c[j] = a[j][i]
                }
            }
        }(b[lo:hi])
    }
    wg.Wait()
    return b
}

However, for a amall, 4 x 4 matrix, the goroutine overhead outweighs any gains.

BenchmarkTranspose-4      2570755    463 ns/op   320 B/op   13 allocs/op
BenchmarkTransposeOpt-4   8241715    145 ns/op   224 B/op    2 allocs/op
BenchmarkTransposeRow-4    908217   1318 ns/op   240 B/op    3 allocs/op
BenchmarkTransposeCPU-4    881936   1330 ns/op   240 B/op    3 allocs/op

As always, when we are exploiting concurrency, we use the Go race detector to check for data races. The overhead to check for data races is considerable. Therefore, we discard any benchmark results.

$ go test goroutine_test.go -bench=. -benchmem -race

By design, there are no data races.

goroutine_test.go:

package main

import (
    "runtime"
    "sync"
    "testing"
)

func transpose(a [][]int) [][]int {
    newArr := make([][]int, len(a))
    for i := 0; i < len(a); i++ {
        for j := 0; j < len(a[0]); j++ {
            newArr[j] = append(newArr[j], a[i][j])
        }
    }
    return newArr
}

func BenchmarkTranspose(b *testing.B) {
    for N := 0; N < b.N; N++ {
        _ = transpose(a)
    }
}

func NewMatrix(d2, d1 int) [][]int {
    a := make([]int, d2*d1)
    m := make([][]int, d2)
    lo, hi := 0, d1
    for i := range m {
        m[i] = a[lo:hi:hi]
        lo, hi = hi, hi+d1
    }
    return m
}

func transposeOpt(a [][]int) [][]int {
    b := NewMatrix(len(a[0]), len(a))
    for i := 0; i < len(b); i++ {
        c := b[i]
        for j := 0; j < len(c); j++ {
            c[j] = a[j][i]
        }
    }
    return b
}

func BenchmarkTransposeOpt(b *testing.B) {
    for N := 0; N < b.N; N++ {
        _ = transposeOpt(a)
    }
}

func transposeRow(a [][]int) [][]int {
    b := NewMatrix(len(a[0]), len(a))
    var wg sync.WaitGroup
    for i := 0; i < len(b); i++ {
        wg.Add(1)
        c := b[i]
        go func(c []int, i int) {
            defer wg.Done()
            for j := 0; j < len(c); j++ {
                c[j] = a[j][i]
            }
        }(c, i)
    }
    wg.Wait()
    return b
}

func BenchmarkTransposeRow(b *testing.B) {
    for N := 0; N < b.N; N++ {
        _ = transposeRow(a)
    }
}

var numCPU = runtime.NumCPU()

func transposeCPU(a [][]int) [][]int {
    b := NewMatrix(len(a[0]), len(a))
    var wg sync.WaitGroup
    n := 2 * numCPU
    stride := (len(b) + n - 1) / n
    for lo := 0; lo < len(b); lo += stride {
        hi := lo + stride
        if hi > len(b) {
            hi = len(b)
        }
        wg.Add(1)
        go func(b [][]int) {
            defer wg.Done()
            for i := 0; i < len(b); i++ {
                c := b[i]
                for j := 0; j < len(c); j++ {
                    c[j] = a[j][i]
                }
            }
        }(b[lo:hi])
    }
    wg.Wait()
    return b
}

func BenchmarkTransposeCPU(b *testing.B) {
    b.ResetTimer()
    for N := 0; N < b.N; N++ {
        _ = transposeCPU(a)
    }
}

var a = func() [][]int {
    b := NewMatrix(1920, 1080)
    for i := range b {
        for j := range b[0] {
            b[i][j] = i<<16 + j
        }
    }
    return b
}()

You might want to look at gonum, the Go numeric module. It's open source.

For matrices:

  package mat

import "gonum.org/v1/gonum/mat"

  Package mat provides implementations of float64 and complex128 matrix
  structures and linear algebra operations on them.