texts:
To get points which lie on the border of a rectangle, I use 4 for loops. At first I thought about creating Rectangle and using PathItterator, but it confused me very much. Is there a better way than mine?

int r = 5;
int x = 0;
int y = 0;
int length = r * 2 + 1;
for (int i = 0; i < length; i++) {
    System.out.print(String.format("(%d,%d) ", x - r + i, y - r));
}
System.out.println();
for (int i = 0; i < length; i++) {
    System.out.print(String.format("(%d,%d) ", x - r + i, y + r));
}        System.out.println();

for (int i = 0; i < length; i++) {
    System.out.print(String.format("(%d,%d) ", x - r , y - r+i));
}        System.out.println();

for (int i = 0; i < length; i++) {
    System.out.print(String.format("(%d,%d) ", x + r , y - r+i));
}
System.out.println();


texts:
I have a match arm in rust, I think it may be simplified, but after googling and read books, I haven't find the solution. Especially for the str_vec.pop(), it returns an option type, I have to write a meanless () to make it compileable.
pub fn simplify_path(path: &String) -> String {
    let mut str_vec: Vec<&str> = Vec::with_capacity(20);
    for line in path.split('/') {
        match line {
            "" | "." => {}
            ".." => {
                str_vec.pop();
                ()
            }
            _ => str_vec.push(line),
        }
    }

    "/".to_string() + &str_vec.join("/")
}


texts:
I'm just messing around with class inheritance. I originally had a separate goal in mind but I ended up here, and my new goal was to have a parent that was completely ignorant of it's self, i.e. no default attributes. This would seem to make it easier to subclass, the MeleClass could set; for instance canRange to True during instantiation without modifying the parent's parameters.

Questions:

Are there any other ways to do this?
How could this be bad?
Are there more efficient ways?

class Character:
    def __init__(self, **kwargs):
        for i in kwargs:
            setattr(self, i, kwargs[i])

class MeleClass(Character):
    def __init__(self, name="default", atk=1, deff=1):
        self.canRange = False
        Character.__init__(self, name=name, attack=atk, defence=deff)

class SpellClass(Character):
    def __init__(self, name="default", atk=1, deff=1):
        self.canRange = True
        Character.__init__(self, name=name, attack=atk, defence=deff)

p = MeleClass(name='TheLazyScripter')
print p.name
print p.attack
print p.canRange


texts:
I'm creating a chat UI with jQueryUI:

$.widget("ui.chatwindow", {
    options: {
        nickname: "obama";
    },
    setNickname: function(nick){
        var self = this;
        var id_pre = 'wchat_' + self.options.nickname;
        $('#' + id_pre + '\\:name').text(self.options.nickname);
    },
    setStatus: function(status){
            var self = this;
            var id_pre = 'wchat_' + self.options.nickname;
            switch(status){
                case 1:
                    $('#' + id_pre + '\\:status').removeAttr('class');
                    $('#' + id_pre + '\\:status').addClass('chat-icon-online');
                    $('#' + id_pre + '\\:status').attr('title','Online');
                    break;
                    ...
                default:
                    break;
            }
            ...
        },
    ...
}

I always write this in every method to change element class or text content:

var self = this;
var id_pre = 'wchat_' + self.options.nickname;

Is this a good or efficient way to code?


texts:
This is a subclass of Backbone.Collection with a method fetchNextPage that returns a Q promise.

To find out the next page's URL, it looks in meta.next from server response.
The server will return null for the last page.

It also has a getState method that returns a state with empty and fetching boolean variables.
When this state changes, it fires change:state event.

Finally, promiseAt is a convenience method that keeps fetching pages until it can return model at given index, or null if it can't.

(function (Backbone, q) {

  'use strict';

  window.st.Collection.PaginatedCollection = Backbone.Collection.extend({
    initialize: function () {
      _.bindAll(this, 'setFetchPromise');
      Backbone.Collection.initialize.apply(this, arguments);

      this.refreshState();
    },

    fetchNextPage: function () {
      if (this.isLastPage()) {
        return q();
      }

      if (this.fetchPromise) {
        return this.fetchPromise;
      }

      var fetchOptions,
          fetchPromise;

      fetchOptions = {
        remove: false,
        url: this.getNextPageUrl()
      };

      fetchPromise = this.fetch(fetchOptions)
        .finally(this.setFetchPromise/*(undefined)*/);

      return this.setFetchPromise(fetchPromise);
    },

    getNextPageUrl: function () {
      return this.lastResponse ?
        this.lastResponse.meta.next :
        this.url;
    },

    getState: function () {
      return {
        empty: this.isEmpty(),
        fetching: this.isFetching()
      };
    },

    isFetching: function () {
      return !!this.fetchPromise;
    },

    isLastPage: function () {
      if (!this.url) {
        return true;
      }

      if (!this.lastResponse) {
        return false;
      }

      return !this.lastResponse.meta.next;
    },

    parse: function (response) {
      this.lastResponse = response;
      return response.objects;
    },

    refreshState: function () {
      var newState = this.getState();
      if (_.isEqual(newState, this.state)) {
        return;
      }

      this.state = newState;
      this.trigger('change:state', newState);
    },

    setFetchPromise: function (promise) {
      this.fetchPromise = promise;
      this.refreshState();

      return promise;
    },

    promiseAt: function (index) {
      var _this = this;

      if (index < this.length - 1 || this.isLastPage()) {
        return q(this.at(index));
      }

      return this.fetchNextPage().then(function () {
        return _this.promiseAt(index);
      });
    }
  });
})(Backbone, Q);


texts: How to abstract DOM manipulation in a simple intuitive way

texts:
I am building a library to abstract DOM manipulation. Here's what the usage looks like:
  vsAddToSection() {

    let _inChapter: c.InChapter;

    let v$sections = vmap([], _ =>
      vh('div.section.item', {}, {
        listeners: {
          click: (e, __) => {
            this.ctrl.inSection(_inChapter, _)
          }
        }
      }, [h('span', _.name)]));

    let v$backToABook = this.vBackToABook(),
    v$backToBook = this.vBackToBook();

    let update = (inChapter: c.InChapter) => {
      _inChapter = inChapter;
      v$backToBook.update(inChapter);
      v$backToBook.update(inChapter);
      v$sections.update(inChapter.sections);
    };

    return [update, [
      v$backToABook,
      v$backToBook,
      h('div.sections', v$sections),
      vh('button', {}, {
        listeners: {
          click: (e, _) => {
            this.ctrl.toNew.pub(_inChapter);
          }
        }
      }, [h('i', '+'), h('span', 'New Section')])
    ]];
  }

  vAddToBookPopup() {

    let v$content = vex([h('div', 'default')]);

    let [vs$addToBookUpdate, vs$addToBook] = this.vsAddToBook(),
    [vs$addToChapterUpdate, vs$addToChapter] = this.vsAddToChapter(),
    [vs$addToSectionUpdate, vs$addToSection] = this.vsAddToSection();

    this.ctrl.addTo.sub(addTo => {
      if (c.isInABook(addTo)) {
        vs$addToBookUpdate(addTo);
        v$content.replace(vs$addToBook);
      } else if (c.isInBook(addTo)) {
        vs$addToChapterUpdate(addTo);
        v$content.replace(vs$addToChapter);
      } else if (c.isInChapter(addTo)) {
        vs$addToSectionUpdate(addTo);
        v$content.replace(vs$addToSection);
      } else if (c.isInSection(addTo)) {
        // console.log(addTo);
        // selected
      }
    });

    return h('div.popup.addtobook', [v$content]);
  }

vh creates a dom node, adds event listeners to it, etc.
h is a wrapper around vh.
vmap takes an array of data, and a function to create children dom nodes. The abstraction has an update method to update the array of data so it can remove old children dom nodes, and create and add new children.
vex takes an array of vh abstraction and has a replace method that replaces the dom contents with the new array of vh's.
this.ctrl.addTo.sub listens to an event that updates the dom, like this:
vs$addToBookUpdate(addTo);
v$content.replace(vs$addToBook);

This updates the contents of a piece of dom, and replaces the parent dom with that new piece of dom.
I return two values from vsAddToSection function, one for to update the abstraction, one returns the abstraction itself to append.
Hope this makes sense, my goal is simplicity, something that works, and avoid using external dependencies. Is this a little cumbersome, should I stick to a regular virtual dom approach?


texts:
I have written a class that connects to a database using MySQLi and has methods for the connection itself and returns the instance of the MySQLi class.

This works, but feels a little "clunky" and can be a bit slow, can someone help me to improve this?

The class is as follows:

<?php

/**
 * Connect to a db.
 */
class mysqli_connector
{
    /** Private to implement Singleton pattern */
    private function __construct() {  }

    private static $init;

    /** @return mysqli_connector */
    public static function Init()
    {
        return static::$init = (
                null === static::$init ? new self() : static::$init
            );
    }
    /** @var mysqli */
    private static $link;
    /**
     * Sets and gets the link to the database based on params
     * @param string $host
     * @param string $username
     * @param string $password
     * @param string $dbname
     * @return mysqli
     */
    public function link($host = '', $username = '', $password = '', $dbname = '')
    {
        static::$link = mysqli_init();
        if ($host != '' && $username != '' && $password != '' && $dbname != '')
        {
            static::$link->real_connect($host, $username, $password, $dbname);
        }
        else if ($host != '' && $username != '' && $password != '' && $dbname == '')
        {
            static::$link->real_connect($host, $username, $password);
        }
        else if ($host != '' && $username != '' && $password == '' && $dbname == '')
        {
            static::$link->real_connect($host, $username);
        }
        else if ($host != '' && $username == '' && $password == '' && $dbname == '')
        {
            static::$link->real_connect($host);
        }
        else
        {
            static::$link->real_connect();
        }
        return static::$link;
    }
}

EDIT

I use the class as such:

<?php

require_once 'include/class/_db/mysqli-connector.php';

$connector = mysqli_connector::Init();
$link = $connector->link("myhost", "mysuser", "mypass", "mydbname");
var_dump($link); # Make sure it works!

?>

Output from the var_dump($link);

object(mysqli)[2]
    public 'affected_rows' => int 0
    public 'client_info' => string 'mysqlnd 5.0.11-dev - 20120503 - $Id: /* removed for security */ $' (length=79)
    public 'client_version' => int 50011
    public 'connect_errno' => int 0
    public 'connect_error' => null
    public 'errno' => int 0
    public 'error' => string '' (length=0)
    public 'error_list' =>
        array (size=0)
            empty
    public 'field_count' => int 0
    public 'host_info' => string 'localhost via TCP/IP' (length=20)
    public 'info' => null
    public 'insert_id' => int 0
    public 'server_info' => string '5.6.26' (length=6)
    public 'server_version' => int 50626
    public 'stat' => string 'Uptime: 118450  Threads: 1  Questions: 149  Slow queries: 0  Opens: 70  Flush tables: 1  Open tables: 63  Queries per second avg: 0.001' (length=135)
    public 'sqlstate' => string '00000' (length=5)
    public 'protocol_version' => int 10
    public 'thread_id' => int 117
    public 'warning_count' => int 0


texts: Implementing quicksort with pivot of first, median or random

texts:
I am attempting to implement the quick sort algorithm whereby the pivot will be chosen by the user, and can either be median, first, or random. I am supposed to return a long that measures the number of times comp.compare() is invoked. I am wondering if you could review for me.

/**
     * The quick sort
     * @param arr the collection array
     * @param comp is the comparator
     * @param pivottype specifies where the pivot is going to be at, can either be "first", "middle", or "random"
     * @return returns the number of comparisons performed during the execution of the sorting algorithm
     */
    public static <E> long quickSort(E[] arr, Comparator<? super E> comp, String pivottype)
    {
        recursiveQuickSort(arr,0, arr.length -1,  pivottype, cp );
        return quickSortCounter;

    }
    private static<E> void recursiveQuickSort(E[] array, int first, int last, String pivottype, Comparator<? super E> comp)
    {
        if(first < last)
        {
            int pivotPosition = partition(array, first, last, cp, pivottype);
            if(pivotPosition > 1)
                recursiveQuickSort(array, first, pivotPosition-1, pivottype, cp);
            if(pivotPosition + 1 < last)
                recursiveQuickSort(array, pivotPosition + 1, last, pivottype, cp);
        }

    }
    private static <E> int partition(E[] collectionArray, int firstIndex, int lastIndex, Comparator<? super E> comp, String pivottype)
    {
        int pivotLocation;
        // counts the number of times the cp.compare() is called
        quickSortCounter = 0;

        if(pivottype.equals("first"))
        {
            pivotLocation = firstIndex;
        }
        else if(pivottype.equals("middle"))
        {
            pivotLocation = (firstIndex + lastIndex)/2;
        }
        else
        {

            pivotLocation = rand.nextInt(lastIndex - firstIndex) + firstIndex;
        }

        E pivotElement = collectionArray[pivotLocation];

        while(firstIndex <= lastIndex)
        {
            //scans right;
            while((firstIndex <= lastIndex) && (cp.compare(collectionArray[firstIndex], pivotElement) == -1))
            {
                firstIndex ++;
                quickSortCounter++;

            }
            //scans left
            while((lastIndex >= firstIndex) && (cp.compare(collectionArray[lastIndex], pivotElement) == 1) ||
                    (lastIndex >= firstIndex) && (cp.compare(collectionArray[lastIndex], pivotElement) == 0))
            {
                lastIndex--;
                quickSortCounter++;
            }
            if(firstIndex >  lastIndex)
            {
                swap(collectionArray, pivotLocation, lastIndex);
            }
            else
            {
                swap(collectionArray, firstIndex, lastIndex);
            }

        }
        return lastIndex;

    }
    private static <E> void swap(E[] array, int i, int j)
    {
        E temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }

}


