texts: Handling of open database connection and calling shared function from WebAPI

texts:
I'm working on an ASP.NET project using VB.NET that uses Dapper and the code as implemented so far runs fine with just me testing. In the example below, Dapper calls a stored proc.

But I am wondering primarily right now if the method of generating an open connection (see dbConnFactory below) implemented in the Domain project is not good practice.

Also, can there be pitfalls to calling a Shared function from .NET's WebAPI, whether it the function is for GET, PUT, POST, or Delete?

AutomoblieDomain project

Imports System.Data.Common
Imports Dapper
Namespace DAL

    Public Class DomainSettings
         Public Shared Property CustomConnectionString As String
    End Class

    Public Class dbConnFactory
        Public Shared Function GetOpenConnection() As DbConnection
            Dim connection = New SqlClient.SqlConnection(CustomConnectionString)
            connection.Open()
            Return connection
        End Function
    End Class

    Public Class CarTypes
        Public Property CarTypeID As Integer
        Public Property CarTypeText As String

        Public Shared Function GetList() As IEnumerable(Of CarTypes)
            Using conn = dbConnFactory.GetOpenConnection()
                Dim _list = conn.Query(Of CarTypes)("dbo.CarTypes_GetList", CommandType.StoredProcedure).ToList()
                Return _list
            End Using
        End Function
    End Class

End Namespace

Web UI Project

Imports System.Net
Imports System.Web.Http
Imports AutomobileDomain

Public Class CarTypesController
    Inherits ApiController

    <HttpGet()>
    Public Function GetList() As IEnumerable(Of DAL.CarTypes)
        Return DAL.CarTypes.GetList()
    End Function

End Class


