texts: Passing $_POST from view to model in MVC

texts:
I am building my own MVC structured project to learn the concepts of MVC and I need to pass $_POST variables from my view (which is a login form) to the model. Down below is my approach but I wonder if it is the correct way to do it or there is a better one for example passing it into the construct or maybe putting $_POST inside an array.. What do you think?

The login method is to generate a token for my login form in the view which is for the cookie

class Users
{

    protected $db;

    public function __construct()
    {
        $this->db = Database::instance();
    }

    public function login()
    {
        return self::genToken();
    }

    public function loginAction()
    {
        $username   = $_POST['username'];
        $password   = $_POST['password'];
        $rememberMe = $_POST['remember_me'];
        $token      = $_POST['token'];
        $redirect   = null;
        ...

    }
    public function genToken()
    {
       return md5(uniqid());
    }

Here is my view. (http://localhost/MVC/public/user/login)

<form id="login" method="post" action="http://localhost/MVC/public/user/loginAction" class="well">

        Username
        <input type="text" name="username" class="form-control" placeholder="">

        Password
        <input type="password" name="password" class="form-control" placeholder="Password">
        <input type="hidden" name="token" value="<?= $data['token'] ?>" />

Forget the password?

        <input type="checkbox" name="remember_me" value="1" checked /> Remember Me

    <button type="submit" class="btn btn-default btn-block" name="signin">Login</button>
</form>


texts: Closures power and concise style vs readability and maintainability?

texts:
Is large use of closures actually a bad thing for readability and maintainability of the code? For example, consider the following code with (comments removed on purpose):

$withMobile  = function($c) { return $c->getMobile() !== null; };
$extractAll  = function($c) { return $c; };
$extractId   = function($c) { return $c->getId(); };

$allUniqueCustomers = $data->customers->filter($withMobile)->map($extractAll);
$customersIds       = $allUniqueCustomers->filter($withMobile)->map($extractId)->toArray();

$isNew = function($c) use($customersIds) { return !in_array($c->getId(), $customersIds); };

foreach($data->tags as $tag) :
    foreach($tag->getCustomers()->filter($isNew)->filter($withMobile) as $newCustomer) :
        $allUniqueCustomers->add($newCustomer);
    endforeach;
endforeach;

$sanitize       = function($m) { return preg_replace("/^(\+|00)/", '', $m); };
$extractMobile  = function($c) use($sanitize) { return $sanitize($c->getMobile()); };

// Unique sanitized phone numbers of customers merged with customers from tags
$customersMobiles = $allUniqueCustomers->map($extractMobile);

It looks good to me. But i love closures.

Would you consider this a nightmare to maintain and change in future in respect of traditional more verbose programming with loops?


texts: Periodically run Bash Job A to conditionally restart Bash Job B based on output of Bash Job A

texts:
Is there any neater way I can accomplish the task (as in title)? Also, I'm not sure why asyncio.Task.all_tasks() explodes and whether this is bad or not.

from concurrent.futures import ProcessPoolExecutor
import asyncio
from contextlib import contextmanager
import random

@contextmanager
def event_loop():
    loop = asyncio.get_event_loop()
    with ProcessPoolExecutor(3) as executor:
        loop.set_default_executor(executor)
        yield loop
    loop.close()

async def start_long_proc(delay=0, *, started_event):
    await asyncio.sleep(delay)
    cmd = 'while true; do date >> temp.log; sleep 0.1; done;'
    proc = await asyncio.create_subprocess_shell(cmd)
    started_event.set()
    return proc

async def periodic_monitor():
    while True:
        n = random.randrange(100)
        cmd = f'echo "{n}"'
        proc = await asyncio.create_subprocess_shell(
            cmd, stdout=asyncio.subprocess.PIPE)
        stdout, stderr = await proc.communicate()
        yield int(stdout.decode().rstrip())

async def f():
    started_event = asyncio.Event()

    # run Bash Job B
    long_proc = await start_long_proc(started_event=started_event)

    p_terminate = 10
    monitor_interval = 1

    async for n in periodic_monitor():  # periodically run Bash Job A
        print(f'n={n}')
        if n < p_terminate:
            print('terminated and reschedule long proc')
            long_proc.terminate()  # kill Bash Job B
            started_event.clear()
            long_proc = await start_long_proc(5, started_event=started_event)
        await asyncio.sleep(monitor_interval)

if __name__ == '__main__':
    with event_loop() as loop:
        asyncio.ensure_future(f())
        loop.run_forever()


texts:
I need to merge some large csv files but I feel that the way I am doing it is not optmized. It gets a number of csvfiles and creates one

public static void MergeFiles(IEnumerable<string> csvFileNames, string outputPath)
{
    var sb = new StringBuilder();
    bool hasHeader = false;
    foreach (string csvFileName in csvFileNames)
    {
        TextReader tr = new StreamReader(csvFileName);
        string headers = tr.ReadLine();
        if (!hasHeader)
        {
            sb.AppendLine(headers);
            hasHeader = true;
        }
        sb.AppendLine(tr.ReadToEnd());
    }
    File.WriteAllText(outputPath, sb.ToString());
}

Any suggestion or code snippets?


texts: Creates an employee record in a time and attendance database and returns the employee object

texts:
I am writing a time and attendance system.  This is my idea of a simple elegant solution for the employee class. To me it makes the client very simple an encapsulates everything it needs, however I an new to Object Orientated Design and would appreciate a review.  I plan to create the other classes like this but fear there may be a better way.

My employee class...

 class Employee
    {
        public static Employee CreateNew(string forename, string surname)
        {
            Employee employee = new Employee(forename, surname);
            AddToDataBase(employee);
            return employee;
        }

        public string Forename { get; set; }
        public string Surname { get; set; }

        private Employee(string forename, string surname)
        {
            this.Forename = forename;
            this.Surname = surname;
        }

        private static void AddToDataBase(Employee employee)
        {
          //code to add employee to database

        }
    }

usage...

Employee.CreateNew("Bob", "Smith");


texts: updateBuildChart method with a lot of dependencies

texts:
I've some refactoring issue with one method.
This method has a lot of dependencies

 function updateBuildChart(Filter, PagerFactory, ChartBuilder, LimitsManager) {
     Filter.clearFilters();

     this.currentReports = $scope.$parent.reports;

     $scope.pager = PagerFactory.Create({
         items: this.currentReports
     });

     this.originalReports = angular.copy(this.currentReports);
     LimitsManager.calcFteLimits();

     if (this.currentReports.length > 0) {
         $scope.showGraph = true;
         ChartBuilder.buildChart(this.currentReports);
     } else {
         $scope.showGraph = false;
     }

     Filter.setReports(self.currentReports);
 };

Now I want to split this big method to a small parts. Do you have some ideas how to change it?


texts: this scope for parent object within inner object

texts:
Is this the best way to get access to the parent scope when dealing with complex objects literals?

I find this a bit ugly, and obviously the best solution would never be involving calling it by name directly, but by saving the state of the previous scope. I tried it with bind() but didn't get it to work properly.

var object = {
　　name : 'foo',
　　getName : (function(){
　　　　　 return function(that){
            return {
                a : 111,
                b : that.name,
                c : function(){
                    return this.b;
                }
            }
       }(this);
 　})
};

object.getName().b  // 'foo'


texts:
var AgeConvertor = {

    Age: function (formattedDate) {
      var now = new Date();
      var yearNow = now.getFullYear();
      var monthNow = now.getMonth() + 1;
      var dayNow = now.getDate();

      // Calculating in days
      var ONE_DAY = 1000 * 60 * 60 * 24;
      var ONE_MONTH = 1000 * 60 * 60 * 24 * 30;
      var date1_ms = new Date().getTime()
      var date2_ms = formattedDate.getTime()
      var difference_ms = Math.abs(date1_ms - date2_ms)
      var yearAge =  Math.round(difference_ms/ONE_DAY);

      if(yearAge < 30) {
            return yearAge =  Math.round(difference_ms/ONE_DAY) + 'D';
      // This condition checks if the number of days is more than 30
      } else if(yearAge > 30 && yearAge < 365){
            return yearAge =  Math.round(difference_ms/ONE_MONTH) + 'M';
      } else {

      // Calculating in years
      var today = new Date(yearNow,monthNow,dayNow);

      if (yearNow < 100) {
        yearNow=yearNow+1900;
      }

      yearAge = yearNow - formattedDate.getFullYear();

      if (monthNow <= formattedDate.getMonth()) {
        if (monthNow < formattedDate.getMonth()) {
          yearAge--;
        } else {
          if (dayNow < formattedDate.getDay()) {
            yearAge--;
          }
        }
      }
      return yearAge + 'Y';
     }
   }

}

How well can this code be improved?
Is there any fault in this code?
Does this code give desired results?

This code returns your age in days, months and years.


texts: Is it a good choice to define my own JSON util class like this?

texts:
package utils;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.google.gson.Gson;

public class JSONUtils {

    public static final Gson gson = new Gson();

    public static String toJSON(Object o, String... fields) {
        HashMap<String, Object> map = new HashMap<String, Object>();
        for (String f : fields) {
            try {
                Field field = o.getClass().getField(f);
                map.put(f, field.get(o));
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }

        return gson.toJson(map);
    }

    public static String toJSONForList(List<?> objects, String... fields) {
        ArrayList<Object> list = new ArrayList<Object>();
        for (Object o : objects) {
            list.add(toJSON(o, fields));
        }
        return gson.toJson(list);
    }
}

Note : I need to convert list to JSON very often.


texts: Billing for work using an hourly, dual, or flat rate

texts:
I asked this on Stack Overflow and got some good ideas, but was advised to post here instead. There are obviously several ways to code this, each with a drawback and a benefit.

A person works a number of hours and can bill for the work in one of three ways:

Hourly: the number of hours worked * hourly rate
Dual: (for simplicity sake) first rate + second rate
Flat: just an amount, regardless of the hours worked

Here's the code that I came up with, but I just can't help but think that there's a much more elegant way to do this. In the code below I have a class per rate type, one base class for a rate, a person, and a calculator that does the math. Suggestions?

using System;

public class Program
{
    public static void Main()
    {
        Person p = new Person();
        p.HoursWorked = 2;
        p.Rate = new Hourly(10);
        //p.Rate = new Dual(10, 1);
        //p.Rate = new Flat(10);
        Console.WriteLine(Calculator.Calculate(p));
    }
}

public class Person
{
    public RateStyle Rate { get; set; }
    public int HoursWorked { get; set; }
}

public abstract class RateStyle
{
}

public class Dual : RateStyle
{
    public int First { get; private set; }
    public int Second { get; private set; }

    public Dual(int a, int b)
    {
        First = a;
        Second = b;
    }
}

public class Hourly : RateStyle
{
    public int Rate { get; private set; }
    public Hourly(int r)
    {
        Rate = r;
    }
}

public class Flat : RateStyle
{
    public int Rate { get; private set; }
    public Flat(int r)
    {
        Rate = r;
    }
}

public static class Calculator
{
    public static int Calculate(Person p)
    {
        if (p.Rate is Hourly)
        {
            return p.HoursWorked * ((Hourly)p.Rate).Rate;
        }
        if (p.Rate is Dual)
        {
            return ((Dual)p.Rate).First + ((Dual)p.Rate).Second;
        }

        return ((Flat)p.Rate).Rate;
    }
}


texts: Navigation bar built from fetched JSON data

texts:
I have finally been able to create my little navigation plugin in an object-oriented way that reads the li from a JSON file.

Now, is my code efficient? Especially, the click function within getRegion function?

Is this the correct way to handle the click events in OO?

Here's is working version: PLNKR

'use strict';
if (typeof Object.create !== 'function') {

    Object.create = function (obj) {
        function F () {
        }
        F.prototype = obj;
        return new F ();
    };
}

(function ($, window, document, undefined) {

    var Navigation = {
        init: function (options, elem) {
            var self = this;

            self.elem = elem;
            self.$elem = $ (elem);

            self.url = 'data.json';

            self.navigation = ( typeof options === 'string' )
                ? options
                : options.navigation;

            self.options = $.extend ({}, $.fn.drawNavigation.options, options);

            self.cycle ();
        },

        cycle: function () {
            var self = this;
            self.fetch ().done (function (results) {
                self.buildFrag (results);
                self.display ();
                self.getRegion ();
            });
        },

        buildFrag: function (results) {
            var self = this;
            var navigationRegion = self.options.navigation;
            self.list = $.map (results[navigationRegion].navigation, function (obj, i) {
                return $ (self.options.wrapEachWith).append (obj);
            });
        },

        fetch: function () {
            return $.ajax ({
                url: this.url
            });
        },

        display: function () {
            this.$elem.hide().html (this.list).fadeIn(800);
        },

        activate: function (item) {
            $ (item).siblings ().removeClass ('flag-active');
            $ (item).addClass ('flag-active');
        },

        getRegion: function () {
            var self = this;
            $ ('#flags').find ('div').on ('click', function () {
                //activate flag
                self.activate (this);
                self.options.navigation = $ (this).attr ('id').split ('_')[0];
                self.fetch ().done (function (results) {
                    self.buildFrag (results);
                    self.display ();
                });
            });

        }
    };

    $.fn.drawNavigation = function (options) {
        return this.each (function () {
            var navigationBar = Object.create (Navigation);
            navigationBar.init (options, this);
        });
    };

    //default
    $.fn.drawNavigation.options = {
        navigation: 'uk',
        wrapEachWith: '

'
    }

}) (jQuery, window, document);

$ (function () {
    $('#navigation').find('ul').drawNavigation({});
});


texts: C++ My implementation of a simple sum type (variant)

texts:
Here is a simple variant type I have made. For simplicity, it only can handle two different values. I am planning on using this to create a variadic variant template, using inheritance and recursion.

The requirements for my variant type:

It must have performance similar to std::variant
It must not dynamically allocate memory
There must be no undefined behavior
It should check as much as possible at compile-time, and throw an exception if access is attempted to the wrong type
It must support nontrivial types

Here is the source:

#include <iostream>
#include <cstddef>
#include <typeindex>
#include <optional>
#include <algorithm>
#include <stdexcept>
#include <functional>

/** A variant (sum type) that can contain one of two different types at any one time**/
template<typename T1, typename T2>
class Either {

    using Bigest = std::conditional_t<sizeof(T1) <= sizeof(T2), T1, T2>;
    alignas(sizeof(Bigest)) std::byte storage[sizeof(Bigest)];
    std::optional<std::type_index> conatinedType;
    std::function<void(std::byte*)> destructor;

public:
    Either() : conatinedType(std::nullopt) {}

    template<typename T>
    Either(const T& value) : conatinedType(typeid(T)) {
        static_assert(std::is_same<T1,T>::value || std::is_same<T2,T>::value, "Either cannot contain type T");
        const auto src = reinterpret_cast<const std::byte*>(&value);
        for(size_t i = 0; i < sizeof(T); i++) {
            storage[i] = src[i];
        }
        destructor = [](std::byte* data){ (*reinterpret_cast<T*>(data)).~T(); };
    }

    class BadVariantAccess : public std::exception {};

    template<typename T>
    const T& getAs() const {
        static_assert(std::is_same<T1,T>::value || std::is_same<T2,T>::value, "Either cannot contain type T");
        if(conatinedType == typeid(T)) {
            const auto ptr = reinterpret_cast<const T*>(&storage);
            return *ptr;
        }
        else throw BadVariantAccess();
    };
};

And a test:

struct MyInt {
    int val;
    MyInt(const int& val) : val(val) {
        std::cout << "making int!" << std::endl;
    }
    ~MyInt() {
        std::cout << "destructing int!" << std::endl;
    }
};

struct MyDouble {
    double val;
    MyDouble(const double& val) : val(val) {
        std::cout << "making double!" << std::endl;
    }
    ~MyDouble() {
        std::cout << "destructing double!" << std::endl;
    }
};

int main()
{
    Either<MyInt, MyDouble> e = MyDouble(5.0987);

    try{
        std::cout << e.getAs<MyDouble>().val << std::endl;
    }
    catch(...) {
        std::cerr << "Bad Variant Access" << std::endl;
    }

    return 0;
}


texts:
Scenario

A portable controls/widgets library for Xamarin.Forms (PCL Profile 111) contains a combobox/dropdown/picker control where the ItemsSource property is an IEnumerable.

The ItemsSource can be populated with any IEnumerable of objects.
The combobox displays value by

DisplayMemberPath: string

The combobox syncs selection:

SelectedItem : object
SelectedIndex: int

To do all this the IEnumerable must be parsed so we can

Select index
Select item from source collection

The tricky part

Parse IEnumerable to Dictionary<object, object> in a Portable Class Library.
The sourceDictionary field is used to sync the "selected" properties as described above.

    private Dictionary<object, object> sourceDictionary;

    /// <summary>
    ///     Parse type of ItemsSource as Dictionary and populate <see cref="Picker.Items" /> and
    ///     <see cref="sourceDictionary" />.
    /// </summary>
    private void PopulateItemsAndSelectionValuesFromDictionary()
    {
        // TODO: Better way to get Dictionary from IEnumerable
        if (this.ItemsSource is Dictionary<object, object>)
        {
            foreach (var newItem in (Dictionary<object, object>)this.ItemsSource)
            {
                this.AddToItemsAndSelectionValues(newItem.Key, newItem.Value);
            }
        }
        else if (this.ItemsSource is Dictionary<object, string>)
        {
            foreach (var newItem in (Dictionary<object, string>)this.ItemsSource)
            {
                this.AddToItemsAndSelectionValues(newItem.Key, newItem.Value);
            }
        }
        else if (this.ItemsSource is Dictionary<object, int>)
        {
            foreach (var newItem in (Dictionary<object, int>)this.ItemsSource)
            {
                this.AddToItemsAndSelectionValues(newItem.Key, newItem.Value);
            }
        }
        else if (this.ItemsSource is Dictionary<int, object>)
        {
            foreach (var newItem in (Dictionary<int, object>)this.ItemsSource)
            {
                this.AddToItemsAndSelectionValues(newItem.Key, newItem.Value);
            }
        }
        else if (this.ItemsSource is Dictionary<string, object>)
        {
            foreach (var newItem in (Dictionary<string, object>)this.ItemsSource)
            {
                this.AddToItemsAndSelectionValues(newItem.Key, newItem.Value);
            }
        }
        else if (this.ItemsSource is Dictionary<int, int>)
        {
            foreach (var newItem in (Dictionary<int, int>)this.ItemsSource)
            {
                this.AddToItemsAndSelectionValues(newItem.Key, newItem.Value);
            }
        }
        else if (this.ItemsSource is Dictionary<string, string>)
        {
            foreach (var newItem in (Dictionary<string, string>)this.ItemsSource)
            {
                this.AddToItemsAndSelectionValues(newItem.Key, newItem.Value);
            }
        }
    }

    /// <summary>
    ///     Add the provided KeyValuePair to <see cref="Picker.Items" /> and <see cref="sourceDictionary" />
    /// </summary>
    private void AddToItemsAndSelectionValues(object key, object value)
    {
        this.Items.Add(this.ValueIsDisplayMember() ? value.ToString() : key.ToString());
        this.sourceDictionary.Add(this.ValueIsDisplayMember() ? key : value, new KeyValuePair<object, object>(key, value));
    }


texts: Using getters and setters to change another variable C#

texts:
Is it a bad practice to use getters and setters this way?

Below is my code:

public struct Settings
{
    public static int workMinutes
    {
        get
        {
            return Properties.Settings.Default.workMinutes;
        }
        set
        {
            Properties.Settings.Default.workMinutes = value;
            save();
        }
    }

    public static int restMinutes
    {
        get
        {
            return Properties.Settings.Default.restMinutes;
        }
        set
        {
            Properties.Settings.Default.restMinutes = value;
            save();
        }
    }

    public static void init()
    {
        if(Properties.Settings.Default.workMinutes == 0)
            Properties.Settings.Default.workMinutes = 5;

        if(Properties.Settings.Default.restMinutes == 0)
            Properties.Settings.Default.restMinutes = 5;

        save();
    }

    private static void save()
    {
        Properties.Settings.Default.Save();
    }
}


texts:
Here's what the question asks:

  Build a class called Course.java. This class should have 4 properties: CourseId, CourseName, Description, and credit hours. Also add the appropriate set and get methods. Add a display() method to display these 4 properties out to the DOS window. Lastly add a main() method for testing. In the main() method instantiate a Course object, fill it with data using the set methods, then call the display method to display the data.

I just want to make sure is my code right and if there are mistake in my code.

public class Course {

//   ========================== Properties ===========================
private int courseid;
private String courseName;
private String description;
private String creditHours;

//   ==========================  Behaviors  ==========================
public void setCourseId(int c) { courseid = c; }
public int getCourseId() { return courseid;}

public void setCourseName(String cn) { courseName = cn; }
public String getCourseName() { return courseName;}

public void setDescription(String d) { description = d; }
public String getDescription() { return description;}

public void setCreditHours(int ch) { ch = 4; }
public int getCreditHours() { return ch;}

//Returning String
public String toString() {
    return courseName + ":" + description + ":" + creditHours;
}

public void display() {
    System.out.println("Course ID             = " + getCourseId());
    System.out.println("Course Name      = " + getCourseName());
    System.out.println("Description      = " + getDescription());
    System.out.println("Credit Hours           = " + getCreditHours());

} //end display()

public static void main(String args []) {

    Course c1;
    c1 = new Course();

    c1.setCourseId(109);
    c1.setCourseName("Intro to Python");
    c1.setDescription("This course intros the Python Prog Lang.");
    c1.setCreditHours(4);

    c1.display();

    //Test out toString() method
    System.out.println(c1);
} //end main
} //end class


texts: Switching from functional jQuery code to object-oriented

texts:
I've been happily using jQuery, creating vars and binding events in my modules (which have only a little bit of JS). But recently I needed to add an anonymous functions to my code and after investigating some more, I learned about modular patterns and encapsulation.

So what I'm trying to teach myself is to write clean, fast and maintainable JavaScript code in object-oriented fashion (as opposed to "functional" jQuery code before).

My module inserts a search box (input) that uses Ajax and displays drop-down results.

What I want to have is a template file with the search box other necessary elements;
Then the most flexible way would be to pass the elements to the code in JavaScript file - I could easily adjust settings in the same file if I decide to change IDs or the elements.

Then there should be a separate file with the actual code; It should make no presumptions about the elements of the page.

I follow this article:

http://esbueno.noahstokes.com/post/77292606977/self-executing-anonymous-functions-or-how-to-write

These are my thoughts and what I would like to know:

Is this structure written correctly to accomplishing this task?
Is the anonymous function (self-executing one) being used correctly here?
Is there anything to be optimized (maybe I'm "overkilling" something)?
Is $.proxy used correctly?
I to use an object to defined methods, however, I cant think of a way to only expose a public method. Is writing non-objective (simple enclosed vars and functions) the way to go?

search_box.tpl

<script type="text/javascript" src="autosearch.js"></script>

<form>
    <input id="search-1" type="search">
</form>

<script type="text/javascript">
    AutoSearch.init({
        input  : $('#search-1'),
        option2: ''
    });
</script>

autosearch.js

var AutoSearch = (function($) {

    var search = {

        cache: {},
        bindEvents: function(){
           this.input.on('keyup', $.proxy(this.processInput, this));
        },
        processInput: function(){ alert(this.input.val()); },

        init: function(options) {
            this.input = options.input;

            this.bindEvents();
        }
    }

    return search;

    })(jQuery);


texts: Finding locations with a distance between 1 and 5000

texts:
I'm wondering how I could refactor this code. It may look a little reiterative and probably there's a shorter method to accomplish the same.

def self.location(distance=100,location)
  if distance.is_a? Integer
    if distance.between?(1,5000)
      distance = distance
    elsif distance < 1
      distance = 1
    elsif distance > 5000
      distance = 5000
    end
  else
    distance = 100
  end
  if location
    within(distance, :origin => location)
  else
    find(:all)
  end
end


texts: python Improve a function in a elegant way

texts:
I have a grid as

>>> data = np.zeros((3, 5))
>>> data
array([[ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.]]

i wrote a function in order to get the ID of each tile.

array([[(0,0), (0,1), (0,2), (0,3), (0,4)],
      [(1,0), (1,1), (1,2), (1,3), (1,4)],
      [(2,0), (2,1), (2,2), (2,3), (2,4)]]

def get_IDgrid(nx,ny):
    lstx = list()
    lsty = list()
    lstgrid = list()
    for p in xrange(ny):
        lstx.append([p]*nx)
    for p in xrange(ny):
        lsty.append(range(0,nx))
    for p in xrange(ny):
        lstgrid.extend(zip(lstx[p],lsty[p]))
    return lstgrid

where nx is the number of columns and ny the number of rows

test = get_IDgrid(5,3)
print test
[(0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (1, 0), (1, 1), (1, 2), (1, 3), (1, 4), (2, 0), (2, 1), (2, 2), (2, 3), (2, 4)]

this function will be embed inside a class

class Grid(object):
    __slots__= ("xMin","yMax","nx","ny","xDist","yDist","ncell")
    def __init__(self,xMin,yMax,nx,ny,xDist,yDist):
        self.xMin = xMin
        self.yMax = yMax
        self.nx = nx
        self.ny = ny
        self.xDist = xDist
        self.yDist= yDist
        self.ncell = nx*ny


texts: Graceful JavaScript fallback for external web service failure

texts:
I use the src.sencha.io service to resize images on the fly according to device width, saving lots of bandwidth on mobiles etc.

Sometimes the service fails randomly with a 503 error, so a fallback is needed. I've written this JS to fallback to "non-sencha" urls, and emit an error event, if the first image requested through sencha fails.

This is my first open-sourced bit of code, so am keen to get feedback on my:

code correctness
whether this prototype-based design pattern is appropriate
alternative better patterns
comment/code clarity

Even just confirming whether it's good would be helpful, as I don't have any formal programming training to be confident.

Github repo here.

jsfiddle with test case prepared for you here.

/** SENCHA SRC IMAGE FALLBACK ***************************************
 *
 * Author: Josh Harrison (http://www.joshharrison.net/)
 * URL: https://github.com/ultrapasty/sencha-src-image-fallback
 * Version: 1.0.0
 * Requires: jQuery
 *
 * Tests to see if the src.sencha.io service is down, and if so,
 * falls back to local images, by removing the sencha domain
 * from the src.
 *
 * Can be instantiated with `new SenchaSRCFallback().init();`
 * Or `var instance = new SenchaSRCFallback().init();`
 *
 * Emits the event `senchafailure` if sencha fails.
 * Listen with `instance.onsenchafailure = func;`
 *
 */

;(function(window, $) {

  var SenchaSRCFallback = function() {

    this.sencha_path_identifier = '.sencha.io/';
    this.sencha_path_regex = /http:\/\/src[1-4]?\.sencha\.io\//i;
    this.$imgs = null;

  };
  SenchaSRCFallback.prototype = {

    init : function() {
      this.$imgs = $("img[src*='" + this.sencha_path_identifier + "']");

      if(this.$imgs.length) {
        this.test_sencha_availability();
      }

      return this;
    },

    test_sencha_availability : function() {
      var t = this, img = new Image();

      img.onerror = function() {
        $(t).trigger("senchafailure");
        t.fallback_to_local_srcs();
      };

      img.src = this.$imgs[0].getAttribute("src");
    },

    fallback_to_local_srcs : function() {
      var t = this;

      this.$imgs.each(function() {
        this.setAttribute("src", this.getAttribute("src").replace(t.sencha_path_regex, ""));
      });
    }

  };

  window.SenchaSRCFallback = SenchaSRCFallback;

})(window, jQuery);

// Example usage:

// Instantiate the fallback
var senchafallback = new SenchaSRCFallback().init();

// Listen for failure like this:
senchafallback.onsenchafailure = function() {
    console.log("It failed.");
    // log failure event in google analytics, etc
};

Images would be initially routed through src.sencha.io to avoid downloading twice. With the above JS, should sencha fail, these image tags:

... would become the following:


texts: Transforming elements of std containers from other std containers

texts:
Problem

In this HackerRank problem we are asked to rotate the elements of a matrix in the following way:

Example Input and Output

First and second entry specify the size of the matrix and third entry how many times it has to be rotated. As an example, the following input:

4 4 2
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16

would produce the following output:

3 4 8 12
2 11 10 16
1 7 6 15
5 9 13 14

Solution

My idea was to rotate these rings.

#include <vector>
#include <iostream>
#include <algorithm>

using Matrix = std::vector<std::vector<int>>;

void rotate_mat (Matrix &mat, int r){
    auto m = mat.size(); // Number of rows
    auto n = mat[0].size(); // Number of columns
    auto n_rings = std::min(m,n)/2; // Number of rings
    for(auto ring_i=0; ring_i<n_rings; ++ring_i){
        // The elements of the ring are stored sequentially
        // in v_ring so it can be rotated with std::rotate
        std::vector<int>  v_ring;
        // v_ring_ptr points to the original places in the matrix,
        // so the rotation of v_ring can be assigned back to the matrix
        std::vector<int*> v_ring_ptr;
        // Top side of the ring
        for(auto j=ring_i; j<=(n-1)-ring_i; ++j) {
            v_ring.push_back(mat[ring_i][j]);
            v_ring_ptr.push_back(&mat[ring_i][j]);
        }
        // Right side of the ring
        for(auto i=ring_i+1; i<=(m-1)-ring_i; ++i) {
            v_ring.push_back(mat[i][(n-1)-ring_i]);
            v_ring_ptr.push_back(&mat[i][(n-1)-ring_i]);
        }
        // Bottom size of the ring
        for(auto j=(n-1)-ring_i-1; j>ring_i; --j) {
            v_ring.push_back(mat[(m-1)-ring_i][j]);
            v_ring_ptr.push_back(&mat[(m-1)-ring_i][j]);
        }
        // Left size of the ring
        for(auto i=(m-1)-ring_i; i>ring_i; --i) {
            v_ring.push_back(mat[i][ring_i]);
            v_ring_ptr.push_back(&mat[i][ring_i]);
        }

        std::rotate(v_ring.begin(),v_ring.begin()+r%v_ring.size(),v_ring.end());
        // Update the rotated values in the original matrix
        for (auto i=0; i<v_ring.size(); ++i){
            *v_ring_ptr[i] = v_ring[i];
        }
    }
};

Matrix read_matrix(int m, int n) {
    Matrix mat;
    mat.reserve(m);
    for(auto i=0; i<m; ++i) {
        mat.push_back(std::vector<int>{});
        mat[i].reserve(n);
        for(auto j=0; j<n; ++j) {
            int x; std::cin >> x;
            mat[i].push_back(x);
        }
    }
    return mat;
};

void print_matrix(Matrix &mat){
    for (auto& i : mat){
        for (auto& j : i) {
            std::cout << j << " ";
        }
        std::cout << "\n";
    }
};

int main() {
    int m,n; std::cin >> m >> n;
    int r; std::cin >> r;

    auto mat = read_matrix(m,n);
    rotate_mat(mat,r);
    print_matrix(mat);

    return 0;
}

Questions

My main problem is that I would like to avoid having the v_ring copy and this part:

for (auto i=0; i<v_ring.size(); ++i){
    *v_ring_ptr[i] = v_ring[i];
}

Is there a way to store references to the content of the original matrix so the transformation in the constructed rings would automatically be reflected? I tried with std::reference_wrapper. It almost works with that, I can modify the elements in the ring for example with ++ operator, but I cannot make assigments, nor std::rotate has any effect on them.

Any ideas? I'm also interested in any other approach that could come to your mind! I thought this way was easy to express in code


texts: Listing payments where all payments lines and transactions are closed

texts:
The goal of this query is to get a list of payments where all the corresponding payment lines and transactions have the status CLOSED. These are one to many relationships. The database is Informix.

I wonder if there is a more efficient way to write this? In its current state it has a lot of repetition which, maybe because my Java background, seems quite ugly to me. Eventually this query will need to be generated through Hibernate, so I'm mostly concerned with its performance.

SELECT p.* FROM payment p
JOIN transaction t
ON t.payment_bk = p.bk
JOIN payment_line pl
on  p.bk = pl.payment_bk
WHERE p.valid AND p.valid_to is null
AND p.date>{ts '2015-05-21 00:00:00'}
AND p.date<{ts '2015-05-22 00:00:00'}
AND t.valid and t.valid_to is null
AND t.transaction_status = 'CLOSED'
AND NOT EXISTS (SELECT 1 FROM transaction t WHERE t.payment_bk = p.bk
AND t.transaction_status <> 'CLOSED'
AND t.valid and t.valid_to is null)
AND pl.valid and pl.valid_to is null
AND pl.payment_line_status = 'CLOSED'
AND NOT EXISTS (SELECT 1 FROM payment_line WHERE pl.payment_bk = p.bk
AND pl.payment_line_status <> 'CLOSED'
AND pl.valid and pl.valid_to is null)

valid is a boolean and the dates/timestamps will sometimes be just a day apart, sometimes a couple of months.


texts:
I wrote this simple solution about FizzBuzz. Is there any possible way to solve or optimize the solution, such as with bitwise tricks?

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

    for(int i = 1 ; i <= 100 ; ++i){
      if(i % (5*3) == 0){
        System.out.println("FizzBuzz");
      }else if(i % 3 == 0){
        System.out.println("Fizz");
      }else if(i % 5 == 0){
        System.out.println("Buzz");
      }else
        System.out.println(i);
    }
  }
}


texts: Beginner programmer on sending error messages

texts:
I am looking to optimize one function that returns error messages to the user.

    /// <summary>
    /// Handles the Ouverture event of the PrescriptionVue control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    private void PrescriptionVueOuverture(object sender, EventArgs e)
    {
        Message message = ServiceCouchePolygoneFacade.Instance.RecalculerSuperficiePolygone();
        Message message2 = ServicePrescriptionFacade.Instance.MettreAJourTablePrescription();
        if (message != null || message2 != null)
        {
            if (message != null)
            {
                this.prescriptionVue.AfficherMessage(message);
            }
            else
            {
                this.prescriptionVue.AfficherMessage(message2);
            }

            this.prescriptionVue.Fermer();
        }

        this.InitialiserVue();
    }

I have 2 service that conduct different manipulation and both of them returns an Object "Message" that are either gonna bu null or contain the error.

What im looking to optimize is the condition block in wich i look if either of those are null and if one isnt, wich one, so that i can send the one that contains the error.


texts: Conversion of an array of integers to string

texts:
In order to save memory space. Strings inside an embedded device are stored in a particular way. Each 32-bit location holds up to 4 chars instead of only 1 char in the usual case.

I wrote a function that convert an encoded string back to its original string. I am new to Python, so I would like to know whether or not I can simplify my code.

The string is encoded in such way that I need to reverse the order of each group of 4 chars.

#!/usr/bin/python
def arrayOfInt2string(array):
    s = ''
    for a in array:
        a = "%0.8x" % a
        b = list()
        for i in range(0, len(a), 2):
            b.append(chr(int(a[i:i+2], 16)))
        s = s + ''.join(b.reverse())
    return s

r = (
    0x33323130,
    0x37363534,
    0x00000038,
    0x00000000
)
arrayOfInt2string(r)

The output is:

"012345678"


texts:
For example if I start with the number 146. I first reverse it, so it becomes 641. Then I add this to the original number to make 787 which is a palindrome. I would repeat the process if the answer is not a palindrome.

I made this program show how long it ran for when it finishes or is interrupted and also to write the output to a file called output.txt.

from sys import exit
from signal import SIGINT, signal
from timeit import default_timer

def n(x):

    counter = 0
    b = 0
    start = default_timer()

    def t(*args):

        end = default_timer()
        total = end - start
        print (total)

        with open('output.txt','w') as f:

            f.write('{}\n{}\n{}'.format(b, counter, total))

        exit(0)

    signal(SIGINT,t)

    while True:

        b += int(str(x)[::-1])

        if b == int(str(b)[::-1]):

            end = default_timer()
            print (b, counter)
            t()
            break

        else:

            counter += 1
            print (b,counter)
            x = b


texts:
I'm working on improving myself by teaching myself how to make classes to remove reppetitive pieces of code and create a class that does it for me.

I have the following xml document.

<?xml version="1.0" encoding="UTF-8"?>
<Attributesets>
    <Aansluitmateriaal>
        <EF023685>
            default
            <name>Thermostatisch voorbereid</name>
        </EF023685>
        <EF023855>
            staartstuk_gebogen
            <name>Met gebogen staartstuk</name>
        </EF023855>
        <EF026393>
            schroefdraad
            <name>Spoed schroefdraad leidingaansluiting</name>
        </EF026393>
    </Aansluitmateriaal>
</Attributesets>

And the following data array

Array(
    'EF023685' => 1,
    'EF023855' => 0,
    'EF026393' => 'spiraal',
    'EF000443' => 'Kanaaleind',
)

Both the data array and the XML document can have nodes that don't exist in the other one. if the node code has default as value the code should be discarded i.e. not returned. otherwise the code should be returned.
To do that I have made the following class and would like to know what I could do better and possible concerns you see.

The script is to return an array with the array keys being the code value from the xml document.
This array is later used to build up an sql update query

The LoadImportAttributes is fed the location of the xml document, the Node to look for, and the name of the node to return. (in that order)

The setEfImportValues takes The array followed by the returned array from LoadImportAttributes

I hope this clears up my question somewhat

class CustomImportClass{
    private $DataArray = Array();
    private $XmlData = Array();
    private $ReturnArray = Array();
    private $XmlDocument;
    private $DataNodeName;
    private $ReturnNodeName;
    /**
    * Object that builds an array of Value 1 and value 2
    * Expects Array 1 = Array[key] value
    * Expects Array 2 = Array[key] value
    * Expects Array 1 [key] == $Array 2 [key]
    * Ignores
    * Any data with Array 2 Value == "default"
    * Any data where Array 2 [key] == null or ""
    * Returns
    * Array[Array 2 Value] = Array 1 Value
    *
    * @return Array
    */
    public function setEfImportValues($DataArray,$XmlData){
        foreach($DataArray as $EfCode => $ProductValue){
            if(!is_null($EfCode) && (string)$EfCode!="" && !is_null($XmlData[$EfCode]) && $XmlData[$EfCode]!='default'){
                $ReturnArray[$XmlData[$EfCode]] = $ProductValue;
            }
        }
        return($ReturnArray);
    }
    /**
    * Object to get specific Node inside Nested Nodes found in the Searched Node
    * Requires SimpleXml & XPath
    * Expects XML Document Path
    * Expects Search Node Name
    * Expects Return Node Name
    * Expects Search Node Name->RandomNodeName->ReturnNodeName
    * Ignores
    * Any other nodes found
    * Returns
    * Array[$NodeName] = ReturnNodeName->Value
    *
    * @return Array
    */
    public function LoadImportAttributes($XmlDocument,$DataNodeName,$ReturnNodeName){
        $Open = new SimpleXMLElement(file_get_contents($XmlDocument));
        foreach($Open->xpath($DataNodeName) as $FoundNodes){
            foreach($FoundNodes as $NodeName => $NodeValue){
                $ReturnArray[$NodeName] = (string)$NodeValue->$ReturnNodeName;
            }
        }
        return($ReturnArray);
    }
}

If you require example arrays of the data as it's send to the function, I can provide that aswell.


texts:
I want to the user to filter a list of receipts by various criteria. Just the regular, an empty filter should show all items, an entry in customer should show all receipts from that customer and an additional entry in date should show all entries from said customer on the given date. I have the feeling, my if else apprach is not the best way, since with 4 criteria I'm already at 16 branches, not speak of 5, 6, or 7 criteria.

What is the most elegant way to achieve this.

Model:

class customer
{

    public int ID { get; set; }

    public string Name { get; set; }

}

class receipt
{

    public int ID { get; set; }

    public string Number { get; set; }

    public DateTime Date { get; set; }

    public double Amount { get; set; }

    public customer Customer { get; set; }

}

Viewmodel

class receiptViewModel
{

    ObservableCollection<receipt> ReceiptList { get; set; }

    List<receipt> ReceiptListView { get; set; }

    private string filter;

    public string Filter
    {
        get { return filter; }
        set
        {

            filter = value;

            if (number != null && date == null && customer && null)
            {
                ReceiptListView = ReceiptList.Where(x => x.Number.Contains(number)).ToList();
            }
            else if (number != null && date != null && customer && null)
            {
                ReceiptListView = ReceiptList.Where(x => x.Number.Contains(number) && x.Date === date).ToList();
            }
            //aso aso aso
          }
    }


texts: Combine lists from two lists of list into a single list of lists

texts:
def combine_in_place(first, second):
    combined = []
    maxLength = max(len(first), len(second))
    for i in range(maxLength):
        if len(first) < i+1:
            combined.append(second[i])
        elif len(second) < i+1:
            combined.append(first[i])
        else:
            if not first[i]:
                combined.append(second[i])
            elif not second[i]:
                combined.append(first[i])
            else:
                combined.append(first[i] + second[i])

    return combined

print combine_in_place([['f'], ['j', 't'], [], ['s'], [], []], [['h', 'd'], [], [], []])
    # prints: [['f', 'h', 'd'], ['d', 't'], [], ['s'], [], []]

So I know to program (been programming in Java for some time now). I am trying to learn Python but I am not sure what's the best way to do some stuff. My question is:
How to write the function in a more Pythonic way?


texts: Shortest distance from one word to another. eg: cat -> cot -> dot -> dog

texts:
Lil' preparation before the interview. This is my solution to the problem in title. The code is pretty straight forward. Requesting suggestions for improvement and also verification of complexity, which I guess is O(26n)

public class CatToDog {

        static Set<String> dictionary;

        static {
            dictionary = new HashSet<String>();
            dictionary.add("camera");
            dictionary.add("cat");
            dictionary.add("cot");
            dictionary.add("cot");
            dictionary.add("dome");
            dictionary.add("dot");
            dictionary.add("dog");

    //        dictionary = new TreeSet<String>();
    //        BufferedReader br = null;
    //        try {
    //            try {
    //                br = new BufferedReader(new FileReader("/Users/ameya.patil/Desktop/text.txt"));
    //                String line;
    //                while ((line = br.readLine()) != null) {
    //                    dictionary.add(line.split(":")[0]);
    //                }
    //
    //            } finally {
    //                br.close();
    //            }
    //        } catch (Exception e) {
    //            throw new RuntimeException("Error while reading dictionary");
    //        }

        }

        private CatToDog () { };

        public static List<String> listWords(String startWord, String endWord) {
            final Queue<String> queue = new LinkedList<String>();
            final Map<String, String> backTrack = new HashMap<String, String>();
            queue.add(startWord);
            backTrack.put(startWord, null);

            while (!queue.isEmpty()) {
                String currentWord = queue.poll();
                if (currentWord.equals(endWord)) {
                    return mapToList(backTrack, endWord);
                }
                addValidOneChangeWords(currentWord, queue, backTrack);
            }
            return Collections.EMPTY_LIST;
        }

        private static void addValidOneChangeWords(String startWord, Queue<String> queue, Map<String, String> backTrack) {
            for (int i = 0; i < startWord.length(); i++) {
                char[] endWord = startWord.toCharArray();
                for (char ch = 'a'; ch < 'z'; ch++) {
                    endWord[i] = ch;
                    String word = new String(endWord);
                    if (validate(word, backTrack, startWord)) {
                        queue.add(word);
                        backTrack.put(word, startWord);
                    }
                }
            }
        }

        private static boolean validate(String word, Map<String, String> backTrack, String startWord) {
            return dictionary.contains(word) && !backTrack.containsKey(word) && !word.equals(startWord);
        }

        private static List<String> mapToList (Map<String, String> backTrack, String endWord) {
            final List<String> wordList = new ArrayList<String>();
            String word = endWord;
            while (backTrack.containsKey(word)) {
                wordList.add(word);
                word = backTrack.get(word);
            }
            Collections.reverse(wordList);
            return wordList;
        }

        public static void main(String[] args) {
           for (String string :  listWords("cat", "dog")) {
               System.out.println(string);
           }
        }
    }


texts:
This is a program in C++ that guesses a number given by the user. I have to do homework and there's my attempt to solve an exercise from the programming book. If you know what can be done better and how to make more beautiful my code, let know me.
#include <iostream>

int main() {
    std::cout << "Enter number from range 0 to 100: ";
    int num;
    std::cin >> num;
    int guess = 50;
    bool lower = false;
    bool upper = false;
    int min = 0;
    int max = 100;
    while (guess != num) {
        if (num < guess) {
            std::cout << "Is this number lower than " << guess << "? (0 - false, 1 - true)\n";
            std::cin >> lower;
            if (lower) {
                upper = false;
                max = guess;
            }
        } else if (num > guess) {
            std::cout << "Is this number greater than " << guess << "? (0 - false, 1 - true)\n";
            std::cin >> upper;
            if (upper) {
                lower = false;
                min = guess;
            }
        } else {
            std::cout << "Let's guess, this number is equal to 50, isn't it?\n";
        }
        guess = (min+max)/2;
    }
    std::cout << "You entered a number " << guess << ", did I guess?\n";
    return 0;
}


texts:
I wrote this short, plain Ruby lib to handle email address validation inside and outside of Rails applications, and I would like to know what you think.

require "i18n"

class EmailAddress
  VALID_EMAIL_ADDRESS_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i

  def self.malformed?(email)
    email !~ VALID_EMAIL_ADDRESS_REGEX
  end

  def self.valid?(email)
    !malformed?(email)
  end

  attr_reader :email, :i18n_scope, :errors

  def initialize(email, i18n_scope: [:models, :email_address])
    @email = email
    @i18n_scope = i18n_scope
    @errors = []
  end

  def valid?
    validate
    errors.empty?
  end

  def validate
    message = I18n.t(:invalid, scope: i18n_scope)
    errors.push(message) if EmailAddress.malformed?(email)
  end
end

Usage can be as simple as:

if EmailAddress.valid?(params[:email))
  # do something
end

Or for remote validations, for example:

def email
  email = EmailAddress.new(params[:email])
  if email.valid?
    render nothing: true, status: 200
  else
    render json: { errors: email.errors }, status: 422
  end
end


texts: Is my code utilizing proper Object Oriented features?

texts:
class element {
   constructor(name){
    this.name = name;
   }
   createNew(){
    var elem = document.createElement(this.name);
    document.body.appendChild(elem);
   }
   setElementAttribute(attr_name, attr_value){
    this.attr_name = attr_name;
    this.attr_value = attr_value;
   }
   createNewWithAttribute(){
    var elem = document.createElement(this.name);
    document.body.appendChild(elem);
    elem.setAttribute(this.attr_name, this.attr_value);
   }
 }
 class elementWithText extends element {
   constructor(name, text){
    super(name);
    this.text = text;
   }
   createNew(){
   var elem = document.createElement(this.name);
   document.body.appendChild(elem);
   elem.innerHTML = this.text;
  }
   setElementAttribute(attr_name, attr_value){
    super.setElementAttribute(attr_name, attr_value);
  }
   createNewWithAttribute(){
    var elem = document.createElement(this.name);
    document.body.appendChild(elem);
    elem.setAttribute(this.attr_name, this.attr_value);
    elem.innerHTML = this.text;
  }
}
   var inputBox = new element('input');
   inputBox.setElementAttribute('type','radio');
   inputBox.createNewWithAttribute();
   var heading = new elementWithText('h1','Hello World');
   heading.setElementAttribute('style','color: red;');
   heading.createNewWithAttribute();


texts: Length of the longest sequence of repeating characters

texts:
I have been going through some CodingBat exercises and I came across this problem. "Given a string, return the length of the largest "block" in the string. A block is a run of adjacent chars that are the same."

Required output:

maxBlock("hoopla") → 2
maxBlock("abbCCCddBBBxx") → 3
maxBlock("") → 0

My code seems to pass all the tests except for the last "other test". Can someone please review my code and tell me where exactly I could have gone wrong?

 public int maxBlock(String str) {
      int charBlock = 0;
      int holder = 1;
      if(str.length() == 0){ //If string is empty return 0
         charBlock = 0;
      } else if(str.length() == 1){ //If string contains only a single char return 1
         charBlock = 1;
      } else {
          for(int i=0; i < str.length()-1; i++){   //loop through each char value
              if((str.length() == 2) && (str.charAt(i) != str.charAt(i+1))){
                  charBlock =1; //return 1 if the length of the string is 2 and non of the two chars match
              }
              else if((str.length() == 3) && (str.charAt(i) != str.charAt(i+1))){
                 charBlock = 1; //return 1 if the length of the string is 3 and non of the three chars match
              }
              else if (str.charAt(i) == str.charAt(i+1)){
                 holder = holder + 1;
                   if(holder > charBlock){
                     charBlock = holder; //update the value of charBlock if a holder is larger current value
                     }
             } else holder = 1;
          }
      }
      return charBlock;
    }

Example test cases:

Expected    Run
maxBlock("hoopla") → 2  2   OK
maxBlock("abbCCCddBBBxx") → 3   3   OK
maxBlock("") → 0    0   OK
maxBlock("xyz") → 1 1   OK
maxBlock("xxyz") → 2    2   OK
maxBlock("xyzz") → 2    2   OK
maxBlock("abbbcbbbxbbbx") → 3   3   OK
maxBlock("XXBBBbbxx") → 3   3   OK
maxBlock("XXBBBBbbxx") → 4  4   OK
maxBlock("XXBBBbbxxXXXX") → 4   4   OK
maxBlock("XX2222BBBbbXX2222") → 4   4   OK
other tests                             X


texts: Least amount of HTML and CSS to create a bottom border for every section?

texts:
I am doing a redesign and have some previously existing content in HTML that is similar to

Bacon ipsum dolor sit amet aliquip est tail occaecat bacon ad qui short loin exercitation.Strip steak sint dolore et ut, elit kielbasa quis.

&ndash;Name Surname

And those classes were manually added to every testimonial. So I have so far wrapped everything in a
 and then every testimonial is wrapped in a div because I wanted to leverage inheritance so that a new testimonial later did not need the classes nor the
 but of course to prevent a future
 within the
 that might be necessary in the future by another dev, I decided to use > p . How do these classes look for keeping code as lean as possible?

HTML

Frankfurter meatloaf quis chuck, sunt jerky voluptate veniam ex aute commodo duis laboris labore. Sint dolor enim boudin pancetta culpa ham hock, laboris brisket veniam doner short loin velit qui duis.

        &ndash Piggy McPiggy

Frankfurter meatloaf quis chuck, sunt jerky voluptate veniam ex aute commodo duis laboris labore. Sint dolor enim boudin pancetta culpa ham hock, laboris brisket veniam doner short loin velit qui duis.

        &ndash Oinky Sausagebreath

Frankfurter meatloaf quis chuck, sunt jerky voluptate veniam ex aute commodo duis laboris labore. Sint dolor enim boudin pancetta culpa ham hock, laboris brisket veniam doner short loin velit qui duis.

        &ndash Pigster Pickled

CSS

div#testimonials > div {
    border-bottom: solid 1px #666;
}

div#testimonials p {
    font-size: 16px;
}

div#testimonials span {
    font-weight: bold;
    color: red;
}

My concern is that if we perhaps need to add a span in the paragraph, that I might need to do something else to make sure that the persons name is still styled as intended. Something about this just does not seem Kosher.


texts:
I have a very large JSON Lines File with 4.000.000 Rows, and I need to convert several events from every row. The resulted CSV File contains 15.000.000 rows. How can I optimize this script?

I'm using Powershell core 7 and it takes around 50 hours to complete the conversion.

My Powershell script:

$stopwatch =  [system.diagnostics.stopwatch]::StartNew()
$totalrows = 4000000

$encoding = [System.Text.Encoding]::UTF8
$i = 0
$ig = 0
$output = @()

$Importfile = "C:\file.jsonl"
$Exportfile = "C:\file.csv"

if (test-path $Exportfile) {
    Remove-Item -path $Exportfile
}

foreach ($line in [System.IO.File]::ReadLines($Importfile, $encoding)) {
    $json = $line | ConvertFrom-Json

    foreach ($item in $json.events.items) {
    $CSVLine = [pscustomobject]@{
    Key = $json.Register.Key
    CompanyID = $json.id
    Eventtype = $item.type
    Eventdate = $item.date
    Eventdescription = $item.description
    }
    $output += $CSVLine
    }

    $i++
    $ig++
    if ($i -ge 30000) {
        $output | Export-Csv -Path $Exportfile -NoTypeInformation -Delimiter ";" -Encoding UTF8 -Append
        $i = 0
        $output = @()

        $minutes = $stopwatch.elapsed.TotalMinutes
        $percentage = $ig / $totalrows * 100
        $totalestimatedtime = $minutes * (100/$percentage)
        $timeremaining = $totalestimatedtime - $minutes

        Write-Host "Events: Total minutes passed: $minutes. Total minutes remaining: $timeremaining. Percentage: $percentage"
    }
}

$output | Export-Csv -Path $Exportfile -NoTypeInformation -Delimiter ";" -Encoding UTF8 -Append

$stopwatch.Stop()


texts:
Fairly new to learning interview questions and I saw this one and gave it a shot. I would very much appreciate some constructive criticism of how I went about it and what you would tell me if you were the interviewer and watched me implement it this way.

public class FizzBuzz {
  public static void main(String[] args) {
    // Go from 1 to 100
    for (int i = 1; i <= 100; i++) {
      String result = "";
      if (i % 3 == 0) { // If divisible by 3
        result += "Fizz";
      }
      if (i % 5 == 0) { // If divisible by 5
        result += "Buzz";
      }
      // If it was divisible by either 3 or 5 (or both), print Fizz, Buzz, or FizzBuzz accordingly.
      if (i % 3 == 0 || i % 5 == 0) {
        System.out.println(result);
      } else { // Or else just print the integer
        System.out.println(i);
      }
    }
  }


texts:
I had posted this here and was asked to move it to code review since my code works and am looking for the best possible solution : original post

NOTE: I have seen the JOIN in GAE related posts but GROUP BY in my requirements made me make a new post and I have made a solution of my own which I wanted to check how good is it.

Datastore Entities properties and types (database)

Entity : PartyEntity let's call this as a

String partyName
String partyId
BlobKey image

Entity : InsertEntity let's call this as b

String partyIdentifier
String name
String constituency

Objective

SELECT * FROM a JOIN b on a.partyId = b.partyIdentifier GROUP BY b.constituency;

The solution I made is as follows.  Do suggest any changes or better ideas.

// SELECT * FROM a (PartyEntity holds unique partyId) and for each partyId SELECT * FROM b

private List<ListDisplay> initData() {

    DatastoreService datastore = DatastoreServiceFactory
            .getDatastoreService();

    List<ListDisplay> data = new ArrayList<ListDisplay>();

    Query query = new Query("PartyEntity");
    PreparedQuery preparedQuery = datastore.prepare(query);
    List<Entity> entities = preparedQuery.asList(FetchOptions.Builder
            .withDefaults());

    for (Entity entity : entities) {

        String PARTY_ID = (String) entity.getProperty("partyId");

        // fetch from another
        Query query2 = new Query("InsertEntity");
        Filter filterByPartyId = new Query.FilterPredicate(
                "partyIdentifier", FilterOperator.EQUAL, PARTY_ID);
        query2.setFilter(filterByPartyId);
        PreparedQuery preparedQuery2 = datastore.prepare(query2);

        List<Entity> entities2 = preparedQuery2.asList(FetchOptions.Builder
                    .withDefaults());

        for (Entity entity2 : entities2) {
            ListDisplay display = new ListDisplay();
            display.setPartyId((String) entity.getProperty("partyId"));
            display.setPartyName((String) entity.getProperty("partyName"));
            display.setImage((BlobKey) entity.getProperty("image"));
            display.setName((String) entity2.getProperty("name"));
            display.setConstituency((String) entity2
                    .getProperty("constituency"));
            data.add(display);
        } // end loop entity2

    } // end loop entity

    return data;
}

// GROUP BY constituency clause part

public HashMap<String, List<ListDisplay>> getData() {
    HashMap<String, List<ListDisplay>> data = new HashMap<>();
    List<ListDisplay> list = initData();

    for (ListDisplay d : list) {
        // if null add
        if (data.get(d.getConstituency()) == null) {
            List<ListDisplay> internal = new ArrayList<>();
            internal.add(d);
            data.put(d.getConstituency(), internal);
        }
        // else modify
        else {
            List<ListDisplay> hashlist = data.get(d.getConstituency());
            hashlist.add(d);
            data.remove(d.getConstituency());
            data.put(d.getConstituency(), hashlist);
        }
    }

    return data;
}


texts:
This was found on CodeEval.

Challenge: Write a program that prints out the final series of numbers where those divisible by X, Y and both are replaced by “F” for fizz, “B” for buzz and “FB” for fizz buzz

Specifications: Your program should accept a file as its first argument. The file contains multiple separated lines; each line contains 3 numbers that are space delimited. The first number is the first divider (X), the second number is the second divider (Y), and the third number is how far you should count (N). You may assume that the input file is formatted correctly and the numbers are valid positive integers. your output should print out one line per set. Ensure that there are no trailing empty spaces in each line you print.

Sample Input:

  3 5 10
  2 7 15

Sample Output:

  1 2 F 4 B F 7 8 F B
  1 F 3 F 5 F B F 9 F 11 F 13 FB 15

My Implementation:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class FizzBuzz {
    public static void main(String[] args) throws FileNotFoundException {
        File file = new File(args[0]);
        Scanner fileScanner = new Scanner(file);
        while (fileScanner.hasNextLine()) {
            printFizzBuzz(fileScanner.nextLine());
        }
    }

    public static void printFizzBuzz(String line) {
        int fizz = Integer.parseInt(line.split(" ")[0]);
        int buzz = Integer.parseInt(line.split(" ")[1]);
        int limit = Integer.parseInt(line.split(" ")[2]);

        StringBuilder sb = new StringBuilder();

        for (int i = 1; i <= limit; i++) {
            if (i % fizz == 0) { sb.append("F"); }
            if (i % buzz == 0) { sb.append("B"); }
            else { if (i % fizz != 0) { sb.append(i); } }
            if (i < limit) { sb.append(" "); }
        }
        System.out.println(sb.toString());
    }
}


texts:
I am new to Python and would like to get helpful tips and suggestions on this code. Would be awesome if you provide info if anything is fundamentally incorrect, improve the algorithm, and any room for further improvements.

class Game:
  def __init__(self):
    self.board = ["0", "1", "2", "3", "4", "5", "6", "7", "8"]
    self.ai = "X"
    self.human = "O"

  def start_game(self):
    print(" %s | %s | %s \n=========\n %s | %s | %s \n=========\n %s | %s | %s \n" % \
        (self.board[0], self.board[1], self.board[2],
             self.board[3], self.board[4], self.board[5],
             self.board[6], self.board[7], self.board[8]))
    print("Enter number between [0-8]:")
    while not self.game_over(self.board) and not self.draw(self.board):
      self.get_human_position()
      if not self.game_over(self.board) and not self.draw(self.board):
        self.eval_board()

      print(" %s | %s | %s \n=========\n %s | %s | %s \n=========\n %s | %s | %s \n" % \
          (self.board[0], self.board[1], self.board[2],
               self.board[3], self.board[4], self.board[5],
               self.board[6], self.board[7], self.board[8]))

    print("Game over") # have to think of way to print Draw when it's a draw

  def get_human_position(self):
    spot = None
    while spot is None:
      spot = int(input())
      if self.board[spot] != "X" and self.board[spot] != "O":
        self.board[spot] = self.human
      else:
        spot = None

  def eval_board(self):
    spot = None
    while spot is None:
      if self.board[4] == "4":
        spot = 4
        self.board[spot] = self.ai
      else:
        spot = self.get_optimal_move(self.board, self.ai)
        if self.board[spot] != "X" and self.board[spot] != "O":
          self.board[spot] = self.ai
        else:
          spot = None

  def get_optimal_move(self, board, next_player, depth = 0, highest_score = {}):
    available_spaces = [s for s in board if s != "X" and s != "O"]
    optimal_move = None

    for available in available_spaces:
      board[int(available)] = self.ai
      if self.game_over(board):
        optimal_move = int(available)
        board[int(available)] = available
        return optimal_move
      else:
        board[int(available)] = self.human
        if self.game_over(board):
          optimal_move = int(available)
          board[int(available)] = available
          return optimal_move
        else:
          board[int(available)] = available

    if optimal_move:
      return optimal_move
    else:
      return int(available_spaces[0])

  def three_in_row(self, *args):
    return args[0] == args[1] == args[2] == "X" or \
        args[0] == args[1] == args[2] == "O"

  def game_over(self, b):
    return self.three_in_row(b[0], b[1], b[2]) == 1 or \
        self.three_in_row(b[3], b[4], b[5]) == 1 or \
        self.three_in_row(b[6], b[7], b[8]) == 1 or \
        self.three_in_row(b[0], b[3], b[6]) == 1 or \
        self.three_in_row(b[1], b[4], b[7]) == 1 or \
        self.three_in_row(b[2], b[5], b[8]) == 1 or \
        self.three_in_row(b[0], b[4], b[8]) == 1 or \
        self.three_in_row(b[2], b[4], b[6]) == 1

  def draw(self, b):
    return len([s for s in b if s == "X" or s == "O"]) == 9

if __name__ == '__main__':
  game = Game()
  game.start_game()

Currently I do want to fix the Draw portion where I would print Draw instead of game-over when it is a draw.


texts: CLRS Exercise 2.3-4: Recursive Insertion Sort

texts:
I'm going through CLRS 3e and executing exercises to obtain a better understanding of CS fundamentals.

Below is my solution to the following exercise from chapter 2:

  We can express insertion sort as a recursive procedure as follows. In order to sort \$A[*1..n*]\$, we recursively sort \$A[*1..n-1*]\$ and then insert \$A[*n*]\$ into the sorted array \$A[*1..n-1*]\$. Write a recurrence for the running time of this recursive version of insertion sort.

I was able to come up with a recurrence of:

T(N) = O(1) if N <= 1; T(N-1) + O(N) if N > 1

NOTE: The \$O\$ is supposed to represent theta notation.

import random

def recursive_insertion_sort(A, n):

    if n < 1:
        return A

    recursive_insertion_sort(A, n - 1)

    key = A[n]

    while n > 0 and key < A[n - 1]:
        A[n] = A[n - 1]
        n -= 1

    A[n] = key
    return A

A = [3, 1, 0, 2, 3]
B = random.sample(range(1, 11), 10)
C = random.sample(range(1, 11), 10)
D = random.sample(range(1, 11), 10)
E = [1]
F = []

assert recursive_insertion_sort(A, len(A) - 1) == sorted(A)
assert recursive_insertion_sort(B, len(B) - 1) == sorted(B)
assert recursive_insertion_sort(C, len(C) - 1) == sorted(C)
assert recursive_insertion_sort(D, len(D) - 1) == sorted(D)
assert recursive_insertion_sort(E, len(E) - 1) == sorted(E)
assert recursive_insertion_sort(F, len(F) - 1) == sorted(F)

I struggle with translating recursive algorithms to code. By my understanding this code is a correct recursive insertion sort due to the invariant that the array at \$A[0.. n - 1]\$ is a sorted array of the first \$n - 1\$ elements of the entire array \$A[0...n]\$.

I do not have a formal CS background so I'm unsure if this invariant holds up to more rigorous analysis. Furthermore if anyone has suggestions to how I can make this code cleaner that would be appreciated. As an aside I am trying to right this code w/o the use of built in functions aside from very primitive (ex. len()) functions.


texts: Count the number of leaders in both sides (slices) of an array in C#. Codility EquiLeaders task

texts:
EquiLeader

  A non-empty array A consisting of N integers is given.
  The leader of this array is the value that occurs in more than half of
  the elements of A.

  An equi leader is an index S such that 0 ≤ S < N − 1 and two sequences
  A[0], A[1], ..., A[S] and A[S + 1], A[S + 2], ..., A[N − 1] have
  leaders of the same value.

  For example, given array A such that:

A[0] = 4
A[1] = 3
A[2] = 4
A[3] = 4
A[4] = 4
A[5] = 2 we can find two equi leaders:

  0, because sequences: (4) and (3, 4, 4, 4, 2) have the same leader,
  whose value is 4. 2, because sequences: (4, 3, 4) and (4, 4, 2) have
  the same leader, whose value is 4. The goal is to count the number of
  equi leaders.

  Write a function:

  class Solution { public int solution(int[] A); }

  that, given a non-empty array A consisting of N integers, returns the
  number of equi leaders.

  For example, given:

A[0] = 4
A[1] = 3
A[2] = 4
A[3] = 4
A[4] = 4
A[5] = 2 the function should return 2, as explained above.

  Write an efficient algorithm for the following assumptions:

  N is an integer within the range [1..100,000]; each element of array A
  is an integer within the range [−1,000,000,000..1,000,000,000].

This is the code I wrote, final score is a 100%. It took me a couple of tries (and days) like most of the solutions I'm posting here. Is it good code? What can be improved? I saw a question about SOLID a couple of hours ago, and that led me to start reading about the subject. This exercises are very specific and won't be extended, so (I know I'm not applying this principles here) should I still apply those principles to this kind of exercises (to practice and get used to them) or just leave it to real life extensible things?

using System;
using System.Collections.Generic;

class Solution {
    public int solution(int[] A) {
        Dictionary<int, int> leftPartition = new Dictionary<int, int>();
        Dictionary<int, int> rightPartition = new Dictionary<int, int>();

        int leadersCounter = 0;
        int leftPartitionSize = 1, rightPartitionSize = A.Length;
        int candidate, leader;

        for (int index = A.Length - 1; index >= 0; index--)
        {
            candidate = A[index];
            if (rightPartition.ContainsKey(candidate))
            {
                rightPartition[candidate]++;
            }
            else
            {
                rightPartition.Add(candidate, 1);
            }
        }
        leader = A[0];
        for (int index = 0; index < A.Length; index++)
        {
            candidate = A[index];
            if (leftPartition.ContainsKey(candidate))
            {
                leftPartition[candidate]++;
            }
            else
            {
                leftPartition.Add(candidate, 1);
            }
            rightPartition[candidate]--;
            rightPartitionSize--;
            if (leftPartition[candidate] > leftPartitionSize / 2)
            {
                leader = candidate;
            }
            if (leftPartition[leader] > leftPartitionSize / 2 && rightPartition[leader] > rightPartitionSize / 2 )
            {
                leadersCounter++;
            }
            leftPartitionSize++;
        }
        return leadersCounter;
    }
}


texts:
I've tried out a hybrid type of event management model, combining elements of the addEventListener-type and the onEvent-type. What I don't like about the addEventListener model is that you have to consult the documentation to choose the right event type, example: addEventListener("click", callback). What I don't like about the onEvent model is that you can only have one listener. Below is what I came up with.

Functions for registering listeners:

function onClick(callback, callbackToReplace) {
    _registerEventHandler(_clickCallbackList, callback, callbackToReplace);
}
function onChange(callback, callbackToReplace) {
    _registerEventHandler(_changeCallbackList, callback, callbackToReplace);
}

The implementation of the function that does the actual registering and removal of listeners:

function _registerEventHandler(callbackList, callback, callbackToReplace) {
    if(callbackToReplace && callbackList.length > 0 && Object.prototype.toString.call(callbackToReplace) === "[object Function]") {
        for(var i=0, l=callbackList.length; i<l; i++) {
            if(callbackToReplace === callbackList[i]) {
                if(callback && Object.prototype.toString.call(callback) === "[object Function]")  {
                    callbackList.splice(i, 1, callback);
                }
                else {
                    callbackList.splice(i, 1);
                }
            }
        }
    }
    else if(callback && Object.prototype.toString.call(callback) === "[object Function]")  {
        callbackList.push(callback);
    }
}

The function used to trigger an event:

function _triggerCallbacks(callbackList, message) {
    for(var i = 0, l = callbackList.length; i<l; i++) {
        callbackList[i].call(null, message);
    }
}

Examples of registering listeners:

function func1(message) {
    // Insert code here
}
function func2(message) {
    // Insert code here
}
function func3(message) {
    // Insert code here
}

onClick(func1); // Add first function
onClick(func2); // Add second function
onClick(func3, func2); // Replace second function with third function
onClick(null, func3); // Remove third function

If you're just adding listeners you simply skip the second argument, making it simple to use when simple is sufficient, but you can also replace and remove with a the same single method making use of the second argument.
The model does require a separate method for each event type. This is a serious drawback since it makes changes to the interface of the module (compared to the extensible addEventListener model). On the other hand, adding support for new events in the addEventListener model requires publicizing this in some way, for example by adding a constant describing the event type. So, adding support for a new Event-type could be said to be functionally equivalent between the models (you still have to change the code, but you do it in different places).

I'm looking for some feedback on this hybrid model - positive and negative. I've used it in a couple of modules and it works fine, but I am concerned with size of the interface (requires more public functions) and the non-standard nature of the event handling model - will it be difficult for programmers to use the module just because it's non-standard and similar.


texts: htaccess for URL remapping, caching, and compression

texts:
I have been collecting snippets from all over the place and then put them all together creating the following .htaccess file.

I really don't understand if what I have done below is good/should work as expected, so your opinion is really appreciated.

I also don't understand the bit just after #Leverage Browser Caching.  Can anyone please explain it to me?

# Date 2 2 2014

ErrorDocument 404 /404

RewriteEngine On
RewriteBase /

    # Redirect if it begins with www.
RewriteCond %{HTTP_HOST} ^www\.(.*)$
RewriteRule ^ http://%1%{REQUEST_URI} [R=301,L]

    # Remove enter code here.php; use THE_REQUEST to prevent infinite loops
    # By puting the L-flag here, the request gets redirected immediately
RewriteCond %{THE_REQUEST} ^GET\ (.*)\.php\ HTTP
RewriteRule (.*)\.php$ $1 [R=301,L]

    # Remove /index
    # By puting the L-flag here, the request gets redirected immediately
    # The trailing slash is removed in a next request, so be efficient and dont put it on there at all
RewriteRule (.*)/index$ $1 [R=301,L]

    # Remove slash if not directory
    # By puting the L-flag here, the request gets redirected immediately
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} /$
RewriteRule (.*)/ $1 [R=301,L]

    # Add .php to access file, but don't redirect
    # On some hosts RewriteCond %{REQUEST_FILENAME}.php -f will be true, even if
    # no such file exists. Be safe and add an extra condition
    # There is no point in escaping a dot in a string
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteCond %{REQUEST_URI} !(/|\.php)$
RewriteRule (.*) $1.php [L]

    # Change the sitemap extension from .php to .xml
RewriteRule ^sitemap.xml(.*)$ /sitemap.php?$1

    # Leverage Browser Caching
    # 480 weeks
<FilesMatch "\.(ico|pdf|flv|jpg|jpeg|png|gif|js|css|swf)$">
    Header set Cache-Control "max-age=290304000, public"
</FilesMatch>

    # 2 DAYS
<FilesMatch "\.(xml|txt)$">
    Header set Cache-Control "max-age=172800, public, must-revalidate"
</FilesMatch>

    # 2 HOURS
<FilesMatch "\.(html|htm)$">
    Header set Cache-Control "max-age=7200, must-revalidate"
</FilesMatch>

<IfModule mod_deflate.c>
    #The following line is enough for .js and .css
AddOutputFilter DEFLATE js css
AddOutputFilterByType DEFLATE text/plain text/xml application/xhtml+xml text/css application/xml application/rss+xml application/atom_xml application/x-javascript application/x-httpd-php application/x-httpd-fastphp text/html

    #The following lines are to avoid bugs with some browsers
BrowserMatch ^Mozilla/4 gzip-only-text/html
BrowserMatch ^Mozilla/4\.0[678] no-gzip
BrowserMatch \bMSIE !no-gzip !gzip-only-text/html


texts:
I have written a small Twitter clone using NodeJs, MongoDB and RabbitMQ, which you can find here.

I started this project because I wanted to get a better understanding of both NodeJs and Rabbit. I'm still learning so if anyone has any comment, suggestion, advice, it would be very appreciated.

All the sources are on my GitHub repo.

One of the weak point is the class responsible for the MongoDb connection:

export class DbFactory implements IDbFactory {
private _dbs: any;

public constructor() {
    this._dbs = {};
}

public async getDb(connectionString: string): Promise<Db> {
    const db = this._dbs[connectionString] as Db;
    if (db) {
        return db;
    }

    let newDb = await MongoClient.connect(connectionString);

    newDb = newDb.on('close', () => {
        console.log('-> lost connection');
        this._dbs[connectionString] = newDb;
    }).on('error', () => {
        console.log('-> on error');
        this._dbs[connectionString] = newDb;
    }).on('reconnect', () => {
        console.log('-> reconnected');
        this._dbs[connectionString] = newDb;
    }).on('connected', function () {
        console.log('Mongo DB connection open for DB');
    });

    this._dbs[connectionString] = newDb;
    return newDb;
}

public async close(connectionString: string): Promise<void> {
    const db = await this.getDb(connectionString);
    if (!db) {
        return;
    }

    delete this._dbs[connectionString];
    return db.close();
}
}

I am injecting an instance into this one:

export class RepositoryFactory implements IRepositoryFactory {
constructor(private readonly _dbFactory: IDbFactory) { }

public async create<T>(options: IRepositoryOptions): Promise<IRepository<T>> {
    const db = await this._dbFactory.getDb(options.connectionString),
        coll = db.collection<T>(options.collectionName),
        repo = new BaseRepository<T>(coll);

    return repo;
}
}

Which is instantiated during the startup. It's working perfectly, but I am not sure this is the right approach to handle the db connection.


texts: Parse sentences and calculate mathematical results

texts:
Content of task:

  Given a string of words and numbers. Extract the expression including:

  the operator: either addition or subtraction
  the two numbers that we are operating on

  Return the result of the calculation.

  Example:

  "Panda has 48 apples and loses 4" returns 44

  "Jerry has 34 apples and gains 6" returns 40

  "loses" and "gains" are the only two words describing operators.

  Should be a nice little kata for you :)

  Note: No fruit debts nor bitten apples = The numbers are integers and
  no negatives

  source: codewars.com

I want to optimise so ugly code:

def calculate(string)
  operator = '-' if string.split(' ').include? 'loses'
  operator = '+' if string.split(' ').include? 'gains'
  sum = 0
  count = 0
  n1 = 0
  n2 = 0
  string.split(' ').map do |s|
    if s.to_i != 0 && s.to_i.is_a?(Numeric)
      if count == 0
        n1 = s.to_i
        count += 1
      else
        n2 = s.to_i
      end
    end
  end
  n1.method(operator).(n2)
end

This code nice works(all tests was passed). But I don't want a large number of variables. Maybe have you some advice how to optimise this code? Thank you in advance.


texts:
I have subclassed Qt QAbstractTableModel with QJsonDocument as data source which I have reimplemented the setData() method in:

bool UeJsonPlacesTableModel::setData(const QModelIndex& index,
                                     const QVariant& value,
                                     int role)
{
    if(role!=Qt::EditRole||
             index.row()<0||
             index.row()>=this->m_ueJsonData.isArray()?this->m_ueJsonData.array().size():this->m_ueJsonData.isObject()?this->m_ueJsonData.object().size():0||
             index.column()<0||
             index.column()>=this->m_ueJsonData.isArray()?this->m_ueJsonData.array().size():this->m_ueJsonData.isObject()?this->m_ueJsonData.object().size()>0?this->m_ueJsonData.object().size():0:0)
    {
        return false;
    }   // if

    QVariantList dataList=this->m_ueJsonData.toVariant().toList();
    QVariantMap dataVariantMap=this->m_ueJsonData.toVariant().toList().at(index.row()).toMap();
    QVariantMap::const_iterator dataIterator=dataVariantMap.constBegin();
    int dataIndex=0;
    QString keyName=QString();
    QString dataValue=QString();

    while(dataIterator!=dataVariantMap.constEnd())
    {
        if(dataIndex==index.column())
        {
            keyName=dataVariantMap.keys().at(dataIndex);
        }
        else
        {
            dataIterator++;
            dataIndex++;
        }   // if
    }   // while

    QVariantMap changedData;

    changedData.insert(keyName,
                       value.toString());

    dataList.replace(index.row(),
                     changedData);

    this->m_ueJsonData=QJsonDocument::fromVariant(dataList);

    emit(dataChanged(index,
                     index));

    return true;
}   // setData

My humble opinion is that the code is very ugly. Can someone show me guidelines for its optimisation?


texts: Displaying styled validation messages to user

texts:
I'm new to AJAX and jQuery, and just for testing, I created this simple code. When the user enters their First Name and their Last Name it displays a message that says

  Thanks for entering everything correctly!

in Bluish color, and when the user forgets to enter their First Name and their Last Name it displays an error that says

  You didn't entered anything

in Red color or something similar.  I know it sounds stupid, but this is just testing.

change_name.php

function displayError($error)
{
    // Display a div with a class of error, We style it using CSS
    echo "
$error

";
}

function displayMessage($message)
{
    // Display a div with a class of message, We style it using CSS
    echo "
$message

";
}

if (isset($_POST['first_name']) && isset($_POST['last_name'])) {
    if (empty($_POST['first_name']) && empty($_POST['last_name'])) {
        displayError('You didn\'t entered anything!');
    } else if (empty($_POST['first_name'])) {
        displayError('You didn\'t entered your first name!');
    } else if (empty($_POST['last_name'])) {
        displayError('You didn\'t entered your last name!');
    } else {
        displayMessage('Thanks for entering everything correctly!');
    }
}

JavaScript

$(document).ready(function(){
    $('#nameChange').on('submit', function (e) {

        $.ajax({
            type: 'POST',
            url: 'ajax/change_name.php',
            data: $(this).serialize(),
            success: function(data) {
               $('.result').empty().append(data);
            }
        });

        e.preventDefault();
    });
});

index.php

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>jQuery AJAX</title>

    <form action="ajax/change_name.php" method="POST" id="nameChange">

        Result:

        First Name:
        <input type="text" name="first_name" id="first_name">

        Last Name:
        <input type="text" name="last_name" id="last_name">

        <input type="submit" name="change_name" value="Change" id="change_name">
    </form>

Is it a good practice to display a
 and then add a class to it, so you can then style it using CSS? Is there a better way for doing this?


texts: Local branch update script using Git and PHP

texts:
I'm using Git and PHP to create an update script which is sync local branch and the master. It checks about new updates, and if yes, it proceeds to the Git pull request and any response got from the sync may send to the server via CURL. What kind of area should I improve for this script and how do I modify it to work with OSX?

 <?php

$getGit                         = new stdClass();
$getGit->lastLocalCommitDate    = array();
$getGit->lastLocalCommitId      = array();
$getGit->lastLocalCommitMessage = array();
$getGit->lastRemoteCommitId     = array();
$getGit->pullOutput             = array();

include_once dirname(__FILE__) . '/../Modal/config.php';

#change the directory

exec("cd ~/system");

#get the date from last commit from git

exec("git log -1 --format=%cd", $getGit->lastLocalCommitDate);
$getDateObject = new DateTime($getGit->lastLocalCommitDate[0]);

#get the last commit id from git

exec("git rev-parse HEAD", $getGit->lastLocalCommitId);

#get the last commit message from git

exec("git log -1 --pretty=%B", $getGit->lastLocalCommitMessage);

#get the last commit id from remote branch

exec("git ls-remote git@github.com:xxx/xxx.git | head -1 | sed 's/HEAD//'", $getGit->lastRemoteCommitId);

#check if the branch is uptodate

if ($getGit->lastLocalCommitId[0] == $getGit->lastRemoteCommitId[0]) {

    $getGit->pullOutput = array(
        'System is upto date'
    );

} else {

    #Trying to get the pull requested from the branch/master
    exec("git pull", $getGit->pullOutput);

}

#clear all stdClass object arrays if not all output getting append to the array

unset($getGit->lastLocalCommitDate);
unset($getGit->lastLocalCommitId);
unset($getGit->lastLocalCommitMessage);
unset($getGit->lastRemoteCommitId);

#get the date from last commit from git

exec("git log -1 --format=%cd", $getGit->lastLocalCommitDate);
$getDateObject = new DateTime($getGit->lastLocalCommitDate[0]);

#get the last commit id from git

exec("git rev-parse HEAD", $getGit->lastLocalCommitId);

#get the last commit message from git

exec("git log -1 --pretty=%B", $getGit->lastLocalCommitMessage);

#curlClass

class curl
{

    private $ch;
    public $serverReturn;
    public $url;
    public $data;

    public function __construct($url, $data)
    {
        $this->url  = $url;
        $this->data = $data;
    }

    public function sendCurl()
    {

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $this->url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($this->data));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $serverReturn = json_decode(curl_exec($ch), true);
        curl_close($ch);

        return $serverReturn;

    }

}

#post pull requested update though curl

$curlObject = new curl('https://xxx.com/xxx/xxx.php', array(
    'branch' => DATABASE,
    'commitId' => $getGit->lastLocalCommitId[0],
    'commitM' => $getGit->lastLocalCommitMessage[0],
    'lastUpdateDate' => $getDateObject->format('Y-m-d H:i:s'),
    'response' => implode(',', $getGit->pullOutput)
));

$curlObject->sendCurl();

?>


texts: Asynchronous task and close sql connection

texts:
The following code compiles correctly:

    public ContextStatus Commit(string userName)
    {
        var status = new ContextStatus();

        var task = Task.Run(async () => { status = await CommitAsync(userName, new CancellationToken()); });
        task.Wait();

        return status;
    }

    public async Task<ContextStatus> CommitAsync(string userName, CancellationToken ct)
    {
        var status = new ContextStatus();

        try
        {
            if (this.Database.Connection.State == ConnectionState.Closed)
            {
                await this.Database.Connection.OpenAsync(ct).ConfigureAwait(false);
            }

            using (var command = this.Database.Connection.CreateCommand())
            {
                SqlParameter param = new SqlParameter()
                {
                    ParameterName = "@user",
                    SqlDbType = SqlDbType.VarChar,
                    Size = 127,
                    Value = userName
                };

                command.CommandText = "setcontextinfo";
                command.CommandType = CommandType.StoredProcedure;
                command.Parameters.Add(param);

                await command.ExecuteNonQueryAsync(ct).ConfigureAwait(false);
            }

            await base.SaveChangesAsync(ct).ConfigureAwait(false);
        }
        catch (DbEntityValidationException dbEx)
        {
            status.SetErrors(dbEx.EntityValidationErrors);
        }
        catch (DbUpdateException duEx)
        {
            status.SetErrors(duEx);
            if (!status.DatabaseErrors.Any())
                throw;
        }

        return status;
    }

Questions:

Will this CommitAsync method execute synchronously in the Commit method?
Is it best practive to pass new CancellationToken() in the Commit method?
Will the base.SaveChangesAsync() call in CommitAsync() close the connection if it was opened beforehand?


texts:
Exercise Description

Create a stop watch which has the following features:

"Start-/Stop" button
"Start-/Stop" button can be triggered by pressing the "s"-key.
"Record current time" button.
Display the recorded times since start.
"Record current time" button can be triggered by pressing the "t" key.
"Reset time" button which sets the timer counter back to 0 and deletes all time records.
"Reset time" button can be triggered by pressing the "r" key.

My Implementation

(function() {
  'use_strict';
  // -- VARIABLE DEFINITIONS ----------------------------------
  let currentTime;
  let timeRunning;
  let pastTimes = ['Past Times'];
  let intervalId;

  let startStop = document.getElementById('start-stop');
  let reset = document.getElementById('reset');
  let recordTime = document.getElementById('record-time');
  let currentTimeDisplay = document.getElementById('current-time-display');
  let pastTimesDisplay = document.getElementById('past-times-display');

  // -- FUNCTION DEFINITIONS ----------------------------------
  function init() {
    if (intervalId) {
      clearInterval(intervalId);
    }

    currentTime = 0;
    timeRunning = false;
    pastTimes.length = 1;
    currentTimeDisplay
      .textContent = currentTime;

    listPastTimes();
  }

  function triggerStartStop() {
    if (!timeRunning) {
      timeRunning = true;

      intervalId = setInterval(() => {
        currentTime += 10; // Increment

        currentTimeDisplay.textContent = // Write
          (currentTime / 1000).toFixed(2);
      }, 10);
    } else {
      clearInterval(intervalId);
      timeRunning = false;
    }
  }

  function listPastTimes() {
    var html = '
';

    pastTimes.forEach((item) => {
      html += '
' + item + '
';
    });

    pastTimesDisplay.innerHTML = html + '
';
  }

  function recordCurrentTime() {
    pastTimes.push((currentTime / 1000).toFixed(2));
    listPastTimes();
  }

  // -- ATTACHING EVENT HANDLER ------------------------
  startStop.addEventListener('click', triggerStartStop);
  reset.addEventListener('click', init);
  recordTime.addEventListener('click', recordCurrentTime);

  startStop.addEventListener('keydown', (event) => {
    if (event.keyCode === 83) { // 83 === 's' in ASCII
      triggerStartStop();
    }
  });

  reset.addEventListener('keydown', (event) => {
    if (event.keyCode === 82) { // 82 === 'r' in ASCII
      init();
    }
  });

  recordTime.addEventListener('keydown', (event) => {
    if (event.keyCode === 84) { // 84 === 't' in ASCII
      recordCurrentTime();
    }
  });

  init();
})();
body {
  font-family: Verdana;
  color: rgba(50, 50, 50, 1.0);
  background-color: rgba(250, 250, 250, 1.0);
}

.main-wrap {
  max-width: 800px;
  margin: 50px auto;
}

.navbar {
  margin: 20px 0;
}

#past-times-display li {
  list-style: none;
}

.subtitle {
  font-weight: 900;
  display: inline-block;
  margin-bottom: 10px;
}

.list-past-times li:nth-of-type(n+2) {
  margin-bottom: 6px;
}

Stopwatch Demo