texts: How to fill an ArrayList of ArrayLists with a Left Join?

texts:
I have a class Employee that contains an ArrayList of Projects.

I'm storing the Employees in one table, and the Projects in another.

I'm trying to find the best way to create an ArrayList of Employee objects based on a result set.  Simply creating an ArrayList of Employees based on a result set is pretty straightforward, but I'm finding that filling an ArrayList of Employees that each contains an ArrayList of Projects isn't so simple.

Right now, my getEmployees() function is using two nested SQL queries to accomplish this, something like this:

public ArrayList<Employee> getEmployees()
{
    PreparedStatement ps1 = null;
    ResultSet rs1 = null;
    PreparedStatement ps2 = null;
    ResultSet rs2 = null;

    ArrayList<Employee> employees = new ArrayList<Employee>();

    String query1 = "SELECT * FROM employees "
                  + "ORDER BY employee_id ASC";

    try
    {
        ps1 = conn.prepareStatement(query1);
        rs1 = ps1.executeQuery();

        while (rs1.next())
        {
            Employee employee = new Employee();

            int employeeID = rs1.getInt("employee_id");
            employee.setEmployeeID(employeeID);
            employee.setName(rs1.getString("employee_name"));

            // Get projects for this employee
            ArrayList<Project> projects = new ArrayList<Project>();

            String query2 = "SELECT * FROM projects "
                          + "WHERE employee_id = ?";

            ps2 = conn.prepareStatement(query2);
            ps2.setInt(1, employeeID);
            rs2 = ps2.executeQuery();

            while (rs2.next())
            {
                Project project = new Project();

                project.setProjectID(rs2.getInt("project_id"));
                project.setName(rs2.getInt("project_name"));

                projects.add(project);
            }

            employee.setProjects(projects);

            employees.add(employee);
        }

        return employees;
    }
    catch (SQLException e)
    {
        e.printStackTrace();
    }
    finally
    {
        try
        {
          // close result sets and prepared statements
        }
        catch (SQLException e)
        {
            e.printStackTrace();
        }
    }

    return null;
}

The above code works, but it seems messy to me.

Is there a way to do this without having to nest two separate SQL queries?  I've tried using a LEFT JOIN to get a single result set back, but I was unable to figure out a way to use that single result set to fill the ArrayList of Employees, each containing an ArrayList of Projects.

EDIT: Assume the tables have the following structures:

employees table:

employee_id  int(11)  NOT NULL  PRIMARY KEY  AUTO_INCREMENT
employee_name  varchar(60)  NOT NULL

projects table:

project_id  int(11)  NOT NULL  PRIMARY KEY  AUTO_INCREMENT
employee_id  int(11)  NOT NULL
project_name  varchar(60)  NULL


texts: Movie repository for storing movies based on country

texts:
The domain model of my application revolves around movies.

Use case:

We have a movie for which only one title (in one country) is known and we want to know titles of this movie in other countries. To get that information, we call external movie repositories.

The Movie class has a map of titles in countries. It also has a list of external IDs. For example, we might know that IMDB's ID for the movie Breakfast at Tiffany's is tt0054698.

class Movie {

    private Map<Country, String> titles;
    private Year yearOfRelease;
    private Map<ExternalMovieRepository, String> externalIds;

    public Map<Country, String> titles() {
        return titles;
    }

    public Year yearOfRelease() {
        return yearOfRelease;
    }

    public Map<ExternalMovieRepository, String> externalIds() {
        return externalIds;
    }

}

The ExternalMovieRepository enum is used as a key to which external ID value is mapped.

enum ExternalMovieRepository {

    IMDB, ROTTEN_TOMATOES;

}

The classes representing the external movie repositories will be able to find additional information only for Movie instances carrying some information the repository requires.

For example, RottenTomatoesMovieRepository requires the Movie instance either to have a US movie title (<Country, String> map entry) or the Rotten Tomatoes' external ID in its externalIds map.

Here is a draft for an interface that could represent the external repositories:

/**
 * Finds movie title for other countries using information from Movie.
 *
 */
interface MovieTitleFinder {

    boolean accepts( Movie m );

    Map<Country, String> findTitles( Movie m );

}

An implementation could look like this:

class RottenTomatoesTitleFinder implements MovieTitleFinder {

    private final String US_ISO = "us";

    private CountryRepository countryRepository;

    RottenTomatoesTitleFinder( CountryRepository countryRepository ) {
        this.countryRepository = countryRepository;
    }

    @Override
    public boolean accepts( Movie m ) {
        return ( getUSTitle( m ) != null || getRTId( m ) != null );
    }

    @Override
    public Map<Country, String> findTitles( Movie m ) {
        String rtId = getRTId( m );
        if ( rtId != null ) {
            return findByRTid( rtId );
        }
        String usTitle = getUSTitle( m );
        if ( usTitle != null ) {
            return findByUSTitle( usTitle );
        }
        return Collections.emptyMap();
    }

    private String getUSTitle( Movie m ) {
        Country us = countryRepository.findByIso( US_ISO );
        return ( m.titles().get( us ) );
    }

    private String getRTId( Movie m ) {
        return ( m.externalIds().get( ExternalMovieRepository.ROTTEN_TOMATOES ) );
    }

    private Map<Country, String> findByUSTitle( String usTitle ) {
        // call some collaborating object
    }

    private Map<Country, String> findByRTid( String rtId ) {
        // call some collaborating object
    }

}

Could this design be improved?


texts:
I created this abstract class:

public abstract class MeasurementType {
  protected String name;
  protected String[] units;

  public MeasurementType() {}

  public MeasurementType(String name) {
    this.name = name;
  }

  protected void setName(String name) {
    this.name = name;
  }

  protected String getName() {
    return name;
  }

  protected void setUnits(String[] values) {
    this.units = values;
  }
}

Then I thought to create to other classes that were its subtypes:

public class Acceleration extends MeasurementType {
  private String name;

  public Acceleration () {
    super();
  }

  public Acceleration(String name) {
    super();
  }
}

public class Density extends MeasurementType {
  private String name;

  public Density() {
    super();
  }

  public Density(String name) {
    super();
  }
}

Plenty to choose from but these were the first two types that cam to my mind, the first question might be what the need for the subtypes are since there isn't anything in those classes that differentiates them apart enough (at least in my implementations) to give them the right to exist as their own entities, but for the sake of the example, lets say they had their own arrays containing units for each distinct type, so density would have kilograms, grams etc.. and acceleration would have mph, kmph etc..

Finally, I have this run class which I quickly made up:

public class run {

  public run() {}

  public static MeasurementType testType() {
    Acceleration a = new Acceleration("meters per second");
    return (MeasurementType) a;
  }

  public static void main(String[] args) {
    MeasurementType mt = testType();
    System.out.println(mt.getClass().toString());
    System.out.println(mt.getClass().getName());

    String type = "acceleration";
    String[] units = new String[8];

    Object mType;
    if(type.equals("acceleration")) {
      mType = new Acceleration();
    } else if(type.equals("density")) {
      mType = new Density();
    } else {
      mType = new Object();
    }

    System.out.println(mType.getName());
  }
}

This is where I encountered the problem that I was thinking about. I was using strings to determine the type that I would instantiate, but the problem is, by default right at the end of the conditional statements I instantiate Object because otherwise the compiler would complain that the mType variable wouldn't have been initialised. I can't create a MeasurementType object since it is an abstract class.

I guess this is more of a design question, but is there a better way of determining the class to instantiate? Please assume that the String type = "acceleration" came from a drop down or somewhere from some user interface, I have just hard coded it in because it isn't really necessary for the question.

Could someone please shed some light on this design fault as I see it please?


texts:
There is a global exception handler in our WebAPI application that looks like the following:

