texts: Calculates the number of hours and days left, where the total number of hours is 486

texts:
I'm new here and this is my first simple console application that calculates the number of hours left. There's a lot to improve and if you have any suggestions on what things to add or refactor that would be awesome!  It's 486 because it's the usual number of hours an internship has.

The user presses 1 to enter the number of days, and 2 gets the current date. The output shows the accumulated number of hours, the remaining hours and days left before the 486 hours are up.

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

namespace Reuseable
{
    //calculates the accumulated hours, remaining hours, and remaining days, where total hours = 486.
    public static class ReuseableClass
    {
        static int AccumulatedHours(int dayhours, int input)
        {
            int result = dayhours * input;
            Console.WriteLine("Accumulated hours: " + result);
            return result;
        }

        static int RemainingHours(int totalhours, int accumulatedhours)
        {
            int result = totalhours - accumulatedhours;
            Console.Write("Remaining hours: " + result);
            return result;
        }

        static int RemainingDays(int remaininghours, int dayhours)
        {
            int result = remaininghours / dayhours;
            Console.Write("\nRemaining days: " + result);
            return result;
        }

        /// <returns>Number of business days during the 'span'</returns>
        public static double GetBusinessDays(DateTime startD, DateTime endD)
        {

            double calcBusinessDays =
                1 + ((endD - startD).TotalDays * 5 -
                (startD.DayOfWeek - endD.DayOfWeek) * 2) / 7;

            if (endD.DayOfWeek == DayOfWeek.Saturday) calcBusinessDays--;
            if (startD.DayOfWeek == DayOfWeek.Sunday) calcBusinessDays--;

            return calcBusinessDays;
        }

        public static void NumberOne()
        {
            //sets the hours
            int dayHours = 9;
            int totalHours = 486;
            int input;

            Console.WriteLine("\nEnter days");

            bool isNumeric = int.TryParse(Console.ReadLine(), out input);

            if (isNumeric == false) //checks if input is ok or not
            {
                Console.WriteLine("Invalid input");
                Console.ReadLine();
                System.Environment.Exit(1);
            }

            //gets input from user
            int accumHours = AccumulatedHours(dayHours, input);
            int remainingHours = RemainingHours(totalHours, accumHours);
            RemainingDays(remainingHours, dayHours);
        }

        public static void NumberTwo()
        {
            int dayHours = 9;
            int totalHours = 486;

            DateTime startDate = new DateTime(2016, 06, 20);
            DateTime endDate = DateTime.Today;

            int input = Convert.ToInt32(GetBusinessDays(startDate, endDate));

            int accumHours = AccumulatedHours(dayHours, input);
            int remainingHours = RemainingHours(totalHours, accumHours);
            RemainingDays(remainingHours, dayHours);

        }
        public static void Main()
        {
            Console.WriteLine("1. Enter No. of Days \n2. Use current day");
            ConsoleKeyInfo button = Console.ReadKey();
            if (button.Key == ConsoleKey.D1)
            {
                NumberOne();
            }
            else if (button.Key == ConsoleKey.D2)
            {
                NumberTwo();
            }
            else
            {
                Console.WriteLine("Invalid input");
            }

            Console.ReadLine();
        }
    }
}


texts: Simplify finding indices of all instances of certain characters in a string

texts:
I have a string util method for finding potential "wrapping points" in a string.

For example, if " " and "-" are considered wrapping chars, then for input string
 "Antoni Gil-Bao" the method would return the sorted set [6, 10].

private static final String WRAPPING_CHARS = " -";
private static final CharMatcher WRAP_CHAR_MATCHER = CharMatcher.anyOf(WRAPPING_CHARS);

public static SortedSet<Integer> findWrappingIndices(String s) {
    SortedSet<Integer> indices = Sets.newTreeSet();
    while (WRAP_CHAR_MATCHER.indexIn(s) != -1) {
        int index = WRAP_CHAR_MATCHER.indexIn(s);
        int indexInOriginalString = indices.isEmpty() ? index :  index + indices.last() + 1;
        indices.add(indexInOriginalString);
        s = s.substring(index + 1);
    }
    return indices;
}

Question is, is there a simpler way to implement this method using Guava? (Besides trivialities like inlining indexInOriginalString.) Based on my unit tests, the above does the job, but it doesn't feel that elegant. Obviously pure Java solutions are welcome too, if they are simpler than my Guava version. In any case, the method should take a String and return SortedSet<Integer>.

