texts:
What I wanted to achieve is tableView with clickable cells, anytime somebody click a certain cell, another cell with picker, UITextField etc appears below, it's like a dropdown menu.

When browsing Stack Overflow, I saw many people suggest using tableView methods such insertRowsAtIndexPaths and deleteRowsAtIndexPaths.

That's fine, but afterwards I found out it requires huge amount of code to make it work (keep track of indexes in data source, add extra element to data source, again playing with changing indexes when deque more cells etc)

I end up with terribly ugly code (it's before refactoring though, sure one can make it better)

   func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

    if (indexPath.row == 1 || indexPath.row == 2 || indexPath.row == 3)
    {
        if self.menuOpen == false {

            self.tableView.beginUpdates()
            let tempIndexPath:NSIndexPath = NSIndexPath(forRow: indexPath.row + 1, inSection: 0)
            self.tableView.insertRowsAtIndexPaths([tempIndexPath], withRowAnimation: .Bottom)

            tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .None)

            data.append(["", ""])
            self.menuOpen = true
            self.menuOpenIndex = indexPath.row + 1
            self.tableView.endUpdates()

            let selection1IndexPath:NSIndexPath = NSIndexPath(forRow: 6, inSection: 0)
            let selection2IndexPath:NSIndexPath = NSIndexPath(forRow: 7, inSection: 0)
            let cell1 = self.tableView.cellForRowAtIndexPath(selection1IndexPath)
            let cell2 = self.tableView.cellForRowAtIndexPath(selection2IndexPath)
            cell1?.userInteractionEnabled = false
            cell2?.userInteractionEnabled = false
            print(data)

        }

        else
        {
            let tempIndexPath:NSIndexPath = NSIndexPath(forRow: self.menuOpenIndex, inSection: 0)
            //bug fixing
            let tempIndexPathToRetainSeparator:NSIndexPath = NSIndexPath(forRow: self.menuOpenIndex-1, inSection: 0)
            self.tableView.beginUpdates()

            let lowerCell:PickerCellTableViewCell = self.tableView.cellForRowAtIndexPath(tempIndexPath) as! PickerCellTableViewCell
            data[tempIndexPath.row-2][1] = "\(lowerCell.valuesDataSource[tempIndexPath.row-2][lowerCell.picker.selectedRowInComponent(0)])"
            self.tableView.deleteRowsAtIndexPaths([tempIndexPath], withRowAnimation: .Top)

            tableView.reloadRowsAtIndexPaths([tempIndexPathToRetainSeparator], withRowAnimation: .None)

            self.data.popLast()
            self.menuOpen = false
            //            self.tableView.reloadData()
            self.tableView.endUpdates()
            let selection1IndexPath:NSIndexPath = NSIndexPath(forRow: 5, inSection: 0)
            let selection2IndexPath:NSIndexPath = NSIndexPath(forRow: 6, inSection: 0)
            let cell1 = self.tableView.cellForRowAtIndexPath(selection1IndexPath)
            let cell2 = self.tableView.cellForRowAtIndexPath(selection2IndexPath)
            cell1?.userInteractionEnabled = true
            cell2?.userInteractionEnabled = true
            print(data)

        }

    }

    if (indexPath.row == 5 || indexPath.row == 6)
    {
        self.selectedIndex = indexPath.row
        self.tableView.reloadData()
        print(selectedIndex)
    }

}

Also, I found another method to do that, however it's even more tricky for me
http://www.appcoda.com/expandable-table-view/

My question is:

What are your methods to build expandable tableView? Do you use some library/pod? Do you deal with coding everything the way I did? Or maybe there's easier, smarter and more concise way to do that?


texts:
I have a module (in file dialect.rb) defined as such:

require 'dialect/generators/elements'

module Dialect
  def self.included(caller)
    caller.extend Dialect::Generator::Element
  end

  def self.version
    "Dialect v#{Dialect::VERSION}"
  end
end

Then I have the file dialect/generators/elements.rb, which looks like this:

module Dialect
  module Generator
    module Element

      puts Dialect.version

    end
  end
end

If I run my app, I get:

/lib/dialect/generators/elements.rb:7:in `<module:Element>':
undefined method `version' for Dialect:Module (NoMethodError)

My question/problem is: I didn't understand why the Element module could not find the version method here.

How I call Dialect is like this:

require 'dialect'

class PageTest
  include Dialect
end

So you can see Dialect is mixed-in to an existing class. It's when this class is instantiated that I get the error above.

When I try a simple IRB session doing what appears to be this same logic, this all seems to work:

irb(main):001:0> module Dialect
irb(main):002:1>   def self.version
irb(main):003:2>     puts "Version number"
irb(main):004:2>   end
irb(main):005:1> end
=> nil
irb(main):006:0> module Dialect
irb(main):007:1>   module Generator
irb(main):008:2>     module Element
irb(main):009:3>       puts Dialect.version
irb(main):010:3>     end
irb(main):011:2>   end
irb(main):012:1> end
Version number

Here I get the "Version number" text back, which tells me (I think?) that Dialect::Generator::Element can call the method version on Dialect.

The issue ended up being corrected by simply moving my require statement to the end, like this:

module Dialect
  def self.included(caller)
    caller.extend Dialect::Generator::Element
  end

  def self.version
    "Dialect v#{Dialect::VERSION}"
  end
end

require 'dialect/generators/elements'

Having the require statement at the end solves the problem I was having.

The question then becomes: is this a good way to do this? I feel like making my logic depend on where the require statement goes seems like a bad idea.


texts:
The problem is instead of doing what is stated in the if statements, does the else line like the if statement is false. However, when printed the variables i am working with, seems i have managed to get the desired expressions. I can't see a problem with the code either so if you experienced coders can please help me. Btw there is probably better ways to do this but I am new to java so no harsh comments please. Thank you.

import java.util.Scanner;

public class Exercise13 {
    public static void main(String[] args) {
        Scanner read = new Scanner(System.in);

        System.out.println("Please enter a mathematical expression in the form '<operand> <operator> <operand>'.");

        String expression = read.nextLine();
        int spacePos1 = expression.indexOf(' ');
        int spacePos2 = expression.lastIndexOf(' ');

        String val1 = expression.substring(0, spacePos1);
        String val2 = expression.substring(spacePos2 + 1);
        String operator = expression.substring(spacePos1 + 1, spacePos2);

        int num1 = Integer.parseInt(val1);
        int num2 = Integer.parseInt(val2);

        if (operator == "+")
            System.out.println("The answer is " + (num1 + num2));
        else if (operator == "-")
            System.out.println("The answer is " + (num1 - num2));
        else if (operator == "*")
            System.out.println("The answer is " + (num1 * num2));
        else if (operator == "/" && num2 !=0)
            System.out.println("The answer is " + (num1 / num2));
        else System.out.println("The answer is " + (num1 % num2));

        System.out.println(num1);
        System.out.println(num2);
        System.out.println(operator);
    }
}


texts: Calculating how many Pomodori fit into a period of time

texts:
I've written some code to calculate how many Pomodori can fit into a period of time, including long and short breaks. I'm looking for alternative solutions because what I have at the moment doesn't feel right. I think I'm missing something.

A Pomodoro is an interval of time 25 minutes long and after each one there should be a short 5 minute break. But every 4x Pomodori should be followed by a long 15 minutes break. So we have the following:

╔═══════╦════════╦═════════════╗
║ Time  ║ Length ║ Activity    ║
╠═══════╬════════╬═════════════╣
║ 12:00 ║ 25:00  ║ Pomodoro    ║
║ 12:25 ║ 05:00  ║ Short Break ║
║ 12:30 ║ 25:00  ║ Pomodoro    ║
║ 12:55 ║ 05:00  ║ Short Break ║
║ 13:00 ║ 25:00  ║ Pomodoro    ║
║ 13:25 ║ 05:00  ║ Short Break ║
║ 13:30 ║ 25:00  ║ Pomodoro    ║
║ 13:55 ║ 15:00  ║ Long Break  ║
║ 14:10 ║ 25:00  ║ Pomodoro    ║
╚═══════╩════════╩═════════════╝

At the moment I use a loop to populate a list and then delete the last element if it's not a Pomodoro, as there's no point in ending the list of Pomodori with a break.

pomodori = []
iterations = 0
seconds = 3 * 60 * 60

while seconds > 0:
    # zero and even numbers are always Pomodori
    if iterations % 2 == 0 or iterations == 0:
        pomodori.append('pomodoro')
        seconds -= 25 * 60
    else:
        quotient, remainder = divmod(iterations+1, 4)

        # if the quotient is even and the remainder is zero, then we
        # are just after a 4x Pomodori and should add a long break
        if quotient % 2 == 0 and remainder == 0:
            pomodori.append('long-break')
            seconds -= 15 * 60
        # otherwise, we're at a short break
        else:
            pomodori.append('short-break')
            seconds -= 5 * 60

    iterations += 1

# remove breaks that are not followed by a Pomodoro
if pomodori[-1] != 'pomodoro':
    del pomodori[-1]

EDIT:

I've gone ahead with jonrsharpe's solution. The code is here for those interested.


texts: Getting the Twitter account from various input formats

texts:
I have an input for users to enter a Twitter account in any different way and I want to extract the user account.

For example:

twitters = [
    "www.twitter.com/twitteruser1",
    "@twitteruser2",
    "twitteruser3",
    "https://twitter.com/twitteruser4",
    "https://www.twitter.com/twitteruser5",
    "www.twitter.com/twitteruser6",
    "http://www.twitter.com/twitteruser7",
    "http://www.twitter.com/twitteruser8",
    "twitter.com/twitteruser9"
]

The script that I've written to extract the data is the following:

twitters.each do |twitter|
    # for the url
    twitter_user = twitter.match(/twitter.com\/([^\/.]*)$/)
    if twitter_user != nil
        puts twitter_user[1]
        next
    end

    # for @ beginning
    twitter_user = twitter.match(/^@([^\/.]*)$/)
    if twitter_user != nil
        puts twitter_user[1]
        next
    end

    # if we arrive, we haven't found any coincidence
    puts twitter

end

It actually works, outputting the following:

twitteruser1
twitteruser2
twitteruser3
twitteruser4
twitteruser5
twitteruser6
twitteruser7
twitteruser8
twitteruser9

But as I'm really newbie in Ruby I wanted to check for possible improvements.


texts: Syncing NTFS permissions with SMB share permissions

texts:
I recently wrote scripts to automate the setup of shares on a server using the New-SmbShare cmdlet.  I hadn't realised that this cmdlet doesn't automatically amend the underlying NTFS permissions to honour the SMB permissions.  This script is a generic one which can be run after the SMB permissions are defined to ensure the NTFS rights support the SMB ones.

NB: Since NTFS rights may need to be more permissive than SMB ones, this operation is solely additive; i.e. there is no logic to remove existing rights or to set access to deny.