public class ApiExceptionHandler : IExceptionHandler
{
    public async Task HandleAsync(ExceptionHandlerContext context, CancellationToken cancellationToken)
    {

        var exceptionType = context.Exception.GetType();

        if (exceptionType == typeof(ResourceNotFoundException))
        {
            context.Result = new ResponseMessageResult(
                context.Request.CreateResponse(HttpStatusCode.NotFound, context.Exception.Message));
        }

        else if (exceptionType == typeof(UserNotFoundException))
        {
            context.Result = new ResponseMessageResult(
                context.Request.CreateResponse(HttpStatusCode.Unauthorized, context.Exception.Message));
        }

        else if (exceptionType == typeof(UserAlreadyExistsExeption))
        {
            context.Result = new ResponseMessageResult(
                context.Request.CreateResponse(HttpStatusCode.Conflict, context.Exception.Message));
        }

        ...

        else
        {
            context.Result = new ResponseMessageResult(
                context.Request.CreateResponse(HttpStatusCode.InternalServerError, "An unexpected error occured"));
        }
    }
}

And each exception has the following form:

public class UserAlreadyExistsExeption: Exception
{
    public UserAlreadyExistsExeption()
    {
    }

    public UserAlreadyExistsExeption(string message) : base(message)
    {
    }

    public UserAlreadyExistsExeption(string message, Exception inner) : base(message, inner)
    {

    }
}

And can be thrown in the code like the following:

//If user exists
throw new UserAlreadyExistsExeption("User already exists");

I was thinking of making all our custom exceptions implement a IHasHttpErrorCode so each one has its own HttpErrorCode - usage like the following:

Interface:

public interface IHasHttpErrorCode
{
    HttpStatusCode GetHttpStatusCode();
}

Exception:

public class UserAlreadyExistsExeption: Exception, IHasHttpErrorCode
{
    public UserAlreadyExistsExeption()
    {
    }

    public UserAlreadyExistsExeption(string message) : base(message)
    {
    }

    public UserAlreadyExistsExeption(string message, Exception inner) : base(message, inner)
    {

    }

    public HttpStatusCode GetHttpStatusCode() {
        return HttpStatusCode.Conflict;
    }
}

Global Error Handler:

public class ApiExceptionHandler : IExceptionHandler
{
    public async Task HandleAsync(ExceptionHandlerContext context, CancellationToken cancellationToken)
    {

        var exceptionType = context.Exception as IHasHttpErrorCode;

        if (customException != null) {
            context.Result = new ResponseMessageResult(
                context.Request.CreateResponse(customException.GetHttpStatusCode(), context.Exception.Message));
        }
        else
        {
            context.Result = new ResponseMessageResult(
                context.Request.CreateResponse(HttpStatusCode.InternalServerError, "An unexpected error occured"));
        }
    }
}

Is this a valid approach to improve the existing code? Is there anything else I should look to improve?


texts: Find longest sequence of zeroes in a binary representation of an integer

texts:
I am aware this problem has been asked before but in java e.g Printing longest sequence of zeroes. This is a similar problem but in C#. A brief explanation of the problem is  to find the longest sequence of zeroes in a binary representation of an Integer. For instance, the Integer 529 in binary gives 1000010001  and the longest sequence of zeroes is 4. So far I have achieved this using the following code

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

class Program
{
    public static int Solution(int N)
    {
        List<int> occurenceCount = new List<int>();
        int Counter=0,value;

        if(N == 0)
        {
            Console.WriteLine(0);
            return 0;
        }

        else{
            string binaryRep = Convert.ToString(N,2);

            // find the first occurence of 1
            int FirstIndex = binaryRep.IndexOf("1");

            // find the last occurence of 1
            int LastIndex = binaryRep.LastIndexOf("1");

            for(int i = FirstIndex; i<LastIndex+1;)
            {

                value = i;

                while(binaryRep[value++] != '1' )
                {
                  Counter = Counter+1;
                }
                occurenceCount.Add(Counter);
                i= value;
               Counter=0;
            }
        return occurenceCount.Max();
        }
    }
    static void Main()
    {
       Console.WriteLine(Solution(1041));
    }
}

Brief description of the code: If the Integer passed is 0, then 0 is returned else the longest sequence. The convert.ToString() gives the binary representation. To improve the performance, I keep track of the index of the first 1 and the last index of 1  and use this in the for loop. In the while  loop, once a 0 is encountered in between two 1's then a counter is incremented until a 1 is encountered and later on added to the List.
I would appreciate if any one can tell me how to improve on this.


texts: Rspec test for Rails method to return alphabetically sorted list of tags

texts:
I have one model class as listed here:

class Post < ActiveRecord::Base
  has_many :comments

  def tags
    comments.map(&:tag).uniq.sort
  end
end

and below is the best rspec as per my understanding:

context 'tags' do
  let(:post) { Post.find_by_code('TX') }

  it 'returns sorted alphabetically list of available tags' do
    expect(post.tags).to eq(post.comments.map(&:tag).uniq.sort)
  end
end

Do we any better way to test it or even it is nor require to test.


texts: Getting the first selected item from a list of Backbone models

texts:
Current code (ES6):

getSelectedItem() {
    let result;
    return ((result = this.getItems().map((s) => {
        return Util.isItemSelected(s.toJSON()) ? s.toJSON() : false;
    }).filter(Boolean)) && result.length) ? result[0] : null;
},

s is a Backbone.js Model (hence the need to .toJSON() on it).

Apart from a very generic, "How can I improve this?", I'm specifically looking to reduce the duplication of .toJSON(), the anonymous function I pass into .map() and then also the need to declare result outside of my return statement.


texts: Find if a part of the integer from another integer is divisible by 7?

texts:
The question states:

  Given an integer A, and two indices Li, Ri. Find if the number from A which is bounded by the two indices is divisible by 7?

  For example if A = 357753
  indices Li = 3, Ri = 4, then the number is 77, which is divisible.

My program give a time limit exceeded when executed for larger numbers. Are there any other performance improvement can be done in my code. Or the whole method is wrong for the solution. Any help would be appreciated. "q" is the number of indices that will be provided as input.

First code (not optimized):

inp = raw_input()

q = input()

temp = ""

for i in range(q):

    l, r = map(int, raw_input().split())

    temp =  int(inp[l - 1:r])

    if temp % 7 == 0:

        print "YES"
    else:

        print "NO"

My second program is:

inp = input()

q = input()

temp = 0
length = len(str(inp)) - 1
for i in range(q):

    left, right = map(int, raw_input().split())

    temp = inp
    end = length - right + 1
    temp = temp / (10 ** end)
    mul = 1
    final = 0

    while right >= left:

        cur = temp % 10
        temp = temp / 10
        right -= 1
        #print cur
        final += (cur * mul)
        mul = mul * 10

    if final % 7 == 0:

        print "YES"
    else:

        print "NO"


texts:
It's common pattern when you need to assign a variable inside a block

def query(sql)
  logger.debug "Db: Executing query #{sql}"
  result = nil
  ts = Benchmark.realtime do
    result = @db.exec sql
  end
  logger.debug "Db: Query completed in #{ts}"
  result
end

Is there a more elegant way to rewrite this snippet?


texts:
So I am learning hooks and context, and I wanted to make a simple router. I wanted a simple API where you can just pass in routes. initialRoute should be optional, and it should pick it up from the pathname, otherwise it defaults to the first route.

I want to expand it to be able to work when server side rendering, since it heavily relys on window location pathname. So I am looking for critic on my typings, my hook usage, how to prepare for server side rendering. Also just looking for any feedback if this is a good way to do a router :)

Below I have linked to a repo where I use this code, and a gist with a usage.tsx file to see how I am using it.

import React, { createContext, useEffect, useMemo, useState } from 'react'
import UrlPattern from 'url-pattern'
import { IRoute, IRouterContext, IRoutes, IState } from './types'

const getRoute = (routeName: string) => (i: { name: string }) =>
    i.name === routeName

const RouterContext = createContext<IRouterContext>(null!)

const RouterProvider = (props: {
    children: JSX.Element[] | JSX.Element
    routes: IRoutes
    initialRoute?: string
}) => {
    if (props.routes.length === 0) {
        throw new Error('You must provide routes')
    }

    const [currentRoute, setCurrentRoute] = useState<IRoute>(() => {
        const initialRoute = props.initialRoute
            ? props.routes.find(getRoute(props.initialRoute))
            : props.routes.find(({ path }) =>  // eslint-disable-line
                new UrlPattern(path).match(window.location.pathname), // eslint-disable-line
            ) // eslint-disable-line

        return initialRoute || props.routes[0]
    })

    const [currentState, setCurrentState] = useState<IState>(() =>
        new UrlPattern(currentRoute.path).match(window.location.pathname),
    )

    const goTo = useMemo(
        () => (toRouteName: string, toState: IState = {}) => {
            const toRoute: IRoute | undefined = props.routes.find(
                getRoute(toRouteName),
            )

            if (!toRoute) {
                throw new Error(`Route ${toRouteName} does not exist`)
            }

            setCurrentRoute(toRoute)
            setCurrentState(toState)
        },
        [currentRoute.name],
    )

    useEffect(() => {
        const pattern = new UrlPattern(currentRoute.path)
        const path = pattern.stringify(currentState)

        if (path !== window.location.pathname) {
            window.history.pushState(null, '', path)
        }
    }, [currentRoute.path, currentState])

    return (
        <RouterContext.Provider
            value={{ goTo, state: currentState, currentRoute }}
        >
            {props.children}
        </RouterContext.Provider>
    )
}

export { RouterContext, RouterProvider }

Links:

gist

github repo


texts:
I have an Oracle 18c table that has an SDO_GEOEMTRY column.
create table a_test_sdo_geom (id number, shape mdsys.sdo_geometry);

insert into a_test_sdo_geom (id, shape)
    values(1, sdo_util.from_wktgeometry (
               'MULTILINESTRING ((671834.096 4861699.7127, 671836.5099 4861701.9158), (671838.2206 4861700.7607, 671842.2311 4861703.3157))'));
insert into a_test_sdo_geom (id, shape)
    values(2, sdo_util.from_wktgeometry (
               'MULTILINESTRING ((671800.123 4861600.1234, 671800.1234 4861700.1234)))'));
commit;

And I have a sister table that stores the vertices of from that table as rows:
create table a_test_vertices (id number, vertex_num number, x number, y number);

insert into a_test_vertices (
select
    a.id,
    v.id as vertex_num,
    v.x,
    v.y
from
    a_test_sdo_geom a
    ,table(sdo_util.getvertices(a.shape)) v
);
commit;

        ID VERTEX_NUM          X          Y
---------- ---------- ---------- ----------
         1          1 671834.096 4861699.71
         1          2 671836.510 4861701.92
         1          3 671838.221 4861700.76
         1          4 671842.231 4861703.32
         2          1 671800.123 4861600.12
         2          2 671800.123 4861700.12

I have a trigger that will automatically update the vertices table whenever the source table's SHAPE gets updated:

When a source row is created
When a source row is deleted
When the source SHAPE column is updated (but not when any of the other columns get updated)

create or replace trigger a_test_sdo_geom_trig
   before insert or update of shape or delete
   on a_test_sdo_geom
   for each row
