texts:
I know that there are many similar questions, but I don't understand most of those questions because I'm not sure if I know what a factory method pattern is.

So, after reading many examples over the web, I came up with the following simple classes.

Am I doing it correctly? If so...any improvements I can add?

abstract class Driveable
{
    abstract public function start();
    abstract public function stop();

}

class CoupeDriveable extends Driveable
{
    public function start()
    {
    }

    public function stop()
    {
    }
}

class MotorcycleDriveable extends Driveable
{
    public function start()
    {
    }

    public function stop()
    {
    }
}

class SedanDriveable extends Driveable
{
    public function start()
    {
    }

    public function stop()
    {
    }
}

class DriveableFactory
{
    static public function create($numberOfPeople){

        if( $numberOfPeople == 1 )
        {
            return new MotorcycleDriveable;
        }
        elseif( $numberOfPeople == 2 )
        {
            return new CoupleDriveable;
        }
        elseif( $numberOfPeople >= 3 && $numberOfPeople < 4)
        {
            return SedanDriveable;
        }
    }
}

class App
{
    static public function getDriveableMachine($numberOfPeople)
    {
        return DriveableFactory::create($numberOfPeople);
    }
}

$DriveableMachine = App::getDriveableMachine(2);
$DriveableMachine->start();

Update: according to palacsint and serghei's valueable advices, I've updated my code.

abstract class DriveableFactory
{
    static public function create($numberOfPeople);
}

class CarDriveableFactory extends DriveableFactory
{
    static public function create($numberOfPeople){

        $products = array
        (
            1=>"MotorcycleDriveable",
            2=>"CoupeDriveable",
            3=>"SedanDriveable",
            4=>"SedanDriveable"
        );

        if( isset( $products[$numberOfPeople] ) )
        {
            return new $products[$numberOfPeople];
        }
        else
        {
            throw new Exception("unable to find a suitable drivable car");
        }

    }
}


texts: Fast comparison of molecular structures and deleting duplicates

texts:
I have a program that reads in two xyz-files (molecular structures) and compares them by an intramolecular distance measure (dRMSD, Fig. 22). A friend told me that my program structure is bad, and as he is a programmer while I am not, I guess he is right. But as he has no time to help me much, I thought maybe some one of you could provide me with helpful answers.

What my program does right now:

read in molecule 1 (p) and molecule 2 (q)
compare them by dRMSD $$\sqrt{\frac{1}{N(N+1)}\sum_{i<j}\left(p_{ij}-q_{ij}\right)^2}$$ with \$N\$ as the total number of atoms and \$p_{ij}\$ and \$q_{ij}\$ as the euclidean distance between atom i and atom j in each molecule
delete the file of molecule 1 if dRMSD is below a certain threshold

#!/usr/bin/env python

import sys
import math
import os
import numpy as np
from scipy import linalg

def ecd(vec1, vec2):
    "euclidean distance"
    a = np.array(vec1)
    b = np.array(vec2)
    return np.linalg.norm(a-b)

def drmsd(p, q):
    "intra-molecular distance measure"
    a = np.array(p)
    b = np.array(q)
    k = len(p)*(len(p)+1.0)
    total = 0.0
    for i in range(len(p)):
        for j in range(i+1,len(p)):
            total += (ecd(a[i],a[j])-ecd(b[i],b[j]))**2
    return np.sqrt(total/k)

nconf = int(sys.argv[1])

for i in range(1,nconf+1):
    for j in range(i+1,nconf+1):
        fname1 = "h" + str(i) + ".xyz"
        xyz = open(fname1)
        n_atoms = int(xyz.readline())
        coord1 = np.zeros(shape=(n_atoms,3))
        title = xyz.readline()

        cnt = 0
        for line in xyz:
            atom,x,y,z = line.split()
            coord1[cnt] = [float(x), float(y), float(z)]
            cnt += 1
        xyz.close()

        fname2 = "h" + str(j) + ".xyz"
        xyz = open(fname2)
        n_atoms = int(xyz.readline())
        coord2 = np.zeros(shape=(n_atoms,3))
        title = xyz.readline()

        cnt = 0
        for line in xyz:
            atom,x,y,z = line.split()
            coord2[cnt] = [float(x), float(y), float(z)]
            cnt += 1
        xyz.close()

        dist = drmsd(coord1,coord2)
        if dist < 0.0001:
            print i, j, dist, " ... ", fname1, "deleted"
            #os.remove(fname1)
            break


texts: How can I avoid all this code duplication?

texts:
As you can see I have to populate the ViewModel with the List of Tags so that the dropdown can have all the options for the user to select.
And I have to do this 2 times for the Create Action and 2 times for the Edit action.

[Authorize]
public ActionResult Create()
{
    var tags = from i in _articleService.GetAllTags()
               select new SelectListItem {Text = i.Name, Value = i.ID.ToString()};
    var model = new CreateArticleViewModel {Tags = tags};
    return View(model);
}

[HttpPost, Authorize]
public ActionResult Create(CreateArticleViewModel model)
{
    if (ModelState.IsValid)
    {
        try
        {
            var currentUser = _userService.GetByUserName(User.Identity.Name);
            var tagIds = model.TagIds.Select(int.Parse);
            var article = _articleService.Create(currentUser, model.Title, model.Body, tagIds);
            return RedirectToAction("ViewArticle", new { id = article.ID });
        }
        catch (Exception ex)
        {
            ModelState.AddModelError("Error", ex.Message);
        }
    }
    var tags = from i in _articleService.GetAllTags()
               select new SelectListItem { Text = i.Name, Value = i.ID.ToString() };
    model.Tags = tags;
    return View(model);
}

[Authorize]
public ActionResult Edit(int id)
{

    var article = _articleService.GetById(id);
    var tags = from tag in _articleService.GetAllTags().ToList()
               select new SelectListItem { Text = tag.Name, Value = tag.ID.ToString(), Selected = article.HasTag(tag)};
    var model = new CreateArticleViewModel {Title=article.Title, Body = article.Body, Tags = tags };

    return View(model);
}

[HttpPost, Authorize]
public ActionResult Edit(CreateArticleViewModel model)
{
    if (ModelState.IsValid)
    {
        try
        {
            //handle article update
        }
        catch (Exception ex)
        {
            //Add ModelState error
        }
    }
    var tags = from tag in _articleService.GetAllTags().ToList()
               select new SelectListItem { Text = tag.Name, Value = tag.ID.ToString(), Selected = article.HasTag(tag)};
    model.Tags= tags;

    return View(model);
}

Is there a better way?


texts:
I made a simple async networking server and I'd like to get some input on the code, whether things can be done better and whether the code is stable (able to hold more than 1000 connections without lag) for a MMORPG game.

GameNetworkListener.cs:

using System;
using System.Net;
using System.Net.Sockets;
using System.Threading.Tasks;

namespace Rain.Networking.Game
{
    public class GameNetworkListener
    {
        private TcpListener _listener;

        public async Task StartListening(int port)
        {
            _listener = new TcpListener(IPAddress.Any, port);
            _listener.Start();

            TcpClient lastClient;

            while ((lastClient = await _listener.AcceptTcpClientAsync()) != null)
            {
                Console.WriteLine($"New connection from {lastClient.Client.RemoteEndPoint}");

                var gameNetworkClient = new GameNetworkClient(lastClient);
                await gameNetworkClient.StartReceiving();
            }
        }

        public void Stop()
        {
            _listener.Stop();
        }
    }
}

GameNetworkClient.cs:

using System;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace Rain.Networking.Game
{
    public class GameNetworkClient
    {
        private readonly TcpClient _client;
        private readonly NetworkStream _stream;

        public GameNetworkClient(TcpClient client)
        {
            _client = client;
            _stream = client.GetStream();
        }

        public async Task StartReceiving()
        {
            while (_client.Connected)
            {
                var bytes = new byte[512];
                var amount = await _stream.ReadAsync(bytes, 0, bytes.Length);

                var raw = Encoding.UTF8.GetString(bytes);

                if (amount > 0)
                {
                    if (raw.StartsWith("<policy-file-request/>"))
                    {
                        await SendData(Encoding.UTF8.GetBytes("<?xml version=\"1.0\"?>\r\n" +
                                                                 "<!DOCTYPE cross-domain-policy SYSTEM \"/xml/dtds/cross-domain-policy.dtd\">\r\n" +
                                                                 "<cross-domain-policy>\r\n" +
                                                                 "<allow-access-from domain=\"*\" to-ports=\"*\" />\r\n" +
                                                                 "</cross-domain-policy>\x0"));
                        _client.Dispose();
                    }
                    else
                    {
                        Console.WriteLine($"Received {raw}");
                    }
                }
                else
                {
                    _client.Dispose();
                }
            }
        }

        public async Task SendData(byte[] data)
        {
            await _stream.WriteAsync(data, 0, data.Length);
        }
    }
}

Following rules start the server:

_gameNetworkListener = serviceProvider.GetService<GameNetworkListener>();
await _gameNetworkListener.StartListening(30000);


texts:
The code should be relatively self-explanatory. I was wondering how much rep the Top Voters on sites did "generate" on a site, in comparison to how much rep they "own".

