texts:
This is my first winsock TCP listener ever written. I can use it for a small framework.

tcp_listener.h:

#pragma once
#include <WinSock2.h>
#include <thread>
class tcp_listener
{
public:
    tcp_listener(std::function< void(SOCKET) > callback);
    void start(unsigned short port);
private:
    SOCKET server;
    std::thread accept_thread;

    std::function< void(SOCKET) > callback;
};

tcp_listener.cpp:

#pragma comment(lib, "Ws2_32.lib")

#include "tcp_listener.h"
#include <iostream>
tcp_listener::tcp_listener(std::function< void(SOCKET) > callback)
{
    this->callback = callback;

    WSADATA wsa;

    if (WSAStartup(MAKEWORD(2, 2), &wsa) == SOCKET_ERROR)
    {
        std::cerr << "Cannot startup WSA: " << WSAGetLastError() << std::endl;
    }
    else
    {
        server = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    }
}

void tcp_listener::start(unsigned short port)
{
    if (server != SOCKET_ERROR)
    {
        SOCKADDR_IN sock_addr;
        sock_addr.sin_port = htons(port);
        sock_addr.sin_family = AF_INET;
        sock_addr.sin_addr.s_addr = htonl(INADDR_ANY);

        if (bind(server, (SOCKADDR*)&sock_addr, sizeof(sock_addr)) == SOCKET_ERROR)
        {
            std::cerr << "Cannot bind socket on port " << port << std::endl;
            return;
        }

        if (listen(server, 10) == SOCKET_ERROR)
        {
            std::cerr << "Cannot listen to socket." << std::endl;
            return;
        }

        accept_thread = std::thread([&]() {
            SOCKET client = SOCKET_ERROR;

            while (client == SOCKET_ERROR)
            {
                client = accept(server, NULL, NULL);

                if (client != SOCKET_ERROR)
                {
                    callback(client);

                    client = SOCKET_ERROR;
                }
            }
        });

        accept_thread.detach();
    }
    else
    {
        std::cerr << "Socket not set." << std::endl;
    }
}

How to use it:

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

void on_accept(SOCKET client)
{
    std::cout << "blabla new connection" << std::endl;

}

int main()
{
    tcp_listener* listener = new tcp_listener(on_accept);
    listener->start(1232);

    getchar();

    return 1;
}

I still have to make a new class where the SOCKET is stored and the IP etc. like system.net.sockets.Socket and use that as callback.

Also I'd like to get a review on my naming convention.


texts: Check if two strings are anagrams - HackerEarth

texts:
You are given two strings. You have to check if the strings are permutations of each other and output "YES" or "NO" accordingly without quotes.

  Input:
  2 lines of input each containing a string. (a to z and 0 to 9)

  Output:
  A single line containing YES or NO.

  Constraints:
  String would not contain any spaces. size of string < 100

Here is my code:

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

char sort(int n, char str[])
{
    int i,j,swap;
    for(i=0;i<n-1;i++)
    {
        for(j=0;j<n-i-1;j++)
        {
            if(str[j]>str[j+1])
            {
                swap=str[j];
                str[j]=str[j+1];
                str[j+1]=swap;
            }
        }
    }
}
int main()
{
    char str1[100],str2[100];
    scanf("%s %s",&str1,&str2);
    sort(strlen(str1),str1);
    sort(strlen(str2),str2);
    if(strcmp(str1,str2)==0)
        printf("YES\n");
    else
        printf("NO\n");
    return 0;
}

How do I make this code as small (shorter code) as possible?


texts: Java hashcode without using the Object#hashCode method

texts:
For an assignment I have to make a HashTable using double hashing, but for the hashing part I am not allowed to use Object#hashCode(), so I have to write my own.

So far I have the following code and I am looking for feedback if I am on the right track or if I should go for a different approach (see hash and hash2 methods).

public class DoubleHashing<Key, Value> {

private int N;
private int M;
private Key[] keys;
private Value[] vals;

public DoubleHashing(final int capacity) {
    M = capacity;
    keys = (Key[]) new Object[M];
    vals = (Value[]) new Object[M];
}

public int hash(final Key key) {
    int hashKey = 0;
    if (key instanceof String) {
        final String k = (String) key;
        for (int i = 0; i < k.length(); i++) {
            int charCode = k.charAt(i);
            hashKey = ((hashKey * 27) + charCode) % M;
        }
    }
    return hashKey;
}

public int hash2(final Key key) {
    int hashKey = 0;
    if (key instanceof String) {
        final String k = (String) key;
        for (int i = 0; i < k.length(); i++) {
            int charCode = k.charAt(i);
            hashKey = 5 - ((hashKey * 27) + charCode) % 5;
        }
    }
    return hashKey;
}

public void put(final Key key, final Value val) {
    if (N == M) {
        System.err.println("Table is full");
        return;
    }
    int i;
    for (i = hash(key); keys[i] != null; i = (i + 1) % M)
        if (keys[i].equals(key)) { vals[i] = val; return; }
    keys[i] = key;
    vals[i] = val;
    N++;
}

public Value get(final Key key) {
    for (int i = hash(key); keys[i] != null; i = (i + 1) % M)
        if (keys[i].equals(key))
            return vals[i];
    return null;
}

public int size() {
    return N;
}
}


texts:
var a = ["a", "b", "c", "d"]
var res = {}
var value = "Hello"
for(var i=a.length; i > 0; i-- ){
  var item = a[i-1]
  var temp = {}
  temp[item] = i == a.length ? value : {}
  if(i != a.length){
    Object.keys(res).forEach(r => {
      temp[item][r] = res[r]
    })
  }
  res = temp
}

console.log(res)

The result is :

{
  "a": {
    "b": {
      "c": {
        "d": "Hello"
      }
    }
  }
}

Which is right, exactly what I need. I was just wondering if I'm doing it the right way or is there any better solutions for this?

Thanks in advance.


texts: ServiceLocator for easy and central access to replaceable parts

texts:
For a bigger project of mine, I needed a simple and extensible solution for easy access to replaceable Parts.

This example will show the usage:

Define an Interface, describing the replaceable part Eg: IReportSender
Define the concrete EMailReportSender and TelegramReportSender
Both will be implementing the IReportSender
On Startup (or anywhere else in the Application) add it to the ServiceLocator:

ServiceLocator.getServiceLocator().addService(IReportSender.class, new EMailReportSender());

Anywhere else in the application get the Service and use it:

IReportSender reportSender = ServiceLocator.getServiceLocator().getService(IReportSender.class);
reportSender.SendReport([...]);

And now the Code:

import java.util.HashMap;

public class ServiceLocator {

    private static ServiceLocator instance;
    private HashMap<Class<?>, Object> services;

    /**
     * Creates a new instance of the {@link ServiceLocator}
     */
    private ServiceLocator() {
        services = new HashMap<Class<?>, Object>();
    }

    /**
     * Gets the {@link ServiceLocator}
     * @return the current {@link ServiceLocator}
     */
    public static ServiceLocator getServiceLocator() {
        if (instance == null) {
            instance = new ServiceLocator();
        }

        return instance;
    }

    /**
     * Adds a service
     * @param clazz class of the defining interface
     * @param service instance of the actual implementation
     * @return true, if the service was added, otherwise false
     */
    public boolean addService(Class<?> clazz, Object service) {
        if (services.containsKey(clazz) || !clazz.isAssignableFrom(service.getClass())) {
            return false;
        }

        services.put(clazz, service);

        return true;
    }

    /**
     * Gets a service
     * @param clazz class of the defining interface
     * @param <T> defining interface
     * @return instance of the actual implementation
     */
    public <T> T getService(Class<T> clazz) {
        if (!services.containsKey(clazz)) {
            return null;
        }

        Object service = services.get(clazz);
        return clazz.cast(service);
    }

    /**
     * Removes a service
     * @param clazz class of the defining interface
     * @return true, if the service was removed, otherwise false
     */
    public boolean removeService(Class<?> clazz) {
        if (!services.containsKey(clazz)) {
            return false;
        }

        services.remove(clazz);

        return true;
    }

    /**
     * Removes all services
     */
    public void removeAllServices() {
        services.clear();
    }

}


texts:
I have a struct of integers and I am trying to increase them based on rules. For example, rule_1 is the max limit that the first increase should reach.

I want to change the order of additions based on priorities map (a=1,b=2,c=3), increase first "a", then "b", then "c". If I change the priorities (a=3,b=2,c=1), the additions should be made first first for "c", then "b", then "c".

I would like code review comments in terms of correct use of language and any suggestions for a better approach on this problem.

#include <iostream>
#include <string>
#include <map>

struct data {
    int a;
    int b;
    int c;
};

struct rules {
    int rule_1;
    int rule_2;
    int rule_3;
};

void set_priorities(const std::map<std::string, int>& priorities, data& d, int *&it_1, int *&it_2, int *&it_3) {

    for (const auto& p : priorities) {
        if (p.first == "a") {
            if (p.second == 1) {
                it_1 = &(d.a);
            } else if (p.second == 2) {
                it_2 = &(d.a);
            } else {
                it_3 = &(d.a);
            }
        }

        if (p.first == "b") {
            if (p.second == 1) {
                it_1 = &(d.b);
            } else if (p.second == 2) {
                it_2 = &(d.b);
            } else {
                it_3 = &(d.b);
            }
        }

        if (p.first == "c") {
            if (p.second == 1) {
                it_1 = &(d.c);
            } else if (p.second == 2) {
                it_2 = &(d.c);
            } else {
                it_3 = &(d.c);
            }
        }
    }

    return;
}

void compute_data(const std::map<std::string, int> &p, const rules r, data& d) {

    int* it_1 = nullptr;
    int* it_2 = nullptr;
    int* it_3 = nullptr;
    set_priorities(p, d, it_1, it_2, it_3);

    do {
        if (*it_1 == r.rule_1) {
            if (*it_2 == r.rule_2) {
                if (*it_3 == r.rule_3) {
                    return;
                } else {
                    (*it_3)++;
                    std::cout << "> > > a: " << d.a << ", b: " << d.b << ", c: " << d.c << std::endl;
                }
            } else {
                (*it_2)++;
                std::cout << "> > a: " << d.a << ", b: " << d.b << ", c: " << d.c << std::endl;
            }
        } else {
            (*it_1)++;
            std::cout << "> a: " << d.a << ", b: " << d.b << ", c: " << d.c << std::endl;
        }
    } while (true);

    return;
}

int main()
{
    std::map<std::string, int> priorities;

    priorities.insert(std::pair<std::string, int>("a", 1));
    priorities.insert(std::pair<std::string, int>("b", 2));
    priorities.insert(std::pair<std::string, int>("c", 3));

    rules r{};
    r.rule_1 = 2;
    r.rule_2 = 4;
    r.rule_3 = 6;

    data d{};

    std::cout << "a: " << d.a << ", b: " << d.b << ", c: " << d.c << std::endl;
    int repetitions = 2;

    do {
        compute_data(priorities, r, d);
        --repetitions;
    } while (repetitions > 0);

    std::cout << "a: " << d.a << ", b: " << d.b << ", c: " << d.c << std::endl;
}


texts: Convert infix regular expression notation to postfix

texts:
This is a small part of a larger program for implementing a limited syntax regular expression constructor using Ken Thompson's construction algorithm. Converting to postfix before the regular expression is processed makes the processing vastly simpler because everything can be smoothly read and processed left to right. The following algorithm for performing the conversion works in a shunting-yard like manner where an operator stack is used to determine when operators should be sent to the output string.
Conversion Function:
typedef struct _conv_ret {
    char *re;
    int err;
} conv_ret;

