texts:
My original code is:

let (upPosition, downPosition, leftPosition, rightPosition) =
    match myMove.MyDirection with
    | Direction.Up -> (GoUp y, y, GoLeft x, GoRight x)
    | Direction.Down-> (y, GoDown y, GoLeft x, GoRight x)
    | Direction.Left -> (GoUp y, GoDown y, GoLeft x, x)
    | Direction.Right -> (GoUp y, GoDown y, x, GoRight x)
    | _ -> (y, y, x, x)

Basically, there is an object on the 2D board. myMove.MyDirection dictates its next move, and x,y are its target position.

Once the object gets to x,y, it would cause some impacts on its front, left, right neighbours from its local rotational space. GoUp, ... , GoRight determines how far those neighbours could be.

So, ultimately, the code returns a "+" (cross) shape centred at x,y, so the minimum variable to describe this shape is (x, y, upPosition, downPosition, leftPosition, rightPosition).

The best solution I can think of to the previous code is the following. However, I feel there is more can be done to make it better. Is there any map function for tuple and is it costly?

let Reverse = function
    | Direction.Up -> Direction.Down
    | Direction.Down -> Direction.Up
    | Direction.Left -> Direction.Right
    | Direction.Right -> Direction.Left
    | _ -> raise (ArgumentException("Not Vaild Move!"))

let Go myDirection filter pos =
    match myDirection, filter with
    | a,b when a=b -> pos
    | Direction.Up , _  -> GoUp pos
    | Direction.Down , _ -> GoDown pos
    | Direction.Left , _ -> GoLeft pos
    | Direction.Right , _ -> GoRight pos
    | _ -> pos

let (upPosition, downPosition, leftPosition, rightPosition) =
    let rev = Reverse myMove.MyDirection
    (Go Direction.Up rev y, Go Direction.Down rev y, Go Direction.Left rev x, Go Direction.Right rev x)


texts: Determining if a sequence is a palindrome

texts:
To complement this Java question on palindrome identification, I came up with this C++(14) version:

#include <iterator>
#include <algorithm>
#include <functional>

namespace detail
{
    template <typename RandomIt, typename BinaryPredicate>
    bool is_palindrome(RandomIt first, RandomIt last, BinaryPredicate pred,
                       std::random_access_iterator_tag)
    {
        return std::equal(first, std::next(first, std::distance(first, last) / 2),
                          std::make_reverse_iterator(last), pred);
    }

    template <typename BidirIt, typename BinaryPredicate>
    bool is_palindrome(BidirIt first, BidirIt last, BinaryPredicate pred,
                       std::bidirectional_iterator_tag)
    {
        if (first == last || first == --last) return true;

        for (; first != last; ++first, --last) {
            if (!pred(*first, *last)) return false;
            if (std::next(first) == last) break;
        }

        return true;
    }
} // namespace detail

template <typename BidirIt, typename BinaryPredicate>
bool is_palindrome(BidirIt first, BidirIt last, BinaryPredicate pred)
{
    return detail::is_palindrome(first, last, pred,
                                 typename std::iterator_traits<BidirIt>::iterator_category {});
}

template <typename BidirIt>
bool is_palindrome(BidirIt first, BidirIt last)
{
    using V = typename std::iterator_traits<BidirIt>::value_type;
    return detail::is_palindrome(first, last,
                                 std::equal_to<V> {},
                                 typename std::iterator_traits<BidirIt>::iterator_category {});
}

template <typename SequenceType, typename BinaryPredicate>
bool is_palindrome(const SequenceType& sequence, BinaryPredicate pred)
{
    return is_palindrome(std::cbegin(sequence), std::cend(sequence), pred);
}

template <typename SequenceType>
bool is_palindrome(const SequenceType& sequence)
{
    return is_palindrome(std::cbegin(sequence), std::cend(sequence));
}

Used as such:

#include <iostream>
#include <string>
#include <list>

int main()
{
    std::cout << std::boolalpha;
    std::string str {"abba"};
    std::cout << is_palindrome(str) << std::endl;
    std::list<char> lst {str.cbegin(), str.cend()};
    std::cout << is_palindrome(lst) << std::endl;
    return 0;
}

Performance is my primary concern here. Comments and suggested improvements are welcome!


texts: Extend jQuery with enable/disable function

texts:
I want to create an extended disable/enable function in jQuery. This is working, but is this the best solution? Is each loop necessary?

 $.fn.ariaDisabled = function (isDisabled) {
        /// <summary>
        ///     Sets the disabled state.
        /// </summary>
        return this.each(function () {

            var $item = $(this);

            if (isDisabled === true) {
                $item
                    .attr('disabled', 'disabled')
                    .attr('aria-disabled', 'true')
                    .addClass('disabled');
            }
            else {
                $item
                    .removeAttr('disabled')
                    .removeAttr('aria-disabled')
                    .removeClass('disabled');
            }
        });
    };


texts:
I'm learning how to write tests in Angular (these are my first tests in general). There are a lot of tutorials out there but each one of them has a different approach. I'm a bit confused if I'm doing things the right way.

I made a simple directive for testing purposes and I've called it tooltip (though its not really a tooltip).

tooltip.js:

angular.module('mytestapp', []);

(function(){
    angular.module('mytestapp').directive('tooltip', tooltip);

    function tooltip() {
        var directive = {
            controller: tooltipCtl,
            controllerAs: 'vm',
            restrict: 'E',
            template:
                "This is a tooltip for {{ name }}" +
                "<button ng-click='vm.myFun()'>Click me!</button>",
            scope: {
                name: '@'
            },
            link: link
        };

        return directive;

        function link(scope, elem, attrs) {}
    }

    function tooltipCtl() {
        var vm = this;

        vm.things = 3;

        vm.myFun = myFun;
        function myFun() {
          vm.age = 30;
        }
    }

})();

tooltip.spec.js:

describe('tooltip', function () {
    angular.mock.module('mytestapp');
    beforeEach(angular.mock.module('mytestapp'));

    describe('template', function () {
        var $compile;
        var $scope;
        var element;
        var controller;
        // beforeEach(module('templates'));

        beforeEach(inject(function(_$compile_, _$rootScope_) {
            $compile = _$compile_;
            scope = _$rootScope_.$new();
            element = angular.element("<tooltip name='john'></tooltip>");
            element = $compile(element)(scope);
            scope.$digest();
        }));

        beforeEach(function () {
            controller = element.controller('tooltip');
        });

        it('should have name equal to john', function (){
            expect(element.html()).toContain('john');
        });

        it('should have 3 items', function (){
            expect(controller.things).toBe(3);
        });

        it('should set age when clicked to 30', function () {
            expect(controller.myFun).toBeDefined();
            controller.myFun();
            expect(controller.age).toBe(30);
        });

    });
});

I'm using Karma and Jasmine, Angular 1.4.7, angular-mocks and ng-html2js. I'd be thankful for a general review of my code. Links to some good, up-to-date guides would help as well.

Additional questions:

I have ng-html2js included but I didn't really use it, can I use it in my example? Should I do it? Yes/no, and why?
I have a beforeEach(module('templates')); that I've used in some previous example but my spec works without it here. Is this module-templates things something common, or is there some sort of pattern where you use it?
I've used angular.mock.module but my spec works fine with just module. Any tips here?


texts: ResettableLazy: a resettable version of .NET Lazy

texts:
I implemented a resettable version of .NET Lazy (context: mostly to use it in a MemoryCache for auto refresh purposes on item expiration)

This is a very naive implementation and I am pretty sure there are couple of things that are not okay. In particular, I am not really sure whether the reset is fine. I think the assignment is atomic but I am not sure what can happen when there is an attempt to get the Value while it is resetting at the same (e.g. I am not sure whether the fact that the assignment is atomic is enough to guarantee proper operations).

public class ResettableLazy<T>
{
    private Lazy<T> _lazy;

    public bool IsValueCreated => _lazy.IsValueCreated;

    public T Value => _lazy.Value;

    public LazyThreadSafetyMode LazyThreadSafetyMode { get; }

    private readonly Func<T> _valueFactory;

    public ResettableLazy(Func<T> valueFactory, LazyThreadSafetyMode lazyThreadSafetyMode = LazyThreadSafetyMode.ExecutionAndPublication)
    {
        _valueFactory = valueFactory;
        LazyThreadSafetyMode = lazyThreadSafetyMode;
        _lazy = new Lazy<T>(_valueFactory, LazyThreadSafetyMode);
    }

    public ResettableLazy(Func<T> valueFactory, bool isThreadSafe)
        : this(valueFactory, isThreadSafe ? LazyThreadSafetyMode.ExecutionAndPublication : LazyThreadSafetyMode.None)
    {
    }

    public void Reset()
    {
        _lazy = new Lazy<T>(_valueFactory, LazyThreadSafetyMode);
    }
}

And played a bit around with:

public static class Program
{
    public static void Main(params string[] args)
    {
        var lazy = new ResettableLazy<int>(() =>
        {
            Thread.Sleep(2000);
            return new Random().Next();
        });

        for (var i = 0; i < 1000; i++)
        {
            if (i % 2 == 0)
            {
                Thread.Sleep(200);
            }

            Task.Run(() => Console.WriteLine(lazy.Value));

            if (i % 3 == 0)
            {
                Task.Run(() => lazy.Reset());
            }
        }

        Console.ReadKey();
    }
}

Is there any red flags in my implementation?


texts: Speeding up Access query with a calculated field calling a VBA function

texts:
At work I have a Microsoft Access database of employees with fields such as employee's manager, employees email, and employee ID. My duties include updating this database and validating entries generated. Biweekly when I run the VBA script to validate records, I am faced with between 25K and 30K of employee records in the table. A typical validation function in VBA is below:

Public Function validateEmployeeManager(empID As String, empStatus as String, empManager As String)

    If ((empStatus = "Active") And isNull(empManager)) Then
        validateEmployeeManager = "Manager is invalid for employee" & " " & empID
    Else
        validateEmployeeManager = "Valid manager"
    End If

Calling the above in a calculated field in a query:

validateEmployeeManager([Employee_Name],[Employee_Status],[Employee_Manager]

I have noticed code such as the above takes quite a bit of time to run and display the results, given the size of the database.

Is there a more efficient method of running this validation?


texts: PowerShell Script to get data from Third Party API and insert into database

texts:
I have created a PowerShell script that will call a REST API and then for each node returned, add the data into a database table. This particular endpoint only returns ~600 records worth of data, however this is the method I will be using for a bunch of other API endpoints.
There are a couple things I think would help with this script:

Bulk add the records into the database rather than one by one
For the ON DUPLICATE KEY UPDATE only change fields that are different.

My understanding of ON DUPLICATE KEY UPDATE it will check if the ScryId exists, and if it does then update the fields listed below. I would like to only update the fields that are different.
Script:
If ( Get-Module -ListAvailable -Name SimplySQL ) { Import-Module -Name SimplySQL } Else { Install-Module -Name SimplySQL -Force }

Write-Host "---------------------------------------------------------------------------" -ForegroundColor DarkGray
Write-Host "Update Production.Set' Table: " -ForegroundColor Gray -NoNewline
$StartTime = $(Get-Date)

$Response = Invoke-RestMethod -Uri "https://api.scryfall.com/sets" -Method GET -UseBasicParsing
$ResponseSorted = $Response.data | Sort-Object -Property @{Expression = "released_at"; Descending = $False}

$username = ""
$password = ConvertTo-SecureString "" -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential ($username, $password)

Open-MySQLConnection -Server "" -Port 1234 -Database "Production" -Credential $credential

Foreach ( $Record in $ResponseSorted ) {
    $ScryID = $Record.id
    $Code = Try{ ($Record.code).ToUpper() } Catch {}
    $Name = Try{ ($Record.name) -replace "'","" } Catch {}
    $SetType = $Record.set_type
    $ReleaseDate = $Record.released_at
    $CardCount = $Record.card_count
    $BlockCode = Try{ ($Record.block_code).ToUpper() } Catch {}
    $BlockName = $Record.block
    $ParentSetCode = Try{ ($Record.parent_set_code).ToUpper() } Catch {}
    $Digital = $Record.digital
    $NonFoil = $Record.nonfoil_only
    $Foil = $Record.foil_only
    $Icon = $Record.icon_svg_uri
    $Status = 0

    Invoke-SQLUpdate -query "
        INSERT INTO Production.`Set`
            (ScryID, Code, Name, SetType, ReleaseDate, CardCount, BlockCode, BlockName, ParentSetCode, Digital, NonFoil, Foil, Icon, Status)
        VALUES
            ( '$ScryID', '$Code', '$Name', '$SetType', '$ReleaseDate', $CardCount, '$BlockCode', '$BlockName', '$ParentSetCode', $Digital, $NonFoil, $Foil, '$Icon', $Status )
        ON DUPLICATE KEY UPDATE
            Code = '$Code',
            Name = '$Name',
            SetType =  '$SetType',
            ReleaseDate = '$ReleaseDate',
            CardCount = $CardCount,
            BlockCode = '$BlockCode',
            BlockName = '$BlockName',
            ParentSetCode = '$ParentSetCode',
            Digital = $Digital,
            NonFoil = $NonFoil,
            Foil = $Foil,
            Icon = '$Icon'
    " | Out-Null
}

Close-SQLConnection

$ElapsedTime = $(Get-Date) - $StartTime
$TotalTime = "{0:HH:mm:ss.fff}" -f ([datetime]$ElapsedTime.Ticks)
Write-Host $TotalTime -ForegroundColor Cyan


texts:
I've been writing some smaller jQuery plugins lately, and I've been thinking of writing up some boilerplate that I can use when writing new ones. I have code that works (for now), but I want to share it and get feedback on things I may be missing as I move to larger plugins.

/**
*  jQuery Plugin Boilerplate
*  - find and replace the following variable names
*    - utilities   : namespace for shared utility functions
*    - PluginClass : class name for plugin object
*    - pluginName  : the name of your plugin function, e.g. $('.foo').myPlugin()
**/
(function($) {

    /**
    *  Utility function object
    *  - namespace wrapper for variables or functions shared between all plugin instances
    **/
    var utilities = {

        // example utility function
        getInt: function(i) {
            i = parseInt(i, 10);
            return isNaN(i) ? 0 : i;
        }

    },

    /**
    *  Main plugin class
    *  - encapsulate each instance of plugin as an object
    **/
    PluginClass = {

        // other instance-specific functions get defined here

        init: function(el,options) {
            var _t = this;  // for maintaining reference to plugin class in callbacks

            this.options = $.extend({}, $.fn.pluginName.defaults, options);
            this.el = el;
            this.$el = $(el);

            // do your plugin stuff
        },

        callFn: function(fn) {
            switch(fn) {
              // case statements matching allowable function aliases
              // which execute the appropriate plugin functions
            }
        }

    };

    /**
    *  Plugin function
    *  - for each element passed to the plugin, create a new class instance
    **/
    $.fn.pluginName = function () {
        var arg = arguments[0];
        var fn, options;

        // if the argument passed is a string, then the user
        // is calling a function. Otherwise, it's an options object
        if(typeof arg === 'string') {
            fn = arg;
        }
        else {
            options = arg;
        }

        if (this.length > 0) {
            return this.each(function(i) {
                var el = $(this), p;

                // if plugin instance already exists, use it
                if(el.data('pluginName')) {
                    p = el.data('pluginName');
                    if(fn) { p.callFn(fn); }
                    else { p.init(this,options); }
                } else {
                    p = Object.create(PluginClass);
                    el.data('pluginName', p);
                    p.init(this,options);
                }
            });
        }

    };

    /**
    *  Plugin default options
    *  - created outside of plugin function for easier overriding by user
    **/
    $.fn.pluginName.defaults = {
        some: thing,
        foo: 'bar'
    };

})(jQuery);

Here's an example I created using this boilerplate. It's nothing fancy, it simply takes the text of an element and paints each character with a different color.

jQuery Plugin Demo - $.paintText()

My main concern here is with the functionality of using $('#foo').paintText('fnAlias') to call a function on an existing plugin instance. My way seems to work, but part of me feels there may be a more efficient way.

Thanks for any help.


texts: Randomly generate a list with predetermined mean

texts:
Aim: randomly generate \$n\$ numbers between \$a\$ and \$b\$ with (roughly) mean \$m\$.

Problem: The simple beginner's code I wrote becomes very inefficient as \$m\$ moves away from \$\frac{a + b}{2}\$.

import random
import numpy as np
import time

low = 0
high = 100

data = 50

def lst_w_mean(target):
    HT = [x for x in range(low, high+1)]
    target_mean = 0

    while target_mean <> int(target):
        outcomes = [random.choice(HT) for x in range(data)]
        target_mean = np.mean(outcomes)
    return outcomes

t1 = time.clock()
data_new = lst_w_mean(54)
print "elapsed time: ", time.clock() - t1
print data_new

t1 = time.clock()
data_new = lst_w_mean(32)
print "elapsed time: ", time.clock() - t1
print data_new

Works pretty decently for means close to the the mean of HT (e.g., means between between 40 and 60). Takes for ever (without generating a run-time error) beyond that narrow range (roughly 28 minutes for mean =30)

%run
elapsed time for mean = 54:  0.00734800000009
[46, 82, 6, 0, 90, 73, 99, 2, 34, 88, 51, 14, 89, 72, 40, 8, 97, 44, 46, 45, 89, 10, 22, 52, 96, 98, 43, 52, 59, 74, 52, 54, 64, 66, 21, 71, 92, 34, 76, 33, 26, 36, 53, 74, 64, 85, 59, 26, 69, 24]

elapsed time for mean = 30:  1695.210358
[67, 43, 30, 78, 67, 33, 13, 24, 27, 1, 2, 4, 4, 2, 49, 1, 41, 16, 6, 9, 6, 90, 1, 31, 52, 91, 5, 11, 4, 94, 2, 74, 60, 38, 8, 2, 10, 20, 92, 25, 17, 36, 12, 9, 7, 22, 16, 72, 44, 32]

Reformulating HT with something like:

if target < 40:
 high = 70

etc., so that the target mean is closer to the mean of HT does not generate realistic data besides being an ad hoc solution.  And yes, I would like what I call "realistic data" to have a "high" standard deviation perhaps with a number of "outliers".

The process speeds up significantly as the value of data diminishes, so maybe the better approach is to try to use recursion with smaller data values (sort of like in merge-sort)?


texts: Making toString function more readable In Java

texts:
I'm trying to make my code more readable. I created a function toString - It returns a string in the following format:

Name: <Name>.
IdNumber: <Number>.
Age: <Number>.
Colors: <Color1, Color2, ..., ColorN>.

Please notice that the colors should be sorted alphabetically. The function I wrote for now:

public String toString() {
    String colorsString = this.colors.stream().sorted().collect(Collectors.joining(", "));
    return "Name: " + this.Name+".\n" +
            "IdNumber: "  + this.Id+".\n" +
            "Age: " + this.Age+".\n" +
            "Colors: " + colorsString + ".";
}

I don't like the way I sorted the colors. I would like to use stream, but in other way if possible. Also, I feel like the format should be constant. Is it possible to keep it as a constant and add values to it? Future more I don't like the use of \n - is it possible without it?


texts: How to make below code more readable and efficient?

texts:
Code below reads static variables from ProductConfiguration class. Functions setAccess and setMarketAccess in two classes ProductInitialization and ProductMarketInitialization reads variables from ProductConfiguration. Can this reading be done in a better way? I still want to have file ProductConfiguration to hold public variables. Was just wondering if there is a better way of reading this variables in the other two classes, may be there in future there will be additional classes that will read variables from ProductConfiguration

public class ProductConfiguration{

      public static final PRODUCT_ACCESS=//this value is read from properties file

      public static final MARKET_PRODUCT_ACCESS=//this value is read from properties file

}

public class ProductInitialization{
    public Product setAccess(Product p){
         if(p.brand == "LOCAL") {
             p.access=ProductConfiguration.PRODUCT_ACCESS;
             return p;
          }
         p.access = "DEFAULT";
        return p;
    }
}

public class ProductMarketInitialization{
       public void setMarketAccess(Product p){
            if(p.type == "MARKET"){
                p.access=
              ProductConfiguration.MARKET_PRODUCT_ACCESS;
              return p;
            }
           p.access ="MARKET_DEFAULT";
          return p;
      }
}


texts:
I am trying to get user's current location base on the accuracy and less battery consumption.

Please review my code to help determine if I am going in right direction.

Location location = null;
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_
try {
    String provider = locationManager.getBestProvider(criteria, false);
    locationManager.requestLocationUpdates(provider, 2000, 5,locationListener);
    location = locationManager.getLastKnownLocation(provider);
    lati = Double.toString(location.getLatitude());
    longi = Double.toString(location.getLongitude());

} catch (Exception ex) {
    ex.printStackTrace();
}


texts:
I am trying to automate this portion of code in python (code shown for 2 polygons, I am trying to do the same for 10 000 polygons). Any ideas on how to implement this using for loop or whichever fastest way you recommend.

### Polygon 1
def checkPolygon1(row):
    point = Point((row['X']), (row['Y']))
    return polygon1.contains(point)

#Apply fn to each row of dataframe (datacopy)
datacopy.apply(checkPolygon1, axis=1)

#Create new variable InPolygon1 in data if X, Y in shapely file
datacopy['InPolygon1'] = datacopy.apply(checkPolygon1, axis=1)

### Polygon 2
def checkPolygon2(row):
    point = Point((row['X']), (row['Y']))
    return polygon2.contains(point)

datacopy.apply(checkPolygon2, axis=1)
#Create new variable InPolygon2 in data if X, Y in shapely file
datacopy['InPolygon2'] = datacopy.apply(checkPolygon2, axis=1)


texts: LINQ queries improvement - repetition of query

texts:
I have a DAL class full of LINQ queries which I would like to improve as I found that I'm repeating myself couple of times.

As you can see the part below is repeated couple of times and I was wondering if it is possible to reduce the number of repetitions (passing the query somehow?) and/or improve the queries overall.

  .Where(x => x.Active == true && x.Variable.Active == true && x.Variable.Question.Active == true)

    private DashboardEntities db;

    public AnswerSelectLabelRepository(DashboardEntities _db)
    {
        this.db = _db;
    }

    public AnswerSelectLabel GetById(string idAnswerSelectLabel)
    {
        return db.AnswerSelectLabel.Find(idAnswerSelectLabel);
    }

    public IEnumerable<AnswerSelectLabel> GetAll()
    {
        return db.AnswerSelectLabel
            .Where(x => x.Active == true && x.Variable.Active == true && x.Variable.Question.Active == true)
            .OrderBy(x => x.DisplayOrder)
            .ThenBy(x => x.Value);
    }

    public IEnumerable<AnswerSelectLabel> GetByVariable(string idVariable)
    {
        return GetAll().Where(x => x.idVariable == idVariable);
    }

    public IEnumerable<AnswerSelectLabel> GetByVariable(IEnumerable<Respondent> respondents, string idVariable)
    {
        return respondents.SelectMany(x => x.AnswerSelect)
            .Select(x => x.AnswerSelectLabel)
            .Where(x => x.Active == true && x.Variable.Active == true && x.Variable.Question.Active == true)
            .Where(x => x.idVariable == idVariable);
    }

    public IEnumerable<AnswerSelectLabel> GetByQuestion(string idQuestion)
    {
        return GetAll().Where(x => x.Variable.idQuestion == idQuestion);
    }

    public IEnumerable<AnswerSelectLabel> GetByQuestion(IEnumerable<Respondent> respondents, string idQuestion)
    {
        return respondents.SelectMany(x => x.AnswerSelect)
            .Select(x => x.AnswerSelectLabel)
            .Where(x => x.Active == true && x.Variable.Active == true && x.Variable.Question.Active == true)
            .Where(x => x.Variable.idQuestion == idQuestion);
    }


texts:
BSON is an extended JSON format. For example these documents are valid BSON documents, but invalid JSON documents:

prettified documents:

[
  {
    "_id": ObjectId("5a934e000102030405000000"),
    "k": 10,
    "dt": ISODate("2018-10-10")
  },
  {
    "_id": ObjectId("5a934e000102030405000001"),
    "k": {
      "field1": "someVal",
      "field2": 12.2323242
    }
  },
  {
    _id: ObjectId("5a934e000102030405000002"),
    k: 7
  }
]

compacted documents

[{"_id":ObjectId("5a934e000102030405000000"),"k":10,"dt":ISODate("2018-10-10")},{"_id":ObjectId("5a934e000102030405000001"),"k":{"field1":"someVal","field2":12.2323242}},{_id:ObjectId("5a934e000102030405000002"),k:7}]

I recently needed a tool to compact or prettify BSON documents. After several attempts with javascript formatter (beautifyjs, prettifier ...) I ended up implementing my own solution.

Important:

the goal of this code is not to check if a document has a valid BSON syntax, but only to prettify/compact a BSON document. Hence, it assumes that the src is valid BSON

Here is my solution:

const compactMode = 0
const indentMode = 1

function indent(src) {
    return write(src, indentMode)
}

function compact(src) {
    return write(src, compactMode)
}

function write(src, mode) {

    var result = ""
    var needIndent = false
    var inValue = false
    var depth = 0

    for (var i = 0; i < src.length; i++) {
        c = src.charAt(i)

        if (c === " " && !inValue || c === "\n") {
            continue
        }

        if (needIndent && c !== "]" && c !== "}") {
            needIndent = false
            depth++
            result += newline(mode, depth)
        }

        switch (c) {
            case "{":
            case "[":
                needIndent = true
                result += c
                break
            case ",":
                result += c
                result += newline(mode, depth)
                break
            case ":":
                result += c
                if (mode === indentMode && !inValue) {
                    result += " "
                }
                break
            case "}":
            case "]":
                if (needIndent) {
                    needIndent = false
                } else {
                    depth--
                    result += newline(mode, depth)
                }
                result += c
                break
            case "\"":
            case "'": // if we get a `'`, replace it with `"`
                inValue = !inValue
                result += "\""
                break
            default:
                result += c
        }
    }
    return result
}

function newline(mode, depth) {
    if (mode === compactMode) {
        return ""
    }
    var line = "\n"
    for (var i = 0; i < depth; i++) {
        line += "  "
    }
    return line
}

How can I improve this ?


texts: Allow certain IP addresses to run a C++ program

texts:
I coded an executable program (.exe) that I only want run either from my home computer, our main server, or people in our development team.

I have coded logic that will only allow the program to be run from certain IP addresses.

The .txt file that's referenced in the getIPlist function looks like this:

[123.456.78.90] = Main Server
[77.34.555.392] = My computer at home
[333.455.3.3] = Assistant coder

And the HTTP address that the parseAllowableIPs function points to is a PHP file that is simply coded:

<?php echo $_SERVER['REMOTE_ADDR']; ?>

This code is working great (except for a bit of memory not being freed), so a review or some efficiency tips are welcome.

bool compareIPs(std::string IPlist, std::string userIP)
{
    const char *U = userIP.c_str();
    char str[20];

    const char *goodList[25] = { '\0' };

    std::string uIP = "";

    while (*U)
    {
        if (atoi(U))
        {
            uIP += itoa(atoi(U), str, 10);
            while (*U && *U != '.')
                *U++;

            if (*U && *U == '.')
                uIP += ".";
        }

        if (*U)
            *U++;
    }

    const char *L = IPlist.c_str();
    int count = 0;
    std::string thisIP = "";

    while (*L)
    {
        switch (*L)
        {
        case '[':
            *L++;

            while (*L && *L != ']')
            {
                thisIP += *L;
                *L++;
            }

            goodList[count] = _strdup(thisIP.c_str());
            thisIP = "";
            count++;
            break;
        default:
            break;
        }

        if (*L && *L != '[')
            *L++;
    }

    std::string comp = "";

    // Now check to see if the user's IP matches any in the goodList[]
    for (int a = count; a >= 0; a--)
    {
        if (!goodList[a])
            continue;

        comp = goodList[a];

        if (!uIP.compare(comp))
        {
            // I need to free() what was _strdup()'d
            // but this causes the progam to crash.

            //free(&goodList[a]);

            return true;
        }
    }

    return false;
}

#pragma comment(lib, "WinInet.Lib")

std::string getIPlist()
{
    HINTERNET hInternet, hFile;
    DWORD rSize;
    char buffer[1024];

    hInternet = InternetOpen(NULL, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
    hFile = InternetOpenUrl(hInternet, "http://www.myWebServer.com/ip/authorizedIPlist.txt", NULL, 0, INTERNET_FLAG_RELOAD, 0);
    InternetReadFile(hFile, &buffer, sizeof(buffer), &rSize);
    buffer[rSize] = '\0';

    InternetCloseHandle(hFile);
    InternetCloseHandle(hInternet);

    std::string result = buffer;

    return result;
}

bool parseAllowableIPs()
{
    // Grap the list of allowable IP's and store it in a string
    // to be parsed in compareIPs() function.
    std::string allowableIPlist = getIPlist();

    HINTERNET hInternet, hFile;
    DWORD rSize;
    char buffer[1024];

    hInternet = InternetOpen(NULL, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
    hFile = InternetOpenUrl(hInternet, "http://www.myWebServer.com/ip/index.php", NULL, 0, INTERNET_FLAG_RELOAD, 0);
    InternetReadFile(hFile, &buffer, sizeof(buffer), &rSize);
    buffer[rSize] = '\0';

    InternetCloseHandle(hFile);
    InternetCloseHandle(hInternet);

    std::string result = buffer;

    if (!compareIPs(allowableIPlist, result))
        return false;

    return true;
}

int main()
{
    //... blah blah blah

    // If not an authorized IP, just exit the game.
    if (!parseAllowableIPs())
    {
        MySQL__disconnect();
        exit(588924);
    }
}


texts: Calculate distance between points and price per area in Pandas

texts:
I'm trying to find distances between all points (latitude, longitude), and for each point, get the average price_area (price/area) of the closest points around it. This code is taking too long:

def create_pa_radius(df, radius):

    df['pa_' + str(radius)] = np.nan

    for index, row in df.iterrows():
        point = [row['latitude'], row['longitude']]
        df['distances'] = df.apply(lambda x: geo_dist(point, [x['latitude'], x['longitude']]).km, axis = 1)
        samples = df.price_area[df.distances < radius/1000]
        mean = samples.mean()

        df['pa_' + str(radius)].iloc[index] = mean

    return df

I would like at least to understand how to make this kind of iteration faster.


texts:
I am relatively new to the Qt framework and I was wondering if I should delete pointers in my program.  I know that, in C++, if memory is not return it could lead to memory leak, but I am not sure if the same applies to Qt.

#include "mainwindow.h"
#include <QApplication>
#include <QTextEdit>
#include <QPushButton>
#include <QVBoxLayout>
#include <QIcon>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QWidget *w = new  QWidget();
    w->setWindowTitle("Music Player");
    QIcon * mainwind_icon = new QIcon("MusicPlayer.png");
    w->setWindowIcon(*mainwind_icon);

    QPushButton * enter_button = new QPushButton();
    QTextEdit  * textbox = new QTextEdit();

    QHBoxLayout * vlayout = new QHBoxLayout;
    vlayout->addWidget(textbox);
    vlayout->addWidget(enter_button);

    w->setLayout(vlayout);

    w -> show();

    return a.exec();
}


texts:
Scenario:

Check if the user exists

If yes: update the details
Else: insert the user details

public bool AddUsers(IEnumerable<UserDetail> users)
    {
        using (var dbTransaction = System.Data.Entity.Database.DefaultConnectionFactory.CreateConnection("MyCon").BeginTransaction())
        {
            using (var entities = new MyDbEntities())
            {
                try
                {
                    foreach (var user in users)
                    {
                        // LINQ under observation
                        var userId = entities.tUsers.Where(u => u.UserName == user.UserName).Select(x => x.UserUID).FirstOrDefault();

                        if (userId > 0)
                        {
                            //update

                        }
                        else
                        {
                             //insert
                        }

                    }
                    dbTransaction.Commit();
                    return true;
                }
                catch (Exception ex)
                {
                    dbTransaction.Rollback();
                    clsErrorHandling.WriteLog("ImportUsersHandler", "AddUsers", ex.Message.ToString());
                    return false;
                }
                finally
                {
                    dbTransaction.Dispose();
                }
            }
        }
    }

Please find the comment //LINQ under observation.

Is there a better way to find the user?

Because if I do this way:-

 tblUser newUser = new tblUser() { Username = user.Username } ;

If the user exists then no issue then in case not then how do I check whether I need to do insert or update.


texts:
Sort a stack in ascending order. You may only use one additional stack to hold items.

Any comments on my solution?
Worst case complexities:
Memory complexity: O(n)
Runtime complexity: O(n^2)

Also, I implemented the Stack class as having Object items and then cast these into Integers to be more general. Is this a good way of doing this?

import org.junit.Test;

public class Solution {
  // Sort a stack in ascending order
  // May only use one additional stack to hold items
  // Stack supports push, pop, peek, and isEmpty
  private Stack stack;

  private Stack auxiliaryStack;

  @Test
  void testStackIncreasingOrder() {
    stack = new Stack();
    stack.push(3);
    stack.push(2);
    stack.push(1);
    System.out.println("original stack");
    printStack();
    sortStack();
    System.out.println("Sorted stack");
    printStack();
  }

  @Test
  void testEmptyStack(){
    stack = new Stack();
    System.out.println("original stack");
    printStack();
    sortStack();
    System.out.println("Sorted stack");
    printStack();
  }

  @Test
  void testStackRandomOrder() {
    stack = new Stack();
    stack.push(3);
    stack.push(2);
    stack.push(1);
    stack.push(5);
    stack.push(1);
    stack.push(1);
    stack.push(12);
    stack.push(0);
    System.out.println("original stack");
    printStack();
    sortStack();
    System.out.println("Sorted stack");
    printStack();
  }

  public static void main(String[] args) {
    Solution e = new Solution();
    System.out.println("Test reverse sorted stack");
    e.testStackIncreasingOrder();
    System.out.println("Test empty stack");
    e.testEmptyStack();
    System.out.println("Test randomly ordered stack");
    e.testStackRandomOrder();
  }

  public void sortStack() {
    auxiliaryStack = new Stack();
    if (stack.isEmpty()) {
      return;
    }

    while (!stack.isEmpty()) {
      Object topOfStack = stack.pop();
      if (auxiliaryStack.top != null) {
        Object topOfAuxiliary = auxiliaryStack.peek();
        if ((Integer) topOfStack > (Integer) topOfAuxiliary) {
          emptyAuxiliary();
        }
      }
      auxiliaryStack.push(topOfStack);
    }
//    System.out.println("AuxiliaryStack");
//    printAuxiliaryStack();
    emptyAuxiliary();
  }

  public void emptyAuxiliary() {
    // Put all the elements of the auxiliary stack back in
    // the original one
    while (!auxiliaryStack.isEmpty()) {
      Object element = auxiliaryStack.pop();
      stack.push(element);
    }
  }

  public Stack getStack() {
    return stack;
  }

  public void printStack() {
    Node current = stack.top;
    while (current != null) {
      System.out.println(current.data);
      current = current.next;
    }
  }

  public void printAuxiliaryStack() {
    Node current = auxiliaryStack.top;
    while (current != null) {
      System.out.println(current.data);
      current = current.next;
    }
  }

}

class Stack {
  Node top;

  Object pop() {
    if (top != null) {
      Object item = top.data;
      top = top.next;
      return item;
    }
    return null;
  }

  void push(Object item) {
    Node t = new Node(item);
    t.next = top;
    top = t;
  }

  Object peek() {
    return top.data;
  }

  boolean isEmpty() {
    if (top == null) {
      return true;
    }
    return false;
  }
}

class Node {
  Object data;

  Node next;

  public Node(Object item) {
    data = item;
  }

  public Node(Object item, Node n) {
    data = item;
    next = n;
  }
}


texts:
I've got a JavaScript object and I am not sure how to implement the last part: adding up all of the prices and putting that in the last row of the table. Besides this question, I would also like to ask you to look at the code and advice me if I can make the code slimmer, less lines of code.

This is the code I would like reviewed:

    function ShoppingList(){
    this.items = [];
    this.setItem = function(product, price){
        var item = new Item(product, price);
        this.items.push(item);
    };
    this.render = function(){
        var placeHolder = document.getElementById("shoppingList");
        placeHolder.innerHTML = "";
        var messageDiv = document.getElementById("message");
        messageDiv.innerHTML = "";

        var tr = document.createElement("tr");
        tr.id = "header";

        var thProduct = document.createElement("th");
        thProduct.innerHTML = "Product";
        tr.appendChild(thProduct);

        var thPrice = document.createElement("th");
        thPrice.innerHTML = "Prijs";
        tr.appendChild(thPrice);

        var thDel = document.createElement("th");
        thDel.innerHTML = "Verwijder";
        tr.appendChild(thDel);

        placeHolder.appendChild(tr);

        for(var i = 0; i < this.items.length; i++){
            var tr = document.createElement("tr");
            tr.id = i;

            var tdProduct = document.createElement("td");
            tdProduct.innerHTML = this.items[i].product;
            tr.appendChild(tdProduct);

            var tdPrice = document.createElement("td");
            tdPrice.innerHTML = Number(this.items[i].price);
            tr.appendChild(tdPrice);

            var tdDel = document.createElement("td");
            tdDel.innerHTML = "Verwijder";
            tdDel.addEventListener("click", delItem, false);
            tr.appendChild(tdDel);

            placeHolder.appendChild(tr);
        }
    };
}

So, in short: how can I write a new table row to the table with the total price that updates when table rows are added or removed and how can I slim down my code?


texts: Singleton manager/service classes with mockable dependencies in swift

texts:
In our swift project, there are multiple service classes that encapsulate functions, mostly network-api calls. They implement a protocol, and depend on other service classes, e.g. an authorization service or a network facade.

Their instances should only exist once, hence they are designed as singletons, with a private constructor and a single point to access, like so:

static let defaultInstance = MyManagerImplementation(networkFacade: MyApiFacade())

In order to write unit tests for each service class, i want to mock the dependencies. Sadly this is not possible in the code above.

So i re-wrote the initialization like this.

let networkFacade: MyApiFacade

private static var instance: MyManagerImplementation?

static func defaultInstance(apiFacade apiFacade: MyApiFacade = RestApiImplementation.defaultInstance) -> MyManager {
    if instance == nil {
        instance = MyManagerImplementation(networkFacade: apiFacade)
    }
    return instance!
}

init(networkFacade: MyApiFacade) {
    self.networkFacade = networkFacade
}

Which should be the classic singleton pattern, as i know it from other languages.

The problem i have with this is that swift seemingly wants to avoid this way of defining a singleton. It is way longer than the single-line-singleton, which is considered best practice in many posts i found on the web.

So, would it make sense to you to define these service-classes completely static? Or would you go with another solution or the solution above?


texts: Collate a growing number of String arrays and search through them

texts:
These string arrays are used to classify whether the incoming feed/message is a driver feed or team feed.

private static final String[] DRIVER_FEED_TYPES = {
        "SEBASTIAN_VETTEL", "LEWIS_HAMILTON", "CHARLES_LECLERC", "MAX_VERSTAPPEN",
};

private static final String[] TEAM_FEED_TYPES = {
        "FERRARI", "MERCEDES", "SAUBER", "REDBULL"
};

This method gets the type of feed through the incoming message and determines the corresponding type through the arrayContains method.

private boolean isFeedEnabled(FormulaOneMessage formulaOneMessage) {
    String feedType = formulaOneMessage.getFeedType();

    if (Helper.arrayContains(DRIVER_FEED_TYPES, feedType)) {
        return isDriverFeedEnabled();
    } else if (Helper.arrayContains(TEAM_FEED_TYPES, feedType)) {
        return isTeamFeedEnabled();
    } else {
        return false;
    }
}

The arrayContains method basically looks through the Object array to see if the object is there.

public static boolean arrayContains(Object[] list, Object item) {
    for (Object s : list) {
        if (s.equals(item)){
            return true;
        }
    }

    return false;
}

The challenge is how to manage the growing number of types of String arrays in the class. Should I make it into a map, stream or an enum?

Also, the if else statement would also grow as I continue to add more FEED_TYPES. Should I continue to use them?

Overall, I wanted to improve the maintainability of this code seeing the number of feed types will continue to grow in the future.


texts: Shorter way of prompting for a height of x feet y inches?

texts:
I'm currently working on a BMI calculator and just wondered if there was a shorter or more condensed version of doing the if validating statement.

I have currently done it this way for both Height and Weight, but I find it to be a mess and it seems to cluttered. There must be a way of shortening this down or condensing it.

boolean Hresult = false;
int resulth = 0;
while(Hresult == false) {

    System.out.print("\nPlease enter your feet: ");
    int heightft = scanner.nextInt();

    if (heightft >=2 && heightft <=7 ){
        System.out.println("You entered: " + heightft);
        Hresult = true;
    }
    else {
           System.out.println("Please try again");
           Hresult = false;
    }
    System.out.print("Please enter your inches: ");
    int heightin = scanner.nextInt();

    if (heightin >=0 && heightin <=11 ){
        System.out.println("You entered: " + heightin);
        Hresult = true;
    }
    else {
        System.out.println("Please try again");
        Hresult = false;
    }
    int resultin = (heightft * 12);
    resulth = (resultin + heightin);
}
return resulth;


texts: JavaScript bookmarklet with a 24 hour cache

texts:
I'm working on a bookmarklet that will be cached for 24 hours only, after that time it will be reloaded from the original source.
Is there something I could improve?

javascript:(function () {var currentTime=new Date();var month=currentTime.getMonth()+1;var day=currentTime.getDate();var year=currentTime.getFullYear();document.getElementsByTagName('head')[0].appendChild(document.createElement('script')).src = 'http://bookmarklet.example.com/js/bookmarklet.js?v='+month+'-'+day+'-'+year}());


texts: "Up" script for moving up directories quickly

texts:
A long time ago I created a script for moving up directories very quickly in the command line using the command up. You can find usage notes here.

It's a very simple script with just 8 lines of source code, as follows:

if [ -z "$1" ]; then
    cd ..
else
    for i in `seq 1 $1`;
    do
        cd ..
    done
fi

I've never personally had any problems with it since I made it and started using it myself — but are there any accidental or malicious inputs (particularly with the blind injection of $1) that might cause this to do something bad that I'm not aware of?

Given that the up command isn't used for anything in any command line I'm aware of, I'd like to promote more widespread usage of this script file so that people can type up instead of cd .. all the time, saving three keystrokes (or more if they want to move up more directories) for a very common operation.


texts: Creating 28 checkboxes with a common name and different values

texts:
There are 28 check boxes that are given a common name and have different values:

<input type="checkbox" name="Schedules" id="checkbox1" value="1">

In controller in post action:

public ActionResult Create(SubscriptionPlanCreateViewModel subscriptionPlanCreateViewModel, FormCollection Form)
{
    string[] AllStrings = Form["Schedules"].Split(',');
    foreach (string item in AllStrings)
    {
        int value = int.Parse(item);
        if (value == 1)
        {
            subscriptionPlanCreateViewModel.Timeschedule = "OneTime";
        }
    }
}

By using this code I need to use 28 if conditions. How can I reduce the code size?


texts: Facility to run code explicitly implemented in a base class that does not follow CA1033

texts:
Sometimes when working with components created by a library vendor such as DevExpress you want to extend the components. Good vendors will leave plenty of virtual methods for you to put to use, but once in a while you need to hook into an interface method call in a class that implements the method explicitly. You can simply reimplement the interface method, but nine times out of ten you will still want to call the base implementation as though it were virtual. As a matter of fact, it should have been virtual (CA1033).

In the meantime, the base implementation is private and you need to use reflection. This class mitigates some of that nuisance so that you don't have to hand-roll reflection code. It hands you an object implementing the interface that calls directly into the private base implementation methods.

An example is worth a thousand explanations:

interface IExampleInterface
{
    string InterfaceMethod();
}

class BaseClass : IExampleInterface
{
    // The authors of BaseClass did not follow CA1033: Interface methods should be callable by child types
    string IExampleInterface.InterfaceMethod()
    {
        return "BaseClass implementation";
    }
}

sealed class CustomizedClass : BaseClass, IExampleInterface
{
    // We have no choice but to override by implementing the method.
    string IExampleInterface.InterfaceMethod()
    {
        // Now in order to access the base explicit implementation, we use the class below:
        return LanguageUtils.ExplicitImplementation<BaseClass, IExampleInterface>(this).InterfaceMethod() + " has been customized.";
    }
}

Surprisingly, there's barely any code:

public static class LanguageUtils
{
    public static TInterface ExplicitImplementation<TBase, TInterface>(TBase @this)
        where TBase : TInterface
        where TInterface : class
    {
        return (TInterface)new ExplicitImplementationProxy(typeof(TBase), @this).GetTransparentProxy();
    }

    private sealed class ExplicitImplementationProxy : RealProxy, IRemotingTypeInfo
    {
        private readonly Type baseType;
        private readonly object instance;

        public ExplicitImplementationProxy(Type baseType, object instance) : base(typeof(MarshalByRefObject))
        {
            this.baseType = baseType;
            this.instance = instance;
        }

        public bool CanCastTo(Type fromType, object o)
        {
            return fromType.IsInterface && fromType.IsAssignableFrom(baseType);
        }

        public string TypeName { get; set; }

        public override IMessage Invoke(IMessage msg)
        {
            var methodCall = msg as IMethodCallMessage;
            if (methodCall == null) throw new NotSupportedException();

            var map = baseType.GetInterfaceMap(methodCall.MethodBase.DeclaringType);
            var args = new object[methodCall.Args.Length];
            Array.Copy(methodCall.Args, args, args.Length);
            return new ReturnMessage(map.TargetMethods[Array.IndexOf(map.InterfaceMethods, (MethodInfo)methodCall.MethodBase)].Invoke(instance, args), args, args.Length, methodCall.LogicalCallContext, methodCall);
        }
    }
}


texts:
The code is correct, passes all testcases, I am looking for input on cleaning it, readability etc

def  insertionSort(a)
    return if a.nil? || a.empty? || a.length == 1
    sort_index = 0
    for i in 1..a.length-1 do
        for j in 0..sort_index do
            next if a[i] > a[j]
            temp = a[i]
            sort_index.downto(j) do |n|
               a[n+1] = a[n]
            end
            a[j] = temp
        end
        sort_index +=1
    end
  a
end


texts: Generating Table Sections from A Property in a List of Objects

texts:
I'm working on a Xamarin application and I'm presenting a list of objects in a TableView that are grouped by a specific property of the object.

The property is a date. For each distinct date, I am creating a table section with a header containing said date. Below is the working code to accomplish this, but It's not very elegant.

    var trades = new List<ViewCell>();
    Dictionary<string, List<ViewCell>> dict = new Dictionary<string, List<ViewCell>>();

    // organizing each object into a dictionary with a key that
    // represents the table header and value for the sections objects
    foreach (var item in completed)
    {
        var date = item.DateClosed.ToString("MMMM dd yyyy");

        if (dict.ContainsKey(date))
        {
            dict[date].Add(new TradeCell(item));
        }
        else {
            dict[date] = new List<ViewCell> { new TradeCell(item) };
        }
    }

    // looping through the resulting dict to assemble the table
    foreach (KeyValuePair<string, List<ViewCell>> entry in dict)
        _table.Root.Add(new TableSection(entry.Key) { entry.Value });

My Question

This gets the job done but I was hoping for a more elegant approach, perhaps using linq?


texts:
I wrote this program as a start towards implementing the game Scattergories.  I had a problem with the _sleep command so I used Sleep in the windows.h library.

Eventually, I would like to add a way to either check if a word is correct, or to suggest words, and to activate a sound when the timer is done.

// A program to keep track of points and time and to give a random letter for the game scattergories

#include<iostream>
#include<Windows.h>
using std::cout;
using std::cin;

void ltr()    //gives a random letter
{
    char letter;
    letter = rand() % 27 + 64;         //assigns a random letter in ascii code to a char (resulting in a random letter)
    cout << "The letter is " << letter << "\n";
}

void clock()   //timer
{
    cout << "You got 1.5 minutes to finish\n";
    for (int i = 90; i > 0; i--)
    {
        if (i % 5 == 0)
            cout << i << "\n";
        Sleep(1000);
    }
    cout << "DING DONG!!! DING DONG!!! Time's up!!!\n";
}

int points()        //points per round
{
    int a, b, c, sum;
    cout << "How many sections only you got?\n";          //worth 15 points
    cin >> a;
    cout << "How many words only you got?\n";       //worth 10 points
    cin >> b;
    cout << "How many words you and another person got?\n";    //worth 5 points
    cin >> c;
    sum = a * 15 + b * 10 + c * 5;
    return sum;           //Note: It doesn't matter how many sections there are.
}

int act()
{
    int Points;
    ltr();
    clock();
    Points=points();
    cout << "You have earned " << Points << " this round\n\n";
    return Points;
}

int main()
{
    int Points;
    cout << "Starting in five seconds\n";
    Sleep(5000);
    Points = act();
    for (;;)          //inf loop
    {
        int ph;
        cout << "Press 1 to continue or 2 to stop\n";
        cin >> ph;
        if (ph == 1)
        {
            Points += act();
        }
        else
        {
            break;
        }
    }
    cout << "You have earned a total of " << Points << " great job!\n\n";
    system("pause");
}


texts: Reduce code complexity by applying ternary operator

texts:
I have a condition in my code where I need to put a lot of nested else if statements.  However, I have managed to reduce some if cases by applying ternary operator, so that code looks nice and is readable. But still I am not satisfied with the result. I would like to remove rest of the if cases too and make the code better.

Can anyone suggest more optimization in this code block?

if (!string.IsNullOrEmpty(SessionValues.AccessToken))
    {
        eventstatuscode = "logged";
        EventStatus eventStatus = rb.GetEventStatus();
        if (eventStatus != null)
        {
            if (!string.IsNullOrEmpty(eventStatus.cancelDate))
            {
                eventstatuscode = DateTime.Parse(eventDetails.signUpDeadline) < DateTime.Now ? "expired": eventstatuscode;

            }

            else if (string.IsNullOrEmpty(eventStatus.cancelDate))
            {
                eventstatuscode = eventStatus.onWaitingList ? "waitinglist" : eventstatuscode;
                eventstatuscode = eventStatus.onWaitingList == false ? "accepted" : eventstatuscode;

            }
        }
        else
        {
            eventstatuscode = DateTime.Parse(eventDetails.signUpDeadline) < DateTime.Now ? "expired" : eventstatuscode;
        }
    }


texts: Finding the number of integers between 1 and K, who's sum of the digits is a multiple of D

texts:
Good day. So, I need to find the number of integers between 1 and K (inclusive) satisfying the following condition, modulo (10^9)+7:

  The sum of the digits in base ten is a multiple of D

Here is my code:

k = int(input())
d = int(input())
count = 0

for i in range(1,k+1):
  hello = sum(list(map(int,str(i))))
  if (hello%d == 0):
    count += 1

print (count)

Basically, what the above code does is:

Takes as input two numbers: k & d.
Defines a counter variable called count, set to the default value of 0.
Iterates over all numbers in the given range: 1 to k.
If any number the sum of any number in the above range is a multiple of d, then it adds to the counter count by 1.
And then, at the end, finally, it outputs the count, meaning the number of integers between 1 and K, that have their sum of digits as a multiple of D.

Now, this code works just fine, but I am seeking to make it run for any number until 10^10000 in 1 second or less.

EDIT:

The actual problem that I am trying to solve can be found here: Digit Sum - DM::OJ

Thank you.


texts: Ruby methods to enable and disable attributes

texts:
I have a Ruby code segment which I need to DRY up. Can it be done without meta programming?

def disable_attribute
  statement1
  @response = Client::Service.disable_attribute(
    param1: param1value,
    param2: param2value
  )
  statement2
end

def enable_attribute
  statement1
  @response = Client::Service.enable_attribute(
    param1: param1value,
    param2: param2value
  )
  statement2
end


texts: Notifying Students in Courses - Strategically

texts:
I have the following implementation, and hope to get suggestions on how to improve the code.

treeListViewModel.Courses is an observablecollection
treeListViewModel.Courses[i].Students is a dictionary

The code loops as follows:

        List<uint> DataNotificationList = new List<uint>()
        {
            2,
            6,
            9
        };

        for (int n = 0; n < DataNotificationList.Count; n++)
        {
            for (int i = 0; i < treeListViewModel.Courses.Count; i++)
            {
                if (treeListViewModel.Courses[i].Students.ContainsKey(DataNotificationList[n]))
                {
                    treeListViewModel.Courses[i].Students[DataNotificationList[n]].ExecuteStrategy(hasError());
                    break;
                }
            }
        }


texts: Determine row from grid search style matrix

texts:
I'm doing some work with optimal design of experiments, related to the Federov Coordinate Exchange algorithm. This considers a candidate set of points and chooses from them to identify the best combination of points. The problem is, there are scenarios where there are 5^18 (nearly 4 trillion) candidates - there's no way I can pre-compute the whole grid and iterate over it. My thinking was to create a 'virtual' grid and pass in what row I'm on to obtain the correct combination of values. In a simple 2^3 example (3 features, 2 levels each) the grid would look like [[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 1, 1], [1, 0, 0], [1, 0, 1], [1, 1, 0], [1, 1, 1]]

The pattern is pretty easy, for the first column you figure out which half of the data you're in, get the index, subset the matrix, move onto the next column, etc. So I wrote a recursive function that does this for any number of features k and any number of levels d. Unsurprisingly, it's very slow compared to pre-computing the grid (when possible). Are there are opportunities to improve the algorithm as I have it here, or, are there other approaches I should consider which are superior to recursion?

def virtual_grid(i, k, d, current_k=1, min_val=0, max_val=None, result=None):
    """
    Pull points from a virtual grid
    :param i: which row of the virtual grid
    :param k: how many features (columns) in the grid
    :param d: how many equally spaced values for feature (density)
    :param current_k: which column is currently being iterated over?
    :param min_val: initially 1, used to modify the search space
    :param max_val: initially d**k, used internally to modify the search space
    :param result: placeholder for final results
    :return: list of values for this particular point in the grid
    """
    if max_val is None:
        max_val = d**k-1
    space = np.linspace(min_val, max_val, d+1)
    position = [ind for ind, val in enumerate(space[1:]) if i <= val][0]
    if result is None:
        result = [position]
    else:
        result.append(position)
    if current_k == k:
        return result
    else:
        return virtual_grid(i=i, current_k=current_k+1, k=k, d=d,
                            min_val=np.ceil(space[position]),
                            max_val=np.floor(space[position+1]),
                            result=result)


texts:
How would one optimize this code?

import java.util.*;
public class VendingMachineAssignement {

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

        double item1 = 1.25;
        double item2 = .75;
        double item3 = .90;
        double item4 = .75;
        double item5 = 1.50;
        double item6 = .75;

        System.out.print("Enter an item number: ");
        int item = keyboard.nextInt();

        System.out.print("Enter the amount paid: ");
        double paid = keyboard.nextDouble();

        if (item == 2 || item == 4 || item == 6)
        {
            if (paid >= item2)
            {
                System.out.println("Thank you for buying item " + item + ", your change is $" + (paid-item2) + ". Please come again!");
            }
            if (paid < item2)
            {
                System.out.println("Please insert another " + "$" + (item2-paid));
            }
        }

        else if (item == 1)
        {
            if (paid >= item1)
            {
                System.out.println("Thank you for buying item " + item + ", your change is $" + (paid-item1) + ". Please come again!");
            }
            if (paid < item1)
            {
                System.out.println("Please insert another " + "$" + (item1-paid));
            }
        }
        else if (item == 3)
        {
            if (paid >= item3)
            {
                System.out.println("Thank you for buying item " + item + ", your change is $" + (paid-item3) + ". Please come again!");
            }
            if (paid < item3)
            {
                System.out.println("Please insert another " + "$" + (item3-paid));
            }
        }
        else if (item == 5)
        {
            if (paid >= item5)
            {
                System.out.println("Thank you for buying item " + item + ", your change is $" + (paid-item5) + ". Please come again!");
            }
            if (paid < item5)
            {
                System.out.println("Please insert another " + "$" + (item5-paid));
            }
        }

    }

}

And also, for example, if I enter 5 for item and .10 for paid, then why does it say Please insert another $1.4 instead of 1.40? Even though 1.50 - 1.4 and 1.50 - 1.40 would be the same, how come it does not display 1.40?


texts: Adding a bulk of items in the middle of a sparse array

texts:
I'd like to add a bulk of items into a sparse array, starting at a certain index.
I came along this requirement in order to accomplish client side pagination while not retrieving all data from server (assuming server returns the right data, given the required indexes).

To keep right indexes when "Skipping" and "Taking", I need to store the items in a sparse array. Besides relevant indexes, other places in array might as well be undefined.

I wrote the following snippet of code, assuming bulk is the retrieved chunk of items from Server, and index is where the first item should be placed.

    items = new Array(totalItemsPossibleCount);
    items = items.slice(-index)
                 .concat(bulk)
                 .concat(items.slice(index+bulk.length));

Is there a shorter way to do so?
Can this be achieved with underscore.js in more readable way?


texts:
Puzzle Description:

  A number is called lucky if the sum of its digits, as well as the sum
  of the squares of its digits is a prime number. How many numbers
  between A and B are lucky?

How can I improve performance of the following code?

import java.util.Scanner;

public class lucky_num {

    public static void main(String[] args) {

        lucky_num sr = new lucky_num();
        Scanner scanner = new Scanner(System.in);
        int no_cases = scanner.nextInt();
        for (int i = 0; i < no_cases; i++) {
            System.out.println(sr.solve(scanner.nextLong(), scanner.nextLong()));
        }
    }

    private int solve(long l, long m) {
        int count = 0;
        for (long i = l; i <= m; i++) {
            if (logic(i)) {
                count++;
            }
        }
        return count;
    }

    private boolean logic(long i) {
        return (isSUM(i) && isSUMsq(i));
    }

    private boolean isSUMsq(long i) {
        int sum = 0;
        while (i > 9) {
            long k = i % 10;
            i = i / 10;
            sum += k * k;
        }
        sum += i * i;
        return (isPrime(sum));
    }

    private boolean isSUM(long i) {
        int sum = 0;
        while (i > 9) {
            long k = i % 10;
            i = i / 10;
            sum += k;
        }
        sum += i;
        return (isPrime(sum));
    }

    private boolean isPrime(int num) {
        if(num==2)
        return true;
        // check if n is a multiple of 2
        if (num % 2 == 0 || num==1 )
            return false;
        // if not, then just check the odds
        for (int i = 3; i * i <= num; i += 2) {
            if (num % i == 0)
            return false;
        }
        return true;
    }
}

Sample input:

2
1 20
120 130

Sample output:

4
1

Constraints:

1 <= T <= 10000
1 <= A <= B <= 10^18


texts:
I created a quick calculator in Javascript and I was wondering if there was a way to make the code look prettier or make it simpler. To me, it looks really cramped and messy and I'm not sure how change that.

function calc() {
    var height = (document.getElementById('height').value) / 100;
    var weight = document.getElementById('weight').value;

    var output = document.getElementById('output');
    var bmi = Math.round((weight / Math.pow(height, 2)) * 10) / 10;

    var result = document.getElementById('result');
    var text = "";
    if (height != "" && weight != "") {
        if (bmi != "NaN" && bmi != 0) {
            if (bmi % 1 != 0) {
                output.innerHTML = bmi;
            } else {
                output.innerHTML = bmi + ".0";
            }
            if (10 <= bmi && bmi < 14) {
                text = "You are seriously underweight!";
            } else if (15 <= bmi && bmi < 18.5) {
                text = "You are slightly underweight.";
            } else if (18.5 <= bmi && bmi < 25) {
                text = "You are healthy!";
            } else if (25 <= bmi && bmi < 30) {
                text = "You are slightly overweight.";
            } else if (30 <= bmi && bmi < 40) {
                text = "You are obese!";
            } else if (40 <= bmi && bmi < 50) {
                text = "You are seriously obese!";
            } else {
                text = "You should be dead...";

            }

            result.innerHTML = text;
        }
    }
}


texts: Robots files generation - simplifying foreach code

texts:
I'm trying to figure out if there's a way I can simplify this code which is used to generate a robots.txt file with numerous rules.  Different files/folders are separated in separate arrays because they're applied differently but in some cases they are applied the same.  In these cases, rather than write out a separate foreach for each one, this is what I'm trying to simplify:

<?php

public function generateRobotsFile($rbfile, $smfile) {
    $tab = array();
    $tab['SemBot'] = array('Googlebot',"bingbot\nCrawl-delay: 5",'MSNBot');

    $tab['Lang'] = array('eb');
    $tab['Files'] = array('address.php','cart.php');
    $tab['Folder'] = array('classes','docs','themes');

    fwrite($writeFd, "\nUser-agent: *\n");
    foreach ($tab['Lang'] as $Lang) {
        fwrite($writeFd, 'Disallow: ' . __PS_BASE_URI__ . $Lang . "\n");
    }
    foreach ($tab['Folder'] as $Folder) {
        fwrite($writeFd, 'Disallow: ' . __PS_BASE_URI__ . $Folder . "\n");
    }

    foreach ($tab['SemBot'] as $SemBot) {
        fwrite($writeFd, "User-agent: ' . $SemBot . "\n");
        foreach ($tab['Files'] as $Files) {
            fwrite($writeFd, 'Disallow: ' . __PS_BASE_URI__ . $Files . "\n");
        }
        foreach ($tab['Folder'] as $Folder) {
            fwrite($writeFd, 'Disallow: ' . __PS_BASE_)URI__ . $Folder . "/\n");
        }
    }

The arrays must remain separated but in some cases they are looped through the same disallow rule so I'm reaching for a foreach array in array but haven't quite grasped it yet.


texts:
Can you guys review my GraphQL search pagination function? I'm afraid there could be some performance issues, or something. Especially at the aggregation section and this const result: any = await this.BooksModel.findOne( section.
I'm using MongoDB as the database and string ISO Date as cursor.
I tried looking for any search pagination example on the internet but found none.
async getBooks({
    first,
    after,
    last,
    before,
    search,
}: {
    first?: number | null
    after?: string | null
    last?: number | null
    before?: string | null
    search?: string | null
}) {
    if (first && last)
        throw new AppError(
            '`first` and `last` cannot be used at the same time',
            400,
        )
    if (!first && !last)
        throw new AppError('Either `first` or `last` is required', 400)
    if (after && before)
        throw new AppError(
            '`after` and `before` cannot be used at the same time',
            400,
        )
    if (search && last)
        throw new AppError('`search` and `last` is not allowed', 400)

    if (search) {
        let score = null
        if (after) {
            const date = new Date(after)
            const result: any = await this.BooksModel.findOne(
                {
                    created: date,
                    $text: { $search: search },
                },
                { score: { $meta: 'textScore' } },
            )
            score = result._doc.score
        }

        const filter = { score: { $lt: score } }
        const limit = first ? first : last!

        const books = await this.BooksModel.aggregate([
            { $match: { $text: { $search: search } } },
            { $addFields: { score: { $meta: 'textScore' }, id: '$_id' } },
            ...(score ? [{ $match: filter }] : []),
            { $sort: { score: { $meta: 'textScore' } } },
            { $limit: limit },
        ])

        return books
    } else {
        const sort = { created: first ? -1 : 1 }
        const limit = first ? first : last!

        const books = await this.BooksModel.find({
            ...(after ? { created: { $lt: new Date(after) } } : null),
            ...(before ? { created: { $gt: new Date(before) } } : null),
        })
            .sort(sort)
            .limit(limit)
            .exec()

        return books
    }
}
```


texts: Modifying the affine transform origin in graphics2D

texts:
As a project I have written a graphics library for educational use to allow kids at my high school to make Java games without directly dealing with to the Java graphics API. I'm in the final stages, tweaking mainly for performance and readability, and I would like some input on how I handle transformations.

The idea of the origin mode is to improve usabilty, making the drawn objects transform (and be drawn) about the most logical point, that being the specified origin point.

My main concern is that every time the origin modification runs, it creates a new AffineTransformation object, which means it quickly eats an unnecessary amount of memory, as it runs every time an object is drawn. Other than that, if you see any issues, or have any stylistic suggestions, they would be appreciated.

The relevant code to the transformation modifications, and the drawing pipeline is as follows. For sanity's sake I have omitted the set-up code and any setters and getters.

private Rectangle2D bounds = new Rectangle2D.Double();
private AffineTransform postTransform = new AffineTransform();

private boolean correct; // these are all user-set in provided setters
private int origin;
protected int plane; // protected because mouse detection needs access
private AffineTransform transform;

private void applyOrigin(Shape shape) {
    applyOrigin(shape.getBounds2D());
}

private void applyOrigin(RectangularShape shape) {
    bounds.setRect(shape.getX(), shape.getY(), shape.getWidth(), shape.getHeight());
    applyOrigin();
}

private void applyOrigin() {
    double x = -bounds.getX();
    double y = -bounds.getY();
    double p = (plane == DCanvas.PLANE_DEFAULT)? bounds.getY(): getHeight()-bounds.getY(); // getHeight = get height of drawing surface

    switch (origin) {
    case ORIGIN_LEFT:
    case ORIGIN_CENTER:
    case ORIGIN_RIGHT:
        y -= bounds.getHeight()/2;
        break;
    case ORIGIN_BOTTOM_LEFT:
    case ORIGIN_BOTTOM:
    case ORIGIN_BOTTOM_RIGHT:
        y -= bounds.getHeight();
        break;
    }

    switch (origin) {
    case ORIGIN_TOP:
    case ORIGIN_CENTER:
    case ORIGIN_BOTTOM:
        x -= bounds.getWidth()/2;
        break;
    case ORIGIN_TOP_RIGHT:
    case ORIGIN_RIGHT:
    case ORIGIN_BOTTOM_RIGHT:
        x -= bounds.getWidth();
        break;
    }

    if (plane == DCanvas.PLANE_CARTESIAN) switch (origin) {
    case ORIGIN_TOP_LEFT:
    case ORIGIN_TOP:
    case ORIGIN_TOP_RIGHT:
        y -= bounds.getHeight();
        break;
    case ORIGIN_BOTTOM_LEFT:
    case ORIGIN_BOTTOM:
    case ORIGIN_BOTTOM_RIGHT:
        y += bounds.getHeight();
        break;
    }

    if (correct) {
        x += 0.5;
        y += 0.5;
        if (plane == DCanvas.PLANE_CARTESIAN) y -= 1;
    }

    postTransform.setToTranslation(x, y);
    postTransform.preConcatenate(transform);
    postTransform.preConcatenate(AffineTransform.getTranslateInstance(bounds.getX(), p)); // this is the line I am most concerened with
    graphics.setTransform(postTransform); // graphics object to draw on surface
}

public synchronized void draw(Shape shape) {
    applyOrigin(shape);
    graphics.draw(shape); // graphics object to draw on surface
}


texts:
I have this code here which varies depending on the system architecture (typed arrays depends on endianness). I'm trying to get a 32bit ARGB data array. I was trying to learn DataView, which has a nice way of dealing with "endian-ness".

Can you please help to revise this to use DataView, while working basically as close to the logic as the code below currently follows?

Documentation on DataView: MDN :: DataView

// Getting pixels as a byte (uint8) array
var imageData = ctx.getImageData(0, 0, can.width, can.height);
var pixels8BitsRGBA = imageData.data;

// Reverting bytes from RGBA to ARGB
var pixels8BitsARGB = new Uint8Array(pixels8BitsRGBA.length + 8); // +8 bytes for the two leading 32 bytes integers
for(var i = 0 ; i < pixels8BitsRGBA.length ; i += 4) {
    pixels8BitsARGB[i+8 ] = pixels8BitsRGBA[i+3];
    pixels8BitsARGB[i+9 ] = pixels8BitsRGBA[i  ];
    pixels8BitsARGB[i+10] = pixels8BitsRGBA[i+1];
    pixels8BitsARGB[i+11] = pixels8BitsRGBA[i+2];
}

// Converting array buffer to a uint32 one, and adding leading width and height
var pixelsAs32Bits = new Uint32Array(pixels8BitsARGB.buffer);
pixelsAs32Bits[0] = can.width;
pixelsAs32Bits[1] = can.height;

console.log(pixelsAs32Bits);


texts:
Due to software constraints, I cannot use the standard libraries, cmath, algorithm, templates, inline, or boost. I am also using standard C (ISO C99) such that array is not a reserved keyword like it is in Visual Studio.

Here is the custom sine, pow and factorial functions I wrote (assume they are all part of the same namespace and not using cmath). I looking for suggestions to improve robustness and efficiency. For example, both the pow and factorial are constrained by the int i in the for loops.

double factorial(double x)
{
    double result = 1;
    for (int i=1;i<=x;i++)
        result *= i;
    return result;
}

double pow(double x,double y)
{
    double result = 1;
    for (int i=0;i<y;i++)
        result *= x;
    return result;
}

double sine_taylor(double x,double n)
{
    double sine = x;
    bool isNeg;
    isNeg = true;
    for (double i=3;i<=n;i+=2)
    {
        if(isNeg)
        {
            sine -= pow(x,i)/factorial(i);
            isNeg = false;
        }
        else
        {
            sine += pow(x,i)/factorial(i);
            isNeg = true;
        }
    }
    return sine;
}

int main()
{
   const double pi = 3.14159265;
   double sineTaylor = sine_taylor(pi/2,7);
}


texts: Finding the longest substring in a string

texts:
I am writing Python code to find the longest substring in a string which is an alphabetical order. I tried to minimize the number of loops to a single for loop.

Any improvements would be appreciated. Any details about the complexity of this algorithm would also be welcome, because I don't know Big-O notation all too well.

substr = '';
final_substr = '';

for index, char in enumerate(s):
    if index < len(s) - 1:
        #print('Comparing %s and %s'% (char, s[index+1]));
        if ord(char) <= ord(s[index + 1]):
            substr += char;
            print(substr);
        else:
            substr += char;
            if len(final_substr) < len(substr):
                final_substr = substr;
            substr = '';

print('Longest substring in alphabetical order is: '+final_substr);


texts: PHP database class - Managing two connections with different privileges

texts:
I'm just trying to master the art of using classes in PHP and have come across a concern.

For security reasons, I sometimes use two database connections in my application; one with read-only privileges and one with full read/write. Unfortunately, I wasn't really thinking about this when I started to build a few classes.

So, I have a database class, which is essentially a pointless PDO wrapper (pointless because PDO is a wrapper), but thought it'd be good practice to write one anyway and I may extend PDO later too. This is what I did:

<?php
class Database {

    private $dbh;

    public function __construct($accessLevel = NULL, $credentials = NULL) {
        if (gettype($credentials) === 'array') {
            $dsn = 'mysql:host='.$credentials['dbHost'].';dbname='.$credentials['dbName'];
            $options = array (
                PDO::ATTR_PERSISTENT => false,
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
            );
            if ($accessLevel == "public") {
                $this->dbh = new PDO($dsn, $credentials['publicUser'], $credentials['publicPassword'], $options);
            } else if ($accessLevel == "private") {
                $this->dbh = new PDO($dsn, $credentials['privateUser'], $credentials['privatePassword'], $options);
            }
        }
    }

    // other database functions

}
?>

For a public connection (read/write), I simply used this:

$db = new Database('public', config['dbConfig']);

... or for a private connection (read-only), I used this:

$db = new Database('private', config['dbConfig']);

... and when I wanted to use the connection in another class, I simply injected the connection, like so:

$user = new User($db);

Works fine, but then I realised that I may need two connections inside that class, one for reading only and one for all. So I got a little confused, but had a go regardless. This is what I did:

Instead of calling the class with either of the connections, I called the class twice with both, like so:

$publicDB = new Database('public', $config['db']);
$privateDB = new Database('private', $config['db']);

and then injected both of those to my other class:

$user = new User($publicDB, $privateDB);

Inside this User class, this how I used the two connections:

<?php
class User {

    private $dbh;
    private $dbhp;

    public function __construct($publicDatabase = NULL, $privateDatabase = NULL) {
        $this->dbh = $publicDatabase;
        $this->dbhp = $privateDatabase;
    }

    public function doSomething() {
        $this->dbh->query("INSERT INTO......");
        $this->dbh->bind(':userInput', $userInput);
        $this->dbh->execute();
    }

    public function doSomethingSafely() {
        $this->dbhp->query("SELECT * FROM......");
        $this->dbhp->bind(':userInput', $userInput);
        $results = $this->dbhp->resultset();
    }
}
?>

Right, this actually works fine but I'm worried it's not the acceptable method or it may cause problems later down the road. I have a few questions:

Is using two connections with different privileges still considered good practice? Even though I'm properly escaping and validating my data and binding the values using PDO?
If yes for above, is there a better way to manage the two connections for using in many classes or is what I have done acceptable?


texts: A simple template engine to display value

texts:
For a specific usage I made a very simple template engine in Python, to display value. The code:

import re

class Template(object):
    """A simple template engine support only the substitute of variable"""
    def __init__(
            self, delimiter_start='[', delimiter_end=']',
            identifier=r'^[^\d\W]\w*$'):
        """To initialize the template class.

        @param delimiter_start: To specify the delimiter start (default [)
        @type param: str

        @param delimiter_end: To specify the delimiter stop (default ])
        @type param: str

        @param identifier: Identifier for variable name (default ^[^\d\W]\w*$)
        @type param: str
        """
        self.delimiter_start = delimiter_start
        self.delimiter_end = delimiter_end
        self.identifier = re.compile(identifier, re.UNICODE)

    def substitute(self, string, template={}):
        """To substitute the string.

        @param string: The string to substitute
        @type string: str

        @param template: The template
        @type string: dict

        @return:  The string substitute
        @rtype :  str

        @raise ValueError:  Identifier is not valid
        """
        words = string.split(" ")

        for index, word in enumerate(words):
            if word.startswith(self.delimiter_start) \
                    and word.endswith(self.delimiter_end):
                        word_without_delimiter = word[1:-1]
                        result = re.match(
                            self.identifier, word_without_delimiter)

                        if result is None:
                            raise ValueError(
                                'The identifier is not a valid identifier')

                        if word_without_delimiter not in template:
                            continue

                        words[index] = '{value}'.format(
                            value=template[word_without_delimiter])

        return ' '.join(words)

And the test:

import unittest

from passport.passport import Template

class TemplateTestCase(unittest.TestCase):
    """To test the template"""
    def setUp(self):
        self.template = Template()

    def test_simple(self):
        string = "To try only [var] it's display correctly"
        result = self.template.substitute(string, {'var': 'if'})

        self.assertEqual("To try only if it's display correctly", result)

    def test_multiple_variable(self):
        string = "To try only [var] it's [other_var] correctly"
        result = self.template.substitute(string, {
            'var': 'if', 'other_var': 'display'})

        self.assertEqual("To try only if it's display correctly", result)

    def test_one_word(self):
        string = '[var]'
        result = self.template.substitute(string, {'var': 'Try'})

        self.assertEqual('Try', result)

    def test_without_template(self):
        string = 'Try without a template in string no substitute'
        result = self.template.substitute(string, {'var': 'Try'})

        self.assertEqual(string, result)

    def test_with_other_delimiter(self):
        template = Template(delimiter_start='{', delimiter_end='}')
        string = "To try only {var} it's display correctly"
        result = template.substitute(string, {'var': 'if'})

        self.assertEqual("To try only if it's display correctly", result)

    def test_key_is_not_present(self):
        string = "To try only [var] it's display correctly"
        result = self.template.substitute(string)

        self.assertEqual("To try only [var] it's display correctly", result)

    def test_with_invalid_identifier(self):
        string = '[42var]'

        with self.assertRaises(ValueError):
            self.template.substitute(string, {'42var': 'Try'})

New methods will be added soon, for example add some take a file and not a string.


texts:
I'm relatively new to Python. I just want some constructive feedback on how to improve my code efficiency, style, error handling, etc.

In this case, I've programmed the Ackermann function, but it won't evaluate well since it's built to handle the recursions relatively poorly - I'll have to fix that in the future. Any tips?

Also, if there are any areas of exploitation in the errors, please let me know too.

For reference, I'm programming this on Ubuntu 16.04 LTS and the language is Python 2.7.12

# Make sure the collected values are of the appropriate forms
def collection ():
    while True:
        # Collect raw_input for m_val and n_val
        m_val = raw_input ("Please enter a nonnegative integer (m) : ")
        n_val = raw_input ("Please enter another nonnegative integer (n): ")

        # Make sure input is acceptable
        try:
            m_val = float(m_val)
            n_val = float(n_val)

            # m_val needs to be a nonnegative integer
            # Check equivalence to 0 first
            if m_val == 0:
                pass
            # Then check if the value is nonintegral
            elif int(m_val) - m_val:
                print("\nYou entered a float for m!\n")
                continue
            # Then make sure the value is nonnegative
            elif m_val < 0:
                print("\nYou entered a negative value for m!\n")
                continue

            # n_val needs to be a nonnegative integer
            # Check equialence to 0 first
            if n_val == 0:
                pass
            # Then check if the value is nonintegral
            elif int (n_val) - n_val:
                print("\nYou enterd a float for n!\n")
                continue
            # Then make sure the value is nonnegative
            elif n_val < 0:
                print("\nYou entered a negative value for n!\n")
                continue

            # If the code makes it this far, it should be ready for return
            return int(m_val), int(n_val)

        except ValueError:
            print("\nPlease enter numerical values for m and n.\n")

def ackermann(m,n):
    if m == 0:
        return n + 1
    elif m > 0 and n == 0:
        return ackermann(m-1,1)
    elif m > 0 and n > 0:
        return ackermann (m-1, ackermann(m,n-1))
    else:
        print "The Value Doesn't Go into the Domain!"

(m,n) = collection()
print ( ackermann(m,n) )


texts: Helper function to return a string based on passed object and some defined rules

texts:
In my application, a notification should be displayed when a chat message arrives.  There are some rules which decide what notification message is to be displayed.

I have created a helper method which takes a ChatMessage object and returns the message to be displayed in the notification.

How can I refactor or improve this piece of code? Any feedback will be appreciated.

private String getNotificationDisplayString(ChatMessage chat) {
    String message;
    boolean isUpdateMessage = (chat.getTag().equals(TAG_UPDATE_MSG));
    if (isUpdateMessage) {
        // for update message
        UserRelationshipInfo relationshipInfo = UserRelationshipInfoManger.getInstance().getInfo(chat.getUserId());
        boolean isUserMyFriend = (relationshipInfo != null && relationshipInfo.getSource() == SOURCE_FRIEND);
        message = Resources.string(isUserMyFriend ? R.string.text_user_is_friend : R.string.text_user_is_stranger);
    } else {
        boolean isDirectMessage = (chat.getType() == DIRECT_MESSAGE);
        boolean isTextMessage = (chat.getTag().equals(TAG_TEXT_MSG));

        if (isDirectMessage) {
            // for direct message (special case)
            String messageName = Resources.string(getMessageType(chat.getTag()));
            // message = "<name> sent you a direct <image/video/etc>"
            message = String.format(Resources.string(R.string.text_new_direct_message), chat.getUserInfo().getDisplayName(), messageName);
        } else if (isTextMessage) {
            // for text (non-direct)
            message = new TextInfo(chat).getText();
        } else {
            // for non-text (non-direct)
            // message = "<name> sent you a message"
            message = String.format(Resources.string(R.string.text_new_message), chat.getUserInfo().getDisplayName());
        }
    }
    return message;
}


texts: Python & C: Trying to create a dict of all declared variables and functions and their types of a .c source file

texts:
Basically trying to create a dict of all declared variables and functions along with their types of a .c source file. Does anyone think I missed anything?

#!usr/python
import string
import re
from types import *
from pprint import pprint

varDict = {}

def find_substring(needle, haystack):
    index = haystack.find(needle)
    if index == -1:
        return False
    if index != 0 and haystack[index-1] not in string.whitespace:
        return False
    L = index + len(needle)
    if L < len(haystack) and haystack[L] not in string.whitespace:
        return False
    return True

f = open('example.c')
varTypeList = []

for varType in open('typesfile.txt'):
        varTypeList.append(varType[:-1])

for line in f:
        for varType in varTypeList:
                if find_substring(varType,line):
                        var = re.search('\s*[\*_a-zA-Z]+[\*_a-zA-Z0-9]?', line.split(varType)[1])
                        if type(var) is not NoneType:
                                varDict[var.group(0)] = varType
pprint(varDict)


texts: Writing nested for loops to produce certain output

texts:
My task:

  Write nested for loops to produce the following output with each line
  48 characters wide:

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~+~~+~~+~~+~~+~~+~~+~~+~~+~~+~~+~~+~~+~~+~~+~~+~
+~++~++~++~++~++~++~++~++~++~++~++~++~++~++~++~+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

This is my idea, but I guess it's pretty much redundant. If so, how can I minimize redundancy here? My output is correct, by the way.

public class Exercises {
    public static void main (String[] args){

    for (int i = 1; i <= 4; i++){
        for (int j = 1; j <= 12; j++){
            System.out.print("~");
        }
    }
            System.out.println();
            System.out.print("~");

    for (int i = 1; i <=15; i++){
            System.out.print("+~~");
    }
            System.out.println("+~");
            System.out.print("+~");
    for (int i = 1; i <= 15; i++){
            System.out.print("++~");
        }
            System.out.println("+");

    for (int i = 1; i <= 4; i++){
        for (int j = 1; j <= 12; j++){
            System.out.print("~");
        }
    }
  }
}


texts: splitWith function for splitting a list doesn't seem optimal

texts:
As an exercise from RWH, I needed to write a function that splits a list every time the predicate is false (words == splitWith (== ' ') for strings):

splitWith :: (a -> Bool) -> [a] -> [[a]]
splitWith _ [] = []
splitWith p xs
    | null pre = splitWith p post'
    | otherwise = pre : splitWith p post'
    where
        (pre, post) = break p xs
        post' = if null post then [] else tail post

My concern is the if..then..else chain; it seems "forced". I have to make sure that post isn't null, or it will crash on the call to tail.

Is there a better way to write this?


texts:
In a module of a win forms application I have a hierarchy of classes like BaseRecovery, LoanRecovery and FineRecovery. Both LoanRecovery and FineRecovery inherits from BaseRecovery. All these models have one view called RecoveryForm where you can enter/view loans and fines of employees. and I'm planing to use single Presenter class called RecoveryPresenter which inherits from BasePresenter. We have a DataService Class for db transactions

LoanRecovery class looks like this...

Class LoanRecovery : BaseRecovery
{
    public string LoanID {get;set;}
    public DateTime IssueDate {get;set;}
    public Decimal Amount {get;set;}
    .
    .
    .
}

So I'd do the following in Programe.cs.

IBaseRcovery recovery=null;
IRecoveryForm recoveryForm = new RecoveryForm();
IDataService dataService = new DataService();

BasePresenter presenter = new RecoveryPresenter( recovery, recoveryForm, dataService );
presenter.Show(); // This will display the form recoveryForm

In the presenter I would say

public RecoveryPresenter( IBaseRecover model, IRecoveryForm view, IDataService dataService )
{
    this._Model = model;
    this._View = view;
    this._DataService = dataService;
    WireUpViewEvents();

}

Now lets say if I need to give a loan, I would run SetModelPropertisFromView() method in the BasePresenter class which use reflection. But before that I should pass an instance of LoanRecovery class (i.e. _Model) to that method together with _View. Like wise we can do same thing for all children classes as follows...

    public void Issue()
    {
        if (_View.Type == "Loan")
        {
            _Model = new LoanRecovery();
            SetModelPropertiesFromView(_Model, _View, _DataService);
            _dataService.InsertLoan(_Model); //Error
        }

        if (_View.Type == "Fine")
        {
            _Model = new FineRecovery();
            SetModelPropertiesFromView(_Model, _View, _DataService);
            _DataService.InsertFine(_Model); //Error
        }

        if (_View.Type == "Insurance")
        {
            _Model = new InsuranceRecovery();
            SetModelPropertiesFromView(_Model, _View, _DataService);
            _DataService.InsertFine(_Model); //Error
        }

    }

Everything is fine until the last line of the above if blocks. The issue is the data access method in the DataService class requires a child instance not a base class instance.

  public void InsertLoan( LoanRecovery loan)
    {
        using (SqlConnection sqlConnection = new SqlConnection(db.GetConnectionString))
        {
            SqlCommand sqlCommand = new SqlCommand("BEGIN INSERT INTO recovery ;
            sqlCommand.Parameters.Add("@empID", SqlDbType.Char).Value = loan.EmployeeID;
            sqlCommand.Parameters.Add("@loanType", SqlDbType.VarChar).Value = loan.Type;
            sqlCommand.Parameters.Add("@loanAmount", SqlDbType.Decimal).Value = loan.FullAmount;
            sqlCommand.Parameters.Add("@loanDuration", SqlDbType.Int).Value = loan.Duration;
            sqlConnection.Open();
            sqlCommand.ExecuteNonQuery();
        }
    }

So I solved the problem like this

    public void Issue()
    {
        if (_View.Type == "Loan")
        {
            LoanRecovery loanModel = new LoanRecovery(); //Creates a child instance
            SetModelPropertiesFromView(loanModel, _View, _DataService);
            _DataService.InsertLoan(loanModel);
        }
    }

Now it's working but my worry is that I'm not using the injected instance through the constructor rather newing a child object which creates a dependency. Can anybody propose a better design to solve this issue please?


texts:
The code I have put together achieves what I want, but I don't know if it is the right way to go about tackling the problem.

I am dealing with 2 tables (CLIENT, CLIENTTYPE) each of which I have an auto-generated entity for in my models folder. As I don't actually want to send all the data from each entity back to the user, I have created a viewmodel for each in a ViewModels folder.

A CLIENT can have multiple CLIENTTYPE, so I have created the a List property of ClientTypeViewModels in my ClientViewModel

    public ClientsWithTypesViewModel getClientAndTypesByCode(string code)
    {
        var x =
            from c in _context.Cases
            where c.ClientID == code
            select new ClientsWithTypesViewModel
            {
                ClientID = c.ClientID,
                Title = c.Title,
                Name = c.FullName,
                ClientTypes = (from w in _context.ClientTypes where w.ClientType == c.ClientType select new ClientTypeViewModel { ClientType = w.ClientType, Description = w.Description }).ToList()
            };
        return x.FirstOrDefault();
    }


texts: Return true if the elements of an array do not contain one or the other

texts:
I am gradually completing the CodingBat exercises for Java. Here is the one I just did:

  Given an array of ints, return true if it contains no 1's or it contains no 4's.

Here is my code:

public boolean no14(int[] nums) {

    int oneCount = 0;
    int fourCount = 0;

    for (int i = 0; i < nums.length; i++) {
        if (nums[i] == 1) {
            oneCount++;
        }
        if (nums[i] == 4) {
            fourCount++;
        }
    }

    if (oneCount > 0 && fourCount > 0) {
        return false;
    }
    return true;
}

Now, I am pretty unfamiliar with arrays, so I would just like to know if there is a simpler/shorter way of finding such information without setting a count for each number? Perhaps using a regular expression?