Therefore I created a little SEDE-Query and I am now wondering, if I follow good SQL-Practices and how the performance of the query could possibly be improved (even though it's rather simple already..)

WITH Voters AS(
   SELECT DISTINCT UpVotes, DownVotes, Id, Reputation
   FROM Users
   WHERE Reputation != 101 AND Reputation != 1 --Exclude users without repchanges
   )

SELECT TOP ##topX:int?20##
    Users.Id as [UserLink],
    Users.DisplayName as [SortName],
    Voters.Upvotes * 8 as [EstimatedAddedRep],
    --as there is no split between question and answer votes
    -- we take 8 as median in accordance to the tendency that there are more
    -- answer votes (10 rep) than question votes (5 rep)
    Voters.Downvotes * 3 as [EstimatedDestroyedRep],
    Users.Reputation as [OwnedRep],
    Voters.Upvotes * 8 / Users.Reputation as [Ratio]
FROM Users, Voters
WHERE users.id = Voters.Id
GROUP BY Users.Id, Users.DisplayName, Users.Reputation, Voters.UpVotes, Voters.DownVotes
ORDER BY EstimatedAddedRep DESC

For anyone who wants to run the newest query, you can do so here: Rep "Created" vs Rep "owned" by topX voters


texts: Any way to optimize or improve this python combinations/subsets functions?

texts:
I believe this is essentially the same method as the itertools.combinations function, but is there any way to make this code more more perfect in terms of speed, code size and readability :

def all_subsets(source,size):
        index = len(source)
        index_sets = [()]
        for sz in xrange(size):
                next_list = []
                for s in index_sets:
                        si = s[len(s)-1] if len(s) > 0 else -1
                        next_list += [s+(i,) for i in xrange(si+1,index)]
                index_sets = next_list
        subsets = []
        for index_set in index_sets:
                rev = [source[i] for i in index_set]
                subsets.append(rev)
        return subsets

Yields:

>>> Apriori.all_subsets(['c','r','i','s'],2)
[['c', 'r'], ['c', 'i'], ['c', 's'], ['r', 'i'], ['r', 's'], ['i', 's']]

There is probably a way to use generators or functional concepts, hopefully someone can suggest improvements.


texts:
The code is returning reviews based on users like status order. It seems it executes a lot of SQL queries, so do you think it can be simplified and can it be a headache to server performance?

ret = _dbEntitySet.AsNoTracking()
           .Where(p => p.PostId == postId && p.IsPublished)
           .Include(p => p.UserLikes)
           .OrderByDescending(p => p.UserLikes.Select(f => f.LikeStatus == LikeStatus.Like).Count() - p.UserLikes.Select(f => f.LikeStatus == LikeStatus.Dislike).Count())
           .Skip((reviewPageIndex - 1) * reviewPageSize)
           .Take(reviewPageSize)
           .Select(p => new PostModalReviewDisplay()
           {
               CommentCount = p.Comments.Count(),
               DislikeCount = p.UserLikes.Where(q => q.LikeStatus == LikeStatus.Dislike).Count(),
               LikeCount = p.UserLikes.Where(q => q.LikeStatus == LikeStatus.Like).Count(),
               IsCurrentUserDisliked = p.UserLikes.Any(w => w.LikeStatus == LikeStatus.Dislike && w.UserInfoId == currUserId),
               IsCurrentUserLiked = p.UserLikes.Any(w => w.LikeStatus == LikeStatus.Like && w.UserInfoId == currUserId),

               Content = p.Content,
               Id = p.Id,
               UserInfo = new UserInfoExtraSmall()
               {
                   AppUserId=p.UserInfo.AppUserId,
                   Name=p.UserInfo.Name,
                   Surname=p.UserInfo.Surname,
                   ProfileImage=p.UserInfo.ProfilePicture.SmallPath
               }
           })


texts: Web Scraping Dynamically Generated Content Python

texts:
This is a small web scraping project I made in 2 hours that targets the website remote.co . I am looking forward for improvements in my code. I know about the inconsistency with the WebDriverWait and time.sleep() waits, but when I used the WebDriverWait to wait until the load_more button was clickable and ran the program selenium crashed my webdriver window and continuously spammed my terminal window with 20-30 lines of seemingly useless text.

import scrapy
from selenium import webdriver
from selenium.common.exceptions import ElementNotInteractableException
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import ElementClickInterceptedException
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from time import sleep

class ScrapeRemote(scrapy.Spider):
    name = 'jobs'
    start_urls = [f'https://remote.co/remote-jobs/search/?search_keywords={job_title}']

    job_title = input('Enter your desired position: ').replace(' ', '+')

    def __init__(self):
        self.driver = webdriver.Chrome(r'C:\Users\leagu\chromedriver.exe')

    def parse(self, response):
        self.driver.get(response.url)

        try:
            load_more = WebDriverWait(self.driver, 10).until(
                EC.visibility_of_element_located((By.XPATH, '/html/body/main/div[2]/div/div[1]/div[3]/div/div/a'))
                )
        except TimeoutException:
            self.log("Timeout - Couldn't load the page!")

        while True:
            try:
                sleep(1.5)
                load_more = self.driver.find_element_by_css_selector('a.load_more_jobs')
                load_more.click()
            except (ElementNotInteractableException, ElementClickInterceptedException):
                try:
                    close_button = WebDriverWait(self.driver, 6).until(
                        EC.element_to_be_clickable((By.CSS_SELECTOR, '#om-oqulaezshgjig4mgnmcn-optin > div > button'))
                        )
                    close_button.click()
                except TimeoutException:
                    self.log('Reached Bottom Of The Page!')
                    break

        selector = scrapy.selector.Selector(text=self.driver.page_source)
        listings = selector.css('li.job_listing').getall()

        for listing in listings:
            selector = scrapy.selector.Selector(text=listing)
            position = selector.css('div.position h3::text').get()
            company = selector.css('div.company strong::text').get()
            more_information = selector.css('a::attr(href)').get()
            yield {
                'position': position,
                'company': company,
                'more_information': more_information
            }

        self.driver.close()


texts:
Related to the question Verb conjugator for French, I was asked an question on whether one could summarize all the $exceptionIs<NAME_OF_EXCEPTION> = $exceptionmodel-> getValue() === ExceptionModel::NAME_OF_EXCEPTION lines. In other words, can one make dynamic variables out of the comparison of a value combined with all values of an enum?

As I'm a bit rusty in php, I made this version, and ask you whether this is a good solution, or if it needs major refactoring. To avoid posting other peoples code, I've mocked the ExceptionModel class, and replace the output of ExceptionModel::getConstants() with a predefined array. This to give you working code to review.  The original code is located on github, as the classes ExceptionModel and Enum.

<?php
// A mockup of the original ExceptionModel inheriting from Enum
class ExceptionModel {
    const NO_EXCEPTIONS = 'no_exception';
    const ALLER = 'aller';
    const AVOIR_IRR = 'avoir_irr';
    const ETRE_IRR = 'etre_irr';

    // ... many more lines ...

    function getConstants() {
        // ... returns array of constants ...
    }
}

function myFunction($exception) {
    // In final version, it should use the following line
    // $exceptionModels = ExceptionModel::getConstants();

    // ... but for now, use this array
    $exceptionModels = array (
        "NO_EXCEPTIONS" => 'no_exception',
        "ALLER" => 'aller',
        "AVOIR_IRR" => 'avoir_irr',
        "ETRE_IRR" => 'etre_irr'
    );

    // Generate dynamic variables testing for equality of
    // of $exception and an Enum value from ExceptionModel
    foreach ($exceptionModels as $constName => $constValue) {
        ${'exceptionIs' . $constName} = $exception === $constValue;
    }

    if ($exceptionIsALLER) {
        echo "ExceptionModel is aller. ";
    }

    else if ($exceptionIsAVOIR_IRR) {
        echo "ExceptionModel is avoir_irr";
    } else {
        echo "ExceptionModel was neither, it is: " . $exception;
    }

    echo "\n";
}

echo "<pre>";
myFunction("none");
myFunction(ExceptionModel::ALLER);
myFunction(ExceptionModel::AVOIR_IRR);
echo "</pre>";
?>

This correctly produces the output:

ExceptionModel was neither, it is: none
ExceptionModel is aller.
ExceptionModel is avoir_irr


texts: Beating built-in timsort with own count sort function

texts:
I am trying to write a count sort in Python to beat the built-in timsort in certain situations. Right now it beats the built-in sorted function, but only for very large arrays (1 million integers in length and longer, I haven't tried over 10 million) and only for a range no larger than 10,000. Additionally, the victory is narrow, with count sort only winning by a significant margin in random lists specifically tailored to it.

I have read about astounding performance gains that can be gained from vectorizing Python code, but I don't particularly understand how to do it or how it could be used here. I would like to know how I can vectorize this code to speed it up, and any other performance suggestions are welcome.

def countsort(unsorted_list):
    counts = {}
    for num in unsorted_list:
        if num in counts:
            counts[num] += 1
        else:
            counts[num] = 1

    sorted_list = []
    for num in xrange(min(unsorted_list), max(unsorted_list) + 1):
        if num in counts:
            for j in xrange(counts[num]):
                sorted_list.append(num)

    return sorted_list

GitHub

Additional info:

All that counts is raw speed here, so sacrificing even more space for speed gains is completely fair game.
I realize the code is fairly short and clear already, so I don't know how much room there is for improvement in speed.
If anyone has a change to the code to make it shorter, as long as it doesn't make it slower, that would be awesome as well.
After doing some more precise timing, it is clear that the first for loop takes about 2/3 of the execution time, with the second, constructor, loop taking just 1/3 of the time.


texts: Simple code to check format of user inputted email address

texts:
I am helping a friend with her Java homework and I adapted a solution I used in a similar project of my own for this. It is supposed to use loose/generous regex to make sure an email entered matches the forms abc123@xyz.net or abc.123@xyz.net.

import java.util.Scanner;

public class App {

    Scanner scanner;

    public App() {
        this.scanner = new Scanner(System.in);
    }

    public static void main(String[] args) {
        App app = new App();

        app.GetUsername(true);
    }

    public void GetUsername(Boolean firstRun) {

        if(!firstRun) {
            System.out.println("The username you have entered was in an incorrect format. Must match abc@xyz.net");
        } else {
            System.out.println("Please enter a username:");
        }

        String userInput = this.scanner.nextLine();

        UsernameCheck usernameCheck = new UsernameCheck(userInput);

        if(usernameCheck.isValid()) {
            System.out.println("Welcome, " + userInput + "!");
        } else {
            GetUsername(false);
        }
    }

}

UsernameCheck.java

import java.util.regex.*;

public class UsernameCheck {

    String username;

    public UsernameCheck(String username) {
        this.username = username;
    }

    public Boolean isValid() {
        return this.username.matches("[a-zA-Z0-9\\.]+@[a-zA-Z0-9\\-\\_\\.]+\\.[a-zA-Z0-9]{3}");
    }
}

I am most interested in hearing alternative solutions for re-prompting a user if the input they've given is invalid. This works in practice, but I am looking for the cleanest way to do it.


texts: String tokenizing with arbitrary token count in C

texts:
I am building a small program for input handling so I can conveniently parse lines and tokenize strings. The token handling works right now but I have to malloc a lot in the main() to make it work. Sadly I can not malloc everything at once because then the strings inside will have NULL pointers. Maybe someone more experienced with C can help me improve this:

#include <stdio.h>

int get_tokens(char *line, char **tokens, size_t number_of_tokens) {

    // Make a copy of line to prevent it from being changed
    char *copy = malloc(strlen(line) + 1);
    if (copy == NULL) {
        perror("Could not allocate memory!");
        exit(EXIT_FAILURE);
    }
    strcpy(copy, line);

    char *delimiter = " ";
    char *token = strtok(copy, delimiter);
    if (token) {
        strcpy(*tokens, token);
        size_t tokens_found = 1;
        while ((token = strtok(NULL, delimiter)) && tokens_found < number_of_tokens) {
            strcpy(*(tokens + tokens_found), token);
            ++tokens_found;
        }
    } else {
        printf("No tokens found! The supplied string was empty.");
        return EXIT_FAILURE;
    }
    free(copy);
    return EXIT_SUCCESS;
}

int main() {

    // this will also be the buffer length for the tokens
    size_t line_length = 10;
    char line[line_length];
    get_line(line, line_length);
    // Above function works just as the name implies

    size_t tokens_wanted = 2;
    char **tokens = malloc(tokens_wanted * sizeof(char**));
    for (size_t j = 0; j < tokens_wanted; ++j) {
        tokens[j] = malloc(sizeof(char) * line_length);
    }

    get_tokens(line, tokens, tokens_wanted);

    // process the tokens
    // free the elements of tokens

    free(tokens);
    return EXIT_SUCCESS;
}


texts:
I wrote some functionality that works as intended in order to create functional clickable rectangles. I inherit from RectangleShape in SFML and I have several objects (not just buttons) that inherit from this. The intended logic is to check if a downpress and release pair both happen inside of the same object.

clickableRect.h

#ifndef CLICKABLERECT
#define CLICKABLERECT

#include <SFML\Graphics.hpp>

class clickableRect : public sf::RectangleShape
{
public:
    clickableRect();

    bool click(const sf::RenderWindow & window, const sf::Event & ev);

    void reset();
private:
    bool m_mouseHeld;
    bool m_pressed;
    bool m_active;

    bool isInside(const sf::RenderWindow & window) const;
};
#endif // !CLICKABLERECT

and

clickableRect.cpp

#include "clickableRect.h"

clickableRect::clickableRect() :
    m_pressed(false),
    m_mouseHeld(false),
    m_active(false)
{
     //do nothing
}

bool clickableRect::click(const sf::RenderWindow & window, const sf::Event & ev)
{
    if (ev.type == sf::Event::MouseButtonPressed && isInside(window) && !m_mouseHeld)
    {
        m_pressed = true;
        m_mouseHeld = true;
    }
    else if (ev.type == sf::Event::MouseButtonPressed)
    {
        m_mouseHeld = true;
    }

    if (ev.type == sf::Event::MouseButtonReleased)
    {
        if (isInside(window) && m_pressed)
        {
            m_active = true;
        }
        m_pressed = false;
        m_mouseHeld = false;
    }

    return m_active;
}

void clickableRect::reset()
{
    m_active = false;
}

bool clickableRect::isInside(const sf::RenderWindow & window) const
{
    return sf::Mouse::getPosition(window).x > getPosition().x
        && sf::Mouse::getPosition(window).x < getPosition().x + getSize().x
        && sf::Mouse::getPosition(window).y > getPosition().y
        && sf::Mouse::getPosition(window).y < getPosition().y + getSize().y;
}

I would love any and all feedback on all aspects of the code provided but request specifically to know about:

Is this a good use of inheritance and am I doing it right? Should I use a component pattern instead?
Can I clean up the logic itself inside the click function. It seems a bit messy to me and also requires me to call reset on the objects immediately after returning a true value.


texts:
I am new to COM programming in C++ and while this code works welcome suggestions to improve readability/reliability. This creates a blank word document and adds the text Hello, World.

// The Microsoft Office Object type library (mso.dll)
    #import "libid:2DF8D04C-5BFA-101B-BDE5-00AA0044DE52" raw_interfaces_only, named_guids,\
        rename("DocumentProperties", "_DocumentProperties"), \
        rename("SearchPath", "_SearchPath"), \
        rename("RGB", "_RGB")

     //  The Microsoft Office Word Object type library (msword.olb)
    #import "libid:00020905-0000-0000-C000-000000000046" raw_interfaces_only,\
        rename("ExitWindows", "_ExitWindows"), \
        rename("ReplaceText", "_ReplaceText"), \
        rename("FindText", "_FindText"), \
        rename("RGB", "_RGB")
    #include <Windows.h>

    int main()
    {
        HRESULT hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
        Word::_ApplicationPtr pWordApp;
        Word::DocumentsPtr pWordDocs;
        Word::_DocumentPtr pWordDoc;
        Word::RangePtr pRange;
        hr = pWordApp.CreateInstance(__uuidof(Word::Application));
        pWordApp->put_Visible(VARIANT_TRUE);
        pWordApp->get_Documents(&pWordDocs);

        pWordDoc.CreateInstance(__uuidof(Word::Document));
        pRange.CreateInstance(__uuidof(Word::Range));
        VARIANT vTemplate;
        VariantInit(&vTemplate);
        vTemplate.vt = VT_BSTR;
        vTemplate.bstrVal = SysAllocString(L"");

        VARIANT vNewTemplate;
        VariantInit(&vNewTemplate);
        vNewTemplate.vt = VT_BOOL;
        vNewTemplate.boolVal = false;

        VARIANT vDocType;
        VariantInit(&vDocType);
        vDocType.vt = VT_I4;
        vDocType.iVal = Word::WdNewDocumentType::wdNewBlankDocument;

        VARIANT vVisible;
        VariantInit(&vVisible);
        vVisible.vt = VT_BOOL;
        vVisible.boolVal = true;

        VARIANT vStart;
        VariantInit(&vStart);
        vStart.vt = VT_I4;
        vStart.iVal = 0;

        VARIANT vEnd;
        VariantInit(&vEnd);
        vEnd.vt = VT_I4;
        vEnd.iVal = 0;

        pWordDocs->Add(&vTemplate, &vNewTemplate, &vDocType, &vVisible, &pWordDoc);
        pWordDoc->Range(&vStart, &vEnd, &pRange);

        BSTR str = SysAllocString(L"Hello, World!");
        pRange->put_Text(str);
        SysFreeString(str);
    }


texts: Small bash script to quickly edit scripts in $PATH

texts:
Staying true to the mantra: "The third time you do something, you automate", I've built up a decent collection of shell scripts that live in ~/bin. Some of these scripts contain useful boilerplate code, or just stuff I can't bring myself to memorise (like colour output stuff). Other scripts I find myself elaborating on from time to time. Though not a great pain, I am very lazy. Rather than typing vim ~/bin/some_script, I've written yet another script that expands some_script to its full path (using which), and opens it in vim. I'm perfectly happy with how the script works, and added a few basic creature-comforts, like checking if any (valid) arguments were provided and so on. Truth be told, I've not been writing that much bash in recent years, and some of the expressions/tricks I found myself using feel clunky. I know I used to have something like this in my .profile, but that particular incarnation of the script/function never made it to my github misc repo.
In short, I'd like to know if there's some stuff I could improve on. First the code, then some specific things that just don't feel right to me.
Usage() {
    cat <<-__EOF_
${0##*/} finds executables in PATH and opens them in vim - useful to quickly edit your scripts
    -o         : opens all scripts using o flag (equivalent to vim -o <paths>)
    -O         : similar to -o, but uses -O flag (so vim -O <paths>)
    -h         : Display help message

__EOF_
    exit "${1:-0}"
}

flags=""
paths=""

while getopts :oOh f; do
    case $f in
        o)
            flags="-o"
            ;;
        O)
            flags="-O"
            ;;
        h)
            Usage
            ;;
        *)
            echo "Unknown flag ${f}${OPTARG}"
            Usage 1
            ;;
    esac
    shift