conv_ret conv(char *re) {
    /* converts limited regex infix notation with explicit
     * catenation denoted by '.' to postfix in a shunting-yard manner */

    conv_ret ret = {NULL, REGEX_TOOLARGE};

    if(strlen(re) > MAX_LINE)
        return ret;

    static char buf[MAX_LINE];
    char *bufp = buf;

    ret.re = buf;
    ret.err = 0;

    /* operator stack */
    int bp[strlen(re)];
    int *sp = bp;

    #define OP_NUM 6

    /* placeholder for id 0 */
    char id_map[OP_NUM+1] = {' ', '(', '|', '.', '?', '+', '*'};
    int prec_map[OP_NUM+1] = {0, 1, 2, 3, 4, 4, 4};

    #define push(id) *++sp = id
    #define pop()    *bufp = id_map[*sp--]; bufp++

    for(; *re; re++) {
        /* loop skips open paren (id 1) because it is only there
         * as a placeholder until the closing paren is pushed */
        for(int id = 2; id < OP_NUM+1; id++) {
            /* pop until incoming op is
             * highest precedence on stack */
            if(id_map[id] == *re) {
                if(sp > bp) {
                    while(prec_map[id] <= prec_map[*sp]) {
                        pop();
                    }
                }
                push(id);
                goto RELOOP;
            }
        }
        switch(*re) {
        case '(':
            push(1);
            goto RELOOP;
        case ')':
            while(*sp != 1) {
                /* couldn't find matching paren. send error */
                if(sp == bp) {
                    ret.re = NULL;
                    ret.err = PAREN_MISMATCH;
                    return ret;
                }
                pop();
            }
            /* pop without sending paren to buf */
            --sp;
            goto RELOOP;
        default:
            /* send non op to buf */
            *bufp = *re;
            bufp++;
        }
        RELOOP: ;
    }
    /* pop all leftover values in stack to buf */
    while(sp > bp) {
        /* error if unmatched open paren */
        if(*sp == 1) {
            ret.re = NULL;
            ret.err = PAREN_MISMATCH;
            return ret;
        }
        pop();
    }

    /* null terminate */
    *bufp = 0;

    return ret;
}

Header:
#include <string.h>

#define MAX_LINE 10000

/* error codes */
#define REGEX_TOOLARGE 1
#define PAREN_MISMATCH 2

Note: Further errors are caught in later stages of parsing within the program, but this post is just about the postfix conversion and the conversion itself is not meant to do a whole lot of syntactic and semantic parsing.
Examples:
a+a -> aa+
a+a* -> aa+*
a.(a+b)*.b -> aab+*.b.
a.(a+b)*.b() -> aab+*.b.
a.(a+b)*.b) -> PAREN_MISMATCH
a.(a+b)*.b( -> PAREN_MISMATCH
Any criticisms aimed towards improving the efficiency and readability of this code would be greatly appreciated.


texts:
Here's my Python implementation of Conway's Game of Life:

class Game(object):

    def __init__(self, state, infinite_board = True):

        self.state = state
        self.width = state.width
        self.height = state.height
        self.infinite_board = infinite_board

    def step(self, count = 1):

        for generation in range(count):

            new_board = [[False] * self.width for row in range(self.height)]

            for y, row in enumerate(self.state.board):
                for x, cell in enumerate(row):
                    neighbours = self.neighbours(x, y)
                    previous_state = self.state.board[y][x]
                    should_live = neighbours == 3 or (neighbours == 2 and previous_state == True)
                    new_board[y][x] = should_live

            self.state.board = new_board

    def neighbours(self, x, y):

        count = 0

        for hor in [-1, 0, 1]:
            for ver in [-1, 0, 1]:
                if not hor == ver == 0 and (self.infinite_board == True or (0 <= x + hor < self.width and 0 <= y + ver < self.height)):
                    count += self.state.board[(y + ver) % self.height][(x + hor) % self.width]

        return count

    def display(self):
        return self.state.display()

class State(object):

    def __init__(self, positions, x, y, width, height):

        active_cells = []

        for y, row in enumerate(positions.splitlines()):
            for x, cell in enumerate(row.strip()):
                if cell == 'o':
                    active_cells.append((x,y))

        board = [[False] * width for row in range(height)]

        for cell in active_cells:
            board[cell[1] + y][cell[0] + x] = True

        self.board = board
        self.width = width
        self.height = height

    def display(self):

        output = ''

        for y, row in enumerate(self.board):
            for x, cell in enumerate(row):
                if self.board[y][x]:
                    output += ' o'
                else:
                    output += ' .'
            output += '\n'

        return output

glider = """ oo.
             o.o
             o.. """

my_game = Game(State(glider, x = 2, y = 3, width = 10, height = 10))
print my_game.display()
my_game.step(27)
print my_game.display()

Output:

 . . . . . . . . . .
 . . . . . . . . . .
 . . o o . . . . . .
 . . o . o . . . . .
 . . o . . . . . . .
 . . . . . . . . . .
 . . . . . . . . . .
 . . . . . . . . . .
 . . . . . . . . . .
 . . . . . . . . . .

 . . . . . . . . . .
 . . . . . . . . . .
 . . . . . . . . . .
 . . . . . . . . . .
 . . . . . . . . . .
 . . . . . . o . . .
 . . . . . o o . . .
 . . . . . o . o . .
 . . . . . . . . . .
 . . . . . . . . . .

I have several concerns:

It feels a bit unnatural to write self.state.board[y][x], instead of [x][y]. However, I thought it would make sense to let the board be an array of rows rather than columns.
I'm not sure how to divide the tasks between the two classes. For instance, I could have implemented the neighbours() function in the State class, rather than in the Game class.
I know it's good practice to write a lot of comments,  but I found most of this code self-explanatory (though that could be because I've just written it).
I used several nested for-loops, but maybe I could replace some with list comprehensions.
I could have left out the display() function of the Game class and just write print my_game.state.display() on the last line. Does this simplify things, or does it only make it more complicated?


texts:
I was trying just as a practice to implement substring on my own.

the Test is inside the Ctor just because it is easy.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication2
{
    public class Substring
    {
        public Substring()
        {
            string test = "giladdarmonwhatareyoudoing";
            string res = ApplySubString(5, test);
            string res2 = ApplySubString2(5, test);
        }

        public string ApplySubString(int i, string test)
        {
            char[] charArray = test.ToArray();
            StringBuilder sb = new StringBuilder();

            for (; i < charArray.Length; i++)
            {
                sb.Append(charArray[i]);
            }
            return sb.ToString();
        }

        public string ApplySubString2(int i, string test)
        {
            char[] charArray = new char[test.Length - i];
            Array.Copy(test.ToCharArray(), i, charArray, 0, test.Length - i);
            return new String(charArray);
        }
    }
}

Please Let me know if you think I'm missing something or can offer a faster way.


texts: Enumerating smart card terminals asynchronously in ViewModel constructor

texts:
I started a project the other day and started going down the path of using async and await as I have never used it before and it seems like a good match. The app that I'm making is a WPF solution using MVVM. It is going to read from a smart card and show the information that was saved to the card. It is part of a demo/concept. As it stands right now the View has next to nothing in it so I'm not going to show it. The test and the ViewModel are of the interest. So let me begin with the test as it is where I first asked this question in my head. I'm using NUnit 3.2 and Moq 4.2

MainWindowViewModelTests.cs

[TestFixture]
public class MainWindowViewModelTests
{
    private Mock<ITerminalFactory> _factory;

    [SetUp]
    public void Setup()
    {
        _factory = new Mock<ITerminalFactory>();
    }

    [Test]
    public void WhenNoTerminalIsConnected_ErrorMessageIndicatesNoTerminal()
    {
        _factory.Setup(f => f.EnumerateTerminals()).Returns(async ()=>
        {
            await Task.Yield();
            return new ITerminal[0];
        });

        var target = GetClassUnderTest();

        Assert.That(target.Error, Is.EqualTo("No Terminals"));
    }

    [Test]
    public void WhenAtleastOneTerminalIsConnected_NoErrorMessages()
    {
        _factory.Setup(f => f.EnumerateTerminals()).Returns(async () =>
        {
            await Task.Yield();
            return new ITerminal[] { Mock.Of<ITerminal>()};
        });

        var target = GetClassUnderTest();

        Assert.That(target.Error, Is.Null.Or.Empty);
        Assert.That(target.Terminals.Count, Is.EqualTo(1));
    }

    private MainWindowViewModel GetClassUnderTest()
    {
        var target = new MainWindowViewModel(_factory.Object);
        while (!target.IsLoaded)
        {
            System.Threading.Thread.Sleep(1);
        }
        return target;
    }
}

MainWindowViewModel.cs

public class MainWindowViewModel : HandleErrorsViewModel
{
    public ICollection<ITerminal> Terminals { get; }
    public bool IsLoaded { get; private set; }

    public MainWindowViewModel(ITerminalFactory terminalFactory)
    {
        Terminals = new ObservableCollection<ITerminal>();
        PopulateTerminals(terminalFactory);
    }

    private async void PopulateTerminals(ITerminalFactory terminalFactory)
    {
        IEnumerable<ITerminal> terminals = await terminalFactory.EnumerateTerminals();
        terminals.ToList().ForEach(Terminals.Add);

        if (Terminals.Count == 0)
            Error = "No Terminals";

        IsLoaded = true;
    }
}

HandleErrorsViewModel.cs and BaseViewModel

omitted as it is just a wrapper around IDataErrorInfo and a BaseViewModel which is just a wrapper around INotifyPropertyChanged

ITerminal/ITerminalFactory

public interface ITerminal : System.IDisposable
{
    string Name { get; }

    IChippedCard Connect();
    void Disconnect();
}
public interface ITerminalFactory
{
    Task<IEnumerable<ITerminal>> EnumerateTerminals();
}

And that is as far as I am right now. I've neve used async and await before. I've never used a Task as a return method before, and I always desire to use the best practices so that is why I am here. So please fire away and let me know thoughts/concerns/tips/ideas.


texts: OOP and non-OOP versions of layout and page animation code

texts:
I am trying to learn how to write more object oriented javascript code, but I am having a hard time understanding the correct way to do it, and how it is useful for front end development. As you can see below, I tried to rewrite my old javascript code to be more object oriented, but it just doesn't seem necessary for what I am doing. I am not even sure if I am doing it correctly (would it be better to use a self executing anonymous function for this?). Could someone take a look at my code and tell me how I can improve it? Also, explain to me why it is important to write object oriented javascript for the development of a websites frontend?

Original Code

// Document and Windows Variables
var $document = $(document),
    $window = $(window);

// Equalize
function equal_heights() {
    var $row = $('.equal');

    if ($row.length > 0) {
        $row.each(function() {
            var $sections = $(this).children(),
                largest_height = 0;

            $sections.height('auto');

            $sections.each(function() {
                var h = $(this).height();
                if (largest_height < h) largest_height = h;
            });

            $sections.height(largest_height);
        });
    }
}

// Position Popups
function position_popup() {
    var $popup = $('.popup'),
        pop_height = $popup.outerHeight(true),
        pop_width = $popup.outerWidth(true),
        browser_height = $(window).height(),
        pop_top = 10,
        page_pos = document.documentElement.scrollTop || document.body.scrollTop;

    if (pop_height < browser_height) {
        pop_top = browser_height / 2 - pop_height / 2;
    }

    $popup.css({
        top: page_pos + pop_top
    });
}

// Page Animation Fade (On Scroll)
function page_animations() {
    $('.fade-me').each(function(i) {
        if ($window.scrollTop() > $(this).offset().top - ($window.height() / 1)) {

            $(this).addClass('is-showing');

        }
    });
}

page_animations();

/********************
Run Functions
********************/
$window.on({
  load: function() {
   equal_heights();
   position_popup();
  }
});

OOP

// Document and Windows Variables
var $reuseVars = {
    window: $(window),
    document: $(document)
}