texts:
This code succeeds in downloading log text files from multiple URLs. Can this be made more efficient?
let private downloadLogs toDirectory =

    let createFileDirectories (url : string) =
        let directory = $@"{toDirectory}\{url.Substring(13, 3)}"

        try
            if not (Directory.Exists(directory))
            then
                Directory.CreateDirectory(directory) |> ignore
        with
            | ex -> failwith ex.Message

    let year = DateTime.Now.Year
    let month = DateTime.Now.Month.ToString("d2")
    let day = DateTime.Now.Day

    let d01LogUrlWithDate = d01LogPartialUrl + $"{year}-{month}-{day}"
    let d02LogUrlWithDate = d02LogPartialUrl + $"{year}-{month}-{day}"
    let s01LogUrlWithDate = s01LogPartialUrl + $"{year}-{month}-{day}"
    let s02LogUrlWithDate = s02LogPartialUrl + $"{year}-{month}-{day}"

    let urlWithDateList = [d01LogUrlWithDate; d02LogUrlWithDate; s01LogUrlWithDate; s02LogUrlWithDate]

    // create folder for each url file
    urlWithDateList |> List.iter createFileDirectories

    let buildFinalUrlAndRequest number url =
        try
            let finalUrl =  if number = 0 then $"%s{url}-1.log" else $"%s{url}-{number}.log"
            printfn $"Searching for URL: {finalUrl}"
            let response = Http.AsyncRequestStream(finalUrl) |> Async.RunSynchronously
            if response.StatusCode >= 200 && response.StatusCode <= 299
            then
                printfn $"URL Ready For Download: {url}"
                Ok response
            else // this is never triggered
                printfn $"Error. Status Code: {response.StatusCode}"
                Error $"Status Code: {response.StatusCode}"
        with
            | ex -> Error $"Request Error: {ex.Message}"

    let buildRequestList (state : seq<Result<HttpResponseWithStream, string>>) t =
        let range = seq{0..11}

        let responseSeq =
            seq{
                for num in range do
                    let numberUpdated = num + 1
                    let response = buildFinalUrlAndRequest numberUpdated t
                    response
            }
        responseSeq |> Seq.filter (fun x -> x |> function | Ok _ -> true | Error _ -> false) |> Seq.append state

    let getResponse urls =
        urls
        |> Seq.fold buildRequestList Seq.empty
        |> Seq.choose (fun x ->
            x |> function
                | Ok response ->
                    Some (async{
                        try
                            let fileName = Path.GetFileName(response.ResponseUrl.Replace(@"/", @"\"))
                            let subDir = response.ResponseUrl.Substring(13,3)
                            let pathName = $"""{toDirectory}\{subDir}\{fileName}"""
                            use outputFile = new FileStream(pathName, FileMode.Create)
                            do! response.ResponseStream.CopyToAsync(outputFile) |> Async.AwaitTask
                            printfn $"File Downloaded: {pathName}"
                            return pathName
                        with
                            | ex ->
                                printfn $"Download error {ex.Message}"
                                return ""
                    }) | _ -> None
        )

    urlWithDateList
    |> getResponse
    |> Async.Parallel
    |> Async.RunSynchronously |> Array.toList


texts:
I am trying to split my list into a dictionary and I wrote a function for it. It takes in a list and gets the list length. If the length of the list is 253 , it creates a dictionary with 26 keys - this is calculated by rounding up the number to a higher 10 (250 will create 25 keys, 251-259 will create 26 keys). Each key will store a chuck of the original list (as of now I am storing 10 elements per list).

I want to know if I can improve it more:

def limit_files(file_list, at_a_time=10):

    l = file_list
    n = len(l)
    d, r = divmod(n, at_a_time)

    num_keys = d + 1 if r else d
    slice = n // num_keys
    vals = (l[i:i+slice] for i in range(0, n, slice+1))
    dct = dict(zip(range(1,num_keys+1),vals))
    return (dct)


texts: Results Reporting / Checking with Multiple Results in For Loop

texts:
hoping to be schooled a little bit here in showing "no results".
This is a working snippet, but I'd like to know if there is a more elegant way to show errors when comparing multiple values in an IF statement within a ForLoop... I could have 10 results with only 2 matching my if statement:

if($value["IsArchived"] == false && !preg_match("/^123 ABC/", $value["ProjectName"]))

Is there better way than capturing a count variable $totalToShow == 0 to show my "No Results" in a new IF statement or is that ok?

$obj = drupal_json_decode($result);
//used to show NO RECORDS or not... probably a more elegant way here?!
$totalToShow = 0;
//loop through the json data and add it to the $output array.
//NOTE: not checking if any are empty
$output .= '
';
//check if the obj is empty, if so, no records to display...
if (!empty((array) $obj)) {
  foreach($obj as $key=>$value){
    if($value["IsArchived"] == false && !preg_match("/^123 ABC/", $value["ProjectName"])){
        $totalToShow++;
        //output project name link to project # and append start/end date after link.
        $output .= '
' . $value["ProjectName"] . ' ('. _abc_date($value["CommentStart"]) . " - " .  _abc_date($value["CommentEnd"]).') ';
        if($lrnmore != ""){
            $output .= ' | '. $lrnmore .'';
        }
        $output .= '| View Comments
';
        $output .= '

' . $value["Description"] . '

';
        $output .= "
";
    }
  }
  if($totalToShow == 0){
    $output .= '
No Records to Display
';
  }


texts: Amalgamation of the repository and command / query pattern

texts:
I am coding a web based solution which consists of N number of tiers, these are:

UI
Web API
Business

The question I have is related to validation, repository and CRUD operations. I am adopting the command / query pattern whereby I have my repositories for data retrieval only (see below) and its query dependencies injected in. I have seen people use repositories for CRUD too, but then I get the impression it is doing too much thus warrants further abstraction.

public interface IAddressRepository
{
    Address GetById(int id);

    IEnumerable<Address> GetByPersonId(int personId);

    IEnumerable<Address> GetByPostalCode(string postalCode);
}

public AddressRepository(IGetAddressByIdQuery getAddressByIdQuery
                       , IGetAddressesByPersonIdQuery getAddressesByPersonIdQuery
                       , IGetAddressesByPostalCodeQuery getAddressesByPostalCodeQuery)
{
    this.getAddressByIdQuery = getAddressByIdQuery;
    this.getAddressesByPersonIdQuery = getAddressesByPersonIdQuery;
    this.getAddressesByPostalCodeQuery = getAddressesByPostalCodeQuery;
}

Should my repository return validation errors? For example, the GetById(int id) method will be checking if the id > 0 then make a DB call or simply return a new instance, likewise with a postal code lookup. However, I also think going by the SOLID design principle everything should be autonomous thus this approach of returning no validation errors is the correct choice. I choose to NOT return null on all my methods simply because checking for null is considered as an anti-pattern.

The encompassing of the CRUD logic.  I have seen uses of a Manager and/or Service classes, for example:

public interface IAddressManager
{
    IEnumerable<Error> Delete(Address address);

    IEnumerable<Error> Save(Address address);

    IEnumerable<Error> IsValid(Address address);
}

public AddressManager(IAddressValidator addressValidator, IAddressCommand addressCommand)
{
    this.addressValidator = addressValidator;
    this.addressCommand = addressCommand;
}

Is the general consensus to have a manager class which encompasses these operations but have the dependencies (the commands injected in)?  This way, before I call save(), I validate the object before persisting it. I can also control this behavior via TDD.

Query code example:

public interface IGetAddressByIdQuery
{
    Address Execute(int id);
}

public class GetAddressByIdQuery : IGetAddressByIdQuery
{
    private readonly string connectionString;

    public GetAddressByIdQuery(string connectionString)
    {
        this.connectionString = connectionString;
    }

    public Address Execute(int id)
    {
        using (var conn = new SqlConnection(this.connectionString))
        {
            return conn.Get<Address>(new { Id = id });
        }
    }
}

The data access tier is not apparent as at the moment as the business library is fairly small. I am a firm believer in not creating several libraries for the sake of it. Only create them when it is warranted to do so, i.e. a library is getting too big.

What are your thoughts as to whether or not a better approach / pattern exists?


texts:
Are there alternative (better) ways to factor out the common parts other than my use of abstract base class?  I find myself following this pattern lately and it makes sense when I code it but sometimes leads to code that is particularly susceptible to obfuscation as time goes by (i.e. I come back to it later and have a hard time remembering how it worked). I am curious to know if it looks good and readable or if maybe it's over-optimized or has other issues.

public abstract class DumpKeyValuePairs : Control
{
    static string XsltPath = "~/Controls/DumpKeys.xslt";
    protected override void OnLoad(EventArgs e)
    {
        this.Controls.Add(new Xml {
            DocumentContent = new XElement("keys",
                                    from key in this.Keys
                                    select new XElement("key",
                                                new XAttribute("name", key),
                                                this[key])).ToString(),
            TransformSource = DumpKeyValuePairs.XsltPath,
        });
        base.OnLoad(e);
    }
    abstract protected IEnumerable<string> Keys { get; }
    abstract protected string this[string index] { get; }
}

public class DumpServerVariables : DumpKeyValuePairs
{
    protected override IEnumerable<string> Keys
    {
        get { return HttpContext.Current.Request.ServerVariables.AllKeys; }
    }

    protected override string this[string index]
    {
        get { return HttpContext.Current.Request.ServerVariables[index]; }
    }
}

public class DumpSessionVariables : DumpKeyValuePairs
{
    protected override string this[string index]
    {
        get { return HttpContext.Current.Session[index].ToString(); }
    }

    protected override IEnumerable<string> Keys
    {
        get { return HttpContext.Current.Session.Cast<string>(); }
    }
}

XSLT:

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="keys">

      <xsl:apply-templates select="key" />

  </xsl:template>
  <xsl:template match="key">

        <xsl:value-of select="@name" />

          <xsl:value-of select="." />

  </xsl:template>
</xsl:stylesheet>


texts:
I'm trying to take my existing parallel Quicksort and make it execute faster. Below is what I have but half the time the optimized version doesn't give me a faster time.

I use them to compare big arrays whose sizes are 10,000 or more. Any advice on what I should change? Nthreads is declared in the main function and set to 4.

void quickSort_parallel_omp(int arr[], int low, int high)
{
    int pi;
    if (low < high)
    {
        pi = partition(arr, low, high);
        omp_set_nested(1);
        #pragma omp parallel sections
        {
            #pragma omp section
            quickSort_parallel_omp(arr, low, pi - 1);
            #pragma omp section
            quickSort_parallel_omp(arr, pi + 1, high);
        }
    }
}

void quickSort_Optparallel_omp(int arr[], int low, int high)   //optimized version
{
    int pi;
    if (low < high)
    {
        pi = partition(arr, low, high);
        omp_set_nested(1);
        #pragma omp parallel sections num_threads(Nthreads)
        {
            #pragma omp section
            quickSort_Optparallel_omp(arr, low, pi - 1);
            #pragma omp section
            quickSort_Optparallel_omp(arr, pi + 1, high);
        }
    }
}


texts: How can this function be faster? Solving for a row of Pascal's triangle

texts:
I saw a posting on Hacker News this morning that was ranting about people not being able to solve an interview question. I thought I would give it a shot, but I would like to know how my attempt could be improved.

def get_pascal_row(n):
    """
    Returns the nth row of Pascal's Triangle for a given n. Uses
    Gray's algorithm.
    """
    if n == 0: return []
    n -= 1
    row = [1]
    for i in xrange(1,n+1):
        row.append(row[-1] * n/i)
        n -= 1
    return row


texts:
The purpose of the code is to store arbitrary number of types. The type can be extracted from it using Extract template, which uses template recursion to get the needed type. There will be compilation error if user will try to get out of bounds. I think it supports both fully defined types and only declared types.

In which ways the code below can be improved?

#ifndef TYPELIST_H
#define TYPELIST_H

#include <cstddef>

struct NullType;

template <typename Head, typename ... Tail>
struct TypeList
{
    using head = Head;
    using tail = typename TypeList<Tail...>;
};

template <typename Single>
struct TypeList <Single>
{
    using head = Single;
    using tail = NullType;
};

template <size_t index, typename typelist>
struct Extract
{
    using result = typename Extract<index - 1, typename typelist::tail>::result;
};

template <typename typelist>
struct Extract <0, typelist>
{
    using result = typename typelist::head;
};

#endif

I doubted about whether or not make NullType declaration only. In my opinion, leaving definition better says "don't use this" than empty definition.

I was thinking about SFINAE on out of range indexes, but thought the behavior will be surprising.

My another concern was creating objects of such classes. I couldn't figure out the way to restrict users from creating the objects. The only thing that came to mind is deleting all constructors, but it is strange, thus I decided to refrain from deleting constructors.

Example usage:

#include "typelist.h"
#include <typeinfo>
#include <iostream>

int main()
{
    using MyList = TypeList<int, char, bool>;
    using extracted = Extract<2, MyList>::result;

    std::cout << (typeid(extracted) == typeid(bool));
}


texts:
I'm looking for code review of part of my replacement of timeout() project. Namely, feedback on SleeperNotifier class:
https://github.com/ledestin/frugal_timeout/blob/master/lib/frugal_timeout.rb#L125

If you would like to give feedback on the whole project, by all means do.

  # {{{1 SleeperNotifier
  # Executes callback when a request expires.
  # 1. Set callback to execute with #onExpiry=.
  # 2. Set expiry time with #expireAt.
  # 3. After the expiry time comes, execute the callback.
  #
  # It's possible to set a new expiry time before the time set previously
  # expires. In this case, processing of the old request stops and the new
  # request processing starts.
  class SleeperNotifier # :nodoc:
    include MonitorMixin

    def initialize
      super()
      @condVar, @expireAt, @onExpiry = new_cond, nil, proc {}

      @thread = Thread.new {
        loop {
          @onExpiry.call if synchronize {
            # Sleep forever until a request comes in.
            wait unless @expireAt

            timeLeft = calcTimeLeft
            disposeOfRequest
            elapsedTime = MonotonicTime.measure { wait timeLeft }

            elapsedTime >= timeLeft
          }
        }
      }
      ObjectSpace.define_finalizer self, proc { @thread.kill }
    end

    def onExpiry &b
      @onExpiry = b
    end

    def expireAt time
      synchronize {
        @expireAt = time
        signalThread
      }
    end

    private

    def calcTimeLeft
      synchronize {
        delay = @expireAt - MonotonicTime.now
        delay < 0 ? 0 : delay
      }
    end

    def disposeOfRequest
      @expireAt = nil
    end

    def signalThread
      @condVar.signal
    end

    def wait sec=nil
      @condVar.wait sec
    end
  end


texts:
Here is my code of project Euler #7:

from math import *
import time
start = time.time()
def isPrime(n):
    prime_fst = [2,3,5,7]
    num = round(sqrt(n))
    j=0
    while num>7:
        if num%2!=0 and num%3!=0 and num%5!=0 and num%7!=0:
            prime_fst.append(num)
        num-=1
    prime_fst.sort()
    while j < len(prime_fst):
        for i in prime_fst:
            if i!=prime_fst[j]:
                if i%prime_fst[j]==0:
                    prime_fst.remove(i)
        j+=1
    for t in prime_fst:
        if n%t==0:
            k=n%t
            return False
    return True

x=int(input())
l=1
res = [2,3,5,7]
while len(res)!=x:
    if l!=1:
        if isPrime(l):
            res.append(l)
    l+=2
print(res[-1])
end = time.time()
print(end-start)

Can you recommend what I should do with algorithm skills? How can I think effectively? Will skills develop with time? All your recommendations and help to speed up this code by explaining?


texts: Upload image using php 7 best practices to make it secure

texts:
I have a script that uploads an image, inserts it into database,  and displays it on the home page.

However it's not secure, how can i make this script more secure and make sure it allows only jpeg/jpg files.

UploadController.php

public function upload_image($filename, $image_name)
{

    $this->uploadfile = $this->directory . basename($filename);

    try{
        $sql = "INSERT INTO images (img, image_name) VALUES (?, ?)";
        $stmt = $this->connect->prepare($sql)->execute([$filename, $image_name]);
        return $stmt;
    }
    catch(PDOExeception $e)
    {
        echo $e->getMessage();
    }

}

Home.php

<?php
require_once 'paritals/header.php';
require_once 'paritals/nav.php';

use Eli\Db as DB;
use ElCont\UploadController as Image;

    if(isset($_FILES['profile_img'])){

        $dbh = new DB();
        $connect = $dbh->connect();
        $image = new Image($connect);

        $filename = $_FILES["profile_img"]["name"];
        $realname = "public/uploads/" . basename($filename);
        $directory = $_SERVER['DOCUMENT_ROOT'] . "/public/uploads/";

        $path = $directory . basename($filename);

        $image_name = $_POST['image_name'];

        if($image->upload_image($realname, $image_name)){

            move_uploaded_file($_FILES["profile_img"]["tmp_name"], $path);

            $owl = $image->get_image();

        }

}?>

Upload Image

            <form action="" enctype="multipart/form-data" method="post">

                    File input
                    <input type="file" name="profile_img" class="form-control-file" id="exampleInputFile" aria-describedby="fileHelp">
                    <input type="text" name="image_name" placeholder="Enter Name Of File" class="mt-3">
                    This is some placeholder block-level help text for the above input. It's a bit lighter and easily wraps to a new line.
                    <button type="submit" class="btn btn-primary">Submit</button>

            </form>

<?php

$dbh = new DB();
$connect = $dbh->connect();
$image = new Image($connect);

$photo =  $image->get_images();
foreach($photo as $pic)

{?>

<?php echo $pic['image_name'];?>

                <img src="<?php echo $pic['img'];?>" width="300" height="400">

<?php }?>

<?php require_once  'paritals/footer.php';?>


texts:
This is how I can access the exact scope value, otherwise it will be $scope.type of local scope.

I am accessing this from the template in NSPopover. NSPopover directive has scope: true.

It's also inside the Angular bootstrap module.

<label ng-class="{selected: $parent.$parent.$parent.type == current.type}" >
    <input type="radio" name="type" ng-value="current.type" ng-change="chooseOption()" ng-model="$parent.$parent.$parent.type"/>


texts:
I'm doing a program for a course in school (intro software development) and I'm looking for some general feedback as well as any ways this bit of code could be cleaner. I'm also wondering if it is bad practice to use %= as I've talked with some people and have been told it's not good to use any operators like that, other than += and -= to keep code readable, although maybe that is specific to this particular course.

private int       heightInInches;
private final int VALUE_OF_ONE_FOOT = 12;

public String getHeightInFeetAndInches() {
    String includeInches = "";
    int leftOver = (heightInInches %= VALUE_OF_ONE_FOOT);
    int newHeight = (heightInInches % VALUE_OF_ONE_FOOT);

    if(leftOver < 0) {
        includeInches = "";
    }else if(leftOver <= 1) {
        includeInches = "Inch";
    }else {
        includeInches = "Inches";
    }
    return newHeight + " feet " + leftOver + " " + includeInches;
}

This method should return a person's height in the form of (for example): 6 feet 1 inch(es) (if the inch amount exceeds 1).


texts: Create a GUI to update parameters of an Object

texts:
I have an Glob object which represents a glob of data. It has several parameters like size, the date it was created, who created it, and so on. I'm building a GUI to modify these Globs of data, and in my GUI is a JTextField for each of these parameters. Each JTextField has a FocusListener attached to it, which looks like:

public class GlobUpdaterGUI {

    HashMap<String, Glob> globs;

    // I know it's not great style to call main like this, but
    // it makes this snippet runnable.
    public static void main(String[] args) {
        new GlobUpdaterGUI();
    }

    public GlobUpdaterGUI() {
        initialize();
    }

    public void initialize() {
        JFrame frame = new JFrame("Glob Updater");
        frame.setMinimumSize(new Dimension(250,150));
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel panel = new JPanel(new GridLayout(4, 2));

        JTextField globNumber = new JTextField(10);

        JTextField dateTextField = new JTextField(10);
        dateTextField.addFocusListener(new FocusListener() {

            @Override public void focusGained(FocusEvent arg0) {}
            @Override
            public void focusLost(FocusEvent e) {

                /* "globNumber" lets the user select a glob from "globs". */
                Glob glob = globs.get(globNumber.getText());

                glob.date = dateTextField.getText();
            }
        });

        JTextField sizeTextField = new JTextField(10);
        sizeTextField.addFocusListener(new FocusListener() {

            @Override public void focusGained(FocusEvent arg0) {}
            @Override
            public void focusLost(FocusEvent e) {
                Glob glob = globs.get(globNumber.getText());

                glob.size = dateTextField.getText();
            }
        });

        JTextField creatorTextField = new JTextField(10);
        creatorTextField.addFocusListener(new FocusListener() {

            @Override public void focusGained(FocusEvent arg0) {}
            @Override
            public void focusLost(FocusEvent e) {
                Glob glob = globs.get(globNumber.getText());

                glob.creator = dateTextField.getText();
            }
        });

        panel.add(new JLabel("Glob Number:"));
        panel.add(globNumber);
        panel.add(new JLabel("Glob Date:"));
        panel.add(dateTextField);
        panel.add(new JLabel("Glob Size:"));
        panel.add(sizeTextField);
        panel.add(new JLabel("Glob Creator:"));
        panel.add(creatorTextField);

        frame.add(panel);
        frame.setVisible(true);
    }
}

My problem is that every FocusListener block is nearly identical to the others, but for a specific parameter.

This practice doesn't support readability, writeability, maintainability, or really any style guideline. Though there are only three blocks now, which isn't too bad, a Glob is going to end up with about a dozen parameters, so I'd like to solve this problem before heading too far down the wrong path.

I'd much rather create a new class which implements FocusListener, which takes in a JTextField (and/or whatever else it may need) and modifies its respective Glob parameter, but I don't know the proper practice if I need to modify a different variable in each one. Is there a way to generalize a Listener so that I don't need nearly identical code littered throughout my project?


texts: Add user star function triggering PHPmailer email optimisation

texts:
The function below simple allows a logged in user to "star" another user for convenience when trying to find the that user another time. At the moment the function works as it should, it inserts the user giving the star and the user receiving the star into a database table, then grabs the first name and email from the users table to get more information about the user receiving the star and finally uses that data to send an email to the user receiving the star.

As it stands however, this function is pretty slow when used. Based on user research, users tend to press the "Star user" button numerous times as the application seems unresponsive; when in reality, it is just taking longer as it is sending an email (I've tested the function without the email trigger and it is much faster).

Is there a better way of triggering emails to increase performance using this as an example? Any improvements/recommendations would also be appreciated.

public function addstar($user_id, $starredBy) {

    $query = $this->db->prepare("INSERT INTO " . DB_NAME . ".user_stars (star_id, starred_by_id) VALUES (?, ?)");

    $query->bindValue(1, $user_id);
    $query->bindValue(2, $starredBy);

    $this->db->beginTransaction();

    try{
        $query->execute();

        $getUserInfo = $this->db->prepare("SELECT u.firstname, u.email, u.user_id FROM " . DB_NAME . ".users AS u WHERE u.user_id = ?");
        $getUserInfo->bindValue(1, $user_id);
        $getUserInfo->execute();
        $to = $getUserInfo->fetch();

        $firstName = $to['firstname'];
        $email = $to['email'];

        $this->emails->sendStarEmail($firstName, $email);

        $this->db->commit();

        header('Location: ' . $_SERVER['HTTP_REFERER']);

    }catch(PDOException $e) {
        $this->db->rollback();
        $users = new Users($db);
        $debug = new Errors();
        $debug->errorView($users, $e);
    }
}


texts: SQL structure to save coordinates for spigot plugin

texts:
I'm writing a spigot plugin where I give the user the possibility to send a message to the admins of the server. One of the requirements is that the coordinates of the player are stored, when the message is sent, and that it is stored in a sql table, so that admins on multiple spigot servers can access them independently of where the message was sent originally.
I have got a simple sql table, which stores the message, the player's uuid, etc in a table, but I really dislike the idea that I have to store all three values of the Vec3 in separate columns. I googled for a possibility to simply store a Vec3 via SQL, but had no luck.
Here's an overview of my current table:

I just have this one table with the data in it, which I create like this:
CREATE TABLE IF NOT EXISTS Meldung (
    id INT AUTO_INCREMENT NOT NULL,
    UUID VARCHAR(64),
    NAME VARCHAR(64),
    MESSAGE TEXT,
    XCOORD INT,
    YCOORD INT,
    ZCOORD INT,
    ISREAD TINYINT(1),
    primary key(id));

I'd like to know how I can improve in this matter, or the general way how my data is stored. I'm particularly interested in alternative methods to store these coordinates, I don't know why, I find my current way very unsatisfying.


texts: An online store, being converted from procedural to OOP

texts:
I just start to learn OOP, and it's far more interesting than procedural style.

I have a complete working online store written in procedural style. After realizing that my code is becoming very huge and very complex, I'm searching  for methods to make my code more maintainable and more comfortable. One solution of course is to move to OOP style. But because I just started to understand how OOP work, I do not know which way to go.

con.php:

// Create a database connection
$connection = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
// Test if connection occurred.
if(mysqli_connect_errno()) {
    die();
}

qfunctions.php

function get_user_info($user_id) {
// this function make a query for the user info
    global $connection, $query_error;;
    $query  = "SELECT *
                FROM users
                WHERE users.user_id = {$user_id}";
    $user_result = mysqli_query($connection, $query);

    // Test if there was a qurey error
    if (!$user_result || mysqli_num_rows($user_result) == 0) {
        $query_error = $err_array["PROFILE_NOT_FOUND"];
    } else {
        return $user_result;
    }

}

I feel like this method is good but not the most efficient way possible, so I built a class for my database.

new_con.php

class MySQLDatabase {

private $connection;

function __construct() {
    $this->open_connection();
}

public function open_connection() {
    $this->connection = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
    if(!$this->connection) {
        die("Database connection failed: " .mysqli_connect_errno());
    } else {
        $db_select = mysqli_select_db($this->connection, DB_NAME);
        if(!$db_select) {
        die("Database selection failed: " .mysqli_error($this->connection));
    }
    }
}

public function close_connection() {
    if(isset($this->connection)) {
    mysqli_close($this->connection);
    unset($this->connection);
    }
}

public function query($sql) {

    $result = mysqli_query($this->connection, $sql);
    $this->confirm_query($result);
    return $result;
}

public function fetch_assoc($result_set) {
    return mysqli_fetch_assoc($result_set);
}

private function confirm_query($result) {
    if(!$result) {
        die("Database query failed: " . mysqli_error($this->connection));
    }
}

public function free_result($result) {
    if($result) {
        return mysqli_free_result($result);
    }
}

}

I think this class is start to make the code more readable, but I now face a new problem: all my query functions are in procedural style and I don't know which way to go.

Option 1: change all the function to OOP style

new_qfunction.php

function get_user_info() {
global $DB;
$sql = "SELECT  * FROM USERS";
$result = $DB->query($sql);
return $DB->fetch_assoc($result);
}

Option 2: change all the functions to class

Class User {
function get_user_info($user_id) {
    $DB = new MySQLDatabase();
    $sql = "SELECT  * FROM USERS";
    $result = $DB->query($sql);
    return $DB->fetch_assoc($result);
}
}

I don't feel like doing Option 1 for all the query function will make a big difference. For Option 2, I think it's better but far complex, especially when I just start coding in OOP.

Can you tell me what is the best approach to move an entire working procedural site to an OOP site, slowly and safety, and without making the code more complex than its now?

Can you recommend an approach to take? And if I go with Option 1, will it be worthwhile?


texts: UserScript that summarizes Stack Exchange flag counts

texts:
I am working on a UserScript that displays total flag counts and other information on the Flag Summary page.

Example:

Everything is working correctly but this bit of code seems rather repetitive and I'm sure it could be improved upon.

The following code pulls the total count of each flag type from the flag summary page.

Is there anything I can do to improve or shorten this code?

var helpful = 0,
    declined = 0,
    disputed = 0,
    aged = 0,
    total = 0;

$("td > a:contains('helpful')").parent().prev().each(function () {
    helpful += parseInt($(this).text().replace(",",""));
});

$("td > a:contains('declined')").parent().prev().each(function () {
    declined += parseInt($(this).text().replace(",",""));
});

$("td > a:contains('disputed')").parent().prev().each(function () {
    disputed += parseInt($(this).text().replace(",",""));
});

$("td > a:contains('aged')").parent().prev().each(function () {
    aged += parseInt($(this).text().replace(",",""));
});

$("td > a:contains('flags')").parent().prev().each(function () {
    total += parseInt($(this).text().replace(",",""));
});

Here is an example of what the markup looks like:

            441
            post flags

            41
            waiting for review

            310
            helpful

            5
            declined

            36
            disputed

            49
            aged away

            412
            comment flags

            6
            waiting for review

            406
            helpful

            5
            spam flags

            5
            helpful

            &nbsp;

            Clear all filters

            &nbsp;

            Filter your flag history by selecting a category above.

Note: I've only included the relevant part as I didn't want to add a bunch of noise to this post.


texts:
I have a website where people can write articles and publish/unpublish them. This is done via single button on the page:

<a id="publish-button" href="#" class="btn btn-default <%= 'btn-success' if @article.published? %>">

As you can see, if an article is already published I'm adding additional btn-success class.

Now, this is the JavaScript code that handles Ajax clicks on that button:

var $editor = $('#editor'); // Article container, it contains update action url as data-url
var $publishButton = $('#publish-button');
var togglePublished = function () {
  var url = $editor.data('url');

  var postData = {
    article: {
      stage: $publishButton.hasClass('btn-success') ? 'unpublished' : 'published'
    },

    _method: 'PUT'
  };

  $.ajax({
    url: url,
    data: postData,
    method: 'POST',
    success: function (article) {
      $publishButton['published' == article.stage ? 'addClass' : 'removeClass']('btn-success');
    }
  });
};
$publishButton.click(function (e) {
  e.preventDefault();
  togglePublished();
});

My controller action just returns a JSON encoded article in this case:

def update
  if @article.update(article_params)
    render json: @article
  else
    render json: { errors: @article.errors.full_messages }, status: :unprocessable_entity
  end
end

There are few things I see wrong with this:

My post data depends on class, which can be changed and changing it would require me to change it on two places: in template and in JS.
If I add data-published attribute to the button I would still have to add/remove class after Ajax has finished resulting in duplicated view logic (in HTML file and JS file).

I can see two ways to avoid this and be DRY:

Add conditional class only in JavaScript and run check upon page load

This would be fairly easy to do but would result in a brief delay because conditional class would be added in JavaScript which runs after all HTML has already loaded.

Extract button to partial view and return it from controller in Ajax

This seems like a more solid approach but since my update action is used in other places too it has to return article as JSON. That's why I would have to create another controller action:

def toggle_published
  @article.toggle_published # Something like this
  render partial: '_publish_button'
end

This reduces "restfulness" of my controller and it seems kind of silly to extract only one HTML element into a partial view.

Is there any better way to do this? It seems like a minor and insignificant code duplication but it's not an isolated example and as website complexity grows these things can multiply a lot and cause a lot of headaches.


texts: How to refactor this code to get a source from property files?

texts:
I want to get the source of these files, but I don't know if I'm efficient.

I get the source of the file, put the source in a list, so I put this in a hashmap with the key is the version of file and the values are the list.

private Map<String, List<String>> loadXmlNodes() {

    Map<String, List<String>> mapNodes = new HashMap<>();
    List<String> nodes = XmlUtil.loadNodes1_10();

    mapNodes.put("1.10", nodes);
    nodes = XmlUtil.loadNodes2_00();
    mapNodes.put("2.00", nodes);

    return mapNodes;
}

public static List<String> loadNodes1_10() {

    List<String> node = new ArrayList<>();

    try {

        InputStream inputStream = XmlUtil.class.getClassLoader().getResourceAsStream("nodes1.10.properties");
        Properties properties = new Properties();
        properties.load(inputStream);

        for (Object value : properties.keySet()) {
            node.add((String) value);
        }

    } catch (IOException e) {
        e.printStackTrace();
    }

    return node;
}

public static List<String> loadNodes2_00() {

    List<String> node = new ArrayList<>();

    try {

        InputStream inputStream = XmlUtil.class.getClassLoader().getResourceAsStream("nodes2.00.properties");
        Properties properties = new Properties();
        properties.load(inputStream);

        for (Object value : properties.keySet()) {
            node.add((String) value);
        }

    } catch (IOException e) {
        e.printStackTrace();
    }

    return node;
}


texts: Using the RAII design pattern in VBA to automatically restore settings

texts:
Using a technique described in this StackOverflow answer by @David Murdoch I created a custom class with methods to speed up Excel (Activate turns off screen updates and set the calculation mode to manual) and to restore it to normal settings (Shutdown).  When the object reaches the end of its life and Class_Terminate is triggered it runs the Shutdown procedure.

The purpose of all this is to avoid problems that occur if (when) I forget to reset these settings at the end of a script or if my code (contains a bug that) skips the section resetting these settings.

I am looking for a broad critique of the nit-picky variety.  In other words, how you would code this.

This code intentionally ignores the initial state of the settings and always turns on screen updating and sets the calculation mode to automatic when the object is destroyed.

The following is in a class module called ExcelTurboBooster.

Option Explicit
'
'  Use the code below to turn off screen updates and automatic
'   calculations.  Screen updates and automatic calculations will be
'   restored when the calling procedure terminates.
'
' EXAMPLE USAGE
' ======================================================================
'   Dim objExcelTurboBooster As New ExcelTurboBooster
'   objExcelTurboBooster.Activate   ' Activates booster
'   objExcelTurboBooster.Shutdown   ' Use to deactivate before procedure
'                                   '  terminates
' ======================================================================
'
'
Public Sub Activate()
    Application.Calculation = xlCalculationManual
    Application.ScreenUpdating = False
End Sub

Public Sub Shutdown()
    On Error Resume Next
    Application.Calculation = xlCalculationAutomatic
    Application.ScreenUpdating = True
End Sub

Private Sub Class_Terminate()
    Shutdown
End Sub


texts:
Inspired by Minimising the triangle

I am writing a fully tested program to solve the following problem:

  A triangle needs a good foundation. Every row in the triangle is derived from the sum of the two values below it. However, there can be
  no repeated values, if a value shows up more than once the triangle
  crumbles. Find the base which minimises the value in the top of the
  triangle satisfying the condition of no duplicates.

Example:

      20
    8   12
 [3]   5   7
1   2  [3]  4

Here 3 occurs twice, so the triangle is invalid.

My main concern is that my code has time complexity \$O(n!)\$ in the function stable_triangles, so it is not scalable at all.

"""
Finds `Reversed Tartaglia's (or Pascals') triangles` where there are
no repeated values.
"""

import doctest
from itertools import permutations

def next_level(level):
    """
    Builds the layer above of the triangle by
    summing the near pairs of numbers.

    >>> next_level([1, 4, 5])
    [5, 9]
    """
    return [curr + level[index + 1]
               for index, curr in enumerate(level[:-1])]

def make_triangle(base):
    """
    Builds a full triangle by `next_level` until the
    top has length 1.

    >>> make_triangle([1,2,3])
    [[1, 2, 3], [3, 5], [8]]
    """
    triangle = [base]
    while len(triangle[-1]) > 1:
        triangle.append(next_level(triangle[-1]))
    return triangle

def all_unique(lst):
    """
    Are the items all unique?

    >>> all_unique([4, 6, 7])
    True
    >>> all_unique([4, 4, 6, 7])
    False
    """
    return len(lst) == len(set(lst))

def flatten1(lst):
    """
    Flattens one level, shallow.

    >>> flatten1([ [1,2], [3,4] ])
    [1, 2, 3, 4]
    """
    return [i for sublst in lst for i in sublst]

def is_stable(triangle):
    """
    A triangle is stable if no number is repeated,
    that is: all the numbers are unique.

    >>> is_stable([[1,2,3], [3,5], [8]])
    False
    >>> is_stable([[1,2], [2]])
    False
    >>> is_stable([[1,3], [4]])
    True
    """
    return all_unique(flatten1(triangle))

def stable_triangles(base_length):
    """
    Yields many stable triangles with the given base length.

    >>> flattend_sum = lambda tri: sum(flatten1(tri))
    >>> min(stable_triangles(3), key=flattend_sum)
    [[2, 1, 4], [3, 5], [8]]
    >>> min(stable_triangles(4), key=flattend_sum)
    [[2, 3, 1, 6], [5, 4, 7], [9, 11], [20]]
    >>> min(stable_triangles(5), key=flattend_sum)
    [[6, 4, 1, 2, 7], [10, 5, 3, 9], [15, 8, 12], [23, 20], [43]]
    >>> next(stable_triangles(6))
    [[1, 2, 4, 7, 5, 8], [3, 6, 11, 12, 13], [9, 17, 23, 25], [26, 40, 48], [66, 88], [154]]

    # >>> next(stable_triangles(7)) # This takes about a minute. Comment out for faster testing.
    # [[1, 2, 4, 7, 5, 8, 10], [3, 6, 11, 12, 13, 18], [9, 17, 23, 25, 31], [26, 40, 48, 56], [66, 88, 104], [154, 192], [346]]
    """
    for base in permutations(range(base_length * 2), base_length):
        triangle = make_triangle(list(base))
        if is_stable(triangle):
            yield triangle

if __name__ == "__main__":
    doctest.testmod()
    for base_length in range(10):
        print(next(stable_triangles(base_length)))


texts: Addition plus division taking up all my CPU - Kinect depth denoising

texts:
I have a method in my class that eats up something like 80% of my processor time while its running. In-fact one line within the method is responsible for the majority of this.

The idea behind this class is to stabilize the depth readings being returned by the Microsoft Kinect device by obtaining the average value of the last 4 frames plus the current one.

This is a the basic layout of the method concerned.

public event EventHandler<DenoisedDepthReadyEventArgs> DenoisedDepthReady;

private const int HistoricFrameCount = 4;

private readonly KinectSensor _KinectSensor;
private List<DepthImagePixel[]> _LastFrames;
private FilteredDepthPixel[] _FilteredDepths;
private bool _ResolutionFilteredDepthsInitialized;

//This is invoked upto 30 times a second
private void KinectSensor_AllFramesReady(object sender, AllFramesReadyEventArgs e)
{
    using (DepthImageFrame depthFrame = e.OpenDepthImageFrame())
    {
        if (depthFrame != null)
        {
            DepthImagePixel[] currentPixels = new DepthImagePixel[depthFrame.PixelDataLength]; //Note this is huge array, usually 307200
            depthFrame.CopyDepthImagePixelDataTo(currentPixels);
            this._LastFrames.Add(currentPixels);
            this.ReduceNoiseAndInvokeIfRequired(currentPixels, depthFrame.PixelDataLength, depthFrame.MaxDepth, depthFrame.MinDepth);
        }
    }
}

private void ReduceNoiseAndInvokeIfRequired(DepthImagePixel[] currentPixels, int totalPixels, int maxDepth, int minDepth)
{
    if (this._LastFrames.Count == HistoricFrameCount)
    {
        if (!this._ResolutionFilteredDepthsInitialized)
        {
            this._FilteredDepths = new FilteredDepthPixel[totalPixels];
            for (int i = 0; i < totalPixels; i++)
            {
                this._FilteredDepths[i] = new FilteredDepthPixel();
            }

            this._ResolutionFilteredDepthsInitialized = true;
        }

        for (int i = 0; i < this._LastFrames.Count; i++)
        {
            DepthImagePixel[] currentFrame = this._LastFrames[i];
            for (int p = 0; p < totalPixels; p++)
            {
                this._FilteredDepths[p].Depth = (this._FilteredDepths[p].Depth + currentFrame[p].Depth) / 2;
            }
        }

        for (int i = 0; i < currentPixels.Length; i++)
        {
            this._FilteredDepths[i].Depth = (this._FilteredDepths[i].Depth + currentPixels[i].Depth) / 2;
            this._FilteredDepths[i].IsKnownDepth = currentPixels[i].IsKnownDepth;
            this._FilteredDepths[i].PlayerIndex = currentPixels[i].PlayerIndex;
        }

        this._LastFrames.RemoveAt(this._LastFrames.Count - 1);

        RaiseOnDenoisedDepthEvent(this._FilteredDepths, maxDepth, minDepth);
    }

}

and here is what the performance profiler says about what I'm doing.

I'm trying to avoid threading and parallelization for the time being. I am also conscious that building a new collection each frame is probably silly too but not sure how to improve this given the immutability of the type I want to return.

Any input or guidance on alternative approaches would be highly appreciated.


texts:
I implemented a PhoneBook utilizing a Trie data structure.

Could I ask you to evaluate it?

Did I apply Trie correctly for such case or is it better to store data somehow else?

I'm looking not only for working solution but also for an optimal one in terms of run-time and storage.

From my calculations, it takes NlogT to add() and get() where N is a number of chars and T is a number of children.

Am I right?

Here is the logic

public final class PhoneBook {

    private final Node name;

    private final Node surname;

    private final Comparator<Record> comparator;

    public PhoneBook() {
        this.name = new Node();
        this.surname = new Node();
        comparator = (r1, r2) -> {
            int result = r1.getName().compareTo(r2.getName());
            if (result == 0) {
                result = r1.getSurname().compareTo(r2.getSurname());
                if (result == 0) {
                    result = r1.getNumber().compareTo(r2.getNumber());
                }
            }
            return result;
        };
    }

    public void add(final Record record) {
        add(record.getName().toLowerCase(), record, name);
        add(record.getSurname().toLowerCase(), record, surname);
    }

    public SortedSet<Record> get(final String prefix) {
        final String lc = prefix.toLowerCase();
        final List<Record> recordsRetrievedByName = get(lc, name);
        final List<Record> recordsRetrievedBySurname = get(lc, surname);
        final SortedSet<Record> result = new TreeSet<>(comparator);
        result.addAll(recordsRetrievedByName);
        result.addAll(recordsRetrievedBySurname);
        return result;
    }

    private List<Record> get(final String prefix, final Node ancestor) {
        Node node = ancestor;
        for (final char c: prefix.toCharArray()) {
            final Node child = node.children.get(c);
            if (child == null) {
                return Collections.emptyList();
            }
            node = child;
        }
        return node.records;
    }

    private void add(final String str, final Record record, final Node ancestor) {
        Node node = ancestor;
        for (final char c: str.toCharArray()) {
            final Node child;
            if (node.children.containsKey(c)) {
                child = node.children.get(c);
            } else {
                child = new Node();
                node.children.put(c, child);
            }
            child.records.add(record);
            node = child;
        }
    }

    private static final class Node {

        private final Map<Character, Node> children = new TreeMap<>();

        private final List<Record> records = new ArrayList<>();

    }

}

And the Record immutable object

public final class Record {

    private final String name;

    private final String surname;

    private final String number;

    //constructor, getters, toString
}


texts:
Any suggestions/improvements for the following custom thread-pool code?

import threading
from Queue import Queue

class Worker(threading.Thread):
    def __init__(self, function, in_queue, out_queue):
        self.function = function
        self.in_queue, self.out_queue = in_queue, out_queue
        super(Worker, self).__init__()

    def run(self):
        while True:
            if self.in_queue.empty(): break
            data = in_queue.get()
            result = self.function(*data)
            self.out_queue.put(result)
            self.in_queue.task_done()

def process(data, function, num_workers=1):
    in_queue = Queue()
    for item in data:
        in_queue.put(item)

    out_queue = Queue(maxsize=in_queue.qsize())
    workers = [Worker(function, in_queue, out_queue) for i in xrange(num_workers)]

    for worker in workers:
        worker.start()

    in_queue.join()

    while not out_queue.empty():
        yield out_queue.get()


texts:
I am trying to create a Sender-Receiver Network. What do I mean under a Sender-Receiver Network. That means that there is some structure which consists of Nodes and connections between them which will be called Channels. Through this channels nodes can transfer some data. So one node can be a sender and another - a receiver. I would like to emphasize that there is no some restriction to be either a sender or a receiver for a node. Each of them (nodes) is able to send or receive data.

Node

Node is a unit that can be send/receive data to/from another node.

Channel

Channel is a unit that transfers data from one node to another. More precisely, a channel connects two nodes with some feature which in this case is a weight. Weight is just a number which says how strongly two nodes are connected i.e. what is the contribution of sent data from \$j\$th node in the received data of \$i\$th node. This could be expressed in the following equation:

$$d^{(i)}_{received} = \sum_{j=1}^{n}w_{ij}d^{(j)}_{sent}$$

My realization of SRN

I find the Observer Design Pattern pretty attractive so I used it:

//Connector.h
//This class is base for Channel class.
#ifndef CONNECTOR_H
#define CONNECTOR_H

class Connector
{
    public :
    virtual double ActivateChannel() = 0;
};
#endif

This is the implementation of the Node:

//Node.h
#ifndef NODE_H
#define NODE_H

#include <iostream>
#include <vector>

#include "Connector.h"

class Node
{
    protected :
        double initialData;
        std::vector<Connector*> senders;
        std::vector<Connector*> receivers;

    public :
        Node( double initialData=0 ) : initialData( initialData ) { };
        ~Node() { };

        void RegisterSender( Connector* sender );
        void RegisterReceiver( Connector* receiver );

        double ReceiveDataFromSenders();
};

void Node::RegisterSender( Connector* sender )
{
    senders.push_back( sender );
}

void Node::RegisterReceiver( Connector* receiver )
{
    receivers.push_back( receiver );
}

double Node::ReceiveDataFromSenders()
{
    double receivedData = 0.;
    for( auto &sender : senders )
    {
        receivedData += sender->ActivateChannel();
    }
    return receivedData + initialData;
}
#endif

This is the implementation of the Channel:

//Channel.h
#ifndef CHANNEL_H
#define CHANNEL_H

#include "Connector.h"
#include "Node.h"

class Node;

class Channel : public Connector
{
    protected :
        Node* sender;
        Node* receiver;
        double weight;

    public :
        Channel( Node* sender, Node* receiver, double weight );
        ~Channel() { };

        double ActivateChannel();
};

Channel::Channel( Node* sender, Node* receiver, double weight )
{
    this->sender   = sender;
    this->receiver = receiver;
    this->weight   = weight;

    //SENDER registrates this connection in its RECEIVER list
    //RECEIVER registrates this connection in its SENDER list
    (this->sender)->RegisterReceiver( this );
    (this->receiver)->RegisterSender( this );
}

double Channel::ActivateChannel()
{
    return sender->ReceiveDataFromSenders() * weight;
}
#endif

Here is how to use this:

//main.cpp
#include "Channel.h"
#include <iostream>

int main()
{
    Node n1(1), n2(1), n3, n4, n5;
    //create connections between nodes
    //Channel( sender, receiver, weight )
    Channel d1( &n1, &n3, 1);
    Channel d2( &n1, &n4, 1);
    Channel d3( &n2, &n3, 1);
    Channel d4( &n2, &n4, 1);
    Channel d5( &n3, &n5, 2);
    Channel d6( &n4, &n5, 2);

    std::cout << n5.ReceiveDataFromSenders() << std::endl;

    return 0;
}

Output is:

8


texts:
The task
was taken from leetcode

  Every email consists of a local name and a domain name, separated by
  the @ sign.

  For example, in alice@leetcode.com, alice is the local name, and
  leetcode.com is the domain name.

  Besides lowercase letters, these emails may contain '.'s or '+'s.

  If you add periods ('.') between some characters in the local name
  part of an email address, mail sent there will be forwarded to the
  same address without dots in the local name.  For example,
  "alice.z@leetcode.com" and "alicez@leetcode.com" forward to the same
  email address.  (Note that this rule does not apply for domain names.)

  If you add a plus ('+') in the local name, everything after the first
  plus sign will be ignored. This allows certain emails to be filtered,
  for example m.y+name@email.com will be forwarded to my@email.com.
  (Again, this rule does not apply for domain names.)

  It is possible to use both of these rules at the same time.

  Given a list of emails, we send one email to each address in the list.
  How many different addresses actually receive mails?

  Example 1:

  Input:
  ["test.email+alex@leetcode.com","test.e.mail+bob.cathy@leetcode.com","testemail+david@lee.tcode.com"]

  Output: 2

  Explanation: "testemail@leetcode.com" and "testemail@lee.tcode.com"
  actually receive mails

  Note:

  1 <= emails[i].length <= 100

  1 <= emails.length <= 100

  Each emails[i] contains exactly one '@' character.

  All local and domain names are non-empty.

  Local names do not start with a '+' character.

My declarative solution

/**
 * @param {string[]} emails
 * @return {number}
 */
var numUniqueEmails = emails => {
    return emails.reduce((validMails, mail) => {
      const names = mail.split('@');
      let [local, domain] = names;
      const iPlus = [...local].findIndex(x => x === '+');
      if (iPlus !== -1) { local = local.substr(0, iPlus); }
      const key = local.split('.').join('') + '@' + domain;
      if (!validMails.has(key)) { validMails.add(key); }
      return validMails
    }, new Set).size;
};

My Imperative solution

/**
 * @param {string[]} emails
 * @return {number}
 */
var numUniqueEmails2 = emails => {
  const validMails = new Set();
  for (const mail of emails) {
    let [local, domain] = mail.split('@');
    const iPlus = [...local].findIndex(x => x === '+');
    if (iPlus !== -1) { local = local.substr(0, iPlus); }
    const key = [...local].filter(x => x !== '.').join() + '@' + domain;
    if (!validMails.has(key)) { validMails.add(key); }
  }
  return validMails.size;
};

My solution with regex

/**
 * @param {string[]} emails
 * @return {number}
 */
var numUniqueEmails3 = emails => {
  const validMails = new Set();
  for (const mail of emails) {
    let [local, domain] = mail.split('@');
    local = local.replace(/\+(.*)$/, '')
      .replace(/\./g, '');
    console.log(local);
    const key = `${local}@${domain}`;
    if (!validMails.has(key)) { validMails.add(key); }
  }
  return validMails.size;
};

Addendum

in numUniqueEmails ran the code with this snippet:

  const names = mail.split('@');
  let [local, domain] = names;

and got 90th percentile. Running it again with this snippet:

  let [local, domain] = mail.split('@');

gives me 25th percentile. I'd assume it should be the opposite. Does anyone know why this is the case and also how come the difference is so big?


texts: Python program to know who wins a tic-tac-toe game

texts:
Given an input where we have two players: "X" and "O", and empty cells marked with a "." like:

check_winner([
        "X.O",
        "XX.",
        "XOO"])

the program outputs if there are three "X" or "O" in horizontal, vertical or diagonal. If there is a draw it outputs "D".

def check_winner(game_result: List[str]) -> str:

    for i, row in enumerate(game_result):
        if game_result[i][0] == game_result[i][1] == game_result[i][2]:
            if game_result[i][0] != ".":
                return game_result[i][0]
        if game_result[0][i] == game_result[1][i] == game_result[2][i]:
            if game_result[0][i] != ".":
                return game_result[0][i]

    if game_result[0][0] == game_result[1][1] == game_result[2][2]:
        if game_result[1][1] != ".":
            return game_result[1][1]

    if game_result[0][2] == game_result[1][1] == game_result[2][0]:
        if game_result[1][1] != ".":
            return game_result[1][1]

    return "D"

How could we improve this code?


texts:
I need to read HTML files and ignore the input until reaching the following tag     <a class="member-modal" then print the characters between that and the closing
 tag.

Below is the extracted line of the file of interest.

Phil Jankins

Below is my approach

#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
#include <cstdlib>
using namespace std;
int main()
{
string temp;
string delimet = "member - modal";

ifstream file;
file.open("in.txt");

getline(file, temp);
cout << temp;
while (!file.eof())
{
    if (temp.find(delimet))
        cout << temp;
    getline(file, temp);
}
file.close();

}


texts: Stateless Maximum Beauty of String implementation

texts:
Inspired by The Beauty and the Strings question, I tried to implement the "Maximum Beauty of String" in a stateless fashion using ES6. Unfortunately, I ran into two places where I had to assign variables.

The questions I have:

How can I remove the state in the reducer for mapLettersByCount?
How can one use generators without assigning it to a variable? (see points variable in the maxBeauty function) Is this even considered state in this situation?

Code:

const EMPTY_STRING = '';
const LETTERS_ONLY = /[a-z]/i;

function mapLettersByCount(sentence) {
  return sentence.split(EMPTY_STRING)
    .filter(letter => LETTERS_ONLY.test(letter))
    .map(letter => [letter.toUpperCase(), 1])
    .reduce((letterCount, [key, count]) => {
      letterCount[key] = (letterCount[key] || 0) + count;
      return letterCount;
    }, {});
}

function * downCounter(maxValue) {
  yield maxValue;
  yield * downCounter(maxValue > 0 ? maxValue - 1 : 0);
}

export function maxBeauty(sentence = "") {
  const points = downCounter(26);
  return Object.values(mapLettersByCount(sentence))
    .sort().reverse()
    .reduce((score, count) => score + count * points.next().value, 0);
}

Test Cases:

import {maxBeauty} from './beauty';

describe('The maximum beauty', () => {
  it('should calculate for a word', () => {
    expect(maxBeauty('AbBCcC')).toBe(152);
  });

  it('should calculate ignoring spaces', () => {
    expect(maxBeauty('This is from Facebook Hacker Cup 2013.'))
      .toBe(551);
  });

  it('should calculate ignoring punctuation', () => {
    expect(maxBeauty('Ignore punctuation, please :)'))
      .toBe(491);
  });
});


texts:
I have an asp.net web application and I want to export to a PDF tables in a particular way.

Tables will have data of type Test. tests have a type(by type i mean an int to tell them apart) and for every type i'm creating a TestTable and for every Test a column in each TestTable , there are 9 types. That's why there are 9 TestTables but in tests there might be for example only two different types.

Is there a better way to do this without creating two arrays that their might be useless

public IEnumerable<TestTable> TestHistoryItems(GetTestExportRequest request)
{

    IEnumerable<Test> tests = repository.FindBy(t => t.Visit.pid == request.PetId &&
                                                                t.Visit.dateofvisit >= request.Start && t.Visit.dateofvisit <= request.End).OrderByDescending(t => t.stamp);

    TestTable[] testTables = new TestTable[9] // all the TestTables are 9 but it might need less depending on tests
    {                                         //every TestTable needs tests, of type IEnumerable<Test>.
        new TestTable(),
        new TestTable(),
        new TestTable(),
        new TestTable(),
        new TestTable(),
        new TestTable(),
        new TestTable(),
        new TestTable(),
        new TestTable()
    };

    List<Test>[] testTypes = new List<Test>[9]
    {
        new List<Test>(),
        new List<Test>(),
        new List<Test>(),
        new List<Test>(),
        new List<Test>(),
        new List<Test>(),
        new List<Test>(),
        new List<Test>(),
        new List<Test>()
    };

    foreach (Test test in tests)
    {
        switch (test.type)
        {
            case 3: GetTable(test, ref testTables[0], 3); testTypes[0].Add(test); break;
            case 4: GetTable(test, ref testTables[1], 4); testTypes[1].Add(test); break;
            case 5: GetTable(test, ref testTables[2], 5); testTypes[2].Add(test); break;
            case 6: GetTable(test, ref testTables[3], 6); testTypes[3].Add(test); break;
            case 7: GetTable(test, ref testTables[4], 7); testTypes[4].Add(test); break;
            case 8: GetTable(test, ref testTables[5], 8); testTypes[5].Add(test); break;
            case 9: GetTable(test, ref testTables[6], 9); testTypes[6].Add(test); break;
            case 10: GetTable(test, ref testTables[7], 10); testTypes[7].Add(test); break;
            case 16: GetTable(test, ref testTables[8], 16); testTypes[8].Add(test); break;
         }
    }
    int i = 0;
    foreach (TestTable test in testTables)
    {
        testTables[i].Tests = testTypes[i]; //add tests in testTables
        i++;
    }

    return testTables;
}

public void GetTable(Test test, ref TestTable table, int index)
{
    if (table.Type != index)
    {
        table.TestName = test.TestTypeName; //One Time for every TestTable
        table.Type = index; //One Time for every TestTable
        table.Rows = test.TestDatas.Count(); //One Time for every TestTable; Rows of the table
    }
    table.Columns++; // columns are the number of tests in every TestTable
}

Here is the Class TestTable.

public class TestTable
{
    public string TestName { get; set; }
    public int Type { get; set; }
    public IEnumerable<Test> Tests { get; set; }
    public int Rows { get; set; }
    public int Columns { get; set; }
}

The program works as expected but I think this is wrong. Can't think of a better way to do this, I'm new to coding.

How can I make this code better?


texts: Algorithm for computing LCM (least common multiple)

texts:
I'm trying to implement this algorithm for computing LCM (from the cut-the-knot website). This is my Java code:

public class LcmAlgorithm {

public static void main(String[] args) {
    long[] input = { 28, 50, 14 };
    System.out.println(lcm(input));
}

private static long lcm(long[] inputs) {
    long[] compute = inputs.clone();
    while (!allEqual(compute)) {
        int minIx = minValueIndex(compute);
        compute[minIx] += inputs[minIx];
    }
    return compute[0];
}

private static boolean allEqual(long[] arr) {
    for (int i = 0; i < arr.length - 1; i++) {
        if (arr[i] != arr[i + 1])
            return false;
    }
    return true;
}

private static int minValueIndex(long[] arr) {
    long min = java.lang.Long.MAX_VALUE;
    int ix = 0;

    for (int i = 0; i < arr.length; i++) {
        if (arr[i] < min) {
            min = arr[i];
            ix = i;
        }
    }
    return ix;
}
}

It works, but I'm pretty new to Java and I'm not sure my code is optimal (or maybe it's embarrassing...?). I'd like to hear what do you think of my code and how I can improve it. (BTW, I have a background in .NET programming.)

Thanks.


texts:
I'm making a scripting language parser and it's shaping up well but it takes about 30ms to do 30 or so odd/even checks.

Profiler tells me that it's taking most of the time in the InvokeOperator.Operate function but that doesn't tell me a lot because the Operate call the Run method on the CodeBlock which in turn again calls the Operate call and makes it very hard to actually determine what's taking as long.

Here's the Github repo

Here are the most important bits of the code:

Stack<Token> solvingStack = new Stack<Token>();
for ( int i = 0 ; i < value.Count ; ++i )
{
   if ( value[ i ] is Operator )
   {
      Operator op = (Operator)value[ i ];
      if ( op.Type == OperatorType.PrefixUnary || op.Type == OperatorType.SufixUnary )
      {
         op.Operate( ( solvingStack.Pop() as Value ), new NoValue() );
      } else
      {
         Value second = (Value)solvingStack.Pop();
         Value result = op.Operate( ( solvingStack.Pop() as Value ), second );
         solvingStack.Push( result );
      }
   } else
   {
      solvingStack.Push( value[ i ] );
   }
}
Compiler.ExitScope();
if ( solvingStack.Count == 0 ) return new NoValue();
else return (Value)solvingStack.Peek();

It's how the code is parsed after the infix expression is turned into RPN.
A token can be an operator or a value and a value can be a literal, identifier, codeblock.

A somewhat special case is a function because it's not parsed to RPN directly but only the code inside of it is. Then is there's an invoke operator, it takes the array of arguments that was provided and the function before it and runs the function (which inherits from CodeBlock, so it also runs the same thing that is shown here).

What each operator does on different types of values is determined by the operator itself in the Operators.cs file.


texts: Does this unit test cover all edge cases?

texts:
I want to test a simple controller and I want to know if this unit test covers all cases:

Controller:

@RequestMapping(method = RequestMethod.GET)
public List<Tags> getAllTags(@RequestParam(value = "query", required = false) String query,
        @RequestParam(value = "limit", required = false) Integer limit,
        @RequestParam(value = "start", required = false) Integer start,
        @RequestParam(value = "approved", required = false) Boolean approved,
        @ActiveLanguage Language language,
        @ActiveUser User user) {
    if (limit == null) {
        limit = 10;
    }
    if (start == null) {
        start = 0;
    }
    if (approved == null) {
        approved = true;
    }
    if (query != null) {
        return tagService.findTagsByQuery(user, query, limit, start, language, approved);
    } else {
        return tagService.findTags(user, limit, start, language);
    }
}

Test:

@Test
public void testGetAllTags_query_notnull() throws Exception {
    List<Tags> tagsList = createTagList();

    //Individual parameters
    String query = "test";
    Boolean approved = true;

    Mockito.when(this.tagServiceMock.findTagsByQuery(user, query, limit, start, language, approved)).thenReturn(tagsList);

    List<Tags> t = tagController.getAllTags(query, limit, start, approved, language, user);

    assertSame(tagsList, t);
    assertNotNull(t);
    assertNotNull(tagsList);

    verify(tagServiceMock, times(1)).findTagsByQuery(user, query, limit, start, language, approved);
    verifyNoMoreInteractions(tagServiceMock);

}

@Test
public void testGetAllTags_query_null() throws Exception {
    List<Tags> tagsList = createTagList();

    //Individiual Parameters
    String query = null;
    Boolean approved = true;

    Mockito.when(this.tagServiceMock.findTags(user, limit, start, language)).thenReturn(tagsList);

    List<Tags> t = tagController.getAllTags(query, limit, start, approved, language, user);
    assertEquals(tagsList, t);
    assertNotNull(t);
    assertNotNull(tagsList);

    verify(tagServiceMock, times(1)).findTags(user, limit, start, language);
    verifyNoMoreInteractions(tagServiceMock);

}

Is there anything left that is not covered by this unit test?


texts:
I have a button dropdown that you can select different currencies from. When you select one, it replaces the button value with that currency type, and displays the currency symbol in a span in front of an input.

I have done some refactoring where I now have just one function getCurrency() that accepts parameters and inserts the proper values, but in here $(".dropdown-menu li").click( function(){...} I have 3 different if else statements. I know there has to be a way to do this by looping through my currencyData array and use this to target a specific element, but I cannot figure it out.

I want to make this more modular so it can scale up. If I had 30 different currencies, this would not work. I would have to change too many lines of code, where I should just be able to add another currency to the array.

It is live, you can view it here.

JS

var currencyData = [
  {
    "currency": "USD",
    "symbol" : "$"
  },
  {
    "currency": "EUR",
    "symbol" : "€"
  },
  {
    "currency": "JPY",
    "symbol" : "¥"
  }
];

/*
 * Inserts
 list of values into the currency dropdown
*/
$.each( currencyData, function( key, val ) {

  var $li = $("
" +
    val.currency + "
");

  $(".dropdown-menu").append( $li );
 });

/*
 * Generate currency symbol and type and swap them depending on which is clicked
*/
$(".dropdown-menu li").click( function() {

 if ( this.textContent === currencyData[0].currency ) {
    getCurrency(currencyData[0].currency, currencyData[0].symbol);

 } else if ( this.textContent === currencyData[1].currency ) {
    getCurrency(currencyData[1].currency, currencyData[1].symbol);

 } else if ( this.textContent === currencyData[2].currency ) {
    getCurrency(currencyData[2].currency, currencyData[2].symbol);
 };
});

/*
 * Swap currency type and symbol
*/
function getCurrency(currency, symbol) {
  // inserts visible currency symbol to form
  var $span = $(" " + symbol + "");

  // hidden input to save currency symbol
  var $input = $("<input type='text' class='js-hidden-currency-symbol' value=" +
   symbol + " style='display:none' name='currencySymbol'>");

  $('.js-currency-symbol').remove();
  $('.js-currency-btn').text( currency );
  $('.js-input-amount-prepend').append( $span );

  $('.js-hidden-currency-symbol').remove();
  $('.js-currency-btn-group').append( $input );
};

HTML

      Amount:

      <input type="text" required class="js-payment-amount-input payment-amount-input" name="amount" placeholder="enter amount">

        <button type="button" class="btn js-currency-btn currency-btn">Currency</button>
        <button type="button" class="btn dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">

          Toggle Dropdown
        </button>


texts: Which option is better for readability when dealing with blank strings?

texts:
I'm working off a specification that says a bunch of fields within a record (one record being one line) must be blank. For example, it says that chars 6-14 must be blank. I am building a class hierarchy structure that represents the layout of the file, and within this class hierarchy I'm including every field for each type of record, including the blank ones.

Basically I want to know if I should make each field return a blank literal, or if I should pad string.Empty with spaces.

Example:

public string ImmediateDestinationRoutingNumber { get { return "        "; } }

Versus

public string ImmediateDestinationRoutingNumber { get { return string.Empty.PadRight(8, ' '); } }

The second option of padding string.Empty looks the most readable to me, but I don't know if the runtime cost is significant enough to worry about.


texts:
Exercise:

  Using a read7() method that returns 7 characters from a file,
  implement readN(n) which reads n characters.

  For example, given a file with the content "Hello world", three
  read7() returns "Hello w", "orld" and then "".

I made a version using std::deque. It seems inefficient to me with all the loops to read/write a string, but I couldn't think of an alternative for this FIFO. Any comments on that part would be especially appreciated.

#include <iostream>
#include <sstream>
#include <deque>

inline auto read7()
{
  static std::istringstream is("1234567890123456789012345678901234567890");
  char res[8]{};
  is.get(res, 8);
  return std::string(res);
}

template <typename T1, typename T2>
auto& operator<<(std::deque<T1>& deq, const T2& seq)
{
  for (const auto& elm : seq)
  {
    deq.push_back(elm);
  }
  return deq;
}

template <typename T1, typename T2>
auto get(std::deque<T2>& deq, std::size_t n)
{
  T1 res;
  while (res.size() != n && !deq.empty())
  {
    res += deq.front();
    deq.pop_front();
  }
  return res;
}

auto readN(std::size_t n)
{
  static std::deque<char> buffer;
  while (n > buffer.size())
  {
    auto old_sz = buffer.size();
    buffer << read7();
    if (old_sz == buffer.size())
      break;
  }

  return get<std::string>(buffer, n);
}

int main()
{
  std::size_t sz;
  while(std::cin >> sz)
    std::cout << readN(sz) << '\n';

  return 0;
}


texts:
If I create a brush like so

HBRUSH hBrush = CreateSolidBrush(RGB(33, 33, 33));

and then later on, I want to change the color of the brush, how would I do this?
I googled a bit and found out that creating a bunch of different brushes is not the way to go.

I was thinking that one possibility would be to just set hBrush to a new brush like so

hBrush = CreateSolidBrush(RGB(0, 0, 0));

everytime I wanted to use a different color, but this seems suspiciously easy, and I'm pretty sure that this would hog resources or something.

Another - presumably bad - idea of mine, was to use the above method, but always use

DeleteObject(hBrush);

immediately after drawing. I have no idea if this is the right way to do things or not. Any help would be greatly appreciated.


texts:
I am coding a Hanning filter which is a recursive relation:

y[i] = 0.25*(x[i] + 2*x[i-1] + x[i-2])

And here is my code were I attempt to unroll 3 times:

public void HanningFilter(float[] array) {
        int len = array.length;
        int i;
        for (i = 2; i < len-3; i+=3) {
            array[i] = 0.25f*(array[i] + 2*array[i-1] + array[i-2]);
            array[i+1] = 0.25f*(array[i+1] + 2*array[i] + array[i-1]);
            array[i+2] = 0.25f*(array[i+2] + 2*array[i+1] + array[i]);
        }
        //Clean-up at the end
        for (int j = i; j < len; j++) {
            array[i] = 0.25f*(array[i] + 2*array[i-1] + array[i-2]);
        }
    }

Would this help at all with an OoO superscalar processor? Is 3 the right amount of times to unroll? Thanks


texts:
I spent an hour or so this morning compiling this, and since I have started reading Clean Code and The Pragmatic Programmer I figured I would let you help me get slightly better at this.

Due to some crappy limitations with the specifics I was forced to work in Excel VBA instead of Access (someone doesn't want to build tables for the two lists in the Excel sheet).

The code pulls a list of defects from a production table, checks a master list to see if it ever existed, then checks an open list to see if it's current and updates the table accordingly. This could be super easy and potentially 100% automated if they would make tables for the two lists. The log of what was found per defect# (writing to sheet) is something I added just in case they want a log.

Private Sub thisbetheshitmane()
    Dim db As DAO.Database
    Dim rst As DAO.Recordset
    Dim vAr As String
    Dim i As Integer
    Dim y As Integer
    Dim InCombined As Boolean
    Dim InOpen As Boolean

    Set db = DBEngine.OpenDatabase("C:\Users\dzcoats\Documents\Microsoft.accdb")
    Set rst = db.OpenRecordset("SELECT DISTINCT [VDefects].Defect FROM [VDefects] WHERE [VDefects].Defect IS NOT NULL;")

    Dim QResult() As Variant
    QResult = rst.GetRows(rst.RecordCount)
    For a = LBound(QResult, 2) To UBound(QResult, 2)
        vAr = QResult(0, a)
        Debug.Print ; vAr
    Next a

    Dim CombinedList() As Variant
    CombinedList = Application.Transpose(Worksheets(1).Range("b2:b2000").Value)
    Dim OpenList() As Variant
    OpenList = Application.Transpose(Worksheets(1).Range("a2:a2000").Value)

    For y = LBound(QResult, 2) To UBound(QResult, 2)
        vAr = Trim(QResult(0, y))
        InCombined = False

        For a = LBound(CombinedList) To UBound(CombinedList)
            If vAr = CombinedList(a) Then InCombined = True
        Next a

        InOpen = False

        For a = LBound(OpenList) To UBound(OpenList)
            If vAr = OpenList(a) Then InOpen = True
        Next a

        If vAr <> "Defect" And vAr <> vbNullString And vAr <> "" Then

            If InCombined = False And InOpen = False Then
                set rst = db.OpenRecordSet ("UPDATE [VDefects] SET [VDefects].Status ='Bad Defect Number' WHERE ((([VDefect].Defect)='"& vAr &"'));")
                Debug.Print "BAD "; vAr
                ThisWorkbook.Sheets("Sheet2").Cells(Sheet2.Rows.Count, 1).End(xlUp).Offset(1, 0).Value = "Bad"
                ThisWorkbook.Sheets("Sheet2").Cells(Sheet2.Rows.Count, 1).End(xlUp).Offset(0, 1).Value = vAr
            End If

            If InCombined = True And InOpen = False Then
                set rst = db.OpenRecordSet ("UPDATE [VDefects] SET [VDefects].Status ='Completed' WHERE ((([VDefects].Defect)='"& vAr &"'));")
                Debug.Print "CLOSED "; vAr
                ThisWorkbook.Sheets("Sheet2").Cells(Sheet2.Rows.Count, 1).End(xlUp).Offset(1, 0).Value = "Closed"
                ThisWorkbook.Sheets("Sheet2").Cells(Sheet2.Rows.Count, 1).End(xlUp).Offset(0, 1).Value = vAr
            End If

            If InCombined = True And InOpen = True Then
                Debug.Print "OPEN "; vAr
                ThisWorkbook.Sheets("Sheet2").Cells(Sheet2.Rows.Count, 1).End(xlUp).Offset(1, 0).Value = "Open"
                ThisWorkbook.Sheets("Sheet2").Cells(Sheet2.Rows.Count, 1).End(xlUp).Offset(0, 1).Value = vAr
            End If
        End If
    Next y

    rst.Close
    Set rs = Nothing
    db.Close
    Set db = Nothing

End Sub


texts:
This is a question in Udacity JS course. I am starting to like Javascript. I feel its a misunderstood language :)

  We learned about relational operators and how they can classify the
  relationship between two values.  Your job is to write the function
  getRelationship(x,y) function, which should return a string
  representing whether x is >, < or = y. For example:

var rel = getRelationship(2, 3);
console.log(rel); // <

  If one or both of the values aren't numbers, your function should
  output:

    "Can't compare relationships because [this value] and [that value] [is]/[are] not [a] number[s]."

  where [this value] and [that value] are replaced with the
  non-numerical values. The sentence should be grammatically correct by
  outputting either is or are and pluralizing number if necessary.

  For example:

var rel1 = getRelationship("this", 2);
console.log(rel1); // "Can't compare relationships because this is not a number"

var rel2 = getRelationship("that");
console.log(rel2) // "Can't compare relationships because that and undefined are not numbers"

  Notice in the second example, because the y value was missing, the
  output said that undefined was not a number.

Here is my stab at the solution.

function getRelationship(x, y) {
    var respObj = validateArgAsNumber(x,y);
    if (respObj.x && respObj.y && !respObj.isXNaN && !respObj.isYNaN) {
        console.log("Both are numbers");
        if (x > y) {
            return ">";
        } else if (x < y) {
            return "<";
        } else {
            return "=";
        }
    } else {
        console.log("Both are NOT numbers");
        //console.log(respObj);
        if ((!respObj.x && !respObj.y) || (respObj.isXNaN && respObj.isYNaN)){
            return "Can't compare relationships because " + x + " and " + y + " are not numbers";
        }
        if (!respObj.x || respObj.isXNaN) {
            return "Can't compare relationships because " + x + " is not a number";
        }
        if (!respObj.y || respObj.isYNaN) {
            return "Can't compare relationships because " + y + " is not a number";
        }
    }
}

function validateArgAsNumber(a,b) {
    var response = {};
    response.isXNaN = isNaN(a);
    response.isYNaN = isNaN(b);
    response.x = typeof(a) == 'number';
    response.y = typeof(b) == 'number';
    return response;
}

console.log(getRelationship(1,4));
console.log(getRelationship(1,1));
console.log(getRelationship("that",2));
console.log(getRelationship("this"," something else"));
console.log(getRelationship(3));
console.log(getRelationship("hi"));
console.log(getRelationship(NaN, NaN));
console.log(getRelationship(NaN));
console.log(getRelationship(NaN, undefined));


texts:
I'm developing some API tests to a SOAP services. The class that performs the call to API is:

class GetUserData(object):

    status_code = ""

    firstname = ""
    lastname = ""
    customer_id = ""

    def do_request(self, user_id):
        form = """
            <soapenv:Envelope>
               <soapenv:Header/>
               <soapenv:Body>
                  ...
                    <soapenv:Body>
                </soapenv:Envelope>
        """ % (user_id)

        encoded_request = form.encode('utf-8')
        requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
        response = requests.post(url=config.url, data=encoded_request, verify=False)

        # Parse response
        self.status_code = response.status_code
        dict = xmltodict.parse(response.text)
        item = dict['soap:Envelope']['soap:Body']['ns1:user']['return']
        self.firstname = item['firstname']
        self.lastname = item['lastname']
        self.customer_id = item['customer_id']

and using this class, the assertions are like:

def assert_results(context, firstname, lastname):
  get_user_data = GetUserData()
  get_user_data.do_request(user_id)

  assert_that(get_user_data.firstname, equal_to(firstname))
  assert_that(get_user_data.lastname, equal_to(lastname))

I'm wondering if instead of saving the result of the request in internal properties, I should do a static method and return an object that contains these values (something like UserDataResponse). Any idea?


texts:
I wrote this class to ensure that anything done in any of my worker threads can be displayed on the GUI via events, but I ran into non-thread-safe problems.

This class should take an action or a function with one or no params, i.e. the event delegate.

Is this code actually thread-safe, and, how could it be improved upon (simplifying the 4 bodies into two or one)?

The class is defined as:

private class ThreadSafeCall
{

    public void Call(Action action)
    {
        try
        {
            ISynchronizeInvoke invokable = action.Target as ISynchronizeInvoke;
            if (invokable != null && invokable.InvokeRequired == true)
            {
                invokable.Invoke(action, null);
            }
            else
            {
                action();
            }
        }
        catch (Exception)
        {

        }
    }

    public void Call(Action<object> action, object param)
    {
        try
        {
            ISynchronizeInvoke invokable = action.Target as ISynchronizeInvoke;
            if (invokable != null && invokable.InvokeRequired == true)
            {
                invokable.Invoke(action, new object[] { param });
            }
            else
            {
                action(param);
            }
        }
        catch (Exception)
        {

        }
    }

    public object Call(Func<object> action)
    {
        try
        {
            ISynchronizeInvoke invokable = action.Target as ISynchronizeInvoke;
            if (invokable != null && invokable.InvokeRequired == true)
            {
                return invokable.Invoke(action, null);
            }
            else
            {
                return action();
            }
        }
        catch (Exception)
        {

        }

        return null;
    }

    public object Call(Func<object, object> action, object param)
    {
        try
        {
            ISynchronizeInvoke invokable = action.Target as ISynchronizeInvoke;
            if (invokable != null && invokable.InvokeRequired == true)
            {
                return invokable.Invoke(action, new object[] { param });
            }
            else
            {
                return action(param);
            }
        }
        catch (Exception)
        {

        }

        return null;
    }
}

It is used:

(new ThreadSafeCall()).Call(() => { onCompleteHandle(); });


texts: Using a map of shared_ptr instead of single pointers as class members

texts:
I'm working on a node.js bindings for libcurl. As libcurl accepts many callback functions as options (like CURLOPT_READFUNCTION for example), I had to store their respective javascript callbacks somewhere when those options were set.

Initially I had the following class members (Easy.h:71):

Nan::Callback *cbChunkBgn;
Nan::Callback *cbChunkEnd;
Nan::Callback *cbDebug;
Nan::Callback *cbHeader;
Nan::Callback *cbFnMatch;
Nan::Callback *cbOnSocketEvent;
Nan::Callback *cbProgress;
Nan::Callback *cbRead;
Nan::Callback *cbXferinfo;
Nan::Callback *cbWrite;

Initialization also was too much code (Easy.cc:58):

Easy::Easy() :
    cbChunkBgn( nullptr ), cbChunkEnd( nullptr ), cbDebug( nullptr ), cbHeader( nullptr ),
    cbFnMatch( nullptr ), cbOnSocketEvent( nullptr ), cbProgress( nullptr ), cbRead( nullptr ),
    cbXferinfo( nullptr ), cbWrite( nullptr ),
    pollHandle( nullptr ),
    isCbProgressAlreadyAborted( false ), isMonitoringSockets( false ),
    readDataFileDescriptor( -1 ), id( Easy::counter++ ), isInsideMultiHandle( false ), isOpen( true )

Also, since one easy handle can be duplicated, I had a copy constructor which took care of copying the other handle data to itself, this included the callbacks. Most of them looks like that (Easy.cc:120):

if ( orig->cbHeader != nullptr ) {
    this->cbHeader = new Nan::Callback( orig->cbHeader->GetFunction() );
}

Trying to improve this code, I thought on using a map (typedef std::map<CURLoption, std::shared_ptr<Nan::Callback>> CallbacksMap;) which would store all the callbacks being used (new_Easy.h:72).

Copying the callbacks from another handle (in the copy constructor) would look like the following (new_Easy.cc:90):

this->callbacks.insert( orig->callbacks.begin(), orig->callbacks.end() );

Setting/removing a new callback, would looks like the following (new_Easy.cc:1134):

obj->callbacks.erase( CURLOPT_CHUNK_BGN_FUNCTION );
// ...
obj->callbacks[CURLOPT_CHUNK_BGN_FUNCTION].reset( new Nan::Callback( callback ) );

Where obj is an instance of the Easy class.

Retrieving one callback so it can be called (new_Easy.cc:509):

CallbacksMap::iterator it = obj->callbacks.find( CURLOPT_CHUNK_BGN_FUNCTION );
// ...
it->second->Call( ... );

And I would remove all those delete's from the destructor.

Thoughts? Would that be an improvement or just some unnecessary modification? Any better alternatives?

Also I would love any other suggestions for other parts of the code that you feel that are wrong or that can be improved.


texts: Bot that selects web reviews based on spreadsheet entries

texts:
In my program, I prompt the user to enter a range of cities (in a spreadsheet), and then a range of review scores, and then make some decisions based on what the user has entered. Since the handling of the both user inputs (both ranges) is common to each, I have combined both into the single function getRanges() below. It works well, but I get the sense that can be improved (shortened, and with fewer if/else's). In the absence of a switch statement in Python, what are some neater approaches here?

# -*- coding: utf-8 -*-
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import NoAlertPresentException
from selenium.common.exceptions import ElementNotVisibleException
from selenium.common.exceptions import WebDriverException
import unittest, time, re
from functions import *
from collections import OrderedDict
import csv
from openpyxl import load_workbook
from easygui import enterbox, msgbox
import traceback

class bot(unittest.TestCase):
    def setUp(self):
        self.wb = load_workbook("Spreadsheet.xlsx", data_only=True)
        self.cities = []
        self.getRanges('cities')
        self.getRanges('reviews')
        print 'Running...'

        try:
            self.driver = webdriver.Firefox()
        except WebDriverException, e:
            print "Unable to load profile, retrying"
            try:
                self.driver = webdriver.Firefox()
            except WebDriverException, e:
                print "Unable to load profile, retrying"
                self.driver = webdriver.Firefox()
        self.driver.implicitly_wait(30)
        self.base_url = "https://www.google.com/ncr"
        self.verificationErrors = []
        self.accept_next_alert = True
        self.reviewPattern = re.compile(ur'\d+')
        self.niche = "plumbers+"

    def getRanges(self, citiesOrReviews):
        self.LowerLimit = enterbox("Enter a lower limit for %s, or 'all'" % citiesOrReviews, 'Range')
        if self.LowerLimit.lower().strip("'") == "all":
            self.reviewRange = False
            if citiesOrReviews.lower() == 'cities':
                for row in self.wb.active.rows:
                    self.cities.append(row[0].value)
        elif self.LowerLimit.isdigit():
            if citiesOrReviews.lower() == 'cities':
                if int(self.LowerLimit) > len(self.wb.active.rows):
                    msgbox("The lower limit you've entered is higher than the number of cities in the spreadsheet. Let's retry.", 'Error')
                    self.getRanges(citiesOrReviews)
            self.UpperLimit = enterbox("Enter an upper limit for %s:" % citiesOrReviews, "Range")
            if self.UpperLimit.isdigit():
                if citiesOrReviews.lower() == 'cities':
                    if int(self.UpperLimit) > len(self.wb.active.rows):
                        msgbox("The upper limit you've entered is higher than the number of cities in the spreadsheet. Let's retry.", "Error")
                        self.getRanges(citiesOrReviews)
                    if self.UpperLimit <= self.LowerLimit:
                        msgbox("The upper and lower limits are identical, or the upper limit is less than the lower. Let's retry.", "Error")
                        self.getRanges(citiesOrReviews)
                    else:
                        if citiesOrReviews.lower() == 'cities':
                            for row in self.wb.active.rows[int(self.LowerLimit) - 1:int(self.UpperLimit)]:
                                self.cities.append(row[0].value)
                elif citiesOrReviews.lower() == 'reviews':
                    self.reviewRange = [int(self.LowerLimit) - 1, int(self.UpperLimit)]
        else:
            msgbox("The value entered must either be 'all', or a number. Let's retry.", "Error")
            self.getRanges(citiesOrReviews)


texts: Dining Philosopher's problem implementation with Java Locking Framework to avoid deadlock

texts:
Dining philosopher problem is one of the classic problems in computer science. I intended to implement it using Java threads. I attempted using the locking framework that came with Java 5 and used the tryLock() method to avoid deadlock. My implementation is fairly simple. I implemented the runnable interface to represent a philosopher and used executor service to run all these runnable.

As a lock, I have used ReentrantLock. I know there are several implementations are already discussed here, but I would like to get some review on my implementation.

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;

public class Philosopher implements Runnable {
    private String name;
    private final Lock leftFork;
    private final Lock rightFork;

    public Philosopher(String name, Lock leftFork, Lock rightFork) {
        this.name = name;
        this.leftFork = leftFork;
        this.rightFork = rightFork;
    }

    public void think() {
        log("thinking");
    }

    public void eat() {
        //assume, eating requires some time.
        //let's put a random number
        try {
            log("eating");
            int eatingTime = getRandomEatingTime();
            TimeUnit.NANOSECONDS.sleep(eatingTime);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }

    @Override
    public void run() {
        while (true) {
            keepThinkingAndEating();
        }
    }

    private void keepThinkingAndEating() {
        think();

        if (leftFork.tryLock()) {
            try {
                log("grabbed left fork");
                if (rightFork.tryLock()) {
                    try {
                        log("grabbed right fork");
                        eat();
                    } finally {
                        log("put down right fork");
                        rightFork.unlock();
                    }
                }
            } finally {
                log("put down left fork");
                leftFork.unlock();
            }
        }
    }

    private void log(String msg) {
        DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_TIME;
        String time = formatter.format(LocalDateTime.now());
        String thread = Thread.currentThread().getName();
        System.out.printf("%12s %s %s: %s%n", time, thread, name, msg);
        System.out.flush();
    }

    private int getRandomEatingTime() {
        Random random = new Random();
        return random.nextInt(500) + 50;
    }
}

And the main method to run this code:

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class PhilosopherMain {
    public static void main(String[] args) {
        Lock[] forks = new Lock[5];
        for (int i = 0; i < forks.length; i++) {
            forks[i] = new ReentrantLock();
        }

        Philosopher[] philosophers = new Philosopher[5];

        ExecutorService executorService = Executors.newFixedThreadPool(5);

        for (int i = 0; i < philosophers.length; i++) {
            Lock leftFork = forks[i];
            Lock rightFork = forks[(i + 1) % forks.length];
            philosophers[i] = new Philosopher("Philosopher " + (i + 1), leftFork, rightFork);
            executorService.execute(philosophers[i]);
        }

        executorService.shutdown();
    }
}


texts: Improvement in file management system based on the file names

texts:
Context:

I have a program which stores data to the disk. The data is then reprocessed during some of the iterations. Thus, it needs to store, search and load set of data.

Let's consider the following class Signal which defines a multiphasic signal:

class Signal:
    def __init__(self, amp, fq, phases):
        self.amp = amp
        self.fq = fq
        self.phases = phases

# List of signal objects:
signals = [Signal(0.2, 50, [20, 30]), Signal(10, 200, [20, 30]), Signal(20, 20, [20, 90])]

Based on the list of signals, a file_name is computed:

def file_name(signals):
    amplitudes = tuple([S.amp for S in signals])
    frequencies = tuple([S.fq for S in signals])
    phases = tuple([S.phases for S in signals])

    return "A{}_F{}_P{}.pkl".format(amplitudes, frequencies, phases)

For the example above, it would return:

 "A(0.2, 10, 20)_F(50, 200, 20)_P([20, 30], [20, 30], [20, 90]).pkl"

As you can see, I'm pickling the files (with _pickle). Let's now believe that hundreds of files have been stored to the folder: folder. To check if a specific combination of signals has been computed I'm using:

import itertools
def is_computed(files, signals):
    """
    Check if the signals are already computed
    """
    return any(file_name(elt) in files for elt in itertools.permutations(signals))

I'm using itertools since the permutations are relevant, i.e.:

signals = [Signal(0.2, 50, [20, 30]), Signal(10, 200, [20, 30]), Signal(20, 20, [20, 90])]
# IS THE SAME AS:
signals = [Signal(10, 200, [20, 30]), Signal(20, 20, [20, 90]), Signal(0.2, 50, [20, 30])]

Issue:

To get the list of files past to is_computed(), I'm using: files = os.listdir(folder) which becomes fairly inefficient as the number of files grows up.

# Folder of 26K files with the size from 1 kB to hundreds of MBs
In:  %timeit os.listdir(folder)
Out: 3.75 s ± 842 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

Question:

How could I make a similar system but efficient?

Thanks for the help!