texts: Python process tracklist, get cumulative timestamp of each track

texts:
The code below parses a tracklist (sample input below) and generates a six-member tuple, including cumulative timestamps in mm:ss. (sample output at bottom).

couldn't easily see how to rewrite it from a for-loop to a generator get_track_with_cumulative_timestamp(itt)
I think we don't need a custom object, i.e. avoid this approach
generator will need to internally store state (tmm, tss) being the end-time of each song. So we yield each result with the start-time of each song; incrementing the time-arithmetic comes after that.
are there better idioms for the (mm,ss) modulo-60 counters? decimal.Decimal seems overkill. I suppose we could always pull a trick internally using one float to represent both (mm,ss)

Current not-so-great procedural code:

tracklist = """
1. Waiting For A Miracle 5:02
2. Bedroom Eyes 5:01
3. In Over My Head 4:31
4. Higher Ground / Written-By – S. Wonder* 3:38
5. Hot Blood 4:15
6. Running Away 4:28
7. I've Had Enough 3:47
8. Blacklisted / Guitar [Other] – Jonny Fean* 4:11
9. Last Thing At Night 2:49"""

tracklist = [t for t in tracklist.split('\n') if t]

import re

pat = re.compile(r'(?P<no>[0-9]+)\. (?P<name>.*) (?P<mm>[0-9]+):(?P<ss>[0-9]+)')

(tmm,tss) = (0,0)
result = []

for t in tracklist:
    m = pat.match(t)
    #print(m.groups())
    lmm, lss = int(m['mm']), int(m['ss'])

    result.append((int(m['no']), tmm, tss, lmm, lss, m['name']))
    #yield (int(m['no']), tmm, tss, lmm, lss, m['name']))

    tss += lss
    tmm += lmm
    if tss >= 60:
        tmm += 1
        tss -= 60

# Output looks like this:
for _ in result: print('{} | {:02d}:{:02d} | {}:{:02d} | {}'.format(*_))

1 | 00:00 | 5:02 | Waiting For A Miracle
2 | 05:02 | 5:01 | Bedroom Eyes
3 | 10:03 | 4:31 | In Over My Head
4 | 14:34 | 3:38 | Higher Ground / Written-By – S. Wonder*
5 | 18:12 | 4:15 | Hot Blood
6 | 22:27 | 4:28 | Running Away
7 | 26:55 | 3:47 | I've Had Enough
8 | 30:42 | 4:11 | Blacklisted / Guitar [Other] – Jonny Fean*
9 | 34:53 | 2:49 | Last Thing At Night


texts: Java cycle detection using DFS in an undirected graph

texts:
I am doing interview studies and can't find a simple DFS for a cycle-finding algorithm.  I want someone to tell me if my DFS algorithm works and how it can be improved.

Where can you get a typical DFS cycle finding algorthm for Java?  I assume you have to "mark" the nodes and edges in order to find a cycle?  Can you simplify / improve it? e.g. A-->B-->A , shouldn't be a cycle!

boolean isCycled(Node root){
    return isCycled(root, -1);
}

boolean isCycled(Node n, int edgeNum){
    //base case
    if(n==null) return false;

    //base case: if an unexplored edge that lead to a node that is visited.
    if(edgeNum>=0){//make sure it is not the first node
        if(n.visted==true && edge[edgeNum]!=true ) {
            return true; //found cycle
        }
    }

    n.visited=true;
    edge[edgeNum]==true; // already explored edge wont' lead to cycle.

    List nodes = getAllNeigbors(n); //visited or unvisited

    boolean isCycle = false;

    for(Node node : nodes){
        isCycle = isCycle || isCycled(node, getEdgeNum(n,node));
    }

    return isCycle;
}


texts: Is using defvar for a non-global variable ok?

texts:
I am calling defvar in the middle of a function definition. And so far I've always seen its use, with defparameter for global variable. Like *error-output* or *standard-output*.