//  Functions Object
function AllFunctions() {}

AllFunctions.prototype = {
    // Equal Heights
    equalHeights: function() {
        var $row = $('.equal');

        if ($row.length > 0) {
            $row.each(function() {
                var $sections = $(this).children(),
                    largest_height = 0;

                $sections.height('auto');

                $sections.each(function() {
                    var h = $(this).height();
                    if (largest_height < h) largest_height = h;
                });

                $sections.height(largest_height);
            });
        }
    },

    // Popup Position
    positionPopup: function() {
        var $popup = $('.popup'),
            pop_height = $popup.outerHeight(true),
            pop_width = $popup.outerWidth(true),
            browser_height = $(window).height(),
            pop_top = 10,
            page_pos = document.documentElement.scrollTop || document.body.scrollTop;

        if (pop_height < browser_height) {
            pop_top = browser_height / 2 - pop_height / 2;
        }

        $popup.css({
            top: page_pos + pop_top
        });
    },

    // Page Fade Animation - On Scroll
    pageAnimation: function() {
        $('.fade-me').each(function(i) {
            if ($reuseVars.window.scrollTop() > $(this).offset().top - ($reuseVars.window.height() / 1)) {

                $(this).addClass('is-showing');

            }
        });
    }
};

// Create All Functions Object
var allFunctions = new AllFunctions();

// Run Functions on doc ready
allFunctions.pageAnimation();

/********************
 Run Functions
********************/
$reuseVars.window.on({
   load: function() {
     allFunctions.equalHeights();
     allFunctions.positionPopup();
   }
});


texts:
Please review this:

#include <iostream>
using namespace std;

template <class T>
struct Node
{
  T data;
  Node * next;
  Node(T data) : data(data), next(NULL) {}
};

template <class T>
class CircularLinkedList
{
public:
  CircularLinkedList() : head(NULL) {}
  ~CircularLinkedList();
  void addNode(T data);
  void deleteNode(T data);
  template <class U>
  friend std::ostream & operator<<(std::ostream & os, const CircularLinkedList<U> & cll);
private:
  Node<T> * head;
};

template <class T>
CircularLinkedList<T>::~CircularLinkedList()
{
  if (head)
    {
      Node<T> * tmp = head;
      while (tmp->next != head)
        {
          Node<T> * t = tmp;
          tmp = tmp->next;
          delete(t);
        }
      delete tmp;
      head = NULL;
    }
}

template <class T>
void CircularLinkedList<T>::addNode(T data)
{
  Node<T> * t = new Node<T>(data);

  if (head == NULL)
    {
      t->next = t;
      head = t;
      return;
    }

  Node<T> * tmp = head;
  while (tmp->next !=  head)
    {
      tmp = tmp->next;
    }

  tmp->next = t;
  t->next = head;
}

template <class T>
void CircularLinkedList<T>::deleteNode(T data)
{
  Node<T> * tmp = head;
  Node<T> * prev = NULL;
  while (tmp->next !=  head)
    {
      if (tmp->data == data) break;
      prev = tmp;
      tmp = tmp->next;
    }

  if (tmp == head)
    {
      while (tmp->next != head)
        {
          tmp = tmp->next;
        }
      tmp->next = head->next;
      delete head;
      head = tmp->next;
    }
  else
    {
      prev->next = tmp->next;
      delete tmp;
    }
}

template <class U>
std::ostream & operator<<(std::ostream & os, const CircularLinkedList<U> & cll)
{
  Node<U> * head = cll.head;
  if (head)
    {
      Node<U> * tmp = head;
      while (tmp->next != head)
        {
          os << tmp->data << " ";
          tmp = tmp->next;
        }
      os << tmp->data;
    }
  return os;
}

int main()
{
  CircularLinkedList<int> cll;

  cll.addNode(1);
  cll.addNode(2);
  cll.addNode(3);
  cll.addNode(4);
  cll.addNode(5);

  cout << cll << endl;

  cll.deleteNode(3);
  cll.deleteNode(1);
  cll.deleteNode(5);

  cout << cll << endl;

  return 0;
}


texts: Counting characters, digits, spaces and newlines in the loaded file

texts:
I wrote an application that loads a file after pressing button and counts characters, digits, spaces and newlines in the loaded file. This application is written in Python language using tkinter library and OOP programming paradigm.

4programmers.py:

# -*- coding: utf-8 -*-
from Tkinter import *
import Tkinter, Tkconstants, tkFileDialog

class GUI:
    def __init__(self, root):
        self.root = root
        self.filePath = StringVar()
        self.filePath.set("File not loaded")
        self.charLength = StringVar()
        self.charLength.set(0)
        self.digitsLength = StringVar()
        self.digitsLength.set(0)
        self.spacesLength = StringVar()
        self.spacesLength.set(0)
        self.entersLength = StringVar()
        self.entersLength.set(0)

        root.title("A program that counts characters, digits, spaces and newlines in the given file.")

        topFrame1 = Frame(root)
        topFrame1.pack( side = TOP )
        Label(topFrame1, text="Chars count: ").pack( side = LEFT )
        lblCharLength = Label(topFrame1, textvariable=self.charLength)
        lblCharLength.pack( side = RIGHT )

        topFrame2 = Frame(root)
        topFrame2.pack( side = TOP )
        Label(topFrame2, text="Digits count: ").pack( side = LEFT )
        lblDigitsLength = Label(topFrame2, textvariable=self.digitsLength)
        lblDigitsLength.pack( side = RIGHT )

        topFrame3 = Frame(root)
        topFrame3.pack( side = TOP )
        Label(topFrame3, text="Spaces count: ").pack( side = LEFT )
        lblSpacesLength = Label(topFrame3, textvariable=self.spacesLength)
        lblSpacesLength.pack( side = RIGHT )

        topFrame4 = Frame(root)
        topFrame4.pack( side = TOP )
        Label(topFrame4, text="Newlines count: ").pack( side = LEFT )
        lblEntersLength = Label(topFrame4, textvariable=self.entersLength)
        lblEntersLength.pack( side = RIGHT )

        bottomFrame = Frame(root)
        bottomFrame.pack( side = BOTTOM )

        lblFileName = Label(bottomFrame, textvariable=self.filePath)
        lblFileName.pack( side = LEFT )

        btnReadFile = Button(
                bottomFrame,
                text="Load a file",
                fg="black",
                command=self.importFile)
        btnReadFile.pack( side = RIGHT )

    def importFile(self):
        self.filePath.set(tkFileDialog.askopenfilename())

        s = open(self.filePath.get()).read()
        self.charLength.set(len(s))
        self.digitsLength.set(sum(c.isdigit() for c in s))
        self.spacesLength.set(sum(c.isspace() for c in s))
        self.entersLength.set(sum(c == "\n" for c in s))
        self.root.update()

root = Tk()
gui = GUI(root)
root.mainloop()


texts:
I'm trying out new things (on class Inproc), specifically using std::unique_ptr and std::move, and I'm wondering if I'm doing it right. The code compiles so that gives me hope. Still, what do you think?

Note: I'm working without exceptions for reasons I won't go into. That means the factory functions are required to handle errors. Keep that in mind please.

class Fan {
public:
    static Fan * create(Fan *peer = NULL) { return new Fan(peer); }
    virtual ~Fan();
private:
    Fan(Fan *peer__ = NULL) : peer_(peer__) { };
    Fan *peer_;
};

class Inproc {
public:
    static Inproc * create();
    ~Inproc();
private:
    Inproc(std::unique_ptr<Fan> bound__,
           std::unique_ptr<Fan> connected__);
    std::unique_ptr<Fan> bound_;
    std::unique_ptr<Fan> connected_;
};

Inproc * Inproc::create() {
    std::unique_ptr<Fan> bound(Fan::create());
    if (bound) {
        std::unique_ptr<Fan> connected(Fan::create(bound.get()));
        if (connected) {
            return new(std::nothrow) Inproc(std::move(bound), std::move(connected));
        }
    }
    return NULL;
}

Inproc::Inproc(std::unique_ptr<Fan> bound__,
               std::unique_ptr<Fan> connected__)
    : bound_(std::move(bound__)), connected_(std::move(connected__)) { }


texts:
I found a Go language code to do RGB to YCbCr conversion from here! I ported it to Java:

private byte[] generateColorBar(int width,int height) {
    final int  COL[][] =
            {
                    { 255, 255, 255 },  // 100% White
                    { 255, 255,   0 },  // Yellow
                    {   0, 255, 255 },  // Cyan
                    {   0, 255,   0 },  // Green
                    { 255,   0, 255 },  // Magenta
                    { 255,   0,   0 },  // Red
                    {   0,   0, 255 },  // Blue
                    {   0,   0,   0 },  // Black
            };

    int columnHeight = height / COL.length;
    byte[] arr = new byte[width*height*3/2];
    int yOffset = 0;
    int uvOffset = width*height;

    for (int j = 0; j < height; j++) {
        for (int i = 0; i < width; i++) {
            int idx = j / columnHeight;
            int R = COL[idx][0];
            int G = COL[idx][1];
            int B = COL[idx][2];
            int yIndex = j*width+i;
            int uvIndex = j*width/2+i;

            int Y = (19595*R + 38470*G + 7471*B + (1<<15)) >> 16;
            int Cb = -11056*R - 21712*G + 32768*B + (257<<15);
            if ((Cb & 0xff000000) == 0) {
                Cb >>= 16;
            } else {
                Cb = 0xffffffff ^ (Cb >> 31);
            }
            int Cr = 32768*R - 27440*G - 5328*B + (257<<15);
            if ((Cr & 0xff000000) == 0) {
                Cr >>= 16;
            } else {
                Cr = 0xffffffff ^ (Cr >> 31);
            }
            arr[yOffset + yIndex] = (byte) Y;
            if (i%2 == 0 && j%2 == 0) {
                arr[uvOffset + uvIndex] = (byte) Cb;
                arr[uvOffset + uvIndex + 1] = (byte) Cr;
            }
        }
    }
    return arr;
}

Please help review it.

The original Go language code is below:

// RGBToYCbCr converts an RGB triple to a Y'CbCr triple.
func RGBToYCbCr(r, g, b uint8) (uint8, uint8, uint8) {
  // The JFIF specification says:
  //  Y' =  0.2990*R + 0.5870*G + 0.1140*B
  //  Cb = -0.1687*R - 0.3313*G + 0.5000*B + 128
  //  Cr =  0.5000*R - 0.4187*G - 0.0813*B + 128
  // https://www.w3.org/Graphics/JPEG/jfif3.pdf says Y but means Y'.

  r1 := int32(r)
  g1 := int32(g)
  b1 := int32(b)

  // yy is in range [0,0xff].
  //
  // Note that 19595 + 38470 + 7471 equals 65536.
  yy := (19595*r1 + 38470*g1 + 7471*b1 + 1<<15) >> 16

  // The bit twiddling below is equivalent to
  //
  // cb := (-11056*r1 - 21712*g1 + 32768*b1 + 257<<15) >> 16
  // if cb < 0 {
  //     cb = 0
  // } else if cb > 0xff {
  //     cb = ^int32(0)
  // }
  //
  // but uses fewer branches and is faster.
  // Note that the uint8 type conversion in the return
  // statement will convert ^int32(0) to 0xff.
  // The code below to compute cr uses a similar pattern.
  //
  // Note that -11056 - 21712 + 32768 equals 0.
  cb := -11056*r1 - 21712*g1 + 32768*b1 + 257<<15
  if uint32(cb)&0xff000000 == 0 {
      cb >>= 16
  } else {
      cb = ^(cb >> 31)
  }

  // Note that 32768 - 27440 - 5328 equals 0.
  cr := 32768*r1 - 27440*g1 - 5328*b1 + 257<<15
  if uint32(cr)&0xff000000 == 0 {
      cr >>= 16
  } else {
      cr = ^(cr >> 31)
  }

  return uint8(yy), uint8(cb), uint8(cr)
}