begin
   case
      when inserting then
         insert into a_test_vertices (id, vertex_num, x, y)
         select :new.id, id, x, y
           from table(sdo_util.getvertices(:new.shape));
      when deleting then
         delete a_test_vertices
         where id = :old.id;
      when updating('shape') then
         merge into a_test_vertices a
            using (select id, x, y
                     from table(sdo_util.getvertices(:new.shape))) b
               on (a.vertex_num = b.id and a.id = :old.id)
            when matched then
               update
                  set x = b.x
                     ,y = b.y
            when not matched then
               insert(id, vertex_num, x, y)
               values(:old.id, b.id, b.x, b.y);
   end case;
end a_test_sdo_geom_trig;

Question:
Can the trigger be improved?


texts: Passing JSON object through loop to be used in jQuery Dialog

texts:
I'm wondering if there is a better (cleaner?) method than my current implementation. I'm currently encoding a PHP SimpleXMLObject (USPS Tracking API) to JSON and looping through said JSON object via JavaScript to operate the front-end.

Examples from my current implementation below:

Function to display dialog implemented anonymously outside of .ready():

var moreInfo_popup = function(i) {
$('#moreinfo'+i).dialog({
        modal:false,
        autoOpen:false,
        height:555,
        title: 'Detailed View',
        width:500,
        draggable:false,
        buttons: {
            Ok: function(){
                $(this).dialog("close");
        }
    }
    });

        $('#moreinfo'+i).dialog('open');

        }

Main loop for displaying Tracking ID, Most Recent Event, and Mail Class for each API response- I'm currently generating a content div appended to #modal_container, then calling moreInfo_popup() inline via <input onClick="">:

for(var key in obj) {
                    if(obj.hasOwnProperty(key)) {
                    if(key % 2 === 0) {
                    $('#page-nav').append("

"+obj[key].TrackInfo.Attributes.ID+"	"+obj[key].TrackInfo.StatusSummary+"	"+obj[key].TrackInfo.Class+"	<input type=\"button\"class=\"moreInfo\"value=\"Detail\"id=\"_buttonMoreInfo\"onClick=\"moreInfo_popup("+key+")\">

");

                    $('#modal_container').append("

" + obj[key].TrackInfo.Attributes.ID +"

").hide();
                  }
                else {
                  $('#page-nav').append("

"
                                      + obj[key].TrackInfo.Attributes.ID + "	" + obj[key].TrackInfo.StatusSummary + "	"
                                      + obj[key].TrackInfo.Class + "	<input type=\"button\" value=\"Detail\" class=\"moreInfo\" id=\"_buttonMoreInfo\"onClick=\"moreInfo_popup("+key+")\">

");

                  $('#modal_container').append("

" + obj[key].TrackInfo.Attributes.ID +"

 <button>OK</button>

");

                }

            }

      $("#page-nav td:contains('undefined')").html("Invalid");
  }

As I'm sure you can see, this feels like an incredibly tedious way of accomplishing the desired outcome, to which there is surely a better alternative. As a newcomer to JavaScript/jQuery, I've done plenty of searching on this subject, but haven't really understood much of what I found, if indeed I was asking the right questions in the first place.


texts: How can I optimize my code that uses nested for loops?

texts:
I am working to solve a problem where I need to determine if a Point lies on a line connecting two other Points.  For example, if I have Point a, b, c, I want to determine if c is on the line segment connecting a and b.  In my code, I have a point, me (a in the example) and two lists of points, hits (b in the example) and reachable (c in the example).  For each point in hits, I want to determine if there is any point in reachable that is on the line segment that connects me and the point in hits. If there is a point on that line segment, then numHits needs to be decremented. Here is my code:

Point me; //Point a from the example above
ArrayList<Point> hits = new ArrayList<>();  //a list of Point b's from the example above
ArrayList<Point> reachable = new ArrayList<>();  //a list of point c's from the example above

for(Point hit : hits) {
    for(Point p : reachable) {
        if(!hit.equals(p) && !me.equals(p)) {
            //find the equation of a line from me to hit
            if(hit.x - me.x == 0) { //if the line has an undefined slope... if the line is vertical
                if( (((p.y <= hit.y) && (p.y >= me.y)) || ((p.y >= hit.y) && (p.y <= me.y))) && p.x - me.x == 0) {  //if there is any occupied point on that line in between me and the hit, that point blocks the hit
                    numHits--;
                    break;
                }
            } else {
                //create a line from me to the hit... if there is any occupied point on that line in between me and the hit, that point blocks the hit
                double deltaY = hit.y - me.y;
                double deltaX = hit.x - me.x;

                double m = deltaY / deltaX; //slope
                double b = me.y - (double)(m*me.x);  //y intercept

                if((double) p.y == ((double)(m * p.x) + b)) {  //if this point is on the same line
                    if( ((p.x <= hit.x && p.x >= me.x) && (p.y <= hit.y && p.y >= me.y)) ||
                                ((p.x <= hit.x && p.x >= me.x) && (p.y >= hit.y && p.y <= me.y)) ||
                                ((p.x >= hit.x && p.x <= me.x) && (p.y >= hit.y && p.y <= me.y)) ||
                                ((p.x >= hit.x && p.x <= me.x) && (p.y <= hit.y && p.y >= me.y))) {  //if the point is in between me and the hit
                        numHits--;
                        break;
                    }
                }
            }
        }
    }
}

My code works to determine if there is any point in reachable between me and each point in hits, it just gets incredibly slow the larger hits and reachable get.  For example, if hits has a size of 780,000 and reachable has a size of 1,500,000 the code takes a very long time to run.  I was wondering how I may be able to optimize this to run more quickly.  I'm not sure if the bottleneck issue lies in the loops themselves or in the code within the loops.  Any help or optimization ideas are greatly appreciated.  Thank you!


texts:
This function generates a unique id for my files, which will be stored in the database to reference them. It returns the id if unique, if not, it generates a new one. My separate file server can then use these ids to locate and retrieve a file.

I'm planning on storing thousands upon maybe millions of files uploaded by users in the future, so this needs to be robust and futureproof.

from django.utils.crypto import get_random_string
from .models import Media

def generateUID():
    uid = get_random_string(length=16, allowed_chars=u'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789')
    date = datetime.datetime.now()

    result = '%s-%s-%s_%s' % (date.year, date.month, date.day, uid)
    print(result)

    try:
        obj = Media.objects.get(uid=result)
    except Media.DoesNotExist:
        return uid
    else:
        return generateUID()

The Media model is a parent which stores the uid. There is an image model that Media can relate to.

For example:

Media uid = 'test':

Image name = 't200x200'
Image name = 'original'

When the files are created, they are stored like this:

Let's say the ID is, for example:

2016-9-14_cKYT96osstPB8z2F

and the filename for the file that we want to get is:

avatars_2016-9-14_cKYT96osstPB8z2F_t200x200.png

Then the file would be saved like this in my file server:

media/avatars/2016/9/14/c/K/Y/cKYT96osstPB8z2F/t200x200.png

This ensures that there will be no collisions, and the file system is split and doesn't have thousand of files in one folder, which will damage performance.

Is there any way I can make this perform better or be more reliable? Avoiding collisions and performance issues is a must.


texts:
This is how I am deleting a node from a singly linked list. Would this be the most correct way?

void Remove(Node** head, int value)
{
    Node** ptr = head;

    while (*ptr && (*ptr)->data != value)
        ptr = &(*ptr)->next;

    if (*ptr)
    {
        Node* next = (*ptr)->next;
        delete *ptr;
        *ptr = next;
    }
}


texts: Organization of work with MongoDB in Flask

texts:
I`m trying to make an API for Flask together with MongoDB, before that I used the SQL DB using SQLAlchemy and there I used models for organizing the database.
Now I'm a bit confused how to organize code for working with DB. Since the standard MongoDB client does not provide an opportunity to create models, and I did not like Mongoengine, I decided to move any database methods into a separate class:
import uuid
from datetime import datetime

from flask import request
from werkzeug.security import generate_password_hash

from app import mongo

class User:

    db = mongo.db.users

    def new_user(self):
        '''New user Registration.

        Request body (JSON):
            email (str)
            username (str)
            password (str)
        Returns:
            status, result (tuple):
                100, user (dict) - in case of successful registration
                102, None - one of the parameters is missing
                201, None - such user already exists
        '''

        try:
            data = {
                '_id': uuid.uuid4().hex,
                'email': request.json['email'],
                'username': request.json['username'],
                'password': generate_password_hash(
                    request.json['password']),
                'createdAt': datetime.utcnow()
            }
        except KeyError:
            return 102, None

        user = self.db.find_one({
            '$or': [
                {'email': data['email']},
                {'username': data['username']}
            ]
        })

        if not user:
            self.db.insert_one(data)
            return 100, data
        else:
            return 201, None

    def login(self):
        pass

    def get_data(self):
        pass

from flask import Blueprint, jsonify, request

from app.models import User

users = Blueprint('users', __name__)

@users.route('/users/new_user', methods=['POST'])
def new_user():
    '''Adding a new user to the database.
    '''

    status, user = User().new_user()

    if status == 100:
        return jsonify({'status': True, 'code': 100, 'result': user})
    elif status == 102:
        return jsonify({
            'status': False, 'code': 102,
            'result': 'missing one of parameters'})
    elif status == 201:
        return jsonify({
            'status': False, 'code': 201, 'result': 'user already exists'})

But it looks very strange to me, if there are many keys in the document and I need to somehow handle them in the route, it will be very unintuitive.
Now I am thinking of making a model by analogy with models from SQLAlchemy, so that class variables represent keys in documents, as well as simple methods for queries in the database. But it can also cause a lot of confusion. I just want to try to avoid code duplication as well as variability for reuse.
I will accept any advice or hints as to how it should be "right". Unfortunately I have not found a project structure using MongoDB.


texts: Disposing the Context in the Repository pattern

texts:
I have a question about the Repository pattern:

public abstract class RepositoryBase<T> : IDisposable, IRepository<T> where T : class, IEntity
    {
        /// <summary>
        /// For iterations using LINQ extension methods on the IQueryable and IEnumerable interfaces
        /// it is required that the context which was used to make the query was not disposed before the iteration
        /// otherwise it will throw an exception
        /// </summary>
        private Context _context;

        protected Context Context
        {
            get { return _context ?? (_context = new Context()); }
        }

        public virtual void AddOrUpdate(T entity)
        {
            var dbSet = Context.Set<T>();

            if (dbSet.Contains(entity))
                entity.ChangeDateTime = DateTime.Now;
            else
                entity.AddeDateTime = DateTime.Now;

            Context.Set<T>().AddOrUpdate(entity);
            Context.SaveChanges();
        }

        public virtual void Delete(T entity)
        {
            Context.Set<T>().Remove(entity);
            Context.SaveChanges();
        }

        public void Drop()
        {
            var dbSet = Context.Set<T>();

            foreach (var entity in dbSet)
                dbSet.Remove(entity);

            Context.SaveChanges();
        }

        public virtual IQueryable<T> Find(Expression<Func<T, bool>> predicate)
        {
            return Context.Set<T>().Where(predicate);
        }

        public IEnumerable<T> GetAll()
        {
            return Context.Set<T>();
        }

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

Why I am not embracing each method implementation with a using and disposing the Context as soon as the query is done?

Some of my methods, as Find and GetAll return collections. I would want to be able to iterate through them using LINQ, only this is not possible if the Context is disposed, as it would be in the original Repository model.

Is this the best approach to go around this issue?


texts:
I'm trying to implement a bunch of sorting algorithms in JavaScript, and I can't figure out why my shell sort is so slow. It's 6x slower than my merge sort, and only slightly faster than my insertion sort. I've seen another implementation online, but I'm more focused on making it clear and readable (as I have a blog for noobs) and the faster implementation is too concise for my purposes. Any thoughts on how I can keep the general plan but get it moving faster? I tried using Marcin Ciura's gap sequence [701, 301, 132, 57, 23, 10, 4, 1], but it was slightly slower. I'm not sure what's the biggest factor slowing down my sort.

  var shellSort = function( list ) {
    var gapSize = Math.floor( list.length / 2 );

    while( gapSize > 0 ) {
      _shellInsertionSort( list, gapSize );
      gapSize = Math.floor( gapSize / 2 );
    }

    return list;
  };

  function _shellInsertionSort( list, gapSize ) {
    var temp, i, j;

    for( i = gapSize; i < list.length; i += gapSize ) {
      j = i;
      while( j > 0 && list[ j - gapSize ] > list[j] ) {
        temp = list[j];
        list[j] = list[ j - gapSize ];
        list[ j - gapSize ] = temp;
        j -= gapSize;
      }
    }
  };

My tests:

  var testSpeed = function( testSize, rounds ) {
    var testArrays = [],
        algorithms = Array.prototype.slice.call( arguments, 2 ),
        results = [],
        i, j;

    for( i = 0; i < rounds; i++ ) {
      testArrays[i] = [];
      for( j = 0; j < testSize; j++ ) {
        testArrays[i].push( Math.ceil( Math.random() * testSize ));
      }
    }

    for( i = 0; i < algorithms.length; i++ ) {
      for( j = 0; j < rounds; j++ ) {
        if( !results[i] ) {
          results[i] = [];
        }
        results[i].push( testAlgorithm( algorithms[i], testArrays[j] ));
      }
    }

    return results;
  };

  var testAlgorithm = function( algorithm, set ) {
    var clone = set.slice(),
        start = new Date().getTime(),
        end;

    algorithm( clone );

    end = new Date().getTime();

    return end - start;
  };


texts:
I call this animateElements function as part of an animation loop (inspired via Dave Gamache). Everything works as expected, but I would love to try and improve/optimize if possible.

var animation, translate, translateY, translateX, scale, rotate, opacity, display;
    animateElements = function() {
        //var animation, translateY, translateX, scale, rotate, opacity, display;

        //do{ //No performance improvement in chrome with neg-loop + ...havent tested others

        //var i = keyframesConverted[currentKeyframe].animations.length;
        //while(i--) {

        for (var i = 0; i < keyframesConverted[currentKeyframe].animations.length; i++) {
            animation = keyframesConverted[currentKeyframe].animations[i];

            //NOT MUCH IN IT: this "if" vs ternary, but fps was better on ternary.

            display = (typeof animation['display'] === 'undefined') ? null : animation['display'][1] || null;

            if (display !== 'none') {
                translateY = (typeof animation['translateY'] === 'undefined') ? 0 : calcPropValue(animation, 'translateY', 2);
                translateX = (typeof animation['translateX'] === 'undefined') ? 0 : calcPropValue(animation, 'translateX', 2);
                scale = (typeof animation['scale'] === 'undefined') ? "" : " scale(" + calcPropValue(animation, 'scale', 2) + ")";
                rotate = (typeof animation['rotate'] === 'undefined') ? "" : " rotateX(" + calcPropValue(animation, 'rotate', 1) + "deg)";
                opacity = (typeof animation['opacity'] === 'undefined') ? 1 : calcPropValue(animation, 'opacity', 2);

                translate = 'translate3d(' + translateX + 'px, ' + translateY + 'px, 0.01px)';

                $(animation.selector).css({
                    'transform': translate + scale + rotate,
                    'opacity': opacity,
                    'display': display //= (opacity < 0) ? 'none' : display//Todo: Potential for performance Improvement but would require major recode?
                });
            } else {
                $(animation.selector).css({ 'display': 'none' });
            }
        }//while(i--)
    }

    calcPropValue = function (animation, property, deciPlaces) {
        var value = animation[property];
        return (tweenEase(relativeScrollTop, value[0], (value[1] - value[0]), keyframesConverted[currentKeyframe].duration, (typeof animation['tween'] === 'undefined') ? null : animation['tween'][1] || null)).toFixed(deciPlaces);
    }

Concerns:

The use of typeof animation[...] as most likely the ternary will reference it twice a loop, for each animation property; hence, should I place it in a var?
When calling calcPropValue(), would there be a performance gain by just passing animation['...type'] in one go, rather than the 'animation' and then its 'type'?
As this function has no further use - except from where it is called - would it be an improvement just to move this function block into that animation loop directly, as I assume 'fewer calls to functions, the better'?


texts:
I am making a video editor with tkinter, and seriously need to clean it up and make it nicer to read / more efficient. Can anybody help me clean up my code (I was sent here from stackoverflow)
Here it is: https://github.com/MiniMinnoww/moviepy-video-editor
The parts I kinda need to figure out are:

Buttons and popup windows. I need 2 functions to run 1 video editor function. For example, if I want to add text, I have to call a function to make a popup window for the details of the text, then call another function when the button is pressed to actually edit the video clip.

Here is what I tried to do (in simple terms):
def addText(self, x=0):
    if x == 0:
        button = Button(root, command=functools.partial(self.addText, 1))
    else:
        # run other stuff for function

Here you can see I am re-executing the function using an argument. Although this is effective, it is messy and I was wondering whether there's a better way to do this?


texts:
Does this part look clean enough? Any suggestions on how to make it cleaner?

if (isCheck)
{
    if (isStuck)
    {
        return GameState.Mate;
    }
    else
    {
        return GameState.Check;
    }
}
else
{
    if (isStuck)
    {
        return GameState.Stalemate;
    }
    else
    {
        return GameState.Ok;
    }
}


texts:
I'm working on a web application that I inherited from a colleague long gone. To connect to the MySQL database I use the following classes:

statement.php

<?php
//class sql
//{
    class Statement
    {
        private $m_connection;

        function __construct($connection)
        {
            $this->m_connection = $connection;
        }

        function query($query)
        {
            $connection = $this->m_connection;
            $handle = $connection->getHandle();

            $result = mysql_query($query,$handle);

            if ($result === FALSE)
                throw new Exception(mysql_error());

            $instance = new Result($this);
            $instance->setHandle($result);

            return $instance;
        }
    }
//}
?>

result.php

<?php
//class sql
//{
    class Result
    {
        private $m_handle;
        private $m_statement;

        function __construct($statement)
        {
            $this->m_statement = $statement;
        }

        function setHandle($handle)
        {
            $this->m_handle = $handle;
        }

        function fetch()
        {
            $handle = $this->m_handle;
            $row = mysql_fetch_array($handle);

            return $row;
        }
    }
//}
?>

connection.php

<?php
include_once("statement.php");
include_once("result.php");

//class sql
//{
    class Connection
    {
        private $m_handle;

        function __construct($server,$username,$password)
        {
            $handle = mysql_connect($server,$username,$password);
            $this->m_handle = $handle;
        }

        function __destruct()
        {
            $handle = $this->m_handle;
            @mysql_close($handle);
        }

        function createStatement()
        {
            return new Statement($this);
        }

        function getHandle()
        {
            return $this->m_handle;
        }
    }
//}
?>

named.php

<?php
include_once("connection.php");

function createNamedConnection($name)
{
    if ($name == "dbalias1")
    {
        $connection = new Connection("first.host.com","user","uspw");

        $statement = $connection->createStatement();
        $statement->query("USE db1");

        return $connection;
    }
    if ($name == "dbalias2")
    {
        $connection = new Connection("second.host.com","user2","nouse");

        $statement = $connection->createStatement();
        $statement->query("USE db2");

        return $connection;
    }

    return null;
}
?>

To have a connection I can use the following script:

$connection = createNamedConnection("dbalias1");
$statement = $connection->createStatement();
$query = "SELECT   *
          FROM     tContent c
          WHERE    c.cID > 100";
$result = $statement->query($query);
while(($row = $result->fetch()) !== FALSE){
    //do something
}

The problem is that those classes caused me a lot of trouble, and I'm sure there is work to be done on them. I don't know where to begin to make those classes more secure and easy to use.


texts: iOS tableView with two special rows of headers

texts:
Using swift for iOS, here is my cellforRow method

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    switch indexPath.section {
    case 0: // Cover Image
        guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifierCover) as? AddBlogCoverTableViewCell else { return UITableViewCell() }
        cell.layer.backgroundColor = UIColor.clear.cgColor
        cell.selectionStyle = .none
        cell.indexPath = indexPath
        cell.delegate = self
        cell.titleTextField.delegate = self
        cell.coverImageView.image = coverImage
        cell.titleTextField.placeholder = "Title"
        cell.titleTextField?.text = articleName ?? ""
        cell.setBorder(of: 0.7, ofColor: UIColor.lightGray.cgColor)

        return cell

    case 1: // rest story
        guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) as? AddBlogTableViewCell else { return UITableViewCell() }
        cell.layer.backgroundColor = UIColor.clear.cgColor
        cell.selectionStyle = .none
        cell.indexPath = indexPath
        cell.delegate = self
        cell.captionTextView.delegate = self
        cell.captionTextView.tag = indexPath.row
        cell.tag = indexPath.section
        cell.media = cards?[indexPath.row].media
        cell.captionTextView.text = cards?[indexPath.row].caption ?? ""
        showLocationSuggestions(at: indexPath, in: cell)
        cell.poi = cards?[indexPath.row].poi
        return cell
    default:
        return UITableViewCell()
    }
    return UITableViewCell()
}

How should I avoid repeating the code that I have to provide to the cell in all cases of switch?


texts: Renaming numbered files for proper sorting

texts:
I have designed a tool that generates some HTML files and a CSS file in a directory, which then feed into a tool called Jutoh that uses these to make eBooks.

However, my output files are of the form 1.htm, 2.htm and so on. Jutoh ranks 10.htm to preceed 2.htm and therefore, I wrote a method to convert 1.htm into 0001.htm. I would like to know your opinion on it and learn where there might be scope for speedup and other improvements.

var inputDir = _cssFile.Directory.FullName + "\\Output\\";
var outputDir = _cssFile.Directory.FullName + "\\Output";
if (!Directory.Exists(outputDir))
    Directory.CreateDirectory(outputDir);
DirectoryInfo di = new DirectoryInfo(inputDir);
foreach (FileInfo fi in di.GetFiles("*.htm"))
{
    string n = fi.Name.Replace(fi.Extension, ""); //remove extension
    int k = Int32.Parse(n); //Convert string to int
    string t = k.ToString("D4"); //convert it into 4 digit
    t = t + fi.Extension; // add extension

    string trgtfile = Path.Combine(fi.DirectoryName, t);
    File.Move(fi.FullName, trgtfile);
}


texts:
Finally happy to see that now we can have iterators and generators. I also need to try to have private properties too so that we have well encapsulated data structures and I see that there are Proxies and Symbols which could help me do that.

Utils:

export const isDefAndNotNull = object =>
  object !== undefined && object !== null;

export const isIterable = object =>
  isDefAndNotNull(object) && typeof object[Symbol.iterator] === 'function';

Code:

import {isDefAndNotNull, isIterable} from "./Utils";

function *reverseArrayGenerator(arr) {
  let i = arr.length;
  while(--i >= 0) {
    yield arr[i];
  }
}

const data = Symbol("data");

export default class {
  constructor(iterable) {
    this[data] = [];
    if (isIterable(iterable)) {
      for (let item of iterable) {
        this.push(item);
      }
    }
  }

  peek() {
    return this[data].slice(-1)[0];
  }

  push(item) {
    this[data].push(item);
  }

  pop() {
    return this[data].pop();
  }

  isEmpty() {
    return this[data].length === 0;
  }

  size() {
    return this[data].length;
  }

  toString() {
    let res = [];
    for (let item of this) {
      res.push(item);
    }
    return JSON.stringify(res.join(' '));
  }

  [Symbol.iterator]() {
    return reverseArrayGenerator(this[data]);
  }
}

Test:

import {strictEqual as equal} from "assert";
import Stack from "../src/Stack";

suite("Stack", () => {
  test("without iterator", () => {
    const s = new Stack();
    s.push(1);
    equal(s.size(), 1);
    equal(s.pop(), 1);
    equal(s.size(), 0);
  });

  test("with iterator", () => {
    let s = new Stack([1, 2, 3]);
    equal(s.size(), 3);
    s = new Stack('hello');
    equal(s.size(), 5);
    s = new Stack([{name: 'Foo'}, {name: 'Bar'}]);
    equal(s.size(), 2);
  });

  test("peek", () => {
    let s = new Stack([1, 2, 3]);
    equal(s.peek(), 3);
    s.pop();
    equal(s.peek(), 2);
  });

  test("iterator", () => {
    const s = new Stack([1, 2, 3]);
    let i = 3;
    for(let item of s) {
      equal(item, i);
      i--;
    }
  });
});

Reference: http://algs4.cs.princeton.edu/13stacks/Stack.java.html


texts: A scalable way to remove duplicates from Arrays without extensions in Swift 4

texts:
This method is an attempt at removing duplicates from arrays without the use of extensions.
func arrayWithDuplicatesRemoved<T: Equatable>(from array: [T]) -> [T] {
    var results = [T]()
    return array.compactMap { (element) -> T? in
        if results.contains(element) {
            return nil
        } else {
            results.append(element)
            return element
        }
    }
}

let dirty = ["apple", "kiwi", "grapefruit", "kiwi", "kiwi", "strawberry", "watermelon", "apple", "banana"]
let clean = arrayWithDuplicatesRemoved(from: dirty)
print(clean) // ["apple", "kiwi", "grapes", "strawberry", "watermelon", "banana"]


texts: Distinct unordered pairs of an array which satisfy a condition

texts:
I came across the below problem in a coding challenge:
Let's define 2 functions, \$F(i)\$ and \$Val(i,j)\$, for an array \$A\$ of size \$N\$ as follows:

$$
\begin{align}
F(i) =& \sum_{j=i+1}^{N} Val(i,j) \\
\\
Val(i, j) =& \begin{cases}
               1,\qquad & \textrm{if } A[i] < A[j] \\
               0,\qquad & \textrm{otherwise}
             \end{cases}
\end{align}
$$
I need to find the number of distinct unordered pairs of elements (a,b) in array \$A\$, such that \$F(a)+F(b) \ge K\$.

Here is my solution:

#include<iostream>
#include<cassert>
#define max 1000000000

int main()
{
    unsigned int N, K;
    std::cin >> N;
    assert((1 <= N) && (N <= 1000000));
    std::cin >> K;
    assert((0 <= K) && (K <= max));
    unsigned int a[N], F[N];
    for(unsigned int i = 0; i < N; i++)
    {
        std::cin >> a[i];
        assert((1 <= a[i]) && (a[i] <= max));
    }
    int sum = 0, val = 0;
    for(unsigned int i = 0; i < N; i++)
    {
        for(unsigned int j = i+1; j < N; j++)
        {
            if(a[i] < a[j])
            val = 1;
            else
            val = 0;

            sum = sum + val;
        }
        F[i] = sum;
        sum = 0;
    }
    int count = 0;
    for(unsigned int i = 0; i < N; i++)
    {
        for(unsigned int j = i+1; j < N; j++)
        {
            if(F[i] + F[j] >= K)
            count++;
        }
    }
    std::cout << count << std::endl;
}

While this works, I would want to know if there is a way to write optimized code which works fast even for larger inputs.


texts:
I currently have this code to read lines from a file

def getLinesFromFile(filename):
    content = []

    # with open(filename, "r+") as file:
    #   for line in file:
    #       line = line.rstrip()
    #       if line:
    #           content.append(line)

    file = None
    try:
        file = open(filename, "r+")
        for line in file:
            line = line.rstrip()
            if line:
                content.append(line)
    except IOError:
        print "[ERR] File does not exist"
    finally:
        if file:
            file.close()

    return content

Please take note of the commented out code using with. I really wanted to use with but I can't find any good resource on how to catch exceptions with with. So I did it using try except.

Question: Is there no better way to do this? Or any comments?

P.S. I come from a Java background and this is my first time writing in Python so I am more inclined to try-except as of the moment.


texts:
I have the code below which is working as expected. It is doing a form validation with Vue.js and Vee-Validate. It is checking that at least one checkbox is checked.

I only don't like that I have to manually call validate for oneChecked-Validator on form submission. With-out the call it's not validating on submit.

It would be great if someone could review my code and give me an advice to the following points:

How can I configure Vee Validator so that it evaluates the oneChecked validator with the call of this.$validator.validateAll();?
Is it possible to pass the this.options array into validate method of oneChecked validator? (Would be more re-usable. I've tried passing as array with JSON.stringify but couldn't get it to work.)

If there is more to improve please let me know. I'm using Vee-Validate for the first time.

You can also find the same code at jsfiddle.

const Checkboxes = {
  template: '#checkboxTmpl',
  data() {
    return {
      text: '',
      options: [{
        id: 0,
        checked: false
      }, {
        id: 1,
        checked: false
      }, {
        id: 2,
        checked: false
      }]
    };
  },
  created() {
    this.$validator.extend('oneChecked', {
      getMessage: field => 'At least one ' + field + ' needs to be checked.',
      validate: (value, [testProp]) => {
        const options = this.options;
        // console.log('questions', value, testProp, options.some((option) => option[testProp]));
        return value || options.some((option) => option[testProp]);
      }
    });
  },
  methods: {
    validateBeforeSubmit(e) {
      this.$validator.validateAll(); // why is oneChecked not validated here? --> manually trigger validate below
      this.options.forEach((option) => {
        this.$validator.validate('check0', option.checked, ['checked'])
      });

      console.log('validator', this.errors);
      if (!this.errors.any()) {
        alert('succesfully submitted!');
      }
    }
  }
};

Vue.use(VeeValidate);

const app = new Vue({
  el: '#app',
  render: (h) => h(Checkboxes)
})


texts:
I have implemented selection sort in java using arraylist. This selection sort is only for integers . Please have a look and give feedback. can we improve it ?

package selectionSort;

import java.util.ArrayList;
import java.util.Scanner;

public class SelectionSort {
private ArrayList<Integer> num_sort=new ArrayList<>();

public SelectionSort(ArrayList<Integer> userlist) {
    this.num_sort=userlist;
    sort_select();

}

public void sort_select() {
    //outer for loop to pick one element at a time
    //e.g if list is 20,12,3,4,5,6,98----this loop will first pick 20
    for(int i=0;i<this.num_sort.size();i++) {
        //assign that element as minimum
        //in our e.g 20 will be assigned min in first iteration
        int min=this.num_sort.get(i);
        int min_index=i;
        //go over the rest of the list and compare minimum by rest of list. if number smaller than min is found, then it is assigned as new min
        //so go over list starting from 12 and comparing 20 with each of them and finding the new min, in this case it will be  3
        for(int j=i+1;j<this.num_sort.size();j++) {
            if(this.num_sort.get(j)<min) {
                min=this.num_sort.get(j);
                min_index=j;

            }
        }
        if(i!=min_index) {
           exchange(i,min_index);
        }
    }
    System.out.println("Sorted entered are : ");
    for(int x:this.num_sort) {
        System.out.print(x+" ");
    }
}

// exchange the element at ith position with min
public void exchange(int current_elem,int new_min) {
    int temp=this.num_sort.get(current_elem);
    this.num_sort.set(current_elem, this.num_sort.get(new_min));
    this.num_sort.set(new_min, temp);

}

public static void main(String[] args) {
    // TODO Auto-generated method stub
    System.out.println("Enter how many numbers you want to sort");

    Scanner in=new Scanner(System.in);
    int num_count=in.nextInt();
    System.out.println("Enter the numbers you want to sort");
    ArrayList<Integer> userlist=new ArrayList<>();

    for(int i=0;i<num_count;i++) {
        userlist.add(in.nextInt());
    }

    SelectionSort s=new SelectionSort(userlist);

}

}


texts: Fizzbuzz questions - job interview rejected

texts:
I have done some programming tasks as a part of my candidacy for a web development apprenticeship. Unfortunately, my application was rejected as the hiring manager "didn't like my codes." I called up their office but no one was able to provide sufficient feedback for me.
If any of you could tell me what I could have misunderstood or what I could have done correctly, I pretty much appreciate it.
The Tasks I worked with
Write a program that shows the numbers from 1 to a specified limit (e.g. 100).
The numbers should be translated as follows: 1. For multiples of 3 return "Fizz" 2. For multiples of 5 return "Buzz" 3. For multiples of 3 and 5 return "FizzBuzz" 4. If none of the other rules apply, return the number itself
Unit tests are optional, but would be a plus.
My Solution
public class FizzBuzz {

    //a class *variable*, not a class
    private static int counter;

    //checking if a multiple of 3
    private static boolean isFizz(int i) {
        return i % 3 == 0; //no need for if
    }

    //checking if a multiple of 5
    private static boolean isBuzz(int i) {
        return i % 5 == 0; //no need for if
    }

    public static void main(String[] args) {
        for (int i = 1; i <= 100; i++) {
            System.out.println(i);
            if (i % 5 == 0 && i % 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);
            }
        }
    }

    @Test public void testFizzBuzz(){
        assertEquals("fizz", fizzBuzz(i == 3));
        assertEquals("buzz", fizzBuzz(i == 5));
        assertEquals("fizzbuzz", fizzBuzz(i == 15));
        assertEquals("2", fizzBuzz(i == 2));
    }

}


texts: Generate regular expression based on inputted number

texts:
This is my first PHP script (although I like to think I'm a good general coder).

The script accepts a number from the user, uses it to generate a regular expression, and then returns all dictionary words that match that expression.

It's currently live here, and I'd appreciate any comments on style, security, best practices, and even efficiency. Please ignore the Html for now - it's got a WordPress template to be inserted into later on.

<title>Major Analysis Number Encoder</title>

Tool for finding keywords for major analysis

    This tool uses the numbering system shown by Derren Brown in the
    excellent book
    Trick
        of the mind. For a (much better) tool that uses the older
    numbering system see
    http://www.rememberg.com/

    <form action="majorEncoder.php" method="post">
        Number to encode (at least three digits
            please): <input type="text" id="targetNumber"
            name="targetNumber" />
 <input type="submit"
            value="Generate results" name="submit" />
    </form>
<?php
if ($_POST != null) {

    $target = $_POST ['targetNumber'];
    if (strlen ( $target ) >= 3) {
        $f = '[waeiouyc]?';
        $regex = '/^' . $f . $target;
        echo 'You entered the target' . $target . '

';
        $regex = str_replace ( '1', 'l' . $f, $regex );
        $regex = str_replace ( '2', 'n' . $f, $regex );
        $regex = str_replace ( '3', 'm' . $f, $regex );
        $regex = str_replace ( '4', 'r' . $f, $regex );
        $regex = str_replace ( '5', '[fv]' . $f, $regex );
        $regex = str_replace ( '6', '[bp]' . $f, $regex );
        $regex = str_replace ( '7', 't' . $f, $regex );
        $regex = str_replace ( '8', '[sc]h' . $f, $regex );
        $regex = str_replace ( '9', '[gd]' . $f, $regex );
        $regex = str_replace ( '0', '[sz]' . $f, $regex );
        $lines = file ( 'words.txt' );

        $fl_array = preg_grep ( $regex . '$/', $lines );
        if (sizeof ( $fl_array ) > 0) {
            echo 'Exact matches:
';
            foreach ( $fl_array as $element ) {
                echo $element . '
';
            }
            echo '
';
        }
        $fl_array = preg_grep ( $regex . '/', $lines );
        if (sizeof ( $fl_array ) > 0) {
            echo 'Matches that allow trailing characters:
';
            foreach ( $fl_array as $element ) {
                echo $element . '
';
            }
        } else {
            echo "No matches found for the input $target";
        }
    } else {
        echo 'Please enter at least three digits
';
    }
}
?>


texts:
I have a mathematical function as shown below

  $$ (h+1) * U(k,h) = \sum_{r=0}^k \sum_{s=0}^h (r + 1) * (k - r + 1) *
 U(r + 1, h - s) * U(k - r + 1, s)\ + \sum_{r=0}^k \sum_{s=0}^h (k - r
  + 1) * (k - r + 2) * U(r, h - s) * U(k - r + 2, s)\,. $$

Base condition for U(k,h) is

  $$ U(k,0) = (-1)^k/k! $$

I am using the following code to calculate the function

public double U(int k, int h)

        {
            h--;
            Int16 r, s;

            if (h == -1)
            {
                return (double)(Power(-1, k) / fact[k]);
            }

            else if (arr1[k, h] != 0 && arr2[k, h] != 0)
                return (double)((arr1[k, h] + arr2[k, h]) / (h + 1));

            else
            {
                for (r = 0; r <= k; r++)
                {
                    for (s = 0; s <= h; s++)
                    {
                        arr1[k,h] += (r + 1) * (k - r + 1) * U(r + 1, h - s) * U(k - r + 1, s);

                    }

                }
                for (r = 0; r <= k; r++)
                {
                    for (s = 0; s <= h; s++)
                    {
                        arr2[k,h] += (k - r + 1) * (k - r + 2) * U(r, h - s) * U(k - r + 2, s);
                    }
                }
                return (double)((arr1[k,h] + arr2[k,h]) / (h + 1));
            }
        }

The function works fine for values of k and h up to 40. After that it prints

  at ndp.functions.U(Int32 k, Int32 h)


texts: How to define UDP connection sessions more correctly?

texts:
Listening to messages from the udp socket, I would like to somehow determine where packets come from and scatter in sessions to get a more detailed report on the received data, I just did it forehead, looking for the current session and recording in its channel, I would like to know if more elegant methods? full code

    func serve(ctx context.Context, addr string, port int) <-chan Message {
type session struct {
    id           int
    conn         *net.UDPAddr
    len          int64
    countMessage int64
    expiration   int64
    buffer       chan []byte
    run          func(wg *sync.WaitGroup, in chan []byte, ip string)
}

var (
    out         = make(chan Message, 64)
    done        = make(chan error, 1)
    wg          sync.WaitGroup
    localAddres = &net.UDPAddr{IP: net.ParseIP(addr), Port: port}
    bufPool     = sync.Pool{New: func() interface{} { return make([]byte, bufferSize) }}
    sessions    []*session

    // TODO может будет не линейный поиск, пока посмотрим так
    getSession = func(addr *net.UDPAddr) (*session, bool) {
        for _, s := range sessions {
            if reflect.DeepEqual(s.conn, addr) {
                return s, true
            }
        }
        return nil, false
    }
    addSession = func(s *session) {
        fmt.Printf("Add new session %s:%d id: %d \n", s.conn.IP.String(), s.conn.Port, s.id)
        sessions = append(sessions, s)
    }
    removeSession = func(sess *session) {
        for i, s := range sessions {
            if s.id == sess.id {
                fmt.Printf("Remove session %s:%d id: %d \n", s.conn.IP.String(), s.conn.Port, s.id)
                sessions = sessions[:i+copy(sessions[i:], sessions[i+1:])]
            }
        }
    }
    gc = func() {
        for {
            <-time.After(time.Duration(3 * time.Second))
            for _, s := range sessions {
                if time.Now().UnixNano() > s.expiration && s.expiration > 0 {
                    removeSession(s)
                }
            }
        }
    }
)
go gc()
go func() {
    pc, err := net.ListenUDP("udp", localAddres)
    if err != nil {
        done <- err
    }
    defer pc.Close()
    go func() {
        for {
            buff := bufPool.Get().([]byte)
            size, addr, err := pc.ReadFromUDP(buff[0:])
            if err != nil {
                done <- err
                return
            }
            switch s, ok := getSession(addr); ok {
            case true:
                s.buffer <- buff[0:size]
                bufPool.Put(buff)
                s.expiration = time.Now().Add(time.Duration(time.Second * 10)).UnixNano()
                atomic.AddInt64(&s.countMessage, 1)
                atomic.AddInt64(&s.len, int64(size))
            case false:
                s := &session{
                    id:         rand.Int(),
                    conn:       addr,
                    expiration: time.Now().UnixNano(),
                    buffer:     make(chan []byte, 64),
                    run: func(wg *sync.WaitGroup, in chan []byte, ip string) {
                        for b := range in {
                            var m Message
                            err := json.Unmarshal(b, &m)
                            if err != nil {
                                log.Fatal(err)
                                continue
                            }
                            m.Device_ip = ip
                            out <- m
                        }
                    },
                }
                wg.Add(1)
                s.buffer <- buff[0:size]
                bufPool.Put(buff)
                atomic.AddInt64(&s.countMessage, 1)
                atomic.AddInt64(&s.len, int64(size))
                go s.run(&wg, s.buffer, s.conn.IP.String())
                addSession(s)
            }
        }
    }()
    select {
    case <-ctx.Done():
        wg.Wait()
        log.Println("cancelled")
        err = ctx.Err()
    case err = <-done:
        panic(err)
    }
}()

return out
}


texts:
Just finished an exercise in the Rust online book and I wanted to know if there is anything worth talking about in the code I wrote... if there's any mistake or optimization possible.
Convert strings to pig latin

The first consonant of each word is moved to the end of the word and
“ay” is added, so “first” becomes “irst-fay”.

Words that start with
a vowel have “hay” added to the end instead (“apple” becomes
“apple-hay”).

Keep in mind the details about UTF-8 encoding!

use std::io;
fn main() {
    let mut user_input = String::new();
    io::stdin()
        .read_line(&mut user_input)
        .expect("Failed to read line.");
    for word in user_input.split_whitespace() {
        match word.chars().nth(0).unwrap() {
            'a' | 'e' | 'i' | 'o' | 'u' | 'y' => print!("{} ", format!("{}-hay", word.trim())),
            _ => print!("{} ", format!("{}{}-ay", &word[word.chars().next().unwrap().len_utf8()..].trim(), word.chars().nth(0).unwrap())),
        };
    }
    println!();
}


texts: A crude clojure progress reporting function

texts:
The purpose of this function is to report processing progress to the terminal.  It loops through an array of maps that contain two properties: :sequence and :function.  Within each sequence-function-map, it will loop through the sequence, and run the function on each item in the sequence.

This is my first Clojure program that will be used in a production environment.  This particular function does the job, but I suspect that it's not very lispy.

(defn run-with-reporting [sequence-function-maps stop-time]
  (def beginning-time (java.util.Date.))
  (let [seq-counts (map #(count (:sequence %)) sequence-function-maps)]
    (def total-sequence-counts (reduce + seq-counts)))
  (println (str "total counts = " total-sequence-counts))
  (def prog-rpt-ref (ref {:todo total-sequence-counts, :done 0, :total-time-taken 0}))
  (doseq [sequence-function-map sequence-function-maps]
    (let [sequence (:sequence sequence-function-map),
          function (:function sequence-function-map)]
      (loop [loop-seq sequence]

        (if (and stop-time (clj-time/after? (clj-time/now) stop-time))
          (println "stopped at " (clj-time/now) ". Requested stop at " stop-time)
          (if loop-seq
            (do
              (def item (first loop-seq))
              (def start-time (java.util.Date.))
              (function item)
              (def end-time (java.util.Date.))
              (def time-delta (- (.getTime end-time) (.getTime start-time)))
              (let [derefd-rpt (deref prog-rpt-ref)]
                (dosync (alter prog-rpt-ref assoc
                               :done (inc (:done derefd-rpt)),
                               :total-time-taken (+ (:total-time-taken derefd-rpt) time-delta))))
              (let [derefd-rpt (deref prog-rpt-ref)]
                (let [average-time (/ (:total-time-taken derefd-rpt) (:done derefd-rpt))]
                  (println "Avg time / each = " (hrs-min-sec average-time)
                           ", Estimated total time left = "
                           (hrs-min-sec (* average-time (- (:todo derefd-rpt) (:done derefd-rpt)))))))
              (recur (next loop-seq))))))))
  (let [derefd-rpt (deref prog-rpt-ref)]
    (println "Total time taken = " (hrs-min-sec (- (.getTime (java.util.Date.)) (.getTime beginning-time))) ", Done = " (:done derefd-rpt) "/" (:todo derefd-rpt))))

Here's a testing function

(defn test-run-w-reporting [stop-clj-time]
  (def testing-func (fn [item] (. java.lang.Thread sleep (rand 1000))))
  (let [sequence-function-maps [{:sequence (range 30), :function testing-func},
                               {:sequence (range 15), :function testing-func}]]
    (run-with-reporting sequence-function-maps stop-clj-time)))


texts: OOP demonstration in C++17 using a Pokémon

texts:
I want to showcase with as minimal code as possible the basic Object-oriented programming (OOP) principles of Polymorphism, Inheritance, and Encapsulation. I know there are many more principles than just these 3 and even different types of the 3 I've mentioned there. I attempted to implement them all below. I think using Pokémon as an example is a good way to show this, so I've used Castform as my buddy of choice for these examples.

If you believe showcasing more than just Polymorphism, Inheritance, and Encapsulation to evaluate a developers understanding of OOP, please provide comments around this and which additional key principles I should add to my Pokémon example.

Main.cpp

#include <iostream>
#include <string>
#include <time.h>

class Pokemon
{
    protected:
        int m_dex_num;
        float m_catch_rate;
        std::string m_type;
    public:
        Pokemon(int dex_num, int catch_rate, std::string type)
            : m_dex_num(dex_num), m_catch_rate(catch_rate), m_type(type) {}

        int dex_num() const { return m_dex_num; }
        float catch_rate() const { return m_catch_rate; }
        std::string type() const { return m_type; }

        virtual bool attempt_catch() = 0;
};

class Castform : public Pokemon
{
    private:
        std::string m_forms[3] = { "sunny", "rainy", "snowy" };
    public:
        Castform() : Pokemon(351, 11.9, "normal") {}

        bool attempt_catch() {
            srand(time(NULL));
            return (rand() % 100) < m_catch_rate;
        }
};

int main()
{
    auto wild_castform = Castform();

    std::cout << "Wild Castform appeared!\n";
    std::cout << "Dex number " << wild_castform.dex_num() << '\n';
    std::cout << "It's a " << wild_castform.type() << " type\n";

    for(int i=0; i < 5; ++i) {
            std::cout << "Catch attempt resulted in " << wild_castform.attempt_catch() << '\n';
    }

    return 0;
}


texts:
The problem (from Cracking the Coding book):

  Given an NxM matrix in which each row and each column is sorted in ascending order, write a method to find an element.

I thought of a modified version of binary search, and I haven't found this solution anywhere on the internet (some solution about quad partitioning is very similar as seen in this link).

Here's my solution:

def search(elem, matrix, up, down, left, right):

    if up > down or right < left:
        return None

    mid_row = int((up + down) / 2)
    mid_col = int((left + right) / 2)

    mid_elem = matrix[mid_row][mid_col]

    if elem == mid_elem:
        return mid_row, mid_col
    elif up == down and left == right:
        return None

    if elem > mid_elem:
        # Search RIGHT
        right_search = search(elem, matrix, up, down, mid_col + 1, right)

        if right_search == None:
            # Search DOWN
            return search(elem, matrix, mid_row + 1, down, left, right)

        return right_search

    else:
        # Search LEFT
        left_search = search(elem, matrix, up, down, left, mid_col - 1)

        if left_search == None:
            # Search UP
            return search(elem, matrix, up, mid_row - 1, left, right)

        return left_search

    return None

The code can be tested with the following:

if __name__ == "__main__":
    matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24]]
    elem = 8
    N = len(matrix)
    M = len(matrix[0])
    print(search(elem, matrix, 0, N-1, 0, M-1))

I think that my code is pretty neat and easy to understand. As far as I tested it works perfectly, and should have a time complexity similar to the QuadPartition. What I don't understand is why haven't I seen this solution code anywhere? Is there a cleaner and faster way to write it?


texts: Fastest way to find all neighbours of a vertex in a graph

texts:
I'm looking for the fastest way to find all neighbours of a vertex in an undirected Graph.  Please improve on the code if possible.

neighbours[g_Graph, v_] :=
 Module[
  {vl = VertexList[g],
   pos},
  pos = Position[vl, v][[1, 1]];
  Pick[VertexList[g], AdjacencyMatrix[g][[pos]], 1]
 ]

I need it to work fast both for sparse and dense graphs.

It is essential to the performance of this solution that it uses SparseArrays.
This is a bottleneck in my application.  Since my graph is constantly changing, trying to precompute neighbours or using memoization will complicate things significantly.

I'd like to stress that speed is essential here.  Here's a graph to test on:

max = 4000;
c = 0.3;

tg = RandomGraph[{max, Round[c max^2]}];

neighbours[tg, 1]; // Timing


texts: 1-dimensional and 2-dimensional Peak Finding Algorithm

texts:
I have the following code for a peak finding algorithm in Python 3.4.3. A peak is an element that is not smaller than its neighbors.

def peak1d(array):
    '''This function recursively finds the peak in an array
       by dividing the array into 2 repeatedly and choosning
       sides.

       Complexity: O(log n)'''

    mid = len(array)//2

    if mid > 0 and array[mid] < array[mid-1]:
        return peak1d(array[:mid])

    elif mid < len(array)-1 and array[mid] < array[mid+1]:
        return peak1d(array[mid:])

    else:
        return array[mid]

def peak2d(array):
    '''This function finds the peak in a 2D array by the
       recursive method.

       Complexity: O(n log m)'''

    n = len(array)
    m = len(array[0])

    j = m//2

    row = [i[j] for i in array]

    i = row.index(max(row))

    print(i, j)

    if j > 0 and array[i][j] < array[i][j-1]:
        return peak2d([row[:j] for row in array])

    elif j < m - 1 and array[i][j] < array[i][j+1]:
        return peak2d([row[j:] for row in array])

    else:
        return array[i][j]

I think that I could utilize the first function in 2D peak finding but I don't know if it's upto the best practices. Also, can you suggest any methods to make my program faster and better.

Just another thought, I believe it doesn't matter if we transpose the array. The peak will remain the same. So should I transpose the array to reduce the complexity at times.


texts: GeeksforGeeks: Rotate matrix by 90 degrees

texts:
Please review the code readability, I would like to have an easier to follow code.
Thanks

using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace ArrayQuestions
{
    /// <summary>
    /// https://www.geeksforgeeks.org/inplace-rotate-square-matrix-by-90-degrees/
    /// </summary>
    [TestClass]
    public class RotateMatrix90
    {
        [TestMethod]
        public void Rotate3x3Test()
        {
            int[,] mat =
            {
                {1, 2, 3},
                {4, 5, 6},
                {7, 8, 9}
            };
            int[,] expected =
            {
                {3, 6, 9},
                {2, 5, 8},
                {1, 4, 7}
            };
            rotateMatrix(mat);
            for (int r = 0; r < mat.GetLength(0); r++)
            {
                for (int c = 0; c < mat.GetLength(1); c++)
                {
                    Assert.AreEqual(expected[r, c], mat[r, c]);
                }
            }

        }

        void rotateMatrix(int[,] mat)
        {
            int size = mat.GetLength(0);
            for (int x = 0; x < size / 2; x++)
            {
                for (int y = x; y < size - x - 1; y++)
                {
                    int temp = mat[x, y];             // save 1
                    mat[x, y] = mat[y, size - x - 1]; // move 3 into 1
                    mat[y, size - x - 1] = mat[size - x - 1, size - y - 1]; // move 9 into 3
                    mat[size - x - 1, size - y - 1] = mat[size - y - 1, x]; // move 7 into 9
                    mat[size - y - 1, x] = temp;
                }
            }
        }
    }
}


texts:
Here I am trying to avoid hardcoding in flash messages by using I18n. Also, I have tried to use a CSS selector for submitting the form to make the tests less brittle (I don't really care that much about what the text on the button is - more what happens when submitting).

Is this a good approach for making tests less brittle due to translation changes?

RSpec.feature "Classic Authentication" do

  let(:submit) {  find(:css, 'input[type="submit"]') }
  let(:user) { FactoryGirl.create(:user) }

  context 'Registation' do
    background do
      visit new_user_registration_path
      page.fill_in 'Email', with: 'test@example.com'
      page.fill_in 'Password', with: 'P4ssword'
      page.fill_in 'Password confirmation', with: 'P4ssword'
    end
    scenario "when I sign up with valid info" do
      submit.click
      expect(page).to have_content I18n.t('devise.registrations.signed_up')
      expect(page).to have_content I18n.t('user.sign_out')
    end
    scenario "when I sign up with invalid info" do
      page.fill_in 'Email', with: 'testasdas'
      submit.click
      expect(page).to have_content 'Email is invalid'
      expect(page).to_not have_content I18n.t('devise.registrations.signed_up')
    end
  end

  context 'Log in' do
    background do
      visit '/'
      click_link I18n.t('user.sign_in')
      page.fill_in 'Email', with: user.email
    end
    scenario 'when I sign in with valid details.' do
      page.fill_in 'Password', with: 'P4ssword'
      submit.click
      expect(page).to have_content I18n.t('devise.sessions.signed_in')
      expect(page).to have_link I18n.t('user.sign_out')
    end
    scenario 'when I sign in with an invalid password' do
      page.fill_in 'Password', with: 'H4XX0R'
      submit.click
      expect(page).to_not have_content I18n.t('devise.sessions.signed_in')
    end
  end
end


texts: Writing a Counter object to a CSV-file in Python 3

texts:
In Python 3.4, a Counter object called cnt like this:

Counter({'0200': 3, '3000': 2, '3011': 2, '0210': 1, '4000': 1})

is to be written to a comma-separated file.

I first tried with CSV and DictWriter that I had not used before, but I kept getting misty errors and was pressed for time, so I decided to make this simple version (it works):

outfile = infile[:-4] + '_freq.csv'
fp = open(outfile, encoding='utf-8-sig', mode='w')
fp.write('KMC|freq\n')
for tag, count in cnt.items():
    fp.write('{}|{}\n'.format(tag, count))

fp.close()

Then when I had some time I felt I should learn to use DictWriter and CSV, assuming it'd be 'better' or 'more pythonic'.

That turned into this (works too):

outfile2 = infile[:-4] + '_freq2.csv'
with open(outfile2, encoding='utf-8-sig', mode='w', newline='') as f:
                # Note: empty newline to avoid blank lines in the output file
    fieldnames = ['KMC', 'freq']
    writer = csv.DictWriter(f, fieldnames=fieldnames, delimiter='|')
    writer.writeheader()
    for tag, count in cnt.items():
        writer.writerow({'KMC': tag, 'freq': str(count)})

The trick with the empty newline to avoid blank lines is from here.

I like the first approach better. I think CSV and DictWriter are intended for much larger amounts of columns than the two small ones I got. But I'm no expert.

Any learned comments?