function Grant-NtfsSmbSharePermissions {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true, ValueFromPipeline = $true)]
        [string]$ShareName
        ,
        [Parameter(Mandatory = $false)]
        [System.Security.AccessControl.InheritanceFlags]$inheritanceFlags = [System.Security.AccessControl.InheritanceFlags]::ContainerInherit -bor [System.Security.AccessControl.InheritanceFlags]::ObjectInherit
        ,
        [Parameter(Mandatory = $false)]
        [System.Security.AccessControl.PropagationFlags]$propagationFlags = [System.Security.AccessControl.PropagationFlags]::None #all child folders should already know to inherit / if any have custom permissions we don't want to impact them
    )
    process {
        $Path = (Get-SmbShare -Name $ShareName -ErrorAction Stop).Path
        $NtfsAcl = Get-Acl $Path -ErrorAction Stop

        $type = [System.Security.AccessControl.AccessControlType]::Allow #we filter for allowed access since don't necessarily want deny on an smb to cause deny on ntfs / this is safest

        #provide a simple mapping from the SMB permissions to the related NTFS ones
        #https://www.codeproject.com/KB/dotnet/871338/FileSystemRights_Table2.png
        $fsr = (New-Object -TypeName PSObject -Property @{
            Full = [System.Security.AccessControl.FileSystemRights]::FullControl
            Change = [System.Security.AccessControl.FileSystemRights]::Modify
            Modify = [System.Security.AccessControl.FileSystemRights]::Modify #in some documentation the AccessRight is listed as Modify rather than Change; testing suggests that's a typo, but this caters for that scenario just in case
            Read = [System.Security.AccessControl.FileSystemRights]::Read
        })

        Get-SmbShareAccess -Name $ShareName -ErrorAction Stop | Where-Object {$_.AccessControlType -eq $type} | ForEach-Object {
            #https://msdn.microsoft.com/en-us/library/sfe70whw(v=vs.110).aspx
            $current = $_
            $fileSystemRights = $fsr."$($current.AccessRight)"
            Write-Verbose "Assiging $($fileSystemRights.ToString()) to $($current.AccountName)"
            $fsar = New-Object -TypeName 'System.Security.AccessControl.FileSystemAccessRule' -ArgumentList @(
                $current.AccountName
                ,$fileSystemRights
                ,$inheritanceFlags
                ,$propagationFlags
                ,$_.AccessControlType
            )
            $NtfsAcl.SetAccessRule($fsar) #NB: this process is additive; i.e. we don't remove any existing permissions which may have been set
        }
        Set-Acl -Path $Path -AclObject $NtfsAcl -ErrorAction Stop
    }
}

I'm not that knowledgable about ACL / permissions, so thought it best to share in case I've left any potholes unfilled.


texts: Getting device type from user agent in Python - is explicit better than implicit?

texts:
I'm debating with my colleagues which code is better:
user_agent is a class instance. The class itself comes from a third-party library so we don't have any control over it.

1.

def _get_ua_device_type(user_agent):
    property_to_type = {'is_mobile': 'mobile', 'is_tablet': 'tablet', 'is_pc': 'pc', 'is_bot': 'bot'}
    for prop, type in property_to_type.items():
        if get_attr(user_agent, prop) is True:
            return type
    return 'unknown'

2.

def _get_ua_device_type(user_agent):
    for type in ('mobile', 'tablet', 'pc', 'bot'):
        if get_attr(user_agent, f'is_{type}') is True:
            return type
    return 'unknown'

3.

def _get_ua_device_type(user_agent):
    if user_agent.is_mobile:
        return 'mobile'
    if user_agent.is_tablet:
        return 'tablet'
    if user_agent.is_pc:
        return 'pc'
    if user_agent.is_bot:
        return 'bot'
    return 'unknown'

Things we discussed:

Static code is easier to understand than dynamic.
Static code is easier to test.
Dynamic code is declarative and more idiomatic than metameric ifs.
Dynamic code will be as hard/easy to understand regardless of the number of choices.
It's hard to anticipate the number of choices up-front so why start with a more complex dynamic form?
Assuming that predicate names are derived from type names is bad.
Where is the line when code is spaghetti-like and should be rewritten in a more dynamic way?
What about Zen of Python (“Explicit is better than implicit.“, “Flat is better than nested.“, “Readability counts.”, “Simple is better than complex.”)

Do you have your own thoughts/suggestions?


texts:
I've written a plugin that takes a generic approach to creating sticky headers and would like to have the code reviewed.  Is this acceptable JavaScript?

Demo Page

It's my first plugin however and I'd like feedback about how to make it more user friendly and more readable before releasing it and putting it up on GitHub.

The header becomes stuck to the top of the page until it encounters the bottom of it's container, upon which it gets stuck to the bottom of the container and floats off the screen.

I had to create a placeholder to take the header's original place once it leaves the document flow and also apply fixed CSS settings to the header to keep it's appearance the same when it leaves the flow.

(function ($) {
$.fn.stickySectionHeaders = function (options) {

    var settings = $.extend({
        stickyClass: 'header',
        padding: 0
    }, options);

    return $(this).each(function () {

        var container = $(this);
        var header = $('.' + settings.stickyClass, container);

        var originalCss = {
            position: header.css('position'),
            top: header.css('top'),
            width: header.css('width')
        };

        var placeholder = undefined;
        var originalWidth = header.outerWidth();

        $(window).scroll(function () {
            var containerTop = container.offset().top;
            var headerOrigin = header.offset().top;
            var headerHeight = header.outerHeight();
            var containerHeight = container.outerHeight();
            var containerTop = container.offset().top;
            var containerSize = container.outerHeight();
            var pageOffset = $(window).scrollTop() + settings.padding;
            var containerBottom = containerHeight + containerTop;

            if (pageOffset < containerTop && placeholder != undefined) {
                if (placeholder != undefined) {
                    placeholder.remove();
                    placeholder = undefined;
                    header.css(originalCss);
                }
            }
            else if (pageOffset > containerTop && pageOffset < (containerBottom - headerHeight)) {
                if (placeholder == undefined) {
                    placeholder = $('<div/>')
                    .css('height', header.outerHeight() + 'px')
                    .css('width', header.width() + 'px');
                    header.before(placeholder);
                    header.css('position', 'fixed');
                    header.css('width', originalWidth + 'px');
                }
                header.css('top', settings.padding + 'px');
            }
            else if (pageOffset > (containerBottom - headerHeight)) {
                header.css('top', (containerBottom - headerHeight) - pageOffset + settings.padding + 'px');
            }
        });
    });
}
})(jQuery);


texts:
I've written a simple Diceware passphrase generator based on this Stack Overflow question and the top answer.

Briefly, in the Diceware method, a die is rolled 5 times for each word in the passphrase and the results matched to the corresponding word in the word list which is of the form:

16226   cask
16231   casket
16232   cast
16233   caste
16234   cat
16235   catch

I'm still very much a Python and programming beginner and appreciate any feedback, but my main concerns are:

Is the method I use to generate keys biased?
Is my handling of command line arguments correct or could it be done better?
Is the way I've broken my code down into individual functions reasonable or should certain functions be combined or broken apart?
Are there any other glaring weaknesses?

import os
import sys

WORDS = "diceware_wordlist.txt"

def exists_arg():
    """Checks if argv input was given."""
    if len(sys.argv) == 1:
        return False
    else:
        return True

def test_arg(arg):
    """Checks if input is of the required form and returns
    various failure cases.
    """
    try:
        arg = int(arg)
    except ValueError:
        return 'Please enter an integer.'
    if arg < 5:
        return 'Length must be >= 5.'
    elif arg > 10:
        return 'Length must be <= 10'
    else:
        return 0, arg

def load_dict():
    """Returns a dictionary of the number to word mappings
    in the Diceware words file.
    """
    word_dict = {}
    with open(WORDS, 'r', 0) as in_file:
        for line in in_file:
            tmp = line.split()
            key = tmp[0]
            value = tmp[1]
            word_dict[key] = value
    return word_dict

def generate_key():
    """Takes 6 bytes one at a time from the OS random device,
    converts them to integers, adds them together, and takes
    the modulo 6 value as a piece of a 5 digit key.

    Returns a key for a value in the Diceware dictionary.
    """
    key = ''
    for i in range(5):
        digit = 0
        for j in range(6):
            digit += ord(os.urandom(1))
        key += str(digit%6 + 1)
    return key

def generate_passphrase(length):
    """Returns a randomly chosen passphrase based on desired length."""
    word_dict = load_dict()
    passphrase = ''
    for i in range(1, length + 1):
        key = generate_key()
        passphrase += word_dict[key] + ' '
    return passphrase

def main():
    flag = True
    while True:
        if flag and exists_arg():
            arg = sys.argv[1]
            flag = False
        else:
            arg = raw_input('Length of desired passphrase: ')
        check = test_arg(arg)
        if check[0] == 0:
            print generate_passphrase(check[1])
            return
        else:
            print check

if __name__ == '__main__':
    main()


texts:
Two code files below : the actual logic & the test logic.

Core Logic

package stringBuilder;

public class NoksStringBuilder {

    //initial capacity
    private static final int INITIAL_SIZE = 3;

    String[] stringList = new String[INITIAL_SIZE];

    //number of strings in the builder currently
    int size = 0;

    //total number of chars in the builder , sum total of length of each string
    int characterCount = 0;

    public void add(String s){
        if(size < stringList.length){
            stringList[size++] = s;
            characterCount += s.length();
        }
        else{
            String[] temp = new String[stringList.length*2];

            for(int i =0 ; i< stringList.length; i++){
                temp[i] = stringList[i];
            }

            stringList = temp;
            add(s);
        }
    }

    public String toString(){
        char[] output = new char[characterCount];
        int outputIndex = 0;

        for(int i = 0; i < size; i++){
            for(int j = 0; j < stringList[i].length(); j++){
                output[outputIndex++] = stringList[i].charAt(j);
            }
        }

        return new String(output);

    }

}

Test Class

package stringBuilder;

import java.util.Scanner;

public class Test {

    public static void main(String[] args){
        NoksStringBuilder stringBuilder = new NoksStringBuilder();

        Scanner inputScanner = new Scanner(System.in);
        int i = 0;

        while(i != 3){

            printMenu();
            i = Integer.parseInt(inputScanner.nextLine());

            if(i == 1){
                System.out.println("Enter string");
                stringBuilder.add(inputScanner.nextLine());
            }
            else if( i == 2){
                System.out.println(stringBuilder.toString());
            }

        }

    }

    private static void printMenu() {
        System.out.println("StringBuilder Options :");
        System.out.println("1.Add");
        System.out.println("2.ToString");
        System.out.println("3.Quit");
    }

}


texts: Optimize jquery plugin "on" method extension

texts:
I would like feedback on how to optimize this jQuery plugin used for triggering change event on any DOM element.
This plugin doesn't use a timer to check for DOM changes but instead extends some jQuery native functions.
I'm mostly concerned by the .on() method extension because I'm sure there is better way of doing this.

jsFiddle to test

;(function ($) {
    var fctsToObserve = {
        append: [$.fn.append, 'self'],
        prepend: [$.fn.prepend, 'self'],
        remove: [$.fn.remove, 'parent'],
        before: [$.fn.before, 'parent'],
        after: [$.fn.after, 'parent']
    }, fctsObserveKeys = '';
    $.each(fctsToObserve, function (key, element) {
        fctsObserveKeys += "hasChanged." + key + " ";
    });
    var oOn = $.fn.on;
    $.fn.on = function () {
        if (arguments[0].indexOf('hasChanged') != -1) arguments[0] += " " + fctsObserveKeys;
        return oOn.apply(this, arguments);
    };
    $.fn.hasChanged = function (types, data, fn) {
        return this.on(fctsObserveKeys, types, null, data, fn);
    };
    $.extend($, {
        observeMethods: function (namespace) {
            var namespace = namespace ? "." + namespace : "";
            var _len = $.fn.length;
            delete $.fn.length;
            $.each(fctsToObserve, function (key) {
                var _pre = this;
                $.fn[key] = function () {
                    var target = _pre[1] === 'self' ? this : this.parent(),
                        ret = _pre[0].apply(this, arguments);
                    target.trigger("hasChanged." + key + namespace, arguments);
                    return ret;
                };
            });
            $.fn.length = _len;
        }
    });
    $.observeMethods()
})(jQuery);