texts: Code for calculating number of trailing zeroes after factorial

texts:
While trying my hands at the beginner codechef problem I came across this . So basically doing that problem with Dynamic programming is an overkill but why not try that and get some DP practice.

Nice, I almost solved that problem in minutes but the problem is this takes too much memory , and ends up with a Segmentation Fault upon entering a big integer , I solved this problem by running a  ulimit -s unlimited in my local machine but that wont make the codechef judge happy.

Here is the code:

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

int getZeroes(long long n){
    if(n>0){
        if(n%5 == 0){
            long long a = n/5;
            int b = 1;
            while(a/5){
                if(a%5 == 0){
                    b++;
                }else{
                    break;
                }
                a = a/5;
            }
            return (b+getZeroes(n-1));
        }else{
            return (getZeroes(n-1));
        }
    }
}

int main(){
    int n;
    std::cin >> n;
    std::vector<int> x;
    for(int i=0;i<n;i++){
        long long cases;
        std::cin >> cases;
        x.push_back(getZeroes(cases));
    }

    for(int itr : x){
        std::cout << itr << std::endl;
    }

return 0;
}

Upon some research I found most recommend to declare the items in a heap rather than stack , but that's somewhat confusing to me.  Can anyone help me to find out what can I do to overcome this?


texts: Iterator to generate all the words (of a given words) that are one change away

texts:
I'm trying to create an iterator, that will generate all the words that are one change away.

For example, if my input is "sam", I should get the following words:

"aam", "bam", ..."ram","tam",...."zam","sbm","scm",..."szm","saa","sab",..."san","sao",..."saz".

Notice that there is no "sam" in the output, as it is 0 changes away.

The following function, it(), is a simple function that does this and prints the output:

public class oneChangeAway implements Iterator {
String s;

oneChangeAway(String s)
{
    this.s =s;
}
@Override
public boolean hasNext() {
      return false;
}

@Override
public Object next() {
    return null;
}

@Override
public void remove() {

}

public void it() {
    int len = s.length();
    String temp ;
    for (int i = 0; i < len; i++)
    {
        char[] char_s = s.toCharArray();
        for(char c= 'a'; c<='z'; c++)
        {
            char_s[i] = c;
            temp = new String(char_s);
            if ( temp.equals(s)) continue;
            System.out.println(temp);
        }
    }
}
}

However, now I want an iterator to do this. This is what I came up with:

public class oneChangeAway implements Iterator {
String s;

int l;
int i ;
char c ;
char[] c_s;
oneChangeAway(String s)
{
    this.s =s;
    l =s.length();
    i = 0;
    c = 'a';
    c_s = s.toCharArray();
}
@Override
public boolean hasNext() {
    if ( i == l)
    return false;

    return true;
}

@Override
public Object next() {
    String temp;
    if ( this.hasNext())
    {
        c_s[i] = c;
        c++;
        temp = new String(c_s);
        if( c == ('z' + 1))
        {
            c = 'a';
            c_s[i] = s.toCharArray()[i];
            i++;
        }
        if (temp.equals(s)) return this.next();
        return temp;
    }

    return null;
}

@Override
public void remove() {

}

public void it() {
    int len = s.length();
    String temp ;
    for (int i = 0; i < len; i++)
    {
        char[] char_s = s.toCharArray();
        for(char c= 'a'; c<='z'; c++)
        {
            char_s[i] = c;
            temp = new String(char_s);
            if ( temp.equals(s)) continue;
            System.out.println(temp);
        }
    }
}
}

The following main function calls it:

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

    oneChangeAway ia = new oneChangeAway("sam");

    //ia.it();

    while (ia.hasNext())
    {
        System.out.println(ia.next());
    }
}
}

This seems to work and the output is as intended. However, am I doing it the 'right' way?


texts: Nullable Generics - Implementing SequentialSearchST in C#

texts:
For learning purposes, I am implementing certain code from Sedgewick & Wayne's Algorithms, Fourth Edition.

Because of language features, a direct translation doesn't seem possible.

For example, I believe the get method in their implementation of SequentialSearchST can return null for both value and reference types because Java boxes/unboxes "value objects" (for lack of a better term) like Integer automatically.

C#, as far as I can tell, does not have an equivalent built in. It also does not appear to be possible to put an all-purpose nullable constraint on a generic type.

At least one other person has tried this, but their implementation does not allow you to store reference types for TValue which prevents you from implementing other Algorithms classes like SeparateChainingHashST.

So, I have decided to throw a runtime error in the static constructor below. Is that about as good as it gets? That is, is there no way to throw a compile time error?

public class SequentialSearchSt<TKey, TValue>
{
    private Node first;

    static SequentialSearchSt()
    {
        if (!default(TValue).Equals(null)) throw new InvalidOperationException("TValue must be a nullable or reference type.");
    }

    private class Node
    {
        public TKey key;
        public TValue val;
        public Node next;

        public Node(TKey key, TValue val, Node next)
        {
            this.key = key;
            this.val = val;
            this.next = next;
        }
    }

    public TValue Get(TKey key)
    {
        for (Node x = first; x != null; x = x.next)
        {
            if (key.Equals(x.key))
            {
                return x.val;
            }
        }
        return default(TValue);
    }

    // more code...
}


texts:
I am trying to improve the performance of my cellular automata lab. I have two arrays of Doubles representing the current values and the next values.

If I run the calculation in a single thread I get about 28 steps per second. However, if I break the work down into 2, 3 or 4 chunks and pass them into a concurrency queue I still get about 28 steps per second. If I increase the chunks further the algorithm takes longer and longer to complete, for example 10 chunks drops the performance to about 10 steps per second.

I'm testing this on a 3rd generation iPad Pro with 4 performance cores and 4 efficiency cores.

func step(from: Int, to: Int) {
    for j in from..<to {
        for i in 0..<w {
            AEMemoryClear(memory);

            AEMemorySetValue(memory, sI,                        cells[i   + (j  )*w])
            AEMemorySetValue(memory, aI, i != 0 && j != 0 ?     cells[i-1 + (j-1)*w] : 0)
            AEMemorySetValue(memory, bI, j != 0 ?               cells[i   + (j-1)*w] : 0)
            AEMemorySetValue(memory, cI, i != wB && j != 0 ?    cells[i+1 + (j-1)*w] : 0)
            AEMemorySetValue(memory, dI, i != wB ?              cells[i+1 + (j  )*w] : 0)
            AEMemorySetValue(memory, eI, i != wB && j != hB ?   cells[i+1 + (j+1)*w] : 0)
            AEMemorySetValue(memory, fI, j != hB ?              cells[i   + (j+1)*w] : 0)
            AEMemorySetValue(memory, gI, i != 0 && j != hB ?    cells[i-1 + (j+1)*w] : 0)
            AEMemorySetValue(memory, hI, i != 0 ?               cells[i-1 + (j  )*w] : 0)

            AERecipeExecute(recipe, memory)

            next[i + j*w] = memory.pointee.slots[index].obj.a.x
        }
    }
}
func step() {

    let start = DispatchTime.now()

    let n: Int = 4
    let z: Int = h/n

    let group = DispatchGroup()
    for i in 0..<n {
        group.enter()
        DispatchQueue.global(qos: .userInteractive).async { [unowned self] in
            self.step(from: i*z, to: i == n-1 ? self.h : (i+1)*z)
            group.leave()
        }
    }

    group.notify(queue: .main) { [unowned self] in
        (self.cells, self.next) = (self.next, self.cells)

        let end = DispatchTime.now()
        let delta = Double(end.uptimeNanoseconds - start.uptimeNanoseconds)/1000000000
        let target: Double = 1.0/60
        print("Time to calculate: \(delta) or \(round(1/delta)) SPS which is \(round(delta/target*100*10)/10)% of target; # of cells: \(self.w)^2 = \(self.w*self.h); seconds per cell: \(delta/Double(self.w*self.w))")
    }

    group.wait()
}

Also, another weird thing I'm noticing: if I run the calculation once a second it takes more than twice as long to complete than if I run it several times a second.  The only reason I can possibly think is that its using the efficiency core instead of the performance core in that case.

Note: AEMemorySetValue, AERecipeExecute, AEMemoryClear are C functions.

h and w are the cell dimensions of the cellular automata; the height and width. In practice they are the same and are about 300-500, depending on the device.  Also, h, w, index, sI, aI...hI are all static values that do not change at all through this entire process.

I also entirely moved the inner step function from Swift to C, but that had zero effect on the performance, positive or negative.


texts:
I have a below code which constructs the URL given a FlowType enum.

private String getURL(FlowType type) throws Exception {
    StringBuilder url = new StringBuilder();

    if (TestUtils.isProduction()) {
        if (type.equals(FlowType.HOLDER)) {
            url.append(VISITOR);
        } else {
            url.append(USER);
        }
    } else {
        if (type.equals(FlowType.HOLDER)) {
            url.append(VISITOR_STAGE);
        } else {
            url.append(USER_STAGE);
        }
    }
    long version = 0;
    if (DataMapping.isInitialized()) {
        if (!TestUtils.isEmpty(DataMapping.getPartition(type))) {
            version = DataMapping.getPartition(type).getVersion();
        }
    }
    url.append("web/hasChanged?ver=" + version);

    return url.toString();
}

I wanted to review this code. Any improvements or suggestions?


texts: Check style found code duplication in factory

texts:
I have some methods in my mapper:

public EventDto mapToDto(Event googleEvent, EventDto baseEventDto) {
    EventDto eventDto = mapToDto(googleEvent, baseEventDto.getOriginalCalendarId());
    eventDto.setCalendarId(baseEventDto.getCalendarId());
    eventDto.setCollectiveId(baseEventDto.getCollectiveId());
    eventDto.setId(baseEventDto.getId());
    return eventDto;
}

and

public EventDto mapToDto(Event googleEvent, String originalCalendarId) {
    ///...
}

difference is in few rows here because of different clients. Right now, my mapper should be improved with abstraction and another child. To use improved mappers I need a factory that contains:

@Autowired
private GoogleEventDtoMapperConfirmed googleEventDtoMapperConfirmed;
@Autowired
private GoogleEventDtoMapperCanceled googleEventDtoMapperCanceled;

public EventDto mapToDto(Event googleEvent, EventDto baseEventDto) {
    switch (googleEvent.getStatus()) {
        case GoogleEventStatus.CANCELLED:
            return googleEventDtoMapperCanceled.mapToDto(googleEvent, baseEventDto);
        case GoogleEventStatus.CONFIRMED:
        case GoogleEventStatus.TENTATIVE:
        default:
            return googleEventDtoMapperConfirmed.mapToDto(googleEvent, baseEventDto);
    }
}

public EventDto mapToDto(Event googleEvent, String originalCalendarId) {
    switch (googleEvent.getStatus()) {
        case GoogleEventStatus.CANCELLED:
            return googleEventDtoMapperCanceled.mapToDto(googleEvent, originalCalendarId);
        case GoogleEventStatus.CONFIRMED:
        case GoogleEventStatus.TENTATIVE:
        default:
            return googleEventDtoMapperConfirmed.mapToDto(googleEvent, originalCalendarId);
    }
}

I believe factory is a good choice, but as you see here, there is some duplication that should be reduced. I can't move part mapper logic to the factory because of semantical reason (if I move duplication part will be fixed), and on the other hand, I have sonar duplicate issues.

Any ideas on how to reduce duplication part? Or, if you think some mapper part can be moved into the factory, please explain concepts why mapper rules should be moved into the factory part.