(Background: the reason I just want the indices, instead of doing any string wrapping here directly, is that eventually I'll be operating inside onDraw(), on a char array, and I want to measure pieces of text in the actual font before making wrapping decisions.)


texts: Finding the person with the biggest loss

texts:
For a course I following and my code is approved I had to make some code that finds the person with the biggest loss where the input is a string[]

The string arrray looks like this :

{ "Tom, 1, 3, -1", "Gillie, 2, 3, 1", "Thor, 1000, 1001, 1002" };

I solved it this way but it's not a clean way. I must say we were not allowed to use classes. that will be the next chapter of the course.

My solution looks now like this :

 public static string FindPersonWithBiggestLoss(string[] peopleAndBalances)
        {
            if (IsInValidInput(peopleAndBalances))
            {
                return InValidOutput;
            }

            var highestLossEver = decimal.MinValue;
            var personWithHighestLoss = new StringBuilder();

            for (int i = 0; i <= peopleAndBalances.Length - 1; i++)
            {
                var currentPersonData = peopleAndBalances[i].Split(',');
                var allAmounts = currentPersonData[1..];

                // calculateLoss

                if (allAmounts.Length <= 1)
                {
                    return InValidOutput;
                }

                for (int j = 0; j < allAmounts.Length - 1; j++)
                {
                    try
                    {
                        var amount1 = decimal.Parse(allAmounts[j], NumberStyles.Currency | NumberStyles.Number);
                        var amount2 = decimal.Parse(allAmounts[j + 1], NumberStyles.Currency | NumberStyles.Number);
                        var lossForCurrentPerson = amount1 - amount2;

                        //check if loss is greater then the current highest loss
                        if (lossForCurrentPerson > highestLossEver)
                        {
                            highestLossEver = lossForCurrentPerson;
                            personWithHighestLoss.Clear();
                            personWithHighestLoss.Append(currentPersonData[0]);
                        }
                    }
                    catch (FormatException ex)
                    {
                        Console.WriteLine($"there is not a valid character in the database. Reason{ex}");
                        break;
                    }
                }
            }

            if (personWithHighestLoss.ToString().Contains(','))
            {
                ReplaceCommaWithAnd(personWithHighestLoss);
            }

            return $"{personWithHighestLoss} lost the most money. -¤{highestLossEver}.";
    }

it works but also I need a lot of nested control statements to make it work.
Is there a cleaner way to make this work ?


texts: brute force algorithm keys with 32bit block and 64bit key using OpenCL

texts:
I wrote a brute-force attack on passwords using video cards for any algorithms with a 32-bit block and a 64-bit key, the password is only in BCD format, in the kernel source code the TEA algorithm, the project is written in c ++ builder 10.4, on a Radeon RX560 video card, a full brute-force attack from 0000000000000000 to 9999999999999999 takes 54 days , on the RTX3070 video card it takes 17 days, who knows OpenCL well, is it possible to speed up the search or I squeezed everything to the maximum ???
project files: https://drive.google.com/file/d/1Hcb2jl9HA_ZUf_Q6GD0u41z6FJBz5185/view?usp=sharing
kernel:
#pragma OPENCL EXTENSION cl_khr_byte_addressable_store : enable
#pragma OPENCL EXTENSION cl_khr_global_int32_base_atomics : enable
#pragma OPENCL EXTENSION cl_khr_local_int32_base_atomics : enable
#pragma OPENCL EXTENSION cl_khr_global_int32_extended_atomics : enable
#pragma OPENCL EXTENSION cl_khr_local_int32_extended_atomics : enable

ulong dec2bcd(uint dec)
{
ulong result = 0;
int shift = 0;

while (dec)
{
    result +=  (dec % 10) << shift;
    dec = dec / 10;
    shift += 4;
}
return result;
}

__kernel void     brute(__global const int *KEY, __global const int *DAT, __global int *CADR,
__global int *RETC)
{
union{
ulong  key_tmp;
ushort Key[4];
}cs;

int i = get_global_id(0);

ushort Data[2];

cs.Key[3]=(KEY[0]>>16);
cs.Key[2]=(KEY[0]&0xFFFF);
cs.Key[1]=(KEY[1]>>16);
cs.Key[0]=(KEY[1]&0xFFFF);

cs.key_tmp+=dec2bcd(i);

 Data[0]=(DAT[0] >> 16);
 Data[1]=(DAT[0] & 0xFFFF);

ushort delta = 0x9e37;
ushort sum = (delta<<5);

for (uint n = 0;n < 32; ++n){
  Data[1]-=(((Data[0])+cs.Key[1])^(Data[0]+sum)^((Data[0]>>5)+cs.Key[0]));
  Data[0]-=(((Data[1]<<4)+cs.Key[3])^(Data[1]+sum)^(Data[1]+cs.Key[2]));
  sum -= delta;
}

if ((Data[0]==0x0000) && (Data[1]==0x0000)){
int a=atomic_inc(CADR);
RETC[a*2]=(((cs.Key[3])<<16)+cs.Key[2]);
RETC[a*2+1]=(((cs.Key[1])<<16)+cs.Key[0]);

}

}


texts:
A few weeks ago, I had started to write a text-editor in C++ using SFML library. The work is now paused pretty much because I am a lazy freak. So, I thought I might use this passive time to get reviews on what I have done so far.

As of now, I want to get reviews on the cursor module (for displaying a blinking cursor), I wrote for the text-editor. I am posting the code as it was written and it was written without many comments. (I am not sure if I am supposed to add comments before putting it up for review on the site.)

Cursor.h:

#ifndef CURSOR_H_INCLUDED
#define CURSOR_H_INCLUDED

#include<iostream>
#include<SFML/Graphics.hpp>

class Cursor{
    private:
    sf::Color color;
    sf::RectangleShape cursorLine;
    sf::Clock clock;
    int col, line;
    int txtX, txtY;
    int maxCol;
    float thickness, length;
    int blinkPeriod, lastTime;
    bool visible;

    public:
    float getCol();
    float getLine();
    float getLength();
    float getThickness();
    void move(int, int);
    void setPosition(int,int);
    void setDefaultValues();
    Cursor();
    Cursor(float, float, float, float, int, int, int);
    void draw(sf::RenderWindow *);
    void update();
};

#endif // CURSOR_H_INCLUDED

Cursor.cpp:

#include "Cursor.h"

void Cursor::setDefaultValues(){
    col = 1;
    line = 1;
    lastTime = 0;
    thickness = 2;
    length = 20;
    blinkPeriod = 400;
    visible = true;
    color = sf::Color(0,255,0);
}

Cursor::Cursor(){
    setDefaultValues();
}

Cursor::Cursor(float x, float y, float len, float thick, int txX, int txY, int maxCol){
    setDefaultValues();
    this->maxCol = maxCol;
    txtX = txX;
    txtY = txY;
    col = x;
    line = y;
    length = len;
    thickness = thick;
}

float Cursor::getCol(){
    return col;
}

float Cursor::getLine(){
    return line;
}

float Cursor::getLength(){
    return length;
}

float Cursor::getThickness(){
    return thickness;
}

void Cursor::move(int dx, int dy){
    if(dx>0){
        if(col+dx<=maxCol)col += dx;
        else{
            col = 2;
            line += 1;
        }
    }
    else{
        if(col+dx>0) col +=dx;
        else{
            if(line>1){
                line -= 1;
                col = maxCol-1;
            }
        }
    }
    if(line+dy>0)line+= dy;
}

void Cursor::setPosition(int dx, int dy){
    col = dx;
    line= dy;
}

void Cursor::update(){
    cursorLine.setFillColor(color);
    cursorLine.setSize(sf::Vector2f(thickness, length));
    if((clock.getElapsedTime().asMilliseconds()-lastTime)>blinkPeriod){ visible = !visible;
    lastTime = clock.getElapsedTime().asMilliseconds();
    }
    cursorLine.setPosition((col-1)*(length*0.6)+txtX, (line-1)*(length*1.2)+txtY);
}

void Cursor::draw(sf::RenderWindow *screen){
    if(visible) screen->draw(cursorLine);
}


texts:
I wrote a simple function to sort an array of integers in ascending order. Here is the code -

void sort(int* begin, int* end) {

    int* it = begin;

    int num1 = 0, num2 = 0;

    while (it != end) {

        num1 = *it;
        num2 = *(it + 1);

        if (num1 > num2) {

            *it = num2;
            *(it + 1) = num1;
            it = begin;

         } else {

             it++;

         }

    }

}

Is there any way I can improve this code?


texts:
When playing Killer Sudoku I find myself repeatedly writing stuff like this:

12/3
921
831
741
732
651
642
543

and then crossing out the combinations that include say 9, 7, and 6

IE I need a list of any 3 digits between 1 and 9 that add up to 12, excluding 9, 7, and 6 because they are already in the house.

So I wrote a Linq query to run in LinqPad that does this. However its pretty specific. Here is the implementation for 3 numbers:

var num=3;
var target=12;
var exceptions=new List<int>{9,7,6};

var List1 = new List<int>{1,2,3,4,5,6,7,8,9};
var List2 = new List<int>{1,2,3,4,5,6,7,8,9};
var List3 = new List<int>{1,2,3,4,5,6,7,8,9};

// Make a Cartesian join of the three lists
// Filter out the stuff that we want
// Sort the result from highest to lowest
var combo = (from l1 in List1
        from l2 in List2
        from l3 in List3        // Cartesian product
        where l1 > l2 && l2 > l3    // exclude duplicates
        && l1 + l2 + l3 == target   // add up to the target
        && !exceptions.Contains(l1) // exclude exceptions
        && !exceptions.Contains(l2)
        && !exceptions.Contains(l3)
        select new List<int>{l1, l2, l3})
        .OrderByDescending (c =>c[0] )
        .ThenByDescending (d => d[1])
        .ThenByDescending (e => e[2]);

Console.WriteLine(string.Format("{0}/{1}", target, num));
foreach(var item in combo){
for (var i=0; i< num;i++){
    Console.Write(item[i]);
}
Console.WriteLine();
}
Console.Write("excluding");
foreach(var i in exceptions){
    Console.Write(string.Format(" {0} ",i));
}

I have found it pretty useful but is there a better and more general way of implementing this?


texts: How can I refactor Api::SessionsController?

texts:
I have session controller for mobile devices. I would like to refactor it a little, for example because my session controller is sub class of Devise::SessionsController I had to duplicate error methods from BaseController.

class Api::V1::SessionsController < Devise::SessionsController
  include Devise::Controllers::Helpers
  prepend_before_filter :require_no_authentication, only: [:create]
  skip_load_and_authorize_resource
  before_filter :ensure_params_exist, only: [:create]

  respond_to :json

  def create
    if user_find params[:user][:member_id]
      self.resource = warden.authenticate!(auth_options)
      sign_in(resource_name, resource)
      resource.reset_authentication_token!
      resource.save!
    else
      error :not_found
    end
  end

  def destroy
    sign_out(resource_name)
  end

  private

  def user_find(id)
    User.find_by member_id: id
  end

  def ensure_params_exist
    unless params[:user]
      error :bad_request
    end
  end

  def error type, context=nil
    render json: { message: error_message(type, context) }, status: type
  end

  def error_message type, context
    scope = [:api, :error, self.controller_name.to_sym]
    scope.push context if context
    t(type, scope: scope)
  end

end

class Api::V1::BaseController < ApplicationController
  load_and_authorize_resource

  respond_to :json

  rescue_from CanCan::AccessDenied do |exception|
    render_status :unauthorized
  end

  private

  def error type, context=nil
    render json: {message: error_message(type, context)}, status: type
  end

  def error_message type, context
    scope = [:api, :error, self.controller_name.to_sym]
    scope.push context if context
    t(type, scope: scope)
  end

  def render_status state
    render status: state, json: {}
  end
end


texts: Ultra-Beginner Python FizzBuzz ... Am I missing something?

texts:
I just started programming in Python this morning, and it is (more or less) my first programming language. I've done a bit of programming before, but never really did much except for "Hello World" in a few languages. I searched around for some Python FizzBuzz solutions, and they all seem significantly more complicated then mine, so I think I must be missing something, even though it works correctly. Could you guys point out any errors I've made, or things I can improve?

count = 0
while (count < 101):
    if (count % 5) == 0 and (count % 3) == 0:
        print "FizzBuzz"
        count = count +1
    elif (count % 3) == 0:
        print "Fizz"
        count = count + 1
    elif (count % 5) == 0:
        print "Buzz"
        count = count +1
    else:
        print count
        count = count + 1


texts:
I am trying to write a script to read a CSV file containing 1 million domain names, look up these domain names and store the results in another CSV file. I am trying the following code, but the number of records I am able to parse with time is quite less. I want to optimize the performance of this to be able to parse more records in less amount of time and also keep the CPU utilization under control. What all should I be focusing on or where can I get help regarding the same:

package main

import (
    "fmt"
    "io"
    "time"
    "net"
    "os"
    "encoding/csv"
    "strings"
)

func main() {

    resc, errc := make(chan string), make(chan error)

    fmt.Println("start time", time.Now())

    concurrency := 1000
    sem := make(chan bool, concurrency)

    csvfile, err := os.Open("1-million-rows.csv")

    if err != nil {
        fmt.Println(err)
        return
    }

    defer csvfile.Close()
    reader := csv.NewReader(csvfile)
    reader.FieldsPerRecord = -1 // see the Reader struct information below
    row_count := 0
    for {
        sem <- true
        record, err := reader.Read()
        if err == io.EOF {
            break
        }
        row_count += 1
        // Stop at EOF.
        domain_name := record[1]
        go func(domain_name string) {
            defer func() { <-sem }()
            body, err := lookup(domain_name)
            if err != nil {
                errc <- err
                return
            }
            resc <- string(body)
        }(domain_name)

    }

    for i := 0; i < cap(sem); i++ {
        sem <- true
    }

    for i := 0; i < row_count; i++ {
        select {
        case res := <-resc:
            fmt.Println(res)
        case err := <-errc:
            fmt.Println(err)
        }
    }
}

func lookup(domain_name string) (string, error) {
  ip, err := net.LookupIP(domain_name)
  if err != nil {
    return "", err
  }
  var ip_addresses []string
  for i := range ip{
    address := ip[i]
    ip_addresses = append(ip_addresses, address.String())
  }
  row := domain_name + ",[" + strings.Join(ip_addresses,":") + "]," + time.Now().String()
  fmt.Println(row)
  return row, nil
}

I am running the script and redirecting the output to another file (which will contain the output records that I need). Another problem that I am facing is that the program almost stops (zero CPU utilization) after a few seconds and after printing nearly 600 lines. Is there anything wrong with the way I am controlling concurrency?


texts: Simple array implementation without bounds-checking

texts:
I am preparing myself for some job interviews. This is a simple array (with the error handling left out for brevity). Any input or suggestions on style and the use of templates would be appreciated.

    #include <iostream>
    template <class T>
    class Array {
    public:
      explicit Array(const int&);
      Array(const int&, const T&);
      Array(const Array&);
      virtual ~Array();
      T getVal(const int&) const;
      void setVal(const int&, const T&);
      T& operator[] (T);
      Array& operator= (const Array&);

      template <class U>
      friend std::ostream& operator<< (std::ostream&, const Array<U>&);

    private:
      T* arr;
      int size;
    };

    template <class T>
    Array<T>::Array(const int& init_size) {
      arr = new T[init_size];
      size = init_size;
    }

    template <class T>
    Array<T>::Array(const int& init_size, const T& init_value) {
      arr = new T[init_size];
      size = init_size;
      for (int i = 0; i < size; ++i) {
        arr[i] = init_value;
      }
    }

    template <class T>
    Array<T>::Array(const Array& original) {
      size = original.size;
      arr = new T[size];
      for (int i = 0; i < size; ++i) {
        arr[i] = original.arr[i];
      }
    }

    template <class T>
    Array<T>::~Array() {
      delete [] arr;
    }

    template <class T>
    T Array<T>::getVal(const int& index) const {
      return arr[index];
    }

    template <class T>
    void Array<T>::setVal(const int& index, const T& value) {
      arr[index] = value;
    }

    template <class T>
    T& Array<T>::operator[] (T index) {
      return arr[index];
    }

    template <class T>
    Array<T>& Array<T>::operator= (const Array& copy) {
      if (arr == copy.arr)
        return *this;
     size = copy.size;
      delete [] arr;
      arr = new T[size];
      for (int i = 0; i < size; ++i) {
        arr[i] = copy.arr[i];
      }
      return *this;
    }

    template <class T>
    std::ostream& operator<< (std::ostream& out, const Array<T>& self) {
      out << "[ ";
      for (int i = 0; i < self.size-1; ++i) {
        out << self.arr[i] << ", ";
      }
      out << self.arr[self.size-1] << " ]";
      return out;
    }


texts: Count number of matching nodes in a Binary tree

texts:
Problem

Count the number of matching nodes in the subtree rooted at some node n.

Solution

from collections import namedtuple

Node = namedtuple('Node', 'key, left, right')

def build_tree(inorder, preorder):
    """Builds a Binary Tree from given inorder and preorder traversal.
    Steps:
    1. Take the first element from the preorder list.
    2. Get the index of the element from inorder list.
    3. Set the element as root.
    4. Take all elements left to root from inorder list.
    5. Take all elements right to root from inorder list.
    6. Calculate preorder list for left and right subtree respectively.
    7. Repeat from step 1 for each subtree.
    """
    if not preorder:
        return
    if len(preorder) == 1:
        return Node(preorder, None, None)
    root = preorder[0]
    root_index    = inorder.find(root)
    inorder_left  = inorder[:root_index]
    inorder_right = inorder[root_index+1:]
    preorder_left = preorder[1:len(inorder_left)+1]
    preorder_right = preorder[root_index+1:]
    return Node(
        root,
        build_tree(inorder_left, preorder_left),
        build_tree(inorder_right, preorder_right))

def match_count(root, key1, key2):
    """Counts the number of node that matches key1 or key2 in the subtree."""
    if root is None:
        return 0
    count_left = match_count(root.left, key1, key2)
    count_right = match_count(root.right, key1, key2)
    if root.key == key1 or root.key == key2:
        return count_left + count_right + 1
    return count_left + count_right

root = build_tree('DBEACF', 'ABDECF')

import unittest

class TestMatchCount(unittest.TestCase):
    def setUp(self):
        """
                A
               / \
              B   C
             /\    \
            D  E    F
        """
        root = build_tree('DBEACF', 'ABDECF')

    def test_noNodesFound(self):
        self.assertEqual(match_count(root, 'Z', 'Q'), 0)

    def test_nodesOnSameSide(self):
        self.assertEqual(match_count(root, 'D', 'E'), 2)

    def test_nodesOnDiffSide(self):
        self.assertEqual(match_count(root, 'D', 'F'), 2)

    def test_oneNodeIsRoot(self):
        self.assertEqual(match_count(root, 'D', 'A'), 2)

if __name__ == '__main__':
  unittest.main()

Time complexity

Since we check each node at least once hence it should be \$O(n)\$, where n is the number of nodes in the Binary Tree.

Note

while unit testing I felt that I am not able to express intent clearly for my test case unlike Jasmine where we can write proper description in it(...) format.


texts: Excel Retrieving Data from website through Internet Explorer

texts:
I took a look at Speed up processing between VBA and IE, but I didn't see anything that addressed the speeding up of the retrieval of information via IE.

Since MS got rid of the stock retrieval database (MSN Money), there wasn't an easy way to get current stock prices. From what I gather, there are some add-ins available through the app store, but like usual, I'm stuck on 2007 doing this.

This was my attempt at a UDF for retrieving the stock price from http://www.msn.com/en-us/money/ which requires finding elements on the page and getting the value from within. It's.. not very elegant, but it works. What can I do to speed up the IE processes? I know, I know - screenupdating, etc

Option Explicit

Public Function GetTickerPrice(ByVal ticker As String) As Double

    Dim IE As Object
    Dim pageData As Object

    Set IE = CreateObject("InternetExplorer.Application")
    Dim URL As String
    URL = "http://www.msn.com/en-us/money/stockdetails/fi-126.1." & ticker & ".NAS?symbol=" & ticker & "=PRFIMQ"

    IE.Navigate URL

     Do Until IE.ReadyState >= 4
            DoEvents
     Loop

     Application.Wait Now + TimeSerial(0, 0, 5)

     Set pageData = IE.document

     GetTickerPrice = pageData.getElementsByClassName("precurrentvalue")(0).innertext

     Set IE = Nothing
     Set pageData = Nothing
End Function


texts:
I wrote an infinite scrolling scrolling plugin for an app I'm developing. When requesting the second 'page' from the server, I loop through each image, and give it a very basic onload function.

// I will have the result in a variable called data
// Fetch each image from result
$images = $( data.content ).find('img');
// Cache length for use in for loop
imagesLength = $images.length;

for ( var i = 0; i < imagesLength; i++ ) {
    // Create new Image object
    img = new Image();
    // Match src of image in the result
    img.src = ( $images[i].src );
    // Add onload listener
    img.onload = function () {
        // Increment iterator, and check if we've loaded all the images
        if( ++imageLoadingIterator == images.length)
            _continue(); // Run _continue() if this is the case
    }
}

I feel like this isn't the best way to do this. Is there a way I can improve this function to run faster? For example: I'm thinking maybe creating a new Image object for each img tag is too much overhead.


texts: Lots of click handlers that hide one element and show another

texts:
I've a lot of code blocks that hide/show some block.

$('#Back').on('click', function () {
    $('#FormRow').hide();
    $('#TableRow').show();
});

$('#AddLanguageShow').on('click', function () {
    $('#FormRow').show();
    $("#TableRow").hide();
});

$('table').on('click', 'button.edit', function (evt) {
    $('#FormRow').show();
    $('#TableRow').hide();
    languageManager.load(getRowId($(this)));
});

Is it possible to split logic of changing blocks visibility ?


texts: Function that returns value based on specific category

texts:
This is a pretty simple function that returns a value based on the variable category. I tried to use switch instead of define menu object that contained functions with tag name but I noticed that it looks pretty dirty so that's how I made this code. After that I realized defining menu variable will run every function in the object to store the value in the properties which is not what I'm trying to do. What I want to do is that I want to run only a function and it needs to run to get a value based on the variable category. How could I make this better?

const getContent = async (category, tag) => {
    let query = { 'tag':tag, 'limit':10 }

    let menu = {
        'feed': () => steem.api.getDiscussionsByFeed(query),
        'blog': () => steem.api.getDiscussionsByBlog(query),
        'new': () => steem.api.getDiscussionsByCreated(query),
        'hot': () => steem.api.getDiscussionsByHot(query),
        'trend': () => steem.api.getDiscussionsByTrending(query)
    }

    return await menu[category]()
}


texts: SQL to find users that the current user hasn't liked/disliked

texts:
I have this really long query, which in my opinion looks ugly next to all the tidy code in my project. I was wondering if there was a way to optimize it or make it shorter at least:

$query = <<<SQL
    SELECT * FROM users
    WHERE NOT EXISTS (
        SELECT id
        FROM profile_likes
        WHERE profile_id = users.id
        AND viewer_id = $my_user->id
    )
    AND NOT EXISTS (
        SELECT id
        FROM profile_dislikes
        WHERE profile_id = users.id
        AND viewer_id = $my_user->id
    )
    AND id != $my_user->id
SQL

This query is a part of an user filter which has the purpose of filtering the users to only those that the currently logged in user ($my_user) hasn't liked/disliked yet.


texts:
I tried to write a foolproof function for the first part of the first problem on adventofcode, which asks for the count of ( characters minus the count of ) characters in a string.

The function intentionally ignores any other characters in the input string.

function findEndFloor(floors, upFloorSymbol, downFloorSymbol) {
  if (typeof floors !== 'string')
      throw 'parameter 1 is expected to be a string';
  if (typeof upFloorSymbol !== 'string')
      throw 'parameter 2 is expected to be a string';
  if (typeof downFloorSymbol !== 'string')
      throw 'parameter 3 is expected to be a string';

  var count = 0;
  var chars = floors.split('');
  for (var i = 0; i <  chars.length; i++) {
      if(chars[i] === upFloorSymbol || chars[i] === downFloorSymbol)
          count += (chars[i] === upFloorSymbol ? 1 : -1);
  }

  return count;
}

Any feedback will be appreciated.


texts:
I'm preparing for coding interviews and I wanted to get feedback on this question which asks you to write a simple ratelimiter that can handle 5 requests every 2 seconds for example. Since it is for a coding interview setting, I don't think it needs to be perfect.
I looked at the guava Ratelimiter for inspiration for this.
Please let me know if I have made any errors or any improvements that can be made. Any feedback is appreciated.
public class RateLimit {
    private double maxCapacity;
    private double refillRate;
    private double availableTokens;
    private long lastRefill;

    public RateLimit(double maxCapacity, long windowInSeconds) {
        this.maxCapacity = maxCapacity;
        this.lastRefill = Instant.now().toEpochMilli();
        this.refillRate = TimeUnit.SECONDS.toMicros(windowInSeconds) / maxCapacity ;
        this.availableTokens = maxCapacity;
    }

    public boolean acquire() {
        return acquire(1, true);
    }

    public boolean acquire(double requiredPermits) {
        return acquire(requiredPermits, true);
    }

    public boolean tryConsume(double requiredPermits) {
        return acquire(requiredPermits, false);
    }

    private synchronized boolean acquire(double requiredToken, boolean shouldBlock) {
        refill();

        boolean acquired = false;
        if (availableTokens >= requiredToken) {
            availableTokens -= requiredToken;
            acquired = true;
        } else if (shouldBlock) {
            double missingTokens = requiredToken - availableTokens;
            try {
                TimeUnit.MICROSECONDS.sleep((long) (refillRate * missingTokens));
                availableTokens = 0D;
                lastRefill = Instant.now().toEpochMilli();
                acquired = true;
            } catch (InterruptedException e) {
                System.out.println("Sleep interrupted");
            }
        }

        return acquired;
    }

    private void refill() {
        long now = Instant.now().toEpochMilli();
        if (now > lastRefill) {
            long elapsedTime = now - lastRefill;
            double tokensToBeAdded = Math.floor(TimeUnit.MILLISECONDS.toMicros(elapsedTime) / refillRate);
            if (tokensToBeAdded > 0) {
                availableTokens = Math.min(maxCapacity, availableTokens + tokensToBeAdded);
                lastRefill = now;
            }
        }
    }
```


texts: Genetic algorithm to find the minimum of a three-variable function

texts:
I've implemented a simple genetic algorithm for continuous floating point parameter spaces and without recombination. However, the way I'm passing in parameters and acquiring results from multiprocessing feels wrong. Should I be using concurrent.futures?

The code below uses the genetic algorithm to find the minimum of the equation x^2+y^2+z/10 over the parameter space -2 < x < 0, 0 < y < 2 and 10 < z < 11, but I'd like to keep the code easy to modify for various parameter spaces and evaluation functions.

import numpy as np

import multiprocessing
from collections import OrderedDict
import os
import time

def eval_iter(arg_lst, l_lst):
    for c_i, args in enumerate(arg_lst):
        yield c_i, args, l_lst

def eval_func(c_i, args, l_lst):
    assert len(args) == 3
    x = args[0]
    y = args[1]
    z = args[2]
    res = x**2 + y**2 + z/10
    print(f"Eval {x}, {y}, {z}: {res}")
    l_lst[c_i] = res

if __name__ == '__main__':

    generation_num = 10
    child_num = 5

    space = OrderedDict((
        ('x', (-2., 0.)),
        ('y', (0., 2.)),
        ('z', (10., 11.))
    ))

    params = OrderedDict([(nm, []) for nm in space.keys()])
    for nm, v_range in space.items():
        params[nm] = np.random.uniform(v_range[0], v_range[1], size=child_num)

    arg_list = []
    for c_n in range(child_num):
        arg_list.append([val[c_n] for val in params.values()])

    manager = multiprocessing.Manager()
    loss_lst = manager.list([np.inf for i in range(child_num)])

    for r_n in range(generation_num):
        with multiprocessing.Pool(os.cpu_count()) as pool:
            pool.starmap(eval_func, eval_iter(arg_list, loss_lst))

        fittest_idx = int(np.argmin(loss_lst))
        base_args = arg_list[fittest_idx]
        print(f"Best {base_args}\n")

        # mutate offspring from fittest individual
        params = OrderedDict([(nm, []) for nm in space.keys()])
        for s_i, (nm, v_range) in enumerate(space.items()):
            std = (v_range[1] - v_range[0]) / 2
            noise = np.random.normal(0, std, size=child_num)
            new_param = base_args[s_i] + noise
            params[nm] = np.clip(new_param, v_range[0], v_range[1])

        arg_list = []
        for c_n in range(child_num):
            arg_list.append([val[c_n] for val in params.values()])

        loss_lst = manager.list([np.inf for i in range(child_num)])


texts:
I've learned PHP following only tutorials on the web and I'm quite sure my style is not at top.

I'd like to understand how this code could be written in a more elegant way:

<?
$posts = // array with informations about posts fetched with PHP PDO from DB

$html = "
";
foreach($posts as $post) {
    $html .= "

".$post["title"]."
".$post["text"]."
";
}
$html .= "
";
echo $html;

I'm not sure if this is already a good piece of code or not.
I hope you guys can help me out.


texts:
I've just started to read K&R and currently, I'm dealing with problem 1-19:

  Write a function reverse(s) that reverses the character string s. Use it to write a program that reverses its input a line at a time.

Here is what I've implemented:

#include <stdio.h>

#define MAX_LINE_LENGTH 1000

void reverseLine(char reversedLine[], char line[], int lineSize);

int main(void) {

    int c;
    int i = 0;

    char line[MAX_LINE_LENGTH];
    while((c = getchar()) != EOF && c != '\n') {
        line[i++] = c;
    }
    if (c == '\n')
        line[i++] = '\0';

    int realSize = i;
    char reversedLine[realSize];

    reverseLine(reversedLine, line, realSize);
    printf("%s\n", reversedLine);

    return 0;
}

void reverseLine(char reversedLine[], char line[], int lineSize){
    int j, k;
    for(j = lineSize - 2, k = 0; j >= 0; j--, k++){
        reversedLine[k] = line[j];
    }
    reversedLine[k] = '\0';
}

I'm having problems on grasping the spirit exactly as I am supposed to be. So, any help to improve my solution will be appreciated!


texts:
I made a mergesort implementation based on this code. Please review my C++ version.

using size = std::size_t;

template<typename T>
void merge(std::vector<T>& v, size low, size mid, size high) {
    size i = low, j = mid+1;
    std::vector<T> old{v};
    for (size x = low; x <= high; ++x) {
        if (i > mid) {
            v[x] = old[j++];
        } else if (j > high){
            v[x] = old[i++];
        } else if (old[j] < old[i]) {
            v[x] = old[j++];
        } else {
            v[x] = old[i++];
        }
    }
}

template<typename T>
void sort(std::vector<T>& v, size low, size high) {
    if (high <= low) {
        return;
    }
    size mid = (high+low)/2;
    sort(v,0,mid);
    sort(v,mid+1,high);
    merge(v,low,mid,high);
}

template<typename T>
void sort(std::vector<T>& v) {
    if (v.size() < 2) {
        throw std::out_of_range("out of range");
    }
    sort(v,0,v.size()-1);
}


texts: Yet another implementation of Conway's Game of life in Haskell

texts:
(Sorry for my bad English)
Hi, I'm interested in getting feedback of my own implementation of Conway's Game of Life.
Some details:

Uses gloss for animation
Uses rio for shorter dependency list

My implementation suffers from performance issue when the population grows larger than 2000 cells.
My code:

Main.hs:

module Main where

import           Lib
import qualified RIO.ByteString                as B
import           System.Environment
import qualified Graphics.Gloss                as G

main :: IO ()
main = do
  [file]      <- getArgs
  initialGrid <- B.readFile file
  let patt = parse initialGrid
  G.simulate G.FullScreen G.white 20 patt golPic (\_ _ ps -> eval ps)

golPic :: [Point] -> G.Picture
golPic ps =
  G.pictures [ G.translate (fromIntegral x * dIMENSION) (fromIntegral y * dIMENSION) (G.color G.black (G.rectangleSolid dIMENSION dIMENSION)) | (x, y) <- ps ]

parse :: B.ByteString -> [Point]
parse bs = map fst . filter ((== 42) . snd) . concatMap (\(x', xs) -> [ ((y', -x'), c) | (y', c) <- zip [1 .. length xs] xs ]) $ zip [1 .. length bs'] bs'
  where bs' = map B.unpack $! B.split 10 bs

dIMENSION :: Float
dIMENSION = 10

Lib.hs:

module Lib where

import qualified RIO.Map                       as M

type Point = (Int, Int)

adjacents :: Point -> [(Point, Int)]
adjacents (x, y) = [ ((x + m, y + n), 1) | m <- [-1, 0, 1], n <- [-1, 0, 1], (m, n) /= (0, 0) ]

eval :: [Point] -> [Point]
eval cs =
  [ x
  | (x, y) <- M.toList . M.fromListWith (+) . concatMap adjacents $ cs
  , case y of
    2 -> x `elem` cs
    3 -> True
    _ -> False
  ]

Any suggestion is welcome.


texts:
I did create a function which loops through the colors of a product and outputs a div with the specific color. After that it finds the image for the available colors. But I think the code can be a lot smarter.

Can someone optimize my code?

<?php
$brand_terms = get_the_terms($post, 'pa_kleur');
$brand_string = ''; // Reset string
foreach ($brand_terms as $term) : ?>
<?php

    if (($term->name) == 'Roze') {
        echo '

';

        $variations = $product->get_available_variations();
        foreach ( $variations as $key => $value ) {
    ?>
        <?php if ($value['attributes']['attribute_pa_kleur'] == 'roze') { ?>

            <?php echo $value['image']['url']; }?>

    <?php
    }
    }
    if (($term->name) == 'Grijs') {
        echo '

';

        $variations = $product->get_available_variations();
        foreach ( $variations as $key => $value ) {
    ?>
        <?php if ($value['attributes']['attribute_pa_kleur'] == 'grijs') { ?>

            <?php echo $value['image']['url']; }?>

    <?php
    }
    }
endforeach;
?>

Thanks for your time!


texts: SemaphoreSlim extension method for safely handling cancellation and disposal

texts:
I have often found myself using a try {semaphore.Wait()} finally {semaphore.Release()} pattern when using a semaphore, so decided I wanted to try and write an extension method to do this instead.

This stems from the problem where I wanted to dispose of my class containing the SemaphoreSlim instance, and was unsure how to safely and elegantly deal with the SemaphoreSlim instance as well.  I'm still not sure if this is the right approach:

public static class SemaphoreSlimExtension
{
    public static async Task RunAsync(this System.Threading.SemaphoreSlim semaphore, Func<Task> action, System.Threading.CancellationToken cancellationToken)
    {
        try
        {
            cancellationToken.ThrowIfCancellationRequested();

            try
            {
                await semaphore.WaitAsync(cancellationToken);
                await action();
            }
            finally
            {
                semaphore.Release();
            }
        }
        catch (OperationCanceledException ex)
        {
            if (cancellationToken != ex.CancellationToken || !cancellationToken.IsCancellationRequested)
            {
                throw;
            }
        }
        catch (ObjectDisposedException ex)
        {
            if (!cancellationToken.IsCancellationRequested)
            {
                throw;
            }
        }
    }
}

Example usage:

public class ClassA : IDisposable
{
    private CancellationTokenSource WorkSemaphoreCancellationTokenSource { get; } = new CancellationTokenSource();
    private SemaphoreSlim WorkSemaphore { get; } = new SemaphoreSlim(1, 1);

    public async Task DoWork()
    {
        await WorkSemaphore.RunAsync(() => Task.Delay(5000), WorkSemaphoreCancellationTokenSource.Token);
    }

    public void Dispose()
    {
        WorkSemaphoreCancellationTokenSource.Cancel();
        WorkSemaphore.Dispose();
        WorkSemaphoreCancellationTokenSource.Dispose();
    }
}

Does this seem like a good approach?  Is there a better way to safely manage the cancellation and disposal of SemaphoreSlim instances?


texts:
I wrote a solution to the Mali problem on Kattis:

  Given inputs a1, a2, a3, …, an and b1, b2, b3, …, bn, determine n pairings (ai, bj) such that each number in the A sequence is used in exactly one pairing, each number in the B sequence is used in exactly one pairing, and the maximum of all sums ai + bj is minimal.

  Input

  The first line of input contains a single integer N (1 ≤ N ≤ 100000), the number of rounds.

  The next N lines contain two integers A and B (1 ≤ A, B ≤ 100), the numbers given in that round.

  Output

  The output consists of N lines, one for each round.  Each line should contain the smallest maximal sum for that round.

I'm fairly sure I can get the right answer 100% of the time, but the code exceeds the time limit of one second. I was wondering if you could help me optimize my code to help it run in time, or if you could explain why my code is inefficient.

#include <iostream>
#include <vector>

int main() {
    int x, c = 0, big = 0;
    std::cin >> x;
    std::vector<int> as, bs;
    for (int i = 0; i < x; i++) {
        bool founda = false, foundb = false;
        int a, b;
        std::cin >> a >> b;
        c++;
        if (c == 1) {
            as.push_back(a);
            bs.push_back(b);
        }
        else {
            for (int i = 0; i < c; i++) {
                if (as[i] < a || i == c-1) {
                    as.insert(as.begin()+i, a);
                    founda = true;
                }
                if (bs[i] < b || i == c-1) {
                    bs.insert(bs.begin()+i, b);
                    foundb = true;
                }
                if (founda == true && foundb == true)
                    break;
            }
        }
        for (int i = 0; i < c; i++) {
            if (as[i] + bs[c-1-i] > big)
                big = as[i] + bs[c-1-i];
        }
        std::cout << big << std::endl;
    }
}


texts:
I have written a function which finds the largest prime factor of some number. This function works but the problem is that it is too slow. For instance, when I enter 600851475143 as a parameter, the process of finding largest prime factor lasts too long. How can I modify it so that it works faster?

class test {

static addArray(someArray, member) {
    for (var i = 0; i <= someArray.length; i++) {
        if (i == someArray.length) {
            someArray[i] = member;
            return someArray;
        }
    }
}
static someLength(someArray) {
    var i = 0;
    while (someArray[i] !== undefined) {
        var lastItem = i;
        i++;
    }
    return i;
}
static testPrime(i) {
    for (var k=2; k < i; k++) {
        if (i % k == 0) {
            return false;
        }
    }
    return true;
}
}

var primeArray = [];
function largestPrime(n) {
    for (var i=2; i < n; i++) {
        //var k = n / i;
        if (n % i == 0 && test.testPrime(i) == true) {
            test.addArray(primeArray, i);
            n == n / i;
        }
    }
    return primeArray[test.someLength(primeArray) - 1];
}

document.write(largestPrime(600851475143));


texts: A function to split an string of alphabets and numbers into arrays and sort them respectively

texts:
if I have a string AYUKB17053UI903TBC. I want a function to return ABKUY01357IU039BCT. So every alphabetical part of the string is sorted, as well as the numerical part. But they retain their original orders in the string...

We can assume that the input only contains number and English letters

I came up with a solution but I don't think it is elegant.

    const string1 = 'AYUKB17053UI903TBC'
    const string2  = `ABKUY01357IU039BCT`

    function fn1(string1) {
      let tempArray = [[]]
      for (const char of string1) {
        let lastCharIsNumber
        let currentCharIsNumber
        const lastArray = tempArray[tempArray.length - 1]
        if(!lastArray.length){
          lastArray.push(char)
          continue
        }
        currentCharIsNumber = !Number.isNaN(Number(char))
        lastCharIsNumber = !Number.isNaN(Number(lastArray[lastArray.length - 1]))
        if (currentCharIsNumber && lastCharIsNumber)  lastArray.push(char)
        else if (!currentCharIsNumber && !lastCharIsNumber) lastArray.push(char)
        else tempArray.push([char])
      }

      tempArray.forEach(item => item.sort())

      return tempArray.map(array => array.join('')).join('')
    }

    console.log(fn1(string1) === string2); // true

Can anyone help to improve my solution?


texts: JavaScript/ECMAscript 6 classes organization

texts:
I have been trying to wrap my head around all the new options in ECMAscript 6 and to do this I tried to develop a simple setup which would allow me to place absolutely positioned <div>s on the page.

main.js:

import {Screen} from './objects/screen';
import {Position} from './objects/position';

var welcomeScreen = new Screen("Hello World");
welcomeScreen.title = "Hello World2";
welcomeScreen.position = new Position(100,100);
//Make sure the following does work if you have any advices, because there is a simple mistake which breaks this:
console.log(welcomeScreen.position.x);

var secondScreen = new Screen("Second screen", new Position(200,200));

objects/baseobject.js:

export class BaseObject{
    on(eventname,func){
        if(typeof this.listeners == "undefined"){
            this.listeners = {};
        }
        if(typeof this.listeners[eventname] == "undefined"){
            this.listeners[eventname] = [];
        }
        this.listeners[eventname].push(func);
        return this;
    }
    trigger(eventname){
        if(this.listeners && this.listeners[eventname]){
            for(let func of this.listeners[eventname]){
                func.call(this);
            }
        }
    }
}

objects/screen.js:

import {BaseObject} from './baseobject';
// private properties:
var pp = {
    position: Symbol(),
    title: Symbol()
};
export class Screen extends BaseObject{
    constructor(title,position = new Position(0,0)){
        this.element = document.createElement("div");
        this.element.classList.add("screen");
        this.title = title;
        this.position = position;
        document.body.appendChild(this.element);
    }
    reposition(){
        this.element.style.left = this.position.x + "px";
        this.element.style.top = this.position.y + "px";
    }
    set position(position){
        var that = this;
        this[pp.position] = position;
        this[pp.position].on("positionchange",function(){
            that.reposition();
        }).trigger("positionchange");
    }
    get position(){
        return this[pp.position];
    }
    set title(value){
        this[pp.title] = value;
        this.element.textContent = value;
    }
    get title(){
        return this[pp.title];
    }
}

objects/position.js:

import {BaseObject} from './baseobject';
// private properties:
var pp = {
    x: Symbol(),
    y: Symbol()
};
export class Position extends BaseObject{
    constructor(x,y){
        this[pp.x]=x;
        this[pp.y]=y;
    }
    set x(value){
        this[pp.x]=x;
        super.trigger("positionchange");
    }
    get x(){
        return this[pp.x];
    }
    set y(value){
        this[pp.y]=y;
        super.trigger("positionchange");
    }
    get y(){
        return this[pp.y];
    }
}

You can transpile ES6 to ES3 (I think it is 3) using (Google) Traceur.

Points of interest:

Are there nice ES6 language features I am forgetting?
Is there a nicer way to handle the 'set triggers' (-> private property construction)?
Should I be using modules? Combine classes into the same files? etc.


texts: Add spaces around variable with $ symbol bookends

texts:
I have some code in a particular coding language, and I am trying to clean it up by adding spaces around the variables. I wrote this code, and it works on small amounts of text and if I set a break point and run through it manually for large amounts of text. But when I try to run through it without frequently stopping the macro, Word stops responding and I have to restart the program. I think it is because the code is inefficient, but I don't have enough knowledge of vba to make it more efficient.

My code

Sub SpaceVarsAndEqns()

Dim i As Long
Dim paragraphIndex As Long
Dim characterIndex As Long
Dim isVar As Boolean
Dim varIndexBegin As Long
Dim varIndexEnd As Long
Dim Doc As Range
Dim Par As Range
Dim Char As Range

Set Doc = ActiveDocument.Range

For paragraphIndex = 1 To Doc.Paragraphs.Count

    Set Par = Doc.Paragraphs(paragraphIndex).Range
    isVar = False

    characterIndex = 1
    Do

        Set Char = Par.Characters(characterIndex)

        If isVar Then
            If Char.Text = "$" Then
                varIndexEnd = characterIndex

                If Not Par.Characters(varIndexEnd + 1).Text = " " Then
                    Par.Characters(varIndexEnd).InsertAfter (" ")
                    characterIndex = characterIndex + 1
                End If
                If Not Par.Characters(varIndexBegin - 1).Text = " " Then
                    Par.Characters(varIndexBegin).InsertBefore (" ")
                    characterIndex = characterIndex + 1
                End If

                varIndexBegin = 0
                varIndexEnd = 0
                isVar = False
            ElseIf Not (IsAlphaNumber(Char.Text) Or (Char.Text = ".")) Then
                varIndexBegin = 0
                varIndexEnd = 0
                isVar = False
            End If
        Else
            If Par.Characters(characterIndex).Text = "$" Then
                varIndexBegin = characterIndex
                isVar = True
            End If
        End If

        characterIndex = characterIndex + 1
    Loop While (characterIndex <= Par.Characters.Count)

Next paragraphIndex

End Sub

Text Before

\begin{bmatrix} $eval(($d$*$d.pmv$)/(|$d.et$|)*($d.et$*$xm$) + (($b$*-1)*$d.pmv$)/(|$d.et$|)*($d.et$*$ym$) + $dist5$,0.###)\\ $eval((((($a$*$d$)-$d.et$)/($b$))*$d.pmv$*-1)/(|$d.et$|)*($d.et$*$xm$) + ($a$*$d.pmv$)/(|$d.et$|)*($d.et$*$ym$)+ $dist6$,0.###) \end{bmatrix}

Text After

\begin{bmatrix} $eval(( $d$ * $d.pmv$ )/(| $d.et$ |)*( $d.et$ * $xm$ ) + (( $b$ *-1)* $d.pmv$ )/(| $d.et$ |)*( $d.et$ * $ym$ ) + $dist5$ ,0.###)\\ $eval((((( $a$ * $d$ )- $d.et$ )/( $b$ ))* $d.pmv$ *-1)/(| $d.et$ |)*( $d.et$ * $xm$ ) + ( $a$ * $d.pmv$ )/(| $d.et$ |)*( $d.et$ * $ym$ )+ $dist6$ ,0.###) \end{bmatrix}

I think it could be improved by using a find method to find two consecutive $ symbols, and checking if the characters in between are consistent with a variable. However, I don't know how I would add spaces doing it this way.


texts:
So here we are, using a StringBuilder to build an email body. I know there's a lot on StackOverflow and endless debate/discussion around how best to concatenate strings.

Can this be done in fewer lines of code in C#?
Can this be done better using templating?

My goals are readability and maintainability.

StringBuilder msgBody = new StringBuilder();
msgBody.AppendLine("Deleted Order Item Information");
msgBody.AppendLine("------------------------------------");
msgBody.AppendLine();
msgBody.AppendLine("Delete Date:    {0}".FormatWith(orderDetail.DeletedDate.FormatDateTime(dtFormat)));
msgBody.AppendLine("Delete Comment: {0}".FormatWith(orderDetail.DeletedComment));
msgBody.AppendLine();
msgBody.AppendLine("Order #:        {0}".FormatWith(order.ID.ToString()));
msgBody.AppendLine("Order Date:     {0}".FormatWith(order.SubmitDate.FormatDateTime(dtFormat)));
msgBody.AppendLine("Order Name:     {0}".FormatWith(order.Name));
msgBody.AppendLine("Order Comment:  {0}".FormatWith(order.Comment));
msgBody.AppendLine("Department:     {0}".FormatWith("{0} - {1}".FormatWith(orderDetail.Department, orderDetail.DepartmentDesc)));
msgBody.AppendLine();
msgBody.AppendLine("Item Number:    {0}".FormatWith(orderDetail.StockNumber));
msgBody.AppendLine("Quantity:       {0}".FormatWith(orderDetail.Quantity));
msgBody.AppendLine("Rush:           {0}".FormatWith((orderDetail.Rush.ToYesNo())));
msgBody.AppendLine("Item Name:      {0}".FormatWith(item.Name));
msgBody.AppendLine("Item Desc:      {0}".FormatWith(item.Description1));
msgBody.AppendLine("                {0}".FormatWith(item.Description2));
msgBody.AppendLine("Stock:          {0}".FormatWith((orderDetail.Stock.ToYesNo())));
msgBody.AppendLine("Item Comment:   {0}".FormatWith(orderDetail.Comment));


texts:
I have an ASP.NET MVC 5 app and I map properties between model and viewmodel and vice versa.

I could use automapper to do this but since I don't need mapping rules to convince me to use it as I mostly do simple 1 to 1 mapping the performance overhead that automapper will add is not worthwhile. If I have mapping differences I'll map it manually where I reference it in my controller.

Here is my code

public class Dog
{
    public int Id { get; set; }

    public string Name { get; set; }

    public DateTime? BirthDate { get; set; }

    public int? CreatedBy{ get; set; }

    public DateTime? DateCreated { get; set; }
}

public class DogViewModel
{
    public int Id { get; set; }

    public string Name { get; set; }

    public DateTime? BirthDate { get; set; }

    public static implicit operator DogViewModel(Dog dm)
    {
        var vm= new DogViewModel{
            Id = dm.Id,
            Name = dm.Name,
            BirthDate = dm.BirthDate
       };
        return vm;
    }

   public static implicit operator Dog(DogViewModel vm)
   {
       var dm = new Dog
       {
            Id = vm.Id,
            Name = vm.Name,
            BirthDate = vm.BirthDate
        };
        return dm;
    }
}

Question: Is there a way to use a common mapping method in my ViewModel class  or some other way to so that I don't have to duplicate code for copying properties?


texts: Checking whether a host has a second-level domain from a list

texts:
I have an url and need to check whether it has some second-level domain (SLD) from a list. For example for SLD foo.com I need to approve hosts foo.com, some.foo.com and reject host kungfoo.com. There is some solution:

domains_a = ['foo.com', 'bar.com', 'fur.net', 'beer.org']
domains_dot_a = ['.foo.com', '.bar.com', '.fur.net', '.beer.org']

domains_b = ['door.com', ... ]
domains_dot_b = ['.door.com', ... ]

domains_c = ['doom.com', ... ]
domains_dot_c = ['.doom.com', ... ]

def any_sld_matches(domains, domains_dot, host):
    return (host in domains) or any(host.endswith(sld) for sld in domains_dot)

def get_url_category(url):
    host = urlparse.urlparse(url.strip()).netloc
    if any_sld_matches(domains_a, domains_dot_a, host):
        return 'a'
    elif any_sld_matches(domains_b, domains_dot_b, host):
        return 'b'
    elif any_sld_matches(domains_c, domains_dot_c, host):
        return 'c'
    elif not host:
        return 'empty'
    else:
        return None


texts: C# Ping - Checking availability of hosts

texts:
Simple Console Application for checking if one of the hosts is available. The implementation should be for around 5 hosts to check with different response times and the method should return fast when one Host can be pinged. Is the asynchronous implementation O.K.?

using System;
using System.Net.NetworkInformation;
using System.Threading;
using System.Threading.Tasks;

namespace PingMe
{
    class Program
    {
        private static volatile bool _result;

        private readonly CancellationTokenSource _source;

        private readonly ParallelOptions _parallelOptions;
        private readonly string[] _hostsToPing = {"google.com", "reddit.com", "netflix.com"};

        private Program()
        {
            _source = new CancellationTokenSource();
            var token = _source.Token;
            _parallelOptions = new ParallelOptions
            {
                CancellationToken = token
            };
        }

        private bool IsOneOfTheHostsAvailable()
        {
            try
            {
                Parallel.ForEach(_hostsToPing, _parallelOptions, (host) =>
                {
                    try
                    {
                        var ping = new Ping();
                        var reply = ping.Send(host);
                        _parallelOptions.CancellationToken.ThrowIfCancellationRequested();
                        if (reply?.Status == IPStatus.Success)
                        {
                            _result = true;
                            Console.WriteLine($"Pinged {host}");
                            if (!_source.IsCancellationRequested)
                                _source.Cancel();
                        }
                    }
                    catch (Exception)
                    {
                        // we are only interested if one of the pings is successful, we don't care about the reason
                    }
                });
            }
            catch (OperationCanceledException)
            {
                // we are done
            }

            return _result;
        }

        private static void Main()
        {
            var program = new Program();
            var oneOfTheHostsIsAvailable = program.IsOneOfTheHostsAvailable();
            Console.WriteLine($"One of the hosts is available: {oneOfTheHostsIsAvailable}");
        }
    }
}


texts: Cross-platform command line tool for finding files

texts:
#!/usr/bin/env python

''' Search for files using wildcards amd magic '''

import os
from fnmatch import fnmatch
import sys
import argparse
import magic

def cmd_args():
    ''' returns a argparse namespane '''
    parser = argparse.ArgumentParser()

    parser.add_argument(
        '--root', default='.',
        help='Starting point [ defaults to cwd ]')

    parser.add_argument(
        '--pattern', default='*.*',
        help='Pattern to use for matching file names [ Defaults to *.* ]')

    parser.add_argument(
        '--depth',
        default=2**32,
        type=int,
         help='''
        Depth is the number of slashes in the files path ''')

    parser.add_argument(
        '--links',
        default=True,
        type=bool,
        help='\nFollow links\n')

    parser.add_argument(
        '--magic',
        default=None,
        type=str,
        help='Filter file by a magic keyword link: image data png')

    parser.add_argument(
        '--cat',
        default=False,
        type=bool,
        help='Concatenate matched files')

    return  parser.parse_args()

CMD_ARGS = cmd_args()

def cat(filename):
    ''' cat(filename) -> file contents'''
    if CMD_ARGS.cat:
        try:
            with open(filename, 'r') as file_object:
                print file_object.read()
        except IOError:
            pass
    else:
        return filename

def depth_check(link):
    '''
    This is called on each files path to control depth cutoff.
    It works by counting the number of slashes in the links path.
    If DEPTH > MAX DEPTH {
        EXIT PROGRAM
    }
    Note: By default max depth is 2**32 aka big ass number
    '''

    if link.count('/') > CMD_ARGS.depth:
        sys.exit()
    else:
        return link

def aggragate_files(root, dirs, files):

    _files = [depth_check(os.path.join(root, filename))
              for filename in files if fnmatch(filename, CMD_ARGS.pattern)]

    _subfiles = [depth_check(os.path.join(root, filename))
                 for filename in dirs if fnmatch(filename, CMD_ARGS.pattern)]

    return set(_files + _subfiles)

def find():
    for root, dirs, files in os.walk(CMD_ARGS.root,
                                     followlinks=CMD_ARGS.links):
        handle_files(aggragate_files(root, dirs, files))

def handle_files(files):
    for filename in files:
        if CMD_ARGS.magic:
            meta = magic.from_file(filename)
            if meta and CMD_ARGS.magic.lower() in meta.lower():
                print cat(filename)
        else:
            print cat(filename)

if __name__ == '__main__':
    find()

My concerns with the the code above:

Is the code easy to read?
Does this code honor PEP8?
Have I made any mistakes in the control-flow?
Would this code be considered pythonic?
Are my naming conventions descriptive?

How can I structure this code to make it easy to add features?

For example, where and how should this be hooked in?

def cat(filename):
        ''' cat(filename) -> file contents'''
        if CMD_ARGS.cat:
            try:
                with open(filename, 'r') as file_object:
                    print file_object.read()
            except IOError:
                pass
        else:
            return filename


texts:
I have a piece of code that calculates the edit distance between words and works, but it's apparently not fast enough.

ClosestWords.java:

import java.util.LinkedList;
import java.util.List;

public class ClosestWords {
  LinkedList<String> closestWords = null;

  int closestDistance = -1;

  public int dynamicEditDistance(char[] str1, char[] str2){
        int temp[][] = new int[str1.length+1][str2.length+1];

        for(int i=0; i < temp[0].length; i++){
            temp[0][i] = i;
        }

        for(int i=0; i < temp.length; i++){
            temp[i][0] = i;
        }

        for(int i=1;i <=str1.length; i++){
            for(int j=1; j <= str2.length; j++){
                if(str1[i-1] == str2[j-1]){
                    temp[i][j] = temp[i-1][j-1];
                }else{
                    temp[i][j] = 1 + Math.min(temp[i-1][j-1], Math.min(temp[i-1][j], temp[i][j-1]));
                }
            }
        }
        return temp[str1.length][str2.length];

    }

  public ClosestWords(String w, List<String> wordList) {
    for (String s : wordList) {
      int dist = dynamicEditDistance(w.toCharArray(), s.toCharArray());
      if (dist < closestDistance || closestDistance == -1) {
        closestDistance = dist;
        closestWords = new LinkedList<String>();
        closestWords.add(s);
      }
      else if (dist == closestDistance)
        closestWords.add(s);
    }
  }

  int getMinDistance() {
    return closestDistance;
  }

  List<String> getClosestWords() {
    return closestWords;
  }
}

Main.java:

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.List;

public class Main {

  public static List<String> readWordList(BufferedReader input) throws IOException {
    LinkedList<String> list = new LinkedList<String>();
    while (true) {
      String s = input.readLine();
      if (s.equals("#"))
        break;
      list.add(s);
    }
    return list;
  }

  public static void main(String args[]) throws IOException {
    BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in, "UTF-8"));
    List<String> wordList = readWordList(stdin);
    String word;
    while ((word = stdin.readLine()) != null) {
      ClosestWords closestWords = new ClosestWords(word, wordList);
      System.out.print(word + " (" + closestWords.getMinDistance() + ")");
      for (String w : closestWords.getClosestWords())
        System.out.print(" " + w);
      System.out.println();
    }
  }
}

Example input:

skål
skålar
skålen
skålens
skålform
#
kål
k
b
sklfrm
skala

Example Output:

kål (1) skål
k (3) skål
b (4) skål
sklfrm (2) skålform
skala (2) skål skålar

The upper part of the input are all the "correct" words and the lower part of the input (below the '#') are the words that need to be corrected. The output lines are of the form:

misspeltWord (minEditDistance)
listOfPossibleCorrectWordsThatShareTheSameEditDistance

Is there a way to make this code more efficient? I am running the code through a sort of "speed test" and it keeps failing on the last part of the test.


texts:
I inherited an application that uses some stored procedures. Here is a sample of one of the stored procedures used to insert or modify user data.

would like to get the group's opinion on the code. The SQL Server version is Microsoft SQL Server 2014 - 12.0.4100.1 (X64).

USE [MyDataBase]
GO
/****** Object:  StoredProcedure [dbo].[InsertOrModifyUserData]    Script Date: 2/2/2016 8:39:57 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER  PROCEDURE [dbo].[InsertOrModifyUserData]
@userName NVARCHAR(200),
@isSuperAdmin BIT = NULL,
@modifiedBy NVARCHAR(200),
@modifiedDate DATETIME = NULL,
@isActive BIT = NULL
AS

BEGIN
    SET NOCOUNT ON;
    SET XACT_ABORT ON;
    BEGIN TRY
        BEGIN TRANSACTION

            IF (@modifiedDate IS NULL OR @modifiedDate ='1900-01-01 00:00:00.000')
                SET @modifiedDate = GETDATE()
            IF (@isActive IS NULL)
                SET @isActive = 1

            IF ((@userName IS NOT NULL OR @userName <>'') AND (@isSuperAdmin IS NOT NULL OR @isSuperAdmin<>'') AND (@modifiedBy IS NOT NULL OR @modifiedBy <>''))
            BEGIN
                IF EXISTS(SELECT UserName FROM [dbo].[UserAccess] WHERE UserName = @userName)
                    UPDATE  [dbo].[UserAccess]
                        SET IsSuperAdmin    = @isSuperAdmin,
                            ModifiedBy      = @modifiedBy,
                            ModifiedDate    =   @modifiedDate,
                            IsActive        = @isActive
                    WHERE   UserName = @userName
                ELSE
                    INSERT INTO [dbo].[UserAccess] (UserName, IsSuperAdmin, CreatedDate, ModifiedBy, ModifiedDate,IsActive)
                    VALUES(@userName, @isSuperAdmin, GETDATE(), @modifiedBy, @modifiedDate, @isActive)

            END
        ELSE
            RAISERROR('Required parameters are not provided or Required parameters are passed as NULL',13,1)
        COMMIT TRANSACTION
        select null
    END TRY
    BEGIN CATCH
            DECLARE @ErrorMessage NVARCHAR(MAX) = ERROR_MESSAGE();
            DECLARE @ErrorSeverity INT = ERROR_SEVERITY();
            DECLARE @ErrorState INT = ERROR_STATE();
            RAISERROR(@ErrorMessage, @ErrorSeverity, @ErrorState);
            ROLLBACK TRANSACTION;
    END CATCH;

END


texts: Does setting the same element in a list does something at all?

texts:
I have a code similar to this:

public class PlayerRound {
    private final List<Strip> playerStrips = new ArrayList<>();

    public boolean addStrip(final Strip aStrip) {
        // ...
        if (playerStrips.contains(aStrip)) {
            playerStrips.set(playerStrips.indexOf(aStrip), aStrip); // DOES THIS LINE CHANGE SOMETHING?
        }
        // ...
        return true;
    }
}

@Entity
@Cacheable(false)
@Table(
        appliesTo = "Strip",
        indexes = {
            @Index(name = "IDX_RoundStrip", columnNames = {"round_id"}),
            @Index(name = "IDX_UserStrip", columnNames = {"user_id"})
        }
)
public class Strip implements Serializable, IAnnotatedProxy {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @Transient
    private Integer tempId = tempIdx++;

    @Override
    public boolean equals(Object obj) {
        Boolean areEqual = Boolean.FALSE;
        if (obj != null && getClass() == obj.getClass()) {
            final Strip other = (Strip) obj;
            if (null == this.id && null == other.id) {
                if (this.tempId.equals(other.tempId)) {
                    areEqual = Boolean.TRUE;
                }
            } else if (null != this.id) {
                if (this.id.equals(other.id)
                        || this.id.equals(other.tempId)) {
                    areEqual = Boolean.TRUE;
                }
            } else if (null != other.id) {
                if (other.id.equals(this.id)
                        || other.id.equals(this.tempId)) {
                    areEqual = Boolean.TRUE;
                }
            }
        }
        return areEqual;
    }
}

My question is: can I safely delete the line that sets the element that already is on the list on the same position?

Does this line does something that I don't know?


texts:
My project is written in node JS + Express and has the following architecture:

routes (e.g controllers)
models (stateless functional modules)
app

Models objects only doing SQL queries like this:

exports.setPassword = function (id, password, callback) {
  pg.connect(conString, function (err, client, done) {
    if (err) callback(err);
    else {
      client.query('UPDATE users SET password=$1 WHERE id=$2', [password, id], function (err) {
        done();
        if (err) callback(err);
        else callback(null);
      });
    }
  });
};

exports.setStatus = function (id, status, callback) {
  pg.connect(conString, function (err, client, done) {
    if (err) callback(err);
    else {
      client.query('UPDATE users SET status=$1 WHERE id=$2', [status, id], function (err) {
        done();
        if (err) callback(err);
        else callback(null);
      });
    }
  });
};

exports.getStayInTouch = function (userId, callback) {
  pg.connect(conString, function (err, client, done) {
    if (err) callback(err);
    else {
      client.query('SELECT * FROM stay_in_touch_contacts WHERE user_id=$1', [userId], function (err, results) {
        done();
        if (err) callback(err);
        else callback(null, results.rows[0]);
      });
    }
  });
};

and many many functions connected with the user in that user.js module.
The only thing I can do with that architecture is to place functions to the different module.

I'd appreciate any critiques of that architecture. How can I do better?


texts:
A company sells iPods online. There are 100 stocks maintained at
  Argentina and Brazil. A single iPod costs $100 in Brazil and $50 in
  Argentina. The cost of exporting stocks from one country to the other
  will cost $400 per 10 blocks. The transportation is always done in the
  multiples of 10. Calculate the minimum cost for purchasing the given
  no of units. Assume that for each transaction, the available stock in
  each country is maintained to be 100.

  Input and output format:

  The country from which the order is being placed: No of units
  Minimum costs:No of stock left in Brazil: No of stock left at Argentina

  Sample input and output:

Brazil:5

500:95:100

Brazil:50

4500:100:50

class Country:
     shp=40
     def country_details(self,numberofitems,sellingprice):
            self.sp=sellingprice
            self.no=numberofitems
     def display(self):
            print self.sp
            print self.no
            print self.shp

Brazil=Country()
Brazil.country_details(100,100)
Brazil.display()

Argentina=Country()
Argentina.country_details(100,50)
Argentina.display()

print "Enter the country from which you order from"
x=raw_input()
if x=="Brazil":
    c=1
else:
    c=2

print "Enter the amount of products needed"
y=raw_input()
y=int(y)

def profit(y):
    if c==1:
        if y%10==0:
            P=orderfromArgentinafb(y);
        else:
            P=orderfromBrazil(y);
    if c==2:
        P=orderfromArgentina(y);

    return P

def calculate(y):
    if (y<101):
        Pr=profit(y)
        return Pr
    else:
        Pr=profit(y-(y%100))+orderfromBrazil(y-100)
        return Pr

def orderfromBrazil(y):
    Cost=y*Brazil.sp
    if c==2:
        Cost=Cost+y*Brazil.shp
    Brazil.no=Brazil.no-y
    return Cost

def orderfromArgentina(y):
    Cost=y*Argentina.sp
    Argentina.no=Argentina.no-y
    return Cost

def orderfromArgentinafb(y):
    Cost=y*Argentina.sp+(y*Argentina.shp)
    Argentina.no=Argentina.no-y
    if Argentina.no <0:
        Argentina.no=0
    return Cost

Pr=calculate(y)
print Pr

print  "%d:%d:%d" %(Pr,Brazil.no,Argentina.no)


texts:
How can I improve this code, without to return async Task?

[WebMethod]
public string Login(string login, string password, string deviceId, string appVersion, string xuid)
{
    var authTask = _SSOFrontendService.GetSSOTokenAsync(login, password, deviceId, appVersion);
    var tokenTimestampTask = _SSOFrontendService.GetSSOTokenTimestampAsync();

    Task.WhenAll(authTask, tokenTimestampTask);
    var authResult = authTask.Result;

    if (authResult.Status == ResultStatus.OK)
    {
        var token = new MappedToken(xuid, login, password, deviceId, appVersion, authResult.Content, tokenTimestampTask.Result.Content);
        var mapTokenTask = _mapTokenService.MapAsync(token);

        Task.WhenAll(_mapTokenService.MapAsync(token));
        return _serializer.Serizalize(mapTokenTask.Result);
    }
    return _serializer.Serizalize(authResult);
}


texts: Simple registration with NodeJS and Mongoose

texts:
I'm new to Node.js (and also backend) for only a week, and now I'm trying to do a simple registration. I found that it's really hard to reduce complexity because pretty much every callback is error-first. Is there any way to reduce this? I found it seems impossible to avoid all of those if-elses.

const User = require('../../models/user')
const ERROR_MESSAGES = require('../../models/constant').ERROR_MESSAGES
const RESPONSE_STATUS = require('../../models/constant').RESPONSE_STATUS
const helper = require('../../helpers/helper')
const validator = require('validator')

module.exports.register = function(req, res) {
    const email = req.body.email
    const password = req.body.password
    const errors = []

    // input validation
    if (!email || email.trim().length == 0) {
        errors.push(ERROR_MESSAGES.EMPTY.EMAIL)
    } else if (!validator.isEmail(email)) {
        errors.push(ERROR_MESSAGES.INVALID.EMAIL)
    }

    if (!password) {
        errors.push(ERROR_MESSAGES.EMPTY.PASSWORD)
    }

    if (errors.length > 0) {
        return res.json(helper.generateResponse(errors, null, RESPONSE_STATUS.REQUEST_DENIED))
    } else {
        User.findOne({email: email}, function(err, user){
            if (err) {
                res.json(helper.generateResponse([ERROR_MESSAGES.UNKNOW], null, RESPONSE_STATUS.REQUEST_DENIED))
            } else if (user) {
                res.json(helper.generateResponse([ERROR_MESSAGES.DUPLICATE.EMAIL], null, RESPONSE_STATUS.REQUEST_DENIED))
            } else {
                var user = new User()
                user.email = email
                user.password = user.generateHash(password)

                var errorValidation = user.validateSync();

                if (errorValidation) {
                    // input validation
                    errors = helper.getMongooseValidationErrors(errorValidation.errors)
                    res.json(helper.generateResponse(errors, null, RESPONSE_STATUS.REQUEST_DENIED))
                } else {
                    user.save(function(error, newUser) {
                        if (error) {
                            res.json(helper.generateResponse([error], null, RESPONSE_STATUS.REQUEST_DENIED))
                        } else {
                            res.json(helper.generateResponse(errors, newUser, RESPONSE_STATUS.SUCCESS))
                        }
                    })
                }
            }
        })
    }
}


texts:
I have a lot of Task continuation that depend on .Result of previous Task -> for example: I have a command that should:

Stop previous instance
Copy files elsewhere
Delete original files
Start instance again

So for example the command function:

public Task<CommandResult> Execute(ICommandArguments arguments)
{
    TaskCompletionSource<CommandResult> tcs = new TaskCompletionSource<CommandResult>();

    // 1. Stop
    var tskStop = this.stopCommand.Execute(arguments);
    tskStop.ContinueWith(stoppingTask =>
    {
        if (stoppingTask.Result == CommandResult.Success)
        {
           // 2. Copy files
           var tskCopy = this.copyCommand.Execute(arguments);
           tskCopy.ContinueWith(copyingTask =>
           {
               if (copyingTask.Result == CommandResult.Success)
               {
                  // 3. Delete
                  ... skip for brevity...
               }
               else
               {
                  // Could not 'delete'
                  tcs.SetResult(CommandResult.Fail);
                }
            }, TaskContinuationOptions.OnlyOnRanToCompletion | TaskContinuationOptions.AttachedToParent);

            tskCopy.ContinueWith(tskCopyBad =>
            {
               //Error in 'copy'
               tcs.SetException(tskCopyBad.Exception.Flatten());
             }, TaskContinuationOptions.NotOnRanToCompletion | TaskContinuationOptions.AttachedToParent);
         }
         else
         {
            // Could not 'stop' for some reason
            tcs.SetResult(stoppingTask.Result);
          }
      }, TaskContinuationOptions.OnlyOnRanToCompletion | TaskContinuationOptions.AttachedToParent);

      tskStop.ContinueWith(tskSTopBad =>
      {
           // Exception in 'stop'
           tcs.SetException(tskStopBad.Exception.Flatten());
      }, TaskContinuationOptions.NotOnRanToCompletion | TaskContinuationOptions.AttachedToParent);
}

and you see that only with 2 'commands' code blown to so many lines. Is there any design pattern, shortcut, or extension that I can add/use to shorten code lines? I depend on the .Result from the previous Task and its Status (to know whether an exception was thrown or not).

Note that we currently develop our app in .NET 4 so we are limited to Task, and unfortunately cannot use async/await.

P.S. All those copyCommand, deleteCommand is also have a public Task<CommandResult> Execute() function


texts:
By having two model classes Conversation and Message, what are the best practices to handle the next situation: A conversation listening for its messages PropertyChanged events and so being able to update itself.

What are the best practices?
How can I improve this model design?
Is it going to generate memory leaks?

code

using SoftConsept.Collections;

public class Conversation
{
    readonly SortedObservableCollection<Message> messages;

    public Conversation ()
    {
        messages = new SortedObservableCollection<Message> ();
    }

    public void Add (Message message)
    {
        messages.Add (message);
        message.PropertyChanged += HandleMessagePropertyChanged;
    }

    public void Remove (Message message)
    {
        message.PropertyChanged -= HandleMessagePropertyChanged;
        messages.Remove (message);
    }

    public IList<Message> Messages ()
    {
        return messages.ToList ();
    }

    void HandleMessagePropertyChanged (object sender, PropertyChangedEventArgs e)
    {
        // Uptade omitted conversations properties using data from the updated message.
    }
}

public class Message : INotifyPropertyChanged
{
}


texts: C# - name separation & last name in upper to Camel

texts:
I had an xls file with lots of full names in the following form at work:
+----------------------------+--------------+-----+-----+
|        [Full name]         | [More data]  |[...]|[...]|
+----------------------------|--------------------------+
|   Cristiano RONALDO        |     ...      | ... | ... |
+----------------------------+--------------+-----+-----+
|   Carol SEVILLA            |     ...      | ... | ... |
+----------------------------|--------------+-----+-----+
|   Ronald Chris MAC DONALDS |     ...      | ... | ... |
+----------------------------|--------------+-----+-----+

some of the data will still be input this way but I want to add a column for last name and let it clear that I don't need the last name in upper case anymore, so I separated name from last name, and then changed the last name to camel case, notice that last names can have many words like "Mc Donalds Rodriguez" (it happens) so I solved it as follows
public static string GetLastNameFromFullName(string fullName)
{
    var lastName = "";
    foreach (var ch in fullName)
    {
        lastName += ch;
        if (char.IsLower(ch))
        {
            lastName = "";
        }
    }
    return lastName.TrimStart();
}

public static string GetCameledLastName(string lastNames)
{
    string[] lastNamesArr = lastNames.Split(' ');
    var lastNamesCameled = "";

    foreach (string lastNameUpper in lastNamesArr)
    {
        lastNamesCameled += lastNameUpper[0];
        for (int i = 1; i < lastNameUpper.Length; i++)
        {
            lastNamesCameled += char.ToLower(lastNameUpper[i]);
        }
    }
    return lastNamesCameled;
}

public static string GetNameWithoutLastName(string fullName)
{
    var possibleLastName = false;
    char possibleLastNameChar = ' '; //just initialized
    var name = "";
    foreach (var ch in fullName)
    {
        if (char.IsUpper(ch))
        {
            possibleLastNameChar = ch;
            if (possibleLastName)
            {
                break;
            }
            possibleLastName = true;
        }
        else
        {
            if (possibleLastName)
            {
                name += possibleLastNameChar;
            }
            name += ch;
            possibleLastName = false;
        }
    }
    return name;
}
private void Form1_Load(object sender, EventArgs e)
{
    var path = @"../../file.txt"; //dumped from xls file
    string contents = File.ReadAllText(path);

    using (StreamReader reader = new StreamReader(path, Encoding.GetEncoding("iso-8859-1"))) //some names had ñ or accented characters
    {
        string line;
        while ((line = reader.ReadLine()) != null)
        {
            var fullName = "";
            foreach (char ch in line)
            {
                if (ch == '\t')
                {
                    //The columns in the xls file were divided by tab characters
                }
                else
                {
                    fullName += ch;
                }
            }
            var lastName = GetLastNameFromFullName(fullName);
            Console.WriteLine("Name: " + GetNameWithoutLastName(fullName));
            Console.WriteLine("Last name: " + GetCameledLastName(lastName));
        }
    }
}

I think my code could be a lot better.
UPDATE: please note that while it is true that cases like "Cinthia del Río" is an actual name that is not considered in this way, it will be converted to "Cinthia Del Rio" because in the xls file it would be in a single column as "Cinthia DEL RIO", and of course it is impossible for the algorithm to know that "DEL" should actually be "del" even though it is perfectly OK for a last name's word to start with a lower case.


texts:
I have this CoffeeScript code running here (with TZM-Blade) and would like to have your opinion on how to better optimize it.

express = require "express"
gzippo = require "gzippo"
assets = require "connect-assets"
jsPaths = require "connect-assets-jspaths"
stylus = require "stylus"
blade = require "blade"
i18n = require "i18next"
http = require "http"
https = require "https"
fs = require "fs"
json = ""

#### Application initialization
# Create app instance.
app = express()

# Define Port
app.port = process.env.PORT or process.env.VMC_APP_PORT or process.env.VCAP_APP_PORT or 3000

# Config module exports has `setEnvironment` function that sets app settings depending on environment.
config = require "./config"
app.configure "production", "development", "testing", ->
  config.setEnvironment app.settings.env

# i18next init
i18n.init
  detectLngQS: "lang"
  ,ns: { namespaces: ['ns.common', 'ns.layout'], defaultNs: 'ns.common'}
  ,resSetPath: "./locales/__lng__/new.__ns__.json"
  ,ignoreRoutes: ["images/", "public/", "css/", "js/"]
  #,locales:['de', 'en', 'fr', 'pt']
  ,extension:".json"
  #,saveMissing: true
  #,sendMissingTo: 'all'
  ,debug: true

#### View initialization
# Add Connect Assets.
app.use assets(build : true)
jsPaths assets, console.log

# Set the public folder as static assets.
app.use gzippo.staticGzip(process.cwd() + "/assets")
app.use gzippo.staticGzip(process.cwd() + "/public")
app.use express.favicon(process.cwd() + "/public/images/favicon.ico")
app.use express.logger('dev')
# Set the nowjs folder as static assets and locales for i18next
app.use gzippo.staticGzip(process.cwd() + "/nowjs")
app.use gzippo.staticGzip(process.cwd() + "/locales")
app.use gzippo.staticGzip(process.cwd() + "/data/topo")

# Set Blade View Engine and tell Express where our views are stored
app.set "view engine", "blade"
app.set "views", process.cwd() + "/views"

try
  app.set "chapters", require(process.cwd() + "/data/chapters.json")
  app.set "languages", require(process.cwd() + "/locales/config.json")
  app.set "translation", require(process.cwd() + "/locales/dev/translation.json")
catch e
  console.warn "files not found: " + e
  app.set "chapters", []
  app.set "languages", []
  app.set "translation", []
  next()
  return

# [Body parser middleware](http://www.senchalabs.org/connect/middleware-bodyParser.html) parses JSON or XML bodies into `req.body` object
app.use express.bodyParser()

app.use i18n.handle
app.use blade.middleware(process.cwd() + "/views")
app.use app.router

#### Finalization
# Register i18next AppHelper so we can use the translate function in template
i18n.registerAppHelper(app)

# Initialize routes
routes = require "./routes"
app.locals.pretty=true
routes(app)

# Export application object
module.exports = app


texts:
Over the weekend I was curious about efficiently merging multiple sorted iterators together, and for them to be in sorted order.
This is quite like a challenge on HackerRank:

  You’re given the pointer to the head nodes of two sorted linked lists. The data in both lists will be sorted in ascending order. Change the next pointers to obtain a single, merged linked list which also has data in ascending order. Either head pointer given may be null meaning that the corresponding list is empty.

I may have cheated a bit by printing, rather than returning the items. However I don't mind that much about the HackerRank challenge.

I managed to do this in about \$O(3l)\$ space and \$O(l(2+n))\$ time. So \$O(l)\$ and \$O(ln)\$. Where \$l\$ is the amount of lists, and \$n\$ is the amount of data.

import operator
import functools

def from_iterable(fn):
    @functools.wraps(fn)
    def inner(*args):
        return fn(args)
    inner.from_iterable = fn
    return inner

@from_iterable
def merge(sources):
    sources = {
        id_: iter(source)
        for id_, source in enumerate(sources)
    }
    values = {}
    for id_, source in list(sources.items()):
        try:
            values[id_] = next(source)
        except StopIteration:
            del sources[id_]

    by_value = operator.itemgetter(1)
    while sources:
        id_, minimum = min(values.items(), key=by_value)
        try:
            values[id_] = next(sources[id_])
        except StopIteration:
            del values[id_], sources[id_]
        yield minimum

def iter_nodes(node):
    while node is not None:
        yield node.data
        node = node.next

def MergeLists(headA, headB):
    vals = merge.from_iterable(iter_nodes(l) for l in (headA, headB))
    print(' '.join(str(i) for i in vals), end='')

A bit overkill for the HackerRank challenge. But that wasn't the main reason for doing it.
Any and all reviews are welcome.


texts: Wrapping MongoDB Call Results in Observables

texts:
I have a number of functions that follow the basic pattern below. The intent is to provide a MongoDB implementation for a storage interface in a TypeScript application.

Is there a better way to clean this up so that is is simpler or more readable?

find(collection: string, query: any, sort = {}): Observable<[SyncedObject]> {
    return Observable.create(obs => {
        this.mongoService.connect(this.server, (err, db) => {
            db.collection(collection).find(query).sort(sort).toArray().then(results => {
                obs.next(results);
                db.close();
            });
        })
    })
}

findOne(collection: string, query: any, sort = {}): Observable<SyncedObject> {
    return Observable.create(obs => {
        this.mongoService.connect(this.server, (err, db) => {
            db.collection(collection).find(query).sort(sort).limit(1).next().then(result => {
                obs.next(result);
                db.close();
            });
        })
    })
}

// Several more functions like this....


texts: Concatenating rows in CSV files and removing old CSV files

texts:
I have written my first Python script that will go into live use at my workplace. I am relatively new to Python and I think this script is pretty good but I would like your input.

It runs very fast, as far as I can tell (~0.01seconds). It is also my first time writing a script that takes arguments from the way it is called, and these arguments are set in the .bat file it is ran from.

import os
import time
from itertools import izip_longest
import fnmatch
import datetime
from datetime import timedelta, datetime
import shutil
import time
from sys import argv

date, raw_dir, today_dir, archive_dir, error_file = argv[1:]

def merge(raw_dir, today_dir, archive_dir, date):
    """Read through all .CSVs in RAW directory and merge rows into Today's "full" CSV """
    archive_file = archive_dir + date + '.csv'
    with open(today_dir + 'TODAY.CSV', 'w') as f_obj:
        rows = []
        files = os.listdir(raw_dir)
        for fi in files:
            if fnmatch.fnmatch(fi, '*.csv') and not fnmatch.fnmatch(fi, 'TODAY.CSV'):
                 rows.append(open(os.path.join(raw_dir, fi)).readlines())
        iter = izip_longest(*rows)
        for row in iter:
            f_obj.write('   '.join([field.strip() for field in row if field is not None]) + '\n')
        shutil.copyfile(today_dir + 'TODAY.CSV', archive_dir + date + '.csv')

def clear(raw_dir):
    """ remove any raw csv files that are older than 14 business days. Data itself
    is not lost because it has been archived in the full csv"""
    files = os.listdir(raw_dir)
    file_paths = []
    file_ints = []
    for f in files:
        file_paths.append(os.path.join(raw_dir, f))
    if len(file_paths) > 14:
        for f in files:
            file_ints.append(int(f[:8])) #converts file names to ints from datenumber
        del_file = raw_dir + str(min(file_ints)) + '.csv' #makes a valid file path from     of the lowest value datenumber
        os.remove(del_file) # deletes lowest value
        print del_file + 'was deleted in clean up'
    else:
        return

I've left out the part with the functions actually being called as it's just simple if __name__ == "__main__" and some try/except


texts: Simple Sieve of Eratosthenes in Python 3

texts:
So yet another Sieve of Eratosthenes in Python 3.

The function returns a list of all primes smaller but not equal max_n.

The motivation is, as a practice, a simple implementation of the algorithm that is faithful, short, readable and transparent, while still getting a reasonable performance.

def primes(max_n):
    """Return a list of primes smaller than max_n."""

    sieve = [True] * max_n

    # p contains the largest prime yet found.
    p = 2

    # Only for p < sqrt(max_n) we check,
    # i.e. p ** 2 < max_n, to avoid float issues.
    while p ** 2 < max_n:

        # Cross-out all true multiples of p:
        for z in range(2 * p, max_n, p):
            sieve[z] = False

        # Find the next prime:
        for z in range(p + 1, max_n):
            if sieve[z]:
                p = z
                break

    # 0 and 1 are not returned:
    return [z for z in range(2, max_n) if sieve[z]]

IMHO it would be preferable to avoid p ** 2 < max_n and instead use p < max_n ** 0.5. Can we do this? It surprisingly seems to work as long as max_n ** 0.5 fits into the float mantissa, even if max_n doesn’t.

The second for-loop doesn’t look very nice with the break but I don’t have any idea how to do it otherwise…

Do you have any suggestions?

Are there still any simplifications possible? Or non-hackish ways to increase performance?


texts:
As Optional have only ifPresent and not have another function to be run in false case so I did the below class for that, please check it and give me your feedback:

public class OptionalConsumer<T> {
private Optional<T> optional;

private OptionalConsumer(Optional<T> optional) {
    this.optional = optional;
}

public static <T> OptionalConsumer<T> of(Optional<T> optional) {
    return new OptionalConsumer<>(optional);
}

public OptionalConsumer<T> ifPresent(Consumer<T> c) {
    optional.ifPresent(c);
    return this;
}

public OptionalConsumer<T> ifNotPresent(Runnable r) {
    if (!optional.isPresent())
        r.run();
    return this;
}

}
Then :

Optional<Any> o = Optional.of(...);
OptionalConsumer.of(o).ifPresent(s ->System.out.println("isPresent "+s))
        .ifNotPresent(() -> System.out.println("! isPresent"));


texts: Remove code duplication inside of a loop preserving performance

texts:
I'm coding a 2D collision engine, and I need to merge adjacent axis-aligned bounding boxes depending on a direction (left, right, top, bottom).

The four cases are very similar, except for the if condition, and the push_back argument.
Is there any way I can refactor this code without compromising performance?

vector<AABB> getMergedAABBSLeft(vector<AABB> mSource)
{
    vector<AABB> result;

    while(!mSource.empty())
    {
        bool merged{false}; AABB a{mSource.back()}; mSource.pop_back();

        for(auto& b : mSource)
            if(a.getRight() == b.getRight())
            {
                result.push_back(getMergedAABBVertically(a, b));
                eraseRemove(mSource, b); merged = true; break;
            }

        if(!merged) result.push_back(a);
    }

    return result;
}

vector<AABB> getMergedAABBSRight(vector<AABB> mSource)
{
    vector<AABB> result;

    while(!mSource.empty())
    {
        bool merged{false}; AABB a{mSource.back()}; mSource.pop_back();

        for(auto& b : mSource)
            if(a.getLeft() == b.getLeft())
            {
                result.push_back(getMergedAABBVertically(a, b));
                eraseRemove(mSource, b); merged = true; break;
            }

        if(!merged) result.push_back(a);
    }

    return result;
}

vector<AABB> getMergedAABBSTop(vector<AABB> mSource)
{
    vector<AABB> result;

    while(!mSource.empty())
    {
        bool merged{false}; AABB a{mSource.back()}; mSource.pop_back();

        for(auto& b : mSource)
            if(a.getBottom() == b.getBottom())
            {
                result.push_back(getMergedAABBHorizontally(a, b));
                eraseRemove(mSource, b); merged = true; break;
            }

        if(!merged) result.push_back(a);
    }

    return result;
}

vector<AABB> getMergedAABBSBottom(vector<AABB> mSource)
{
    vector<AABB> result;

    while(!mSource.empty())
    {
        bool merged{false}; AABB a{mSource.back()}; mSource.pop_back();

        for(auto& b : mSource)
            if(a.getTop() == b.getTop())
            {
                result.push_back(getMergedAABBHorizontally(a, b));
                eraseRemove(mSource, b); merged = true; break;
            }

        if(!merged) result.push_back(a);
    }

    return result;
}


texts: Abstracting the process of finding the index of the maximum in Python

texts:
Suppose I want to find the index of the maximal value of a given sequence. In Matlab, this is:

[value, index] = max(x)

In Python, I would abstract the following pattern:

def find_best_element_index(elements, is_better):
    best_so_far = elements[0]
    best_so_far_index = 0
    for (index, element) in enumerate(elements):
        if is_better(element, best_so_far):
            best_so_far = element
            best_so_far_index = index
    return best_so_far_index

Which I could use in the following way:

import operator
assert find_best_element_index([6, 3, 9, 8, 0, 9, 7, 9, 7, 8], operator.gt) == 2

But I wonder if there is a more pythonic way to go when I just want to find the index of the "best" item.