texts:
I have implemented a method which takes 2 numbers and returns the Greatest Common Divisor, using the Euclidean algorithm.
The Euclidean algorithm goes like this:
If we take the numbers 585 and 442:

585 / 442 = 1 (remainder 143)
442 / 143 = 3 (remainder 13)
143 / 13 = 11 (remainder 0)

The process stops here and GCD = 13.
Is there any way I can make this implementation better, considering time, resources and refactoring?
using System;

class Program
{
    static void Main()
    {
        Console.WriteLine("Input first number: ");
        int x = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine("Input second number: ");
        int y = Convert.ToInt32(Console.ReadLine());

        Console.WriteLine(GetGCD(x, y));

        Console.ReadKey();
    }

    static int GetGCD(int x, int y)
    {
        while (Math.Max(x, y) % Math.Min(x, y) != 0)
        {
            int tmp = Math.Max(x, y) % Math.Min(x, y);
            if (x < y) y = tmp;
            else x = tmp;
        }

        return Math.Min(x, y);
    }
}


texts: Test whether or not a 4x4 matrix is a magic square

texts:
Here is what I have. I have it outputting most of the sums just so I can check there values. I think the problem is with the value of the elements in the array storing the column sums. I would greatly appreciate any feedback.

#include <iostream>
#include <cmath>
using namespace std;

void fillMatrix(int matrix[][4],const int SIZE);
int rowSum(int matrix[][4],const int SIZE,int row[]);
int columnSum(int matrix[][4], const int SIZE, int column[]);
bool isMagic(int matrix[][4], const int SIZE,int row[],int column[]);

int main()
{
const int SIZE=4;
int matrix[SIZE][SIZE];
int row[4],column[4];//arrays to be filled with row and column sums.
char response=0;

cout<<"This program determines whether or not a 4x4 square matrix is a magic square.\n";
do
{
    fillMatrix(matrix,SIZE);
    rowSum(matrix,SIZE,row);
    columnSum(matrix,SIZE,row);

    if(isMagic(matrix,SIZE,row,column))
        cout<<"This is a magic square.\n\n";
    else {
        cout<<"This is not a magic square.\n\n";
    }
    cout<<"To end this program, enter q. To check another matrix, enter any other letter.\n";
    cin>>response;
}while(response!='q'&&response!='Q');

return 0;
}

void fillMatrix(int matrix[][4],const int SIZE)
{
for(int i=0;i<4;i++)
{
    cout<<"Enter four values for row "<<i+1<<".\n";
    for(int j=0;j<4;j++)
    {
        cin>>matrix[i][j];
    }
}
}

int rowSum(int matrix[][4],const int SIZE,int row[4])
{
int i=0;
int rowsum=0;
for(i=0;i<4;i++)
{
    rowsum=0;
    for(int j=0;j<4;j++)
    {
        rowsum+=matrix[i][j];
    }
   row[i]=rowsum;
    cout<<row[i]<<endl;
}
return row[i];

}
int columnSum(int matrix[][4], const int SIZE, int column[4])
{
int j=0;
int columnsum=0;
for(j=0;j<4;j++)
{
    columnsum=0;
    for(int i=0;i<4;i++)
    {
        columnsum+=matrix[i][j];
    }
    column[j]=columnsum;
    cout<<column[j]<<endl;
}
return column[j];
}

bool isMagic(int matrix[][4], const int SIZE,int row[4],int column[4])
{
int rightdiagonalsum=0, leftdiagonalsum=0, check;

for(int i=0;i<4;i++)
{
    rightdiagonalsum+=matrix[i][i];
}
cout<<rightdiagonalsum<<endl;
for(int i=0;i<4;i++)
{
    leftdiagonalsum+=matrix[i][3-i];
}
cout<<leftdiagonalsum<<endl;
for(int i=1;i<4;i++)
{
    if (row[i]==row[i-1])
    {
        check=row[i];
    }
    else {
        return false;
    }
}
for(int j=0;j<4;j++)
{
    if (column[j]!=check)
    {
        cout<<column[j]<<"*****";//For some reason, the value of column[j] is 0.
        return false;
    }
}

if (rightdiagonalsum!=check||leftdiagonalsum!=check)
{
    return false;
}

return true;
}


texts:
I'm writing a static class to log my application errors into a text file. I am planning on using this as a library on any application I intend to develop in the future. Please let me know how I can improve this more and what could be changed so it would perform better.