texts:
I am still learning PowerShell and I would like your opinion on my log writing function. It creates a log entry with timestamp and message passed thru a parameter Message or thru pipeline, and saves the log entry to log file, to report log file, and writes the same entry to console. In Configuration.cfg file paths to report log and permanent log file are contained, and option to turn on or off whether a report log and permanent log should be written. If Configuration.cfg file is absent it loads the default values. Depending on the OperationResult parameter, log entry can be written with or without a timestamp. Format of the timestamp is "yyyy.MM.dd. HH:mm:ss:fff", and this function adds " - " after timestamp and before the main message.
function Write-Log {
    param (
        [Parameter(Position = 0, ValueFromPipelineByPropertyName)]
        [ValidateSet('Success', 'Fail', 'Partial', 'Info', 'None')]
        [String]
        $OperationResult = 'None',

        [Parameter(Position = 1, Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)]
        [String]
        $Message
    )

    begin {

        if (Test-Path -Path '.\Configuration.cfg') {
            $Configuration = Get-Content '.\Configuration.cfg' | ConvertFrom-StringData
            $LogFile    = $Configuration.LogFile
            $ReportFile = $Configuration.ReportFile
            $WriteLog   = $Configuration.WriteLog -eq 'true'
            $SendReport = $Configuration.SendReport -eq 'true'
        }
        else {
            $LogFile    = '.\Log.log'
            $ReportFile = '.\Report.log'
            $WriteLog   = $true
            $SendReport = $true
        }

        if (-not (Test-Path -Path $LogFile)) {
            New-Item -Path $LogFile -ItemType File
        }

        if (-not (Test-Path -Path $ReportFile)) {
            New-Item -Path $ReportFile -ItemType File
        }
    }

    process {
        $Timestamp = Get-Date -Format 'yyyy.MM.dd. HH:mm:ss:fff'
        $LogEntry = $Timestamp + " - " + $Message

        switch ($OperationResult) {
            'Success' {
                $ForegroundColor = 'Green'
                break
            }

            'Fail' {
                $ForegroundColor = 'Red'
                break
            }

            'Partial' {
                $ForegroundColor = 'Yellow'
                break
            }

            'Info' {
                $ForegroundColor = 'Cyan'
                break
            }

            'None' {
                $ForegroundColor = 'White'
                $LogEntry = $Message
            }
        }

        Write-Host $LogEntry -ForegroundColor $ForegroundColor -BackgroundColor Black

        if ($WriteLog) {
            Add-content -Path $LogFile -Value $LogEntry
        }

        if ($SendReport) {
            Add-content -Path $ReportFile -Value $LogEntry
        }
    }
}


texts: Checking whether a store is open or not by querying over its business hours

texts:
I currently have a method that checks if the store is open. It's working nicely, however on the main page I have quite a few stores. Whom again have different locations. Each of these locations again have opening hours.

Now I'm not particularly good with SQL and DB querying and Skylight is complaining and telling me this can most likely be optimized. However I have no clue how.

This is taken from my Store model:

  has_many :business_hours, through: :locations
  ...

  def open?
    if current_business_hour
      true
    else
      false
    end
  end

  def current_business_hour(current_time: Time.current)
      business_hours.where('week_day = ? AND open_at <= ? AND close_at >= ?',
                           current_time.wday, current_time.to_s(:time), current_time.to_s(:time)).first
  end

I'm using Postgres. Now the code should be quite straight forward. I'm looking for business hours that match the current day, and that have a business hour that fits within the current time frame.

This generates:

SELECT  "business_hours".* FROM "business_hours" INNER JOIN "locations" ON "business_hours"."location_id" = "locations"."id" WHERE "locations"."store_id" = ? AND (week_day = ? AND open_at <= ? AND close_at >= ?) ORDER BY week_day LIMIT ?

I'm being notified that:

Skylight detected that this SQL query was repeated multiple times in a single request, which had a significant impact on its response time.

The stores are being rendered like this on a page:

<%= render @stores %>

the _store.html.erb looks like this:

<% if store.open? %>
  <li style="background-image: url(<%= store.header.url %>);">
    <%= link_to store_path(store) do %>

<%= store.name %>, <%= store.city.name %>

Open

    <% end %>

<% else %>
  <li style="background-image: url(<%= store.header.url %>);" class="store-closed">
    <%= link_to store_path(store) do %>

<%= store.name %>, <%= store.city.name %>

    <% end %>

Closed

<% end %>

Now my goal is to try and improve this.


texts:
I wrote this for a CodeWars challenge while trying to learn ECMAScript and would really like to have some advice on how it could be improved.

What I don't like about this code myself, but am unsure on how to improve:

I didn't yet found a way to have a class in ECMAScript that mixes public and private methods in a way, where the public methods (and only them) can still access private methods and vars.
(Partly caused by the point above) I think the code is way too verbose and bloated. Too much of it is wasted on language specific implementation details. There must be a smarter way to do this - I feel like I could write the same functionality in PHP using 10% of the lines I needed now.

function LRUCache(capacity, init) {

  this._capacity = capacity;
  this._size = 0;
  this._accessMap = [];
  this._items = [];
  this._frozenMethods = ['cache', 'delete'];
  this._functionalProps = ['size', 'capacity'];

  this.cache = function(key, value) {

    if( this._accessMap.indexOf(key) == -1 ) {
      this._addNewItem(key);
    }

    this._items[key] = this[key] = value;
    this._updateAccessMap(key);

    return this;
  },
  this.delete = function(key) {

    if(this._frozenMethods.indexOf(key) !== -1 ||
    this._functionalProps.indexOf(key) !== -1) {
      return false;
    }

    if( this._accessMap.indexOf(key) === -1 ) {
      return true;
    }

    delete this[key];
    delete this._items[key];
    this._size--;

    this._updateAccessMap(key, true);

    return true;
  },
  this._removeOldest = function() {
    var key = this._accessMap[0];

    this.delete(key);
  },
  this._updateAccessMap = function(key, remove) {

    index = this._accessMap.indexOf(key);

    if( index !== -1) {
      this._accessMap.splice(index, 1);
    }

    if(!remove) {
      this._accessMap.push(key);
    }
  },
  this._addNewItem = function(key) {

    this._size++;

    if(this._size > this._capacity) {
      this._removeOldest();
    }

    Object.defineProperty(this, key, {
      get: function() {
        this._updateAccessMap(key);

        return this._items[key];
      },
      set: function(v) {
        this._items[key] = v;
        this._updateAccessMap(key);
        return this;
      },
      enumerable: true,
      configurable: true
    });
  };

  var obj = this;

  this._frozenMethods.map( function(v) {
    Object.defineProperty(obj, v, {
      enumerable: false,
      writable: false,
      configurable: false
    });
  });

  ['_items', '_capacity', '_accessMap', '_frozenMethods','_size', '_functionalProps',
  '_removeOldest','_updateAccessMap','_addNewItem'].map( function(v) {
    Object.defineProperty(obj, v, {
      enumerable: false,
      configurable: true
    });
  });

  Object.defineProperty(this, 'capacity', {
    set: function(v) {

      while(this.size > v) {
        this._removeOldest();
      }

      this._capacity = v;
    },
    get: function() {
      return this._capacity;
    },
    configurable: false
  });

  Object.defineProperty(this, 'size', {
    set: function(v) {
      return false;
    },
    get: function() {
      return this._size;
    },
    configurable: false
  });

  if(init) {
    for(var attr in init) {
      if( !init.hasOwnProperty(attr) ) {
        continue;
      }
      this.cache(attr, init[attr]);
    }
  }
}


texts: Trig based functions in sfml, angling of sprites

texts:
void moveCircle(float dt, int radius) { //so center of screen will be rotation point
        setPosition(400+cos(_angle)*radius, 400 - sin(_angle)*radius);

        _angle += (2*pi)*dt;

        if (_angle >= (2 * pi)) {
            _angle -= (2 * pi);
        }
        this->rotate(-2*dt*180);

    }

sf::Vector2f rotateCoordinate(sf::Vector2f mouseCoords, float angle) {
            return sf::Vector2f((mouseCoords.x*cos(angle) + mouseCoords.y*sin(angle)), (mouseCoords.y*cos(angle) - mouseCoords.x*sin(angle)));
    }

void angleShipToMouse(sf::RenderWindow* window) {

        if (sf::Mouse::isButtonPressed(sf::Mouse::Button::Left)) {

            sf::Vector2f mousePosition(sf::Mouse::getPosition(*window));
            std::cout << mousePosition.x << ", " << mousePosition.y << std::endl;

            if (mousePosition.x > _windowWidth || mousePosition.x < 0 || mousePosition.y<0 || mousePosition.y>_windowHeight) {
                return;
            }

            //position of mouse relative to ship in 0 rotation reference frame(absolute)
            sf::Vector2f mouseRelativeShip(mousePosition.x - getX(), (mousePosition.y - getY()));

            //adjusting coordinates to any rotation the sprite has to account for change in orientation of axis.
            mouseRelativeShip = rotateCoordinate(mouseRelativeShip, _angle*(pi/180));

            float angle = atan2(mouseRelativeShip.y, mouseRelativeShip.x) *(180 / pi); //atan2 produces negative angles QUADS 1&2, positive in QUADS 3&4
            this->rotate(angle);

            _angle = this->getRotation();
        }
    }

So these are different fns obviously the first one is unrelated really to the other 2 - just want your opinion on how its done since i didnt look at any examples of others before doing it. I'm wondering if my angleShipToMouse is good code because I honestly got really confused on whether I wanted the local coordinates of the object to show y+ as being "above" the sprite or to just keep it as y- and how this would affect the rotation, in fact it took a long time of just tinkering to  get it to work and I'm unsure specifically why this setup works with y- pointing up. I understand trig but the whole axis issue and the fact that rotation is measured clockwise here when it's normally anti-clockwise, really messed up my brain, lol.

The circle one just moves in a circle with the space ship angled in a way that looks like its travelling around it.


texts:
I've written a function that works however I'm sure there is a better way. I need to parse specific tags from an xml document (Microsoft Word docx document.xml).

Here is the general structure of the xml in question.

//A ton of crap
...
<w:tbl>
  <w:tr>
    <w:tc>
      <w:p>
        <w:r>
          <w:t>Data_I_want</w:t>
        </w:r>
      </w:p>
    </w:tc>
  </w:tr>
  <w:tr>
    <w:tc>
      <w:p>
        <w:r>
          <w:t>Data_I_want</w:t>
        </w:r>
      </w:p>
    </w:tc>
  </w:tr>
</w:tbl>
...
// A ton more crap
//Same structure repeats and I need to grab that n number of times where n is unknown.
// Also the order of the data must be preserved within each parent tbl tag.

Here is an excerpt of my code:

def recurse_search_tables(self, xml_data):
    """
    Recursively traverse the xml child nodes..
    """
    tag_base = r'{http://schemas.openxmlformats.org/wordprocessingml/2006/main}'
    for child in xml_data:
        if child.tag.replace(tag_base,'') == 'tbl':
                for c in child:
                    if c.tag.replace(tag_base,'') == 'tr':
                        for tr in c:
                            if tr.tag.replace(tag_base,'') == 'tc':
                                for tc in tr:
                                    if tc.tag.replace(tag_base,'') == 'p':
                                        for p in tc:
                                            if p.tag.replace(tag_base,'') == 'r':
                                                for r in p:
                                                    if r.tag.replace(tag_base,'') == 't':
                                                        try:
                                                            self.decide_to_print(r.text.encode('UTF-8'))
                                                        except:
                                                            pass
                                                        finally:
                                                            self.recurse_search_tables(child)
                                                    else:
                                                        self.recurse_search_tables(child)
                                            else:
                                                self.recurse_search_tables(child)
                                    else:
                                        self.recurse_search_tables(child)
                            else:
                                self.recurse_search_tables(child)
                    else:
                        self.recurse_search_tables(child)
        else:
            self.recurse_search_tables(child)