(defun consume-socket-reply (socket end-test-form)
  (do* ((line "" (read-line (usocket:socket-stream socket) nil))
        (text "" (concatenate 'string text line)))
       ((funcall end-test-form) text)))

(defun read-http-content (socket)
  (defvar line)
  (consume-socket-reply socket (lambda () (not line))))

Is there a better way to write what I am trying to do? That is: being able to pass the end-test-form to the final inner loop.


texts: My own twist on the classic "Guessing Game" script in Python

texts:
This is a (letter, or whatever the user decides to change it to) guessing game I wrote which implements both a mechanic to randomly change the order of elements in a list, as well as limit the number of attempts you get to complete the game. There's not much else to say about it. I'm just looking for some suggestions on where I can condense things and better optimize my code.

import random

samples = random.sample(['x', 'y', 'z'], 3)
keys = []

for i in samples:
    str(keys.append(i))

attempts_left = 3

print("X, Y, and Z are arranged in random order.")
print("The object of the game is to guess them in order before you run out of tries.\n")

while len(keys) > 0:

    for i, j in list(enumerate(keys, start=1)):
        key = j

        while attempts_left > 0:

            print("Round {}".format(i))
            guess = input("> ").lower()

            if guess == key:
                i += 1
                print("Correct\n")
                keys.remove(key)
                break

            elif guess not in ['x', 'y', 'z']:
                print("That's not one of the options.")

            else:
                print("Wrong\n")
                attempts_left -= 1

    if attempts_left > 0:
        print("You win!")
        break

    else:
        print("You LOSE!")
        print("Good DAY, sir!")
        break


texts:
I have a list of rule names coming from .xml file. These rule names needs to be validated against rule names in database (Validator.cs). If valid, then Id of these rule names are used to fetch user data from database (ExportService.cs).

I am using a Dictionary object to save name, Id pair from database -

Validator.cs

var rulesDictionary = new Dictionary<string, string>();
while (sqlDataReader.Read())
{
    string ruleName = sqlDataReader["NAME"].ToString();
    string ruleLink = sqlDataReader["LINK"].ToString();
    rulesDictionary.Add(ruleName, ruleLink);
}

The values coming from XML file are validated against this dictionary as -

ExportService.cs

if (DepositRulesDictionary.ContainsKey(xmlRuleName1) == false)
{
     //log error
}

If all the values are valid, then this dictionary is further used to pass 'ruleLink' values in ExportService.cs.

I used Dictionary object in this instance as it returns O(1) result for validating XML file values.

My XML file is not going to be very big, so efficiency is not a major concern right now.

My question is what is more recommended -

Dictionary<string, string> object or
List<T> where T is having two properties of Name and Link.

For scalability and unit-testability?


texts:
foo = {}
print 'yes' if foo.get('bar', None) else None

Is there any way if I can improve this code?

Logic: if bar key is there, print 'yes' else print None


texts:
Are there more optimization possible in this code to achieve better performance and minimal memory usage?

#include<stdio.h>
char * strrev(char* str)
{
     int length=0;
     char* str1=str;

     while(*str++)
        ++length;

     str=str1;
     char  temp;

     for ( int i=0; i< length/2; ++i)
     {
           temp= *(str +i);
           *(str +i) = *(str+length -1-i);
           *(str+length -1-i)= temp;
     }

     return str1;
}
int main()
{
    char str[]="Hello World!";
    strrev(str);
    printf("Reversed str:%s", str);

    return 0;

}


texts: Heavily nested anonymous classes for Swing UIs

texts:
Oftentimes, I write small little dialogs or forms without a UI builder. I usually find myself having a lot of "container" panel variables that just float around. I found this leads to time-wasting experiences.

Where did I put that BorderLayout panel?
Oh right, here it is.
Wait, never mind. That one has a GridLayout.

A while ago, I had the idea to nest widgets in anonymous classes, directly in add calls. This way, a simple layout has fewer variables that get in the way of digesting the code's logic since every component is nicely indented in its own scope.
Pros

Component hierarchy is obvious, as are component attributes like colors and fonts
Code is cleaner, with less dummy container variables
Forces component logic to be encapsulated directly in the component (i.e. not 50 lines up or below the component initialization: saves time)
I found it easier to come back to code written in this style after a couple months and still understand the layout.

Cons

Might bloat generated code size, because all the Swing constants would have to be written to each classfile

Below is a simple (Java 8) frame that shows a button and a label. I realise that this same layout could have been made with fewer panels, but I'm presenting it as an overly explicit example of my approach.
import javax.swing.*;
import java.awt.*;

public class TestFrame extends JFrame {
    public TestFrame() {
        super("A Frame");
        add(new JPanel() {
            {
                setLayout(new BorderLayout());
                setBackground(Color.LIGHT_GRAY);
                add(new JPanel() {
                    {
                        setLayout(new BorderLayout());
                        setOpaque(false);
                        add(new JLabel("A label", JLabel.LEFT) {
                            {
                                setBorder(BorderFactory.createEmptyBorder(0, 10, 0, 10));
                                setFont(getFont().deriveFont(Font.BOLD));
                            }
                        }, BorderLayout.EAST);
                        add(new JButton("Click me!") {
                            int timesClicked = 0;

                            {
                                addActionListener((x) -> {
                                    timesClicked++;
                                    setText(String.format("You've clicked me %d time(s)!", timesClicked));
                                });
                            }
                        }, BorderLayout.CENTER);
                    }
                });
            }
        });
        setSize(new Dimension(640, 480));
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    public static void main(String[] argv) {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (ReflectiveOperationException | UnsupportedLookAndFeelException ignored) {
        }
        SwingUtilities.invokeLater(() -> {
            TestFrame test = new TestFrame();
            test.setVisible(true);
        });
    }
}

I (and I'm not by any means an expert on Swing) haven't seen Swing code like this around on StackExchange sites, or really, anywhere I look. I can't have been the only one to think of this approach - is there a reason why an aggressive subclassing approach is not preferred, or have I just not been searching hard enough?
I think the readability benefits far outweigh any costs this approach has.


texts: Comparing data in SQL using foreign keys

texts:
The following is given:

CREATE TABLE City (
  city_name varchar(255),
  country varchar(255),
  primary key (city_name)
  );

insert into City(city_name, country) values('London', 'England');
insert into City(city_name, country) values('Santiago', 'Chile');
insert into City(city_name, country) values('Edinburgh', 'Scotland');
insert into City(city_name, country) values('Tallinn', 'Estonia');
insert into City(city_name, country) values('Madrid', 'Spain');
insert into City(city_name, country) values('Paris', 'France');

CREATE TABLE Airport (
  airport_code int,
  city_name varchar(255),
  primary key (airport_code)
  );

insert into Airport(airport_code, city_name) values (123, 'London');
insert into Airport(airport_code, city_name) values (431, 'London');
insert into Airport(airport_code, city_name) values (439, 'Tallinn');
insert into Airport(airport_code, city_name) values (252, 'Santiago');
insert into Airport(airport_code, city_name) values (240, 'Paris');
insert into Airport(airport_code, city_name) values (992, 'Edinburgh');
insert into Airport(airport_code, city_name) values (972, 'Tallinn');
insert into Airport(airport_code, city_name) values (754, 'Tallinn');

CREATE TABLE FlightDelays (
   flight_code varchar(255),
   origin int,
   destination int,
   average_minute_delay int,
   price int,
   primary key (flight_code),
   foreign key (origin) references Airport (airport_code),
   foreign key (destination) references Airport (airport_code)
   );

insert into FlightDelays(flight_code, origin, destination, average_minute_delay, price) values
('XQ1242', 123, 431, 10, 20);
insert into FlightDelays(flight_code, origin, destination, average_minute_delay, price) values
('PX1203', 439, 252, 2, 20);
insert into FlightDelays(flight_code, origin, destination, average_minute_delay, price) values
('OO2442', 992, 972, 9, 20);
insert into FlightDelays(flight_code, origin, destination, average_minute_delay, price) values
('XK1442', 972, 431, 15, 20);
insert into FlightDelays(flight_code, origin, destination, average_minute_delay, price) values
('PW4332', 123, 754, 40, 20);
insert into FlightDelays(flight_code, origin, destination, average_minute_delay, price) values
('QJ332', 754, 431, 4, 20);

Question:

  Express the following query in SQL:
  "What are the ﬂights whose origin airport and destination airport are in the same city?"

How can I improve my solution?

select z.flight_code, z.origin, z.destination
from (
      select a.flight_code, a.origin, a.oCity, a.destination, Airport.city_name as dCity
      from (
            select FlightDelays.flight_code, FlightDelays.origin, Airport.city_name as oCity, FlightDelays.destination
            from FlightDelays
            inner join Airport on FlightDelays.origin = Airport.airport_code) as a
      inner join Airport on a.destination = Airport.airport_code) as z
where oCity=dCity;


texts: Enumerating text (ranges) vertically and horizontally

texts:
I'm writing a parser and I need to iterate through text vertically (down to bottom) and horizontally (left to right).

This alone would be easy but some text parts need to be rescanned by another parser and for this I need to reiterate over random lines or a text range.

I wrote two enumerators.

One for enumerating all lines or only some of them:

internal class LineEnumerator
{
    private const int IndexOutOfRange = -1;

    public LineEnumerator(IReadOnlyList<string> lines) : this(lines, null) { }

    public LineEnumerator(IReadOnlyList<string> lines, IReadOnlyList<int> lineNumbers)
    {
        Lines = lines;
        Index = -1;
        LineNumbers = lineNumbers;
    }

    public IReadOnlyList<string> Lines { get; }
    public IReadOnlyList<int> LineNumbers { get; }
    public int Index { get; private set; }
    public bool IsIndexInRange => Index > IndexOutOfRange && Index < (LineNumbers?.Count ?? Lines.Count);
    public int LineNumber
    {
        get
        {
            if (!IsIndexInRange) { return IndexOutOfRange; }
            return LineNumbers?[Index] ?? Index;
        }
    }
    public string Current => IsIndexInRange ? Lines[LineNumber] : null;

    public CharEnumerator Chars => IsIndexInRange ? new CharEnumerator(Current) : null;

    public bool MoveNext() => ++Index < (LineNumbers?.Count ?? Lines.Count);
}

and another one for enumerating chars or only a particular range:

internal class CharEnumerator
{
    private const int IndexOutOfRange = -1;

    public CharEnumerator(string line) : this(line, 0, line.Length) { }

    public CharEnumerator(string line, int index0, int length)
    {
        Line = line;
        Index0 = index0;
        Length = length;
        Index = IndexOutOfRange;
    }

    public string Line { get; }
    public int Index0 { get; }
    public int Length { get; }
    public int Counter { get; private set; }
    public int Index { get; private set; }
    public bool IsIndexInRange => Index >= Index0 && Counter <= Length;
    public char Current => IsIndexInRange ? Line[Index] : '\0';

    public bool MoveNext()
    {
        if (!IsIndexInRange)
        {
            Index = Index0;
            Counter++;
            return true;
        }
        Index++;
        Counter++;
        return (Counter <= Length);
    }
}

They shouldn't just enumerate the text but also keep track of where they are so that I can throw exceptions with exact location if something goes wrong thus the line enumerator needs to work with real indexes even for a range. The same applies to the char enumerator.

I feel like the enumerators violate SRP (single responsibility principle) and I should create two more enumerators for enumerating a range of lines or a range of characters. Is this necessary or would you leave it like that?

Examples

var lines = new[] { "foo", "bar", "baz", "qux" };
var lineEnumerator = new LineEnumerator(lines);
while (lineEnumerator.MoveNext())
{
    Console.WriteLine(lineEnumerator.Current);
}

  foo bar baz qux

Console.WriteLine();
var lineRangeEnumerator = new LineEnumerator(lines, new[] { 1, 3 });
while (lineRangeEnumerator.MoveNext())
{
    Console.WriteLine(lineRangeEnumerator.Current);
}

  bar qux

Console.WriteLine();
var line = "foo bar baz";
var charEnumerator = new CharEnumerator(line);
while (charEnumerator.MoveNext())
{
    Console.WriteLine(charEnumerator.Current);
}

  f o o   b a r   b a z

Console.WriteLine();
var charRangeEnumerator = new CharEnumerator(line, 4, 3);
while (charRangeEnumerator.MoveNext())
{
    Console.WriteLine(charRangeEnumerator.Current);
}

  b a r


texts: Iterating through a linked-list in a cleaner manner

texts:
I have a collection of PlaylistItem objects. They are linked together such that each item knows the ID of its next/previous item. I am iterating over this collection of objects, starting at a known position and working with each object once. I'm not a big fan of how I do this, but I am not seeing an obvious way of rewriting it.

var firstItemId = activePlaylist.get('firstItemId');
var currentItem = activePlaylist.get('items').get(firstItemId);

//  Build up the ul of li's representing each playlistItem.
do {

    var listItem = $('<li/>', {
        'data-itemid': currentItem.get('id'),
        contextmenu: function (e) {

            var clickedItemId = $(this).data('itemid');
            var clickedItem = activePlaylist.get('items').get(clickedItemId);

            contextMenu.initialize(clickedItem);

            //  +1 offset because if contextmenu appears directly under mouse, hover css will be removed from element.
            contextMenu.show(e.pageY, e.pageX + 1);
            //  Prevent default context menu display.
            return false;
        }
    }).appendTo(playlistItemList);

    $('<img>', {
        'class': 'playlistItemVideoImage',
        src: 'http://img.youtube.com/vi/' + currentItem.get('video').get('id') + '/default.jpg',
    }).appendTo(listItem);

    $('<a/>', {
        text: currentItem.get('title')
    }).appendTo(listItem);

    currentItem = activePlaylist.get('items').get(currentItem.get('nextItemId'));
} while (currentItem && currentItem.get('id') !== firstItemId)

How would you write this?

Note that it is a do-while because I want to ensure I always render that firstItem. If there's only one item in the list, the loop will immediately terminate. Thus the need for the do-while.


texts:
I'm practicing Python. Being completely new to the language I'd like to hear someone else thoughts on the way I use the language. I'm coming from (mainly) Java and C so I'd expect new ways of doing stuff offered by Python which I am surely not aware of because I'm still learning.

I came up with a very simple implementation for a binary tree. The idea is to practice with classes in Python. The tree supports just inserting elements and traversing pre-order, in-order and post-order. I'm not concerned about the functionality but more about comments.

from __future__ import print_function
import math
import os

class BinaryTree:
    __left = None
    __right = None
    __value = None

    def __init__(self):
        return

    def addValue(self, value):
        if self.__value is None:
            self.__value = value

        elif value > self.__value:
            if self.__right is None:
                self.__right = BinaryTree()
            self.__right.addValue(value)

        elif value < self.__value:
            if self.__left is None:
                self.__left = BinaryTree()
            self.__left.addValue(value)

        return

    def preOrderTraverse(self):
        """
        Performs a pre-order traversal of the tree.
        Returns the list of elements
        """
        elements = []
        if self.__value is not None:
            # Visit the root node first
            elements.append(self.__value)
            # Then visit the left node if present
            if self.__left is not None:
                elements += self.__left.preOrderTraverse()
            # Then visit the right node if present
            if self.__right is not None:
                elements += self.__right.preOrderTraverse()

        return elements

    def inOrderTraverse(self):
        """
        Performs a in-order traversal of the tree.
        Returns the list of elements
        """
        elements = []
        if self.__value is not None:
            # Visit the left node first if present
            if self.__left is not None:
                elements += self.__left.inOrderTraverse()
            # Then visit the root node
            elements.append(self.__value)
            # Then visit the right node if present
            if self.__right is not None:
                elements += self.__right.inOrderTraverse()

        return elements

    def postOrderTraverse(self):
        """
        Performs a post-order traversal of the tree.
        Returns the list of elements
        """
        elements = []
        if self.__value is not None:
            # Visit the left node first if present
            if self.__left is not None:
                elements += self.__left.postOrderTraverse()
            # Then visit the right node if present
            if self.__right is not None:
                elements += self.__right.postOrderTraverse()
            # Then visit the root node
            elements.append(self.__value)

        return elements

if __name__ == "__main__":
    binarytree = BinaryTree()
    binarytree.addValue(23)
    binarytree.addValue(15)
    binarytree.addValue(19)
    binarytree.addValue(8)
    binarytree.addValue(7)
    binarytree.addValue(42)
    binarytree.addValue(0)
    binarytree.addValue(1)
    elements = binarytree.preOrderTraverse()

    print("Pre order traversal: ", end="")
    for val in elements:
        print(val, end=" ")

    print("")

    elements = binarytree.inOrderTraverse()

    print("In order traversal: ", end="")
    for val in elements:
        print(val, end=" ")

    print("")

    elements = binarytree.postOrderTraverse()

    print("Post order traversal: ", end="")
    for val in elements:
        print(val, end=" ")

    print("")


texts:
Here is my vampire based text adventure game.
I recently started learning Python and Googled for some good projects to practice with. I wrote all this code myself after checking out some examples on the internet.
import time #added to enable pause

#A text based dracula survival game

#possible answers
answer_A = ['A', 'a']
answer_B = ['B', 'b']
answer_C = ['C', 'c']
yes = ['yes', 'Yes', 'y', 'Y']
no = ['no', 'No', 'n', 'N']

#story begins here
def intro():
    print('You wake up in front of a castle, you have no idea where you are or why you are here.'
    'You suddenly see a colony of bats fly away.' 'You turn back and see a vampire figure appear out of nowhere. You will:')
    time.sleep(1)
    print('''    A. Ask for direction.
    B. Run inside the castle.
    C. Run to the cave.''')
    choice = input('>>>  ')
    if choice in answer_A:
        print('\n Well you dont ask vampires for directions. \n\nRip')
    elif choice in answer_B:
        option_castle()
    elif choice in answer_C:
        option_cave()
    else:
        print("That's not an option idiot")
        intro()

def option_castle():
    print('You ran inside the castle and see a glass front cubboard with garlic inside.You hear the Vampire coming,''You will: ')
    time.sleep(1)
    print('''    A. Take the garllic to scare the vampire.
    B. Hide
    C. Escape from backdoor.''')
    choice = input('>>>  ')
    if choice in answer_A:
        print('This is not a story book, what are you doing? Making salad? \n\n RIP')
        option_death()
    elif choice in answer_B:
        print("This is not hide n'seek \n\n RIP" )
        option_death()
    elif choice in answer_C:
        option_abdvilllage()
    else:
        print('Not an option idiot')
        option_castle()

def option_cave():
    print('You ran inside a dark cave, you were not sure if its a good idea or not but in there you see a shiny silver dagger.' 'Hurry bats are coming: ')
    time.sleep(1)
    print('''    A. You pick up the dagger and fight.
    B. You pick up the dagger and hide.
    C. You run.''')
    choice = input('>>>  ')
    if choice in answer_A:
        print('You picked the silver dagger and stood there like a fearsome warrior. The vampire attacked you but you were cunning and avoiding its attack stabbed the vampire right in its heart. Well done vampire slayer, you may live.')
    elif choice in answer_B:
        print("Cowards don't get to fight and live. \n\n RIP")
        option_death()
    elif choice in answer_C:
        option_abdvilllage()
    else:
        print('not an option idiot')
        option_cave()

def option_abdvilllage():
    print('You ran towards an abandoned village in the open. The bats are coming faster than before, you will: ')
    time.sleep(1)
    print('''    A. Hide
    B. Pick a wood to stab the vampire
    C. Enter the cave''')
    choice = input('>>>  ')
    if choice in answer_A:
        print('You hid in a hut and well it worked, you were lucky and the sun rose killing the vampire. You were a coward but a lucky one.')
    elif choice in answer_B:
        print("For real? How can a piece of wood kill an immortal blood sucking human size bat? \n\n RIP")
        option_death()
    elif choice in answer_C:
        option_cave()
    else:
        print('not an option idiot')
        option_abdvilllage()

def option_death():
    choice = input('Do you want to play again? Yes or No  ')
    if choice in yes:
        intro()
    else:
        print('very well')

play = input('Do you want to play? Y or N  ')
if play == 'Y'.lower():
    intro()
else:
    print('very well')


texts: Creating a C++ style class for storing a data on 2D grid on GPU memory

texts:
UPDATED
I would like to create a class, which is intended to represent a field of values on a 2D grid. So, I would like to access the elements with a double square bracket A[i][j], and inside the __global__ or __device__ function access the dimensions of the field - nx_, ny_, because I do not want to pass them each time as an arguments to the functions.
In order to execute multiple threads on this structure, as far as I understand, I have to pass it as a pointer on the device memory. I've come with a following solution, but it doesn't look very beatufil and efficient.
template <typename T>
struct Field
{
    DEVHOST Field(size_t nx, size_t ny)
    {
        cudaMalloc(reinterpret_cast<void**>(&dev_ptr_), sizeof(dev_ptr_));
        init_kernel<<<1,1>>>(dev_ptr_, nx, ny);
    }

    DEVHOST ~Field()
    {
        delete_kernel<<<1,1>>>(dev_ptr_);
        cudaFree(dev_ptr_);
    }

    Field<T>* devPtr()
    {
         return dev_ptr_;
    }

    const Field<T>* devPtr() const
    {
         return dev_ptr_;
    }

    DEVHOST size_t size() const
    {
        return nx_ * ny_;
    }

    DEVHOST T* operator[](size_t idx)
    {
        return data_ + idx * nx_;
    }

    DEVHOST const T* operator[](size_t idx) const
    {
        return data_ + idx * nx_;
    }

public:
    size_t nx_;
    size_t ny_;

    T* data_;

    Field<T>* dev_ptr_;
};

template <typename T>
KERNEL void init_kernel(Field<T>* f, size_t nx, size_t ny)
{
    f->nx_ = nx;
    f->ny_ = ny;
    f->data_ = reinterpret_cast<T*>(malloc(nx * ny * sizeof(T)));
}

template <typename T>
KERNEL void delete_kernel(Field<T>* f)
{
    free(f->data_);
}

In order to create an instance of Field<T> to be worked with further, I need to call a kernel, which initializes it. And then a kernel to delete this object on the device memory. The code on the host will look like:
Field<float>* f;
init_kernel<<<1,1>>>(f, 100, 100);
delete_kernel<<<1,1>>>(f);

What would be the more robust and clever way to implement the desired functionality. I would appreciate any suggestions, or references to the good practices of CUDA Programming, except for the docs.nvidia.com.
The intended usage
Several instances of this Field are stored in another structure, namely
struct NavierStokesSolver{
    //some methods
private:
    //velocity fields
    Field<Vec2> v_old, v_new;

    //pressure fields
    Field<float> p_old, p_new;

    //color fields
    Field<Color3> c_old, c_new;
};

There is a method, which runs an iteration on the data, where the device pointers are passed to the __global__ functions, and updated.
Something like
 advect_kernel<<<blocks, threads>>>(v_new.devPtr(), v_old.devPtr(), c_new.devPtr(), c_old.devPtr(), decay, dt);
 project_kernel<<<blocks, threads>>>(v_old.devPtr(), p_old.devPtr());


texts: Find the perfect numbers within the range of 1 and a chosen number

texts:
My program is complete and working, but I would like second opinions on it. The program prompts the user for a positive value that will serve as the maximum for the range that will be checked for perfect numbers. Although this is one of those do-what-you-want-with-it problems, I have to keep the two prototypes. Are there any extra adjustments I should make in the program or is it already efficient the way it is?

#include "stdafx.h"
#include <iostream>
using namespace std;

/* Function prototypes */
bool isPerfect(int n);
int sumOfProperDivisors(int n);

/* Main program*/
int main()
{
    // Declare variable(s)
    int bound;  // Stores upper limit of number range

    // Prompt user to enter a positive integer
    cout << "Enter upper bound: ";
    cin >> bound;

    // Display the information
    cout << "\n\nThe perfect numbers between 1 and " << bound << " are: " << endl;

    for (int i = 1; i <= bound; i++)
    {
        if (isPerfect(i))
        {
            cout << i << endl;
        }
    }

    system("PAUSE");

    return 0;
}

/*
* Function: isPerfect
* -------------------
* Returns the sum of the number(s) within the testing range
*/
bool isPerfect(int n)
{
    int sum = 0;

    for (int i = 1; i < n; i++)
    {
        if (n % i == 0)
        {
            sum += i;
        }
    }

    return sum == n;
}

/*
* Function: int sumOfProperDivisors
* ---------------------------------
* Returns the sum of a number's divisors
*/
int sumOfProperDivisors(int n)
{
    int sum = 1;

    for (int i = 2; i <= n/2; i++)
    {
        if ((n % i) == 0)
        {
            sum += i;

            if (i * i == n)
            {
                sum -= i;
            }
        }
    }

    return sum;
}


texts:
I'm trying to create some tool for easier dependency injection in c++14, here is one of my concepts using std::tuple.

template <class... Types>
class injector
{
public:
    injector(Types... i) { injected_ = std::tuple<Types...>(i...); }

protected:
    template <class T>
    T *injected()
    {
        return std::get<T *>(injected_);
    }

private:
    std::tuple<Types...> injected_;
};

using component_injector = injector<scene *, entity *, foo *>;
class component : component_injector
{
public:
    component(component_injector injected) : component_injector(injected) {};
    virtual ~component(){};

    void method()
    {
        injected<scene>()->method();
        injected<foo>()->method();
    }
};

int main(int argc, char *argv[])
{
    scene s;
    entity e;
    foo f;

    component c({&s, &e, &f});
    c.method();

    return 0;
}

Is it good idea to create dependence this way? It has some limitations, for example I cannot have two dependencies of the same type etc. but code of useful part (component class) seems to be much clearer.
The injected types should be replaced by interfaces but the real types are used directly here for simplicity.


texts: Enforcing C# Task to exist only once at any given point of time for a given ID

texts:
There were multiple times in different applications that I needed to accomplish the following behavior with C# Task and I did it in a certain way, and would like to receive an insight whether it's the best way to achieve the desired effect, or there are other better ways.

The issue is that in certain circumstances I would like a specific Task to exist only in one instance. For example, if someone requests, let's say a list of products by executed a method like Task GetProductsAsync(), and someone else tries to request the same thing, it wouldn't fire another task, but rather return already existing task. When the GetProductsAsync finishes, all of those callers who had previously requested the result will receive the same result. So, there should ever be only one GetProductsAsync execution at a given point of time.

After failed trials to find something similar and well known design pattern to solve this issue, I came up with my own implementation:

public class TaskManager : ITaskManager
    {
        private readonly object _taskLocker = new object();
        private readonly Dictionary<string, Task> _tasks = new Dictionary<string, Task>();
        private readonly Dictionary<string, Task> _continuations = new Dictionary<string, Task>();

        public Task<T> ExecuteOnceAsync<T>(string taskId, Func<Task<T>> taskFactory)
        {
            lock(_taskLocker)
            {

                if(_tasks.TryGetValue(taskId, out Task task))
                {
                    if(!(task is Task<T> concreteTask))
                    {
                        throw new TaskManagerException($"Task with id {taskId} already exists but it has a different type {task.GetType()}. {typeof(Task<T>)} was expected");
                    }
                    else
                    {
                        return concreteTask;
                    }
                }
                else
                {
                    Task<T> concreteTask = taskFactory();
                    _tasks.Add(taskId, concreteTask);
                    _continuations.Add(taskId, concreteTask.ContinueWith(_ => RemoveTask(taskId)));
                    return concreteTask;
                }
            }
        }

        private void RemoveTask(string taskId)
        {
            lock(_taskLocker)
            {
                if(_tasks.ContainsKey(taskId))
                {
                    _tasks.Remove(taskId);
                }

                if(_continuations.ContainsKey(taskId))
                {
                    _continuations.Remove(taskId);
                }
            }
        }
    }

The idea is that we will have a single instance of TaskManager throughout the application lifetime. Any async Task request that should be executed only once at a given point in time, will call ExecuteOnceAsync providing the factory method to create the Task itself, and desired application wide unique ID. Any other task that will come in with the same ID, the Task manager with reply with the same instance of Task created before. Only if there are no other Tasks with that ID, the manager will call the factory method and will start the task. I have added locks around code task creation and removal, to ensure thread safety. Also, in order to remove the task from the stored dictionary after Task has been completed, I've added a continuation task using ContinueWith method. So, after a task has been completed, both the task itself, and its continuation will be removed.

From my side this seems to be a pretty common scenario. I would assume there is a well established design pattern, or perhaps C# API that accomplishes this exact same thing. So, any insights or suggestions will be very appreciated.


texts: Python list comparison: Can this code run faster?

texts:
The idea is to apply some function on each element in each list, then compare two lists by the value returned by the function.

My current solution works but is not fast enough. running "python -m cProfile" gives sth. like:

  ncalls    tottime  percall  cumtime  percall filename:lineno(function)
  2412505   13.335   0.000    23.633   0.000   common.py:38(<genexpr>)
  285000    5.434    0.000    29.067   0.000   common.py:37(to_dict)
  142500    3.392    0.000    35.948   0.000   common.py:3(compare_lists)

Here is my code, I would like to know how to optimize it to run faster.

import itertools

def compare_lists(li1, li2, value_func1=None, value_func2=None):
    """ Compare *li1* and *li2*, return the results as a list in the following form:

    [[data seen in both lists], [data only seen in li1], [data only seen in li2]]

    and [data seen in both lists] contains 2 tuple: [(actual items in li1), (actual items in li2)]

    * *value_func1* callback function to li1, applied to each item in the list, returning the **logical** value for comparison
    * *value_func2* callback function to li2, similarly

    If not supplied, lists will be compared as it is.

    Usage::

        >>> compare_lists([1, 2, 3], [1, 3, 5])
        >>> ([(1, 3), (1, 3)], [2], [5])

    Or with callback functions specified::

        >>> f = lambda x: x['v']
        >>>
        >>> li1 = [{'v': 1}, {'v': 2}, {'v': 3}]
        >>> li2 = [1, 3, 5]
        >>>
        >>> compare_lists(li1, li2, value_func1=f)
        >>> ([({'v': 1}, {'v': 3}), (1, 3)], [{'v': 2}], [5])

    """

    if not value_func1:
        value_func1 = (lambda x:x)
    if not value_func2:
        value_func2 = (lambda x:x)

    def to_dict(li, vfunc):
        return dict((k, list(g)) for k, g in itertools.groupby(li, vfunc))

    def flatten(li):
        return reduce(list.__add__, li) if li else []

    d1 = to_dict(li1, value_func1)
    d2 = to_dict(li2, value_func2)

    if d1 == d2:
        return (li1, li2), [], []

    k1 = set(d1.keys())
    k2 = set(d2.keys())

    elems_left  = flatten([d1[k] for k in k1 - k2])
    elems_right = flatten([d2[k] for k in k2 - k1])

    common_keys = k1 & k2
    elems_both  = flatten([d1[k] for k in common_keys]), flatten([d2[k] for k in common_keys])

    return elems_both, elems_left, elems_right

Edit:

zeekay suggests using set, which is also what I was doing, except that I make a dict for each list first, then compare the keys using set, finally return the original elements using the dict. I realized that the speed actually depends on which one will take more time -- the callback function, or the groupby. In my case, the possible callback functions are mostly dot access on objects, and the length of lists can be large causing groupby on lists takes more time.

In the improved version each callback function is executed more than once on every single element, which I considered is a waste and has been trying to avoid in the first place, but it's still much faster than my original approach, and much simpler.

def compare_lists(li1, li2, vf1=None, vf2=None):
    l1 = map(vf1, li1) if vf1 else li1
    l2 = map(vf2, li2) if vf2 else li2

    s1, s2 = set(l1), set(l2)
    both, left, right = s1 & s2, s1 - s2, s2 - s1

    orig_both = list((x for x in li1 if vf1(x) in both) if vf1 else both), list((x for x in li2 if vf2(x) in both) if vf2 else both)
    orig_left = list((x for x in li1 if vf1(x) in left) if vf1 else left)
    orig_right = list((x for x in li2 if vf2(x) in right) if vf2 else right)

    return orig_both, orig_left, orig_right


texts:
I am working on Problem 2.30 from Structure and Interpretation of Computer Programs. I book is in scheme, but I am doing the exercises in Clojure.

The problem is to write code that takes a tree of numbers and return a new tree with the numbers squared. I have done it in two ways:

Without higher-order functions:

(defn square-tree1 [tree]
  (lazy-seq
    (when-let [s (seq tree)]
      (if (coll? (first s))
        (cons (square-tree1 (first s))
              (square-tree1 (rest s)))
        (cons (square (first s))
              (square-tree1 (rest s)))))))

Using map

(defn square-tree2 [tree]
  (if (coll? tree)
    (map square-tree2 tree)
    (square tree)))

Where:

(defn square [x]
  (* x x))

My tests for this are:

(deftest e2.30a
  (testing "Ex 2.30a: square-tree"
    (is (=
         (square-tree1
          (list 1
                (list 2 (list 3 4) 5)
                (list 6 7)))
         '(1 (4 (9 16) 25) (36 49))))
    (is (= (square-tree1 '()) '()))
    (is (= (square-tree1 [1 2 3 4 5]) [1 4 9 16 25]))
    (is (= (square-tree1 [1 [2 [3]]]) [1 [4 [9]]]))))

I want the functions to work with lists and vector inputs.
I am unsure if 1 is the proper usage of lazy-seq and whether there is a neater way to express this.
Is (col? (first s)) the correct predicate here? I find it tricky in Clojure to test if the node in the tree is another sub-tree or if it is number. In Scheme it is easier because you have the pair? predicate. I would like to see if there is a better way.

Edit -- After a useful discussion with Timothy Pratley about clojure.walk

After looking at the source code of clojure.walk I have come up with a third square-tree function that extends the square-tree2, but now preserves the input collection types of the input tree like clojure.walk does:

    (defn square-tree3
      [tree]
      (cond
        (list? tree) (apply list (map square-tree3 tree))
        (seq? tree) (doall (map square-tree3 tree))
        (coll? tree) (into (empty tree) (map square-tree3 tree))
        :else (square tree)))

So it extends the answer to the coll? predicate with a (into (empty tree)...) which puts the result of map into whatever type of collection tree is. It also adds cases for list and seq types, handling each of them in their own special way so that they replicate into the same collection type.


texts: Should I return an object wrapped by an article tag?

texts:
Not sure if this is the right board for this topic but since it will affect my SEO i guess it's not that wrong to ask about this in here.

I just took on a website that lists some stores around your location.
You can enter some conditions and it will return a list of nearby stores.

I noticed that the List of stores will be returned as a
 and each store is represented by an
.

                               Ice Cream Store 1

                                                foo

                    foo

                               Ice Cream Store 2

                                                foo2

                    foo

            ....

Is this good code style? I thought
 should be represent ...well...articles about some topic like news or articles about a specific topic. Instead these articles are some stores which will change every few weeks. Whats the best way to represent a list like this?


texts: Using python and beautifulsoup to iterate through a list of websites to find a particular string

texts:
I'm attempting to find companies who mention a particular service in on their homepage. To do this, I am iterating through a csv file with two columns - ID and URL. I'm using BeautifulSoup to get the html and regex to find the string.

At present, my code works, but it feels very clunky and takes forever. I'm also not writing my matching IDs to the new csv, which I haven't been able to figure out.

Since this is at least working, hopefully, it will help someone else who is spinning their wheels trying to figure it out.

How can it be improved?

import requests
from bs4 import BeautifulSoup
import re
import csv

with open('web1.csv', mode='r') as infile:
    reader = csv.reader(infile)
    with open('websites_new.csv', mode='w') as outfile:
        writer = csv.writer(outfile)
        mydict = dict((rows[0],rows[1]) for rows in reader)

newlist = []

for v in mydict.itervalues():
    try:
        page = requests.get('http://www.' + v)
    except:
        pass
    soup = BeautifulSoup(page.content, 'html.parser')
    soupString = str(soup)
    re1='.*?'
    re2='(secretword)'
    rg = re.compile(re1+re2,re.IGNORECASE|re.DOTALL)
    m = rg.search(soupString)
    if m is None:
        value = 'x'
        newlist.extend(value)
    else:
        newlist.extend(v)

print newlist


texts: Find all concatenated words in a given list of words

texts:
This is a Leetcode problem -

  Given a list of words (without duplicates), write a program that
  returns all concatenated words in the given list of words.

  A concatenated word is defined as a string that is comprised entirely
  of at least two shorter words in the given array.

  Note -

  The number of elements of the given array will not exceed 10,000.
  The length sum of elements in the given array will not exceed 600,000.
  All the input string will only include lower case letters.
  The returned order of elements does not matter.

Here is my solution to this challenge (DFS solution) -

def find_all_concatenated_words_in_a_dict(words):
    """
    :type words: List[str]
    :rtype: List[str]
    """
    words = set(words)
    output = []
    for w in words:

        if not w:
            continue

        stack = [0]
        seen = {0}
        word_len = len(w)

        while stack:
            i = stack.pop()
            if i == word_len or (i > 0 and w[i:] in words):
                output.append(w)
                break
            for x in range(word_len - i + 1):
                if w[i: i + x] in words and i + x not in seen and x != word_len:
                    stack.append(i + x)
                    seen.add(i + x)
    return output

Here is an example output -

#print(find_all_concatenated_words_in_a_dict(["cat", "cats", "catsdogcats", "dog", "dogcatsdog", "hippopotamuses", "rat", "ratcatdogcat"]))

>>> ['catsdogcats', 'ratcatdogcat', 'dogcatsdog']

Explanation -

"catsdogcats" can be concatenated by "cats", "dog" and "cats";

"dogcatsdog" can be concatenated by "dog", "cats" and "dog";

"ratcatdogcat" can be concatenated by "rat", "cat", "dog" and "cat".

Here is the time taken for this output -

%timeit find_all_concatenated_words_in_a_dict(["cat", "cats", "catsdogcats", "dog", "dogcatsdog", "hippopotamuses", "rat", "ratcatdogcat"])
41.1 µs ± 2.93 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

So, I would like to know whether I could make this program shorter and more efficient.


texts: Proper way of a testable method with multiple return points

texts:
I have the following piece of java method code:

@Override
public void applyStates(int timestamp, State[] states) {

    // Calculate the time diff between current time and the time stamp of the given states.
    int diff = getNetworkTime() - timestamp;

    if (diff <= 0) {
        Log.e("Ignoring states that seem to come from the future!");
        return;
    }

    if (diff >= DIFF_THRESHOLD) {
        Log.w("Ignoring states that are too old. Diff is: " + diff);
        return;
    }

    // Do the real processing here.
}

I'd like this code to be testable (by unit tests), however since it has a flow that's comprised of multiple return statements, it's not so easy for me to do so.

I'd like to verify for example, that depending on the input, i go into the 2 different validation clauses in the beginning of the method.

Is there a better design than this? how can this method be better structured for testabilty?


texts: Too many objects, too "deep" class structure?

texts:
I have a pretty large model library I'm working on and it's turning out quite complex, or so I believe at least and I could use a second opinion.

The basic idea is that the user should only have to create an instance of a big base class and then build on that with the other object types.

These are some of the properties in the base class:

public class ConfigurationSheet
{
    public List<MainStep> MainSteps { get; set; }
    public List<SequenceStep> SequenceSteps { get; set; }
    public List<SubSequenceStep> SubSequenceSteps { get; set; }
    public List<ConfigurationRow> ConfigurationRows { get; set; }

    public List<Tag> PLCTags
    {
        get { return ConfigurationRows.Select(x => x.PLCTag).ToList(); }
    }
}

These types are all mine and comes with the library, for example the  ConfigurationRow-object looks like this:

public class ConfigurationRow
{
    public Tag PLCTag { get; set; }
    public Dictionary<int, StepArguments> Arguments { get; set; }
}

And it continues like this.  Here's the StepArguments object:

public class StepArguments
{
    public Configurations Configurations { get; set; }
    public Calculations Calculations { get; set; }
}

The Configurations object actually goes another two steps deeper.

This could, potentially, result in code like this:

if(sheet.SequenceStep[0].DefaultConfigurations.Tolerances.SetPoint > 0)
    sheet.ConfigurationRows[1].Arguments[120].Configurations.Tolerances.HighLimit = 200;

And this doesn't seem right to me.  Should I perhaps break some of my objects and put the properties in bigger classes, or should I create shortcut properties/methods/indexers or am I maybe just overreacting?

I'm thinking maybe something like this:

public class StepArguments
{
    public Configurations Configurations { get; set; }
    public Calculations Calculations { get; set; }
    public double HighLimit { get { return Configurations.Tolerances.HighLimit; } }
}

Which would allow this:

if(sheet.SequenceStep[0].SetPoint > 0)
    sheet.ConfigurationRows[1].Arguments[120].HighLimit = 200;

While this would make clearer code it would also ruin the purpose of having the Configurations class in the first place.


texts: List all possible permutations from a python dictionary of lists

texts:
The following code takes a dictionary of lists (indexed by keyword)  and converts it into a list of list of dictionaries that contains all possible permutations of those lists.  However, my solution seems hackish, and is certainly space inefficient.. I feel like I'm missing something obvious.

The use case is for enumerating all the possible hyperparameters for a neural network (think sklearn grid search).  So I specify the options in a compact dictionary containing the name of the parameter, and a list of values to test, and then convert that into a list of single-entry-per-key dictionaries that contain all possible permutations of those configuration parameters.

It's important to note I'm trying to make this generic, so that there can be an arbitrary number of keys specified in the initial dictionary, with an arbitrary number of options for each key.

Here's the code:

import copy

config_overrides = {
    'nodetype': ['srnn', 'lstm', 'gru'],
    'nhidden': [1,2,3,4,5,6,8,10,12,16,20],
    'opt': ['sgd', 'rmsprop', 'adagrad', 'adamax', 'adam', 'nadam', 'adadelta'],
    'actfunc': ['softplus', 'softsign', 'tanh', 'sigmoid', 'hard_sigmoid', 'linear', 'relu'],
    'loss': ['mse', 'msle']
}

experiments = [{},]

for k,v in config_overrides.items():
    new_values = len(v)
    current_exp_len = len(experiments)
    for _ in range(new_values-1):
       experiments.extend(copy.deepcopy(experiments[:current_exp_len]))
    for validx in range(len(v)):
       for exp in experiments[validx*current_exp_len:(validx+1)*current_exp_len]:
            exp[k] = v[validx]

print(len(experiments))
print([x for x in experiments[1034:1039]])

The output of the above program, which includes random outputs from the middle of the list, and shows it appears tobe working correctly (the above example should come out to 3234 permutations):

3234
[{'loss': 'mse', 'opt': 'adadelta', 'actfunc': 'sigmoid', 'nodetype': 'lstm', 'nhidden': 4}, {'loss': 'msle', 'opt': 'adadelta', 'actfunc': 'sigmoid', 'nodetype': 'lstm', 'nhidden': 4}, {'loss': 'mse', 'opt': 'sgd', 'actfunc': 'hard_sigmoid', 'nodetype': 'lstm', 'nhidden': 4}, {'loss': 'msle', 'opt': 'sgd', 'actfunc': 'hard_sigmoid', 'nodetype': 'lstm', 'nhidden': 4}, {'loss': 'mse', 'opt': 'rmsprop', 'actfunc': 'hard_sigmoid', 'nodetype': 'lstm', 'nhidden': 4}]

A few immediate questions:

Is list.extend() the best way to expand the list?
The deepcopy() is necessary, or else you end up with copies of the original dictionary. But that also means the strings are copied, redundantly.  Not a huge deal, but doesn't feel right to me.

Other than that, it just seems like there should be a cleaner, less obtuse way of doing this..and maybe I'm just too tired to think of it.  Any ideas?


texts: Should a PDO object be passed to classes and procedural functions as a parameter?

texts:
I've been trying to figure out the best way to manage database connections for a while now and am still unsure of how I should be doing things. I know there are a lot of similar questions on here, but I've read many of them and am still confused.

Some answers on here say singletons should be used, but it seems a larger percentage of answers say not to use singletons because they make debugging much harder.

My current method is to create a PDO object and then pass it as a parameter:

/**
 * Creates and returns PDO object
 *
 * @return PDO
 */
function createPDO() {
    // MySQL connection
    $dbUser = '';
    $dbPass = '';
    $dbName = '';

    try {
        $db = new PDO("mysql:dbname=$dbName;charset=utf8", $dbUser, $dbPass, array(PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
    }
    catch (PDOException $e) {
        errorHandler(0, $e->getMessage(), $e->getFile(), $e->getLine(), print_r($e, true), 'sql');
        die('SQL Error, terminating script.');
    }

    return $db;
}

/**
 * Makes a PDO query
 *
 * @param @var $stmt The PDO statement
 * @param array $array The array of PDO statement parameters
 */
function makeQuery($stmt, $array) {
    try {
        $stmt->execute($array);
    }
    catch (PDOException $e) {
        errorHandler(0, $e->getMessage(), $e->getFile(), $e->getLine(), print_r($e, true), 'sql');
        die('SQL Error, terminating script.');
    }
}

Then in my scripts I'll use the object like this:

$db = createPDO();

$stmt = $db->prepare('SELECT ....')
makeQuery($stmt, array(':boundParameter' => '..'));
$result = $stmt->fetch(PDO::FETCH_ASSOC);

If I instantiate new classes, or call procedural functions, I pass $db as a parameter:

$myClass = new myClass($db);

Is this a good way of doing things, or is there a better way?


texts: Determining Pythagorean triples based on the hypotenuse

texts:
Below is my written code to determine if, based on the hypotenuse, a Pythagorean triple is possible, and what are the lengths. I was wondering if there is a more efficient way of doing so.

#Victor C
#Determines if a right triangle with user inputted hypotenuse is capable of being a Pythagorean Triple

import math
triplecheck = True
while True:
    hypotenuse = int(input("Please enter the hypotentuse:")) #Smallest hypotenuse which results in a pythagorean triple is 5.
    if hypotenuse > 4:
        break
c = csqr = hypotenuse**2 #sets two variables to be equivalent to c^^2. c is to be modified to shorten factoring, csqr as a reference to set a value
if c % 2 != 0:   #even, odd check of value c, to create an integer when dividing by half.
    c = (c+1)//2
else:
    c = c//2
for b in range(1,c+1):  #let b^^2 = b || b is equal to each iteration of factors of c^^2, a is set to be remainder of c^^2 minus length b.
    a = csqr-b
    if (math.sqrt(a))%1 == 0 and (math.sqrt(b))%1 == 0: #if squareroots of a and b are both equal to 0, they are integers, therefore fulfilling conditions
       tripleprompt = "You have a Pythagorean Triple, with the lengths of "+str(int(math.sqrt(b)))+", "+str(int(math.sqrt(a)))+" and "+str(hypotenuse)
       print(tripleprompt)
       triplecheck = False
if triplecheck == True:
    print("Sorry, your hypotenuse does not make a Pythagorean Triple.")


texts:
(I am not sure of the official CS name for the problem in question, so I just gave it the name of the kata).

Problem

  CLEAR CUTTER'S NEEDS YOUR HELP!

  The logging company Clear Cutter's makes its money by optimizing the price-to-length of each log they cut before selling them. An example of one of their price tables is included:

# So a price table p
p = [ 0,  1,  5,  8,  9, 10]

# Can be imagined as:
# length i | 0  1  2  3  4  5 *in feet*
# price pi | 0  1  5  8  9 10 *in money*

  They hired an intern last summer to create a recursive function for them to easily calculate the most profitable price for a log of length n using price table p as follows:

def cut_log(p, n):
   if (n == 0):
      return 0
   q = -1
   for i in range(1, n+1)
      q = max(q, p[i] + cut_log(p, n-i))
   return q

  An example of the working code:

# 5ft = $10, BUT 2ft + 3ft = 5ft -> $5 + $8 = $13 which is greater in value

  However, their senior software engineer realized that the number of recursive calls in the function gives it an awful running time of 2^n (as this function iterates through ALL 2^n-1 possibilities for a log of length n).

  Having discovered this problem just as you've arrived for your internship, he responsibly delegates the issue to you.

  Using the power of Stack Overflow and Google, he wants you to create a solution that runs in Θ(n^2) time so that it doesn't take 5 hours to calculate the optimal price for a log of size 50. (He also suggests to research the problem using the keywords in the tags)

  (Be aware that if your algorithm is not efficient, it will attempt to look at 2^49 = 562949953421312 nodes instead of 49^2 = 2401... The solution will automatically fail if it takes longer than 6 seconds... which occurs at right around Log 23)

Solution

def cut_log(p, n):
    for i in range(2, len(p)):
        p[i] = max(p[i-k] + p[k] for k in range((i//2)+1))
    return p[n]

It passes all the tests. I'm putting it up for review because I'm pretty proud of it and experience as shown me that there's usually some improvement to be made.


texts:
I need some help with the graph and Dijkstra's algorithm in Python 3. I tested this code (look below) at one site and it says to me that the code took too long. Can anybody suggest how to solve that? I don't know how to speed up this code. I read many sites but I didn't find normal examples...
P.S. this is a new code version with deque and something like this, but it's still too slow.
from collections import deque

class node:

    def __init__(self, name, neighbors, distance, visited):
        self.neighbors = neighbors
        self.distance = distance
        self.visited = visited
        self.name = name

    def addNeighbor(self, neighbor_name, dist): # adding new neighbor and length to him

        if neighbor_name not in self.neighbors:
            self.neighbors.append(neighbor_name)
            self.distance.append(dist)

class graph:

    def __init__(self):
        self.graphStructure = {} # vocabulary with information in format: node_name, [neighbors], [length to every neighbor], visited_status

    def addNode(self, index): # adding new node to graph structure

        if self.graphStructure.get(index) is None:
            self.graphStructure[index] = node(index, [], [], False)

    def addConnection(self, node0_name, node1_name, length): # adding connection between 2 nodes
        n0 = self.graphStructure.get(node0_name)

        n0.addNeighbor(node1_name, length)

        n1 = self.graphStructure.get(node1_name)
        n1.addNeighbor(node0_name, length)

    def returnGraph(self): # printing graph nodes and connections

        print('')
        for i in range(len(self.graphStructure)):
            nodeInfo = self.graphStructure.get(i + 1)
            print('name =', nodeInfo.name, '  neighborns =', nodeInfo.neighbors, '           length to neighborns =', nodeInfo.distance)

    def bfs(self, index): # bfs method of searching (also used Dijkstra's algorithm)

        distanceToNodes = [float('inf')] * len(self.graphStructure)
        distanceToNodes[index - 1] = 0
        currentNode = self.graphStructure.get(index)
        queue = deque()

        for i in range(len(currentNode.neighbors)):
            n = currentNode.neighbors[i]
            distanceToNodes[n - 1] = currentNode.distance[i]
            queue.append(n)

        while len(queue) > 0: # creating queue and visition all nodes
            u = queue.popleft()
            node_u = self.graphStructure.get(u)
            node_u.visited = True

            for v in range(len(node_u.neighbors)):
                node_v = self.graphStructure.get(node_u.neighbors[v])
                distanceToNodes[node_u.neighbors[v] - 1] =  min(distanceToNodes[node_u.neighbors[v] - 1], distanceToNodes[u - 1] + node_u.distance[v]) # update minimal length to node
                if not node_v.visited:
                    queue.append(node_u.neighbors[v])

        return distanceToNodes

def readInputToGraph(graph): # reading input data and write to graph datatbase
    node0, node1, length = map(int, input().split())

    graph.addNode(node0)
    graph.addNode(node1)
    graph.addConnection(node0, node1, length)

def main():
  newGraph = graph()
  countOfNodes, countOfPairs = map(int, input().split())

  if countOfPairs == 0:
      print('0')
      exit()

  for _ in range(countOfPairs): # reading input data for n(countOfPairs) rows
      readInputToGraph(newGraph)

  # newGraph.returnGraph() # printing information

  print(sum(newGraph.bfs(1))) # starting bfs from start position

main()

The input graph structure may look like this:
15 17
3 7 2
7 5 1
7 11 5
11 5 1
11 1 2
1 12 1
1 13 3
12 10 1
12 4 3
12 15 1
12 13 4
1 2 1
2 8 2
8 14 1
14 6 3
6 9 1
13 9 2

I'm only learning python so I think I may be doing something wrong.


texts: Automatically redirect /index.php files to their URL directory with .htaccess

texts:
The requirements:

Work inside .htaccess (preferably via mod_rewrite)
Redirect requests from /any/directory/index.php to /any/directory/
Make sure that /index.php-with-stupid-stuff-here does not get rewritten
Add trailing slash to directories, /another/directory becomes /another/directory/

Also note that:

The ideal scenario would be to use manual 301 redirects, but this is a case where there are far too many directories to do that for individually.
Internal linking is clean (always goes to the right place), so this is a just-in-case solution. (But others who find this question might be in a different situation.)

DaveRandom helped me revise my solution, resulting in…

RewriteEngine On
RewriteCond %{THE_REQUEST} (?:/[^/]*)*/index\.php[?#\ ]
RewriteRule .* %{REQUEST_URI}/../ [L,R=301]

  The basic idea behind it is that by using %{THE_REQUEST} in a RewriteCond you are looking at the actual URI requested by the user before any file system mappings, alias, other rewrite rules etc. were applied.

  This is important, because if you just look at the request-URI in a RewriteRule you will almost definitely end up in a redirect loop.

Questions:

Is that solid, correct code?
Anything else that should be added, or taken into account?
Or, considering best practices, is there a better way entirely?


texts:
I am pretty new to C++ and I think I have some problems of keeping code clean and optimized, especially I have problems with writing comments. I just don't know when should I be explaining what I write. Any tips and advices will be hugely appreciated!
Here's the code:
#include <iostream>
#include <initializer_list>
#include <stdexcept>

template <typename T>
class DynamicArray
{
public:

    DynamicArray(std::initializer_list<T> elements)
        : m_size(elements.size())
        , m_capacity(elements.size())
        , m_array(new T[elements.size()])
    {
        std::copy(elements.begin(), elements.end(), m_array);
    }

    DynamicArray()
        : m_size(0)
        , m_capacity(1)
        , m_array(nullptr)
    { }

    DynamicArray(DynamicArray<T>&& other)
        : DynamicArray()
    {
        swap(*this, other);
    }

    ~DynamicArray()
    {
        delete[] m_array;
    }

    DynamicArray(const DynamicArray& other)
        : m_capacity(other.m_capacity)
        , m_size(other.m_size)
        , m_array(new T[other.m_capacity])
    {
        std::copy(other.m_array, other.m_array + other.m_size, m_array);
    }

    DynamicArray& operator=(DynamicArray other)
    {
        swap(*this, other);
        return *this;
    }

    friend void swap(DynamicArray<T>& obj1, DynamicArray<T>& obj2) noexcept
    {
        std::swap(obj1.m_size, obj2.m_size);
        std::swap(obj1.m_capacity, obj2.m_capacity);
        std::swap(obj1.m_array, obj2.m_array);
    }

    void insert(int index, T value)
    {
        if (index != m_size) m_check_range(index);
        if (m_capacity == m_size) resize(m_capacity * 2);

        m_size++;

        for (int i = m_size - 2; i >= index; i--)
        {
            (*this)[i + 1] = (*this)[i];
        }

        (*this)[index] = value;
    }

    T remove(int index)
    {
        m_check_range(index);
        T to_remove = (*this)[index];

        for (int i = index; i < m_size - 1; i++)
        {
            (*this)[i] = (*this)[i + 1];
        }

        m_size--;
        return to_remove;
    }

    // Resizes array to store n elements.
    // Guarantees strong exception safety.
    void resize(int n)
    {
        T *temp = new T[n];
        m_capacity = n;

        std::copy(m_array, m_array + m_capacity, temp);
        delete[] m_array;
        m_array = temp;
    }

    void shrink_to_fit()
    {
        resize(m_size);
    }

    int size() const
    {
        return m_size;
    }

    bool empty() const
    {
        return m_size == 0;
    }

    int capacity() const
    {
        return m_capacity;
    }

    void append(T value)
    {
        insert(m_size, value);
    }

    void prepend(T value)
    {
        insert(0, value);
    }

    T pop(int index)
    {
        return remove(m_size - 1);
    }

    T front() const
    {
        return (*this)[0];
    }

    T back() const
    {
        return (*this)[m_size - 1];
    }

    void print() const
    {
        for (int i = 0; i < m_size; i++)
        {
            std::cout << m_array[i] << " ";
        }
        std::cout << std::endl;
    }

    T& operator[](int index)
    {
        m_check_range(index);
        return m_array[index];
    }

    const T& operator[](int index) const
    {
        m_check_range(index);
        return m_array[index];
    }

private:

    T *m_array;
    int m_capacity; // Capacity of the array
    int m_size ; // Number of added elements

    void m_check_range(int index) const
    {
        if (index < 0 || index >= m_size)
        {
            throw std::out_of_range("Index out of range!");
        }
    }
};


texts:
I recently wrote a piece of code to convert between two bases of X, (Where 26 > X > 0). I was mighty proud that I did this. And then I started wondering, am I using modern coding conventions/practices?

The code can be found here.

And some sample outputs are shown:

// syntax: convertBase(input, inputBase, outputBase)
convertBase("10", 10, 11) // "a"
convertBase("3", 10, 3)   // "10"
convertBase("4", 10, 3)   // "11"

The full code is here:

function convertBase(inNumber, inBase, outputBase) {
  var result = [];
  if (typeof inNumber !== "number" && typeof inNumber !== "string") {
    throw new Error("You input is not a number or a string.");
  }
  var encodings = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"];
  if (typeof inNumber === "number") {
    inNumber = JSON.stringify(inNumber);
  }
  if (inBase === outputBase) {
    return inNumber;
  }
  inNumber = inNumber.toLowerCase();
  inNumber = inNumber.split("").map(function(item) {
    return encodings.indexOf(item);
  });
  inNumber = inNumber.reverse();
  inNumber = inNumber.map(function(item, index) {
    return item * Math.pow(inBase, index);
  });
  var res = 0;
  inNumber.forEach(function(item) {
    res += item;
    return;
  });
  var ones = res % outputBase;
  var remainder = (res - res % outputBase) / outputBase;
  result.unshift(ones);
  var left = remainder > 1;
  while (left) {
    var ones = remainder;
    var remainder = (remainder - remainder % outputBase) / outputBase;
    result.unshift(ones);
    var left = remainder > 1;
  }
  return result.map(function(item) {
    return encodings[item];
  }).join("");
}
;


texts:
I have a system that receives messages. Each message has a type defined. These types are declared in an enum:

enum MessageType {
  TYPE1, TYPE2, ... , TYPE999
}

People can extend my system by implementing message processors. Each message type can only have one processor and most will have none. My current design has users writing their processors and I have one factory that they have to change:

public static Map<MessageType, MessageProcessor> getProcessors() {
  Map<MessageType, MessageProcessor> processors = Maps.newHashMap();
  processors.put(TYPE33,  new Type33Processor());
  processors.put(TYPE111, new Type111Processor());
  processors.put(TYPE222, new Type222Processor());
  processors.put(TYPE444, new Type444Processor());
  return processors;
}

My problem with this is twofold:

Each new processor has to remember to add this boilerplate.
This factory has to know all processor types.

I thought of maybe solving this using reflection:

public static Map<MessageType, MessageProcessor> getProcessors() {
  Map<MessageType, MessageProcessor> processors = Maps.newHashMap();
  Reflections reflections = new Reflections(getClass().getPackage().getName());
  Set<Class<? extends MessageProcessor>> allProcessors =
      reflections.getSubTypesOf(MessageProcessor.class);
  for (Class<? extends MessageProcessor> processorClass : allProcessors) {
    MessageProcessor processor = processorClass.getConstructor().newInstance();
    processors.put(processor.getMessageType(), processor);
  }
  return processors;
}

This solution solves the two issues I mentioned above.
My questions are:

I understand that reflection has dangers and pitfalls. Is this a valid scenario to use it?
Is there a better way to improve my first solution without having to resort to using reflection?


texts: Phone Number and Email Address Extractor - Is there any way to simplify this code?

texts:
I'm very new to programming and I don't feel confident about the readability of this program.

This program gets the text you copied then extracts phone numbers and email addresses in the text. Once those are extracted, you can paste them anywhere(Eg: notepad).

Are there any ways that I can improve this code? Any suggestions will surely be appreciated. Thanks!

import pyperclip, re
# Python 3 - 30/04/2020
# emailAndNumberExtractor.py - finds phone and email addresses on the clipboard

emailRegex = re.compile(r'''(
    [a-zA-Z0-9._%+-]+           # username
    @                           # @ symbol
    [a-zA-Z0-9.-]+              # domain name
    (\.[a-zA-Z]{2,4})           # dot something
    )''', re.VERBOSE)

phoneRegex = re.compile(r'''(
    (\d{3}|\(\d{3}\))?          # area code
    (\s|-|\.)?                  # separator
    \d{3}                       # first 3 digits
    (\s|-|\.)                   # separator
    \d{4}                       # last 4 digits
    (\s*(ext|x|ext.)\s*\d{2,5})?# extension
 )''', re.VERBOSE)

all_emails = "\nEMAILS FOUND:\n"
all_numbers = "\nNUMBERS FOUND:\n"

# get copied text and paste it to text var
text = str(pyperclip.paste())

# check if there are phone numbers/ emails in the text
if len(emailRegex.findall(text)) > 0 :
    for email in emailRegex.findall(text):
        all_emails += '\n\t' + email[0]
else:
    all_emails += "\n\tSorry, there are no emails."

if len(phoneRegex.findall(text)) > 0:
    for num in (phoneRegex.findall(text)):
        all_numbers  += '\n\t' + num[0]
else:
    all_numbers += "\n\tSorry, there are no phone numbers."

# Collects all numbers and emails found
matches = all_numbers + "\n" +  all_emails

print(text)
pyperclip.copy(matches)
print("Copied to clipboard:")
print(matches)
```


texts: Parsing server request data for visualization in C3.js

texts:
The following is a snippet from a script I have that fetches a list of objects representing requests to a server and graphs them using C3.js. I've only included the relevant code that parses the list of request objects for relevant data.

const iterByDay = (min, max, callback) => {
  var tmp = moment(min)
  for (const day = tmp; day.isBefore(max); day.add(1, 'day')) {
    callback(day)
  }
}

const getDateRange = data => {
  return data.length < 2 ? null : {
    min: moment(data[0].timestamp).startOf('day'),
    max: moment(data[data.length - 1].timestamp).endOf('day')
  }
}

const min = l => {
  return !l ? 0 : Math.round(Math.min(...l))
}

const avg = l => {
  return !l ? 0 : Math.round(l.reduce((a, b) => a + b) / l.length)
}

const max = l => {
  return !l ? 0 : Math.round(Math.max(...l))
}

const getTrafficData = data => {
  const hitsPerDay = new Map()
  for (const entry of data) {
    const day = moment(entry.timestamp).startOf('day').toString()
    hitsPerDay.set(day, (hitsPerDay.get(day) || 0) + 1)
  }
  const dateColumn = ['date']
  const hitsPerDayColumn = ['total requests']
  const range = getDateRange(data)
  iterByDay(range.min, range.max, day => {
    dateColumn.push(day.format('YYYY-MM-DD'))
    day = day.toString()
    hitsPerDayColumn.push(hitsPerDay.get(day) || 0)
  })
  return [dateColumn, hitsPerDayColumn]
}

const getResponseTimeData = data => {
  const timesByDay = []
  for (var entry of data) {
    const day = moment(entry.timestamp).startOf('day')
    if (timesByDay[day]) {
      timesByDay[day].push(entry.responseTime || 0)
    } else {
      timesByDay[day] = [entry.responseTime || 0]
    }
  };
  const dateColumn = ['date']
  const minColumn = ['min']
  const avgColumn = ['avg']
  const maxColumn = ['max']
  const range = getDateRange(data)
  iterByDay(range.min, range.max, day => {
    dateColumn.push(day.format('YYYY-MM-DD'))
    minColumn.push(min(timesByDay[day]))
    avgColumn.push(avg(timesByDay[day]))
    maxColumn.push(max(timesByDay[day]))
  })
  return [dateColumn, maxColumn, avgColumn, minColumn]
}

const getSectionFrequencyData = data => {
  const frequencies = new Map()
  for (const entry of data) {
    const url = /\/([a-z]+)|$/g.exec(entry.req.url || '')[1] || 'home'
    frequencies.set(url, (frequencies.get(url) || 0) + 1)
  }
  const sorted10 = new Map(
    [...frequencies.entries()].sort((a, b) => b[1] - a[1]).slice(0, 10)
  )
  return [
    ['sections', ...sorted10.keys()],
    ['frequency', ...sorted10.values()]
  ]
}

const getCountryFrequencyData = data => {
  const frequencies = new Map()
  for (const entry of data) {
    const country = entry.country || 'unknown'
    frequencies.set(country, (frequencies.get(country) || 0) + 1)
  }
  const sorted10 = new Map(
    [...frequencies.entries()].sort((a, b) => b[1] - a[1]).slice(0, 10)
  )
  return [
    ['countries', ...sorted10.keys()],
    ['frequency', ...sorted10.values()]
  ]
}

The functions are passed lists of objects that look like this:

[{
  timestamp: ...,
  country: ...,
  url: ...,
  ....
}, {
  timestamp: ...,
  country: ...,
  url: ...,
  ...
}]

and I am guaranteed that the objects are already sorted chronologically by timestamp. I'm sure that this code can be vastly improved.


texts: Assignment function as alternative to std::tie

texts:
What do you think about this assignment "idiom"?
template <typename ...A>
constexpr auto assign(A& ...a) noexcept
{
  return [&](auto&& ...v)
//  noexcept(noexcept(((a = std::forward<decltype(v)>(v)), ...)))
    {
      ((a = std::forward<decltype(v)>(v)), ...);
    };
}

It seems a better alternative to me than the std::tie() idiom. Uncommenting the comment could cause a segfault in gcc.
Usage:
int a, b, c;
assign(a, b, c)(1, 2, 3);


texts:
I'm trying to grasp this whole MVC design pattern idea but I'm in the dark if I'm doing it correct. This is where I need some feedback on what I've done so far. Here's what I'm wondering:

Does the hideMenu and showMenu fall under the view or controller?
Have I put viewNewPage in the correct block?
How can I make the animation of the menu boxes less repetetive but still allow jQuery to wait until all of the animations have been run before updating the view with the new page? This should probably be done via a class containing CSS3 animations but I'm really unsure on how to rewrite it.
Should I bind elements to functions in the controller or model?
Have I made any other blunders here when trying to follow the MVC pattern?

Simple markup:

Portfolio

Biography

Blog

Logo here

Contact

Snippets

jQuery:

$(document).ready(function() {

var model = {
    elements: {
        wrapper: $('main.content'),
        portfolio: $('#portfolio'),
        biography: $('#biography'),
        blog: $('#blog'),
        logo: $('#logo'),
        contact: $('#contact'),
        snippets: $('#snippets')
    },
    getPage: function(href) {

        return $.ajax({
            url: '../includes/pages/' + href + '.php',
            type: 'post'
        });
    }
}

var view = {
    viewNewPage: function(promise) {

        promise.done(function(data) {
            model.elements.wrapper.append(data).hide().fadeIn();
        });
    }
}

var ctrl = {
    hideMenu: function() {

        var box = $(this);
        var href = box.data('href');

        model.elements.portfolio.animate({top: '-50%'}, 500);
        model.elements.biography.animate({top: '-70%'}, 500);
        model.elements.blog.animate({left: '-45%'}, 500);
        model.elements.logo.fadeOut('slow');
        model.elements.contact.animate({bottom: '-50%'}, 500);
        model.elements.snippets.animate({right: '-55%'}, 500, function() {
            var promise = model.getPage(href);
            view.viewNewPage(promise);
        });
    },
    setElementBindings: function() {
        model.elements.wrapper.on('click', '.hoverable', ctrl.hideMenu);
        model.elements.wrapper.on('click', '.home', ctrl.showMenu);
    },

    showMenu: function() {

        var wrapper = model.elements.wrapper.children('.wrapper');

        wrapper.fadeOut('fast', function() {
            wrapper.remove();
        });

        model.elements.portfolio.animate({top: 0}, 500);
        model.elements.biography.animate({top: 0}, 500);
        model.elements.blog.animate({left: 0}, 500);
        model.elements.logo.fadeIn('slow');
        model.elements.contact.animate({bottom: 0}, 500);
        model.elements.snippets.animate({right: 0}, 500);
    }

}

ctrl.setElementBindings();
});


texts: Designing a toy dependency injection library

texts:
Just for learning purpose I thought to write a simple and useful dependency injection service which would just do dependency injection but also it should expose its core too which would let the client code to do some advance stuffs.

I took inspiration from here but I think it does too much apart from that I think that the Factory and Provider thing can be done via calling resolve method in my library.

I need to know if I am missing something or can I improve my code to handle more cases which I don't know yet.

const RE = /^function\s*[^\(]*\(\s*([^\)]*)\)/m;

const Color = {
  RED: 'RED',
  GREEN: 'GREEN',
  BLUE: 'BLUE',
};

class Door {
  constructor(color) {
    this.color = color;
  }

  open() {
    console.log('Kitchen door is open now!');
  }
}

class Stove {
  constructor() {
  }

  on() {
    console.log('Gas stove is turned on!');
  }

  off() {
    console.log('Gas stove is now off!');
  }
}

class TeaMaker {
  constructor(door, stove) {
    this.door  = door;
    this.stove = stove;
  }

  makeTea() {
    this.door.open();
    this.stove.on();
    console.log('Put water on stop');
    this.stove.off();
    console.log('Enjoying tea :)');
  }
}

const injector = {
  dependencies: {},
  register: (key, value) => {
    injector.dependencies[key] = value;
  },
  resolve: (deps, fn, scope={}) => {
    let args = [];
    for (let d of deps) {
      if (injector.dependencies[d]) {
        args.push(injector.dependencies[d]);
      } else {
        throw new Error(`Unkown Dep: ${d}`);
      }
    }

    return () => {
      return fn.call(scope, ...args, ...arguments);
    };
  },
  get: (fn) => {
    let deps = fn.toString().match(RE)[1].replace(/ /g, '').split(',');
    let args = [];
    for (let d of deps) {
      if (injector.dependencies[d]) {
        args.push(injector.dependencies[d]);
      } else {
        throw new Error(`Unkown Dep: ${d}`);
      }
    }
    return new fn(...args);
  }
};

injector.register('door',  new Door(Color.RED));
injector.register('stove', new Stove());

let makeTea = injector.resolve(['door', 'stove'], function(door, stove) {
  door.open();
  stove.on();
  console.log('Put water on stop');
  stove.off();
  console.log('Enjoying tea :)');
});

makeTea();
let teaMaker = injector.get(TeaMaker);
teaMaker.makeTea();

Output:

Kitchen door is open now!
Gas stove is turned on!
Put water on stop
Gas stove is now off!
Enjoying tea :)
Kitchen door is open now!
Gas stove is turned on!
Put water on stop
Gas stove is now off!
Enjoying tea :)


texts:
The problem:

2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?

The solution in Swift:
import Foundation

var number = 2520
var found = false

while found == false {
    var counter = 0

    for var iterator = 2; iterator < 21; iterator++ {

        if number % iterator == 0 {

            counter++

        } else {

            println("\(number) is not the number")
            break;

        }

    }

    if counter == 19 {

        found = true;

    } else {

        number = number + 2

    }
}
println("\(number) is the number!!")

Comments on making this code more efficient, making it more cleaner or violations of best practices would be highly appreciated.


texts:
So I needed to represent by objects in terms in ini format and change their values from the ini as well, so I thought why don't implement a property system for this. I want it to be bit fast so I would really like if anyone can remove the std::function if possible but its not necessary. The target application is GUI so small performance should not be a big issue, but still, I think this can be done in a faster way but I can't think of any. no one likes lag. Also, the properties are around 100 or more

#include <functional>
#include <stdexcept>
#include <string>
#include <type_traits>
#include <unordered_map>
#include <variant>

#include <QDebug>

template <typename C> class PropertySet {
public:
    using PropertyValue = std::variant<bool, int, float, std::string>;

    void set(const std::string &prop, PropertyValue v) {
        auto p = m_properties.find(prop);
        if (p == m_properties.end()) {
            throw std::runtime_error("Invalid property key");
        }
        // p.value().setter(v);
        p->second.setter(v);
    }

    void set(const std::string &prop, const std::string &v) {
        auto p = m_properties.find(prop);
        if (p == m_properties.end()) {
            throw std::runtime_error("Invalid property key");
        }
        // p.value().setter(p.value().fromStr(v));
        p->second.setter(p->second.fromStr(v));
    }

    std::unordered_map<std::string, std::string> getAllValues() {
        std::unordered_map<std::string, std::string> r;
        qDebug() << m_properties.size();
        for (const auto &p : m_properties) {
            // r[p.key()] = p.value().toStr();
            r[p.first] = p.second.toStr();
        }
        return r;
    }

private:
    struct Payload {
        std::function<std::string()> toStr;
        std::function<PropertyValue(const std::string &)> fromStr;
        std::function<PropertyValue()> getter;
        std::function<void(PropertyValue)> setter;
    };
    std::unordered_map<std::string, Payload> m_properties;

protected:
    template <typename T> static auto fromStr(const std::string &s) {
        if constexpr (std::is_same<T, int>::value) {
            return std::stoi(s);
        } else if constexpr (std::is_same<T, bool>::value) {
            return s == "true" || s == "1";
        }
        static_assert("Error");
    }

    template <typename T, typename Getter, typename Setter>
    void add(const std::string &name, Getter getter, Setter setter) {
        auto cptr = static_cast<C *>(this);
        Payload p;
        p.toStr = [getter, cptr]() { return std::to_string(std::invoke(getter, cptr)); };
        p.fromStr = [](const std::string &s) { return PropertySet::fromStr<T>(s); };
        p.getter = [getter, cptr]() { return PropertyValue(std::invoke(getter, cptr)); };
        p.setter = [setter, cptr](PropertyValue v) { std::invoke(setter, cptr, std::get<int>(v)); };
        m_properties[name] = p;
    }
};

Also, I'm using Qt, so I was thinking of replacing std::string with QString or QByteArray and std::unordered_map with QHash.


texts: Efficient mechanism to generate operator overload functions

texts:
I'm attempting to tidy up a C++ framework (PyCXX).

One particular file contains ~400 lines of operator overload functions, which I've managed to reduce to the following:

#define OP( op, l, r, cmpL, cmpR ) \
    bool operator op( l, r ) { return cmpL op cmpR; }

#define OPS( l, r, cmpL, cmpR ) \
    OP( !=, l, r, cmpL, cmpR ) \
    OP( ==, l, r, cmpL, cmpR ) \
    OP( > , l, r, cmpL, cmpR ) \
    OP( >=, l, r, cmpL, cmpR ) \
    OP( < , l, r, cmpL, cmpR ) \
    OP( <=, l, r, cmpL, cmpR )

    OPS( const Long &a, const Long &b,   a.as_long() , b.as_long() )
    OPS( const Long &a,       int   b,   a.as_long() , b           )
    OPS( const Long &a,       long  b,   a.as_long() , b           )
    OPS( int         a, const Long &b,   a           , b.as_long() )
    OPS( long        a, const Long &b,   a           , b.as_long() )

#ifdef HAVE_LONG_LONG
    OPS( const Long &a, PY_LONG_LONG b,   a.as_long_long() , b                )
    OPS( PY_LONG_LONG a, const Long &b,   a                , b.as_long_long() )
#endif

    //------------------------------------------------------------
    // compare operators
    OPS( const Float &a, const Float &b,   a.as_double() , b.as_double() )
    OPS( const Float &a, double       b,   a.as_double() , b             )
    OPS( double a,       const Float &b,   a             , b.as_double() )

}    // end of namespace Py

However, I wonder if it may be possible to tidy it up further.

It looks as though I can save having to pass all the parameters each time by using:

#define OPS( ... ) \
    OP( !=, ##__VA_ARGS__ ) \
    OP( ==, ##__VA_ARGS__ ) \
    OP( > , ##__VA_ARGS__ ) \
    OP( >=, ##__VA_ARGS__ ) \
    OP( < , ##__VA_ARGS__ ) \
    OP( <=, ##__VA_ARGS__ )

Although I have a hunch this might be making the code less transparent.

Another possible idea would involve storing pairs:

#define FD(op, x) (       Float &x , op, x.as_double()    )
#define L1(op, x) ( const Long &x  , op, x.as_long()      )
#define L2(op, x) ( const Long &x  , op, x.as_long_long() )
:

but I am risking obfuscation through trying too hard.  I think it is commonly accepted that other things being equal, readability trumps concise.

What other viable design patterns could I consider?


texts: Access function to return "number of working days until date" for form

texts:
I need a function I can put on a form which does:

Calculates number of working days until a given date
Excludes weekends
Excludes any dates in a "holiday" table

This is replacing something which looks like:

 =DateDiff("d",Now(),[DateEstimatedDesignStartBy])

with

 =getWorkingDaysUntilDate([DateEstimatedDesignStartBy])

The below is a all within a single module I am using to do this.

I am reading in the entire table of holidays and caching it, and then iterating until teh required date to find the number of days and then caching this result as well.

The net result is a much faster function than having to do the calculation for each time I do anything.

Any feedback would be great. I have a lot of poor naming but am not really sure what would be good...

It seems a bit slower than what it is replacing.

Option Compare Database
Option Explicit

Private m_HolidayLibrary As Scripting.Dictionary
Private m_WorkingDaysUntilDate As Scripting.Dictionary

Public Function getWorkingDaysUntilDate(p_date As Date) As Integer

    If getWorkindDaysUntilDateDict.exists(p_date) = False Then
        getWorkindDaysUntilDateDict.Add p_date, calculateWorkingDaysUntilDate(p_date)
    End If

    getWorkingDaysUntilDate = getWorkindDaysUntilDateDict(p_date)
End Function
Private Function getWorkindDaysUntilDateDict() As Scripting.Dictionary

    If m_WorkingDaysUntilDate Is Nothing Then
        Set m_WorkingDaysUntilDate = New Scripting.Dictionary

    End If

    Set getWorkindDaysUntilDateDict = m_WorkingDaysUntilDate

End Function
Private Function calculateWorkingDaysUntilDate(p_date As Date) As Integer

    Dim iteratedDate As Date
    iteratedDate = Date
    calculateWorkingDaysUntilDate = 0

    Do Until iteratedDate >= p_date
        calculateWorkingDaysUntilDate = calculateWorkingDaysUntilDate + 1

        Do
            iteratedDate = DateAdd("d", 1, iteratedDate)
            If isDateValidAdd(iteratedDate) Then Exit Do
        Loop

    Loop

End Function

Private Function isDateValidAdd(p_date As Date) As Boolean
    isDateValidAdd = True

    If getHolidayLibrary.exists(p_date) Then
        isDateValidAdd = False
    'saturdays
    ElseIf Weekday(p_date, vbSaturday) = 1 Then
        isDateValidAdd = False
    'sunday
    ElseIf Weekday(p_date, vbSaturday) = 2 Then
        isDateValidAdd = False
    End If

End Function

Private Function getHolidayLibrary() As Scripting.Dictionary

    If m_HolidayLibrary Is Nothing Then
        Set m_HolidayLibrary = createHolidayLibrary
    End If

    Set getHolidayLibrary = m_HolidayLibrary

End Function
Private Function createHolidayLibrary() As Scripting.Dictionary

   Dim rs As ADODB.Recordset
   Set rs = New ADODB.Recordset
   Set createHolidayLibrary = New Scripting.Dictionary

   rs.Open "eHolidays", CurrentProject.Connection, , adLockReadOnly

   Do Until rs.EOF
        createHolidayLibrary.Add CDate(rs.fields("Holiday")), rs.fields("HolidaysID")
        rs.MoveNext
   Loop

End Function


texts:
I'm looking for (and be as brutal as you like) ways to improve the code or the algorithm (I'm aware there should be comments) - I'm a recreational programmer and would like to be improving my skills. My next step is to get the targetNumber value from a nearby file without losing the current count.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN "http://www.w3.org/TR/html4/strict.dtd">

  <title>Count to a particular target</title>

Starting


texts: Text-based Tic Tac Toe with DRY and PEP-8

texts:
This is a basic Tic-Tac-Toe game with a minimal interface. The only concessions to ease of use are input validation (7 lines) and 1-indexed rows and columns (a few bytes). I've been trying to tighten it up while still maintaining readability and PEP-8 style.

I'm pretty happy with most of it, except for printing the board: I'd like to do it at the beginning, between each move, and at the end, but I don't see how to manage that without either repeating the formatted print() call or turning it into a function and calling it twice. As you can see, my current compromise omits the empty starting board in favor of the more interesting ending board.

This printing issue is my focus at the moment, but I'm also interested in any other suggestions for improvement.

board = [['*' for i in range(3)] for j in range(3)]

def askmove(piece):
    while True:
        try:
            x,y = map(int, input('\n> '))
            if board[x-1][y-1] == '*':
                board[x-1][y-1] = piece
            else:
                continue
        except (ValueError, IndexError):
            pass
        else:
            break
    print('', *(' '.join(row) for row in board), sep='\n')
    if ([piece] * 3 in board or
        (piece,) * 3 in zip(*board) or
        all(board[i][i] == piece for i in range(3)) or
        all(board[i][2-i] == piece for i in range(3))):
        print(piece, 'wins.')
        return True
    elif all(p!='*' for row in board for p in row):
        print('Tie.')
        return True

while True:
    if askmove('X') or askmove('O'):
        break


texts:
This program prints out a 10x10 square and uses only bit operations. It works well, but I don't like that global array.

Can you tell me if the code is proper or not?

#include <iostream>

const std::size_t HEIGHT = 10;
const std::size_t WIDTH = 10;

char graphics[WIDTH/8][HEIGHT];

inline void set_bit(std::size_t x, std::size_t y)
{
    graphics[(x) / 8][y] |= (0x80 >> ((x) % 8));
}

void print_screen(void)
{
    for (int y = 0; y < HEIGHT; y++)
    {
        for (int x = 0; x < WIDTH/8+1; x++)
        {
            for (int i = 0x80; i != 0; i = (i >> 1))
            {
                if ((graphics[x][y] & i) != 0)
                    std::cout << "*";
                else
                    std::cout << " ";
            }
        }
            std::cout<<std::endl;
    }
}

int main()
{
    for(int x = 0; x < WIDTH; x++)
    {
        for(int y = 0; y < HEIGHT; y++)
        {
            if(x == 0 || y == 0 || x == WIDTH-1 || y == HEIGHT-1)
                set_bit(x,y);
        }
    }
    print_screen();
    return 0;
}


texts: Format capital letters at the start of a sentence

texts:
I have a set of predefined templates for messages, where you can insert different arguments to make it more specific.

In order for the messages to be looking good I needed a way to capitalize the first letters of each sentence because you might pass the argument fully lower-cased while in some messages that argument happen to be the start of the sentence which would require a capital letter at the start.

This is my extension method:

public static class Extensions
{
    private static readonly char[] _punctuationMarks = {'.', '!', '?'};

    public static string FormatCapitalLetters(this string source)
    {
        StringBuilder result = new StringBuilder();
        result.Append(source.First().ToUpper());
        for (int i = 1; i < source.Length; i++)
        {
            result.Append(source[i]);
            if (IsPunctuationMark(source[i]))
            {
                int index = i + 1;
                if (index >= source.Length || IsPunctuationMark(source[index]))
                {
                    continue;
                }
                if (source[index] == ' ')
                {
                    index++;
                }
                result.Append(' ');
                result.Append(source[index].ToUpper());
                i += index - i;
            }
        }
        return result.ToString();
    }

    private static string ToUpper(this char input) => input.ToString().ToUpper();

    private static bool IsPunctuationMark(char input) => _punctuationMarks.Any(
        punctuationMark => punctuationMark == input);
}

I'm looking for any comments on how to improve the current code or fix any flaws I'm unaware of, any alternative solutions are welcome as well.


texts: DFT (Discrete Fourier Transform) Algorithm in Swift

texts:
I am looking to replicate in Swift what the FFT function does in Matlab. Essentially, it takes an arbitrary length signal (not necessarily a multiple of \$2^n\$) and gives real and complex DFT coefficients.

Since the FFT described in Accelerate can only handle sample sizes that are multiples of \$2^n\$, I wrote a brute force algorithm in Swift that produces exactly the same results as the Matlab FFT function for arbitrary sample size.

The problem: When my sample size > 15,000 sample (say), this algorithm takes about 20 s to complete. Could this be sped up?

import Foundation

public func fft(x: [Double]) -> ([Double],[Double]) {

    let N = x.count
    var Xre: [Double] = Array(repeating:0, count:N)
    var Xim: [Double] = Array(repeating:0, count:N)

    for k in 0..<N
    {
        Xre[k] = 0
        Xim[k] = 0
        for n in 0..<N {
            let q = (Double(n)*Double(k)*2.0*M_PI)/Double(N)
            Xre[k] += x[n]*cos(q) // Real part of X[k]
            Xim[k] -= x[n]*sin(q) // Imag part of X[k]
        }
    }
    return (Xre, Xim)
}

// Call FFT
let x: [Double] = [1, 2, 3, 4, 5, 6] // works rapidly
// let x = Array(stride(from: 0, through: 15000, by: (1.0))) // Will   choke it
let (fr, fi) = fft (x: x)
print("Real:", fr)
print(" ")
print("Imag:", fi)
// Call FFT