done

[ $# -lt 1 ] && echo "No arguments given" && Usage 2

for b in "$@"; do
    p=$(which "${b}") && paths="${paths} ${p}"
done
[ ${#paths} -gt 0 ] || :(){ echo "No valid executables found in path" && exit 3; };:

# We want globbing and word splitting here
# shellcheck disable=SC2086
vim $flags $paths

Things that just feel a tad off would be:

[ $# -lt 1 ] && echo "No arguments given" && Usage 2 I do this all the time, and it works just fine, but chaining together 3 commands with && like this just looks ugly. If there's a cleaner, more concise way to do the same thing, I'm all ears.
p=$(which "${b}") && paths="${paths} ${p}". I'm not sold on the use of the subshell here. I'm using #!/usr/bin/env bash for my hashbang, I'm not sure I need the subshell. If not, what would be the alternative? What are the pro's, what are the con's?
[ ${#paths} -gt 0 ] || :(){ echo "No valid executables found in path" && exit 3; };: same as chaining things, only this time, because I'm using an ||, then an &&, I just wrap the last 2 expressions in a function and call it. This smells IMO. I could change it to [ ${#paths} -le 0 ] && ..., but then it's just another chain. Personally, I prefer -gt over -le or -eq in this case. I also prefer to have the eventual command (vim) to be the last one, so that the exit code of vim is passed back on success (without needing an explicit exit like [ ${#paths} -gt 0 ] && vim $flags $paths && exit or exit $? if want to be super-explicit)

There might be other things I can improve on, so feel free to point them out.


texts: Splitting code into separate methods and avoiding the Unit Of Work / Repository pattern

texts:
Take a look a this service method:

public static void CreateSocialEvent(int employeeId)
{
    using (var dbContext = new EmployeeEntities())
    {
        using (var transaction = dbContext.Database.BeginTransaction())
        {
            try
            {
                // I would prefer the next two statements to be in a separate method :
                var employee = dbContext.Employees.SingleOrDefault(e => e.IsActive
                    && e.IsSocialEmployee);
                dbContext.SaveChanges();

                // I would prefer the next three statements to be in a separate method :
                var reminder = new Reminder
                    {
                        EmployeeId = employee.EmployeeId,
                        CreationDate = DateTime.Now
                    }
                dbContext.Reminders.Add(reminder);
                dbContext.SaveChanges();

                // I would prefer the next three statements to be in a separate method :
                var socialMailingListSubscriber = new socialMailingListSubscriber
                    {
                        EmployeeId = employee.employeeId
                    }
                dbContext.SocialMailingListSubscribers.Add(socialMailingListSubscriber);
                dbContext.SaveChanges();

                // I would prefer the next three statements to be in a separate method :
                var subscription = new Subscription
                    {
                        subscription.EmployeeId = employee.Id
                    }
                dbContext.Subscriptions.Add(subscription);
                dbContext.SaveChanges();

                // I would prefer the next three statements to be in a separate method :
                var department = dbContext.Department.Find(employee.DepartmentId)
                    .Include(d => d.Subscribers);
                employee.Subscribers = department.Subscribers;
                dbContext.SaveChanges();

                transaction.Commit();
            }
            catch (Exception)
            {
                transaction.Rollback();
                throw;
            }
        }
    }
}

As you saw from my comments, I would prefer to segregate each operation in it's own method, to respect the single responsibility principle, as I don't like having very long methods that do many things.

Say I create a Reminder service that handles Reminders and a SocialMailingList service that handles MailingLists, I would have to inject either the dbContext or the transaction into these other services or into the other methods.

If I choose to inject the transaction, it won't work because if I open a new dbContext there, I cannot assign the injected transaction : it has to come from the same dbContext.

If I inject the dbContext entirely, I will have to write more code just to handle the dbContext lifetime. So, I'm close to implementing the Unit Of Work / Repository Pattern, and that's what I want to avoid at all costs.

If I understand correctly, DbContext in itself is a Unit Of Work, and the DbSet collections act as Repositories (am I right?). I don't like abstracting out something that has already been abstracted for me.

In other words, what should I do?

Keep that long method there so I can keep the Entity-Framework code simple?
Implement the Unit Of Work / Repository pattern so I can control the lifetime of my transaction?

I've never implemented the Unit Of Work / Repository Pattern so far. I've read a lot on that, though, and the amount of code to write to implement it just scares me!

I don't need to mock anything, I don't need to support any other rdbms than MS SQL Server, I don't even unit test anything in this project.

If it's better to implement it, can you suggest the simplest way to do so?


texts:
This question is a follow-up of a previous question of mine: Genetic Drift Simulator.

Following the advice given in the last question, and some more general improvements, the code has been slimmed down a bit. The major one was implementing Underscore.js, which slimmed down a few of the loops into functions.

The config has identical properties to the last question, however, they've been renamed.

numGenerations: the number of generations to iterate over. Can be number input or infinite to go until one population remains.
population: an object containing the names of the populations and the amount of each.
drawAmount: the amount of population to be surveyed.

var GeneticDriftSimulator = function (user_config) {
    this.config = _.defaults(user_config, {
        numGenerations: '5',
        population: {
            red: 50,
            blue: 50
        },
        drawAmount: 10
    });
};

GeneticDriftSimulator.prototype.run = function () {
    var ratioPopulation = this.config.population;
    var isIndefinite = (this.config.numGenerations == 'infinite');
    for (var i = 0; isIndefinite || i < this.config.numGenerations; i++) {
        if (Object.keys(ratioPopulation).length == 1) {
            console.log('Generation ' + i + ': One trait left: ' + Object.keys(ratioPopulation)[0]);
            break;
        }
        var population = [];
        for (var populationName in ratioPopulation) {
            for (var k = 0; k < ratioPopulation[populationName]; k++) {
                population.push(populationName);
            }
        }
        ratioPopulation = this.ProcessGeneration(population, config.drawAmount);

        var print_result = "Generation " + i + ": ";
        Object.keys(ratioPopulation).forEach(function (key) {
            print_result += key + ':' + ratioPopulation[key] + ' '
        });
        console.log(print_result);
    }
};

GeneticDriftSimulator.prototype.ProcessGeneration = function (population, drawAmount) {
    var temp_drawn = [];
    if (config.drawAmount >= population.length) {
        throw 'SimulationError: The DrawAmount is more than the Population.';
    }
    if (population.length % drawAmount != 0) {
        throw 'SimulationError: The DrawAmount cannot be evenly divided by Population';
    }

    temp_drawn = _.sample(population, drawAmount);
    var multiplier = population.length / drawAmount;
    return this.RatioCount(multiplier, temp_drawn);
};

GeneticDriftSimulator.prototype.RatioCount = function (multiplier, temp_drawn) {
    var final = {};
    _.each(temp_drawn, function (population) {
        for (var i = 0; i < multiplier; i++) {
            if (!(population in final)) {
                final[population] = 0;
            }
            final[population]++;
        }
    });
    return final;
}

with usage like the following:

var config = {
    numGenerations: 'infinite',
    population: {
        cats: 3e4,
        dogs: 7e4,
    },
    drawAmount: 5e4
};
var simulation = new GeneticDriftSimulator(config);
simulation.run();


texts:
I have have attempted to use generics and constraints to create functions that retrieve and save data from a number of similar objects. Each of these objects describe their own properties. When I use these methods for a particular Type I don't understand why I have to specify new() in the constraint and also create a new version of the type in order to access its underlying properties to assist me. I'm sure there is a better way, but my knowledge in this area is a little lacking.

There are a number of objects that inherit from RawDataAggregatedItem.

public class Project : RawDataAggregatedItem
{
    public override string IdColumnName
    {
        get { return "project_id"; }
    }

    public override string DescriptionColumnName
    {
        get { return "project_description"; }
    }

    public override string GetStoredProcedureName
    {
        get { return "R_projects_sp"; }
    }
}

...

public class Category : RawDataAggregatedItem
{
    public override string IdColumnName
    {
        get { return "asset_category"; }
    }

    public override string GetStoredProcedureName
    {
        get { return "R_asset_category_sp"; }
    }
}

RawDataAggregatedItem has it's own interface:

public interface IRawDataAggregatedItem
{
    string IdColumnName { get; }
    string DescriptionColumnName { get; }
}

public abstract class RawDataAggregatedItem : IRawDataAggregatedItem
{

    public abstract string IdColumnName { get; }
    public virtual string DescriptionColumnName
    {
        get { return string.Empty; }
    }
    public abstract string GetStoredProcedureName { get; }
}

I've created functions that get and save data to the database using generics expecting these different object types:

public RawDataAggregatedItems<T> GetRawDataAggregated<T>(int? id) where T : IRawDataAggregatedItem, new()
    {
        try
        {
            var itemType = new T();
            using (var cn = Connection())
            {
                var cmd = new SqlCommand(itemType.GetStoredProcedureName, cn) { CommandTimeout = _commandTimeout, CommandType = CommandType.StoredProcedure };
                cmd.Parameters.Add(new SqlParameter("@periodId", SqlDbType.Int)).Value = id;
                return new RawDataAggregatedItems<T>(cmd.ExecuteReader());
            }
        }
        catch (Exception ex)
        {
            throw new Exception("Error fetching aggregated rawdata list.", ex);
        }
    }

public void UpdateRawDataAggregated(RawDataAggregatedItem itemToUpdate)
    {
        try
        {
            using (var cn = Connection())
            {
                var cmd = new SqlCommand(itemToUpdate.UpdateStoredProcedureName, cn) { CommandTimeout = _commandTimeout, CommandType = CommandType.StoredProcedure };
                cmd.Parameters.Add(new SqlParameter("@projectid", SqlDbType.VarChar)).Value = ((IRawDataAggregatedItem)itemToUpdate).ID;
                cmd.Parameters.Add(new SqlParameter("@is_flagged", SqlDbType.Bit)).Value = ((IRawDataAggregatedItem)itemToUpdate).isFlaggedForReview;
                cmd.Parameters.Add(new SqlParameter("@is_reviewed", SqlDbType.Bit)).Value = ((IRawDataAggregatedItem)itemToUpdate).isReviewed;
                cmd.ExecuteReader();
            }
        }
        catch (Exception ex)
        {
            throw new Exception("Error updating aggregated rawdata item.", ex);
        }
    }

If feels a bit wrong to

supply new() in the GetRawDataAggregated constraint but the compiler is forcing me to.
New-ing up a Type T (var itemType = new T()) in order to get to T.Property.

Please could you suggest a better way of doing this?


texts:
I saw a sassy CSS for a rails app like this:

$std-margin: 30px;

@mixin solid-bg($color: #EEEEEE) {
  background: none repeat scroll 0 0 $color;
}

@mixin solid-border($direction, $width: 1px, $color: black) {
  @if $direction == "" {
    border: {
      color: $color ;
      width: $width;
      style: solid;
    }
  } @else {
    border-#{$direction}: {
      color: $color ;
      width: $width;
      style: solid;
    }
  }
}

html {
  font: 90%/1.3 arial,sans-serif;
  body {
    margin: $std-margin;
    .top-nav {
      text-align: center;
      width: 100%;
      .login {
        float: right;
        padding-right: 63px;
        clear: both;
      }
      a {
        text-decoration: none;
      }
    }
    .content {
      @include solid-border("");
      clear: both;
      padding: 15px;
    }
    h2 {
      margin: $std-margin;
      margin-left: 0px;
    }
    h3, .detail {
      margin: $std-margin;
    }
    #header {
      ul {
        list-style: none outside none;
        padding: 0;
        li {
          float: left;
          a {
            @include solid-bg();
            color: #0000CC;
            display: block;
            padding: 0.24em 1em;
            text-decoration: none;
          }
        }
      }
      #selected a {
        @include solid-bg(white);
        color: black;
        font-weight: bold;
        position: relative;
        top: 1px;
        @include solid-border("");
        @include solid-border('bottom', 0px);
      }
    }
    label {
      float: left;
      margin-right: 1em;
      text-align: right;
      width: 10em;
    }
    input {
      @include solid-bg(#FAFAFA);
      -moz-border-radius: 0.4em 0.4em 0.4em 0.4em;
      @include solid-border("", 1px, #DDDDDD);
      font: bold 0.95em arial,sans-serif;
      padding: 0.15em;
      width: 10em;
    }
    .field {
      padding: 5px;
      clear: both;
      input {
        width:12em;
        @include solid-border("", 1px, #006);
        @include solid-bg(#ffc);
        &:hover {
          @include solid-border("");
          @include solid-bg(#ff6);
        }
      }
      .fieldWithErrors {
        float: left;
        padding: 3px;
        input {
        @extend .field.input;
        @include solid-border("", 2px, red);
        }
      }
      .create {
        width:5em;
      }
      .submit {
        @include solid-bg(#D0DAFD);
        border: 0 none;
        cursor: pointer !important;
        display: block;
        height: 26px;
        margin: 1em;
        overflow: hidden;
        width: 69px;
      }
    }

    table {
      border-collapse: collapse;
      margin: 20px;
      text-align: left;
      width: 480px;
      font {
       family: "Lucida Sans Unicode","Lucida Grande",Sans-Serif;
       size: 12px;
      }
      th {
        @include solid-bg(#B9C9FE);
        @include solid-border('bottom', 1px, #FFFFFF);
        @include solid-border('top', 4px, #AABCFE);
        color: #003399;
        font-size: 13px;
        font-weight: normal;
        padding: 8px;
      }
      tr {
        @include solid-bg(#E8EDFF);
        &:hover td {
          @include solid-bg(#D0DAFD);
          color: #333399;
        }
        td.title {
         color: #333399;
        }
      }
      td {
        @include solid-border('bottom', 1px, #FFFFFF);
        @include solid-border('top', 1px, transparent);
        color: #666699;
        padding: 8px;
      }
    }
    .activities {
      padding: 10px;
      a{
        margin: 10px;
      }
    }
    .flash {
      font-family:'Trebuchet MS';
      color:#FF0000;
      font-size:14px;
    }
    .calendar_date_select table {
      width: 78px;
      td {
        padding: 5px;
      }
    }
    .main-content {
      clear: both;
      float: left;
      width: 100%;
    }
    .clear {
      clear: both;
    }
    #errorExplanation {
      @include solid-bg();
      margin: 10px;
      padding: 5px 0 5px 20px;
    }
  }
}

Using best practice how this can be optimized?


texts:
How can I improve this code? Is it somehow possible to remove fields from HTML and pass all necessary data through FormGroup?

app.components.ts

import { Component } from '@angular/core';
import { FormGroup, FormBuilder, FormControl } from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  myForm: FormGroup;

  fields = [
    { label: "Drill Bit Type", name: "drillBitType", options: ["Masonry", "SDS", "Universal"], type: "mat-input" },
    { label: "Drill Bit SharpAngel", name: "drillBitSharpAngel", options: ["118", "120", "135"], type: "mat-select" },
    { label: "Drill Bit Sharp Direction", name: "drillBitSharpDirection", options: ["Left", "Right"], type: "mat-select" }];

  constructor(private formBuilder: FormBuilder) {
    let dictionary: { [key: string]: FormControl; } = {};
    this.fields.forEach(element => {
      dictionary[element.name] = new FormControl(element.label);
    });
    this.myForm = new FormGroup(dictionary);
  }

  Submit() {
    this.fields.forEach(element => {
      console.log(this.myForm.value[element.name]);
    });
  }
}

app.components.html

<form [formGroup]="myForm">
  <ng-container *ngFor="let field of fields">

    <mat-form-field class="example-full-width" *ngIf="field.type=='mat-input'">
      <input matInput formControlName="{{field.name}}">
    </mat-form-field>

    <mat-form-field *ngIf="field.type=='mat-select'">
      <mat-label>{{field.label}}</mat-label>
      <mat-select formControlName="{{field.name}}">
        <mat-option *ngFor="let option of field.options" [value]="option">
          {{option}}
        </mat-option>
      </mat-select>
    </mat-form-field>
  </ng-container>

  <button mat-button (click)="Submit()" type="submit">Submit!</button>
</form>


texts:
I am writing an "Enter key pressed" event-handler, so when user presses the "enter" key in the input of type text, this code is called:

    var email = "";
    var subscriberInput = $("input[name='subscriber_email']")
    // Subscribe RSS
    subscriberInput.keyup(function(e){
        if(e.which == 13){ // Enter key was pressed
            email = subscriberInput.val();
            $.post("/en/subscriber/add", { email: email }).done(function(data){
                 if(data == "success"){

                       subscribeBox.find('div.row').remove();

                       if(isEnglish){
                           subscribeBox.find('h5').text("You're subscribed!").addClass('green-text');
                       } else {
                           subscribeBox.find('h5').text("Sunteti abonat cu success").addClass('green-text');
                       }

                       setTimeout(function(){
                           subscribeBox.fadeOut('slow');
                       }, 5000)
                 } else {
                     alert(data);
                 }
            });
            return false;
        }
    });

How can I improve this code?


texts: class MUserNew | Add DRY, remove constants to mysql defaults

texts:
Note, I choose not to use the Factory Pattern out of preference.

This is a ( M ) odel class in the MVC pattern.

Private functions return Booleans and public functions return strings which I then output to the browser from the Controller.  The class returns a string from the invoke call.

Here is the only call to the class:

Call

$model = new UserNew( new IUniversals() , new IDatabase(), new IText(), new IMessage() );
echo $model->invoke();

Class

class MUserNew extends MUser // set mysql defaults
{
    private $universal_object;
    private $text_object;
    private $message_object;
    private $input_fields = array( 'name', 'email', 'pass' );

    public function __construct( $universal_object, $text_object, $message_object  )
    {
        parent::__construct();
        $this->universal_object = $universal_object;
        $this->text_object = $text_object;
        $this->message_object = $message_object;
    }
    public function invoke()
    {
        $not_validated = $this->checkInput();
        if( $this->universal_object->get( 'load' ) && ( $not_validated !== true ) )
        {
            return $not_validated;
        }
        else
        {
            $email_is_unique = $this->checkEmail();
            if( ( $email_is_unique === true ) )
            {
                return $this->message_object->get( 'PASS' ) . $this->insertRecord() ;
            }
            else
            {
                return $email_is_unique;
            }
        }
    }
    private function checkInput()
    {
        if( !$this->text_object->checkEmpty() )
        {
            return $this->text_object->get( 'empty' );
        }
        foreach( $this->input_fields AS $pattern )
        {
            if( !$this->text_object->checkPattern( $pattern ) )
            {
                return $this->message_object->get( $pattern );
            }
        }
        return true;
    }
    private function checkEmail()
    {
        if( $this->database_object->_pdoQuery( 'single', 'signup_check', array($this->text_object->get('email') ) ) )
        {
            return $this->$message_object->get( 'taken' );
        }
        else
        {
            return true;
        }
    }
    private function insertRecord()
    {
        srand( time() );
        $hash = crypt( $this->text_object->get( 'pass' ), substr( strval( rand() ), -2 ) );
        $this->text_object->set('pass', $hash );
        $this->database_object->_pdoQuery( 'single', 'signup_insert', array( '', $this->text_object->get('name'), $this->text_object->get('email'), $this->text_object->get('pass'), 0, 0 ) );
        $this->database_object->_pdoQuery( 'none', 'bookmark_insert', array($result['id'], 'Facebook', 'http://www.facebook.com', 'facebook.com', 'social', 'http://static.ak.fbcdn.net/rsrc.php/yi/r/q9U99v3_saj.ico'));
        return $hash;
    }

}


texts: Which is better code for implementing quicksort?

texts:
This is how I used to implement quicksort:

def quickSort(alist):
   quickSortHelper(alist,0,len(alist)-1)

def quickSortHelper(alist,first,last):
   if first<last:

       splitpoint = partition(alist,first,last)

       quickSortHelper(alist,first,splitpoint-1)
       quickSortHelper(alist,splitpoint+1,last)

def partition(alist,first,last):
   pivotvalue = alist[first]

   leftmark = first+1
   rightmark = last

   done = False
   while not done:

       while leftmark <= rightmark and alist[leftmark] <= pivotvalue:
           leftmark = leftmark + 1

       while alist[rightmark] >= pivotvalue and rightmark >= leftmark:
           rightmark = rightmark -1

       if rightmark < leftmark:
           done = True
       else:
           temp = alist[leftmark]
           alist[leftmark] = alist[rightmark]
           alist[rightmark] = temp

   temp = alist[first]
   alist[first] = alist[rightmark]
   alist[rightmark] = temp

   return rightmark

alist = [54,26,93,17,77,31,44,55,20]
quickSort(alist)
print(alist)

But recently I have come across this way of implementing quicksort:

def quickSort(L):
    if L == []: return []
    return     quickSort([x for x in L[1:] if x< L[0]]) + L[0:1] + quickSort([x for x in L[1:] if x>=L[0]])

a = [54,26,93,17,77,31,44,55,20]

a = quickSort(a)
print(a)

Which implementation is better in terms of memory usage and time complexity?


texts: LeetCode: Finding all possible letter combinations from an inputted phone number

texts:
Problem Statement:

Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent.
A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.

This is a leetcode problem. I am looking for feedbacks on how to write better, more elegant code. Any suggestions on style, simplicity, comments, etc., are welcome.
My Code:
class Solution {
public:
  vector<string> letterCombinations(string digits) {
    map<char, vector<char>> num_letter_map;
    construct_num_letter_map(num_letter_map);
    vector<string> result;
    letter_combination_helper(digits, num_letter_map, 0, result, "");
    return result;
}

private:
  void construct_num_letter_map(map<char, vector<char>> &num_letter_map) {
    num_letter_map['2'] = vector<char>{'a', 'b', 'c'};
    num_letter_map['3'] = vector<char>{'d', 'e', 'f'};
    num_letter_map['4'] = vector<char>{'g', 'h', 'i'};
    num_letter_map['5'] = vector<char>{'j', 'k', 'l'};
    num_letter_map['6'] = vector<char>{'m', 'n', 'o'};
    num_letter_map['7'] = vector<char>{'p', 'q', 'r', 's'};
    num_letter_map['8'] = vector<char>{'t', 'u', 'v'};
    num_letter_map['9'] = vector<char>{'w', 'x', 'y', 'z'};

    return;
}

  void letter_combination_helper(string digits, const map<char, vector<char>> &num_letter_map, int i, vector<string> &result, string s) {
    if (i == digits.size()) {
        if (i != 0) {
            result.push_back(s);
        }
        return;
    }

    for (char c : num_letter_map.at(digits[i])) {
        letter_combination_helper(digits, num_letter_map, i+1, result, s + string({c}));
    }
}

};


texts:
Convert a decimal number to binary using only loops, strings, if/else statements.

This is my first C++ project and it took me a while to do it. Let me know what you think.

#include <iostream>
#include <string>

using namespace std;

string ConvertInt(int value);
string ConvertDec(double value);
void printBinary1(string str1);
void printBinary2(string str2);

int main()
{
    double number, decValue;
    int remainder, intValue;
    string binary1, binary2;

    cout << "Enter a deciaml value to be converted to binary. Then press ENTER: ";
    cin >> number;

    intValue = (int)number;
    decValue = number - intValue;

    binary1 = ConvertInt(intValue);

    binary2 = ConvertDec(decValue);

    printBinary1(binary1);

    cout << ".";

    printBinary2(binary2);

    int pause;
    cin >> pause;

    return 0;
}

string ConvertInt(int value)
{
    int remainder;
    string binary;

    while(value != 0)
    {
        remainder = value % 2;
        binary += remainder;
        value /= 2;
    }

    return binary;

}

string ConvertDec(double value)
{
    string binary;
    int integer;
    double decimal;

    for(int i = 1; i <= 5; i++)
    {
        integer = (int)value;
        binary += integer;
        decimal = value - integer;
        value = decimal * 2;
    }

    return binary;
}

void printBinary1(string str1)
{
    string binary1 = str1;

    for(int i = (binary1.length() - 1); i <= (binary1.length() - 1); i--)
    {
        cout <<  (int)binary1[i];
    }
}

void printBinary2(string str2)
{
    string binary2 = str2;

    for(int index = 1; index < binary2.length(); index++)
    {
        cout << (int)binary2[index];
    }
}


texts: Opening a file and printing its contents line by line

texts:
Everything that I've read online says that the best way to open a file in python is:

with open('<filename>') as f:
    for line in f.read().splitlines():
        print line

That way you don't have to worry about forgetting to close the file. But I put this in an assignment in my python class and my professor marked points off saying that it was "VB style" (I have no idea what that means, Visual Basic style?) and that from now on I should open a file this way in python:

f=open('<filename>')
for line in f.read().splitlines():
        print line
f.close()

That seems messy to me and like you would run the risk of forgetting to close one of your files, but then again I'm just a student. What's the best way to open a file in Python?


texts: Checking form input data on submit with pure PHP

texts:
I have some experience with PHP but I have never even try to do this wit pure PHP, but now a friend of mine asked me to help him with this task so I sat down and write some code. What I'm asking is for opinion if this is the right way to do this when you want to use only PHP and is there anything I can change to make the code better. Besides that I think the code is working at least with the few test I made with it.

Here it is:

<?php
session_start();

// define variables and initialize with empty values
    $name = $address = $email = "";
    $nameErr = $addrErr = $emailErr = "";
    $_SESSION["name"] = $_SESSION["address"] = $_SESSION["email"] = "";
    $_SESSION["first_page"] = false;

    if ($_SERVER["REQUEST_METHOD"] == "POST") {
        if (empty($_POST["name"])) {
            $nameErr = "Missing";
        }
        else {
            $_SESSION["name"] = $_POST["name"];
            $name = $_POST["name"];
        }

        if (empty($_POST["address"])) {
            $addrErr = "Missing";
        }
        else {
            $_SESSION["address"] = $_POST["address"];
            $address = $_POST["address"];
        }

        if (empty($_POST["email"]))  {
            $emailErr = "Missing";
        }
        else {
            $_SESSION["email"] = $_POST["email"];
            $email = $_POST["email"];
        }
    }
    if ($_SESSION["name"] != "" && $_SESSION["address"] != "" && $_SESSION["email"] != "") {
    $_SESSION["first_page"] = true;
    header('Location: http://localhost/formProcessing2.php');
    //echo $_SESSION["name"]. " " .$_SESSION["address"]. " " .$_SESSION["email"];
    }
?>
<DCTYPE! html>

<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name <input type="text" name="name" value="<?php echo htmlspecialchars($name);?>">
<?php echo $nameErr;?>

Address <input type="text" name="address" value="<?php echo htmlspecialchars($address);?>">
<?php echo $addrErr;?>

Email <input type="text" name="email" value="<?php echo htmlspecialchars($email);?>">
<?php echo $emailErr;?>

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


texts:
I want to traverse a xml tree until I find the first element whose position matches the path. So if I'm looking for Foo/Bar/FooBar I want to get this:

<Root>
  <Foo>
    <Bar>
      <FooBar /> <!-- This one -->
    </Bar>
  </Foo>
</Root>

However there could be any number of <FooBar />'s in my way and I only want the one at this path. I wrote 2 methods to get this:

private static XElement ElementByName(XElement parent, string name)
{
  return parent.Elements().Where(element => element.Name.LocalName == name).First();
}

private static XElement ElementAtPath(XElement root, string path)
{
  XElement target = root;
  string[] pathArr = path.Split('/');
  for (int i = 0; i < pathArr.Length; i ++)
    {
      target = ElementByName(target, pathArr[i]);
    }
  return target;
}

Is there a faster / more efficient way I could achieve this?


texts:
By this method I am able to solve my problem, but is there any other way that I can make this type of triangle? Please correct my code if I am doing this the long way.

public class Pyramid{
    public static void main(String [] args){
        for (int i=0;i<= 6 ;i++) {
            for (int x=0;x < 6-i;x++) {
                System.out.print(" ");
                }
                for (int k=1;k<=i;k++) {
                        if (k <= 1) {
                            System.out.print(" *");
                        }
                        else if(k <= 2) {
                            System.out.print("  ");
                        }
                        else if(k <= 3) {
                            System.out.print("  ");
                        }
                        else if(k <= 4) {
                            System.out.print("  ");
                        }
                        else if(k <= 5) {
                            System.out.print("  ");
                        }
                        else if(k <= 6) {
                            System.out.print("  ");
                        }

                }
                for (int l=0;l<=i;l++) {
                        if (l <= 0) {
                            System.out.print(" *");
                        }

                }
                System.out.println();

    }
    System.out.print("* * * * * * * *");
}
}


texts: Splitting the coordinates of the world into equal blocks

texts:
It's a function to split the coordinates to some small blocks. For example, some country has a coordinates of north-east and south-west, two diagonals.

If I set the interval to 0.05, it will returns all the coordinates with an interval of 0.05 (or some very close value).

Note: you could regard the blocks as square, and the length of it's edge is 'interval'

For these function, how can simplify it and make it more readable?

Sample results:

[{'ne_lng': -53.0, 'sw_lat': 71.97411764705882, 'interval': 0.05, 'sw_lng': -53.04941176470588, 'ne_lat': 72.0}, {'ne_lng': -53.0, 'sw_lat': 71.94823529411764, 'interval': 0.05, 'sw_lng': -53.04941176470588, 'ne_lat': 71.97411764705882}]

Country = {
    'ne_lat' : 89.000000,
    'ne_lng' : 179.000000,
    'sw_lat' : -89.000000,
    'sw_lng' : -179.000000
}

def getCoordinate(Country, interval):
    ne_lng = Country['ne_lng']
    ne_lat = Country['ne_lat']
    sw_lng = Country['sw_lng']
    sw_lat = Country['sw_lat']
    interval = float(interval)
    i = 0
    temp = ne_lng
    lngList = []
    n = int((ne_lng - sw_lng)/interval)+1
    for _ in range(n):
        i += 1
        lngList.append(temp)
        temp -= (ne_lng - sw_lng) / n
    i = 0
    temp = ne_lat
    latList = []
    n = int((ne_lng - sw_lng)/interval)+1
    for _ in range(n):
        i += 1
        latList.append(temp)
        temp -= (ne_lat - sw_lat) / n
    coordinate = []
    for ki, vi in enumerate(lngList):
        for kj, vj in enumerate(latList):
            if ki == n-1 or kj == n-1:
                pass
            else:
                coordinate.append([vi, vj, lngList[ki+1], latList[kj+1]])
    newList = []
    for host in coordinate:
        newDict = {
            'ne_lng': host[0],
            'ne_lat': host[1],
            'sw_lng': host[2],
            'sw_lat': host[3],
            "interval": interval
        }
        # print posts.insert(newDict)
        newList.append(newDict)
    return newList


texts: Get list of new questions from Stack Overflow

texts:
I would like to write a little pet project using Clojure to study it, something like Stack Overflow client.

Here is a my first code to get list of new questions from site. I am in the very beginning in Clojure so any help will be appreciated.

core.clj:

(ns stackify.core
  (:require [clj-http.client :as client]
            [clojure.data.json :as json]
            [stackify.utils :as utils]
            [stackify.configuration :as config]))

; TODO: move key to environment variables
(def ^:const stackKey "put-your-key-here")
(def ^:const baseUrl "https://api.stackexchange.com/2.2/questions?page=%d&pagesize=100&fromdate=%d&order=asc&sort=creation&site=%s&key=%s")

; Fetch questions
(defn fetch-json [url]
  "fetch internet page by url and return JSON"
  (let [data (client/get url)
        body (get data :body)]

    (json/read-str body)))

(defn fetch-questions [page from site accum]
  "recursive function to get questions"
  (let [url (format baseUrl page from site stackKey)
        json-content (fetch-json url)
        questions (get json-content "items")
        has_more (get json-content "has_more")]

    (println (format "Fetching page %d (has_more=%b)" page has_more))

    (cond
      (= has_more true) (fetch-question (+ page 1) from site (concat accum questions))
      :else (concat accum questions))
    ))

(defn get-questions []
  (let [from (config/read-time)
        now (utils/current-time)]

    (println from)
    (config/save-time now)
    (fetch-questions 1 from "stackoverflow" (vector))))

(defn print-questions [questions]
    (doseq [q questions] (println (get q "title"))))

utils.clj:

(ns stackify.utils
  (:require [clj-time.core :as time]
            [clj-time.coerce :as tc]))

(defn current-time []
  "returns unix time"
  (let [moment (tc/to-long (time/now))]
    (int (/ moment 1000))))

(defn parse-int [s]
  "convert string to int"
  (Integer. (re-find  #"\d+" s )))

configuration.clj:

(ns stackify.configuration
  (:require [stackify.utils :as utils]))

(def ^:const configFileName "last_sync_time")

(defn save-time [value]
  "save value to configuration file; file will be overwritten"
  (spit configFileName value))

(defn read-time []
  "read last sync time from configuration file"
  (let [value (slurp configFileName)]
    (utils/parse-int value)))

(defn init []
  "initiliza configuration file"
  (save-time (utils/current-time)))


texts:
Given the problem:

  You are given a 2-Dimensional array with M rows and N columns. You are
  initially positioned at (0,0) which is the top-left cell in the array.
  You are allowed to move either right or downwards. The array is filled
  with 1's and 0's. A 1 indicates that you can move through that cell, a
  0 indicates that you cannot move through the cell. Return the number
  of paths from the top-left cell to the bottom-right cell (i.e. (0,0)
  to (M-1,N-1)).

And my implementation:

#include <iostream>

#define ROW M // Fill this in
#define COL N // Fill this in

bool pathCount(int (&matrix)[ROW][COL], int M, int N, int m, int n, int &paths)
{
  std::cout << "@ (" << m << ", " << n << ")" << std::endl;
  if (m == M - 1 && n == N - 1 && matrix[m][n]) {
      ++paths;
      return false;
  } else if (m == M || n == N || !matrix[m][n]) {
      return false;
  }

  while (pathCount(matrix, N, M, m, n + 1, paths));
  while (pathCount(matrix, N, M, m + 1, n, paths));

  return false;
}

int pathCount(int (&matrix)[ROW][COL], int M, int N)
{
  int paths = 0;
  pathCount(matrix, M, N, 0, 0, paths);
  return paths;
}

Are there any improvements or potential bugs in the implementation? I ran it through a few tests. In terms of performance I am seeing this as having worst-case complexity of \$O(n + m)\$ which is the complexity of depth first search. Is that correct?


texts: Generate Cartesian product of List in Java

texts:
My code, which generates Cartesian product of all lists given as arguments:

public static <T> List<List<T>> cartesianProduct(List<T>... lists) {

    List<List<T>> product = new ArrayList<List<T>>();

    for (List<T> list : lists) {

        List<List<T>> newProduct = new ArrayList<List<T>>();

        for (T listElement : list) {

            if (product.isEmpty()) {

                List<T> newProductList = new ArrayList<T>();
                newProductList.add(listElement);
                newProduct.add(newProductList);
            } else {

                for (List<T> productList : product) {

                    List<T> newProductList = new ArrayList<T>(productList);
                    newProductList.add(listElement);
                    newProduct.add(newProductList);
                }
            }
        }

        product = newProduct;
    }

    return product;
}

Can this code be simplified?


texts: Simple "nullable" template class. Are there weaknesses in the implementation?

texts:
The goal is to have fields in a class which are optional and can be determined if they are set in order to be able to leave them out of serialization.

template<typename T>
class Nullable
{
public:
    Nullable() : m_value(), m_isSet(false) {}
    Nullable(T value) : m_value(value), m_isSet(true) {}
    Nullable(const Nullable& other) : m_value(other.m_value), m_isSet(other.m_isSet) {}

    friend void swap(Nullable& a, Nullable& b)
    {
        using std::swap;
        swap(a.m_isSet, b.m_isSet);
        swap(a.m_value, b.m_value);
    }

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

    T operator=(T value) { set(value); return m_value; }
    bool operator==(T value) { return m_isSet && value == m_value; }
    operator T() const { return get(); }

    T get() const
    {
        if (m_isSet) return m_value;
        else throw std::logic_error("Value of Nullable is not set.");
    }

    bool is_set() const { return m_isSet; }

    void reset() { m_isSet = false; m_value = T(); }

private:
    void set(T value) { m_value = value; m_isSet = true; }

private:
    T m_value;
    bool m_isSet;
};

Any comments are welcome.


texts: Breadth first search of a binary-tree with channels

texts:
As an exercise in using channels in Go I implemented a breadth-first traversal of a binary tree, using a channel as a queue to store the order of the nodes to traverse. After ironing out a bunch of bugs related to all goroutines sleeping I ended up with this code:
package main

import "fmt"

type Node struct {
    Value int
    Left  *Node
    Right *Node
}

var tree *Node

func init() {
    tree = &Node{1, &Node{2, &Node{4, &Node{6, nil, nil}, nil}, &Node{5, nil, &Node{7, nil, nil}}}, &Node{3, nil, nil}}
}

func (t *Node) BFS() {
    c := make(chan *Node, 512)
    c <- t
    bfs(c)
    close(c)
}

func bfs(c chan *Node) {
    empty := false
    for {
        select {
        case next := <-c:
            if next != nil {
                c <- next.Left
                c <- next.Right
                fmt.Println(next.Value)
            }
        default:
            empty = true
        }
        if empty {
            break
        }
    }
}

func main() {
    tree.BFS()
}

While I appreciate advice on any part of the code, I am specifically concerned about the tight for loop in the body of bfs(), the not particularly safe-for-concurrency code and other possible issues mentioned in this question on stackoverflow.


texts: Shuffle the elements of the array randomly

texts:
I have written the code to shuffle the elements of the array. Please let me know of any loopholes in the written code.

package dataStructureInJava;

import java.awt.SystemTray;
import java.util.Random;
import java.util.Scanner;

public class ShuffleArr {
    public static void main(String[] args){
        System.out.println("Main Method Started");
        int [] arr = initArr();
        printArr(arr);
        arr = swapArr(arr);
        printArr(arr);
        System.out.println("Main MEthod Ended");
    }
    public static int[] initArr(){
        Scanner in = new Scanner(System.in);
        Random rand = new Random();
        System.out.println("Enter the limit of the arr");
        int limit = in.nextInt();
        System.out.println("Enter the maximum value of the arr");
        int maxValue = in.nextInt();
        int[] arr = new int[limit];
        for(int ii=0;ii<limit;ii++){
            arr[ii] =  rand.nextInt(maxValue);
        }
        return arr;
    }
    public static int[] swapArr(int[] arr){
        Random rand = new Random();
        for(int ii=0;ii<arr.length;ii++){
            arr = swap(arr,ii,rand.nextInt(arr.length));
        }
        return arr;
    }
    public static int[] swap(int[] arr,int ii,int jj){
        int temp=arr[ii];
        arr[ii]=arr[jj];
        arr[jj]=temp;
        return arr;
    }
    public static void printArr(int[] arr){
        System.out.println("Element of the arr are");
        System.out.print("{");
        for(int ii=0;ii<arr.length;ii++){
            System.out.print(arr[ii] + " ");
        }
        System.out.print("}");
        System.out.println();
    }
}

I got his question as an assignment and want to know if it is correct or not.


texts:
I want to call an Action every X cycles (in my case, to a transaction commit every 100 records), so I do:

public class CyclicActionCaller
{
    private int _counter;
    private int _cycleValue;
    private Action _methodToCall;

    public CyclicActionCaller()
    {
        _counter = 0;
    }

    public CyclicActionCaller Every(int cycleValue)
    {
        _cycleValue = cycleValue;
        return this;
    }

    public CyclicActionCaller Call(Action methodToCall)
    {
        _methodToCall = methodToCall;
        return this;
    }

    public void PerformCall()
    {
        Interlocked.Increment(ref _counter);
        // IS THIS THREAD SAFE - SHOULD BE CALLED EVERY _counter % _cycleValue - EVEN IN MULTITHREADING ENVIRONMENT
        if (_counter % _cycleValue == 0)
        {
            _methodToCall();
        }
    }
}

CyclicActionCaller cyclicActionCaller = new CyclicActionCaller();
using (ModelContainer container = new ModelContainer())
{
   cyclicActionCaller.Every(100).Call(() => { container.SaveChanges(); });

   while(...) { // Import Loop - assume multiple workers inside
       cyclicActionCaller.PerformCall(); // every worker calls this after inserting a row
   }
}

Is this function thread safe? I want that - even if multiple threads call PerformCall - that it is just called once every 100 calls.


texts: Checking HTTP headers with asyncio and aiohttp

texts:
This is one of my first attempts to do something practical with asyncio. The task is simple:

  Given a list of URLs, determine if the content type is HTML for every URL.

I've used aiohttp, initializing a single "session", ignoring SSL errors and issuing HEAD requests to avoid downloading the whole endpoint body. Then, I simply check if text/html is inside the Content-Type header string:

import asyncio

import aiohttp

@asyncio.coroutine
def is_html(session, url):
    response = yield from session.head(url, compress=True)
    print(url, "text/html" in response.headers["Content-Type"])

if __name__ == '__main__':
    links = ["https://httpbin.org/html",
             "https://httpbin.org/image/png",
             "https://httpbin.org/image/svg",
             "https://httpbin.org/image"]
    loop = asyncio.get_event_loop()

    conn = aiohttp.TCPConnector(verify_ssl=False)
    with aiohttp.ClientSession(connector=conn, loop=loop) as session:
        f = asyncio.wait([is_html(session, link) for link in links])
        loop.run_until_complete(f)

The code works, it prints (the output order is inconsistent, of course):

https://httpbin.org/image/svg False
https://httpbin.org/image False
https://httpbin.org/image/png False
https://httpbin.org/html True

But, I'm not sure if I'm using asyncio loop, wait and coroutines, aiohttp's connection and session objects appropriately. What would you recommend to improve?


texts:
Find the sum of all the multiples of 3 or 5 below 1000.

https://projecteuler.net/problem=1
Is there any hack to do modulo operation in better way?

#include<iostream>

int main()
{
    unsigned int sum=0;

    for( int i = 0; i < 1000; ++i )
    {
        if( ( i % 3 == 0 ) || ( i % 5 == 0 )  ||
           ( ( i % 3 == 0 ) && ( i % 5 == 0 ) ) )
        {
            sum += i;
        }
    }
    std::cout<< sum <<"\n";
}


texts: Setting fields, with default values, before saving a row

texts:
I would like to find out if there's a cleaner way to go about validating input before it goes into a function. What I'm doing seems like a lot of code, I'm sure there's a better way. I would also really appreciate some constructive criticism as my goal is to grow as a developer so anything you may see wrong with it or something you would've done better please mention it.

The code below does get the job done. I have tested it and it works, however I would like to improve its beauty and efficiency.

    Private Sub dgvproformas_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles dgvproformas.CellContentClick

    Dim colname As String = ""

    colname = dgvproformas.Columns(e.ColumnIndex).Name

    Select Case colname

        Case "btnsave"

            Dim jobid As Integer = 0
            Dim proformano As String = ""
            Dim paymentreceiveddate As DateTime = Nothing
            Dim paymentreceived As Boolean = False
            Dim proformarequired As Boolean = False
            Dim proformaraised As Boolean = False

            jobid = dgvproformas.Item("job id", e.RowIndex).Value

            If Not IsDBNull(dgvproformas.Item("proformano", e.RowIndex).Value) Then
                proformano = dgvproformas.Item("proformano", e.RowIndex).Value
            End If

            If Not IsDBNull(dgvproformas.Item("proformapaymentreceived", e.RowIndex)) Then
                paymentreceived = dgvproformas.Item("proformapaymentreceived", e.RowIndex).Value
            End If

            If Not IsDBNull(dgvproformas.Item("proformarequired", e.RowIndex).Value) Then
                proformarequired = dgvproformas.Item("proformarequired", e.RowIndex).Value
            End If

            If Not IsDBNull(dgvproformas.Item("proformaraised", e.RowIndex).Value) Then
                proformaraised = dgvproformas.Item("proformaraised", e.RowIndex).Value
            End If

            If Not IsDBNull(dgvproformas.Item("proformapaymentreceiveddate", e.RowIndex).Value) Then
                paymentreceiveddate = dgvproformas.Item("proformapaymentreceiveddate", e.RowIndex).Value
            End If

            If MsgBox("Are you sure you'd like to save this record?", vbYesNo) = vbYes Then
                updateProforma(jobid, proformano, paymentreceived, proformaraised, proformarequired, paymentreceiveddate)
            End If

        Case Else

    End Select

End Sub


texts:
I'm expanding the functionality of this SO answer.

Mainly I'm focusing on:

You can add as many handlers as you want.
You can remove (i.e. cancel) the handler.
You can receive the sender parameter in the handler closure.
You can add "oneshot" handler.

import UIKit

extension UIControl {
    private class EventHandler {

        let _cb: (UIControl, UIEvent) -> Void
        let _oneshot: Bool

        init(_ cb: (UIControl, UIEvent) -> Void, oneshot: Bool) {
            _cb = cb
            _oneshot = oneshot
        }

        @objc func invoke(sender: UIControl, event: UIEvent) {
            _cb(sender, event)
            if _oneshot {
                sender.off(unsafeAddressOf(self))
            }
        }
    }

    typealias EventHandlerId = UnsafePointer<Void>

    func on<T: UIControl>(events: UIControlEvents, _ callback: (T, UIEvent) -> Void) -> EventHandlerId {
        assert(self.isKindOfClass(T), "The handler must receive \(NSStringFromClass(self.dynamicType)) or UIControl")
        return self._on(events, EventHandler({ callback($0 as T, $1) }, oneshot: false))
    }
    func once<T: UIControl>(events: UIControlEvents, _ callback: (T, UIEvent) -> Void) -> EventHandlerId {
        assert(self.isKindOfClass(T), "The handler must receive \(NSStringFromClass(self.dynamicType)) or UIControl")
        return self._on(events, EventHandler({ callback($0 as T, $1) }, oneshot: true))
    }

    func on(events: UIControlEvents, _ callback: () -> Void) -> EventHandlerId {
        return self._on(events, EventHandler({ _, _ in callback() }, oneshot: false))
    }
    func once(events: UIControlEvents, _ callback: () -> Void) -> EventHandlerId {
        return self._on(events, EventHandler({ _, _ in callback() }, oneshot: true))
    }

    private func _on(events: UIControlEvents, _ handler: EventHandler) -> EventHandlerId {
        let ptr = unsafeAddressOf(handler)
        self.addTarget(handler, action: "invoke:event:", forControlEvents: events)
        objc_setAssociatedObject(self, ptr, handler, objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN_NONATOMIC))
        return ptr
    }

    func off(identifier: EventHandlerId) {
        if let handler = objc_getAssociatedObject(self, identifier) as? EventHandler {
            self.removeTarget(handler, action: nil, forControlEvents: .AllEvents)
            objc_setAssociatedObject(self, identifier, nil, 0)
        }
    }
}

Usage:

class MyViewController:UIViewController {

    @IBOutlet weak var myButton:UIButton!

    override func viewDidLoad() {
        super.viewDidLoad()

        // add event handler
        let handle = myButton.on(.TouchUpInside) { (sender, event) in
            // `sender` is the control itself.
            // `event` is the UIEvent object.
        }

        // remove event handler
        myButton.off(handle)

        // event handler can be () -> Void type
        myButton.on(.TouchUpInside) { [unowned self] in
            // your work
        }

        // "oneshot" event handler
        myButton.once(.TouchUpInside) {
            // your work
        }
    }
}

It's working OK... But, for example:

let btn = UIButton()
btn.on(.TouchUpInside) { (sender: UISwitch, _) in /* ... */ }
                                  ^^^^^^^^

This compiles, but I want to make this compile time error.

Currently, as a workaround, I'm doing "assertion":

assert(self.isKindOfClass(T), "The handler must receive \(NSStringFromClass(self.dynamicType)) or UIControl")

And, if possible, I wish the compiler could infer the type of the sender, like this:

let btn = UIButton()
btn.on(.TouchUpInside) { sender, _ in
    sender.titleLabel.text = "Pushed !!"
}

Any ideas?


texts: Modeling Cash-Case differences - should WebAPI DTO's be flat?

texts:
I have an n-layer application with domain models and DTOs models.

My DTOs are going through entire application(every layer) and also I return them from my WebAPI. It is good approach?

Basically, if my DTOs go out app by API they should be flat or not?

Flat:

public class CashCase
{
    public string Id;
    public string Title;
    public DateTime Opened;

    public decimal DifferenceAmount;
    public decimal DifferenceOriginalAmount;
    public decimal DifferenceOriginalFcyAmount;
    public CashCaseDifferenceCurrency DifferenceCurrency;
    public CashCaseDifferenceSource DifferenceSource;
    public CashCaseDifferenceType DifferenceType;
}
public enum CashCaseDifferenceCurrency
{
    PLN
}
public enum CashCaseDifferenceSource
{
    ATM,
    [EnumMember(Value = "ATM Offsite")]
    ATMOffsite,
    Cash
}
public enum CashCaseDifferenceType
{
    Surplus, Deficiency
}

Not flat:

public class CashCase
{
    public string Id;
    public string Title;
    public DateTime Opened;

    public CashCaseDifference Difference;
}
public class CashCaseDifference
{
    public decimal Amount { get; set; }
    public decimal OriginalAmount;
    public decimal OriginalFcyAmount;
    public CashCaseDifferenceCurrency Currency { get; set; }
    public CashCaseDifferenceSource Source { get; set; }
    public CashCaseDifferenceType Type { get; set; }
}
public enum CashCaseDifferenceCurrency
{
    PLN
}
public enum CashCaseDifferenceSource
{
    ATM,
    [EnumMember(Value = "ATM Offsite")]
    ATMOffsite,
    Cash
}
public enum CashCaseDifferenceType
{
    Surplus,
    Deficiency
}

What would be the best style?

Make them flat if they will be exposed outside applications? I think I don't want expose my inner domain structure to world.


texts: Gravitational Brute Force N-body Algorithm

texts:
I've just started dabbling with code, and as a learning exercise I've written a simple algorithm for solving gravitational n-body problems numerically in JavaScript.

I would be very grateful for general feedback as far as the quality of the code goes (first time I'm asking somebody to review my code; I'm very shy about it!), and more specifically advise on how I could optimize it as when I implement the algorithm in THREE.js in the shape of a simulation of the solar system the simulation starts lagging when I include more than around 70 bodies in the simulation. I know n-body algorithms are computationally intensive by nature, especially those of the brute force variety, but I'm pretty sure I've missed out on some useful tricks that would push it a bit further.

Update: to see a working example of the code, check out the jsfiddle I have thrown together https://jsfiddle.net/e9t88dwh

function nBodyProblem(parameters) {

    this.g = parameters.g; //Gravitational constant
    this.law = parameters.law; //Force law, inverse-square in our universe
this.dt = parameters.dt; //Time step to be used
    this.masses = parameters.masses; //Object array with initial conditions for the bodiess to be simulated

}

nBodyProblem.prototype = {

constructor: nBodyProblem,

getDistance: function (m1, m2) {

    return Math.pow((m1.x - m2.x) * (m1.x - m2.x) + (m1.y - m2.y) * (m1.y - m2.y) + (m1.z - m2.z) * (m1.z - m2.z), this.law);

    },

    updatePositionVectors: function () {

        for (var i = 0, len = this.masses.length; i < len; i++) {

            this.masses[i].x += this.masses[i].vx * this.dt;
            this.masses[i].y += this.masses[i].vy * this.dt;
            this.masses[i].z += this.masses[i].vz * this.dt;
        }

        return this;

    },

    updateVelocityVectors: function () {

        var forceVectorX = 0;
        var forceVectorY = 0;
        var forceVectorZ = 0;

        for (var i = 0, ilen = this.masses.length; i < ilen; i++) {

            for (var j = 0, jlen = this.masses.length; j < jlen; j++) {

                //We don't want to calculate self gravity!!!!!

                if (i !== j) {

                    forceVectorX += (this.g * this.masses[j].m) * (this.masses[j].x - this.masses[i].x) / this.getDistance(this.masses[i], this.masses[j]);
                    forceVectorY += (this.g * this.masses[j].m) * (this.masses[j].y - this.masses[i].y) / this.getDistance(this.masses[i], this.masses[j]);
                    forceVectorZ += (this.g * this.masses[j].m) * (this.masses[j].z - this.masses[i].z) / this.getDistance(this.masses[i], this.masses[j]);

                }

            }

            this.masses[i].vx += forceVectorX * this.dt;
            this.masses[i].vy += forceVectorY * this.dt;
            this.masses[i].vz += forceVectorZ * this.dt;

            forceVectorX = 0;
            forceVectorY = 0;
            forceVectorZ = 0;

        }

        return this;

    }

};


texts:
I was looking for a proper implementation of the AES256 encryption in C# but didn't find anything I was entirely satisfied with, so I decided to take this opportunity to write a class myself and maybe learn a thing or two.

After doing some research I managed to come up with this class :

class AES256
{

    private readonly byte[] _secretKey;

    public AES256(byte[] secretKey)
    {
        _secretKey = secretKey;
    }

    public byte[] Encrypt(byte[] plainBytes)
    {
        return Encrypt(plainBytes, GetRijndaelManaged(_secretKey));
    }

    public byte[] Decrypt(byte[] encryptedBytes)
    {
        return Decrypt(encryptedBytes, GetRijndaelManaged(_secretKey));
    }

    private byte[] Encrypt(byte[] plainBytes, RijndaelManaged rijndaelManaged)
    {
        byte[] transformFinalBlock = rijndaelManaged.CreateEncryptor().TransformFinalBlock(plainBytes, 0, plainBytes.Length);
        return transformFinalBlock;
    }

    private byte[] Decrypt(byte[] encryptedData, RijndaelManaged rijndaelManaged)
    {
        return rijndaelManaged.CreateDecryptor().TransformFinalBlock(encryptedData, 0, encryptedData.Length);
    }

    private RijndaelManaged GetRijndaelManaged(byte[] key)
    {
        var keyBytes = new byte[16];
        var secretKeyBytes = key;
        Array.Copy(secretKeyBytes, keyBytes, System.Math.Min(keyBytes.Length, secretKeyBytes.Length));
        var rijndaelManaged = new RijndaelManaged
        {
            Mode = CipherMode.CBC,
            Padding = PaddingMode.PKCS7,
            KeySize = 256,
            BlockSize = 128,
            Key = keyBytes,
            IV = keyBytes
        };
        return rijndaelManaged;
    }

}

It works, - but obviously that alone doesn't make the code good.
What can I improve in this class, is there anything I can optimize?
Feedback is welcome !


texts:
I have created a site for practice and I have already asked a question on Stack Overflow about XSS.

  Someone tell me to show your php functions on this site that i created using filter_Var

These are two PHP functions I created that sanitize/validate user input and after passing the the user input in these function I save the user input in my server (storage).

function Meg_selfvalidator_html($data){//Validator
    if(is_array ($data)){

        $arrayLen = count($data);

        for($i=0;$i<$arrayLen;$i++){
            $data[$i] = trim($data[$i]);
            $data[$i] = stripslashes($data[$i]);
            $data[$i] = htmlentities($data[$i], ENT_QUOTES);
            $data[$i] = filter_var($data[$i], FILTER_SANITIZE_STRIPPED, FILTER_FLAG_STRIP_HIGH );
            $data[$i] = filter_var($data[$i], FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
            $data[$i] = filter_var($data[$i], FILTER_SANITIZE_STRIPPED, FILTER_SANITIZE_STRING);

        }
        return $data;

    }else{
        $data= trim($data);
        $data= htmlentities($data, ENT_QUOTES);
        $data = stripslashes($data);
        $secured_output = filter_var($data, FILTER_SANITIZE_STRIPPED, FILTER_FLAG_STRIP_HIGH );
        $secured_output = filter_var($secured_output,  FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH );
        $secured_output = filter_var($secured_output, FILTER_SANITIZE_STRIPPED, FILTER_SANITIZE_STRING);
        return $secured_output;
    }

}

This is my second PHP function:

function selfValidator($data) {//Validator

    if(is_array ($data)){

        $arrayLen = count($data);

        for($i=0;$i<$arrayLen;$i++){
            $data[$i] = trim($data[$i]);
            $data[$i] = stripslashes($data[$i]);
            $data[$i] = strip_tags($data[$i]);
            $data[$i] = htmlspecialchars($data[$i]);
            $data[$i] = filter_var($data[$i], FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
        }
        return $data;

    }else{
        $data = trim($data);
        $data = stripslashes($data);
        $data = strip_tags($data);
        $data = htmlspecialchars($data);
        return $data;
    }
}

Which one is the best function or what is bad in these functions? How do I add a filter to validate the link?


texts:
Just wondering if I could solicit some feedback on a stored procedure I'm running and whether there's a more efficient way of handling the scenario (I'm pretty sure there will be!).

Basically I have a single SP that I call to return a list of records (Jobs) that may have one or more statuses and a sort order (I'm using RowNum for paging). At the moment I'm using WITH RECOMPILE because the variations on the statuses can change all the time (depending on user etc). There's also some filtering going on.

I'm using an IF statement to essentially run the same bit of code with the only change being the sort order.

I guess my questions are: Is there a better way of doing this (maybe different SP's for different statuses)? Am I overcomplicating things due to lack of knowledge (quite likely) Is the SP actually ok, but requires minor tweaks to reduce the number of lines?

I've pasted a portion of the SP below - the only difference to the full code is the additional IF statements for the different sort orders...

I'd appreciate any feedback.

Thanks in advance!

CREATE PROCEDURE [dbo].[sp_Jobs]
(
    @PageNumber int,
    @PageSize int,
    @FilterExpression varchar(500),
    @OrderBy varchar(50),
    @CustomerID int,
    @ShowNotSet bit,
    @ShowPlaced bit,
    @ShowProofed bit,
    @ShowReProofed bit,
    @ShowApproved bit,
    @ShowOnTime bit,
    @ShowLate bit,
    @ShowProblem bit,
    @ShowCompleted bit,
    @ShowDispatched bit,
    @ShowUnapproved bit,
    @ShowClosed bit,
    @ShowReturned bit,
    @UserID int
)
WITH RECOMPILE
AS
    --JobNumber DESC
    if @OrderBy='JobNumberDESC'
    BEGIN

    WITH Keys AS (SELECT TOP (@PageNumber * @PageSize) ROW_NUMBER() OVER (ORDER BY JobNumber DESC) as rn,P1.jobNumber,P1.CustID,P1.DateIn,P1.DateDue,P1.DateOut,p1.client,p1.MasterJobStatusID,p1.MasterJobStatusTimestamp,p1.OwnerID

    FROM
    vw_Jobs_List P1 WITH (NOLOCK)

    WHERE
    (@CustomerID = 0 OR CustID = @CustomerID)
    AND (@UserID = 0 OR OwnerID = @UserID)
    AND ((@ShowNotSet = 1 AND MasterJobStatusID=1) OR (@ShowPlaced = 1 AND MasterJobStatusID=2) OR (@ShowProofed = 1 AND MasterJobStatusID=3) OR (@ShowReProofed = 1 AND MasterJobStatusID=4) OR (@ShowApproved = 1 AND MasterJobStatusID=5) OR (@ShowOnTime = 1 AND MasterJobStatusID=6) OR (@ShowLate = 1 AND MasterJobStatusID=7) OR (@ShowProblem = 1 AND MasterJobStatusID=8) OR (@ShowCompleted = 1 AND MasterJobStatusID=9) OR (@ShowDispatched = 1 AND MasterJobStatusID=10) OR (@ShowUnapproved = 1 AND MasterJobStatusID=11) OR (@ShowClosed = 1 AND MasterJobStatusID=12) OR (@ShowReturned = 1 AND MasterJobStatusID=13)) AND (Search LIKE '%'+@FilterExpression+'%')

    ORDER BY
    P1.JobNumber DESC ),SelectedKeys AS (
    SELECT TOP (@PageSize)SK.rn,SK.JobNumber,SK.CustID,SK.DateIn,SK.DateDue,SK.DateOut

    FROM
    Keys SK

    WHERE
    SK.rn > ((@PageNumber-1) * @PageSize)

    ORDER BY
    SK.JobNumber DESC)

    SELECT SK.rn,J.JobNumber,J.OwnerID,J.Description,J.Client,SK.CustID,OrderNumber, CAST(DateAdd(d, -2, CAST(isnull(SK.DateIn,0) AS DateTime)) AS nvarchar) AS DateIn, CAST(DateAdd(d, -2, CAST(isnull(SK.DateDue,0) AS DateTime)) AS nvarchar) AS DateDue,CAST(DateAdd(d, -2, CAST(isnull(SK.DateOut,0) AS DateTime)) AS nvarchar) AS DateOut, Del_Method,Ticket#, InvoiceEmailed, InvoicePrinted, InvoiceExported, InvoiceComplete, JobStatus,j.MasterJobStatusID,j.MasterJobStatusTimestamp,js.MasterJobStatus

    FROM SelectedKeys SK JOIN vw_Jobs_List J WITH (NOLOCK) ON j.JobNumber=SK.JobNumber JOIN tbl_SYSTEM_MasterJobStatus js WITH (NOLOCK) ON j.MasterJobStatusID=js.MasterJobStatusID

    ORDER BY
    SK.JobNumber DESC
END

--ELSE IF for other column sorting


texts:
I always seem to struggle refactoring my code. I can look at any other code and know exactly what is going on, but when it comes to cleaning up my code, I get writers block.

The following code works, but I know if can be done much nicer, and with few lines of code. I just wanted to wrap a memcache client to use one server for testing and another for dev/prod or just fetch the value if it cannot connect to the server.

Any tips on refactoring, etc. are much appreciated.

require 'dalli'
class Cache
    def self.fetch(key, ttl, &block)
        if memcache
            memcache.fetch(key, ttl, &block)
        else
            block.call
        end
    end

    def self.memcache
        begin
        if(ENV['RACK_ENV'] == :production or ENV['RACK_ENV'] == :development)
            @memcache ||= Dalli::Client.new('cache.amazonaws.com:11211')
        else
            @memcache ||= Dalli::Client.new('localhost:11211')
        end
        rescue Exception => e
            false
        end
    end
end