public static class Logger
{
    public static void Log(Exception ex)
    {
        StreamWriter sw = null;
        try
        {
            sw = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "\\Log.txt", true);
            sw.WriteLine(
                DateTime.Now.ToString() + " : " + "\r\nSource " + ex.Source.ToString().Trim() +
                "\r\nMessage : " + ex.Message.ToString().Trim() +
                "\r\nInner Exceptions: " + Convert.ToString(ex.InnerException) +
                "\r\nException thrown from: " + getExceptionGeneratedMethod(ex) +
                "\r\nLine Number: " + getExceptionGeneratedLineNumber(ex) +
                "\r\nStack Trace: " + ex.StackTrace.ToString() ;
            sw.Flush();
            sw.Close();
        }
        catch (Exception e)
        {
            sw = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "\\Log.txt", true);
            sw.WriteLine("Error Could not be logged!!");
            throw ex;
        }
    }

    /// <summary>Writes a log file in the root directory with a custom message.
    /// <param name="message">String that will be displayed as a message</param>
    /// </summary>
    public static void writeCustomErrorLog(string message)
    {
        StreamWriter sw = null;
        try
        {
            sw = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "\\PassiveLog.txt", true);
            sw.WriteLine(DateTime.Now.ToString() + " : " + "\n Custom Message: " + message);
            sw.Flush();
            sw.Close();
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    /// <summary>Writes a log file in the a directory  passed in as a location with a custom message and a custom file-name.
    /// <param name="message">String that will be displayed as a message</param>
    /// <param name="location">String value that accepts a location for the log file to be generated</param>
    /// <param name="fileName">String value that accepts a file-name for the log file to be generated</param>
    /// </summary>
    public static void writeCustomErrorLog(string location, string message,string fileName)
    {
        StreamWriter sw = null;
        try
        {
            sw = new StreamWriter(location + "\\"+fileName+".txt", true);
            sw.WriteLine(DateTime.Now.ToString() + " : " + "\n" + message);
            sw.Flush();
            sw.Close();
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    /// <summary>Returns the Mathod name the exception occured
    /// <param name="ex">The <c>exception</c> must be passed as a parameter</param>
    /// <returns>returns the method name where the exception occured as a <c>string</c></returns>
    /// </summary>
    public static string getExceptionGeneratedMethod(Exception ex)
    {
        var s = new StackTrace(ex);
        var thisasm = Assembly.GetExecutingAssembly();
        string methodname = s.GetFrames().Select(f => f.GetMethod()).First(m =>
        m.Module.Assembly == thisasm).Name.ToString();
        return methodname;
    }

    /// <summary>Returns the line number on which the exception occured
    /// <param name="ex">The <c>exception</c> must be passed as a parameter</param>
    /// <returns>returns the line number where the exception occured as a <c>integer</c> value</returns>
    /// </summary>
    public static int getExceptionGeneratedLineNumber(Exception ex)
    {
        var st = new StackTrace(ex, true);
        var frame = st.GetFrame(0);
        int line = frame.GetFileLineNumber();
        return line;
    }
}


texts: Simple memory pool using no extra memory

texts:
I've borrowed the idea from the internet and I would like to know if my implementation is all right and what could be improved.

It uses the free memory to store links to each node, so there's no extra memory being used.

memory_pool.h

#ifndef MEMORY_POOL_H
#define MEMORY_POOL_H

#include <stdlib.h>

#define MEMORY_POOL_SUCCESS 1
#define MEMORY_POOL_ERROR 0
#define MEMORY_POOL_MINIMUM_SIZE sizeof(void *)

typedef struct {
    void **head;
    void *memory;
} Memory_Pool;

//size must be greater than or equal to MEMORY_POOL_MINIMUM_SIZE
int mp_init(Memory_Pool *mp, size_t size, size_t slots);
void mp_destroy(Memory_Pool *mp);

void *mp_get(Memory_Pool *mp);
void mp_release(Memory_Pool *mp, void *mem);

#endif

memory_pool.c

#include "memory_pool.h"

int mp_init(Memory_Pool *mp, size_t size, size_t slots)
{
    //allocate memory
    if((mp->memory = malloc(size * slots)) == NULL)
        return MEMORY_POOL_ERROR;

    //initialize
    mp->head = NULL;

    //add every slot to the list
    char *end = (char *)mp->memory + size * slots;
    for(char *ite = mp->memory; ite < end; ite += size)
        mp_release(mp, ite);

    return MEMORY_POOL_SUCCESS;
}

void mp_destroy(Memory_Pool *mp)
{
    free(mp->memory);
}

void *mp_get(Memory_Pool *mp)
{
    if(mp->head == NULL)
        return NULL;

    //store first address
    void *temp = mp->head;

    //link one past it
    mp->head = *mp->head;

    //return the first address
    return temp;
}

void mp_release(Memory_Pool *mp, void *mem)
{
    //store first address
    void *temp = mp->head;

    //link new node
    mp->head = mem;

    //link to the list from new node
    *mp->head = temp;
}


texts: Database Design for representing category relationships

texts:
So I am new to Databases.Recently I was asked this question in an interview where they expected me to come with a schema for storing and retrieving categories for an E-commerce website in an RDBMS. Each category could have many sub-categories. But each sub-category could have just one parent category. So this is the idea that I gave them:
First I created the table like so:

create table category(category_id TEXT PRIMARY KEY,
category_name TEXT,parent_id TEXT);

Then I created an index on the parent_id, like so:

 Create index idx_category_table on category(parent_id);

Then I used the following queries to get the parent and child queries:

Select B.category_name as CategoryName from category A,
category B  where A.category_id='3' and
A.parent_id = B.category_id;

Select B.category_name as CategoryName from category A,
category B  where A.category_id='1' and A.category_id = B.parent_id;

I was rejected from the interview. However, I am curious to know how to better this.


texts: Serving static assets through wildcard rule

texts:
I wrote this as a way to deliver static portion of the app.  I'm wondering if there is a better way to write this, as I am new to Express.

The goal is to let a single-page app to handle routing as needed. There is an API layer of this app that is defined under the /api/ route namespace.

I wanted to note that all assets are served from /app folder and are not public. I can adjust that, but as of now, that's the folder structure. /app is a compilation destination. root folder contains server.js where the below code resides and contains app/ and src/ folders, as well as server/ folder that contains API related stuff.

var express = require('express');
var http = require('http');
var path = require('path');
var app = express();

require('./express/api')(app);

app.get("/css/*",function(req,res){
  res.sendfile('app'+req.path);
});
app.get("/js/*",function(req,res){
  res.sendfile('app'+req.path);
});
app.get("/img/*",function(req,res){
  res.sendfile('app'+req.path);
});
app.get("/pages/*",function(req,res){
  res.sendfile('app'+req.path);
});
app.get('*',function(req,res){
  res.sendfile('app/index.html');
});

app.listen(3000);
console.log('Listening on port 3000');


texts:
Based on this question I though I would pull together an iterator that iterated over a container of containers.

template<typename C>
class IteratorForContainerOfContainer
{
    public:
        using Container             = C;
        using ContainerContainer    = typename Container::value_type;
        using Contained             = typename ContainerContainer::value_type;

        using Level1Iter            = typename Container::iterator;
        using Level2Iter            = typename ContainerContainer::iterator;

        using iterator_category     = std::forward_iterator_tag;
        using value_type            = Contained;
        using difference_type       = std::size_t;
        using pointer               = value_type*;
        using reference             = value_type&;

        IteratorForContainerOfContainer(C& c)
            : outerLoop(std::begin(c))
            , outerEnd(std::end(c))
            , innerLoop(std::begin(*outerLoop))
            , innerEnd(std::end(*outerLoop))
        {
            nextValidPos();
        }
        IteratorForContainerOfContainer()
            : outerLoop()
            , outerEnd()
            , innerLoop()
            , innerEnd()
        {}

        IteratorForContainerOfContainer& operator++()
        {
            ++innerLoop;
            nextValidPos();
            return *this;
        }
        value_type& operator*()
        {
            return *innerLoop;
        }
        bool operator!=(IteratorForContainerOfContainer const& rhs) const
        {
            return outerLoop != rhs.outerLoop || innerLoop != rhs.innerLoop;
        }

        private:
            void nextValidPos()
            {
                while ((innerLoop == innerEnd) && (outerLoop != outerEnd)) {
                    ++outerLoop;
                    if (outerLoop != outerEnd) {
                        innerLoop = std::begin(*outerLoop);
                        innerEnd  = std::end(*outerLoop);
                    }
                }
                if (outerLoop == outerEnd) {
                    outerLoop   = Level1Iter();
                    outerEnd    = Level1Iter();
                    innerLoop   = Level2Iter();
                    innerEnd    = Level2Iter();
                }
            }
            Level1Iter          outerLoop;
            Level1Iter          outerEnd;
            Level2Iter          innerLoop;
            Level2Iter          innerEnd;
};

So an example of simple usage would be:

int main()
{
    using CC = std::vector<std::vector<int>>;
    using It = IteratorForContainerOfContainer<CC>;

    CC   data = {{1,2,3},{4,5,6},{7,8,9}};

     for(It loop(data);loop != It(); ++loop) {
        std::cout << *loop << " ";
    }
    std::cout << "\n";

}


texts:
I am no expert in RxJS as I am still learning my way around the new paradigm of Observable/Subject.

I was trying to implement a broadcast service (based on NgRadio) that allows a new subscriber to get the nth last value of events he was listening to and the next emitted values after subscription.

As I stumbled upon issues with ReplaySubject to ask for the last n values... I ended up implementing it as follows. I feel that the code is not that crisp and clean so I would appreciate any improvement from more experienced RxJS developers.

import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { Observable } from 'rxjs/Observable';
import { ReplaySubject } from 'rxjs/ReplaySubject';
import { Subject } from 'rxjs/Subject';
import * as _ from 'lodash';
export interface RadioEvent {
    key: string;
    data?: any;
}

export class RadioService {
    private separator = ':';
    private _eventBus = new Subject<RadioEvent>();
    private _eventCacheBus = new ReplaySubject<RadioEvent>();

    keyMatch(key, wildcard) {
        var w = '*';
        var ww = '**';
        var partMatch = function (wl, k) {
            var match = (wl === w) || (wl === k);
            return match;
        };
        var sep = this.separator;
        var kArr = key.split(sep);
        var wArr = wildcard.split(sep);
        var kLen = kArr.length;
        var wLen = wArr.length;
        var max = Math.max(kLen, wLen);
        for (var i = 0; i < max; i++) {
            var cK = kArr[i];
            var cW = wArr[i];
            // '**' match all gragments
            if (cW == ww && (typeof cK !== 'undefined')) {
                return true;
            }
            // test if fragments match
            if (!partMatch(cW, cK)) {
                return false;
            }
        }
        return true;
    };

    cast<T>(key: string, data?: any) {
        if (typeof key !== 'string' || !key.length) {
            throw 'Bad key. Please provide a string';
         }

        this._eventBus.next({ key: key, data: data });
        this._eventCacheBus.next({ key: key, data: data });
    };

    on<T>(key: string, count?: number) {
        var _this = this;
        var normalobs = this._eventBus
        .filter(function (event: RadioEvent) {
            return _this.keyMatch(event.key, key);
        }).map(function (event) {
            return event.data;
        });
        if (_.isNil(count)) {
            return normalobs;
        } else {
            let obs = this._eventCacheBus
            .filter(function (event: RadioEvent) {
                return _this.keyMatch(event.key, key);
            }).map(function (event) {
                return event.data;
            });
            let subject = new ReplaySubject<T>(count);
            obs.subscribe(value => {
                subject.next(value);
            })
            return Observable.merge(normalobs, subject).distinct();
        }
    }
}


texts:
#region GetBookListByPriority
private static List<BCBook> GetBookListByPriority(List<BCBook> listBcBook)
{
    List<BCBook> newList = new List<BCBook>();
    try
    {
        List<BCBook> listNonPriorityBcBooks = new List<BCBook>();
        List<BCBook> listPriorityBcBooks = new List<BCBook>();

        foreach (BCBook bcBook in listBcBook)
        {
            BookHistoryDto historyDto = new BookHistoryFacade().FindHistoryByBookIdByPriority(bcBook.id.ToString(CultureInfo.CurrentCulture));
            if (historyDto != null && historyDto.HistoryId > 0)
            {
                bcBook.Priority = historyDto.Priority;
                listPriorityBcBooks.Add(bcBook);
            }
            else
            {
                listNonPriorityBcBooks.Add(bcBook);
            }
        }
        int count = 0;
        int prio = 0;
        foreach (BCBook bcBook in listNonPriorityBcBooks)
        {
            for (int j = count + 1; j <= 5; j++)
            {
                List<BCBook> listBook = new List<BCBook>();
                listBook = ListBookPriority(listPriorityBcBooks, j, newList);
                count++;
                if (listBook.Count() > 0)
                {
                    prio++;
                }
                else
                {
                    break;
                }
                foreach (BCBook bc in listBook)
                {
                    newList.Add(bc);
                }
            }
            newList.Add(bcBook);
        }
    }
    catch (Exception ex)
    {
        ErrorLogger.WriteErrorToLog(ex);
    }

    return newList;
}
#endregion

#region ListBookPriority
private static List<BCBook> ListBookPriority(List<BCBook> list, int priority, List<BCBook> newList)
{

    List<BCBook> listBook = new List<BCBook>();
    try
    {
        foreach (BCBook vid in list)
        {
            if (!IsExists(newList, vid.id.ToString(CultureInfo.CurrentCulture)))
            {
                if (vid.Priority == priority)
                {
                    listBook.Add(vid);
                }
            }
        }
    }
    catch (Exception ex)
    {
        ErrorLogger.WriteErrorToLog(ex);
    }
    return listBook;
}
#endregion


texts: Combinatorial Geometry Algorithm (synthetic)

texts:
I created an algorithm to solve in synthetic geometry. This problem states that these points are a scalar (real) number. The goal is to first make the possible triangles from the line segments. Then sum up the points within the triangles. For this question, ordering does not matter within the triangle.
I would like to know if there are any improvements possible on the algorithm. For example, if there is a Las Vegas Algorithm for it.
Also, I would like to know if I should make classes or is this even less maintainable than using built-in data structures.

"""

Triangle sums module

module fn
make_triangles(the_lines: [(float, float)]) -> [(float, float, float)]
total_triangles(the_triangles: [(float, float, float)]) -> [float]
user_output(the_sums: [float]) -> None

"""

"""
Problem

Given:
    Our points are made of a single float
    These points are made into tuples within a list
Find:
    the triangles within the points
    The sum of the points on the triangle

Note: the triangles have no distinct ordering in the points
"""

def make_triangles(the_lines: [(float, float)]) -> [(float, float, float)]:
    """
    :param the_lines: the lines to make triangles from
    :return: the triangles
    time: O(len(the_lines) * len(the_lines)
    space: O(len(the_lines) * len(the_lines))
    """
    the_triangles: [(float, float, float)] = []
    for pair_a in the_lines:
        for pair_b in the_lines:
            if pair_a == pair_b:
                continue
            if pair_a[0] == pair_b[0]:
                the_triangles.append((pair_a[0], pair_a[1], pair_b[1]))
            elif pair_a[0] == pair_b[1]:
                the_triangles.append((pair_a[0], pair_a[1], pair_b[0]))
    return the_triangles

def total_triangles(the_triangles: [(float, float, float)]) -> [float]:
    """
    :param the_triangles: the triangles of points to add up
    :return: a list of the totals
    time: O(len(the_triangles))
    space: O(len(the_triangles))
    """
    vec: [float] = [0.0] * len(the_triangles)
    for row in range(len(vec)):
        vec[row] = the_triangles[row][0] + the_triangles[row][1] + the_triangles[row][2]
    return vec

def user_output(the_sums: [float]) -> None:
    """
    :param the_sums: the calculated sums
    :return: None
    Output: std output
    """
    row = 0
    for number in the_sums:
        if row % 3 == 0:
            print('', end='\n')
        print(str(number), end=" ")
        row = row + 1
    print('\n', end='')

def main() -> None:
    """
    Entry point for script
    :return: None
    Input: None
    Output: std output
    """
    the_lines = [(0.0, 1.0), (1.0, 2.0), (2.0, 3.0)]
    the_triangles = make_triangles(the_lines)
    the_sums = total_triangles(the_triangles)
    user_output(the_sums)

if __name__ == "__main__":
    main()

 ```


texts:
I want to have an std::unordered_map which uses arrays as keys. As long as a type has an operator== and an std::hash it can be used as a key.

Here is my std::hash<std::array>

template<class T, size_t N>
struct std::hash<std::array<T, N>> {
    auto operator() (const std::array<T, N>& key) const {
        std::hash<T> hasher;
        size_t result = 0;
        for(size_t i = 0; i < N; ++i) {
            result = result * 31 + hasher(key[i]); // ??
        }
        return result;
    }
};

I copied the multiply by 31 from somewhere. An example here uses << and ^. I don't know which is better or how to apply the cppreference example to an array.

// cppreference example
template<> struct hash<S>
    {
        typedef S argument_type;
        typedef std::size_t result_type;
        result_type operator()(argument_type const& s) const
        {
            result_type const h1 ( std::hash<std::string>{}(s.first_name) );
            result_type const h2 ( std::hash<std::string>{}(s.last_name) );
            return h1 ^ (h2 << 1); // or use boost::hash_combine (see Discussion)
        }
    };

It seems to work. All of the code compiles and the return values for std::hash<key_type> seem ok to me.

using key_type = std::array<int, 2>;
using hash_type = std::hash<key_type>;
using map_type = std::unordered_map<key_type, int>;

map_type map; // compiles
hash_type hasher; // compiles

int main() {
    // test return values of std::hash<key_type>
    for(int y = -2; y < 3; ++y) {
        for(int x = -2; x < 3; ++x) {
            std::cout << hasher({x, y}) << " ";
        }
        std::cout << std::endl;
    }
}

The values printed from this code are:

18446744073709551552 18446744073709551583 18446744073709551614 29 60
18446744073709551553 18446744073709551584 18446744073709551615 30 61
18446744073709551554 18446744073709551585 0 31 62
18446744073709551555 18446744073709551586 1 32 63
18446744073709551556 18446744073709551587 2 33 64

I'm not sure what makes a good hash function for std::unordered_map, so I'd appreciate any feedback on how to make this hash function better.


texts:
Is there any other way to optimize the below code? I feel the below code is huge for the operations it performs.

{
    if ((currentElement == null ||
        (firstGridRow["Low"].ToString() == string.Empty ||
        firstGridRow["High"].ToString() == string.Empty ||
        firstGridRow["Mean"].ToString() == string.Empty ||
        firstGridRow["StdDev"].ToString() == string.Empty)))
    {
        continue;
    }

    double currentLow = Convert.ToDouble(firstGridRow["Low"]);
    double currentHigh = Convert.ToDouble(firstGridRow["High"]);
    double currentMean = Convert.ToDouble(firstGridRow["Mean"]);
    double currentStdDev = Convert.ToDouble(firstGridRow["StdDev"]);
    if (newRow.Length != 0)
    {
        AddColorList(currentElement, opid, currentLow, "Low", newRow, listCollectionLow);
        AddColorList(currentElement, opid, currentHigh, "High", newRow, listCollectionHigh);
        AddColorList(currentElement, opid, currentMean, "Mean", newRow, listCollectionMean);
        AddColorList(currentElement, opid, currentStdDev, "StdDev", newRow, listCollectionStdDev);
    }
}


texts:
I have a pretty unusual situation (please, don't ask why) where I need to compare objects which might be a string or double to string which might be a string or a double.ToString(). I've come up with something which I really don't like, so please feel free to criticize it and suggest a better solution.

public bool AreEqual(string stringValue, object objectValue)
{
    double numericValue;
    return (stringValue == (objectValue ?? string.Empty).ToString()) || // trying to compare values as strings
           (double.TryParse(stringValue, out numericValue) && (numericValue == objectValue as double?)); // otherwise - as double
}

To make it clear what I expect to get from that function:

[TestCase("a", "a", true)]
[TestCase("a", "b", false)]
[TestCase("10", 10, true)]
[TestCase("11", 10, false)]
[TestCase("11", "11.0", true)]
[TestCase("11", "11.5", false)]
public void ComparisionTest(string stringValue, object objectValue, bool areEqual)
{
     bool result = AreEqual(stringValue, objectValue);
     Assert.That(result == areEqual)
}


texts: Checking whether number is in given range

texts:
Introduction

I want to check whether number is in given range.
Function takes:

long number that should be checked
2 longs threshold values
byte range mode

Range mode is represented as number of type byte that can be from 0 to 4

0 for 00 => exclusive check
3 for 11 => inclusive check
1 for 01 => maximum - inclusive, minimum - exclusive
2 for 10 => maximum - exclusive, minimum - inclusive

Code

Range check constant flags

public static final byte RANGE_EXCLUSIVE = 0; // 00
public static final byte RANGE_INCLUSIVE = 3; // 11
public static final byte RANGE_MAX_INCLUSIVE = 1; // 01
public static final byte RANGE_MIN_INCLUSIVE = 2; // 10

Function

public static boolean inRange(long value, long range_a, long range_b, byte checkMode) {
    if (range_a > range_b) {
        long tmp = range_a;
        range_a = range_b;
        range_b = tmp;
    }

    // If value is on the left edge - check if it is inclusive
    if (value == range_a && (checkMode & RANGE_MIN_INCLUSIVE) == 0) return false;
    // If value is on the right edge - check if it is inclusive
    if (value == range_b && (checkMode & RANGE_MAX_INCLUSIVE) == 0) return false;

    // If value is out of range - return false
    if (value < range_a) return false;
    if (value > range_b) return false;

    return true;
}

Question

What do you think about this code?

Should I throw exceptions if range_a is less than range_b?

Or I can return false because range_a is expected to be less or equal to range_b

My first(and current) variant was to swap their values so range_a is always minimum, and range_b is always maximum of them

About style

I'm using camelcase for methods and variables

Underscore is used to show that values are connected. and used together:

Example: pos_x, pos_y or range_a, range_b


texts:
Online challenge on Hacker Rank.

  Alice has a binary string, B, of length n. She thinks a binary
  string is beautiful if and only if it doesn't contain the substring
  010.

  In one step, Alice can change a 0 to 1 a  (or vice-versa). Count
  and print the minimum number of steps needed to make Alice see the
  string as beautiful.

  Input Format

  The first line contains an integer, n (the length of binary string
  B).  The second line contains a single binary string, B, of length
  n.

  Output Format

  Print the minimum number of steps needed to make the string beautiful.

public class Solution {
    private static int countChange(String text, String pattern) {
        int textLen = text.length();
        int patternLen = pattern.length();

        char[] chars = text.toCharArray();
        int count = 0;
        for (int i = 0; i <= textLen - patternLen; i++) {
          int j = 0;
          while (j < patternLen && chars[i+j] == pattern.charAt(j)) {
            j++;
          }
          if (j == patternLen) {
            count++;
            chars[i+2] = '1';
          }
        }
        return count;
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        String B = in.next();
        System.out.println(countChange(B, "010"));
    }
}


texts: URLify a given String - replace spaces with %20

texts:
I have written a code to replace all spaces in a String with %20.
Input: "Mr John Smith "
Output: "Mr%20John%20Smith"

My logic:
public class URLify {
    public static void main(String[] args) {
        String str = "Mr John Smith  ";
        str = str.stripTrailing();
        char[] ch = str.toCharArray();
        StringBuilder sb = new StringBuilder();
        for(char c : ch) {
            if(c != ' ')
                sb.append(c);
            else {
                sb.append("%20");
            }
        }
        System.out.println(sb.toString());
    }
}

The given solution:
static int MAX = 1000;
static char[] replaceSpaces(char str[]) {
    int space_count = 0, i = 0;
    for (i = 0; i < str.length; i++)
        if (str[i] == ' ')
            space_count++;
    while (str[i - 1] == ' ') {
        space_count--;
        i--;
    }
    int new_length = i + space_count * 2;
    if (new_length > MAX)
        return str;
    int index = new_length - 1;
    char[] old_str = str;
    str = new char[new_length];
    for (int j = i - 1; j >= 0; j--) {
        if (old_str[j] == ' ') {
            str[index] = '0';
            str[index - 1] = '2';
            str[index - 2] = '%';
            index = index - 3;
        }
        else {
            str[index] = old_str[j];
            index--;
        }
    }
    return str;
}

Both work correctly with a linear time complexity of () however, can someone please suggest which solution is a better one especially if asked in an interview? Thanks!


texts: Determining if an entity exists in a database via a stored procedure

texts:
Here is a short and simple Ajax method that returns "True" or "False" if an entity exists in a database via a stored procedure that returns just "Y" or "N" (the details of this entity and database are not relevant to my question though).

This is the first time I've used the C# using() statement, and was wondering if anyone would be kind enough to review this and give me feedback.

[WebMethod]
public string ValidateEntity(string EntityType, string EntityName)
{
    string connstr = (from c in Companys where c.Name.Equals(company, StringComparison.OrdinalIgnoreCase) select c.ConnectionString).FirstOrDefault();
    if (connstr == null) { return "False"; }
    using (SqlConnection conn = new SqlConnection(connstr))
    {
        using (SqlDataAdapter da = new SqlDataAdapter())
        {
            using (da.SelectCommand = new SqlCommand("ValidateEntity", conn))
            {
                da.SelectCommand.CommandType = CommandType.StoredProcedure;
                da.SelectCommand.Parameters.AddWithValue("@EntityType", EntityType);
                da.SelectCommand.Parameters.AddWithValue("@EntityName", EntityName);
                using(DataSet ds = new DataSet())
                {
                    da.Fill(ds, "result_name");
                    DataTable dt = ds.Tables["result_name"];
                    if ( dt.Rows.Count > 0){
                        if (dt.Rows[0]["Valid"].ToString()=="Y") { return "True"; }
                    }
                }
            }
        }
    }
    return "False";
}


texts:
After implementing most of the suggestions from the first question, This is the code I got:

from math import log

zero_to_nineteen = ("zero", "one", "two", "three", "four",
                    "five", "six", "seven", "eight", "nine",
                    "ten", "eleven", "twelve", "thirteen", "fourteen",
                    "fifteen", "sixteen", "seventeen", "eighteen", "nineteen")

tens = ("zero", "ten", "twenty", "thirty", "forty",
        "fifty", "sixty", "seventy", "eighty", "ninety")

# Powers of a thousand (US system of naming)
suffixes = ("zero", "thousand", "million", "billion", "trillion",
            "quadrillion", "quintillion", "sextillion", "septillion",
            "octillion", "nonillion", "decillion", "undecillion",
            "duodecillion", "tredecillion", "quattuordecillion",
            "quinquadecillion", "sedecillion", "septendecillion",
            "octodecillion", "novendecillion", "vigintillion",
            "unvigintillion", "duovigintillion", "tresvigintillion",
            "quattuorvigintillion", "quinquavigintillion", "sesvigintillion",
            "septemvigintillion", "octovigintillion", "novemvigintillion",
            "trigintillion", "untrigintillion", "duotrigintillion",
            "trestrigintilion", "quattuortrigintillion",
            "quinquatrigintillion", "sestrigintillion", "septentrigintillion",
            "octotrigintillion", "noventrigintillion", "quadragintillion")

def spell_out(number):
    """Returns a string representation of the number, in the US system"""
    try:
        number = int(number)
    except OverflowError:
        # This will be triggered with large float values such as 1e584
        return "infinity"

    if number < 0:
        return "negative " + spell_out(-1 * number)

    if number < 20:
        return zero_to_nineteen[number]

    if number < 100:
        tens_digit, ones_digit = divmod(number, 10)
        return _createNumber(tens[tens_digit], ones_digit, "-")

    if number < 1000:
        hundreds_digit, rest = divmod(number, 100)
        return _createNumber(spell_out(hundreds_digit) + " hundred", rest)

    suffix_index = int(log(number, 1000))

    if suffix_index < len(suffixes):
        suffix_value = 1000 ** suffix_index
        prefix, rest = divmod(number, suffix_value)
        prefix = spell_out(prefix) + " " + suffixes[suffix_index]
        return _createNumber(prefix, rest, ", ")

    return "infinity"

def _createNumber(prefix, suffix, seperator=" "):
    # Returns a number with given prefix and suffix (if needed)
    if not isinstance(prefix, str):
        prefix = spell_out(prefix)
    return prefix if suffix == 0 else prefix + seperator + spell_out(suffix)

I'd like to hear any comments about readability/performance/pythonicity and anything else you can think about that could use improving.


texts: Function to delete oldest items out of HTML5 localStorage. Can I make it more efficient?

texts:
In a current javascript project, I'm working with the browsers localStorage, and it will pretty consistently be full. To overcome this, I wrote a wrapper to surround the localStorage object that would keep track of when an object was added.

The hard(er) part, was coming up with the algorithm to make room for any new data. I was wondering if anyone could critique my method, and let me know if a better method exists.

DataStore.prototype.makeRoom = function() {
    var tmpData = {};
    for (var key in localStorage) {
        var expTime = JSON.parse(localStorage.getItem(key)).expirationTime;
        if (Object.size(tmpData) < 3) {
            tmpData[key] = expTime;
            continue;
        }
        for (var tmpKey in tmpData) {
            var tmpExp = JSON.parse(localStorage.getItem(tmpKey)).expirationTime;
            if (tmpExp > expTime) {
                delete tmpData[tmpKey];
                tmpData[key] = expTime;
                break;
            }
        }
    }
    for (var deleteKey in tmpData) {
        this.destroyItem(deleteKey);
    }
    return true;
};

And for reference, DataStore.destroyItem(), and DataStore.store() where the data is written:

DataStore.prototype.store = function(dataKey, data, minutesUntilExpiration, overWrite) {
    if (!overWrite && this.hasItem(dataKey))
        return false;
    var dataToSave = {
        data: data,
        expirationTime: (new Date().getTime() + (minutesUntilExpiration * 60 * 1000))
    };
    try {
        localStorage.setItem(dataKey, JSON.stringify(dataToSave));
    } catch (e) {
        this.makeRoom();
        this.store(dataKey,data,minutesUntilExpiration,overWrite);
    }
    return true;
};

DataStore.prototype.destroyItem = function(dataKey) {
    if (this.hasItem(dataKey)) {
        localStorage.removeItem(dataKey);
        return true;
    }
    return false;
};

Object.size = function(obj) {
    var size = 0, key;
    for (key in obj) {
        if (obj.hasOwnProperty(key)) size++;
    }
    return size;
};


texts: Header file for accessing components globally in library

texts:
In my project I have a header file which contains only functions which are put into a namespace, the purpose of these functions is to be used from another class of the framework I'm working on, or from client code.

Does this code follow best practices? How can I efficiently just keep such data?

#pragma once

#include <iomanip>
#include <sstream>
#include <chrono>
#include <ctime>

namespace lwlog::datetime
{
    std::string get_chrono(std::string format)
    {
        auto now = std::chrono::system_clock::now();
        auto in_time_t = std::chrono::system_clock::to_time_t(now);

        std::stringstream ss;
        ss << std::put_time(std::localtime(&in_time_t), format.c_str());
        return ss.str();
    }

    std::string get_time()                      { return get_chrono("%H:%M:%S"); }
    std::string get_date()                      { return get_chrono("%Y-%m-%d"); }
    std::string get_date_short()                { return get_chrono("%m/%d/%y"); }
    std::string get_second()                    { return get_chrono("%S"); }
    std::string get_minute()                    { return get_chrono("%M"); }
    std::string get_hour_24()                   { return get_chrono("%H"); }
    std::string get_hour_12()                   { return get_chrono("%I"); }
    std::string get_weekday()                   { return get_chrono("%A"); }
    std::string get_weekday_abbreviated()       { return get_chrono("%a"); }
    std::string get_day()                       { return get_chrono("%d"); }
    std::string get_month()                     { return get_chrono("%m"); }
    std::string get_month_name()                { return get_chrono("%B"); }
    std::string get_month_name_abbreviated()    { return get_chrono("%b"); }
    std::string get_year()                      { return get_chrono("%Y"); }
    std::string get_year_short()                { return get_chrono("%y"); }
}


texts:
Is there a way I could improve my code's readability, or have I finally won the war against sloppy coding?

Here's a game launcher I made for The Sims 3 to fix the awful performance caused by big cache files.

using System.Collections.Generic;
using System.Diagnostics;
using System.Windows.Forms;

namespace Sims_3___Anti_Cache
{
    public partial class Form1 : Form
    {
        Game Sims3;

        public Form1()
        {
            InitializeComponent();

            Sims3 = new Game();
            Sims3.cache = new List<string>() { "CASPartCache.package", "compositorCache.package", "scriptCache.package",
                                               "simCompositorCache.package", "socialCache.package" };

            Sims3.cache_path = "C:/Users/DarkShadow/Documents/Electronic Arts/The Sims 3/";
            Sims3.clear_cache();
            Sims3.path = "C:/Program Files (x86)/Electronic Arts/The Sims 3/Game/Bin/TS3.exe";

            isCleared.Enabled = true;
        }

        private void isCleared_Tick(object sender, System.EventArgs e)
        {
            if (Sims3.cache_cleared)
            {
                Process.Start(Sims3.path);
                Application.Exit();
            }
        }

    }
}


texts: JavaScript jQuery plugin options. Defaults, User Options, and immutable settings pattern?

texts:
I'm writing a jQuery plugin.

I'm allowing the user to pass options (optionally-- argument 2 to extend) but I also require some defaults (argument 1), and some things user is not allowed to modify (argument 3).

I follow the global override pattern recommended by most jQuery plugins.  But I'm running into something I've never seen discussed which is where you have defaults that need to be set in a specific scope (caption being set to self._tableName, for example).

This forces you to do an extend pretty much everywhere you need options + internal state.  It's not that terrible, but my code review sense is tingling.

Anything in the snippet is up for debate.  Leave your thoughts, please.

For context, how I'm doing options in the constructor

       this.options = $.extend(true, $.fn.myPlugin.Defaults, options);

And here is the argument object I'm creating to be passed to a plugin.  To reiterate, I'm forming this object much later when it's time to create the jqgrid.

       $.extend({ caption: self._tableName },
                self.options ? self.options.jqgrid : {},
                {
                    datatype: function (postdata) {
                        hubProxy.server.requestPage(postdata);
                    },
                    ColNames: ColNames,
                    colModel: ColModel,
                    pager: '#' + pager,
                    ondblClickRow: function (rowid) {
                        $(this).jqGrid('editGridRow', rowid, editTemplate);
                    }
                });


texts: Billboards InterviewStreet - Code Optimization

texts:
Heres the link to the original question . Billboards Link

I initially declared n*k array which led to a Out Of Memory Exception.

Then I resorted to using just 2 * k matrix and alternating between 0 and 1 during each iteration. Now the issue is time limit. As of now 8/10 cases are solved using this approach.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Billboards
{
class Program
{
    static void Main(string[] args)
    {
        long n, k;
        string line;
        string[] parts = new string[2];
        line = Console.ReadLine();
        parts = line.Split(new char[] { ' ' });
        n = long.Parse(parts[0]);
        k = long.Parse(parts[1]);
        long i, j;
        long[]  c = new long[n];
        for (i = 0; i < n; i++)
        {
            c[i] = long.Parse(Console.ReadLine());
        }
        long[][] dp = new long[2][];
        long max = 0;
        int var1, var2, temp;
        var1 = 0;
        var2 = 1;
        for(i=0;i<=1;i++){
            dp[i] = new long[k + 1];
        }

        for (i = 1; i <= n; i++)
        {
            dp[var2][0] = max;
    max = 0;
            for (j = 1; j <= k; j++)
            {
                dp[var2][j] = Math.Max(dp[var1][j - 1] + c[i-1], dp[var1][j]);
        if(dp[var2][j] > max)
        max = dp[var2][j];
            }
    temp = var1;
    var1 = var2;
    var2 = temp;
        }

        max = Max(dp[var1]);

        Console.WriteLine(max);
    }

    static long Max(long[] arr)
    {
        long max = 0;
        for (long i = 0; i < arr.Length; i++)
        {
            if (arr[i] > max)
            {
                max = arr[i];
            }
        }
        return max;
    }
}
}


texts: Extract lines under the specified heading

texts:
I wrote the following working code, which I just can't stomach:

var data = [
    { id: 0, isHeading: true, description: "A heading" },
    { id: 1, isHeading: false, description: "Blah 1" },
    { id: 2, isHeading: false, description: "Blah 2" },
    { id: 3, isHeading: true, description: "A heading" },
    { id: 4, isHeading: false, description: "Blah 3" },
    { id: 5, isHeading: false, description: "Blah 4" },
    { id: 7, isHeading: false, description: "Blah 5" },
    { id: 8, isHeading: false, description: "Blah 6" },
    { id: 9, isHeading: true, description: "A heading" },
    { id: 10, isHeading: false, description: "Blah 7" },
    { id: 11, isHeading: false, description: "Blah 8" },
    { id: 12, isHeading: false, description: "Blah 9" },
    { id: 13, isHeading: true, description: "A heading" },
    { id: 14, isHeading: false, description: "Blah 10" },
    { id: 15, isHeading: false, description: "Blah 11" },
    { id: 16, isHeading: true, description: "A heading" },
    { id: 17, isHeading: false, description: "Blah 12" },
    { id: 18, isHeading: false, description: "Blah 13" },
    { id: 19, isHeading: false, description: "Blah 14" }
  ]
  function getLines (headingId) {
    var r = []
    var inThere = false
    for (let line of data) {
      if (line.isHeading) {
        if(line.id === headingId) {
          inThere = true
          continue
        } else if (line.id !== headingId && inThere) {
          return r
        }
      }
      if (inThere) r.push(line)
    }
    return r
  }
  getLines(9)

Basically, it's taking a chunk of a list; it's a state automaton where the inThere state is set by a matching heading ID, and the routine is done when either there are no more items, or a new heading comes up.

Is there a much better way of writing this?


texts:
I want to improve the following peace of code as much as possible, both regarding to speed and other aspects I may not know about. Since I have learned C++ myself, there are probably many things to learn and to improve.

To point it out, I want to improve the code with just one core in mind. I know it can be trivially parallelized on a GPU for instance, but I want to get the most out of one core as possible.

void VoxelGrid::integrateDepth(const cv::Mat &depthImg, const Eigen::Matrix4d &camera){
for (int k = 0; k < resolution; ++k){
    for (int j = 0; j < resolution; ++j){
        for (int i = 0;i < resolution; ++i){
            vector3 xGlobal = _getGlobal(i, j, k);
            vector3 xLocal = getLocal(xGlobal, camera);

                if (xLocal.z > 0){
                vector2 pixel = getProjection(xLocal);

                if (pixel.y >= 0 && pixel.x >= 0 && pixel.y < depthImg.rows && pixel.x < depthImg.cols){
                        float z = depthImg.at<float>(pixel.y, pixel.x);
                    if (!isnan(z)){
                        float tDist = min(Delta, max(-Delta, xLocal.z - z));
                        float tWeight = getWeight(tDist);
                        Voxel *tmp = getVoxel(i, j, k);
                        tmp->distance = (tmp->distance*tmp->weight + tDist*tWeight) / (tmp->weight + tWeight);
                        tmp->weight += tWeight;
                    }
                }
            }
        }
    }
  }
}

With functions:

VoxelGrid::vector3 VoxelGrid::_getGlobal(int i, int j, int k){
    vector3 tmp = { start.x + i*step, start.y + j*step, start.z + k*step };
    return tmp;
}

and

VoxelGrid::vector3 VoxelGrid::getLocal(const vector3 &xGlobal, const Eigen::Matrix4d &camera){
    float x = camera(0, 0)*xGlobal.x + camera(0, 1)*xGlobal.y + camera(0, 2)*xGlobal.z + camera(0, 3);
    float y = camera(1, 0)*xGlobal.x + camera(1, 1)*xGlobal.y + camera(1, 2)*xGlobal.z + camera(1, 3);
    float z = camera(2, 0)*xGlobal.x + camera(2, 1)*xGlobal.y + camera(2, 2)*xGlobal.z + camera(2, 3);
    vector3 tmp = { x, y, z };
    return tmp;
}

getLocal is intentionally made to look similar to later CUDA code, where you cannot use the Eigen library in Visual Studio on CUDA, as far as I know.

The other functions used:

float VoxelGrid::getWeight(float d){
    if (d <= Epsilon){
        return 1;
    }
    if (d < Delta){
        return expf(-Sigma*sqr(d - Epsilon));
    }
    else {
        return 0;
    }
}

VoxelGrid::vector2 VoxelGrid::getProjection(const vector3 &p){
    float x = fx*p.x / p.z + cx;
    float y = fy *p.y / p.z + cy;
    vector2 tmp = { x, y };
    return tmp;
}

VoxelGrid::Voxel* VoxelGrid::getVoxel(int i, int j, int k){
    return &grid[i + j*resolution + k*resolution*resolution];
}

struct Voxel {
             float distance;
             float weight;
             float red;
             float green;
             float blue;
             float cweight;
         };

Now, I have written this with later CUDA code in mind so that I can easier debug it if it looks the same in C++. Otherwise it would be easier to use the Eigen library completely, but as it is, what can be made better?

Would it be possible to improve performance by using other data types for example? Are there better ways of writing the code with respect to security or just making it look better or more professional?

vector3 and vector2 are just structs with three and two floats respectively, so I guess they work exactly the same as float3 and float2, so it was a bit unnecessary to define structs which already exist.


texts: Iterating through list and calling method with different parameters for each item

texts:
I am iterating over a list of environments but calling the same method each time. The only difference is the parameters are changing depending on what environment it is. The result so far is similar to the code below, i know this is not great but cant find a better way to solve it. Any ideas?

       foreach (var environment in Environments)
        {
            if(environment == "environment1")
            {
                FillList("connectionstring1", query1);
            }
            else if (environment == "environment2")
            {
                FillList("connectionstring1", query2);
            }
            else if (environment == "environment3")
            {
                FillList("connectionstring2", query1);
            }
        }


texts:
I'm just starting out in MIPS (as is evident by the fact that I'm writing a FizzBuzz program), and my program runs fine and gives the desired output, but I feel like there is a way to do it without as many branches.

.data

    fstring:    .asciiz     "Fizz\n"
    bstring:    .asciiz     "Buzz\n"
    hstring:    .asciiz     "FizzBuzz\n"

.text

.globl main

main:
    li  $t0, 0

loop:
    bgt     $t0, 99, exit
    add     $t0, $t0, 1
    rem     $t1, $t0, 15
    rem     $t2, $t0, 3
    rem     $t3, $t0, 5
    beq     $t1, 0, fizzbuzz
    beq     $t2, 0, fizz
    beq     $t3, 0, buzz
    li      $v0, 1
    move    $a0, $t0
    syscall
    move    $t0, $a0
    li      $a0, 10
    li      $v0, 11
    syscall
    b       loop

fizzbuzz:
    la      $a0, hstring
    li      $v0, 4
    syscall
    b       loop

fizz:
    la      $a0, fstring
    li      $v0, 4
    syscall
    b       loop

buzz:
    la      $a0, bstring
    li      $v0, 4
    syscall
    b       loop

exit:
    li      $v0, 10
    syscall

Is there a way to sure up this program or is it relatively concise for what it's supposed to do?


texts:
This is a script I made for the ESP8266 that uses the Wi-Fi chip and creates a new Access Point every 5 seconds in order to display a message on WiFi lists on nearby devices that looks like this:

The code is:

#include <ESP8266WiFi.h>

const char* ssids[] = {"Never gonna give you up","Never gonna let you down","Never gonna run around","Never gonna make you cry","Never gonna say goodbye","Never gonna tell a lie"};
const char* pass = "pass_goes_here";
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  int currentssidno = 0;
  while (true)
  {
    const char* ssid = ssids[currentssidno];
    Serial.print("SSID: ");
    Serial.println(ssid);
    WiFi.softAP(ssid, pass);
    delay(5000);
    WiFi.softAPdisconnect(false);
    currentssidno = currentssidno + 1;
    if (currentssidno == 6) //please change this count if you change the amount of ssids
    {
      currentssidno = 0;
    }
  }
}

void loop() {
}

The code is also on GitHub.

How can I improve this code? This is my second or third project with Arduino and I pretty much made it in 15 minutes and looking at it now, some parts feels like dirty code (especially the part where I switch reset the SSID counter), how can I improve this?

Extra resources: Wi-Fi Library, ESP8266 Arduino Core


texts:
I want to get the query result that contains all entries from array and some data from the DB.
It's like the array is a DB table and by left join I connect the data that I need.

I've solved this task in a clumsy way and am asking for tips on how to rewrite this solution.
Here is my query:

        $subquery = 'Select \'' .
        implode('\' as id union Select \'', $var_array) . '\'';

        $query = "Select tmp.variable,
        fields.content is NULL as content FROM  ({$subquery}) tmp
        LEFT JOIN fields
        ON tmp.id= fields.id";


texts: Inizialize an Jarray wih n JObject that contain an progressive index

texts:
I need to inizialize an JArray with a JObject that contain a property areaNum that is an incremental integer.

Right now I wrote the below code, which works ok if I have a small number of JObjects, otherwise it takes too long.

I'm looking for a way to write the below code that take in consideration the performance at time side

i need to initialize an JArray with n JObject that contain the areaNum that is a incremental number

Function csvToWebSocketStringSuper3(lclrow As CsvRow) As String

Dim panelsArray As New JArray()
        Dim panel As New JObject

        For i As Integer = 1 To 5
            panel = New JObject(
                New JProperty("areaNum",            i),
                New JProperty("numbers",            New JArray({New JArray({}),New JArray({}),New JArray({})})),
                New JProperty("systems",            New JArray({""})),
                New JProperty("multiplier",         New JArray({""})),
                New JProperty("qp",                 false),
                New JProperty("series",             false),
                New JProperty("noseries",           false),
                New JProperty("twodigit",           false),
                New JProperty("onedigit",           false),
                New JProperty("void",               false))
            panelsArray.Add(panel)
        Next i
    Dim obj As JObject  = New JObject(
            New JProperty("playslipID",             2331),
            New JProperty("ticketID",               2100) ,
            New JProperty("participationMethod",    0),
            New JProperty("multidraws",             New JArray({formatStringToEmptyORIntegerReplace0(lclrow.getMultipleDraws)})),
            New JProperty("advancedraws",           New JArray({formatStringToEmptyORIntegerReplace0(lclrow.getDrawOffsets)})),
            New JProperty("proto",                  New JArray({formatStringToEmptyORIntegerReplace0(lclrow.getProductId)})),
            New JProperty("areas",                  panelsArray
            ))

        Return JsonConvert.SerializeObject(obj)


texts: Search and filter in MVC3 Razor using Linq

texts:
This code works fine, but I just don't like all the if else.  If I keep adding field to filter, it's going to get messy.

I am not using EF and cannot on this.

Controller code:

var books = bookRepository.GetDogs();
if (!String.IsNullOrEmpty(searchString))
{

    if (!String.IsNullOrWhiteSpace(searchString) && searchGender != String.Empty && searchHand != String.Empty)
    {
        books = books.Where(b => b.Name.ToUpper().Contains(searchString.ToUpper())
                                 && b.Gender == searchGender && b.Handedness == searchHand);
    }
    else if (!String.IsNullOrWhiteSpace(searchGender) && searchString == String.Empty && searchHand == String.Empty)
    {
        books = books.Where(b => b.Gender == searchGender);
    }
    else if (String.IsNullOrWhiteSpace(searchGender) && searchString != String.Empty && searchHand == String.Empty)
    {
        books = books.Where(b => b.Name.ToUpper().Contains(searchString.ToUpper()));
    }
}

return View(books);

My view:

<p>Find by Name : @Html.TextBox("searchString", ViewBag.CurrentFilter as string)

@Html.DropDownList("searchGender", new SelectList(ViewBag.BookNames), "-- Select All --")
@Html.DropDownList("searchHand", new SelectList(ViewBag.HandNames), "---Select All--")


texts:
I'm just starting with rails and testing, and not sure what's good way to dry code like this.

require 'rails_helper'

describe EventsController, type: :controller do
  let(:admin) { create(:user_admin) }
  let(:mod) { create(:user_moderator) }
  let(:user) { create(:user) }

  let(:link) { create(:link) }
  let(:event) { create(:event) }

  describe 'GET #new' do
    it 'allows admin user to perform action' do
      sign_in admin

      get :new, link: link.id

      expect(flash[:alert]).to_not match(/^You are not authorized to perform this action./)
    end

    it 'allows mod user to perform action' do
      sign_in mod

      get :new, link: link.id

      expect(flash[:alert]).to_not match(/^You are not authorized to perform this action./)
    end

    it 'does not allow regular user to perform action' do
      sign_in user

      get :new, link: link.id

      expect(flash[:alert]).to match(/^You are not authorized to perform this action./)
    end

    it 'does not allow guest to perform action' do
      get :new, link: link.id

      expect(flash[:alert]).to match(/^You are not authorized to perform this action./)
    end
  end

  describe 'POST #create' do
    it 'allows admin user to perform action' do
      sign_in admin

      post :create, event: attributes_for_event(event, link)

      expect(flash[:alert]).to_not match(/^You are not authorized to perform this action./)
    end

    it 'allows mod user to perform action' do
      sign_in mod

      post :create, event: attributes_for_event(event, link)

      expect(flash[:alert]).to_not match(/^You are not authorized to perform this action./)
    end

    it 'does not allow regular user to perform action' do
      sign_in user

      post :create, event: attributes_for_event(event, link)

      expect(flash[:alert]).to match(/^You are not authorized to perform this action./)
    end

    it 'does not allow guest to perform action' do
      post :create, event: attributes_for_event(event, link)

      expect(flash[:alert]).to match(/^You are not authorized to perform this action./)
    end
  end
end


texts:
For debugging purposes I am storing requests into files. This code is supposed to create a new file for each request.

Somehow it doesn't look very nice, can it be improved? Additionally it would be nice if it could be made atomic.

filenamePrefix := exeDir + "/debug/" + time.Now().Format("20060102150405")
var filename string

for i := 0 ; ; i++ {
    if (i > 100) {
        log.Print("Could not find free filename")
        return
    }

    filename = filenamePrefix + "-" + strconv.Itoa(i)
    _, err := os.Stat(filename);
        if os.IsNotExist(err) {
        break
    }
}

fd, err := os.Create(filename)
if err != nil {
    log.Print(err.Error())
    return
}
defer fd.Close()

io.Copy(fd, request.Body)


texts: Shortest path via two intermediate points

texts:
My code takes a long time for big graphs.

How can I make it faster?

I'm trying to calculate the shortest path for 3 path's using queue but for big input my program crashes.

I'm stuck here. Can someone help me?

def bfs(graph, start, end):
    queue = []
    queue.append([start])
    while queue:
        path = queue.pop(0)
        node = path[-1]
        if node == end:
            return len(path)
        for adjacent in graph.get(node, []):
            new_path = list(path)
            new_path.append(adjacent)
            queue.append(new_path)

def all_possiblities():
    possiblites = []
    for clinique in cliniques[0][1:]:
        for clinique2 in cliniques[1][1:]:
            path1 = bfs(sorted_connections, a, clinique)
            path2 = bfs(sorted_connections, clinique, clinique2)
            path3 = bfs(sorted_connections, clinique2, b)
            total_path = path1 + path2 + path3
            possiblites.append(total_path)
    return min(possiblites) - 2

if __name__ == '__main__':
    input_values = input().split()
    n, m = int(input_values[0]), int(input_values[1])
    a, b = int(input_values[2]), int(input_values[3])
    connections = [list(map(int, input().split())) for _ in range(m)]
    cliniques = [list(map(int, input().split())) for _ in range(m, m+2)]
    sorted_connections = {}
    for road in connections:
        city1, city2 = road
        sorted_connections.setdefault(city1, []).append(city2)
        sorted_connections.setdefault(city2, []).append(city1)
    print(all_possiblities())

Input:

10 12 4 6
0 1
1 2
2 7
7 6
6 9
9 8
8 4
4 3
3 0
5 1
5 4
5 6
2 0 2
2 8 9

Output:

8


texts: Sequentially remove members "repelled" by previous members

texts:
I was working on a project that need to remove extra data such that the remains are not "too close" to each other, and the algorithm should be as generalize as possible. To have more general usage, I try to write in std  format.

I'm not sure if the algorithm is the best way to accomplish the goal, or if the style of coding is optimal.

#ifndef _REPEL
#define _REPEL

#include <algorithm>
#if __cplusplus >= 201103L
#include <utility>
#endif

#if __cplusplus >= 201103L
template<class ForwardIt, class InputIt, class BinaryPredicate>
bool check_repelled(ForwardIt first, ForwardIt last, InputIt target, BinaryPredicate p){
    return last != std::find_if(first, last, [p, target](decltype(*first) i)->bool{ return p(i, *target); });
}
#else
template<class ForwardIt, class InputIt, class BinaryPredicate>
bool check_repelled(ForwardIt first, ForwardIt last, InputIt target, BinaryPredicate p){
    for(ForwardIt i = first; i != last; ++i)
        if(p(*i, *target))
            return true;
    return false;
}
#endif

template<class InputIt, class ForwardIt, class BinaryPredicate>
ForwardIt remove_copy_repelled(InputIt first, InputIt last, ForwardIt d_first, BinaryPredicate p){
    ForwardIt d_end = d_first;
    for(; first != last; ++first){
        if(!check_repelled(d_first, d_end, first, p))
            *d_end++ = *first;
    }
    return d_end;
}

template<class ForwardIt, class BinaryPredicate>
ForwardIt remove_repelled(ForwardIt first, ForwardIt last, BinaryPredicate p){
    ForwardIt i, j;
    for(i = first; i != last; ++i)
        if(check_repelled(first, i, i, p))
            break;
    if(i == last)
        return last;
    for(j = i; ++j != last;)
        if(!check_repelled(first, i, j, p))
#if __cplusplus >= 201103L
            *i++ = std::move(*j);
#else
            std::iter_swap(i++, j);
#endif
    return i;
}
#endif

Possible implementation:

std::vector<int>x = {1,3,2,8,5,6,7};
x.erase(remove_repelled(x.begin(), x.end(), [](int a,int b)->bool{std::abs(a-b) < 2;}),x.end());
//x == {1,3,8,5}


texts: shopify get jquery code more readable, usable

texts:
Hi so like in my question,
i wrote some part of code for shopify to get recent orders for past 30 day
and i wondering if it is really readable, or maybe i schould change something?

I mean maybe there is a better way to achive same result.

Or maybe i schould use different names? change position for function?

$(document).ready(function() {
    const collection = [];

    //set minimum recent order limit to show
    const minimumOrders = 2;

    //set number of days for recent orders
    const numberOfDays = 30;

   let date = new Date();
   date.setDate(date.getDate() - numberOfDays)
   let startDate = date.toISOString();

    function insertData(item, quality){
      //part of code that will be executed for cert page
      if($( "input[value='"+item+"']" )){
        $( "input[value='"+item+"']" ).parent().append(""+quality+" purchased recently");
      }
      //part of code that will be executed for checkouts
      if($("tr[data-variant-id='"+item+"']")){
        $("tr[data-variant-id='"+item+"'] > .product__description").append(""+quality+" purchased recently");
      }
    }

    function countOrders(){
      $.getJSON('/admin/api/2020-01/orders.json', function (data ) {
        ordersEl = data.orders;

        ordersEl.forEach( function(element, index) {
          if(element.created_at > startDate) {
            element.line_items.forEach( function(item, index) {
              if(collection.hasOwnProperty(item.variant_id)){
                newValue = collection[item.variant_id]['quantity'] + item.quantity;
                collection[item.variant_id]['quantity'] = newValue;
              }
            });
          }
        });

        for(el in collection) {
          if(collection[el]['quantity'] > minimumOrders){
            insertData(el, collection[el]['quantity'])
          }
        }
      });
    }

    $.getJSON('/cart.json', function (data ) {
      data.items.forEach( function(element, index) {
        collection[element.id] = [];
        collection[element.id]['quantity'] = 0;
      });

      countOrders();
    });
  });

every comment, suggestion will be relevant

i do arrow functions and i think there is something more i can do but... the code just stop working...

i would like to change that one :

for(el in collection) {
   if(collection[el]['quantity'] > minimumOrders){
      insertData(el, collection[el]['quantity'])
   }
}

for:

collection.map( el => ((collection[el]['quantity'] > minimumOrders) ? insertData(el, collection[el]['quantity']) : null)


texts: Is this a good implementation of a thread-safe singleton using the observer pattern?

texts:
I need a singleton that can safely operate in a multi-thread environment. Threading and concurrency is new to me, so I'm not sure if this implementation holds. Take a look:

public class ObserverSingleton {

    private static ObserverSingleton _instance;
    private ArrayList<OnRequestFinishedListener> _listeners;

    private ObserverSingleton() {
        _listeners = new  ArrayList<OnRequestFinishedListener>();
    }

    public static synchronized ObserverSingleton getInstance() {
        if(_instance == null) {
            _instance = new ObserverSingleton();
        }

        return _instance;
    }

    public synchronized void addOnRequestFinishedListener(OnRequestFinishedListener listener) {
        // Check if listener already exists in list, skip if it does
        for (OnRequestFinishedListener listListener : _listeners) {
            if(listListener.equals(listener)) {
                return;
            }
        }

        _listeners.add(listener);
    }

    public synchronized void removeOnRequestFinishedListener(OnRequestFinishedListener listener) {
        // Check if listener exists in list, remove if it does
        for (OnRequestFinishedListener listListener : _listeners) {
            if(listListener.equals(listener)) {
                _listeners.remove(listListener);
            }
        }
    }

    private void notifyListeners() {
        for (OnRequestFinishedListener listener : _listeners) {
            listener.onRequestFinished();
        }
    }

    public Object clone() throws CloneNotSupportedException {
        throw new CloneNotSupportedException();
    }

    public interface OnRequestFinishedListener {

        public void onRequestFinished();

    }

}

Any feedback?


texts:
I was writing a program for my math class because my Professor asked me to. The problem is as follows: 300 people are arranged in 30 rows each of 10 people. The tallest of each row is chosen, and the shortest of each column. The problem is to prove whether the shortest of the taller people is taller, or the tallest of the shorter people. My program is as follows, but 90% of my coding standards are from PPCG, so my code is likely awful.

import random

multiple = int(input("Would you like multiple runs or one (enter 1 or 0)?\n").rstrip())

def weighted_random():
    # between 3 ft and 6 ft
    temp = random.random()
    t = 0
    if temp > 0.95:
        t = 6
    elif temp < 0.1:
        t = 3
    elif temp < 0.5:
        t = 4
    else:
        t = 5
    return t + random.random()

def output_array(array):
    for i in array:
        for j in i:
            print("%.3f" % j, end=' ')
        print()

def _zip(array):
    _x = len(array[1])
    _temp = []
    for i in range(_x):
        _temp.append([j[i] for j in array])
    return _temp

heights = [[weighted_random() for j in range(10)] for i in range(30)]

if not multiple:
    print("Men")

    output_array(heights)

    tall = [max(i) for i in heights]

    tall_man = min(tall)

    short = [min(i) for i in _zip(heights)]

    short_man = max(short)

    print("Tallest of short: ", end='')

    print(short_man)

    print("Shortest of tall: ", end='')

    print(tall_man)

    print("Answer is: ", end='')

    print(["tallest of short", "shortest of tall"][short_man < tall_man])

else:
    evalf = []

    times = int(input("Number of evaluations?\n").rstrip()) or 10000

    zeroes = 0

    for _i in range(times):
        heights = [[weighted_random() for j in range(10)] for i in range(30)]

        tall = [max(i) for i in heights]

        tall_man = min(tall)

        short = [min(i) for i in _zip(heights)]

        short_man = max(short)

        if short_man >= tall_man:

            zeroes += 1

    print("Out of %d evaluations, we got %d results as shortest of tall taller than tallest of short, and %d times they were equal." % (times, times - zeroes, zeroes))


texts: Readability of two rectangular point function samples

texts:
I have two implementations of the same function. Which of these is easier to understand?

Code sample A

function makeRectanglePoint(box, index){

    var boxToUse;

    function randomPoint(a, b){
        return Math.random() * Math.abs(a - b) + Math.min(b, a)
    }

    if(index % 2){ boxToUse = box.p1 } else { boxToUse = box.p2 }

    if(index < 2){
        return new Point(randomPoint(box.p1.x, box.p2.x), boxToUse.y);
    } else {
        return new Point(boxToUse.x, randomPoint(box.p1.y, box.p2.y));
    }

}

Code sample B

function makeRectanglePoint(rectangle, pointIndex){

    function getRectangleEdge(){

        function getPointByIndex(index) {
            switch (index) {
                case 0: return rectangle.p1;
                case 1: return new Point(rectangle.p2.x, rectangle.p1.y);
                case 2: return rectangle.p2;
                case 3: return new Point(rectangle.p1.x, rectangle.p2.y);
            }
        }

        function Line(p1, p2){
            this.p1 = p1;
            this.p2 = p2;
        }

        var endPointIndex = (pointIndex + 1) % 4;
        return new Line(
            getPointByIndex(pointIndex),
            getPointByIndex(endPointIndex)
        );
    }

    function generateRandomPointOnEdge(line){

        function generateRandomBetween(a, b){
            return Math.min(a, b) + Math.random() * Math.abs(a - b);
        }

        return new Point(
            generateRandomBetween(line.p1.x, line.p2.x),
            generateRandomBetween(line.p1.y, line.p2.y)
        );

    }

    return generateRandomPointOnEdge(getRectangleEdge());
}


texts: Selecting subset of size k using recursion

texts:
Sometimes I need to implement recursive algorithms that pass a certain state from one recursive call to another. For example, a greedy subset selection: we have a set of candidate objects, and we select a subset of size k greedily, one-by-one. The choice depends on the already selected objects and some constantly re-computed state. This state (and the set of candidates) can be discarded, once the selection is complete.

type O /* Individual objects */
type S /* Intermediate state */

def selectSubset(candidates: Seq[O], k: Int): Seq[O] =
    selectRec(candidates, Seq[O](), k, initialState(candidates))._2

def selectRec(candidates: Seq[O], acc: Seq[O], k: Int, state: S): (Seq[O], Seq[O], Int, S) =
    if (k > 0 && candidates.nonEmpty) {
        val next = selectNext(candidates, acc, state)
        selectRec(candidates - next, acc + next, k - 1, computeState(state, next))
    } else {
         (null, acc, null, null) /* (Early) termination */
    }

/* Implemented by library users */
def initialState(candidates: Seq[O]): S

def selectNext(candidates: Seq[O], alreadySelected: Seq[O], state: S): O

def computeState(previousState:S, lastSelected:O): S

Is recursion a good choice here?
Is there a neat alternative to Tuple as the return type of the recursive function? E.g. a case class might be more readable. In principle, candidates, i, and state can be merged into a single variable, but that also doesn't seem neat.
How to "express" (early) termination with tuples? We don't care about anything but acc at this point, but nulls look ugly.