Calling that mess via:

tree = ET.parse('document.xml')
root = tree.getroot()
self.recurse_search_tables(root)

Now like i said, this code works however it isn't the fastest (but is is suitable). How can I improve this?


texts:
Is there a faster way of getting the key of 1 or 2 by using the accs value for my getID function? Unfortunately I cannot use an inverse dict due to the fact I'm using a list for the value which causes a unhasable list error. Mainly I'm worried more when the db gets larger in size the getID function will take longer to loop through the db.

db = {"users":{"1":{"main":"charles","accs":["charles","ashketchum"],"rank":4},"2":{"main":"don","accs":["don","donny"],"rank":4}}}

class user_data:

    def get(name, key):
        key = key.lower()
        if key in db["users"][name]:
            return db["users"][name][key]
        else:
            return None

    def getID(name):
        name = name.lower()
        for key in db["users"].keys():
            if name in db["users"][key]["accs"]:
                return key
        return None

Note: the accs value will change as well.


texts:
I'm learning more about PHP, so I've decided to create a simple login/create account system. Entering information for creating a new account sends the data to my localhost machine, using MySQLi and the web server MySQL. I'm looking for feedback about security, efficiency, and overall code. I would like to kick old habits to the curb before it's too late. Any and all help is appreciated and considered. Thank you in advance!

create.html

<!DOCTYPE html>

        <meta charset="UTF-8">
        <title>create.html</title>

        <link rel="stylesheet" type="text/css" href="style.css">

            <form action="create.php" method="post">
                Username
                <input type="text" name="username">

                Password
                <input type="password" name="password">

                Re-enter Password
                <input type="password" name="confirm_password">

                <button type="submit">Create Account</button>
            </form>

create.php

<!DOCTYPE html>

        <meta charset="UTF-8">
        <title>create.php</title>

        <?php

            $servername = "localhost";
            $username = "XXXXXXXXXX"; // Not shown
            $password = "XXXXXXXXXX"; // Not shown
            $dbname = "Database";

            //Create connection
            $mysqli = new mysqli($servername, $username, $password, $dbname);

            //Test connection
            if ($mysqli->connect_error) {
                die("Connection failed: " . $mysqli->connect_error);
            }

            $new_user_usr = filter_input(INPUT_POST, 'username');
            $new_user_pwd = filter_input(INPUT_POST, 'password');
            $new_user_pwd_conf = filter_input(INPUT_POST, 'confirm_password');

            $sql = "SELECT usr, pwd FROM Users";
            $result = $mysqli->query($sql);

            if($result->num_rows > 0) {

                /* If passwords don't match */
                if($new_user_pwd !== $new_user_pwd_conf) {
                    die("Passwords don't match");
                }

                /* If password isn't between bounds */
                if(strlen($new_user_pwd) <= 7 || strlen($new_user_pwd) >= 13) {
                    die("Password not long enough! Must be at least 8 characters long, but not greater than 12 characters");
                }

                /* If username is the same as password*/
                if($new_user_usr === $new_user_pwd) {
                    die("Username cannot equal password!");
                }

                while($row = $result->fetch_assoc()) {
                    if($row['usr'] === $new_user_usr) {
                        die("Username already taken");
                    }
                }

                $add = "INSERT INTO Users (usr, pwd) VALUES ('$new_user_usr', '$new_user_pwd')";

                echo $mysqli->query($add) ? "user created successfully" : "Error: " . $add . "
" . $mysqli->error;

            }

        ?>


texts: Reading and writing an unknown character into an appropriately named file

texts:
I would like to refactor this code a bit further and make it better and more generic.

