texts:
Here is a simple function I wrote to parse record-jar data. I need it in a php5.3 application to validate bcp47 language tags. It converts the language subtag registry among other things, into a nested php array. Any suggestions on how I can improve it?

/**
 * Quick script to parse any record-jar data into an array.
 *
 * In particular, this is of use to someone trying to validate bcp47 language codes.
 * @see http://tools.ietf.org/search/bcp47#section-3.1.1
 */
function parse_record_jar($record_jar_string) {
  $records = array();
  $record = array();
  foreach(explode('%%', $record_jar_string) as $recordstr) {
    array_splice($record, null); // truncate $record
    foreach(array_filter(explode("\n", $recordstr)) as $line) {
      $parts = array_map('trim', explode(":", $line, 2));
      if (count($parts) === 2) {
        list($key, $value) = $parts;
      } else {
        // $key retains its value from the previous iteration.
        $value = $parts[0];
      }
      if (!isset($record[$key])) {
        $record[$key] = '';
      }
      $record[$key] .= $value;
    }
    $records[] = $record;
  }
  return $records;
}


texts: A Scala Maze Generator in Functional Style

texts:
I'm wondering if there is more I can do to incorporate more idiomatic scala and functional programming principles. I know the maze itself is mutable but i didn't see an easy solution to making it immutable. Also, if there is anything I can do to improve my algorithm, that would be great too. The reason I have the trait is so that I can implement more mazes: Prim's, Kruskal's, ... and get the functionality of the trait.

trait Maze {
  val height: Int
  val length: Int
  var maz: Array[Array[Int]]

  def maze: Maze

  override def toString() = {
    val strBuilder = new StringBuilder()
    for (i <- 0 until height) {
      for (j <- 0 until length) {
        strBuilder.append(maz(i)(j))
      }
      strBuilder.append("\n")
    }
    strBuilder.toString()
  }
}

class DepthFirstSearch(val height: Int, val length: Int, var maz: Array[Array[Int]]) extends Maze {

  def this(height: Int, length: Int) {
    this(height, length, Array.ofDim[Int](height, length))
  }

  override def maze = {
    maz(0)(0) = 1
    val stack = List[(Int, Int)]()
    mazify((0, 0) :: stack, (0, 0))
  }

  private def mazify(stack: List[(Int, Int)], currentCell: (Int, Int)): DepthFirstSearch = {
    if (stack.nonEmpty) {
      val unvisitedNeighbor = getRandomUnvisitedNeighbor(maz, currentCell)
      if (unvisitedNeighbor._1) {
        val newCurrentCell = unvisitedNeighbor._2
        maz(newCurrentCell._1)(newCurrentCell._2) = 1
        mazify(currentCell :: stack, newCurrentCell)
      } else if (stack.nonEmpty) {
        val newCurrentCell = stack.head
        mazify(stack.tail, newCurrentCell)
      }
    }
    new DepthFirstSearch(height, length, maz)
  }

  private def neighbors(cell: (Int, Int)) = {
    List((cell._1 - 1, cell._2), (cell._1 + 1, cell._2), (cell._1, cell._2 + 1), (cell._1, cell._2 - 1))
  }

  private def insideMaze(cell: (Int, Int)) = {
    cell._1 >= 0 && cell._1 < height && cell._2 >= 0 && cell._2 < length
  }

  private def notOriginalCell(cell: (Int, Int), originalCell: (Int, Int)) = {
    cell._1 != originalCell._1 && cell._2 != originalCell._2
  }

  private def cellVisited(cell: (Int, Int)) = {
    maz(cell._1)(cell._2) == DepthFirstSearch.Visited
  }

  private def hasValidNeighbors(cell: (Int, Int), originalCell: (Int, Int)) = {
    val neighboringCells = neighbors(cell)
    val filteredNeighbors = neighboringCells.filter(c => insideMaze(c) && cellVisited(c) && notOriginalCell(c, originalCell))
    val isValidCell = filteredNeighbors.isEmpty
    isValidCell
  }

  private def getUnvisitedNeighbors(maze: Array[Array[Int]], cell: (Int, Int)) = {
    val neighboringCells = neighbors(cell)
    val filteredNeighbors = neighboringCells.filter(c => c._1 >= 0 && c._1 < height && c._2 >= 0 && c._2 < length && maze(c._1)(c._2) != 1 && hasValidNeighbors(c, cell))
    filteredNeighbors
  }

  private def getRandomUnvisitedNeighbor(maze: Array[Array[Int]], cell: (Int, Int)): (Boolean, (Int, Int)) = {
    val neighbors = getUnvisitedNeighbors(maze, cell)
    if (neighbors.length > 0)
      (true, neighbors(Random.nextInt(neighbors.size)))
    else
      (false, (-1, -1))
  }
}

object DepthFirstSearch {
  private val Visited = 1

  def apply(height: Int, length: Int) = new DepthFirstSearch(height, length)
}


texts:
I have an agreement with a customer. When the agreement ends, the customer needs to pay. The amount which the customer needs to pay increases for each month that has passed since the agreement was initiated. The maximum duration is 3 years, so I have a final expiration date. From this final expiration date, I must be able to find the periodic expiration date (the date when the payment increases). In other words, I need a function which does this:

DateTime GetNextExpirationDate(finalExpirationDate)

One of the issues which I am struggling with is that the algorithm needs to consider whether the expiration date in the current month has already passed (there will be a date each month). It also needs to consider that the day of the month for the final expiration date, might not exist for the periodic expiration dates (e.g. if the final expiration date is the 31st of something).

I have some code which is working, but it appears somewhat redundant and with many steps. I was wondering, if perhaps it could be simplified (either a little or a lot).

public DateTime GetNextExpirationDate(DateTime finalExpirationDate)
{
    int expirationDay = finalExpirationDate.Day;
    int currentMonth = DateTime.Now.Month;
    int currentYear = DateTime.Now.Year;
    int daysInCurrentMonth = DateTime.DaysInMonth(currentYear, currentMonth);

    // If the month has less days that the day of the final expiration date,
    // then we need to use the maximum date of the month.
    int expirationDayThisMonth = Math.Min(expirationDay, daysInCurrentMonth);

    DateTime expirationDateThisMonth = new DateTime(currentYear, currentMonth, expirationDayThisMonth);

    // If the periodic expiration date in the current month is already surpassed,
    // then we need to the date in the next month.
    if (expirationDateThisMonth < DateTime.Now)
    {
        DateTime dateInOneMonth = DateTime.Now.AddMonths(1);
        int nextMonthMonth = dateInOneMonth.Month;
        int nextMonthYear = dateInOneMonth.Year;
        int daysInNextMonth = DateTime.DaysInMonth(nextMonthYear, nextMonthMonth);

        int expirationDayNextMonth = Math.Min(expirationDay, daysInNextMonth);

        DateTime expirationDateNextMonth = new DateTime(nextMonthYear, nextMonthMonth, expirationDayNextMonth);

        return expirationDateNextMonth;
    }
    else
    {
        return expirationDateThisMonth;
    }
}

Any ways to improve this?

Input/output examples:

Final expiration date: 15.12.2019
DateTime.Now: 12.03.2019
Output: 15.03.2019

Final expiration date 11.10.2019
DateTime.Now: 16.04.2019
Output: 11.05.2019

(I know that I cannot change DateTime.Now but it does work as an pseudo-input, which is why I included it).


texts: Number of occurrences of each different word in a line of text

texts:
I am looking for feedback on a solution to the following problem posed from a book that I'm working through (Java: How To Program 9th Edition):

  Write an application that reads a line of text and prints a table indicating the number of occurrences of each different word in the text. The application should include the words in the table in the same order in which they appear in the text. For example, the lines

  To be, or not to be: that is the question:
  Whether 'tis nobler in the mind to suffer

  contain the word “to” three times, the word “be” two times, the word “or” once, etc.

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

public class TextAnalysisC {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    Scanner sc = new Scanner( System.in );
    System.out.println( "Please enter a line of text" );
    String userInput = sc.nextLine();

    userInput = userInput.toLowerCase();

    userInput = userInput.replaceAll( "\\W", " " );     // strip out any non words.
    userInput = userInput.replaceAll( "  ", " " );      // strip out any double spaces
                                                        //   created from stripping out non words
                                                        //   in the first place!
    String[] tokens = userInput.split( " " );
    System.out.println( userInput );

    ArrayList< String > items = new ArrayList< String >();

    items.addAll( Arrays.asList( tokens ) );

    int count = 0;

    for( int i = 0; i < items.size(); i++ )
    {
        System.out.printf( "%s: ", items.get( i ) );
        for( int j = 0; j < items.size(); j++ )
        {
            if( items.get( i ).equals( items.get( j ) ) )
                count++;
            if( items.get( i ).equals( items.get( j ) ) && count > 1 )
                items.remove( j );                      // after having counted at least
        }                                               // one, remove duplicates from List
        System.out.printf( "%d\n", count );
        count = 0;
    }
}
}

Can this be simplified?  Is this easy to understand?  What should I improve?

I regret to report that I have been remiss on the current scope of my knowledge as I work through my textbook (Java: 9th Edition). Solutions should be within the limits of what I have covered so far, that being:

Introduction to Computers and Java
Introduction to Java Applications
Introduction to Classes, Objects, Methods and Strings
Control Statements: Part 1
Control Statements: Part 2
Methods: A Deeper Look
Arrays and ArrayLists
Classes and Objects: A Deeper Look
Object-Oriented Programming: Inheritance
Object-Oriented Programming: Polymorphism
Exception Handling: A Deeper Look
GUI Components: Part 1 (Swing)
Strings, Characters and Regular Expressions


texts: Take a Ten Minute Walk: A City Tour Solution