    <button id="start-stop" tabindex="1">Start/Stop</button>
    <button id="reset" tabindex="2">Reset</button>
    <button id="record-time" tabindex="3">Record Time</button>

Has become quite a lot of code in the end.

Any ideas how one could accomplish the task with less code?
Are there points which could be improved or solved more elegantly?
Is everything done well?


texts:
The code takes a matrix and turns it into a tree of all the possible combinations.  It then "maps" the tree by setting the value of the ending nodes to the total distance of the nodes from beginning node to ending node.

It seems to work fairly well but I've got a couple questions:

Is a Python dict the best way to represent a tree?
Any ways to simplify, speed up, or otherwise make it more clean and legible?

Keep in mind I'll need to sort the set so I can display the most attractive routes.

You can find the code on my GitHub page (starts at line 61).

def matrix_to_tree(nodes):
  """
  Creates a tree of all possible combinations of
  provided nodes in dict format
  """
  tree = {}
  for node in nodes:
    children = nodes[:]
    children.remove(node)
    tree[node] = matrix_to_tree(children)
  return tree

def set_start(tree, start):
  """
  Removes extraneous starting nodes if only one
  starting location is desired.
  """
  tree = tree[start]
  return tree

def set_end(tree, end):
  """
  Removes ending nodes when they are not the
  last node of the branch.  Used when one
  ending location is desired.
  """
  if tree[end]:
    del tree[end]
  nodes = tree.keys()
  if len(nodes) > 1:
    for node in nodes:
      set_end(tree[node], end)
  return tree

def map_tree(tree, matrix, start, distance=0):
  """
  Maps the distance from the root to each
  ending node.
  """
  for node in tree:
    new_distance = distance + node_distance(matrix, start, node)
    if tree[node]:
      map_tree(tree[node], matrix, node, new_distance)
    else:
      tree[node] = new_distance
  return tree

def node_distance(matrix, start, end):
  """
  Searches a matrix for the value of two
  points.
  """
  return matrix[start][end]

nodes = [key for key in x.keys()]
a = matrix_to_tree(nodes)
b = set_start(a, 'A')
c = set_end(b, 'G')
d = map_tree(c, x, 'A')
print(d)

Input example:

  {
         A: {B:1, C:2},
         B: {A:1, C:3},
         C: {A:2, B:3},
     }

Output example:

# 'A' being the root node with no ending node specified
{
    A: {B:{C:4}, C:{B:5}},
}