texts:
The game of Set involves cards with four properties: number, symbol, shading, and colour.

Three cards make a "Set" if the property is either all the same or all different across the three cards, for each of the four properties.

I wrote some code to verify if three cards constitute a "Set". But I'm not satisfied with the final function isSet. I feel there should be some way to iterate over the four properties instead of writing four separate lines. Any help would be appreciated - I'm fairly new to F#.

type Number = | One | Two | Three
type Symbol = | Round | Wavy | Diamond
type Shading = | Empty | Lines | Full
type Colour = | Red | Green | Blue

type Card = {number: Number;
            symbol: Symbol;
            shading: Shading;
            colour: Colour}

let all =
    List.reduce (=)

let numUnique list =
    list
    |> List.distinct
    |> List.length

let allSame list =
    list
    |> numUnique
    |> (=) 1

let allUnique list =
    let length = List.length list
    list
    |> numUnique
    |> (=) length

let allSameOrUnique list =
    allSame list || allUnique list

let isSet card1 card2 card3 =

    let check1 = allSameOrUnique [card1.number; card2.number; card3.number]
    let check2 = allSameOrUnique [card1.symbol; card2.symbol; card3.symbol]
    let check3 = allSameOrUnique [card1.shading; card2.shading; card3.shading]
    let check4 = allSameOrUnique [card1.colour; card2.colour; card3.colour]

    all [check1; check2; check3; check3; check4]

let card1 = {number = Two; symbol = Round; shading = Lines; colour = Green}
let card2 = {number = One; symbol = Round; shading = Empty; colour = Green}
let card3 = {number = Three; symbol = Round; shading = Full; colour = Green}

The final function returns a boolean for verifying the set:

> isSet card1 card2 card3

val it : bool = true


texts:
I've written tests that use Bash for testing a custom shell. I think the tests work but I'm sure you know better because this is my first test I write this way.

#!/bin/bash
echo "-- Testing our implementation of OpenShell --"
echo ""
echo "- If you have any problem in passing a test read the corresponding"
echo "- source file to understand what the test is checking"
echo ""
echo -n "********************* PRESS ENTER TO RUN TESTS  ... "
read answ
echo ls -al openshell.*|./shell
echo -n "********************* TEST ALGORITHMS ... "
read answ
./shell < <(echo "ls -al|grep open|awk '{print \$9}'")
echo -n "********************* TEST DONE. YOU SHOULD SEE FILENAMES ABOVE ... "

Now I run the test and see what I expect, my command interpreter executes the pipeline from the Bash script.

$ ./RUN_TESTS
-- Testing our implementation of OpenShell --

- If you have any problem in passing a test read the corresponding
- source file to understand what the test is checking

********************* PRESS ENTER TO RUN TESTS  ...
Current working dir: /home/dac/ClionProjects/shell2/openshell
'PATH' is set to /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin.
stdin is a file or a pipe

p[0][0] ls
p[0][1] -al
p[0][2] openshell.h

-rw-rw-r-- 1 dac dac 1439 maj  1 16:45 openshell.h
********************* TEST ALGORITHMS ...
Current working dir: /home/dac/ClionProjects/shell2/openshell
'PATH' is set to /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin.
stdin is a file or a pipe
 {ls} {-al} {|} {grep} {open} {|} {awk} {{print $9}} {|}
p[0][0] ls
p[0][1] -al
p[1][0] grep
p[1][1] open
p[2][0] awk
p[2][1] {print $9}

openshell-0.16430.tar.gz
openshell.h
********************* TEST DONE


texts: In-place quicksort algorithm in Python 2

texts:
I have tried to implement an in-place quicksort Algorithm in Python 2. Please suggest how I can

Make the code more efficient
Increase readability
Improve writing style
Make it more Pythonic

def swap(x,y):
    return y,x

def sort(ar, start, end, l):

    if start<end-1:

        # pivot element is taken as the last element
        p = ar[end-1]

        ind=start-1

        # when a smaller no. than pivot is found, swap it with first bigger-tahn-pivot element.
        # keep index as the recently swapped smaller integer, if no smaller number found, than index is start-1 because pivot is out as first element

        for i in xrange(start,end-1):
            if ar[i]<p:
                ind=i
                for j in xrange(0,i):
                    if ar[j]>p:
                        ind=j
                        ar[i],ar[j] = swap(ar[i],ar[j])
                        break

        #Swap pivot with the first bigger-than-pivot number
        ar[ind+1], ar[end-1] = swap(ar[ind+1], p)

        ar = sort(ar, start, ind+1, l)
        ar = sort(ar, ind+2, end, l)

        return ar

    else:
        return ar


texts:
A few weeks ago, I wrote a Python implementation of 2048. Since then, I've been working on a simple AI to play the game for me. The code uses expectimax search to evaluate each move, and chooses the move that maximizes the search as the next move to execute.

Similar to what others have suggested, the evaluation function examines monotonicity along a "snake path"; I also penalize boards that don't keep the largest tile at the snake path's terminal.

The AI can get to 2048 (and even 4096 occasionally), but not further. One of the things I've had difficulty with is tuning the evaluation function, and looking at what to try next. I have taken a look at awarding bonuses for zero tiles (for example, z*log(s) where z is the number of zeros and s is the total sum of the tiles on the board; zeros become more valuable deeper into the game) but haven't had much luck improving things. Rather, I feel like I'm guessing at what to do next to improve the heuristic (or I'll look at a board that defied my human strategy, and try and write something to mirror this), and am curious what someone else might suggest.

The code for the game and the AI can be found here. You can run aiplay with a Game instance.

Below is the relevant AI code:

from game import *

import math

def aimove(b):
    """
    Returns a list of possible moves ("left", "right", "up", "down")
    and each corresponding fitness
    """
    def fitness(b):
        """
        Returns the heuristic value of b

        Snake refers to the "snake line pattern" (http://tinyurl.com/l9bstk6)
        Here we only evaluate one direction; we award more points if high valued tiles
        occur along this path. We penalize the board for not having
        the highest valued tile in the lower left corner
        """
        if Game.over(b):
            return -float("inf")

        snake = []
        for i, col in enumerate(zip(*b)):
            snake.extend(reversed(col) if i % 2 == 0 else col)

        m = max(snake)
        return sum(x/10**n for n, x in enumerate(snake)) - \
               math.pow((b[3][0] != m)*abs(b[3][0] - m), 2)

    def search(b, d, move=False):
        """
        Performs expectimax search on a given configuration to
        specified depth (d).

        Algorithm details:
           - if the AI needs to move, make each child move,
             recurse, return the maximum fitness value
           - if it is not the AI's turn, form all
             possible child spawns, and return their weighted average
             as that node's evaluation
        """
        if d == 0 or (move and Game.over(b)):
            return fitness(b)

        alpha = fitness(b)
        if move:
            for _, child in Game.actions(b):
                return max(alpha, search(child, d-1))
        else:
            alpha = 0
            zeros = [(i,j) for i,j in itertools.product(range(4), range(4)) if b[i][j] == 0]
            for i, j in zeros:
                c1 = [[x for x in row] for row in b]
                c2 = [[x for x in row] for row in b]
                c1[i][j] = 2
                c2[i][j] = 4
                alpha += .9*search(c1, d-1, True)/len(zeros) + \
                         .1*search(c2, d-1, True)/len(zeros)
        return alpha
    return [(action, search(child, 5)) for action ,child in Game.actions(b)]

def aiplay(game):
    """
    Runs a game instance playing the move determined
    by aimove.
    """
    b = game.b
    while True:
        print(Game.string(b) + "\n")
        action = max(aimove(b), key = lambda x: x[1])[0]

        if action == "left" : b = Game.left(b)
        if action == "right": b = Game.right(b)
        if action == "up"   : b = Game.up(b)
        if action == "down" : b = Game.down(b)
        b = Game.spawn(b, 1)
        if Game.over(b):
            m = max(x for row in b for x in row)
            print("game over...best was %s" %m)
            print(Game.string(b))
            break


texts: Create list of objects from an object where the key is properCase using Lodash

texts:
I'm trying to create a filtered list of objects where each object in the list has both a label and value property.

First I use .pick to select the key/value pairs I want from the initial object, then I iterate over the 'picked' properties and push the key into an object property called label, and push the value of the property into a property called value. I then return the empty array.

function formatToInput(obj, list) {
    var empty = []

    _.forIn(_.pick(obj, list), (val, key) => {
        empty.push({
            label: _.startCase(key),
            value: val
        });
    });

    return empty;
}

// use like so

var test = {blue: 10, green: 5, yellow: 3, pink: 1};
var filter = ['green', 'yellow'];

var results = formatToInput(test, filter)

console.log(results);

// [{label: Green, value: 5}, {label: Yellow, value: 3}]

I'm trying to avoid having to manually create an array and pushing objects into it, but I couldn't find a solution (in Lodash) that would allow me to do this.


texts: Use a comma-separated field in another SQL query