texts:
I recently came across the following problem on Codewars:

  Take a Ten Minute Walk

  You live in the city of Cartesia where all roads are laid out in a perfect grid.
  You arrived ten minutes too early to an appointment, so you decided to take
  the opportunity to go for a short walk. The city provides its citizens with a
  Walk Generating App on their phones -- every time you press the button it sends you an array of one-letter strings representing directions to walk
  (eg. ['n', 's', 'w', 'e']).
  You know it takes you one minute to traverse one city block, so create a function
  that will return true if the walk the app gives you will take you exactly ten
   minutes (you don't want to be early or late!) and will, of course, return you to
  your starting point. Return false otherwise.

I solved the problem with the following function:

function isValidWalk(walk) {
  var directions = {
    'n': 0,
    's': 0,
    'e': 0,
    'w': 0
  }
  walk.forEach( function(direction) {
    directions[direction]++;
  }
  var displacement = {
    x: directions['n'] - directions['s'],
    y: directions['e'] - directions['w']
  }
  /*it take 1 min to traverse 1 block & I only have 10 minutes,
  & I also want to attend appointment, so i want to come from where i start.*/
  return walk.length === 10 && displacement.x === 0 && displacement.y === 0;
}


texts: Creating Docker network with REST API using Python Django

texts:
This solution is to create a docker network using Docker supported APIs. For achieving this, I am using Python and Django framework for providing RESTful APIs.

cat network.py
from django.http import JsonResponse
import requests
import json

HEADERS = {"Content-Type" : "application/json", "Accept" : "application/json"}

def network_details():
    response = requests.get("http://127.0.0.1:6000/networks")
    #table = [[Name, Id, Driver, Subnet, Gateway]]
    table = []
    details = {}
    for network in response.json():
        details["Name"] = network["Name"].encode("utf-8")
        details["Id"] = network["Id"].encode("utf-8")[:12]
        details["Driver"] = network["Driver"].encode("utf-8")

        #to check if dict is Null
        if network["IPAM"]["Config"].__len__() == 0:
            details["Subnet"] = "none"
            details["Gateway"] = "none"
        else:
            ip_config = network["IPAM"]["Config"][0]

            details["Subnet"] = ip_config["Subnet"]
            details["Gateway"] = ip_config["Gateway"]

        table.append(details)
        #intializing to dict to None as scope is outside the for loop as well
        details = {}
    return table

def network_info(request):
    if request.method == "GET":
        return JsonResponse(network_details(), safe=False)

def create_nw(content):
    response = requests.post("http://127.0.0.1:6000/networks/create",
                            content, headers = HEADERS )
    return response.json()

def create_network(request):
    if request.method == "POST":
        try:
            response = create_nw(request.body)
            #explicitly looking for Warning or message to know the status
            if "Warning" in response:
                return JsonResponse("Success, Network created with ID: {}".
                                   format(response['Id'].encode('utf-8')[:12]),safe=False)
         elif "message" in response:
                return JsonResponse("Error : {}".
                                   format(response.values()[0]),safe=False)
        except ValueError:
        return JsonResponse("Error : Improper JSON format provided", safe=False)

URLs information:

cat urls.py
from django.conf.urls import url

from . import views, images, containers, network

urlpatterns = [
              url(r'images', images.images_info),
              url(r'containers', containers.active_containers),
              url(r'network/create', network.create_network),
              url(r'network', network.network_info),
              url(r'^$', views.index, name='index'),
              ]

RESTful API to the solution:

curl -X POST <****>/network/create -d @create_network.json --header "Content-Type: application/json" | jq

Can someone suggest if this the right way to build an application using Django framework?

I am not looking for the appropriate/optimized solution for the idea I want to work on. I am looking for your suggestions how can I improve in my coding skills. The reason for selecting Django is to get hands on the framework.


texts:
I'm not sure if this implementation is good enough.  The function takes a vector of 1 million chars and creates a table of the sequences that pass before the next occurrence of itself.

Some questions I have, though feel free to point other things out as well:

Is the initialization of the hash-map done well?
Am I using the correct / optimal data structures and algorithm?
I think my code is more procedural than needs to be, having trouble thinking of folding this correctly.

(define (get-reocc v)
;'(#\J #\S #\T #\I #\J #\I #\O #\Z #\T #\S ....) ->
;  '#hash((#\T . #(1 357 1661 1939 1759 1425 1240 985 890 716 556 483 392 335 268 1258))
;       (#\J . #(1 449 1613 1914 1725 1480 1266 1021 850 748 581 527 377 317 255 1223))
;       (#\S . #(1 379 1678 1995 1708 1397 1230 1006 860 714 605 489 378 318 323 1211))
;       (#\L . #(1 449 1671 1916 1663 1492 1256 1000 862 735 572 449 400 330 276 1259))
;       (#\O . #(1 396 1596 1854 1727 1491 1270 1109 873 743 584 473 371 315 273 1209))
;       (#\I . #(1 396 1625 1901 1758 1414 1229 1057 852 733 605 483 359 328 260 1249))
;       (#\Z . #(1 394 1529 1973 1657 1473 1309 1018 863 746 569 481 362 355 245 1256)))
  (define reocc-table2 (make-hash))
  (for ([i pieces])
    (hash-set! reocc-table2 i (make-vector 16 0)))

  (define (update-reocc key pos t)
; #\T 3 '#hash((#\T . #(1 357 1661 1939 1759 -> '#hash((#\T . #(1 357 1661 1940 1759
    (define v2 (hash-ref t key))
  (vector-set! v2 pos (+ 1 (vector-ref v2 pos))))
;    (hash-set y key (vector-set! v2 pos (+ 1 (vector-ref v2 pos)))))  same as above?

(define (find-prev v piece pos i2)
  ; (#\J #\S #\T #\I #\J #\I #\O #\Z #\T #\S) #\T, #\T, 10, 0 -> 8
  ;   (define x (vector-ref v (- pos i2)))
                   (cond [(char=? piece x) i2]
                         [(= 0 (- pos i2)) 0]
                         [#t (find-prev v piece pos (+ i2 1))]))

(define (f v t i)
  (define p (vector-ref v i))
  (define stop (- 1 (vector-length v)))
    (if(>= i stop)
       t
        (f v (lambda () (update-reocc p (find-prev v p i 0) t)) (+ i 1))))

  (f v reocc-table2 0))


texts: Extract thoughput value from JMeter log file

texts:
I use JMeter for load testing and want to report error on CI pipeline when application though put is less than 1/sec. JMeter logs summary of results as -

2017/01/17 01:57:00 INFO  - jmeter.reporters.Summariser: summary +    103 in 00:00:30 =    3.4/s Avg:  2937 Min:    48 Max:  7962 Err:     0 (0.00%) Active: 2 Started: 10 Finished: 8
2017/01/17 01:57:00 INFO  - jmeter.reporters.Summariser: summary =  12218 in 01:00:03 =    3.4/s Avg:  2942 Min:    20 Max: 27317 Err:     1 (0.01%)
2017/01/17 01:57:00 INFO  - jmeter.reporters.Summariser: summary +      1 in 00:00:00 =   66.7/s Avg:  3227 Min:  3227 Max:  3227 Err:     0 (0.00%) Active: 0 Started: 10 Finished: 10
2017/01/17 01:57:00 INFO  - jmeter.reporters.Summariser: summary =  12219 in 01:00:03 =    3.4/s Avg:  2942 Min:    20 Max: 27317 Err:     1 (0.01%)

Herein I would capture the last line and if value of throughput is less than 1 (which is 3.4/s in the current example) then it would be reported as error. Here is the script I wrote to capture value of throughput -

grep "meter.reporters.Summariser: summary" test.log | tail -1 | awk '{print $12}' | cut -d "." -f1

and it gets me 3 which is ok. How can I improve this script?


texts: Get JSON script code with pushing to heatmap

texts:
I have a script that makes a database call and then filters the results. After filtering it pushes it to an array and shows it on a map.

Here is my function:

function getDriving() {
    pointArray.length = 0;
    markers.length = 0;
    var todayval = new Date();

    var url = $('#map').data('request-url2');
    $.getJSON(url,
        function (data) {
            $.each(data,
                function (i, item) {

                    markers.push({
                        'location': new google.maps.LatLng(item.Latitude, item.Longitude),
                        'map': map,
                        'weight': item.Speed,
                        'radius': 10,
                        'date': item.CurrentDateTime,
                        'imei': item.Imei
                    });
                });
            imei = parseInt($('#selectVehicles').val());

            var startValue = $('#startDate').val().split("/");
            var endValue = $('#endDate').val().split("/");
            var valDateStart = new Date(startValue[2], startValue[1] - 1, startValue[0]);
            var valDateEnd = new Date(endValue[2], endValue[1] - 1, endValue[0]);

            filtered = markers.filter(function (marker) {
                var getDate = marker.date.match(/\d/g).join('');
                var markerDate = new Date(parseFloat(getDate));
                return ((markerDate >= valDateStart && markerDate <= valDateEnd) && marker.imei === imei);
            });
            var pointArray = new google.maps.MVCArray(filtered);

            heatmap = new google.maps.visualization.HeatmapLayer({
                data: pointArray
            });
            heatmap.setMap(map);
        });
};

It works well, but I want to know if everything is okay with the code or how I can improve it.


texts:
Here is my entry for the Code Jam problem Full Binary Tree (I didn't compete but tackled the problem afterwards). It does solve the provided inputs, so I suppose it is correct. I am looking for any suggestions regarding the code. One thing I don't like is the fact that the Node constructor clears the array that it receives as a parameter, do you see a clean way to fix this ? Is it possible without declaring an extra class wrapping Node ?

import java.util.*;

class Node {
    static NodeComparator cmp = new NodeComparator();

    private ArrayList<Node> children = new ArrayList<>();
    private int nDescendants = 0;    // descendants = number of children and, recursively, children of children, etc.

    public int getNDescendants() {
        return nDescendants;
    }

    // turns the tree into a full binary tree by removing as few nodes as possible
    public void makeFullBinary() {
        // first, recursively make all the children into full binary trees
        for (Node n : children) {
            n.makeFullBinary();
        }
        // sort the children from least to most number of descendants
        Collections.sort(children, cmp);
        // remove descendants as needed to end up with 0 or 2
        while ((children.size() != 0) && (children.size() != 2)) {
            children.remove(0);
        }
        // recompute the number of descendants
        nDescendants = 0;
        for (Node c : children) {
            nDescendants += 1 + c.getNDescendants();
        }
    }

    // builds a tree from an array of booleans (adjacency matrix)
    // edges is destroyed after the constructor is called
    public Node(boolean[][] edges, int root) {
        for (int i = 0; i < edges.length; i++) {
            if (edges[root][i]) {
                edges[root][i] = false;
                edges[i][root] = false;
                children.add(new Node(edges, i));
            }
        }
        for (Node c : children) {
            nDescendants += 1 + c.getNDescendants();
        }
    }
}

// comparator for sorting only
class NodeComparator implements Comparator<Node> {
    @Override
    public int compare(Node n0, Node n1) {
        return n0.getNDescendants() - n1.getNDescendants();
    }
}

public class Program {

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

        int nCases = in.nextInt();
        in.nextLine();

        for (int caseNumber = 1; caseNumber <= nCases; caseNumber++) {
            int nNodes = in.nextInt();
            in.nextLine();

            boolean[][] edges = new boolean[nNodes][nNodes];

            for (int i = 0; i < nNodes-1; i++) {
                String[] s = in.nextLine().split(" ");
                int x = Integer.parseInt(s[0])-1;
                int y = Integer.parseInt(s[1])-1;
                edges[x][y] = true;
                edges[y][x] = true;
            }

            int maxDescendants = 0;
            boolean [][] e = new boolean[nNodes][nNodes];
            for (int i = 0; i < nNodes; i++) {
                for (int a = 0; a < nNodes; a++) {
                    for (int b = 0; b < nNodes; b++) {
                        e[a][b] = edges[a][b];
                    }
                }
                Node tree = new Node(e, i);
                tree.makeFullBinary();
                maxDescendants = Math.max(maxDescendants, tree.getNDescendants());
            }

            System.out.print("Case #");
            System.out.print(caseNumber);
            System.out.print(": ");
            System.out.println(nNodes - maxDescendants - 1);
        }
        in.close();
    }
}


texts:
This works just fine, however, the assignment was to write a recursive "function".  I'm curious to see if this should count.

Any comments / suggestions/ stuff I should watch out for are appreciated.

#include <iostream>
#include <functional>
#include <cctype>
#include <cstdlib>

int main() {

    char go_again = 'Y';

    do {

        int lhs, rhs;
        std::cout << "Enter 2 integer values: ";
        std::cin >> lhs >> rhs;

        if (lhs < 0 || rhs < 0)
            std::cout << "Implicit converstion to positive integers.\n";

        std::function<int(int, int)>
            gcd = [&](int lhs, int rhs) -> int {
                return rhs == 0 ? std::abs(lhs) : gcd(rhs, lhs % rhs);
        };

        std::cout << "gcd == " << gcd(lhs, rhs) << '\n';
        std::cout << "Go again? <Y/N> ";
        std::cin >> go_again;

    } while (std::toupper(go_again) == 'Y');

}


texts: Pass Cassandra session reference to http handlers

texts:
I'm building a golang backend using gorilla/mux and gocql. My objective is to create a session to a remote cassandra and share the very same session to a serie of handlers.

I came out with this implementation:

server.go:

package main

import (
    "fmt"
    "net/http"
    "os"

    "github.com/andream16/price-probe-go/api/item/rest"
    "github.com/andream16/price-probe-go/cassandra"
    "github.com/gorilla/mux"
)

func main() {

    fmt.Println("Initializing Cassandra connection . . .")
    s, err := cassandra.InitCassandraClient()
    if err != nil {
        fmt.Println("Unable to set up Cassandra client!")
        os.Exit(1)
    }
    fmt.Println("Successfully initialized Cassandra connection . . .")

    fmt.Println("Starting server . . .")
    router := mux.NewRouter()
    router.HandleFunc("/item", itemrest.ItemHandler(&s))

    . . .

}

I create a new HandleFunc for each route and pass it &s.

And each handler is like:

func ItemHandler(session *gocql.Session) func(w http.ResponseWriter, r *http.Request) { }

Is there a more elegant way to achieve this?


texts: Usage of state machine to model lifetime of an IP address

texts:
I need to model an IP address and thought using a state machine (the state_machine gem) would be a good idea.

An IP has the following characteristics:

It is assigned to a server.
It can be in state unbound (implies unprotected), bound (implies protected), reserved.
It has several firewall rules which should be automatically activated/deactivated when binding/unbinding.
It can be migrated from/to another server.
All operations, such as (de)activating firewall rules and (un)binding, may fail or externally change their state (consider a machine reboot).

Here is what I came up with so far:

require 'rubygems'
require 'state_machine'
require 'awesome_print'

class Ip
  state_machine :state, :initial => :unbound do
    # idle states, i.e. only an event (either external or internal) will trigger a transition.
    state :unbound, :bound, :reserved

    # transitionary states, we expect a state change after a certain period of time.
    state :protected, :unprotected

    event :cycle do
      transition :unbound => :protected
      transition :protected => :bound
      transition :bound => :unprotected
      transition :unprotected => :unbound
    end

    event :reserve do
      transition :unbound => :reserved
    end

    event :release do
      transition :reserved => :unbound
    end

    before_transition any => any, :if => :refreshing? do |ip, transition|
      puts "refreshing, before_transition -> state is: #{transition.from}, state will be: #{transition.to}"
      throw :halt unless ip.send("is_#{transition.to}?")
    end

    before_transition any => any do |ip, transition|
      puts "before_transition -> state is: #{transition.from}, state will be: #{transition.to}"
    end

    before_transition any => :protected, :do => :activate_firewall_rules
    before_transition any => :unprotected, :do => :deactivate_firewall_rules

    before_transition any => :bound, :do => :bind_to_server
    before_transition any => :unbound, :do => :unbind_from_server

    after_transition any => any do |ip, transition|
      puts "after_transition -> state was: #{transition.from}, state is: #{transition.to}"
    end
  end

  def bind!
    wait!(:bound)
  end

  def unbind!
    wait!(:unbound)
  end

  def migrate!(new_server)
    restore_state do
      unbind!
      self.server = new_server
    end
  end

  def refresh!
    return if reserved?
    self.state = self.class.new.state # set to initial state
    @refreshing = true
    nil while cycle
    @refreshing = false
  end

  def restore_state
    old_state = state
    yield
    wait!(old_state)
  end

  def wait!(desired_state)
    cycle! while !state?(desired_state)
  end

  def refreshing?
    @refreshing
  end

  def activate_firewall_rules
    puts "activate_firewall_rules..."
    @is_protected = true
  end

  def deactivate_firewall_rules
    puts "deactivate_firewall_rules..."
    @is_protected = false
  end

  def bind_to_server
    puts "bind_to_server..."
    @is_bound = true
  end

  def unbind_from_server
    puts "unbind_from_server..."
    @is_bound = false
  end

  def is_protected?
    puts "is_protected: #{@is_protected}"
    @is_protected
  end

  def is_unprotected?
    !is_protected?
  end

  def is_bound?
    puts "is_bound: #{@is_bound}"
    @is_bound
  end

  def is_unbound?
    !is_bound?
  end
end

The public API should be something like this:

bind! (bring up firewall and bind address to server)
unbind! (unbind address to server and bring down firewall
refresh! (get real/external state and update internal state)
migrate! (assign to new server, retain state)

Since this is my very first state machine I thought I'd like to ask what you think about it. Do you think using a state machine makes sense here at all? Am I using it correctly or am I doing something wrong? What and why?


texts: Node.js Nested Callbacks, multiple requests

texts:
I'm making requests to Parse.com to 3 different objects that are needed to render a View.
I'd like to know what's the general/best approach in cases like these in which there are multiple requests before actually handling the data.

Code:

    var Parse = require('parse-api').Parse;
    var parse = new Parse();

    exports.single = function() {
        parse.find('Class_1',params1,function(error,response1){
            parse.find('Class_2',params2,function(error, response2){
                parse.find('Class_3',params3,function(error3, response3){

                    // handle responses....
                    // render view....
                })
            })
        })
    }

Thanks!


texts: Making an alphabatical list grouped by letters

texts:
I have a pet project (open source on GitHub) that I built as a learning exercise. It is a lyrics web application built in .NET Core MVC.
On the artists page of the site (view on mobile size viewport, it is only optimised for mobiles so far), I list all artists alphabetically. The artists are grouped by letter.
The code that builds that page is the following:
Controller
[Route("artists")]
public async Task<IActionResult> Index()
{
  IDictionary<char, List<LibraryArtistViewModel>> viewModel = await _artistsService
    .GetAllArtistsAsync();

  return View(viewModel);
}

Service
public async Task<IDictionary<char, List<LibraryArtistViewModel>>> GetAllArtistsAsync()
{
  List<LibraryArtistViewModel> artists = new List<LibraryArtistViewModel>();

  await using NpgsqlConnection connection = new NpgsqlConnection(databaseOptions.ConnectionString);
  await connection.OpenAsync();

  await using NpgsqlCommand command = new NpgsqlCommand("select a.first_name, a.last_name, \"as\".name as primary_slug, ai.data as image_data, count(l.title) as number_of_lyrics from artists a left join artist_images ai on ai.artist_id = a.id inner join artist_slugs \"as\" on \"as\".artist_id = a.id left join lyrics l on l.artist_id = a.id where a.is_approved = true and a.is_deleted = false and \"as\".is_primary = true and l.is_approved = true and l.is_deleted = false group by a.id, \"as\".name, ai.data order by a.first_name asc;", connection);

  await using NpgsqlDataReader reader = await command.ExecuteReaderAsync();

  while (await reader.ReadAsync())
  {
    LibraryArtistViewModel artist = new LibraryArtistViewModel();
    string firstName = Convert.ToString(reader[0]);
    string lastName = Convert.ToString(reader[1]);
    string fullName = textInfo.ToTitleCase($"{firstName} {lastName}");
    string primarySlug = Convert.ToString(reader[2]);
    bool hasImage = reader[3] != System.DBNull.Value;
    int numberOfLyrics = Convert.ToInt32(reader[4]);

    artist.FirstName = firstName;
    artist.LastName = lastName;
    artist.FullName = fullName;
    artist.PrimarySlug = primarySlug;
    artist.HasImage = hasImage;
    artist.NumberOfLyrics = numberOfLyrics;

    artists.Add(artist);
  }

  IDictionary<char, List<LibraryArtistViewModel>> dictionary = BuildDictionary(artists);

  return dictionary;
}

private IDictionary<char, List<LibraryArtistViewModel>> BuildDictionary(List<LibraryArtistViewModel> artists)
{
  List<char> letters = new List<char>();

  IDictionary<char, List<LibraryArtistViewModel>> dictionary =
    new Dictionary<char, List<LibraryArtistViewModel>>();

  foreach (LibraryArtistViewModel artist in artists)
  {
    char firstLetter = char.ToUpper(artist.FirstName[0]);

    if (!letters.Contains(firstLetter))
    {
      letters.Add(firstLetter);

      dictionary.Add(firstLetter, new List<LibraryArtistViewModel>());
    }
  }

  foreach (char letter in letters)
  {
    foreach (LibraryArtistViewModel artist in artists)
    {
      char firstLetter = char.ToUpper(artist.FirstName[0]);

      if (letter == firstLetter)
      {
        List<LibraryArtistViewModel> artistsBeginningWithTheLetter = dictionary[letter];
        artistsBeginningWithTheLetter.Add(artist);
      }
    }
  }

  return dictionary;
}

The code above works, but I feel like it isn't efficient. I feel like there's a better way of doing this.
Also, I am very unsure about the way I serve up images. My images are currently stored in the database as bytes and I have a controller that serves up the image. This seems to be really killing my performance metrics on https://web.dev.
I built this project to learn things. So I'd really love to learn how to do things "properly" even if they are deemed an overkill.
I'd appreciate some pointers on the above and also on how exactly I can improve the artist images situation.


texts: Basic password authentication system app

texts:
This is a console app I wrote for an end-of-chapter assignment in Jumping into C++. The parameters were for it to have a basic password system, and if you are eager, a multiple password / username system.  I am going through this book completely on my own free will.  It's not through a school assignment or whatnot.

It works quite well, but as I have a limited programming background, I wanted to post it here so any bad techniques or poor syntax could be brought to my attention.

#include <iostream>

using namespace std;

string usrnam[] = { "admin", "user", "" };
string pasword[] = { "root", "default", ""};

string temp_pass;
string temp_usr;

bool loggedin;

int n = sizeof(usrnam) / sizeof(string);

int findPassword( string str[], int array_size, string query )
{
    for ( int i = 0; i < array_size; i++ )
    {
        if ( str[i] == query )
    {
        return i;
    }
}
}

int commandC()
{
    int stage;
    cout << "Enter '1' for calculator: ";
    cin >> stage;
    switch(stage)
{
    case 1: {
        cout << endl;
        cout << "Not fully developed" << endl << endl;

    }
}

cout << "_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-";
}

void login(string user, string pass){
     if ( pass == pasword[findPassword(usrnam, n, user)] )
     {
        cout << "Logged in as " << user << endl << endl;
        loggedin = true;
        commandC();
     }
}

void registerUser()
{
    string answer;
    cout << "No matches found in the database...would you like to make new account? (Y/N)";
    cin >> answer;
    if (answer == "y" || answer == "Y")
    {
        cout << "Please enter a username: ";
        cin >> usrnam[n-1];
        cout << "Please enter a password: ";
        cin >> pasword[n-1];

        login(usrnam[n-1],pasword[n-1]);
    }
}

int main()
{
    cout << "Enter username: ";
    cin >> temp_usr;
    cout << "Enter password; ";
    cin >> temp_pass;

    login(temp_usr,temp_pass);

    if(!loggedin)
        registerUser();
}


texts:
I've never had my C++ code reviewed before so I'd appreciate any feedback. Although my main focus was not on the implementation of the algorithm itself, any suggestions regarding improving it would be welcome. I'm mostly looking for C++ related feedback though.

#include <iostream>
#include <vector>

using namespace std;

class MinHeap {
public:
  void push(int num) {
    /* add num to end of the heap and rearrange by up-heap */
    heap.push_back(num);
    int ind = heap.size() - 1;

    if (heap.size() > 1) {
      int par = parent_index(ind);

      while (heap[ind] < heap[par]) {
        swap(heap[ind], heap[par]);
        ind = par;
        if (ind == 0) break;
        par = parent_index(ind);
      }
    }
  }

  void pop() {
    /* pop the element at the of the heap and finding a new top
    by replacing with the last element and performing a down-heap */
    if (heap.size() == 1) heap.pop_back();
    else if (heap.size() > 1) {
      swap(heap[0], heap.back());
      heap.pop_back();
      int ind = 0;
      int min_c = get_min_child(ind);

      while (heap[min_c] < heap[ind]) {
        swap(heap[min_c], heap[ind]);
        ind = min_c;
        if (child_count(ind) == 0) break;
        min_c = get_min_child(ind);
      }
    }
  }

  int top() {
    /* return element at the top of the heap (should be the min) */
    return heap.front();
  }

private:
  vector<int> heap;

  int get_min_child(int index) {
    /* find the smaller child of a node given by index */
    if (index < heap.size() - 2) {
      int left = left_child_index(index);
      int right = right_child_index(index);
      return (heap[left] < heap[right]) ? left : right;
    }
    else if (index < heap.size() - 1) {
      return left_child_index(index);
    }
    else throw invalid_argument("node has no children");
  }

  int parent_index(int index) {
    /* return index of parent node */
    if (index > 0) {
      return (index - 1) / 2;
    }
    else throw out_of_range("Trying to access root parent");
  }

  int child_count(int index) {
    /* return the number of children a given node has */
    if (2*index + 2 < heap.size()) return 2;
    else if (2*index + 1 < heap.size()) return 1;
    else return 0;
  }

  int left_child_index(int index) {
    int ind = 2*index + 1;
    if (ind < heap.size()) return ind;
    else throw out_of_range("Index out of range");
  }

  int right_child_index(int index) {
    int ind = 2*index + 2;
    if (ind < heap.size()) return ind;
    else throw out_of_range("Index out of range");
  }
};


texts:
We have a working implementation that is doing I/O operations, returning data from blobs in an async/await manner from Azure Blob Storage.

//Method1 is not async, this is what is called from the controller
public IEnumerable<Data> Method1()
{
    //Running the async method and returning the result from task
    return Task.Run(() => GetDataAsync()).Result;
}

private async Task<IEnumerable<Data>> GetDataAsync()
{
    //There are multiple blob address where the data is held. The code creates, in parallel multiple tasks for each address.
    //It returns tasks that will be run in Async pattern
    var tasks = multipleBlobAddress.AsParallel.Select(blobAddress =>{
            Task<IEnumerable<Data>> task = GetDataFromBlobsAsync(blobAddress);
            return task;
    });

    //Awaits all tasks to complete
    var completedTasks = await Task.WhenAll<IEnumerable<Data>>(tasks);
    //Selects all the tasks and returns them. Each tasks has data.
    return completedTasks.SelectMany(t => t);
}

private Task<IEnumerable<Data>> GetDataFromBlobsAsync(string address)
{
    //Opens the blob and reads from it
    using (var blobStream = blobService.OpenRead(address))
    {
        //Deserialises the data read from the blob
        data = service.DeserialiseData(blobStream);
    }

    return Task.FromResult<IEnumerable<Data>>(data);
}

We have understood that the best way to read from blobs is to follow the async/await pattern and not using the AsParallel method (other suggestions are most welcomed). I have the following questions:

By creating tasks in parallel and then waiting for all of them to complete, do we lose any performance?
What are the obvious areas where we got it wrong or we can improve and potentially increase the performance or make the code better to maintain/read?
Are we correctly following the async / await pattern?

If you need any extra information about the code, I will happily provide it and hope to make it clearer.


texts:
I created a program that picks a champion for a role on the game League of Legends using arrays and random numbers.

Is there a quicker and more efficient way of doing this?

There is one form that contains this:

namespace Random_Champ_Picker_V2
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    internal void button1_Click( object sender, EventArgs e )
    {

        arrays array = new arrays();
        if( radioButton1.Checked == true )
        {
            Random T = new Random();
            int t = T.Next( 0, 57 );
            string toop = (string) array.top.GetValue( t );
            textBox1.Text = toop;
        }
        else if( radioButton2.Checked == true )
        {
            Random T = new Random();
            int t = T.Next( 0, 38 );
            string toop = (string) array.jung.GetValue( t );
            textBox1.Text = toop;
        }
        else if( radioButton3.Checked == true )
        {
            Random T = new Random();
            int t = T.Next( 0, 41 );
            string toop = (string) array.mid.GetValue( t );
            textBox1.Text = toop;
        }
        else if( radioButton4.Checked == true )
        {
            Random T = new Random();
            int t = T.Next( 0, 15 );
            string toop = (string) array.marksmen.GetValue( t );
            textBox1.Text = toop;
        }
        else if( radioButton5.Checked == true )
        {
            Random T = new Random();
            int t = T.Next( 0, 18 );
            string toop = (string) array.supp.GetValue( t );
            textBox1.Text = toop;
        }

    }

Class that contains the arrays (I removed most champ names for this post not to be cluttered):

namespace Random_Champ_Picker_V2
{
internal class arrays
{
    internal string[] supp = new string[]    {"Taric","Thresh"};

    internal string[] marksmen = new string[]{"Ezreal","Ashe"};

    internal string[] top = new string[]{"Zac","Aatrox"};

    internal string[] jung = new string[]{"Amumu","Jarvan IV"};

    internal string[] mid = new string[]{"karma","ziggs"};
}
}


texts:
I did two simple functions in VBA (see below).

When a user calls TirNoPer360 in Excel he must select cashflows and dates (as range), then he will get a rate (through iterations according to the second function TirNoPer360).

Function Opt(Caja, Fecha As Range, tasa As Double)

Dim i As Integer
Dim sum As Double
Dim Initial As Date

Initial = Fecha(1, 1)

For i = 1 To Caja.Rows.Count
    sum = sum + Caja(i) / ((1 + tasa) ^ (Application.WorksheetFunction.Days360(Initial, Fecha(i)) / 360))
Next i

Opt = sum

End Function

======================

Function TirNoPer360(Cash, Dates As Range, rate As Double)
Dim tolerance  As Double
tolerance = 0.00001

For Iteration = 1 To 100
    If Opt(Cash, Dates, rate) > 0 And Opt(Cash, Dates, rate) > tolerance Then
        rate = rate + 0.0000001
    ElseIf Opt(Cash, Dates, rate) < 0 And Opt(Cash, Dates, rate) < tolerance * -1 Then
        rate = rate - 0.0000001
    Else
        rate = rate
    End If
    TirNoPer360 = rate
Next Iteration

End Function

When cashflows and dates increase I need more than 100 tries in order to get a good rate (approximated to four decimals) and time increases a lot. So, I would like to speed up my code.
I think I must improve the root finder algorithm, but I don't know how exactly I can do it.
Can anyone help me?

PD: I read Excel uses Newton's algorithm to find the root for a function.


texts:
So, as an exercise I wanted to write a dynamic array, like std::vector. I wanted to know if there are any things that could be done better or anything I did wrong. Thank you!

    template<typename T>
    class myVector {
    using size_type = size_t;
    public:
    void pop(void) {
      changeSize(--m_Used);
    }

    void pop(size_type index) {
      if (!(index < m_Size)) return;
      changeSize(m_Used -= index);
    }

    bool push(const T& obj) {
      if (m_Used == m_Size) {
        bool temp = changeSize(++m_Used);
        m_Buffer[m_Used - 1] = obj;
        return temp;
      }
      m_Buffer[m_Used++] = obj;
      return true;
    }

    inline size_type used(void) const { return m_Used; }
    inline size_type size(void) const { return m_Size; }

    T& operator[](size_type index){
      return m_Buffer[index];
    }

    const T& operator[](size_type index) const{
      return m_Buffer[index];
    }

    inline T* begin(void) { return m_Buffer; }
    inline T* end(void) { return begin() + m_Used; }
    inline const T* const begin(void) const { return m_Buffer; }
    inline const T* const end(void) const { return begin() + m_Used; }

  public:
    bool reserve(size_type _size) {
      if (m_Buffer and !(m_Size < _size)) return 1;
      return changeSize(_size);
    }

    myVector(void) {
      m_Buffer = (T*)malloc(sizeof(T));
      m_Used = 0;
      m_Size = 1;
    }

    myVector(const myVector<T>& other) {
      *this = other;
    }

    myVector<T>& operator=(const myVector<T>& rhs) {
      if(rhs.m_Buffer){
        m_Used = rhs.m_Used;
        m_Size = rhs.m_Size;
        free(m_Buffer);
        m_Buffer = (T*)malloc(sizeof(T) * m_Size);
        memcpy(m_Buffer,rhs.m_Buffer,sizeof(T) * m_Size);
      }
      return *this;
    }

    template<size_type N>
    myVector(const T (&inputArr)[N]) {
      *this = inputArr;
    }

    template<size_type N>
    myVector<T>& operator=(const T (&inputArr)[N]) {
      m_Size = N;
      m_Used = m_Size;
      m_Buffer = (T*)malloc(m_Size * sizeof(T));
      memcpy(m_Buffer,inputArr, N * sizeof(T));
      return *this;
    }

    myVector<T>& operator=(const std::initializer_list<T>& rhs) {
      m_Size = rhs.size();
      m_Used = m_Size;
      m_Buffer = (T*)malloc(m_Size * sizeof(T));
      memcpy(m_Buffer,rhs.begin(),m_Size * sizeof(T));
      return *this;
    }

    myVector(const std::initializer_list<T>& other) {
      *this = other;
    }

    ~myVector() {
      free(m_Buffer);
    }

    bool contains(const T& obj) const {
        return std::find(begin(),end(),obj) != end();
    }

  private:
    T* m_Buffer;
    size_type m_Used;
    size_type m_Size;

    bool changeSize(size_type _size) {
      T* newBuffer = (T*)realloc(m_Buffer, sizeof(T) * _size);
      if (newBuffer) {
        m_Buffer = newBuffer;
        m_Size = _size;
        return true;
      }
      return false;
    }
};


texts: Command-Line tool to find large files on a Linux system

texts:
Is the code pythonic and easy to read and understand? Is there a better way to exclude directories? Did I miss any bugs?

'''Find large files on a linux system.

:Example:
excludes = ['/proc', '/sys', '/dev', '/swapfile']
find_larg_files('/', n_results=20, excludes=excludes)
'''

import os
import operator
from itertools import islice
import fnmatch
import re
import argparse

def take(number, iterable):
    """Return first n items of the iterable as a list.

    :param number: `int` How many do you want to take.
    :param iterable: `iterable`
    :rtype: `list`
    """
    return list(islice(iterable, number))

def walk(fpath, **kwargs):
    ''' Traverse thru a directory tree.

    :param fpath: `int` The root file path
    :param excludes: `list` optional directories to exclude
    :rtype: `generator`
    '''
    kwargs.setdefault('excludes', [])
    excludes = kwargs.get('excludes')
    # transform glob patterns to regular expressions
    excludes = r'|'.join([fnmatch.translate(x) for x in excludes]) or r'$.'
    for root, dirs, files in os.walk(fpath, topdown=1):
        # exclude dirs
        if excludes:
            dirs[:] = [os.path.join(root, d) for d in dirs]
            dirs[:] = [d for d in dirs if not re.match(excludes, d)]
        for name in files:
            yield os.path.join(root, name)

def getsize(fpath):
    ''' Return the size of a file.
    Will return 0 if an OSError is raised.
    :param fpath: `str`
    '''
    try:
        return os.path.getsize(fpath)
    except OSError:
        return 0

def find_larg_files(fpath, n_results=10, **kwargs):
    ''' Recursively find the largest files in a directory.

    return n largest files in a directory tree.
    :param fpath: `str` where to start.
    :param n_results: `int` how many results to retrun.
    :param kwargs: This will be passed to walk.
    :rtype: `None` it prints the paths and sizes to the screen.
    '''
    results = {}
    for name in walk(fpath, **kwargs):
        results[name] = getsize(name)

    results = reversed(sorted(results.items(), key=operator.itemgetter(1)))
    for name, size in take(n_results, results):
        print name, size

def main():

    parser = argparse.ArgumentParser(description='Find large files')
    parser.add_argument('path', metavar='-p', type=str, help='The path to start crawling')
    parser.add_argument(
        '--results', metavar='-n', type=int,
        help='How many results to return the default is 10.',
        default=10
        )
    parser.add_argument(
        '--exclude', metavar='-e', type=list,
        help='Directoris to exclude in the search.',
        nargs='+', default=[]
        )

    args = parser.parse_args()
    find_larg_files(args.path, n_results=args.results, excludes=args.exclude)

if __name__ == '__main__':
    main()


texts:
Today I have dealt with logging in PowerShell as well as with the different streams and the pipeline. Unfortunately, none of these solutions really met my needs.

My requirements are:

I need to output information from PowerShell to a file log.
The file log has a predefined structure. So it's not enough to just redirect all streams to the file.
I want to use mainly standard PowerShell functions such as Write-Error, Write-Warning, Write-Verbose.
The overhead in the code through logging should be minimal.

I have developed the following idea now:

When calling a function from my script, all streams are piped to a logging function.
This function separates the debug, verbose, warning and error objects from the resulting object.
The resulting object is released back into the pipeline.

Here is my solution:

function Split-Streams {
    [CmdletBinding()]
    param(
        [Parameter(ValueFromPipeline)]
        $InputStream
    )
    process{
        switch($InputStream.GetType())
        {
            'System.Management.Automation.DebugRecord' {
                                                         # Do whatever you want, like formatting an writing to a file.
                                                         Write-Host $InputStream -ForegroundColor Gray
                                                       }
            'System.Management.Automation.ErrorRecord' {
                                                         Write-Host $InputStream -ForegroundColor Red
                                                         Write-Host ('Error function: {0}' -f $InputStream[0].InvocationInfo.MyCommand.Name) -ForegroundColor Red
                                                       }
            'System.Management.Automation.VerboseRecord' { Write-Host $InputStream -ForegroundColor Cyan }
            'System.Management.Automation.WarningRecord' { Write-Host $InputStream -ForegroundColor Yellow }
            default { return $InputStream }
        }
    }
}

function Write-Messages
{
    [CmdletBinding()]
    param()
    Write-Debug "Debug message"
    Write-Output "Output message"
    Write-Verbose "Verbose message"
    Write-Warning "Warning message"
    Write-Error "Error message"
}

$Test2 = Write-Messages -Verbose -Debug *>&1 | Split-Streams

Write-Host $Test2 -ForegroundColor White

So now my question:

Is there something wrong with my solution?
Have I missed any problems?


texts:
Task description:
Declare a function twoInThree(a: Set, b: Set, c: Set), which returns the set of all elements, which are contained in exactly two of the three given sets a, b, c.
My solution:
fun main(args: Array<String>) {
    var a = setOf<Int>(1, 2, 5)
    var b = setOf<Int>(2, 7, 0)
    var c = setOf<Int>(3, 5)

    val result = twoInThree(a, b, c)
    println(result) // [2, 5]
}

fun twoInThree(a: Set<Int>, b: Set<Int>, c: Set<Int>): MutableSet<Int> {
    var results = mutableSetOf<Int>()
    var intersectOfAll = a.intersect(b).intersect(c)

    val aIntersectB = a.intersect(b)
    val aIntersectC = a.intersect(c)
    val bIntersectC = b.intersect(c)

    results.addAll(aIntersectB)
    results.addAll(aIntersectC)
    results.addAll(bIntersectC)

    results.removeAll(intersectOfAll)

    return results
}

If got the same result as the instructor and tried it with other sets. It always returned the expected result. So, I guess my solution is formally correct.
But: Could the exercise become solved in a better way?


texts:
I am trying to implement topological sort. The idea is that I have a vector of pairs in which the first element is indegree and the second is a linked list. I tried a bunch of tests, they seem to work, but I am not really sure about my implementation. Is this really a topological sort? Can you please review my code and give some advice on how to improve it?

#include <iostream>
#include <list>
#include <vector>
#include <stack>

using namespace std;

class Graph {
public:
    Graph(int V) {
        this->V = V;
        adj.resize(V);
    }

    void addEdge(int from, int to) {
        adj[from].second.push_back(to);
    }

    void FillIndegrees() {
        for (int i = 0; i < adj.size(); ++i) {
            for (int v : adj[i].second) {
                adj[v].first++;
            }
        }
    }

    void PrintIndegrees() {
        for (int i = 0; i < adj.size(); ++i) {
            cout << adj[i].first << endl;
        }
    }

    void TopologicalSort() {

        FillIndegrees();

        stack<int> st;

        // find zero indegree and add it to a stack
        for (int i = 0; i < adj.size(); ++i) {
            if (adj[i].first == 0) {
                st.push(i);
            }
        }

        while (!st.empty()) {
            int idx = st.top();
            cout << idx << " ";
            st.pop();
            for (int v : adj[idx].second) {
                adj[v].first--;
                if (adj[v].first == 0) {
                    st.push(v);
                }
            }
        }

    }

private:
    int V;
    // indegree, list of edges
    vector<pair<int, list<int>>> adj;
};

int main() {

    Graph g(4);
    g.addEdge(0, 1);
    g.addEdge(0, 2);
    g.addEdge(1, 3);
    g.addEdge(2, 3);

    // Graph g(6);
    // g.addEdge(5, 2);
    // g.addEdge(5, 0);
    // g.addEdge(4, 0);
    // g.addEdge(4, 1);
    // g.addEdge(2, 3);
    // g.addEdge(3, 1);

    g.TopologicalSort();

    return 0;
}


texts: Lazy Pirate Request Response pattern using zeromq and C#/.NET bindings

texts:
I'm a zeromq newb and have implemented the REQ/RES Lazy Pirate pattern with C#. It's essentially a port from the C example given in the documentation. It's harnessed by tests, and seems to be work to my expectations. I'm interested to know if I'm understanding the pattern correctly, or if I can improve the API. If anyone knows of a pre-existing solution, I'd love to know too. Any advice would be great.

using System;
using System.Text;
using ZMQ;

namespace zeromq.net {
    public class LazyPirateClient : ReqRes {
        private readonly string _address;
        private readonly long _timeOut;
        private readonly int _retries;
        private bool _responseReceived;
        private int _attempt;

        public LazyPirateClient(string address, long timeOut, int retries) {
            _address = address;
            _timeOut = timeOut;
            _retries = retries;
        }

        public override void Send(Func<byte[]> byteProvider) {
            _responseReceived = false;
            using (var context = new Context(1)) {
                _attempt = 0;
                do {
                    using (var requester = context.Socket(SocketType.REQ)) {
                        _attempt++;
                        requester.Connect(_address);
                        requester.Send(byteProvider(), SendRecvOpt.NOBLOCK);
                        var item = requester.CreatePollItem(IOMultiPlex.POLLIN);
                        item.PollInHandler += item_PollInHandler;
                        context.Poll(new[] { item }, _timeOut);
                        requester.Linger = 0;
                    }
                } while (_attempt < _retries && !_responseReceived);

                if (!_responseReceived)
                     throw new PermenantFailException(_attempt);
            }
        }

        private void item_PollInHandler(Socket socket, IOMultiPlex revents) {
            _responseReceived = true;
            var bytes = socket.Recv(SendRecvOpt.NOBLOCK);
            OnReceived(new ResponseReceivedEventArgs(bytes, _attempt));
        }
    }

     public abstract class ReqRes {
        public abstract void Send(Func<byte[]> byteProvider);
        public delegate void ResponseReceived(object sender, ResponseReceivedEventArgs e);
        public event ResponseReceived ReceivedHandler;

        public void OnReceived(ResponseReceivedEventArgs e) {
            var handler = ReceivedHandler;
            if (handler != null) handler(this, e);
        }
     }


texts: Get all recipes from database with the cheapest ingredients

texts:
I have the following query which tries to get all the cheapest products linked to my recipes and it takes 10 seconds to return from the database:

SELECT PRODUCTOS.id, PRODUCTOS.titulo, CONCAT (INGREDIENTES.titulo," ", CONCAT(RECETA_INGREDIENTE.cantidad * $pers, "", PRODUCTOS.medida)) as ingrediente , precio, precio_medio , RECETA_INGREDIENTE.cantidad as cantidad_receta, PRODUCTOS.Volumen as cantidad_producto, PRODUCTOS.imagen, RECETA_INGREDIENTE.id_ingrediente as idingrediente, PRODUCTOS.precio_medio as precio_medio, PRODUCTOS.medida
FROM PRODUCTOS
INNER JOIN INGREDIENTES ON INGREDIENTES.id = PRODUCTOS.ingrediente
INNER JOIN RECETA_INGREDIENTE ON INGREDIENTES.id = RECETA_INGREDIENTE.id_ingrediente
WHERE precio = (SELECT MIN(precio) FROM PRODUCTOS AS f WHERE f.ingrediente = PRODUCTOS.ingrediente) AND RECETA_INGREDIENTE.id_receta = $id;

I found the SELECT MIN(precio)... within the WHERE case is making the query take too long. I found out the price is a float column which I believe is not the most suitable data type for a price. This is taking products with the cheapest price in the PRODUCTS table and I was thinking about replace the FROM PRODUCTS part with something more like this:

select *,MIN(precio) from PRODUCTOS where ingrediente is not null group by titulo;

But I still couldn't get it working. Any advice?

The output is all the ingredients for a particular recipe with the cheapest products.

Table definition:

/*Table structure for table `INGREDIENTES` */

DROP TABLE IF EXISTS `INGREDIENTES`;

CREATE TABLE `INGREDIENTES` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `titulo` varchar(255) DEFAULT NULL,
  `slug` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=65 DEFAULT CHARSET=utf8;

/*Table structure for table `PRODUCTOS` */

DROP TABLE IF EXISTS `PRODUCTOS`;

CREATE TABLE `PRODUCTOS` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `titulo` varchar(255) DEFAULT NULL,
  `categoria` varchar(255) DEFAULT NULL,
  `precio` float DEFAULT NULL,
  `precio_medio` float DEFAULT NULL,
  `volumen` int(5) DEFAULT '0',
  `promo` varchar(255) DEFAULT NULL,
  `url` varchar(255) DEFAULT NULL,
  `ingrediente` int(11) DEFAULT NULL,
  `ref` int(11) DEFAULT NULL,
  `imagen` varchar(255) DEFAULT NULL,
  `medida` varchar(4) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=321 DEFAULT CHARSET=utf8;

/*Table structure for table `RECETAS` */

DROP TABLE IF EXISTS `RECETAS`;

CREATE TABLE `RECETAS` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `titulo` varchar(255) DEFAULT NULL,
  `cal` varchar(50) DEFAULT NULL,
  `descripcion` text,
  `imagen` varchar(255) DEFAULT NULL,
  `orden` int(11) DEFAULT NULL,
  `visible` tinyint(1) DEFAULT '0',
  `TYPE` varchar(255) DEFAULT NULL,
  `id_tipo` int(1) DEFAULT NULL,
  `id_dificultad` int(1) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=16 DEFAULT CHARSET=utf8;

/*Table structure for table `RECETA_INGREDIENTE` */

DROP TABLE IF EXISTS `RECETA_INGREDIENTE`;

CREATE TABLE `RECETA_INGREDIENTE` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `id_ingrediente` int(11) DEFAULT NULL,
  `cantidad` int(11) DEFAULT NULL,
  `orden` int(11) DEFAULT NULL,
  `id_receta` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=75 DEFAULT CHARSET=utf8;


texts:
I have just started Haskell, and I want to check if my code is following the spirit of the language.

  By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

fibonacci :: [Int]
fibonacci = 1 : 1 : (next 1 1)
    where
    next x y = sxy : (next y sxy)
        where
        sxy = x + y

main = do
    putStrLn $ show $ sum $ filter odd $ takeWhile (< 4000000) fibonacci


texts:
I am trying to implement message encryption/decryption with password in java. Here is the code I'm using:
import java.security.MessageDigest;
import java.security.spec.InvalidKeySpecException;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;

public class Cryptography {

  public static final int SECRET_KEY_ITERATIONS = 45928;
  public static final int SALT_ITERATIONS = 11879;
  public static final int IV_ITERATIONS = 13275;
  public static final int KEY_LENGTH = 256;

  private static Cipher cipher;
  private static MessageDigest sha256;
  private static SecretKeyFactory secretKeyFactory;

  static {
    try {
      cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
      sha256 = MessageDigest.getInstance("SHA-256");
      secretKeyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  public static String encryptText(String password, String plaintext) throws Exception {
    byte[] passwordBytes = password.getBytes();
    SecretKey secretKey = getKeyFromPassword(password, getSaltFromPassword(passwordBytes));
    IvParameterSpec ivParameterSpec = getIvFromPassword(passwordBytes);
    cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivParameterSpec);
    return Base64.getEncoder().encodeToString(cipher.doFinal(plaintext.getBytes()));
  }

  public static String decryptText(String password, String ciphertext) throws Exception {
    byte[] passwordBytes = password.getBytes();
    SecretKey secretKey = getKeyFromPassword(password, getSaltFromPassword(passwordBytes));
    IvParameterSpec ivParameterSpec = getIvFromPassword(passwordBytes);
    cipher.init(Cipher.DECRYPT_MODE, secretKey, ivParameterSpec);
    return new String(cipher.doFinal(Base64.getDecoder().decode(ciphertext)));
  }

  private static SecretKey getKeyFromPassword(String password, byte[] salt)
      throws InvalidKeySpecException {
    PBEKeySpec spec = new PBEKeySpec(password.toCharArray(), salt, SECRET_KEY_ITERATIONS, KEY_LENGTH);
    byte[] bytes = secretKeyFactory.generateSecret(spec).getEncoded();
    return new SecretKeySpec(bytes, "AES");
  }

  private static byte[] getSaltFromPassword(byte[] passwordByteArray) {
    byte[] bytes = sha256.digest(passwordByteArray);
    for (int i = 0; i < SALT_ITERATIONS; i++) {
      bytes = sha256.digest(bytes);
    }
    return bytes;
  }

  private static IvParameterSpec getIvFromPassword(byte[] passwordByteArray) {
    byte[] bytes = sha256.digest(passwordByteArray);
    for (int i = 0; i < IV_ITERATIONS; i++) {
      bytes = sha256.digest(bytes);
    }
    byte[] ivBuffer = new byte[16];
    System.arraycopy(bytes, 0, ivBuffer, 0, 16);
    return new IvParameterSpec(ivBuffer);
  }
}

Is this a secure way to do encryption/decryption, or does it have serious issues?


texts: Sorting an array of numbers by descending frequency

texts:
Somebody asked me to create a code that orders unique numbers of an array according to their frequency, ie:

{1,3,3,4,4,4,4,4,2,2,5,5,5,5}

to

{4,5,3,2,1}

I'm a beginner and only started learning C last week so my code probably isn't optimal. I managed to get it in just over 100 lines without worrying too much about space. I haven't messed with memory allocation yet but I should start looking into it.

Any tips or feedback?

#include <stdio.h>
#include <string.h>

void CalculateFrequency(int numbers[], int frequency[]) //Populates an array with the frequency of numbers in another
{
    int hasSorted = 0;
    do
    {
        hasSorted = 0;
        for(int currentInt=0; currentInt<10; currentInt++)
        {
            for(int i=0; i<10; i++)
            {
                if(numbers[i] == currentInt)
                {
                    frequency[currentInt]++;
                    hasSorted = 1;
                }
            }
        }
        if(hasSorted == 0)
        {
            break;
        }
    }while(hasSorted == 0);
}
void SortByFrequency(int numbers[], int frequency[])    //Sorts an array according to the frequency of the numbers
{
    int hasSorted = 0;
    int temp = 0;
    do
    {
        hasSorted = 0;
        for(int i=0; i<10; i++)
        {
            for(int i=0; i<10; i++)
            {
                if(frequency[numbers[i]] < frequency[numbers[i+1]])
                {
                    temp = numbers[i+1];
                    numbers[i+1] = numbers[i];
                    numbers[i] = temp;
                    hasSorted = 1;
                }
            }
        }
        if(hasSorted == 0)
        {
            break;
        }
    }while(hasSorted == 0);
}
int CountUniqueNumbers(int array[], int arrayLength)    //Counts unique numbers in an array
{
    int count = 1; //At least 1 number
    for(int i=0; i<arrayLength-1; i++)
    {
        if(array[i] != array[i+1])
        {
            count++;
        }
    }
    return count;
}
int PopulateArrayByFrequencyAndReturnLength(int numbers[], int sortedByFrequency[])
{
    int k = 0;
    sortedByFrequency[0] = numbers[0];
    for(int i=0; i<10; i++)
    {
        if(numbers[i] != numbers[i+1])
        {
            sortedByFrequency[k] = numbers[i];
            k++;
        }
    }
    return k;
}
int counter;

int main(void)
{
    int numbers[10] = {1,2,2,2,5,7,8,8,8,8};
    int frequency[10] = {0,0,0,0,0,0,0,0,0,0};
    int sortedByFrequency[10] = {0,0,0,0,0,0,0,0,0,0};
    int sortedByFrequencyTrueLength = 0;
    int differentNumbers = 1;   /*The array must have at least 1 number*/
    int sizeofNumbersArray = 10;
    int uniqueNumbersInArray = 0;
    int i = 0;
    /*print the numbers*/
    printf("Numbers:\t");
    for(int i=0; i<10; i++)
    {
        printf("%d ", numbers[i]);
    }
    puts("");
    /*Perform functions*/
    CalculateFrequency(numbers, frequency);
    SortByFrequency(numbers, frequency);
    /*Get amount of unique numbers in the array*/
    uniqueNumbersInArray = CountUniqueNumbers(numbers, sizeofNumbersArray);
    /*Poupulate the unique number frequency array and get the true length*/
    sortedByFrequencyTrueLength = PopulateArrayByFrequencyAndReturnLength(numbers, sortedByFrequency);
    //Print unique number frequency array
    printf("Numbers sorted by frequency:\t");
    for(i=0; i<sortedByFrequencyTrueLength; i++)
    {
        printf("%d ", sortedByFrequency[i]);
    }
    puts("");

    return 0;
}


texts:
I have this old project I wrote years ago and it's all classes and methods all over the place. I am trying to learn/understand how I can apply a more OOP principle. It is very large and can't paste all the code here. Instead I will demonstrate what I have as a basic.

Checkup.cs

public class CheckUp
{
    //General information
    public string CliniciansName { get; set; }
    public string EmploymentStatus { get; set; }
    public DateTime DateOfCheck { get; set; }
    public string CheckUpType { get; set; }

    public ColourVision ColourVisionObject { get; set; }
    ///lots of other checkups like 45 and growing and forever changin
}

ColourVision.cs

public class ColourVision
{
    public int ColourVisionType { get; set; }
    public int OutcomeID { get; set; }
    public DateTime RecallDate { get; set; }
    public string Recommendations { get; set; }

    //Contains a few horrible methods to parse form other formats,
    // CSV datatables, XML, but needed. Here is one from a DataTable
    public Boolean ColourVision Load(System.Data.DataTable dt){

        Boolean isLoaded = false;
        System.Data.DataRow row = DataRow;
        try
        {
            ColourVisionType = row["ColourVision"].ToString();
            FFTOutcomeID = Convert.ToInt32(import.getOutcomeValue(row["ColourVisionOutcome"].ToString()));
            RecallDate = (row["ColourVisionRecallDate"] != DBNull.Value) ? (DateTime)row["ColourVisionRecallDate"] : DateTime.MinValue;
            Recommendations = (row["ColourVisionRecommendations"] != DBNull.Value) ? (string)row["ColourVisionRecommendations"] : "";
            isLoaded = true;
        }
        catch (Exception ex)
        {
            isLoaded = false;
        }
        return isLoaded;

     }

    //And this takes the data row and populates it self
    //by reference from healtchcheck, where there
    //are thousands of checks and lines of code
    //and this is what I am trying to streamline
    public void Update(ref Data.CheckUp checkUp)
}

The database is one table with over 400 columns and contains at least the General Info defined in CheckUp. It may or may not contain 0 more fields up to all the fields.

I am racking up my brain on how to create a Checkup Class, that can load the basic data form the data table, or 0 or more checkup objects, without manually calling methods like this for each kind of import logic.

if (ColorurVision.Load(ref dataRowFromSomethingElse) == true ) { CheckUp.ColourVision == null }

I am reading about Inheritance and the examples are clear but I just cannot for the life of me figure out how to do that here. I have a feeling this is perfect project for that. Maybe I am just looking at it wrong. Should I be rather inheriting from something else, like System.Data.DataTable and returning ColourVision, or CheckUp?

This is really a high level code review question based more on programming principles.


texts:
I have these two methods on a class that differ only in one method call. Obviously, this is very un-DRY, especially as both use the same formula. Could anyone give me advice on how to tidy this up?

public class PlayerCharacter {
    int level;
    public int getAttack() {
        int attack = 1 + level;
        for(Equipment e : equipments)
           attack += e.getAttack();
        return attack * Math.sqrt(level);
    }
    public int getDefense() {
        int attack = 1 + level;
        for(Equipment e : equipments)
           attack += e.getDefense();
        return attack * Math.sqrt(level);
    }
}

I thought of refactoring the loop to an external method but the different method calls has me stumped.


texts: Byte array to floating point such as FPE2 in Java

texts:
Apple's System Management Controller uses FPE2 and SP78 as floating-point formats.

While writing a Java library that that interfaces with the SMC, I ported someone's C function to convert read a FPE2-formatted byte array as a float.

public static float strtof(byte[] bytes, int size, int e) {
    int total = 0;
    // Add up bits to left of fractional bits
    for (int i = 0; i < size; i++) {
        if (i == (size - 1))
            total += (bytes[i] & 0xff) >> e;
        else
            total += (bytes[i] & 0xff) << (size - 1 - i) * (8 - e);
    }
    // Mask fractional bits and divide
    return total + (bytes[size - 1] & (1 << e) - 1) / (float) (1 << e);
}

The bytes and size parameters come from reading a structure in Apple's SMC interface.  The array is a byte[32] value in a structure, where a second part of the structure states how many of the elements of the array are significant.  In the use case, getting fan speed, bytes[0] and bytes[1] will be populated with data (the other 30 bytes are ignored) and size will have a value of 2.

In the given code, the value of e represents how many rightmost bits out of the size bytes are for the fractional part.  If e is 2 (such as for FPE2), then the final 2 bits can have values 0, 1, 2, or 3 representing the fractions 0.0, 0.25, 0.5, and 0.75.  The remaining leading bits are interpreted as the integer part.

Example input:

bytes = { 0x00, 0x05, 0x00, 0x00, ... } // First 2 bytes binary 101
size = 2
e = 2

Example output: 1.25 // Integer portion is 1, fraction is 1/4.

Did I do it right (assuming arguments are already validated: e will never be more than 8, and size will never be more than 4)?  Points of concern are order of operation, what happens bitwise when I promote a byte to an int and then shift it.

While this function converts an FPE2 format number, I'm trying to make it a bit more general.  A similar format, SP78, is used for temperature.  The rightmost 8 bits (divided by 256) are the fractional portion, the left 8 bits are a signed byte.  (This method is not intended to handle the signed calculation but this is given as a reference.)


texts: C++ binary search tree, not using recursion

texts:
I made binary search tree using classes. I would like to know if I could do something better or maybe there is something wrong with my code. I decided not to use recursion. I would be very thankful for any suggestions.

#include "stdafx.h"
#include <iostream>
#include <string>

using namespace std;

class Bst
{
private:
    struct BstNode
    {
        int data;
        BstNode* left;
        BstNode* right;
    };
public:
    Bst()
    {
        root = nullptr;
    }
    BstNode* insert(int data)
    {
        BstNode* newNode = new BstNode();
        newNode->data = data;
        newNode->left = nullptr;
        newNode->right = nullptr;
        return newNode;
    }
    bool add(int number)
    {
        if (root == nullptr)
        {
            root = insert(number);
        }
        else
        {
            BstNode* tmp_root = root;
            while (tmp_root != nullptr)
            {
                if (number <= tmp_root->data)
                {
                    if (tmp_root->left == nullptr)
                    {
                        tmp_root->left = insert(number);
                        return true;
                    }
                    else
                    {
                        tmp_root = tmp_root->left;
                    }
                }
                else
                {
                    if (tmp_root->right == nullptr)
                    {
                        tmp_root->right = insert(number);
                        return true;
                    }
                    else
                    {
                        tmp_root = tmp_root->right;
                    }

                }
            }
        }
        return false;
    }
    bool search(int number)
    {
        BstNode* tmp_root = root;
        while (tmp_root != nullptr)
        {
            if (number == tmp_root->data) return true;
            if (number < tmp_root->data)
            {
                tmp_root = tmp_root->left;
                continue;
            }
            if (number > tmp_root->data)
            {
                tmp_root = tmp_root->right;
            }
        }
        return false;
    }

private:
    BstNode* root;
};

int main()
{
    Bst tree;
    tree.add(10);
    tree.add(15);
    tree.add(2);
    tree.add(4);
    tree.add(7);
    for (int i = 1; i <= 20; i++)
    {
        string exist = tree.search(i) ? "YES" : "NO";
        cout << i << ": " << exist << endl;
    }
    system("pause");
    return 0;
}


texts:
I came up with the following solution to find the number of prime numbers from 1 to n.

I'm wondering if there is a more optimal way.

var max = 10;
var compositeNumbers = {};

mainLoop:
for (var i=2; i<= max;i++)
{
  smallLoop:
   for (var j=2; j<=Math.ceil(Math.sqrt(i));j++)
   {
      if (i % j == 0)
      {
          compositeNumbers[i]=1;
          continue mainLoop;
      }
   }

}

console.log(max - Object.keys(compositeNumbers).length);


texts: Is there a better or more concise way to do this?

texts:
My goal was to make a list dynamically list itself into two columns, no matter the length of the list. I know this is possible by just floating the li nodes, but I wanted to keep the li nodes in the same vertical order. I would really like to hear from people who know more about JavaScript and jQuery than I do if this code looks good or if there is a better or more concise method for implementing this sort of thing.

Demo: http://jsfiddle.net/mkimitch/ZEL5x/

HTML:

Australia

Brazil

Canada

Chile

China

France

India

Italy

Malaysia

Norway

Russia

United Kingdom

United States

JavaScript:

var colLength = $('.columned li').length;
var colHeight = $('.columned').height();
var liHeight = $('.columned li').height();
if ($('.columned li').length % 2 != 0) {
    var half = (Math.round(colHeight / 2)) + liHeight / 2;
} else {
    var half = Math.round(colHeight / 2);
}
var firstrow = Math.ceil(colLength / 2);
var secondrow = firstrow + 1;
$('.columned li:nth-child(-n+' + firstrow + ')').addClass('column1');
$('.columned li:nth-child(n+' + secondrow + ')').addClass('column2');
$('.columned li:nth-child(' + secondrow + ')').css('margin-top', -half);


texts:
All the test cases pass except one of the test case which runs > 10 seconds. What can I do to make my solution faster?

def in_row(grid,i,k)
    grid[i].include? k
end

def in_col(grid,j,k)
    0.upto(8) do |i|
      return true if grid[i][j] == k
    end
    false
end

def in_grid(grid,i,j,k)
    x,y =0,0
    x = 3 if i > 2
    x = 6 if i > 5
    y = 3 if j > 2
    y = 6 if j > 5
    x.upto(x+2) do |xx|
      y.upto(y+2) do |yy|
        return true if grid[xx][yy] == k
      end
    end
    return false
end

def find_unassigned_location(grid)
  grid.each_with_index do |rows,i|
    rows.each_with_index do |cols,j|
      return [i,j] if cols == 0
    end
  end
  false
end
def sudoku_solve grid
    # If there is no unassigned location, we are done
    cell = find_unassigned_location(grid)
    return [true,grid] unless cell # No unassigned cell remaining
    i,j = cell[0],cell[1]
    1.upto(9) do |k|
      next if in_row(grid,i,k) || in_col(grid,j,k) || in_grid(grid,i,j,k)
      grid[i][j] = k
      return [true,grid] if sudoku_solve(grid)[0] == true  # Recursively solve
      grid[i][j] = 0 # Unassign location if recursive solution returns false
    end
    return [false,grid]
end
def print_grid (grid)
    grid.each do |rows|
      rows.each do |cols|
        print "#{cols} "
      end
      puts ''
    end
end

board = []
(0...9).each do |i|
  board << gets.split.map {|num| num.to_i}
end
solution = sudoku_solve(board)
print_grid(solution[1]) if solution[0]

# -- input
4 0 0 0 0 6 0 0 0
0 6 0 0 0 0 0 0 9
0 0 0 0 0 0 0 0 0
0 0 2 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 3 0 6 0 0 2 0
1 0 0 0 0 0 9 0 0
8 0 0 0 0 5 0 0 0
0 0 0 0 0 0 0 0 5


texts: Factory to augment JS classes with validation methods

texts:
I have some validation classes. To keep things smooth, I create a single class that has those validation classes inside of it. That class will be a singleton, and gets injected into my other classes.

The validation classes have a method that needs to be executed by the depending object. So lets make this clear:

The Matrix class

Gets a validate class injected

and calls validate.validateMatrix().

That method, validateMatrix(), is actually in another class, that validate imports and creates a reference to. The validateMatrix class, for example, looks like this:

export class validateMatrix {
    validateMatrix(props){
       ...
    }
}

The validateclass has a generator for those classes that it needs, and all the validation classes have a method with the exact same name as the class name. That way, I can request the class name and call out to the validate method. That class looks like this:

import {validateString} from './validate/validateString';
import {validateSlider} from './validate/validateSlider';
import {validateCheckbox} from './validate/validateCheckbox';
import {validateRadio} from './validate/validateRadio';
import {validateDatetime} from './validate/validateDatetime';
import {validateMatrix} from './validate/validateMatrix';

export class validate {

    // this is just the library containing all the validators, for easy import.

    constructor(){
        this.classGenerator(
            validateString,
            validateSlider,
            validateCheckbox,
            validateRadio,
            validateMatrix,
            validateDatetime
        );
    }

    classGenerator(...classes){
        // pass in a class with the same method name as class name
        // and that function will be referred from here
        // e.g. this.validateMatrix()

        classes.forEach( (theClass) => {
            let classObj = new theClass();
            this[classObj.constructor.name] = classObj[classObj.constructor.name];
        });
    }
}

Usage:

validate() {
    this.validator.validateMatrix(this.question.properties)
        .then(this.branching.branch());
}

Is this a good way to create a factory method to generate those methods, and keep them hidden in other classes?


texts: Device-dependent image descriptor fields

texts:
In a Java class that belongs in a library, I have a field size that indicates size of image. It must be int, but some values are depending to devices, so other developers can set  various types for it:

thumbnail (value depends on device)
real size (value depends on device)
custom (arbitrary integer)

I want to restrict other developers (that use this library) to set value of size with one option from set of specific and meaningful options.My purpose is to show list of legal options to developer and also type safety, like Enum. But I think it is impossible to do that only by enum, so I create an interface and some classes:

public interface SizeMode {
}

public enum DevicePreDefinedImageSizeMode implements SizeMode {
    THUMBNAIL, REAL_SIZE
}

public enum CustomImageSizeMode implements SizeMode {
    CUSTOM_SIZE
}

public abstract class Size {

    private final SizeMode mode;

    public SizeMode getMode() {
        return mode;
    }

    public abstract int getDownSampleFactor();

    protected Size(SizeMode mode) {
        this.mode = mode;
    }
}

public class DevicePreDefinedImageSize extends Size {

    public DevicePreDefinedImageSize(DevicePreDefinedImageSizeMode mode) {
        super(mode);
    }

    @Override
    public int getDownSampleFactor() {
        throw new UnknownError("????");
    }

}

public class CustomImageSize extends Size {
    private final int downSampleFactor;

    private CustomImageSize(CustomImageSizeMode mode, int downSampleFactor) {
        super(mode);
        this.downSampleFactor = downSampleFactor;
    }

    @Override
    public int getDownSampleFactor() {
        return downSampleFactor;
    }

}

Now I can declare field size of type Size class and other developers are restricted to use one of sub classes of Size and initialize them with THUMBNAIL, REAL_SIZE or CUSTOM_SIZE.

But is there a better approach to achieve my purpose?


texts:
I have written a class which I will use as a base class, allowing other classes to extend this class.

How can I improve this? Am I breaking any conventions or styling?

import requests
import feedparser
from BeautifulSoup import BeautifulSoup

class BaseCrawler(object):
    ''' Base Class will be extended by other classes'''

    def __init__(self, url):
        self.url = url

    def test(self):
        return self.url

    def get_feed(self):
        feed = feedparser.parse(self.url)
        return feed

    def post_request(self):
        res = requests.post(self.url, self.data)
        return res

    def get_request(self):
        res = requests.get(self.url)
        self.raw = res.content
        return self.raw

    def build_entity(self):
        raise NotImplementedError("Subclasses should implement this!")

    def process(self):
        return NotImplementedError("Subclasses should implement this!")

    def build_query(self):
        return NotImplementedError("Subclasses should implement this!")


texts:
I just learned about Maybe in Haskell, so I decided to try to use it with a binary search.

Here's the function:

binarySearch :: (Ord a, Int b) => [a] -> a -> b -> b -> Maybe b

binarySearch l e beg last
 | lookat < e = (binarySearch l e i last)
 | lookat > e = (binarySearch l e beg i)
 | lookat == e = Just i
 | otherwise = Nothing
 where i = floor ((beg+last)/2)
       lookat = l !! i

l is a list, e is the element of interest, beg is the start of
the section of interest and end is the end of said section. The error I am getting is:

BinarySearch.hs:1:25:
    `Int' is applied to too many type arguments
    In the type signature for `binarySearch':
      binarySearch :: (Ord a, Int b) => [a] -> a -> b -> b -> Maybe b

I have tried a few other things including:

binarySearch :: Ord a => [a] -> a -> Int -> Int -> Maybe b

Yielding the error:

BinarySearch.hs:6:23:
    Could not deduce (b ~ Int)
    from the context (Ord a)
      bound by the type signature for
                 binarySearch :: Ord a => [a] -> a -> Int -> Int -> Maybe b
      at BinarySearch.hs:(3,1)-(9,22)
      `b' is a rigid type variable bound by
          the type signature for
            binarySearch :: Ord a => [a] -> a -> Int -> Int -> Maybe b
          at BinarySearch.hs:3:1
    In the first argument of `Just', namely `i'
    In the expression: Just i
    In an equation for `binarySearch':
        binarySearch l e beg last
          | lookat < e = (binarySearch l e i last)
          | lookat > e = (binarySearch l e beg i)
          | lookat == e = Just i
          | otherwise = Nothing
          where
              i = floor ((beg + last) / 2)
              lookat = l !! i

I am not sure what I am doing wrong. Any corrections or comments on style or solution would be highly appreciated.


texts: Simple object oriented design for a patient system

texts:
I want to model this scenario in object oriented language:

A hospital has number of patients
A patient can have zero or more medical conditions
A medical condition is identified by name and date

Please review my code and tell me:

What can I do to incorporate object oriented fundamentals like reusability and extensibility?
Do I need to implement an equals method in the MedicalCondition class?
Do I need to initialize all the instance variables in constructor?

import java.util.Date;
import java.util.*;
import java.text.*;
class Patient
{
    private String name;
    private String streetAdress1;
    private String phoneNumber;
    private String streetAdress2;
    private String zipCode; //I really dont need to preform any numerical operations.
    private List<MedicalCondition> mcList;

    public Patient(String name) //Public for constructor.
    {
        this.name = name;
        mcList = new ArrayList<MedicalCondition>();
    }

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

    public String getName()
    {
        return name;
    }

    //All setter and getters

    public void addMedicalCondition(MedicalCondition mc)
    {
        mcList.add(mc);
    }

    public void deleteMedicalCondition(MedicalCondition mc)
    {
        mcList.remove(mc);
    }

    public List<MedicalCondition> getMedicalConditions()
    {
        return mcList;
    }

    public String toString(){
        return name;
    }
 }

class MedicalCondition
{
      private String nameOfCondition;
      Date dateOfReport;

      public MedicalCondition(String nameOfCondition,Date dateOfReport)
      {
          this.nameOfCondition = nameOfCondition;
          this.dateOfReport = dateOfReport;
      }

      public String toString()
      {
          return nameOfCondition;
      }
 }

 public class HelloWorld{

     public static void main(String args[]) throws ParseException{
        Patient p1 = new Patient("Mike");

        DateFormat format = new SimpleDateFormat("mm/dd/yyyy");
        MedicalCondition mc1 = new MedicalCondition("Diabetes",format.parse("03/23/2000"));
        p1.addMedicalCondition(mc1);

        System.out.println(p1);
        for(MedicalCondition mc : p1.getMedicalConditions())
        {
            System.out.println(mc);
        }

        p1.deleteMedicalCondition(mc1); //Delete the condition

         System.out.println(p1);
        for(MedicalCondition mc : p1.getMedicalConditions())
        {
            System.out.println(mc);
        }
     }
}


texts: Code to find the proper index comparing 3 values for max one

texts:
I have an algorithm and the idea is to move over an array choosing as index the index of the neighboring cell that has the max value.
I.e.

if array[i + 1][j + 1] has the largest value among the 3 then move there.

I have 2 versions of this, but I think it can be cleaner.

version 1:

int maxI = i + 1;
int maxJ = j + 1;
if(array[i + 1][j] > array[maxI][maxJ]){
    maxI = i + 1;
    maxJ = j;
}
if(array[i][j + 1] > array[maxI][maxJ]){
    maxI = i;
    maxJ = j + 1;
}
i = maxI;
j = maxJ;

version 2:

if(LCS[i + 1][j + 1] > LCS[i][j + 1] && LCS[i + 1][j + 1] > LCS[i + 1][j]){
    i++;
    j++;
}
else{
    if(LCS[i][j + 1] > LCS[i + 1][j]){
        j++;
    }
    else{i++;}
}

Both versions occur in a while loop which I omitted for clarity.
How can these versions become better?


texts:
The .proto file is as below:

syntax = "proto3";

package bamboo;

// -----------------Cart service-----------------

service CartService {
    rpc AddItem(AddItemRequest) returns (Empty) {}
    rpc GetCart(GetCartRequest) returns (Cart) {}
    rpc EmptyCart(EmptyCartRequest) returns (Empty) {}
}

message CartItem {
    string product_id = 1;
    int32  quantity = 2;
}

message AddItemRequest {
    string user_id = 1;
    CartItem item = 2;
}

message EmptyCartRequest {
    string user_id = 1;
}

message GetCartRequest {
    string user_id = 1;
}

message Cart {
    string user_id = 1;
    repeated CartItem items = 2;
}

message Empty {}

And I have a Cart service on gRPC that is as simple as below:

from grpczoo import bamboo_pb2_grpc, bamboo_pb2
from concurrent import futures
import grpc
import time

class CartService(bamboo_pb2_grpc.CartServiceServicer):
    def AddItem(self, request, context):
        print(request.user_id, request.item)
        return bamboo_pb2.Empty()

if __name__ == "__main__":
    channel = grpc.insecure_channel('127.0.0.1')
    cart_stub = bamboo_pb2_grpc.CartServiceStub(channel)

    # create gRPC server
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))

    # add class to gRPC server
    service = CartService()
    bamboo_pb2_grpc.add_CartServiceServicer_to_server(service, server)

    # start server
    server.add_insecure_port('[::]:9000')
    server.start()

    # keep alive
    try:
        while True:
            time.sleep(10000)
    except KeyboardInterrupt:
            server.stop(0)

Let's assume that starting a service like above seems good when you have 40 services (We can create a base class for starting a service)

The most annoying part of the system is where I have to initiate a client when I need to send a RPC call to a service (here cart service):

import grpc

# set up server stub
from grpczoo import bamboo_pb2_grpc, bamboo_pb2

channel = grpc.insecure_channel('localhost:9000')
stub = bamboo_pb2_grpc.CartServiceStub(channel)
# form request
request = bamboo_pb2.AddItemRequest(user_id="123", item={'product_id': '21', 'quantity': 2})

# make call to server
response = stub.AddItem(request)
print(response)

As you can see for a simple RPC call like above I have to open channel to that service and form a request and then call the remote method AddItem. In a real world micro-service project I have to call at least 5 different methods and for each I have to create a channel and for the request and so on.

The question is how should I manage RPC calls to different methods when project gets bigger and I have 20 to 50 different services? The above code does not seems maintainable at all. How do you handle such cases?


texts: Find next occurring Friday (or any dayOfWeek)

texts:
Given a particular Date,  want to find the next occurring Friday.  I solved it using the below code.  Various tested scenarios work good for me.

Are there any boundary conditions the code might break?
Can it be written any better?

function dates() {
    var dayOfWeek = 5;//friday
    var date = new Date(2013, 10, 13);
    var diff = date.getDay() - dayOfWeek;
    if (diff > 0) {
        date.setDate(date.getDate() + 6);
    }
    else if (diff < 0) {
        date.setDate(date.getDate() + ((-1) * diff))
    }
    console.log(date);
}


texts:
I have written a small Python function to extract version info from a string.
Input is of format:

v{Major}.{Minor}[b{beta-num}]

Eg: v1.1, v1.10b100, v1.100b01
Goal is to extract Major, Minor and beta numbers.

import re
def VersionInfo(x):
    reg = re.compile('^v([0-9]+)([.])([0-9]+)(b)?([0-9]+)?$')
    return reg.findall(x)
if __name__ == '__main__':
    print(VersionInfo('v1.01b10'))
    print(VersionInfo('v1.01'))
    print(VersionInfo('v1.0'))

Output:

[('1', '.', '01', 'b', '10')]
[('1', '.', '01', '', '')]
[('1', '.', '0', '', '')]

Question is:

Is it sufficient to cover all cases?
Better regex?


texts: Overloading __getitem__() for two key types in Python

texts:
I've got a collection of users with two types of IDs (a_id, b_id) where one is a positive integer and the other is a six-letter string. For my collection class, I'd like to be able to look up users using either type of ID.

Is there something wrong with using __contains__ and __getitem__ for either type of ID?

class UserList:
    def __init__(self, users_json):
        self.a_ids = {}
        self.b_ids = {}
        for user in users_json:
            a_id = user['a_id']
            b_id = user['b_id']
            self.a_ids[a_id] = user
            self.b_ids[b_id] = user

    def __contains__(self, some_id):
        return some_id in self.a_ids or some_id in self.b_ids

    def __getitem__(self, some_id):
        try:
            return self.a_ids[some_id]
        except KeyError:
            return self.b_ids[some_id]

Update: This is for Python 3.x, and there is no implementation of __setitem__; updating users is handled in separate API functions.


texts: Number of anagrams in an array of words (Codewars)

texts:
Codewars Kata in Question.

  An anagram is a word, a phrase, or a sentence formed from another by
  rearranging its letters. An example of this is "angel", which is an
  anagram of "glean".

  Write a function that receives an array of words, and returns the
  total number of distinct pairs of anagramic words inside it.

  Some examples:

  There are 2 anagrams in the array ["dell", "ledl", "abc", "cba"]

  There are 7 anagrams in the array ["dell", "ledl", "abc", "cba", "bca", "bac"]

My code is usually not optimal, and I would like to improve my coding practices, and coding sense which is why I try to put up for review all nontrivial code I write.

My Code

from collections import Counter
import math

def choose(n, k):   #Each distinct anagram pair is a selection from the set of all words that have the same count.
    f = math.factorial
    return (f(n)//(f(n-k)*f(k)))

def anagram_counter(words):
    words = list(set(words))    #Suppress duplicates.
    unique = set()  #Set of unique words.
    count = {}  #Dictionary that stores the count for each word.
    unique = set()
    for word in words:
        #The current word is not an anagram of any word already in the set.
        wordID = Counter(word)
        if not unique or all((wordID != count[distinct][1] for distinct in unique)):
            unique.add(word)
            count[word] = [1,wordID]    #A tuple containing number of anagrams of a word and its `wordID`.
        else:   #If the current word is an anagram of a word already in the set.
            for distinct in list(unique):
                if count[distinct][1] == wordID:    #If the word is an anagram of a preexisting word.
                    count[distinct][0] += 1     #Increment the counter.
                    break
    return 0 if count == {} else sum((choose(itm[0], 2) for itm in count.values() if itm[0] > 1))


texts:
I have the following Scala code:

  def getLists(token: String, username: String):Future[Try[Seq[Group]]] = {
    val result:Future[Try[JsValue]] = getAPIResult(token, "https://myapi.com/screen_name=" + username)
    result.map( x => convertFromJsValueToObject(x))
  }

  def getSubscriptions(token: String, username: String):Future[Try[Seq[Group]]] = {...} //same as above

  private def getAPIResult(token: String, apiCall: String):Future[Try[JsValue]] = {
    WS.url(apiCall)
    .withHeaders("Authorization" -> ("Bearer " + token))
    .get().map(response =>
       response.status match {
       case 200 => Success(Json.parse(response.body))
       case _ => Failure(new RuntimeException("Web service call failed: " + response.body))
    })
  }

  private def convertFromJsValueToObject(json: Try[JsValue]): Try[Seq[Group]] = {
    json match {
      case Success(v) => {
        Success(v.as[Seq[Group]])
      }
      case Failure(t) => Failure(t)
      }
  }

and I have a third function like this:

def getAllListsAndSubscriptions(token: String, username: String):Future[Try[Seq[Group]]] = {...}

Which is supposed to concatenate the two Seq collections of Group objects together and return them as per the type signature. I'm really struggling to figure out how to do this though, as the types are so deeply nested.

Have I written my code badly or is there another way to do this?