As of right now, it is doing what I want it to do (reading a list of URL's, splitting the query and the ampersand and writing the split into appropriately named files). However, I would like to take the hash list out and make it as generic as possible. I guess what I mean is, if the loop finds a character, read what the character is (i.e: a=12(character would be 'a')), have Python create a text file for it ('a_file.txt') and append into the newly created text file. So, there was not file there before, but there is now. And Python would do this for every character past the query (http://www.asdasd.com/asds/asd?a=6&b=12&c=123 would create 'a_file.txt', 'b_file.txt', 'c_file.txt').

I feel as if I am asking the right question, but correct me if I am wrong.

import urlparse
def parse_file(input_file):
  tags = {tag: tag + '_file.txt' for tag in {'blog',
        'p','attachment_id','lang',
        'portfolio','page_id','comments_popup',
        'iframe','width','height'}}
with open(input_file) as input:
for line in input:
    parsed_url = urlparse.parse_qsl(urlparse.urlparse(line).query)
    if parsed_url > 0:
        for key, value in parsed_url:
            if key in tags:
                with open(tags[key], 'a') as output_file:
                    output_file.write(value)
            else:
                print key + " not in tags."
    else:
        print(line + " does not yield query.")
parse_file()

Once again, correct me if I am wrong or if my question is confusing.


texts:
Purpose

As I've never implemented a queue, I decided to create a very simple implementation using a linked list approach.

Discussion

I create a singly linked list, using a private Node class that references some data and a previous Node,
that will be used in my SimpleQueue class.

When enqueuing data, I check to see if the linked list is empty or not (by checking to see if the head of the list is null).
If it's empty, point the head to a newly-created Node with the input data. If the list is not empty, I iterate through
the list until I reach the end (i.e. the previous Node is null) and then I insert a newly-created Node.

When dequeuing, I throw an IllegalStateException if the queue is empty. If the queue is not empty, I set the new head of
the queue to be the old head's previous value, and return the old head's data value.

Implementation

public class SimpleQueue<T> {
    private Node<T> head;

    private class Node<E> {
        private final E data;
        private Node<E> previous;

        public Node(E data, Node<E> previous) {
            this.data = data;
            this.previous = previous;
        }
    }

    public boolean isEmpty() {
        return this.head == null;
    }

    public void enqueue(T data) {
        Node<T> currentNode = this.head;
        Node<T> nodeToInsert = new Node<>(data, null);

        if (this.isEmpty()) {
            this.head = nodeToInsert;
        } else {
            while (currentNode.previous != null) {
                currentNode = currentNode.previous;
            }

            currentNode.previous = nodeToInsert;
        }
    }

    public T dequeue() {
        if (this.isEmpty()) {
            throw new IllegalStateException("Unable to dequeue from empty queue");
        }

        Node<T> currentNode = this.head;
        this.head = currentNode.previous;

        return currentNode.data;
    }

    public T peek() {
        if (this.isEmpty()) {
            throw new IllegalStateException("Unable to peek empty queue");
        }

        return this.head.data;
    }
}


texts: Capturing optional regex segment with PHP

texts:
I need to check the end of a URL for the possible existence of /news_archive or /news_archive/5 in PHP. The below snippet does exactly what I want, but I know that I could achieve this with one preg_match rather than two. How can I improve this code to treat the /5 as an optional segment and capture it if it exists?

if (preg_match('~/[0-9A-Za-z_-]+_archive/[0-9]+$~', $_SERVER['HTTP_REFERER'], $matches) || preg_match('~/[0-9A-Za-z_-]+_archive$~', $_SERVER['HTTP_REFERER'], $matches)) {
    $page_info['parent_page']['page_label'] = ltrim($matches[0], '/');
}


texts: Filter column and row according to regex in header

texts:
I'm writing a script that can grep the rows and columns from a text file that match a regex. I have an implementation but I'm looking to make it more elegant.

input.tsv

        a       b       c       d
a       2       9       6       1
b       6       4       7       0
c       3       7       2       0
d       5       8       2       2

I want to do something like this:

$ grep-row-column.py -E "[a|c]" input.tsv
         a       c
a        2       6
c        3       2

The solution should be able to stream a file (i.e. not read the entire thing into memory).

from __future__ import print_function
import sys,re

filename="input.tsv"
regex="[a|c]"

prog=re.compile(".*"+regex+".*")
with open(filename) as tsv:
    #find the appropriate columns in the header that match the regex
    line=tsv.readline()
    header=line.split("\t")
    count=0
    cols=[]
    print(header[0], end='')
    for token in header:
        if prog.match(token):
            #add the column indices to a list for use later
            cols.append(count)
            print("\t",token, end='')
        count+=1
    print()
    #in the rest of the line, find the matching rows and
    #print the columns that match the indices found above
    while line!="":
        line=tsv.readline()
        if line.strip()=="":
            continue
        tokens=line.split()
        if prog.match(tokens[0]):
            print(tokens[0], end='')
            for col in cols:
                print("\t",tokens[col], end='')
            print()

Is there a more 'pythonic' way to do this? I couldn't figure out how to avoid all the for loops and if statements.

(Cross-posted from here)


texts: Kotlin Stack using an ArrayList to compare and remove elements

texts:
Is this a performant strategy to implement a stack in Kotlin to compare and delete values?
Expect
Create a stack in order to compare an array of asteroids (ASTs) and handle collisions (deletions), returning the final array of ASTs after collisions.

Each AST moves at the same speed
Negative numbers move left, positive numbers move right
Smaller ASTs explode (are deleted), the same size both explode, and same direction ASTs do nothing

See: LeetCode
Example 1:
Input: asteroids = [5, 10, -5]
Output: [5, 10]
Explanation: The 10 and -5 collide resulting in 10.  The 5 and 10 never collide.

ArrayList Stack Strategy
Create a stack using an ArrayList to compare asteroid (AST) direction, values, and remove ASTs.
The solution performs as expected in terms of achieving the correct results. However, I'm looking to improve speed and memory performance.
See: GitHub repository

Build ArrayList used as a stack and add the AST values to the stack
Start curIndex at the top of the stack and check the stack until curIndex is at the second element of the stack, thus checking for all possible AST collisions.
Using the current cur and previous prev values, check whether a collision will occur. A collision occurs when prev is positive and cur is negative.
Given a collision with ASTs with equal value, remove both ASTs. If the curIndex is not at the end of the stack after removing ASTs, continue to check for right-most collisions by decrementing curIndex--. Otherwise, fully decrement curIndex-=2
Given a collision with one AST with a larger value, remove the smaller AST. Only decrement when curIndex is at the end of the stack.
If there are no collisions, decrement the stack curIndex--.

Implement
fun asteroidCollision(asteroids: IntArray): IntArray {
    val stack = ArrayList<Int>()
    for (a in asteroids) stack.add(a)
    var curIndex = stack.size - 1
    while (curIndex >= 1) {
        val cur = stack.get(curIndex)
        val prev = stack.get(curIndex - 1)
        if (prev.isRight() && cur.isLeft()) {
            if (Math.abs(cur) == Math.abs(prev)) {
                stack.removeAt(curIndex)
                stack.removeAt(curIndex - 1)
                if (curIndex - 2 == stack.size - 1)
                    curIndex -= 2
                else curIndex--
            } else if (Math.abs(prev) > Math.abs(cur)) {
                stack.removeAt(curIndex)
                if (curIndex - 1 == stack.size - 1)
                    curIndex--
            } else {
                stack.removeAt(curIndex - 1)
                curIndex--
            }
        } else curIndex--
    }
    return stack.toIntArray()
}

fun Int.isLeft() = this < 0
fun Int.isRight() = this > 0

Potential improvement
This seems like it could be a potential improvement. However, it still requires creating a new data structure vs. working with the original array and requires converting the data structure back into an array to return the results.

Build a double LinkedList class.
Pass in one element at a time.
Check the top/last element to see if it collides with the previous element.
Continue to check previous elements after all of the original elements are added.


texts: Script for keeping track of teams in a class

texts:
I wrote this script to help me keep track of who has worked together and for what project or discussion in my classes.

I make a Google Sheet with the names of the students going across the first row and down the first column. Each student gets a number corresponding to their location in the spreadsheet. The value is the letter or number to represent the project or discussion and the numbers are the students who are on a team for that project.

I was particularly unsure of my use of getDataRange() because it seemed like that might not really be necessary since I'm just trying to get a cell. I just didn't see a more efficient way to do that. In my function for setting the backgrounds of the cells to white, I tried using getRange('upperleft:lowerright'), but I wasn't sure if that was really any better (and could possibly introduce errors if I tried to reuse the code for similar purposes in a larger class since I might forget to change it). The updateTeams() code is just where I enter the teams to see how that balances things out since I am trying to have students pair up with as many people as possible in the first few discussions or projects. It's there so I can try out different arrangements without having to remember much about what I tried before. If there is a yellow square at the intersection of two names, it means they have worked together before and the letters or numbers tell on what they worked together.

function fillInTeam(value, numbers){
  var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  var first = 1;
  for (var i = 0; i< numbers.length; i++) {
    var theNum1 = numbers[i];
    for (var z = first; z < numbers.length; z++) {
      var y = numbers[z];
      var cell = spreadsheet.getDataRange().getCell(theNum1, y).setBackground('yellow');
      cell.setValue(cell.getValue() + value);
    }
    first++;
  }
}

function updateTeams(){
  clearBackgrounds();
  fillInTeam('s', [15, 14]);
  fillInTeam('s', [13, 12]);
  fillInTeam('s', [11, 10]);
  fillInTeam('s', [9, 8]);
  fillInTeam('s', [7, 6]);
  fillInTeam('s', [5, 4]);
  fillInTeam('s', [3, 2]);
  fillInTeam('h', [14, 13]);
  fillInTeam('h', [12, 11]);
  fillInTeam('h', [10, 9]);
  fillInTeam('h', [8, 7]);
  fillInTeam('h', [6, 5]);
  fillInTeam('h', [4, 3]);
  fillInTeam('h', [15, 2]);
  fillInTeam('j', [15, 13, 11, 9]);
  fillInTeam('j', [14, 12, 10, 8]);
  fillInTeam('j', [7, 5, 3]);
  fillInTeam('j', [6, 4, 2]);

}

function clearBackgrounds() {
  SpreadsheetApp.getActiveSpreadsheet().getDataRange().setBackground('white');
  SpreadsheetApp.getActiveSpreadsheet().getRange('B2:O15').setValue('');
}


texts: Self Join Exercise. Have I over-complicated it?

texts:
This my 3rd question on the same exercise, but by no means a duplicate.  The two previous questions were posted on StackOverflow here and here.

Now I'm posting my Oracle solution (below) that works. I wonder if the same could've been simpler and/or much more efficient. Not in terms of CTE or analytic expressions but with basic simple logic.

Data:

CREATE TABLE Readings (
  user_id varchar(10),
  reading_time int ,
  x decimal(10,2),
  y decimal(10,2)
);

INSERT ALL
    INTO Readings (user_id, reading_time, x, y) VALUES ('u1', 60, 345, 400)
    INTO Readings (user_id, reading_time, x, y) VALUES ('u1', 100, 560, 300)
    INTO Readings (user_id, reading_time, x, y) VALUES ('u2', 35, 1024, 250)
    INTO Readings (user_id, reading_time, x, y) VALUES ('u1', 90, 450, 450)
    INTO Readings (user_id, reading_time, x, y) VALUES ('u3', 150, 600, 100)
    INTO Readings (user_id, reading_time, x, y) VALUES ('u3', 100, 500, 125)
SELECT * FROM dual;

Intermediate script:

SELECT r.user_id, rm.reading_time start_time, r.reading_time end_time,
       (r.reading_time-rm.reading_time) time_spent,
       (TO_CHAR(rm.x)||' ; '||TO_CHAR(rm.y)) start_point,
       (TO_CHAR(r.x)||' ; '||TO_CHAR(r.y)) end_point,
       SQRT(POWER(r.x-rm.x, 2)+POWER(r.x-rm.y, 2)) distance
FROM Readings r
JOIN Readings rm ON (r.user_id = rm.user_id and
                     rm.reading_time = (SELECT MAX(r2.reading_time) FROM Readings r2 WHERE r2.reading_time < r.reading_time))
ORDER BY 1,2;

Final script:

SELECT rr.user_id, SUM(rr.distance) "Total Distance",
       SUM(rr.time_spent) "Total Time", SUM(rr.distance)/SUM(rr.time_spent) "Average Speed"
FROM
(SELECT r.user_id, (r.reading_time-rm.reading_time) time_spent,
        SQRT(POWER(r.x-rm.x, 2)+POWER(r.x-rm.y, 2)) distance
FROM Readings r
JOIN Readings rm ON (r.user_id = rm.user_id and
                     rm.reading_time = (SELECT MAX(r2.reading_time) FROM Readings r2 WHERE r2.reading_time < r.reading_time))) rr
GROUP BY rr.user_id
ORDER BY 1;

Exercise Description

Multiple users roam a plain and at irregular time intervals report their coordinates (x, y).  This information (user id, time-stamp and the coordinates) populate table Readings.

For each user that reported more than one set of coordinates we need to find total distance traveled, total time spent, and their average speed.

For the sake of simplicity coordinates are Cartesian and time-stamps are integers.


texts:
I have written some code to solve the following interview question. Please advise how it can be improved. Thanks in advance.
A unival tree (which stands for "universal value") is a tree where all nodes under it have the same value. Given the root to a binary tree, count the number of unival subtrees.
For example, the following tree has 5 unival subtrees:
    0
   / \
  1   0
     / \
    1   0
   / \
  1   1

Implementation:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

typedef struct stTree
{
    struct stTree * left;
    struct stTree * right;
    int value;
}

stTree;

stTree* createNode(int value)
{
    stTree *node = malloc(sizeof *node);
    node->left = NULL;
    node->right = NULL;
    node->value = value;

    return node;
}

bool isTreeUniv(stTree *node)
{
    bool flag = true;

    if (!node)
        return false;

    if (node->right && node->right->value != node->value)
    {
        flag = false;
    }

    if (node->left && node->left->value != node->value)
    {
        flag = false;
    }

    return flag;
}

stTree* insertRight(stTree *currNode, int value)
{
    stTree *node = malloc(sizeof *node);

    currNode->right = node;
    node->left = NULL;
    node->right = NULL;
    node->value = value;
    return node;
}

stTree* insertLeft(stTree *currNode, int value)
{
    stTree *node = malloc(sizeof *node);

    currNode->left = node;
    node->left = NULL;
    node->right = NULL;
    node->value = value;
    return node;
}

unsigned int uTreeCount = 0;
void countUnivSubT(stTree *Node)
{
    if (isTreeUniv(Node))
        uTreeCount++;

    if (Node->left)
        countUnivSubT(Node->left);

    if (Node->right)
        countUnivSubT(Node->right);

}

int main(void)
{
    //build a tree
    stTree *rootNode = createNode(0);
    insertLeft(rootNode, 1);
    insertRight(rootNode, 0);

    insertLeft(rootNode->right, 1);
    insertRight(rootNode->right, 0);

    insertLeft(rootNode->right->left, 1);
    insertRight(rootNode->right->left, 1);

    countUnivSubT(rootNode);
    printf("total universal subree: %u\n", uTreeCount);

}


texts: A program that spells a given number [1-999,999,999,999]

texts:
This program created by me spells a number in the standard notation (Billions, Millions etc). I was wondering if there is a better way to do the same thing, or if I have been a victim of some of the bad practices in this language.

I am fairly new to Python and have only been learning it for the past 20 days.
Any other types of suggestions and feedback on my variable naming practices, techniques would be wonderful.

names_dict = {}
names_dict['ones'] = {0: '', 1:'one', 2:'two', 3:'three', 4:'four', 5:'five', 6:'six', 7:'seven', 8:'eight', 9:'nine'}
names_dict['tens'] = {0: '', 2: 'twenty', 3: 'thirty', 4: 'fourty', 5: 'fifty', 6: 'sixty', 7: 'seventy', 8: 'eighty', 9: 'ninty'}

exep = {0: 'ten', 1: 'eleven', 2: 'twelve', 3: 'thirteen', 4: 'fourteen', 5: 'fifteen', 6: 'sixteen', 7: 'seventeen', 8: 'eighteen', 9: 'ninteen'}
sufix = {0: 'billion', 1: 'million', 2: 'thousand', 3: ''}

# int ----> list
def digit_extract(num):
    digit = [0]*12
    iterator = 0
    while num != 0:
        digit[iterator] = num % 10
        iterator += 1
        num //= 10
    return digit[::-1]

#list [3 digit] to str
def hundered(three_digit):
    name = ''
    if three_digit[0] != 0:
        name += names_dict['ones'][three_digit[0]] + ' '  + 'hundered' + ' '

    if three_digit[1] != 1:
        if three_digit[1] != 0:
            name += names_dict['tens'][three_digit[1]] + ' '
        if three_digit[2] != 0:
            name += names_dict['ones'][three_digit[2]]
    else:
        name += exep[three_digit[2]]

    return name

def numberNames():
    num = int(input('Enter the number: '))
    digits = digit_extract(num)
    final_name = ''

    for i in range(4):
        hund = hundered(digits[i*3: (i*3) + 3])
        if hund != '':
            final_name += hund + ' ' + sufix[i] + ' '

    print(final_name.title())

numberNames()


texts:
I want to cythonise the python implementation of the Sutherland-Hogman algorithm. This algorithm updates a list of vertices according to pretty simple rules (being inside or outside an edge, etc.) but the details are not important. Here is the python version it accepts lists of vertices of polygons oriented clockwise. For instance those:

sP=[(50 150),  (200 50),  (350 150), (350 300), (250 300), (200 250), (150 350)(100 250) (100 200)]
cP=[(100, 100), (300, 100), (300, 300), (100, 300)]

and calculate their intersection:

inter=clip(sP, cP)

Here is the code found on rosettacode and slightly modified to return an empty list if there is no intersection.

def clip(subjectPolygon, clipPolygon):
   def inside(p):
      return(cp2[0]-cp1[0])*(p[1]-cp1[1]) > (cp2[1]-cp1[1])*(p[0]-cp1[0])

   def computeIntersection():
      dc = [ cp1[0] - cp2[0], cp1[1] - cp2[1] ]
      dp = [ s[0] - e[0], s[1] - e[1] ]
      n1 = cp1[0] * cp2[1] - cp1[1] * cp2[0]
      n2 = s[0] * e[1] - s[1] * e[0]
      n3 = 1.0 / (dc[0] * dp[1] - dc[1] * dp[0])
      return [(n1*dp[0] - n2*dc[0]) * n3, (n1*dp[1] - n2*dc[1]) * n3]

   outputList = subjectPolygon
   cp1 = clipPolygon[-1]

   for clipVertex in clipPolygon:
      cp2 = clipVertex
      inputList = outputList
      outputList = []
      s = inputList[-1]

      for subjectVertex in inputList:
         e = subjectVertex
         if inside(e):
            if not inside(s):
               outputList.append(computeIntersection())
            outputList.append(e)
         elif inside(s):
            outputList.append(computeIntersection())
         s = e
      if len(outputList)<1:
          return []
      cp1 = cp2
   return(outputList)

This function is excruciatingly slow for my applications so I tried to cythonize it using numpy. Here is my cython version. I had to define the two functions outside clip because I had error messages about buffer inputs.

cimport cython
import numpy as np
cimport numpy as np

def clip(np.ndarray[np.float32_t, ndim=2] subjectPolygon,np.ndarray[np.float32_t, ndim=2] clipPolygon):

    outputList = list(subjectPolygon)
    cdef np.ndarray[np.float32_t, ndim=1] cp1 = clipPolygon[-1,:]
    cdef np.ndarray[np.float32_t, ndim=1] cp2

    for i in xrange(clipPolygon.shape[0]):
       cp2 = clipPolygon[i]
       inputList = outputList
       outputList = []
       s = inputList[-1]

       for subjectVertex in inputList:
          e = subjectVertex
          if inside(e, cp1, cp2):
             if not inside(s, cp1, cp2):
                outputList.append(computeIntersection(cp1, cp2, e, s))
             outputList.append(e)
          elif inside(s, cp1, cp2):
             outputList.append(computeIntersection(cp1, cp2, e, s))
          s = e
       if len(outputList)<1:
         return []
       cp1 = cp2

    return(outputList)

def computeIntersection(np.ndarray[np.float32_t, ndim=1] cp1, np.ndarray[np.float32_t, ndim=1] cp2, np.ndarray[np.float32_t, ndim=1] e, np.ndarray[np.float32_t, ndim=1] s):
    cdef np.ndarray[np.float32_t, ndim=1] dc = cp1-cp2
    cdef np.ndarray[np.float32_t, ndim=1] dp = s-e
    cdef np.float32_t n1 = cp1[0] * cp2[1] - cp1[1] * cp2[0]
    cdef np.float32_t n2 = s[0] * e[1] - s[1] * e[0]
    cdef np.float32_t n3 = 1.0 / (dc[0] * dp[1] - dc[1] * dp[0])
    cdef np.ndarray[np.float32_t, ndim=1] res=np.array([(n1*dp[0] - n2*dc[0]) * n3, (n1*dp[1] - n2*dc[1]) * n3], dtype=np.float32)
    return res

def inside(np.ndarray[np.float32_t, ndim=1] p, np.ndarray[np.float32_t, ndim=1] cp1, np.ndarray[np.float32_t, ndim=1] cp2):

    cdef bint b=(cp2[0]-cp1[0])*(p[1]-cp1[1]) > (cp2[1]-cp1[1])*(p[0]-cp1[0])
    return b

When I time the two versions I gained only a factor of two in speed-up I need at least 10 times that (or 100x !). Is there something to do ?
How does one deal with variable sized list with Cython ?
I do not know if this could be useful but my inputs are of fixed length.


texts:
I have one table on which I want to perform some calculations.  The table stores employee points that are awarded for performing various tasks.  The relevant structure is as follows (table has about 15,000 rows):

PointsTable:

  ID int IDENTITY(1, 1),
  EmployeeFirstName (varchar),
  EmployeeLastName (varchar),
  PointsAwarded (decimal(18, 2)),
  TransactionDate (date)

For each row, I want to return the following:

Employee Name
Points Awarded
Transaction Date
Employee's Running Total (cumulative sum for that one employee)
Employee's Total Points (sum of all points for that one employee)
Running Total (cumulative sum for all employees)
Total Points (sum of all points for all employees)
Employee's Running Percentage (Employee's Running Total / Employee's Total Points)
Employees' Total Percentage (Employee's Total Points / Total Points)
Total Running Percentage (Running Total / Total Points)