texts:
I was just wondering if there was a better way to write this block of code in php. I have a string with values separated by commas. I need to prepare that string to pass it on to the query using IN clause.

 $sql = "SELECT domain, items FROM rep_skills WHERE report_id = $id ";
 $data = $conn->query($sql)->fetch_object();

 while($data){
     // can this be done in one line?
     $array =  explode(",",$data->items); // string here is 39,40,41
     $items = implode("','",$array);  // string here is 39','40','41
     // end of block

     $result = $conn->query("SELECT description
           FROM ".$tables[$data->domain]."
           WHERE item_id IN ('".$items."')");

     $description = '';
     while($row = $result->fetch_object()){
        $details .= '- '.$row->description;
    }
}


texts: Given points on a 2D plane, find line that passes through the most points

texts:
Could someone give some feedbacks from perspective of oo design and coding style on the following codes:

Question: Given n points on a 2D plane, find the Line with maximum number of points that lie on it. Similar to https://leetcode.com/problems/max-points-on-a-line/description/. I was given Point interface, empty Line class, empty Solution class and was asked to fill in some functions.

My codes:

public interface Point
{
  public double getX();
  public double getY();
}

public class Line
{ // added by myself.
  private Point p1, p2;
  public Line(Point p1, Point p2) {
    this.p1 = p1;
    this.p2 = p2;
  }
}

public class Solution
{
  // Write the function here
  public Line maxPointsLine(Point[] points) {
    if(points == null) return null;
    if(points.length==1) return new Line(points[0], new Point(p));//
    Map<Double, Integer> map = new HashMap<>();// O(n), n = points.length. n-1
    Line result;
    int maxPoints = 0;
    for(int i = 0; i < points.length; i++) { // One Point
      map.clear();
      int overlap =0;
      int countSameX = 1;
      for(int j = i+1; j < points.length; j++) { // the second Point
        double x = points[j].getX() - points[i].getX(); // x intersect
        double y = points[j].getY() - points[i].getY(); // intersect on y coordinate

        if(x==0 && y==0) {
          overlap++;
        }
        if(points[j].getX()==points[i].getX()) {// slope is infi,
          // slope (1) finite, (2) infinite,
          countSameX++;
          continue;
        }
        double slope = y/x;
        if(map.contains(slope)) map.put(slope, map.get(slope)+1);
        else map.put(slope, 2);
        if(map.get(slope)+overlap > maxPoints) { // each line slope and points[i]
          // update result and maxPoints
          maxPoints = map.get(slope)+overlap;
          result = new Line(points[i], points[j]);
        }
      }
      if(countSameX>maxPoints) { // line parallel to Y coordinate
        // update result and maxPoints
        maxPoints = countSameX;
        result = new Line(points[i], points[j]);
      }
    }
    return result;// null
  }
}

In the above codes, I added some comments based on questions I was asked.

(I did this coding question long ago. just came into my mind. ) In fact, the interviewer told me that didn’t have good coding style and lack of OO design. suggestions are welcomed for me to improve myself. Thanks.

By the way, as for coding style, there are plugins following standards like https://google.github.io/styleguide/javaguide.html. I just did not fix coding style issues manually due to lack of time.

As for OO design, I was given empty classes. I just added some functions to solve problem I was given.

I really did not find any big issues in my codes. Confused and frustrated.


texts:
I am absolutely new to c++ and am trying to learn SDL2 with c++. I am setting up my first project and I was unsure if the way I have structured the project is good or if I have over done it. Here is the code:
generalFuncs.h
#pragma once

#include "SDL.h"
#include <iostream>

struct State
{
    bool quit = false;
};

class CreateWindow
{
public:
    CreateWindow(
        int x,
        int y,
        int w,
        int h,
        bool fullScreen = false
    )
    {
        pWindow = SDL_CreateWindow("", x, y, w, h, fullScreen);
    }

    inline SDL_Window* getWindow()
    {
        return pWindow;
    }
private:
    SDL_Window* pWindow;
};

class Events
{
public:
    void handleEvents(State* state)
    {
        while (SDL_PollEvent(&event))
        {
            if (event.type == SDL_QUIT)
                state->quit = true;
        }
    }

private:
    SDL_Event event;
};

renderer.h
#pragma once

#include "SDL.h"

class Renderer
{
public:
    Renderer(SDL_Window* pWindow)
    {
        pRenderer = SDL_CreateRenderer(pWindow, -1, 0);
    }

    inline SDL_Renderer* getRenderer()
    {
        return pRenderer;
    }

    inline void clearScreen(int r, int g, int b, int a)
    {
        SDL_SetRenderDrawColor(pRenderer, r, g, b, a);
        SDL_RenderClear(pRenderer);
    }

    inline void update()
    {
        SDL_RenderPresent(pRenderer);
    }

    void render()
    {

    }

private:
    SDL_Renderer* pRenderer;
};

main.cpp
#include <iostream>
#include <SDL.h>
#include <vector>
#include "generalFuncs.h"
#include "renderer.h"

int main(int argc, char* argv[])
{

    if (SDL_Init(SDL_INIT_EVERYTHING) != 0)
    {
        std::cout << "Could not initialze SDL properly \n" << SDL_GetError() << std::endl;
        return 0;
    }

    CreateWindow window(SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1200, 600);
    Renderer renderer(window.getWindow());
    State state;
    Events events;

    if (window.getWindow() == NULL)
    {
        std::cout << "Could not window properly \n" << SDL_GetError() << std::endl;
        return 0;
    }
    if (renderer.getRenderer() == NULL)
    {
        std::cout << "Could not window properly \n" << SDL_GetError() << std::endl;
        return 0;
    }

    while (!state.quit)
    {
        events.handleEvents(&state);
        renderer.clearScreen(255, 255, 255, 255);
        renderer.render();
        renderer.update();
    }

    SDL_DestroyWindow(window.getWindow());
    SDL_Quit();
    return EXIT_SUCCESS;

}

The way I plan on using this is make other header files, include them to render.h, then draw them in the render method. Please let me know if there are better way to do things or if my setup can be improved. Thank you.


texts:
I have the below MySQL query that does exactly what I need, but I am sure there are better queries that do the same thing.

If you see something very ugly or bad and have any suggestions, I will be very glad to hear them.

SELECT c.`ID_COURIER`, c.`NAME`,
    c.`NICKNAME`, c.`AREA_CODE`,
    c.`PHONE_NUMBER`, d.`ID_DELIVERY`,
    d.`DESCRIPTION`, d.`START_DATE`,
    d.`END_DATE`, d.`CANCELED`,
    r.`LAT`, r.`LNG`,
    (SELECT COUNT(DISTINCT `ID_ORDER`) FROM `ORDERS` WHERE `ID_DELIVERY` = d.`ID_DELIVERY` AND `DELIVERY_DATE` IS NULL AND `CANCELED` = false) as REMAINING_ORDERS
FROM `COURIER` as c
    LEFT JOIN `DELIVERY` as d USING (`ID_COURIER`)
    LEFT JOIN `GEOLOCATIONS` as r ON r.`ID_DELIVERY` = d.`ID_DELIVERY`
WHERE c.`ID_COMPANY` = ? AND c.`DISABLED` = false
    AND (
        CASE WHEN (SELECT MAX(`START_DATE`)
                       FROM `DELIVERY`
                       WHERE `ID_COURIER` = c.`ID_COURIER`)
                 IS NULL THEN d.`START_DATE` IS NULL
                 ELSE d.`START_DATE` = (SELECT MAX(`START_DATE`)
                                        FROM `DELIVERY`
                                        WHERE `ID_COURIER` = c.`ID_COURIER`)
            END )
    AND (
        CASE WHEN (SELECT MAX(`ID_GEOLOCATION`)
                       FROM `GEOLOCATIONS`
                       WHERE `ID_DELIVERY` = d.`ID_DELIVERY`)
                     IS NULL THEN r.`ID_GEOLOCATION` IS NULL
                   ELSE r.`ID_GEOLOCATION` = (SELECT MAX(`ID_GEOLOCATION`)
                                               FROM `GEOLOCATIONS`
                                               WHERE `ID_DELIVERY` = d.`ID_DELIVERY`)
            END)
GROUP BY c.`ID_COURIER`
ORDER BY d.`START_DATE` DESC


texts: Is this escape unescape function pair correct?

texts:
Is this example of an escape - unescape function correct?

ESCAPE = '/'

def escape(s):
    rv = s
    rv = rv.replace(ESCAPE, ESCAPE + ESCAPE)
    rv = rv.replace('+', ESCAPE + 'PLUS')
    rv = rv.replace('-', ESCAPE + 'MINUS')
    return rv

def unescape(s):
    rv = s
    rv = rv.replace(ESCAPE + 'MINUS', '-')
    rv = rv.replace(ESCAPE + 'PLUS', '+')
    rv = rv.replace(ESCAPE + ESCAPE, ESCAPE)
    return rv


texts:
I would like to request some code review and feedback on a stack implementation using Swift.

Disclaimer: I might have not used protocols, optional unwrapping and error and nil check correctly (still trying to figure out the essence of protocols - but that's the drill I'm going through now).

import Foundation

/* Node conformance */
protocol NodeProtocol {

    typealias IDType;
    typealias IDNode;
    func insertNode(element : IDType, nextNode : IDNode?);
}

/* Stack's conformance prototol */
protocol StackProtocol {

    typealias IDType;
    /* Function to push element on stack */
    func push(element : IDType);
}

class IDNode<IDType> : NodeProtocol
{
    var element: IDType?;
    var nextNode: IDNode?;

    /* Sets the element and updates next pointer */
    func insertNode(element: IDType, nextNode: IDNode?) {

        self.element = element;
        self.nextNode = nextNode;
    }
}

class IDStack<IDType> : StackProtocol
{
    private var stackHead: IDNode<IDType>?;

    init() {

        /* Constructor to initialize the stack */
        stackHead = IDNode<IDType>();
    }

    func push(element: IDType) {

        /* If stackHead is empty - just create a new stack
        * Ideally the constructor should have taken care of this.
        * but in our case - because of optional. stackHead can be NULL.
        * So we don't want to take any chance while pushing element to stack.
        */
        if(stackHead == nil) {
            stackHead = IDNode<IDType>();
        }

        /* if stack's first element is empty - Insert as the first element
        * At this point stack is guaranteed not NULL. Right?
        * What if memory allocation fails from above?
        */
        if(stackHead!.element == nil) {
            stackHead!.insertNode(element, nextNode: nil);
        }else {
            /* create a new node and insert the new element at top */
            var nodeToPushInStack: IDNode<IDType>! = IDNode<IDType>();
            /* I'm assuming memory allocation always passes from above.
            * Is it correct?
            */
            nodeToPushInStack.insertNode(element, nextNode: stackHead);
            /* Update stack's head to the new Node */
            stackHead = nodeToPushInStack;
        }

    }

    func popElement() -> IDType? {

        /* Remove from top and return the element. */
        var itemPoppedFromStack : IDType?;

        if(self.stackHead == nil) {
            /* Stack is empty / not initialized */
            return nil;
        }

        itemPoppedFromStack = self.stackHead!.element!;

        if(itemPoppedFromStack == nil) {
            return nil;
        } else {
           /* restore pointer order */
            stackHead = stackHead!.nextNode;
        }
        return itemPoppedFromStack;
    }

    func getLength() -> Double {

        var length: Double = 0;
        var headNode: IDNode<IDType>! = self.stackHead;

        if(headNode == nil) {
            /* stack is probably empty, just return 0 */
            return 0;
        }

        while(self.stackHead != nil) {

            length++;
            self.stackHead = self.stackHead!.nextNode;
        }
        /* restore back stackHead to original head */
        self.stackHead = headNode;

        return length;
    }
}


texts: Compare two strings in extended memory - classic 8052

texts:
I'm looking for a simpler code that isn't resource hungry that can compare two strings stored in different locations in the extended memory of a classic 8052 (namely the AT89S52 microcontroller) to make sure the characters match exactly.

The error flag can be a bit value, but the only thing that concerns me is that I need scanning to begin at any two 16-bit memory locations of my choice and that the same number of consecutive bytes in each location need to be scanned.

I was considering applying boolean logic to DPH or the DPL variables (example ANL and ORL) but at the same time will I be able to make that programmer friendly? I don't want to make the memory addressing confusing later on. Also, I'm looking for code that can replace this that can provide better performance (meaning fewer instructions required to execute a string comparison code).

Any ideas are welcome.

;Load # bytes to check in R7
mov R7,#BYTESTOCHECK

;R6 = our error status. Assume no error here
mov R6,#0h

;Load first memory pointer address to R2:R3
mov R2,#HIGHBYTE1
mov R3,#LOWBYTE1

;Load second memory pointer address to R4:R5
mov R4,#HIGHBYTE2
mov R5,#LOWBYTE2

checknextbyte:

  mov DPL,R2
  mov DPH,R3
  ;DPTR here = R2:R3
  movx A,@DPTR
  ;Store value at DPTR in B
  mov B,A
  inc DPTR
  mov R3,DPH
  mov R2,DPL

  mov DPL,R4
  mov DPH,R5
  ;DPTR here = R4:R5
  movx A,@DPTR
  ;Store value at DPTR in A
  inc DPTR
  mov R5,DPH
  mov R4,DPL

  CJNE A,B,notsame
    ;Both addresses aren't same so string isn't same
    ;make R7=1 to exit loop faster
    mov R7,#1h
    ;Make R6=1 to show we have error
    mov R6,#1h
  notsame:

djnz R7,checknextbyte


texts:
I'm going to screw around with visualizing Recamán's Sequence, but want to have a good sequence generator to generate the sequence before I start. I want to use a lazy generator for my actual application, but decided to make a strict version first since it will likely be simpler.

This is what I ended up with. It works (verified against the OEIS), but is quite verbose. I don't technically require seen, but doing constant linear searching over acc would likely be unacceptable. I'm just looking for broad suggestions on how this can be improved, because while it's fairly fast (it can find the first million numbers in ~2 seconds on my potato), it's rather ugly.

I know though that I can make use of transients here, but they're easy enough to add afterwards that that's not a big deal.

Any suggestions would be appreciated, because I feel like I'm missing something obvious.

(defn strict-recamans-sequence [max-n]
  (let [c-last #(get % (dec (count %)))]
    (loop [n 1
           seen #{}
           acc [0]]
      (if (> n max-n)
        acc

        (let [prev (c-last acc)
              back (- prev n)
              new-n (if (and (pos? back) (not (seen back)))
                      back
                      (+ prev n))]
          (recur (inc n) (conj seen new-n) (conj acc new-n)))))))


texts: Plotting terrain pixels with PyGame based on random NumPy array

texts:
I am experimenting with Perlin Noise and random map generation. I have a 2D numpy ndarray full of 16-bit floats called map_list that I call from the singleton ST. It has 900 rows with 1600 elements each. I am iterating through it to display different colored pixels to represent terrain at different points in the map. Array values in different ranges produce pixels of different colors. The total possible range is [0, 1] because I am normalizing the values.

Is there a way to display the aforementioned pixels faster than I am capable of now?

"""

This file holds functions that modify pyGame surfaces.

"""

from __future__ import division
from singleton import ST
from pygame import gfxdraw

def display_map(surface):
    """
    This takes in a pyGame surface, and draws colored tiles on it according to
    the values in ST.map_list. The higher the value, the lighter the shade of
    the tile.

    :param surface: A pyGame surface.
    """

    x_pos = 0
    y_pos = 0

    for y in range(len(ST.map_list)):

        for x in range(len(ST.map_list[y])):
            noise_value = ST.map_list[y][x]
            shade = int(noise_value * 255)
            color = __color_tiles(noise_value, shade)

            gfxdraw.pixel(surface, x_pos, y_pos, color)
            x_pos += ST.TILE_SIZE

        x_pos = 0
        y_pos += ST.TILE_SIZE

def __color_tiles(noise_value, shade):
    """
    Treat this function as private. It should only be called by functions and
    methods within this file. It returns a 3-element 1D tuple that represents
    the rgb color values to display the tile as.

    :param noise_value: The noise value at a specific point in ST.map_list.
    :param shade: How dark or light the tile should be.
    :return: tuple
    """

    if noise_value < ST.WATER_LEVEL:
        rgb = (shade, shade, 255)
    elif noise_value > ST.MOUNTAIN_LEVEL:
        rgb = (shade, shade, shade)
    else:
        rgb = (shade, 255, shade)

    return rgb

What it generates


texts:
This takes a string input like 1,2,3,4,5, splits it using , delimiter, converts each char to int and output it in a single line like this : 12345

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

int* createIntArray(char* numbersInString, int* array_size);

int* createIntArray(char* numbersInString, int* array_size)
{
    char* token = strtok(numbersInString,",");
    int* numbersArray = malloc(sizeof(int)*100);
    int i = 0;

    while(token != NULL)
    {
        numbersArray[i] = (int)*token -'0';
        token = strtok(NULL,",");
        i++;
    }

    *array_size = i;
    return numbersArray;
}

int main(){
    char* stringNumbers = malloc(sizeof(char)*100);
    int* intArray;
    int arrayLength = 0;
    printf("Enter numbers\n");
    scanf("%s",stringNumbers);
    intArray = createIntArray(stringNumbers,&arrayLength);

    int i;
    for(i = 0; i < arrayLength;i++)
    {
        printf("%d",intArray[i]);
    }

    free(stringNumbers);
    free(intArray);
    return 0;
}

I know the code is super useless, but I'm starting to learn C and I wanted to see if my code was alright and if it complies to C coding standards.


texts: Parsing positive integers from CSV file Part-2

texts:
Part-1 here

This is a small CSV parser for positive integers mostly intended for personal projects.
I (hopefully) improved the code from Part-1 by condensing some parts and improving others while also keeping performance the same.
My main worries are any obvious pitfalls I might have missed as well as concerns about the general approach. Of course anything else you notice is also welcome.
Please see part-1 for a list of requirements/restrictions I had when writing this.

For anyone who wants to test this against actual input I provide a small Perl script to generate CSV files.

Call it with: perl [scriptname] [how many lines you want] >outputfile

use strict;
use warnings "all";

die "usage: perl $0 <amount_of_lines>\n" unless (int(@ARGV) > 0);

for (1 .. $ARGV[0]) {
    my $vals_per_line = int(rand(10));
    my @values;
    for (0 .. $vals_per_line) {
        push(@values, int(rand(1000)));
    }
    print join(",", @values) . "\n";
}

Code:

#include <fstream>
#include <string>
#include <vector>

template<typename T>
void parse_lines(
        const std::string& filename,
        const uint_fast8_t& line_length_estimate,
        const uint_fast8_t& values_per_line_estimate,
        T callback) {
    std::ifstream infile{filename};
    if (!infile.good()) {
        return;
    }

    std::vector<uint_fast16_t> numbers;
    numbers.reserve(values_per_line_estimate);

    std::string buffer;
    buffer.reserve(line_length_estimate);

    while (infile.good() && std::getline(infile, buffer)) {
        if (buffer[buffer.size() - 1] == '\r') {
            buffer[buffer.size() - 1] = ',';
        }
        else {
            buffer.push_back(',');
        }

        uint_fast16_t parsed_number = 0;
        for (const auto& digit : buffer) {
            if (digit == ',') {
                numbers.emplace_back(parsed_number);
                parsed_number = 0;
            }
            else {
                parsed_number = (parsed_number * 10) + (digit - '0');
            }
        }
        callback(numbers);
        numbers.clear();
    }
}

int main(int argc, char** argv) {
    constexpr uint_fast8_t line_length_estimate = 50;
    constexpr uint_fast8_t values_per_line_estimate = 15;
    parse_lines(argv[1], line_length_estimate, values_per_line_estimate, [](auto& values) {
        // ...
    });
}


texts:
I created this to count points in an area.

$(document).ready(function () {
    var area = [
        [4, 4],
        [4, -4],
        [-4, -4],
        [-2, -2],
        [-2, 2],
        [-4, 4],
        [4, 4]
    ];
    var points = [
        [2, 1],
        [1, 2],
        [5, 3]
    ];
    var res = countPoints(area, points);
    $('#result').text("count : " + res);
});

function countPoints(area, points) {
    var count = 0;
    var xptsOfArea = [];
    var yptsOfArea = [];
    for (var ii = 0; ii < area.length; ii++) {
        xptsOfArea.push(area[ii][0]);
        yptsOfArea.push(area[ii][1]);
    }
    var xptsToCount = [];
    var yptsToCount = [];
    for (var ii = 0; ii < points.length; ii++) {
        xptsToCount.push(points[ii][0]);
        yptsToCount.push(points[ii][1]);
    }

    for (var ii = 0; ii < points.length; ii++) {
        if (checkFor(xptsOfArea, xptsToCount[ii], 0) && checkFor(yptsOfArea, yptsToCount[ii], 0)) {
            count += 1;
            console.log('[' + xptsToCount[ii] + ',' + yptsToCount[ii] + ']');
        }
    }
    return count;
}

function checkFor(area, point, position) {
    if (area.length == position) return true;
    else {
        if (area[position] > 0) {
            if (area[position] >= point) {
                return checkFor(area, point, ++position);
            } else {
                return false;
            }
        } else {
            if (area[position] <= point) {
                return checkFor(area, point, ++position);
            } else {
                return false;
            }
        }
    }
}

I want to make this open source, so I have three main concerns:

Naming
Complexity
Idiomaticness


texts:
Push a button and an LED lights up1 and sends a signal to another computer that plays a song.

First project on the Raspberry pi, really simple but definitely fun and educational to implement. Also, second time using python and sockets so I'd especially appreciate input on anything I do inefficiently.2

Mostly feedback to ensure that the program is running/button is active.
I know it's straightforward, but this site has shown me that even the simplest things leave room to be executed much more elegantly.

SongServer.java:

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
import java.awt.Desktop;

public class SongServer {
    final static int PORT = 9001;

    public static void main(String[] args) {
        try(ServerSocket server = new ServerSocket(PORT)) {
            System.out.println(new Date() + "\nServer online.");

            while(true) {
                new Thread(new ClientHandler(server.accept())).start();
            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }

    private static class ClientHandler implements Runnable {
        private Socket socket;
        private BufferedReader in;
        private PrintWriter out;

        ClientHandler(Socket socket) {
            this.socket = socket;
            System.out.println("Client connected!");
        }

        @Override
        public void run() {
            try {
                in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                out = new PrintWriter(socket.getOutputStream(), true);

                out.println("Connection success");
                while (true) {
                    String input = in.readLine();
                    if (input == null || input.trim().isEmpty()) {
                        continue;
                    }
                    System.out.println(input);

                    if (input.startsWith("play")) {
                        Desktop.getDesktop().open(new File("uptown_funk.mp3"));
                    }
                }
            } catch (Exception e) {
                System.out.println("Client disconnected!");
            }
        }
    }
}

funk_button.py:

import RPi.GPIO as GPIO
import socket

funk_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
funk_socket.connect(("10.0.0.18", 9001))
sent = False

button = 17
led = 22

GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(led, GPIO.OUT)
GPIO.setup(button, GPIO.IN)

while True:
    if GPIO.input(button):
        GPIO.output(led, GPIO.LOW)
    else:
        GPIO.output(led, GPIO.HIGH)
        if not sent:
            funk_socket.send(bytearray("play\r\n", "utf-8"))
            sent = True


texts: "Rock, Paper, Scissors" game - follow-up

texts:
This is a follow-up to ""Rock, Paper, Scissors" game". I did almost everything the answers recommended and I hope you like it.

import os
from random import choice

def player_choice():
    while True:
        print("Rock, paper or scissors?")
        choice = input(">").capitalize()
        if choice in ('Rock', 'Paper', 'Scissors'):
            return choice

def win_msg(player_choice, computer_choice):
    msg = f"{player_choice} beats {computer_choice}. You won!"
    return msg

def lose_msg(player_choice, computer_choice):
    msg = f"{computer_choice} beats {player_choice}. You lost!"
    return msg

def computer_choice():
    return choice(('Rock', 'Paper', 'Scissors'))

def show_statistics(scores):
    os.system('cls' if os.name == 'nt' else 'clear')
    print(f"Wins: {scores[0]}\nLosses: {scores[1]}\nDraws: {scores[2]}")

def game_outcome(player, computer):
    if player == computer:
        return 'Draw'
    elif player == 'Rock':
        if computer == 'Paper':
            return 'Lose'
        else:
            return 'Win'
    elif player == 'Paper':
        if computer == 'Rock':
            return 'Win'
        else:
            return 'Lose'
    else:
        if computer == 'Rock':
            return 'Lose'
        else:
            return 'Win'

def show_results(outcome, player, computer):
    if outcome == 'Win':
        print(win_msg(player, computer))
    elif outcome == 'Lose':
        print(lose_msg(player, computer))
    else:
        print("Draw. Nobody wins or losses.")

def update_scores(scores, outcome):
    new_scores = list(scores)
    if outcome == 'Win':
        new_scores[0] += 1
    elif outcome == 'Lose':
        new_scores[1] += 1
    else:
        new_scores[2] += 1
    new_scores = tuple(new_scores)
    return new_scores

def rock_paper_scissors(scores):
    player = player_choice()
    computer = computer_choice()
    outcome = game_outcome(player, computer)
    show_results(outcome, player, computer)
    new_scores = update_scores(scores, outcome)
    return new_scores

def play_again():
    while True:
        print("\nDo you want to play again?")
        print("(Y)es")
        print("(N)o")
        ans = input("> ").lower()
        if ans == 'y':
            return True
        elif ans == 'n':
            return False

def starting_scores():
    return 0, 0, 0

def main():
    scores = starting_scores()
    still_playing = True
    while still_playing:
        show_statistics(scores)
        scores = rock_paper_scissors(scores)
        still_playing = play_again()

if __name__ == '__main__':
    main()


texts:
An includable select to pick the first day of quarter:

<cfparam name="dtFirst" default="#now()#"><!--- first date in select --->
<cfparam name="selQtrName" default="selQtr"><!--- name attr of select --->
<cfparam name="selQtrCss" default=""><!--- special style css --->
<cfparam name="howManyOpts" default="10"><!--- how many quarters to go back --->
<cfparam name="selQtrDefault" default=""><!--- default selected date  current qtr: #right("0"&(1+(quarter(now())-1)*3), 2)#/01/#year(now())# --->
<cfset raQtoDt=["01/01/","04/01/","07/01/","10/01/"]>
<cfset qtrZWX=quarter(dtFirst)>
<cfset yrZWX=year(dtFirst)>
<cfoutput>
<select name="#selQtrName#" id="#selQtrName#" style="#selQtrCss#">
<cfloop from="1" to="#howManyOpts#" index="idxZWX">
    <option value="#raQtoDt[qtrZWX]##yrZWX#"
    <cfif len(selQtrDefault) and selQtrDefault eq "#raQtoDt[qtrZWX]##yrZWX#">selected</cfif>>#raQtoDt[qtrZWX]##yrZWX#</option>
    <cfset qtrZWX=qtrZWX-1>
    <cfif qtrZWX eq "0">
        <cfset qtrZWX=4>
        <cfset yrZWX=yrZWX-1>
    </cfif>
</cfloop>
</select>
</cfoutput>


texts: Binary search traversal with in/pre/post order and BFS/DFS

texts:
I have the following code for the BST for the inorder, postorder, preorder, breadth first and depth first traversals. Can you review and let me know the optimisation points and issues, if any?

import java.util.ArrayDeque;
import java.util.Queue;
import java.util.Scanner;
import java.util.Stack;

public class BST {

    static class Node {

        int data;
        Node right, left;

        Node(int data) {
            this.data = data;
            right = left = null;
        }

        @Override
        public String toString() {
            return "Node [data=" + data + ", right=" + right + ", left=" + left + "]";
        }

    }

    public static void preOrder(Node root) {
        if (root != null) {
            System.out.print(root.data + " ");
            preOrder(root.left);
            preOrder(root.right);
        }
    }

    public static void inOrder(Node root) {
        if (root != null) {
            inOrder(root.left);
            System.out.print(root.data + " ");
            inOrder(root.right);
        }
    }

    public static void postOrder(Node root) {
        if (root != null) {
            postOrder(root.left);
            postOrder(root.right);
            System.out.print(root.data + " ");
        }
    }

    public static void breadthFirstTraversal(Node root) {
        Queue<Node> queue = new ArrayDeque<Node>();
        if (root != null) {
            queue.add(root);
        }
        while (!queue.isEmpty()) {
            Node node = queue.remove();
            System.out.print(node.data + " ");
            if (node.left != null) {
                queue.add(node.left);
            }
            if (node.right != null) {
                queue.add(node.right);
            }
        }
    }

    public static void depthFirstTraversal(Node root) {
        Stack<Node> stack = new Stack<Node>();
        if (root != null) {
            stack.push(root);
        }
        while (!stack.isEmpty()) {
            Node node = stack.pop();
            System.out.print(node.data + " ");
            if (node.right != null) {
                stack.push(node.right);
            }
            if (node.left != null) {
                stack.push(node.left);
            }

        }
    }

    public static Node insert(Node node, int data) {
        if (node == null) {
            return new Node(data);
        }
        Node cur;
        if (data <= node.data) {
            cur = insert(node.left, data);
            node.left = cur;
        } else {
            cur = insert(node.right, data);
            node.right = cur;
        }
        return node;
    }

    public static void main(String args[]) {
        BST bst = new BST();
        Scanner sc = new Scanner(System.in);
        int t = sc.nextInt();
        Node root = null;
        while (t-- > 0) {
            int data = sc.nextInt();
            root = insert(root, data);
        }

        System.out.println("Preorder :");
        preOrder(root);
        System.out.println("\nInOrder ");
        inOrder(root);
        System.out.println("\nPostOrder ");
        postOrder(root);
        System.out.println("\nBreadth First Traversal ");
        breadthFirstTraversal(root);
        System.out.println("\nDepth First Traversal ");
        depthFirstTraversal(root);
    }

}


texts:
I've been struggling with concurrent programming in Haskell for a while.  It's so hard to reason about, especially when exceptions come into the picture.

As a learning exercise, I implemented a simple chat server.  Clients connect using telnet on port 1337, and start typing text.  Each message is broadcast to all connected clients.  Clients are distinguished by an incrementing counter.

Requires the stm-linkedlist package

import Control.Concurrent
import Control.Concurrent.STM
import Control.Exception as E hiding (handle)
import Control.Monad
import Network
import Data.STM.LinkedList (LinkedList)
import System.IO

import qualified Data.STM.LinkedList as LL

type Client = TChan String

main :: IO ()
main = do
    clients <- LL.emptyIO
    sock <- listenOn (PortNumber 1337)
    let loop n = do
            (handle, host, port) <- accept sock
            putStrLn $ "Accepted connection from " ++ host ++ ":" ++ show port
            _ <- forkIO $ serve clients handle n
            loop $! n+1
     in loop 0

serve :: LinkedList Client -> Handle -> Integer -> IO ()
serve clients handle n = do
    hSetBuffering handle LineBuffering
    send_chan <- newTChanIO
    receiver <- myThreadId

    let sendLoop = forever $
            atomically (readTChan send_chan) >>= hPutStrLn handle

        receiveLoop = forever $ do
            line <- hGetLine handle
            broadcast $ "<client " ++ show n ++ ">: " ++ line

        broadcast message =
            atomically $ LL.toList clients >>= mapM_ (flip writeTChan message)

        start = do
            node   <- atomically $ LL.append send_chan clients
            sender <- forkIO $ sendLoop `onException` killThread receiver
            return $ do
                atomically $ LL.delete node
                killThread sender

     in bracket start (\finish -> finish) (\_ -> receiveLoop)

One hurdle is that I can't send and receive simultaneously in the same thread.  Thus, I'm forced to send and receive in separate threads.

In the code below, I spawn two threads per client:

A "receive" thread, which gets lines from the client and broadcasts them.
A "send" thread, which reads this client's TChan (written to by "receive" threads) and sends each message to the client.

Using a TChan, rather than having other threads write directly to this thread's Handle, has two benefits:

If sending produces an exception, it doesn't kill the innocent sending client's thread.  It only kills the "send" thread of the target client.
It keeps message text from getting interleaved.

When the "receive" thread hits an exception, its finalizer removes the client's send channel from the linked list and kills the "send" thread.  When the "send" thread hits an exception, it kills the "receive" thread, causing its finalizer to be invoked.

Is this a good approach?  Is there a better way to organize network code like this?


texts: Spring MVC dynamically adding form elements

texts:
I made a simple form with an option of adding one text field dynamically on mouse click. And I will be grateful for suggestions on how I may improve the code.

@Controller
public class MyController {

public ArrayList<NewField> fieldArrayList;
@RequestMapping(value="/create", method= RequestMethod.GET)
public String myForm(Model model, @ModelAttribute NewField newField) {

    fieldArrayList = new ArrayList<>();
    fieldArrayList.add(newField);
    model.addAttribute("dataForm", new DataForm());

    return "create";
}

@RequestMapping(value="/create", method=RequestMethod.POST)
public String formSubmit(Model model, HttpServletRequest hsr, @ModelAttribute DataForm dataForm) {

    if (hsr.getParameterValues("lastField") != null) {

        String[] lastF = null;
        lastF = hsr.getParameterValues("lastField");
        List<String> d = Arrays.asList(lastF);

        int count = d.size() + 1;
        for (int i = 2; i < count+1; i++) {
            NewField newField = new NewField();
            String s1 = hsr.getParameter("p_new_" + String.valueOf(i));
            String s2 = hsr.getParameter("l_" + String.valueOf(i));
            newField.setStr1(s2);
            newField.setStr2(s1);
            fieldArrayList.add(newField);
        }
    }
    model.addAttribute("dataForm", dataForm);
    model.addAttribute("fieldArrayList", fieldArrayList);

    return "view";
}

<!DOCTYPE HTML>

    <title>Getting Started: Handing Form Submission</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

Form

<form action="#" th:action="@{/create}" th:object="${dataForm}" method="post">

Id: <input type="text" th:field="*{id}" />

Name: <input type="text" th:field="*{content}" />

<input type="submit" value="Submit" />

</form>
<input type="text" id="p_new" size="20" name="p_new" value="" placeholder="Input Value" />
<input type="button" id="addNew" value="Add New field"/>


texts:
I'm writing a Morse code translator for homework in C#. It takes an input from the user and returns the Morse code version of their input. I understand that this code may look horrible, so how could I improve it in terms of efficiency and readability?

Program.cs

using System;
using System.Collections.Generic;

namespace MorseCodeTranslator
{
    class Program
    {
        static Dictionary<char, string> translator;

        static void Main(string[] args)
        {
            InitialiseDictionary();
            getUserInput();
        }

        private static void InitialiseDictionary()
        {
            char dot = '.';
            char dash = '−';

            translator = new Dictionary<char, string>()
            {
                {'a', string.Concat(dot, dash)},
                {'b', string.Concat(dash, dot, dot, dot)},
                {'c', string.Concat(dash, dot, dash, dot)},
                {'d', string.Concat(dash, dot, dot)},
                {'e', dot.ToString()},
                {'f', string.Concat(dot, dot, dash, dot)},
                {'g', string.Concat(dash, dash, dot)},
                {'h', string.Concat(dot, dot, dot, dot)},
                {'i', string.Concat(dot, dot)},
                {'j', string.Concat(dot, dash, dash, dash)},
                {'k', string.Concat(dash, dot, dash)},
                {'l', string.Concat(dot, dash, dot, dot)},
                {'m', string.Concat(dash, dash)},
                {'n', string.Concat(dash, dot)},
                {'o', string.Concat(dash, dash, dash)},
                {'p', string.Concat(dot, dash, dash, dot)},
                {'q', string.Concat(dash, dash, dot, dash)},
                {'r', string.Concat(dot, dash, dot)},
                {'s', string.Concat(dot, dot, dot)},
                {'t', string.Concat(dash)},
                {'u', string.Concat(dot, dot, dash)},
                {'v', string.Concat(dot, dot, dot, dash)},
                {'w', string.Concat(dot, dash, dash)},
                {'x', string.Concat(dash, dot, dot, dash)},
                {'y', string.Concat(dash, dot, dash, dash)},
                {'z', string.Concat(dash, dash, dot, dot)},
                {'0', string.Concat(dash, dash, dash, dash, dash)},
                {'1', string.Concat(dot, dash, dash, dash, dash)},
                {'2', string.Concat(dot, dot, dash, dash, dash)},
                {'3', string.Concat(dot, dot, dot, dash, dash)},
                {'4', string.Concat(dot, dot, dot, dot, dash)},
                {'5', string.Concat(dot, dot, dot, dot, dot)},
                {'6', string.Concat(dash, dot, dot, dot, dot)},
                {'7', string.Concat(dash, dash, dot, dot, dot)},
                {'8', string.Concat(dash, dash, dash, dot, dot)},
                {'9', string.Concat(dash, dash, dash, dash, dot)}
            };
        }

        public static void getUserInput()
        {
            string input;
            Console.WriteLine("What did you want to say?");
            input = Console.ReadLine();
            input = input.ToLower();
            Console.WriteLine("Your output is: " + translate(input));
            Console.WriteLine("Press enter to end.");
            Console.ReadLine();
        }

        private static string translate(string input)
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            foreach(char character in input)
            {
                if(translator.ContainsKey(character))
                {
                    sb.Append(translator[character] + " ");
                } else if (character == ' ')
                {
                    sb.Append("/ ");
                } else
                {
                    sb.Append(character + " ");
                }
            }
            return sb.ToString();
        }
    }
}


texts: PowerShell - Sort strings containing numbers numerically

texts:
I am a newbie in programming, but I do have potential, I am using PowerShell to hone my skills, I have written a simple function to sort strings consisted of numbers humanly (i.e. in a order like 1 2 10 25 32 123), using the basic concept of padding, I would like to see it be expanded so that it can sort strings containing numbers like "a12b3 c14","a10b5 c12","a5b1 c2" alphanumerically(according to the value of numbers rather than single digits), it is currently above my level, for now, so I want someone more experienced than me to help me expand my code, I will post it below so you can review it:
    function Sort-Num {
 PARAM (
        [Parameter(ValueFromPipeline=$true)]
        [System.String]$String
        )
    Process {
        $array = $String.Split( )
        $padnum = @()
        $sorted = @()
        $numbers = @()
        $length=0
        foreach ($arra in $array) {
            while ($arra.Length -gt $length) {
            $length=$arra.Length
            }
        }
        foreach ($arra in $array) {
            $padded = "{0:D$length}" -f [int64]$arra
            $padnum +=$padded
        }
        $sorted = $padnum | Sort-Object
        foreach ($sorte in $sorted) {
            $number=[int64]$sorte
            $numbers+=$number
        }
        $numbers
    }
}

Edit: My idea is: first split the string by space and create an array of the substrings, then use regex match to find letters and numbers in the substrings, remember their respective position, creating an array of [PSCustomObject], then split the substrings in the first array into substrings of letters and numbers based on regex match recursively, foreach iteration of substrings of substrings create an [PSCustomObject] of the substring according to the order identified in second step, like: [PSCustomObject]@{letter="a";number=12;letter="b";number=3...}
then find the longest number in each column and pad other numbers in the same column to the same length, and then sort the second array and then eliminate the leading zeroes and then rejoin the substrings of the second array and add them to a third array...
Maybe this sounds complex in natural language but this would be much simpler in code, I just haven't figured out how to implement my idea in code, yet...


texts:
This is my first go at a Go program that's not a variation of "Hello {$name}". It's about twice as long as my previous Python implementation, and perhaps an order of magnitude messier.

The goal is to read in /etc/hosts and combine the various entries I've made over time:

127.0.0.1 host1.test
127.0.0.1 host2.test
111.111.111.111 staging.dev otherproject.dev
127.0.0.1 localhost host.test

into:

127.0.0.1 host.test host1.test host2.test localhost
111.111.111.111 otherproject.dev staging.dev

Any thoughts on how to make this cleaner, better, and/or more idiomatic?

package main

import (
    "os"
    "io/ioutil"
    "strings"
    "sort"
)

// Because this doesn't exist?
type StringSet struct {
    set map[string]bool
}

func NewStringSet() StringSet {
    return StringSet{ make(map[string]bool) }
}

// Returns true if added, false if already exists
func (s StringSet) Add(str string) bool {
    _, found := s.set[str]
    s.set[str] = true
    return !found
}
// Returns the hostnames in alphabetical order
func (s StringSet) GetHostnames() []string {
    keys := make([]string, 0, len(s.set))
    for key := range s.set {
        keys = append(keys, key)
    }
    sort.Strings(keys)
    return keys
}

// Because this doesn't exist?
func pop(s []string) (string, []string) {
    var x string
    x, s = s[0], s[1:len(s)]
    return x, s
}

// Returns the lines of a file
func GetLines(filename string) []string {
    raw, err := ioutil.ReadFile("/etc/hosts")
    if err != nil {
        panic(err)
    }
    return strings.Split(string(raw[:]), "\n")
}

func WriteHostsFile(outfile string, hosts map[string]StringSet) bool {
    // Range outputs a random order -.-
    fd, err := os.Create(outfile)

    if err != nil {
        panic(err)
    }

    defer fd.Close()

    fd.WriteString("# Managed by hosts.go\n")

    for k := range hosts {
        names := hosts[k].GetHostnames()
        line := k + " " + strings.Join(names, " ")
        fd.WriteString(line + "\n")
    }

    return true
}

func ProcessHosts(data []string) map[string]StringSet {
    hosts := make(map[string]StringSet)
    for _, line := range data {
        var ip string
        parts := strings.Split(line, " ")

        if len(parts) > 1 {
            ip, parts = pop(parts)
            if ip[0] == '#' {
                continue
            }

            // Check if nil map
            if len(hosts[ip].set) == 0 {
                hosts[ip] = NewStringSet()
            }

            for _, word := range parts {
                hosts[ip].Add(word)
            }
        }
    }
    return hosts
}

func main() {
    data := GetLines("/etc/hosts")
    hosts := ProcessHosts(data)
    WriteHostsFile("hosts", hosts)
}


texts: Designing DAOs that handle composite objects

texts:
Suppose I have following elementary DTOs, each DTO corresponding to a database table:

class Event {
    String name
}
class Player {
    String name
}

DAOs for elementary DTOs:

class PlayerDao {
    def insert(Player p) {
        //sql to insert local members
    }
}
class EventDao {
    def insert(Event e) {
        //sql to insert local members
    }
}

Composite DTO related to other DTOs via foreign keys:

class Game {
    Event e
    Player p
    Date d
}

Now there are two approaches to designing the DAO for game object:

Have the caller hand over entire game object to GameDao and GameDao calls other DAOs to save the child objects.

class GameDao {
    def insert(Game g) {
        eventDao.insert(g.e)
        playerDao.insert(g.p)
        //sql to insert local members
    }
}
class Caller {
    def static main(String[] a) {
        def g = new Game()
        gameDao.insert(g)
    }
}

Make GameDao save only local state of object and leave the responsibility of saving related objects to caller.

class GameDao {
    def insert(Game g) {
        //sql to insert local members
    }
}
class Caller {
    def static main(String[] a) {
        def g = new Game()
        eventDao.insert(g.e)
        playerDao.insert(g.p)
        gameDao.insert(g)
    }
}

Use of an ORM is out of question.

Which design is better and why?


texts: Template for endianness-free code, data always packed as BIG-Endian

texts:
It's been a while since I've been properly grilled about my code.

I had this Idea which should probably never make it into production code but still I couldn't find anything seriously wrong with it at a glance...

All your comments are welcome.

#ifndef BITFIELDMEMBER_H
#define BITFIELDMEMBER_H

/************************************************************************
 * This is for creating Endianness-free bit-fields.
 * The values are always packed as big-endian.
 * When used for arithmetics/comparison, the values are read in the
 * proper endianness for the current CPU mode.
 *
 * Note: The fields can overlap if you want
 */

template<int firstBit, int bitSize>
struct BitFieldMember
{
    typedef BitFieldMember<firstBit, bitSize> self_t;
    typedef unsigned char uchar;
    enum {
        lastBit = firstBit + bitSize - 1,
        mask = (1 << bitSize) - 1
    };
    uchar *selfArray()
    {
        return reinterpret_cast<uchar *>(this);
    }
    const uchar *selfArray() const
    {
        return reinterpret_cast<const uchar *>(this);
    }

    /* used to read data from the field */
    /* will also work with all the operators that work with integral types */
    inline operator unsigned() const
    {
        const uchar *arr = selfArray();
        const uchar *p = arr + firstBit / 8;
        int i = 8 - (firstBit & 7);
        unsigned ret = 0;
        ret |= *p;
        while (i < bitSize)
        {
            ret <<= 8;
            ret |= *(++p);
            i += 8;
        }
        return ((ret >> (7 - (lastBit & 7))) & mask);
    }

    /* used to assign a value into the field */
    inline self_t& operator=(unsigned m)
    {
        uchar *arr = selfArray();
        m &= mask;
        unsigned wmask = ~(mask << (7 - (lastBit & 7)));
        m <<= (7 - (lastBit & 7));
        uchar *p = arr + lastBit / 8;
        int i = (lastBit & 7) + 1;
        (*p &= wmask) |= m;
        while (i < bitSize)
        {
            m >>= 8;
            wmask >>= 8;
            (*(--p) &= wmask) |= m;
            i += 8;
        }
        return *this;
    }

    inline self_t& operator+=(unsigned m)
    {
        *this = *this + m;
        return *this;
    }

    inline self_t& operator-=(unsigned m)
    {
        *this = *this - m;
        return *this;
    }

    inline self_t& operator*=(unsigned m)
    {
        *this = *this * m;
        return *this;
    }

    inline self_t& operator/=(unsigned m)
    {
        *this = *this / m;
        return *this;
    }

    inline self_t& operator%=(unsigned m)
    {
        *this = *this % m;
        return *this;
    }

    inline self_t& operator<<=(unsigned m)
    {
        *this = *this << m;
        return *this;
    }

    inline self_t& operator>>=(unsigned m)
    {
        *this = *this >> m;
        return *this;
    }

    inline self_t& operator|=(unsigned m)
    {
        *this = *this | m;
        return *this;
    }

    inline self_t& operator&=(unsigned m)
    {
        *this = *this & m;
        return *this;
    }

    inline self_t& operator^=(unsigned m)
    {
        *this = *this ^ m;
        return *this;
    }

};
#endif

Usage example:

union header
{
    unsigned char arr[2];       // space allocation, 2 bytes (16 bits)

    BitFieldMember<0, 4> m1;     // first 4 bits
    BitFieldMember<4, 5> m2;     // The following 5 bits
    BitFieldMember<9, 6> m3;     // The following 6 bits, total 16 bits
};

int main()
{
    header a;
    memset(a.arr, 0, sizeof(a.arr));
    a.m1 = rand();
    a.m3 = a.m1;
    a.m2 = ~a.m1;
    return 0;
}

This sometimes wouldn't work for fields that are larger than 24 bits... the shifting may trim the most significant bits.


texts:
The code below is slow. Any thoughts on speeding up?

dict1 = {}
dict2 = {}
list_needed  = []

for val in dict1.itervalues():
    for k,v in d1ct2.iteritems():
        if val == k:
            list_needed.append([val,v])


texts:
I wrote a simple summation program in MARS to practice using loops and jump instructions. I feel like this is pretty lightweight and wanted some feedback on possible improvements:

Lowering instruction count
Organizational changes

Am I correct in assuming this is a "do-while" loop?

# Description: Summation program implementing a do-while loop
# Author: Evan Bechtol

        .data
Prompt: .asciiz "Enter number to get summation: "
Output: .ascii  "Sum of numbers is: "
        .globl main
        .text
main:
    # Prompt for input
    li   $v0, 4
    la   $a0, Prompt
    syscall

    # Read input
    li   $v0, 5
    syscall
    add  $s0, $zero, $v0

    # Begin summation
    addi $s1, $zero, 1 # $s1 used to store summation, starts at 1
    addi $t1, $zero, 1 # $t1 used as counter, starts at 1
    jal  loop          # Go to loop

    # Display
    li   $v0, 4
    la   $a0, Output
    syscall

    li   $v0, 1
    add  $a0, $zero, $s1
    syscall

    # Exit
    la   $v0, 10
    syscall

loop:
    addi $t1, $t1, 1
    add  $s1, $s1, $t1
    bne  $t1, $s0, loop
    jr   $ra


texts:
Here's the challenge description:

  A parking garage charges a $2.00 minimum fee to park for up to three hours.
  The garage charges an additional $0.50 per hour for each hour or part thereof in excess of three hours.
  The maximum charge for any given 24 hour period is $10.00.
  Assume that no car parks for longer than 24 hours at a time.

  Write a Java program that calculates and displays the parking charges for each customer who parked in the garage yesterday.
  Input the number of hours parked for each customer. The number of customers can be fixed using a final constant.

  The program should display the charge for the current customer and should calculate and display the running total of the day's receipts.
  Use a method called calculateCharges to determine the charge for each customer.

Here's my code:

import java.text.DecimalFormat;
import java.util.Scanner;

public class Hwk4B {

    public static void main(String[] args)
    {

        Scanner keyboard = new Scanner(System.in);
        DecimalFormat formatter = new DecimalFormat("$##.00");

        System.out.print("Enter the number of cars parked yesterday: ");
        final int NUMBER_OF_CARS = keyboard.nextInt();

        double hoursParked=0;
        double currentCost=0;
        double totalCost=0;

        for(int count = 1; count<=NUMBER_OF_CARS; count++)
        {
            System.out.print("Enter hours parked for car " + count + ": ");
            hoursParked = keyboard.nextDouble();
            currentCost = calculateCharges(hoursParked); //most recent customer
            totalCost+=currentCost; //Running total
        }

        System.out.println("Most recent customer paid: "   +  formatter.format(currentCost));
        System.out.println("Running total of receipts: " + formatter.format(totalCost));

    }

    public static double calculateCharges (double numHours)
    {

        double garageCost = 0;

        if(numHours<=3)
            garageCost = 2;

        else if(numHours>3 && numHours<=19)
            garageCost = 2.0 + 0.5*(numHours - 3);

        else if (numHours >19)
            garageCost = 10;

        return garageCost;
    }

}


texts:
I always end up creating a quick return statement above a code block if the simple condition of textbox null fields are found. Naturally, these tend to build up the more controls are added. Now I'm staring at this mess of code, and I'm looking for advice as to avoid this very common mistake in the future.

This is the spaghetti code of a small winform C# project that I'm sure will trigger more than a few people:

   if (txtFirst.Text == "" || txtLast.Text == "" || txtGross.Text == "" ||
        txtLessTNT.Text == "" || txtTCI.Text == "" || txtADDTI.Text == "" || txtGTI.Text == "" ||
        txtLessTE.Text == "" || txtLessPPH.Text == "" || txtLessNTI.Text == "" || txtTD.Text == "" ||
        txtTWCE.Text == "" || txtTWPE.Text == "" || txtTATW.Text == "" ||
        txtFirst.Text == " " || txtLast.Text == " " || txtGross.Text == " " ||
        txtLessTNT.Text == " " || txtTCI.Text == " " || txtADDTI.Text == " " || txtGTI.Text == " " ||
        txtLessTE.Text == " " || txtLessPPH.Text == " " || txtLessNTI.Text == " " || txtTD.Text == " " ||
        txtTWCE.Text == " " || txtTWPE.Text == " " || txtTATW.Text == " " || txtID.Text == "" ||
        txtID.Text == " " || txtTIN.Text == "" || txtTIN.Text == " " || txtFrom.Text == " " || txtFrom.Text == "" || txtTo.Text == " " || txtTo.Text == "" || txtCTC.Text == " " || txtCTC.Text == "" || txtCTC.Text == " " || txtPOI.Text == "" || txtPOI.Text == " " || txtDOI.Text == "" || txtDOI.Text == " " || txtDOI.Text == "" || txtAMT.Text == " " || txtAMT.Text == ""
    )

    {
        MessageBox.Show("Cannot enter null values!");
        return;
    }

Surely, there is an easier way to do this that allows the code to be modular and concise that permits the addition of new textbox controls. This happens more often than I'd like to admit and I wish to get rid of this habit once and for all.

Note that, I do have another solution, it's a linq block that iterates through ALL textbox controls in a given form. But what I'm looking for is as I mentioned, code that allows for selection of the controls involved.


texts:
This code load a 40MB txt into a dictionary. It runs in about 40 seconds (sometimes 20, no idea why). Is there a way to make it run under 4 seconds, or hopefully in 1 second?

Sub ScriptDic()

Dim FileNum As Integer
Dim DataLine As String
Dim tmp As Variant
Dim Dict As Object
Dim duplicatecount As Object
Dim key As String
Dim count As Long

Set Dict = CreateObject("Scripting.Dictionary")
Set duplicatecount = CreateObject("Scripting.Dictionary")

Sheets("Control").Cells(5, 3).Value2 = Now
Filename = "C:\Users\MyFolder\Documents\PerformanceTests\MyData.txt"
FileNum = FreeFile()

Open Filename For Input As #FileNum
While Not EOF(FileNum)
    Line Input #FileNum, DataLine ' read in data 1 line at a time
    tmp = Split(DataLine, Chr(9))
    key = tmp(7) & "-" & tmp(8)
    If Not Dict.exists(key) Then
        Dict.Add key, tmp
        duplicatecount.Add key, 1
    Else
        count = duplicatecount(key)
        duplicatecount.Remove (key)

        Dict.Add key & ">" & count, tmp
        duplicatecount.Add key, count + 1
    End If
Wend

Sheets("Control").Cells(6, 3).Value2 = Now
End Sub


texts: Async tcp socket client: send multiple requests with one connection

texts:
I'm new to socket programming and c++. I have a the following method that sends an array to server and receives sum of the array, I tried to make it async.
std::future<void> AsyncClient::ReqSum(const std::vector<double>& numbers)
{
    return std::async(
        std::launch::async,
        [&, numbers]()
        {
            // Setup connection. Can move to seperate method?
            boost::asio::io_service _ioservice;
            tcp::socket _socket(_ioservice);
            _socket.connect(m_endpoint);

            std::string requestJson = Serializer::ArraySumRequest(numbers);
            boost::system::error_code err;

            boost::asio::write(_socket, boost::asio::buffer(requestJson), err);
            if (err)
            {
                std::stringstream ss;
                ss << "Couldn't write to socket! error code: " << err;
                throw ss.str();
            }

            // getting response from server
            boost::asio::streambuf receiveBuffer;
            boost::asio::read(_socket, receiveBuffer, boost::asio::transfer_all(), err);

            if (err && err != boost::asio::error::eof)
            {
                std::stringstream ss;
                ss << "Receiving from the server failed! error code: " << err.message();
                throw ss.str();
            }

            const char* data = boost::asio::buffer_cast<const char*>(receiveBuffer.data());

            rapidjson::Document doc;
            doc.Parse<rapidjson::kParseDefaultFlags>(data);

            if (!doc.HasMember("result"))
                throw "No result found!";

            double result = doc["result"].GetDouble();

            std::cout << "Sum of the array: " << result << std::endl;

            _socket.shutdown(boost::asio::socket_base::shutdown_both);
            _socket.close();
        });
}

Actually I want to know is it possible to use one connection to for multiple requests(i.e move that socket and connection to another method)?
And if there are any fixes to my code please let me know.


texts:
This is the Good Numbers problem at Code Chef:

  A number is called a square-free number if there does not exist a number greater than 1, whose square divides the number. For example, 8 is not a square-free number as 4 (the square of 2) divides 8. Similarly, 4 is not a square-free number. However, 1, 3, and 6 are all square-free numbers.

  A number \$n\$ is called a good number if the following properties hold:

  It is a square-free number.
  Let \$s\$ denote the sum of all divisors of \$n\$ (including the trivial divisors 1 and \$n\$). Let \$c\$ denote the number of prime numbers dividing \$s\$. Number \$c\$ should be a prime number.

  You are given two numbers \$L\$ and \$R\$, and you have to find the sum of divisors (including the trivial divisors) of all the good numbers in the range \$L\$ to \$R\$ inclusive.

  Input

  The first line of the input contains an integer \$T\$ denoting the number of test cases. The description of \$T\$ test cases follows.

  The only line of each test case contains two space separated integers \$L\$ and \$R\$ denoting the range for which you have to find sum of divisors of good numbers.

  Output

  For each test case, output a single line corresponding to answer of the test case.

  Example

  Input:

2
1 5
6 10

  Output:

6
30

  Explanation

  These numbers in the range 1 to 10 are square-free numbers: 1, 2, 3, 5, 6, 7, 10.
  The sum of their divisors is 1, 3, 4, 6, 12, 8, 18 respectively.
  The number of prime divisors of their sum of divisors is 0, 1, 1, 2, 2, 1, 2 respectively.
  So, the numbers 5, 6, and 10 are good numbers.

  Example case 1. The only good number in the range 1 to 5 is 5. The sum of divisors of 5 is 6.

  Example case 2. In the range 6 to 10, the numbers 6 and 10 are good. The sum of their divisors is 12 + 18 = 30.

How can I improve my code? It is taking too much time to execute (5–20 seconds). Where the time limit is 1 second.

My code:

finds square free integers,
gets the sum of the unique divisors of the number,
Finds the amount of prime divisors for (2).

import time
start_time = time.time()
n=int(input())

for t in range(n):
 v=[]
 a,b=[int (x) for x in input().strip().split(' ')]
 for u in range(a,b+1):
        if u==1:
            v.append(u)
        elif u>1:
            for k in range(2,u):               # to find the square free no's
                if(u%(k**2)==0 and u>=(k**2)):

                    break;
            else:

                    v.append(u)
 sd=[]
 pd=[]
 for j in v:
    s=0

    for k in range(1,j+1):
        if j%k==0:
            s=s+k   #gives the no. of divisor for each square free no
    sd.append(s)

 for k in sd:  #This part is for finding the no of prime divisors for each square free no.
  count=[]
  for x in range (1,k):
   for u in range(2,x):
      if x%u==0 :
          break
   else :

       if (x!=1 and k%x==0):
         count.append(x)

  pd.append(len(count))  #counts the no of prime divisor

 pos=0
 su=0
 for j in pd:

    if j<=1:
      pos=pos+1
    else:

      su=su+sd[pos]
      pos=pos+1
 print(su)      #prints the sum of divisor of good numbers
print("---%s seconds ---" % (time.time() - start_time))


texts: Make this Ruby array pivot more efficient?

texts:
A puzzle I was given:

  Description:

  Write a method that returns the "pivot" index of a list of integers.
  We define the pivot index as the index where the sum of the numbers on
  the left is equal to the sum of the numbers on the right. Given [1, 4,
  6, 3, 2], the method should return 2, since the sum of the numbers to
  the left of index 2 is equal to the sum of numbers to the right of
  index 2 (1 + 4 = 3 + 2). If no such index exists, it should return -1.
  If there are multiple pivots, you can return the left-most pivot.
  You can write the method in any language.

  Make sure that the method:

  runs successfully
  handles all edge cases
  is as efficient as you can make it!

Apparently my solution is not efficient enough:

def pivot(arr)
  results = []
  arr.each_with_index do |n,index|
    last      = arr.size - 1
    sum_left  = arr[0..index].inject(:+)
    sum_right = arr[index..last].inject(:+)
    results << index if sum_left == sum_right
  end
  results.any? ? results.first : -1
end


texts:
This is my array implementation on stack in Java. It involves push, pop, get and growth when limit of array size is reached.

I am a self-taught programmer starting to learn data structures and algorithms.

I am looking for

any recommendation on conventions
an honest opinion on how bad this piece of code if this is an interview.
anything wrong and room for improvement.

I wrote this code myself, not looking at any other similar questions on Code Review.

public class stackAlist{
    int[] data;
    int size;
    static int growthmultipler = 1;

    public stackAlist(){
        data = new int[2*growthmultipler];
        size = 0;
    }

    public void push(int value){
        if(this.size == 0){
            this.data[0] = value;
            this.size += 1;
            this.growthmultipler = 1;
            }
        else if(this.size == 2*growthmultipler){
            growthmultipler += 1;
            stackAlist newlist = new stackAlist();
            newlist.data = new int[2*growthmultipler];
            System.arraycopy(this.data, 0, newlist.data, 0, this.size);
            this.data = newlist.data;
            this.data[size] = value;
            this.size += 1;
        }
        else{
        this.data[size] = value;
        this.size += 1;
        }
    }

    public void pop(){
        this.data[size-1] = 0;
        this.size = this.size-1;
    }

    public void get(){
        int i;
        for(i =0; i < this.size; i++){
            System.out.println(data[i]);
        }
    }

    public static void main(String[] args){
        stackAlist a = new stackAlist();
        a.push(1);
        a.push(2);
        a.get();
        a.pop();
        a.get();
        a.push(3);
        a.push(4);
        a.get();
    }
}


texts: Moving or copying images from a flat directory to subdirectories

texts:
I have a huge Google Photos directory that is difficult to navigate - there are just too many files so I thougt I need to sort them somehow. I decided to make it simple and group them by date-taken. As I always wanted to learn python I thought I'll give it a try so this is my first take on it.

There is no rocket-science here (yet). It looks for files in the pictures_path, groups them by their modified date, enumerates this iterator, creates directories and moves or copies files according to the whatif option. This is measured by the perf_counter().

I'd be great if you could take a look at it and tell me whether I did something terribly wrong as a beginner before I let it work with my actual collection.

import os
import time
import itertools
import shutil
from pprint import pprint

def format_filemtime(path):
    filemtime = os.path.getmtime(path)
    return time.strftime('%Y-%m-%d', time.gmtime(filemtime))

def group_pictures(whatif=False):
    pictures_path = "C:\\temp\\picturepy\\pictures\\"
    galleries_path = "C:\\temp\\picturepy\\galleries\\"

    start = time.perf_counter()

    picture_names = os.listdir(pictures_path)

    print(f"picture count: {len(picture_names)}")

    pictures_by_mtime = itertools.groupby(picture_names, lambda name: format_filemtime(os.path.join(pictures_path,name)))

    for (dir, picture_names) in pictures_by_mtime:
        path_dir = os.path.join(galleries_path, dir)
        if not os.path.exists(path_dir):
            os.makedirs(path_dir)
            print(f"'{dir}' created.")
        else:
            print(f"'{dir}' already exists.")

        do = shutil.copyfile if whatif else shutil.move
        verb = "copied" if whatif else "moved"

        for file in picture_names:
            do(
                src=os.path.join(pictures_path, file),
                dst=os.path.join(path_dir, file))
            print(f"\t'{file}' {verb}.")

    end = time.perf_counter()
    elapsed = round(end - start,2)
    print(f"elapsed: {elapsed} sec")

# --- --- ---

def main():
    group_pictures(whatif=True)
    #group_pictures()

if __name__ == '__main__':
    main()

I tested it with VSCode and it's doing its job pretty well.


texts: Find all starting indices in a string which are anagrams of a word

texts:
The task:

  Given a word W and a string S, find all starting indices in S which
  are anagrams of W.

  For example, given that W is "ab", and S is "abxaba", return 0, 3, and
  4.

My solution:

    const anagramOccurrencesOf = (w, s) => {
      const occurrencesCopy = [];
      let sCopy = s.slice(0);

      let index = 0;
      while (sCopy.length && index !== -1) {
        index = sCopy.indexOf(w);
        if (index === -1) { break; }
        occurrencesCopy.push((occurrencesCopy[occurrencesCopy.length - 1] + index + 1 || 0));
        sCopy = sCopy.slice(index + 1);
      }
      const occurrencesReverse = [];
      let sReverse = s.split('').reverse().join('');

      index = 0;
      while (sReverse.length && index !== -1) {
        index = sReverse.indexOf(w);
        if (index === -1) { break; }
        occurrencesReverse.push( (occurrencesReverse[occurrencesReverse.length - 1] - w.length - index + 1) || s.length - w.length);
        sReverse = sReverse.slice(index + 1);
      }

      return [...occurrencesCopy, ...occurrencesReverse].sort((a,b) => a -b);
    };

    console.log(anagramOccurrencesOf("ab", "abxaba"));

EDIT: The solution above would find indexes of palindromes. The solution below should find indexes of anagrams:

const sortAlphabetically = x => x.toLowerCase().split('').sort().join('')
const getIndexOfAnagramIn = (s, w) => {
  const wSorted = sortAlphabetically(w);
  const result = []
  for (let i = 0; i < s.length + 1 - w.length; i++) {
    if (sortAlphabetically(s.slice(i, i + w.length)) === wSorted) {
      result.push(i);
    }
  }
  return result;
}

console.log(getIndexOfAnagramIn('abxaba', 'ab'));


texts: Rendering the AuthorName using the DOMParser to read XML

texts:
I need to concatenate the LastName and Initials and all of that authors affiliations. Is there a better way or faster way to do this?  I'm very new to working XML in JavaScript.

This is a portion of an XML string that I get back from an API that I parse in JavaScript:

   <AuthorList CompleteYN="Y">
                <Author ValidYN="Y">
                    <LastName>Basree</LastName>
                    <ForeName>Mustafa M</ForeName>
                    <Initials>MM</Initials>
                    <AffiliationInfo>
                        <Affiliation>The Cancer Center...</Affiliation>
                    </AffiliationInfo>
                </Author>
                <Author ValidYN="Y">
                    <LastName>Shinde</LastName>
                    <ForeName>Neelam</ForeName>
                    <Initials>N</Initials>
                    <AffiliationInfo>
                        <Affiliation>The Comprehensive..</Affiliation>
                    </AffiliationInfo>
                </Author>
                <Author ValidYN="Y">
                    <LastName>Koivisto</LastName>
                    <ForeName>Christopher</ForeName>
                    <Initials>C</Initials>
                    <AffiliationInfo>
                        <Affiliation>Hollings ...</Affiliation>
                    </AffiliationInfo>
                    <AffiliationInfo>
                        <Affiliation>Department ...</Affiliation>
                    </AffiliationInfo>
                </Author>
                <Author ValidYN="Y">
                    <LastName>Cuitino</LastName>
                    <ForeName>Maria</ForeName>
                    <Initials>M</Initials>
                    <AffiliationInfo>
                        <Affiliation>Hollings...</Affiliation>
                    </AffiliationInfo>
                    <AffiliationInfo>
                        <Affiliation>Department ..</Affiliation>
                    </AffiliationInfo>
                </Author>
</AuthorList>

my Code:

      let HTMLContent = ""
      parser = new DOMParser();
      xmlDoc = parser.parseFromString(response.data, "text/xml");

      const AuthorsInfo = xmlDoc.querySelectorAll("Author");

      AuthorsInfo.forEach(a => {
        let affiliations = "";
        let AuthorName = "";

        for (var i = 0; i < a.children.length; i++) {
          let tt = a.children[i].nodeName;
          let t = a.children[i].textContent;
          if (tt === "AffiliationInfo") {
            affiliations += a.children[i].textContent;
            affiliations += "

";
          } else if (tt === "LastName") {
            AuthorName = a.children[i].textContent;
          } else if (tt === "Initials") {
            AuthorName += " " + a.children[i].textContent;
            AuthorName += "

";
          }
        }
        HTMLContent  += AuthorName + " " + affiliations;
      });


texts: Method to get user information (OOP / MVC approach)

texts:
I coded a small user script with PHP. I'm improving the script, learning from my mistakes. I recently learned about object oriented programming and wrote 2 big god classes (user class and message class). That didn't feel right, so read about the MVC model. I wrote a controller class to handle the big god classes while being easy to use in the views (I want to be able to rewrite the big god classes without rewriting the views).

This controller class allows me to streamline my big god classes, which is exactly what I wanted to achieve.

I'm replacing the method user_search() with user_search_info(). It should return a row of user information based on the given user_id or user_id. It should return false if the query fails or returns empty. When I am satisfied, I will delete user_search().

The new method works like I want it to, and I find it very elegant and easy to read. But is it the right approach? I'm sure there's still room for improvement.

This is from the user class file:

  class user{
    // new methods don't care about this anymore so this will get deleted
    public $logs = array();

    // ... irrelevant methods left out ...

    // old method
    public function user_search($db_connection, $user_id=null, $username=null){
      $result = false;
      if($user_id == null && $username == null)
        $this->logs[] = "No information to search on has been found.";
      elseif($db_connection == false)
        $this->logs[] = "Something went wrong with the database.";
      else{
        $this->logs[] = "Searching the user in the database.";
        $query_user_search = $db_connection->prepare('SELECT * FROM users WHERE user_username=:user_username OR user_id=:user_id');
        $query_user_search->bindValue(':user_username', $username, PDO::PARAM_STR);
        $query_user_search->bindValue(':user_id', $user_id, PDO::PARAM_STR);
        $query_user_search->execute();
        if($result = $query_user_search->fetch())
          $this->logs[] = "We found the user.";
        else
          $this->logs[] = "We didn't find the user.";
      }
      return $result;
    }

    // new method
    public function user_search_info($db_con, $user_id=null, $user_username=null){
      $query_user_search_info = $db_con->prepare('SELECT * FROM users WHERE user_username=:user_username OR user_id=:user_id');
      $query_user_search_info->bindValue(':user_id', $user_id, PDO::PARAM_STR);
      $query_user_search_info->bindValue(':user_username', $user_username, PDO::PARAM_STR);
      $query_user_search_info->execute();
      return $query_user_search_info->fetch();
    }
  }

And this is from the controller class file:

public function return_user_search_info($search_user_variable, $search_user_value)
{
  $user_search_info = false;
  if($search_user_variable == "user_id")
    $user_search_info = $this->user->user_search_info($this->db_con, $search_user_value, "");
  elseif($search_user_variable == "user_username")
    $user_search_info = $this->user->user_search_info($this->db_con, "", $search_user_value);
  return $user_search_info;
}


texts:
From the HackerRank question definition:

  The word google can be spelled in many different ways.

  E.g. google, g00gle, g0oGle, g<>0gl3, googl3, GooGIe etc...

  Because

  g = G

  o = O = 0 = () = [] = <>

  l = L = I

  e = E = 3

  That's the problem here to solve.

  And the match has to be only this single word, nothing more, nothing
  less.

  E.g.

  "g00gle" = True, "g00gle " = False, "g google" = False, "GGOOGLE" =
  False, "hey google" = False

What I'm looking in review: How can I make my code more pythonic?

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import re

g = ["g", "G"]
o = ["o", "O", "0", "()", "[]", "<>"]
l = ["l", "L", "I"]
e = ["e", "E", "3"]

regex = (g, o, o, g, l, e)
regex = ((re.escape(y) for y in x) for x in regex)
regex = ("(?:{})".format("|".join(x)) for x in regex)
regex = "^{}$".format("".join(regex))

print(bool(re.match(regex, input())))


texts: More efficient way to narrow down a range

texts:
I need to get data from a spreadsheet where there are three parameters.  A product ID which is multiple rows, within the rows of product ID, there is another set of rows with the charge type, within that set of rows, there is a charge I want to find, which may also span multiple rows.  If the charge does span multiple rows, I take the first one.

I have a function called New_Rng which takes the sheet object, the range within the sheet to be searched, and the string to look for, and returns the range which encompasses the first and last occurrence of the search string.

I'm doing multiple calls to wind up with the value that I need, but I know it's not efficient.

This is what I have now:

dim fndRng as range
dim shtz as new workshseet
dim ctr as long

    ctr = 4

    set shtz = sheets("DATA")

    Set fndRng = shtz .range(StartRange, shtz .Cells(LastRow,LastColumn))

    If Not fndRng Is Nothing Then Set fndRng = New_Rng(shtz, fndRng, shtz.Cells(ctr, searchVal)

    If Not fndRng Is Nothing Then Set fndRng = fndRng.Offset(0, (SchCol1 - SchCol2))
    If Not fndRng Is Nothing Then Set fndRng = New_Rng(shtz, fndRng, SVal2)
    If Not fndRng Is Nothing Then Set fndRng = fndRng.Offset(0, (SchCol2 - SchCol3 ))
    If Not fndRng Is Nothing Then Set fndRng = New_Rng(shtz, fndRng, val3)
    If Not fndRng Is Nothing Then Set fndRng = fndRng.Offset(0, (SchCol3  - SchCol4))
    If Not fndRng Is Nothing Then
        For Each zell In fndRng
            If zell.Row = fndRng.Row Then LoadVar(ctr, 0) = zell.value
        Next zell
    End If

I know there's a better way, but I can't figure it out.


texts:
I wrote this function to test if one string is a substring of another.

I'm curious to get some feedback on the implementation - does my solution seem reasonable? Is the code "well written"? Is there a better way of doing this?

<?php
function isSubStr($a, $b){
    if(!strpos($a, $b[0])){
        return false;
    }
    $result = true;
    $start = strpos($a, $b[0]);
    for ($pos = 0; $pos < strlen($b); $pos++){
            if($b[$pos] != $a[$start + $pos]){
                $result = false;
            }
    }
    return $result;
}

Tests below:

<?php
require 'solution.php';
use PHPUnit\Framework\TestCase;

class myTests extends TestCase {
  public function testExamples() {
        $this->assertEquals(isSubStr('cat', 'at'), true);
        $this->assertEquals(isSubStr('cat', 'fluffy'), false);
        $this->assertEquals(isSubStr('cheeze', 'ee'), true);
        $this->assertEquals(isSubStr('snow', 'o'), true);
        $this->assertEquals(isSubStr('octopus', 'top'), true);
        $this->assertEquals(isSubStr('octopus', 'zzz'), false);
  }
}


texts:
I have a function that I intend to use for validating zip codes and I wanted to know if my way could be made better.

function zipcode (inputtxt)
{
    var zipcode = /^\+?([0-9]{2})\)?[-. ]?([0-9]{4})[-. ]?([0-9]{4})$/;

    if((inputtxt.value.match(zipcode))
        {
          return true;
        }
        else
        {
            alert("message");
            return false;
        }
}


texts:
This draws blocks on the screen from a grid to make a background for my game. I am wondering if anyone has any suggestions on optimizing it for speed.

int blockwidth=blocksize-2;
//Draw coloured blocks
for (int x=0;x<sizex;x++){
   int screenx=-(int)camerax+(x*blocksize);
      if (screenx>-blocksize && screenx<gamewidth){
        for (int y=0;y<sizey;y++){
          int screeny=-(int)cameray+(y*blocksize);
          if (screeny>-blocksize && screeny<gameheight){
            if (tiles[x][y][0]>0){
                g.setColor(new Color( tiles[x][y][1]));
                //g.fillRect(screenx,screeny,blockwidth,blockwidth);
                g.drawImage(Iloader.Imagelist.get(0), screenx,screeny, screenx+blockwidth,screeny+blockwidth, graphicsize,0,graphicsize*2,graphicsize, null);
            } else {
                //g.setColor(new Color( tiles[x][y][1]  | 0xFFFF0000));
                g.setColor(new Color( tiles[x][y][1]));
                g.fillRect(screenx,screeny,blockwidth,blockwidth);

            }
          }
        }
    }
 }


texts:
I'm learning F#.
The code below gets a number e.g. 100 and list of factors and should divide that number by the factors without any rest. (There is an actual code I've got in C#, but this is F# port).

I especially didn't liked equalsDifference function.. any better solution?

namespace RozbijaczApp
module Rozbijacz =
    let precision = 2

    let minUnit = 1m / (pown 10m precision)

    let round x = System.Math.Round(decimal x, precision, System.MidpointRounding.AwayFromZero)

    let mainMapper factor factorSum x =
        round (x * factor / factorSum)

    let equalsDifference minUnit (difference: decimal) (l: decimal list) =
        let listSize = List.length l
        let mutable acc = difference

        [for i in [0..listSize-1] do
            let element = l |> List.item i
            if acc <> 0m then
                if difference < 0m then
                    if element >= minUnit then
                        acc <- acc + minUnit
                        yield element - minUnit
                    else
                        yield element
                else
                    acc <- acc - minUnit
                    yield element + minUnit
            else
                yield element
        ]

    let divider (number:decimal) factors =
        let factorsSum = factors |> List.sum
        let result = factors |> List.map (fun x -> mainMapper number factorsSum x)
        let controlSum = result |> List.sum
        let difference = number - controlSum
        printfn "Difference %O" difference
        // add or substract diffenernce by minUnit for results
        let fixResult = equalsDifference minUnit difference result
        let finalControlSum = fixResult |> List.sum
        let finalDifference = number - finalControlSum
        printfn "Final difference %O should by zero"finalDifference

        fixResult

and usage:

        let factors = [0.2m;0.3m;0.4m]
        let results = Rozbijacz.divider 100m factors
        printfn "Result: %A" results

ok, as you suggested map is better:

let equalsDifference minUnit (difference: decimal) (l: decimal list) =
    let listSize = List.length l
    let mutable acc = difference

    let resp = l |> List.map (fun element -> (
        if acc <> 0m then
            if difference < 0m then
                if element >= minUnit then
                    acc <- acc + minUnit
                    element - minUnit
                else
                    element
            else
                acc <- acc - minUnit
                element + minUnit
        else
            element
        ) )
    resp

But is this enough? Any F# magic?


texts:
In the world of casinos, there are different types of games and jackpots. In this example, there are normal jackpots, multi-casino jackpots. I have a separate model for each of these. I need to display these in-line with each other. For instance, I'm grabbing the top 10 Caribbean Stud jackpots (Model: Jackpot), then displaying the top 10 multi-casino Caribbean stud jackpots (Model: MultiJackpot), and then displaying the top 10 Blackjack jackpots (Model: Jackpot) followed by the top 10 multi-casino Blackjack jackpots (Model: MultiJackpot).

I have two main problems with a chunk of code: I need to interpolate 2 different models in a specific order in a list.

This is a simplified example, but I have a similar scenario with slot jackpots where the models differ even more, which is preventing me from merging the models themselves.

Currently (and very inefficiently) I am doing 1 database call for each game and assigning it to its own instance variable for the view.

@caribbean_stud =                   Jackpot.where(:jackpot_game_id => JackpotGame.find_by_name("Caribbean Stud")).order("prize DESC").limit(10)
@multi_caribbean_stud =             MultiJackpot.where(:multi_jackpot_game_id => MultiJackpotGame.find_by_name("Caribbean Stud")).order("prize DESC").limit(10)
@progressive_blackjack =            Jackpot.where(:jackpot_game_id => JackpotGame.find_by_name("Progressive Blackjack")).order("prize DESC").limit(10)
@multi_progressive_blackjack =      MultiJackpot.where(:multi_jackpot_game_id => MultiJackpotGame.find_by_name("Progressive Blackjack")).order("prize DESC").limit(10)

In the view, I'm taking each instance variable and hard coding the order/interpolation.

The obvious 2 problem I'm running into:

Many more database calls than necessary (I have over 30 games I'm doing this for)
The view is not DRY (I could move the output for each model here into a partial, but I'm still hard coding the actual order & interpolation.)


texts: Print limited previous lines from a file

texts:
This is a question from careercup.com. Given a word w and a number k.Find k words in the file occurring before occurrence of w.Assume that the average word size is m in the file
eg.
aaa
bbb
ccc
booking
alpha
beta
gamma

for k=3 and w = booking
the output should be [aaa,bbb,ccc,booking]
similarly for k =2 and w = beta
output should be [booking,alpha,beta]
Assume that the file size can grow very large
and try to get solution with space complexity lesser than O(n)

package com.careercup;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class LimitedLengthQueue {

    private List<String> innerStore;
    private int size;
    private static final String FILENAME="C:/filepath.txt.txt";
    public LimitedLengthQueue(int size) {
        this.innerStore = new ArrayList<>();
        this.size = size;
    }

    boolean add(String s){
        if(innerStore.size() == size){
            innerStore.remove(0);
            innerStore.add(s);
            return true;
        }
        innerStore.add(s);
        return true;
    }

    public static void main(String[] args) throws FileNotFoundException, IOException  {
        LimitedLengthQueue inputQueue = new LimitedLengthQueue(Integer.parseInt(args[0]));
        String key = args[1];

        try( FileReader fr = new FileReader(FILENAME);
             BufferedReader br = new BufferedReader(fr)){

            String input = null;

            while( (input = br.readLine()) != null){

                if(key.equals(input.trim())){
                    inputQueue.innerStore.forEach(System.out::println);
                    System.out.println(input);
                    break;
                }
                inputQueue.add(input);
             }
        }
    }
}


texts:
So, I've recently started learning OOP in PHP and learned $this keyword. I know it's a reference to the current object. So I wrote a class and couple of functions in it.

<?php
Class Connection{
var $databaseHost;
var $databaseUsername;
var $databasePassword;
var $databaseName;

var $query,$result,$conn,$rows;

function setVariables($databaseHost,$databaseUsername,$databasePassword,$databaseName){
    $this->databaseHost=$databaseHost;
    $this->databaseUsername=$databaseUsername;
    $this->databasePassword=$databasePassword;
    $this->databaseName=$databaseName;
}

function playingWithDatabase(){
    $this->conn = new PDO("mysql:host=$this->databaseHost;dbname=$this->databaseName;", $this->databaseUsername, $this->databasePassword);
    $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    //Connect
    try{
        $this->result = $this->conn->prepare("SELECT * FROM student_data");
        $this->result->execute();
        $this->rows = $this->result->fetch(PDO::FETCH_NUM);
        //Dirty Debug
        echo " Displaying First Record

";
        echo $this->rows[1];
        echo "
";
        echo $this->rows[2];
        echo "
";
        echo $this->rows[4];
        echo "
";
        echo $this->rows[6];
        echo "
";
    }
    catch (Exception $e){
        echo "Failure";
    }
    return $this->rows;
}

So, as you can see I took a C# approach to get and set except I'm trying to set in another function and trying to connect to the database in that function.

I feel I'm doing a redundant job here.

  Shall I reduce the usage $this and if yes, How so?
  How will a professional PHP developer will do it?