Here is the query I am currently using:

SELECT  EmployeeFirstName + ' ' + EmployeeLastName AS [Employee],
        PointsAwarded,
        TransactionDate,
        [Employee Running Total],
        [Employee Running Total] / [Employee Total Points] AS [Employee Running Percentage],
        [Employee Total Points],
        [Employee Total Points] / [Total Points] AS [Employee Total Percentage],
        [Running Total Points],
        [Running Total Points] / [Total Points] AS [Total Running Percentage],
        [Total Points]
FROM
    (
    SELECT  EmployeeFirstName,
            EmployeeLastName,
            PointsAwarded,
            TransactionDate,
            SUM(PointsAwarded) OVER (PARTITION BY EmployeeFirstName, EmployeeLastName ORDER BY ID) AS [Employee Running Total],
            SUM(PointsAwarded) OVER (PARTITION BY EmployeeFirstName, EmployeeLastName) AS [Employee Total Points],
            SUM(PointsAwarded) OVER(ORDER BY ID) AS [Running Total Points],
            SUM(PointsAwarded) OVER() AS [Total Points]
    FROM PointsTable
    ) t

This query works and returns the results as expected.  However, I feel like it can be optimized.  Is it possible to include the calculations within the sub query, without repeating code?

For example, this code is necessary to give the Employee Running Percentage:

SUM(PointsAwarded) OVER (PARTITION BY EmployeeFirstName, EmployeeLastName ORDER BY ID) /
SUM(PointsAwarded) OVER (PARTITION BY EmployeeFirstName, EmployeeLastName)

Is there a way to accomplish this with windowing - WITHOUT repeating the OVER functions a bunch of times?  So far, the only way I've been able to achieve this is in the manner I've posted.  I'm thinking a CTE would be more or less the same, but I'm not an expert.

Here is the execution plan.


texts:
I've been trying to write a jQuery script where when someone clicks on the input the space clears and then if they don't type anything in, it reappears.

This is what I came up with. Is there a better way to do this? If so why is it better?

$(document).ready(function() {
            // set all input.text default value according to alt attribute
            $("input.contactStyle").each(function(){
                $(this).val($(this).attr("alt"));
            });

            // clear input.text on focus, if still in default
            $("input.contactStyle").focus(function() {

                if($(this).val()==$(this).attr("alt")) {
                    $(this).val("");
                }
            });

            // if field is empty afterward, add text again
            $("input.contactStyle").blur(function() {
                if($(this).val()=="") {
                    $(this).val($(this).attr("alt"));
                }
            });

            // set all input.text default value according to alt attribute
            $("textarea.contactStyle").each(function(){
                $(this).val($(this).attr("title"));
            });

            // clear input.text on focus, if still in default
            $("textarea.contactStyle").focus(function() {

                if($(this).val()==$(this).attr("title")) {
                    $(this).val("");
                }
            });

            // if field is empty afterward, add text again
            $("textarea.contactStyle").blur(function() {
                if($(this).val()=="") {
                    $(this).val($(this).attr("title"));
                }
            });
});


texts:
I still have to implement API keys for client auth, but so far this is what I have for users.  This was built using WebAPI and SimpleMembership with Forms Auth:

Is Authenticated:

public class AccountController : ApiController
{
public static DtoService _service = new DtoService();

// GET/api/isAuthenticated
[System.Web.Http.HttpGet]
public HttpResponseMessage IsAuthenticated()
{
    try
    {
        if (User.Identity.IsAuthenticated)
            return Request.CreateResponse(HttpStatusCode.OK, WebSecurity.GetUserId(User.Identity.Name));
        else
            return Request.CreateResponse(HttpStatusCode.OK, false);
    }
    catch (Exception e)
    {
        return Request.CreateResponse(HttpStatusCode.InternalServerError, e);
    }

}

Login:

// POST /api/login
// [System.Web.Http.AllowAnonymous]
[System.Web.Http.HttpPost]
public HttpResponseMessage LogIn(LoginModel model)
{
    if (!ModelState.IsValid)
        return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
    try
    {
        if (User.Identity.IsAuthenticated)
            return Request.CreateResponse(HttpStatusCode.Conflict, "already logged in.");
        if (!WebSecurity.UserExists(model.UserName))
            return Request.CreateResponse(HttpStatusCode.BadRequest, "User does not exist.");
        if (WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe))
        {
            FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
            return Request.CreateResponse(HttpStatusCode.OK, "logged in successfully");
        }
        return Request.CreateResponse(HttpStatusCode.BadRequest, "Login Failed.");
    }
    catch (Exception e)
    {
        return Request.CreateResponse(HttpStatusCode.InternalServerError, e);
    }
}

Log Out:

// POST /api/logout
[System.Web.Http.HttpPost]
////[ValidateAntiForgeryToken]
// [System.Web.Http.AllowAnonymous]
[Authorize]
public HttpResponseMessage LogOut()
{
    try
    {
        if (User.Identity.IsAuthenticated)
        {
            WebSecurity.Logout();
            return Request.CreateResponse(HttpStatusCode.OK, "logged out successfully.");
        }
        return Request.CreateResponse(HttpStatusCode.Conflict, "already done.");
    }
    catch (Exception e)
    {
        return Request.CreateResponse(HttpStatusCode.InternalServerError, e);
    }
}

Register:

// POST: /api/register
[System.Web.Http.HttpPost]
//[ValidateAntiForgeryToken]
public HttpResponseMessage Register(RegisterModel model)
{
    if (!ModelState.IsValid)
    {
        return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
    }
    try
    {
        if (User.Identity.IsAuthenticated)
            return Request.CreateResponse(HttpStatusCode.Conflict, "User Already Registered and Logged In");
        if (WebSecurity.UserExists(model.UserName))
            return Request.CreateResponse(HttpStatusCode.Conflict, "User Already Registered");
        else
        {
            // Attempt to register the user
            WebSecurity.CreateUserAndAccount(model.UserName, model.Password);
            WebSecurity.Login(model.UserName, model.Password);
            InitiateDatabaseForNewUser(WebSecurity.GetUserId(model.UserName));

            FormsAuthentication.SetAuthCookie(model.UserName, createPersistentCookie: false);
            return Request.CreateResponse(HttpStatusCode.Created, WebSecurity.GetUserId(model.UserName));
        }

    }
    catch (Exception e)
    {
        return Request.CreateResponse(HttpStatusCode.InternalServerError, e);
    }
}


texts:
I wanted to make a class that connects to my server and returns a value, a URL in this case. As Android 4.0 doesn't let me run network task on the main UI thread (rightly so) I have made this.

Please give me your feedback as to if it is thread safe or not and ways to improve it. I have never used ExecutorService or Future before so I would be grateful to know if I am using it correctly. I would also like to know if this is blocking the thread that called getDownloadURL.

public class DownloadURLServerGetter implements DownloadURLGetter {

    private ServerAdapter serverAdapter;
    private String id;

    @Inject
    public DownloadURLServerGetter(ServerAdapter serverAdapter) {
        this.serverAdapter = serverAdapter;
    }

    @Override
    public synchronized String getDownloadURL(String id) throws IOException {
        this.id = id;
        final ExecutorService service;
        final Future<String> task;

        service = Executors.newFixedThreadPool(1);
        task = service.submit(new MyCallable());
        try {
            return task.get();
        } catch (InterruptedException e) {
            throw new IOException(e);
        } catch (ExecutionException e) {
            throw new IOException(e);
        }
    }

    public class MyCallable implements Callable<String> {

        @Override
        public String call() throws Exception {

            HttpResponse resp = serverAdapter.get("blobs/" + id);
            String url = EntityUtils.toString(resp.getEntity());
            return Parser.parseURL(url);
        }
    }

}


texts:
I started learning PHP and MySQL, was using MySQL_ functions. Then I learned they are deprecated, had to choose between PDO and MySQL. I chose MySQL and started using it.

As I learn OOP PHP, I thought I should change my code to OOP style, since it's cleaner. I was wondering whether this block of my code is secure or not. I use mysqli_real_escape_string() and htmlspecialchars() above.

Old code

$result = "INSERT INTO book(book_original_name, book_turkish_name, book_publication_date, book_synopsis) VALUES (?,?,?,?)";
$stmt = mysqli_prepare($sqli, $result);
mysqli_stmt_bind_param($stmt, "ssss", $_POST['book_original_name'], $_POST['book_tr_name'], $_POST['book_year'], $_POST['book_synopsis']);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);

New code ($sqli is my connection variable.)

$stmt = $sqli->prepare("INSERT INTO book(book_original_name, book_turkish_name, book_publication_date, book_synopsis) VALUES (?,?,?,?)");
$stmt->bind_param("ssss", $_POST['book_original_name'], $_POST['book_tr_name'], $_POST['book_year'], $_POST['book_synopsis']);
$stmt->execute();
$stmt->close();
echo "Mission has been completed, sir!";