texts: Is there a better, more efficient way to write this loop?

texts:
While working with someone else's code I've isolated a time-killer in the (very large) script. Basically this program runs through a list of thousands and thousands of objects to find matches to an input (or many inputs) object. It works well when the number is below 50 but any input higher than that and it begins to take a looooong time. Is this just an issue with the database I'm running it against (30,000 things)? Or is this code written inefficiently?

for i in range(BestX):
       Tin=model[BestFitsModel[0][i]][2]
       Tau2=np.append(Tau2,model[BestFitsModel[0][i]][6])
       Dir=model[BestFitsModel[0][i]][0]
       Dir=Dir.replace('inp','out',1) ##open up correct .out file
       T=open(Dir,"rb")
       hold=''
       Tau=[]
       for line in T:
        if not line.strip():
         continue
        else:
         hold=line.split()
         Tau.append(hold)
       Tauline=0
       Taunumber=0
       print 'Loop'
       for j in range(5,len(Tau)-50):
        if 'RESULTS:' in Tau[j-5][0]:
         for k in range(j,j+50):
          if (Tau[k][1] == model[BestFitsModel[0][i]][6]):
           Tauline=i #line number of the tau
           Taunumber=k-(j) #Tau 1, 2, 3, etc.

   Dir=Dir.replace('out','stb',1)#.stb file
   Dir2=np.append(Dir2,Dir)
   F=open(Dir, "rb")
   hold=''
   Spectrum=[]
   for line in F:
    hold=line.split()
    Spectrum.append(hold)

BestX is a list of 30,000 objects (stars).

I'm not looking for an answer to this problem, I'm looking for code-critique...there has to be a way to write this so that it performs faster, right?

Thanks.

EDIT: Reading through the Python Performance Tips I've noticed one little snag (so far). Starting with the line Tau=[] and continuing for the next six lines. I can shorten it up by

Tau=[line.split() for line in T]

I'm gonna keep looking. Hopefully I'm on the right track.


texts: Create a generator that returns every permutation (unique arrangement) of positive integers up to n

texts:
I watched this video from The Unqualified Engineer on YouTube and tried out the challenge. The challenge (or interview question) is to build a generator that returns all the permutations of the positive integers up to \$n\$ (that is, \$1,2,3,\ldots,n\$).

I know about itertools.permutations but want to implement it myself.

def gen_perm(n):
    l=tuple(range(1,n+1))
    yield l
    while True:
        l=increment_lex(l)
        if(not l):
            raise StopIteration
            break
        yield l

def increment_lex(l):
    for i in range(len(l)-1):
        x=len(l)-(i+1)
        y=len(l)-(i+2)
        if l[x] > l[y]:
            m=min([i for i in l[x:] if i > l[y]])
            cl=list(l[x:])
            cl[cl.index(m)] = l[y]
            il=tuple(l[:y] + (m,) + tuple(cl[::-1]))
            return il
    return

for i in gen_perm(3):
    print(i)

This outputs:

(1, 2, 3)
(1, 3, 2)
(2, 1, 3)
(2, 3, 1)
(3, 1, 2)
(3, 2, 1)

In order to extend this to the other direction as well, however I couldn't think of a way to do it without adding two additional functions:

def gen_perm_reverse(n):
    l=tuple(range(n,0,-1))
    yield l
    while True:
        l=decrement_lex(l)
        if not l:
            raise StopIteration
            break
        yield l

def decrement_lex(l):
    for i in range(len(l)-1):
        x=len(l)-(i+1)
        y=len(l)-(i+2)
        if l[x] < l[y]:
            m=max([i for i in l[x:] if i < l[y]])
            cl=list(l[x:])
            cl[cl.index(m)] = l[y]
            il=tuple(l[:y] + (m,) + tuple(cl[::-1]))
            return il
    return

Apologies for the use of l as an identifier. It works nicely on my editor font but not here.


texts:
Given a slice of unknown length (potentially very small or very large), and another slice containing (unique) integers indicating indices to be removed from that slice, the most straight forward way to achieve this would be to sort the indices in reverse order then remove each of them from the slice in turn via:

mySlice = append(mySlice[:i], mySlice[i+1:]...)

Alternatively I could create a new empty slice like:

newSlice = make([]*Whatever, 0, len(mySlice)-len(indices))

And build it up like:

sort.Ints(indices)
nextIndex := 0
for i, thing := range mySlice {
    if nextIndex == len(indices) || i == indices[nextIndex] {
        nextIndex++
    } else {
        newSlice = append(newSlice, mySlice[i])
    }
}

I haven't benchmarked these yet, because I would rather understand why one would be faster than the other (and possibly under what conditions).

In particular, what actually happens in memory to the slice in the first strategy? I understand that slices are simple abstractions over arrays which are contiguous blocks of memory, but does removing the middle item of a slice require that memory to be moved around, such that it would be quicker to manage copying over every second item to a new slice/array than to remove every second item from the original slice?


texts:
This code is part of a tic tac toe game. It uses a 2D array for the board.

The functionality of the following code is to check for a win on the board, in rows, columns and diagonals. How can I improve it?

public bool WhoWon(Cell cell)
{
    for (int i = 0; i < 3; i++)
    {
        for (int j = 0; j < 3; j++)
        {
            if (_board[i, 0] == cell && _board[i, 1] == cell && _board[i, 2] == cell)
            {
                return true;
            }
            else if (_board[0, j] == cell && _board[1, j] == cell && _board[2, j] == cell)
            {
                return true;
            }
        }
    }

    if (_board[0, 0] == cell && _board[1,1] == cell && _board[2,2] == cell)
    {
        return true;
    }
    else if (_board[0, 2] == cell && _board[1, 1] == cell && _board[2, 0] == cell)
    {
        return true;
    }
    return false;
}


texts: Smallest element in an array that is repeated exactly ‘k’ times

texts:
This is a problem from GeeksForGeeks and I have tried to solve it on my own and I have written this code.

  Given an array of size n, the goal is to find out the smallest number
  that is repeated exactly ‘k’ times where k > 0? Assume that array has
  only positive integers and 1 <= arr[i] < 1000 for each i = 0 to n -1.

  Examples:

  Input:

arr[] = {2 2 1 3 1}
k = 2

  Output: 1

  Explanation:

  Here in array:

  2 is repeated 2 times
  1 is repeated 2 times
  3 is repeated 1 time

  Hence 2 and 1 both are repeated 'k' times

  i.e 2 and min(2, 1) is 1

  Input:

arr[] = {3 5 3 2}
k = 1

  Output: 2

  Explanation:

  Both 2 and 5 are repeating 1 time but min(5, 2) is 2

How can I improve this code?

#include <iostream>
#include <vector>
#include <map>

template<class T>
void findElement(std::vector<T>& vec, int k)
{
  std::map<T, int> count;
  for(T x : vec)
  {
    count[x]++;
  }

  typename std::map<T, int>::iterator itr;
  for(itr = count.begin(); itr != count.end(); itr++)
  {
    if(itr->second == k)
    {
      std::cout << itr->first <<'\n';
      return;
    }
  }
  std::cerr << "No such element \n ";
}

int main()
{
  std::vector<char> v;
  v.push_back('r');
  v.push_back('t');
  v.push_back('q');
  v.push_back('r');
  v.push_back('u');
  v.push_back('q');
  v.push_back('s');
  int k;
  std::cout << " Enter the number of repetitions you want : ";
  std::cin >> k;
  std::cout << "The smallest element that has " << k <<" reptition is : ";
  findElement(v, k);
}


texts: Binary search a sorted list of integers in Python 3

texts:
y is the value I am searching for. Is this the correct implementation for binary search?

y= 3
x= range(0,100)
left = 0
right = len(x)-1
mid=int((left+right)/2)

while x[mid]!=y:
    if x[mid]>y:
        right = mid
        mid=int((left+right)/2)
    if x[mid]<y:
        left = mid
        mid=int((left+right)/2)


texts: Very simple calculator with four basic operations using only if/else statements

texts:
I created a simple calculator with multiplication, division, addition, and subtraction. Is there a way to write it shorter? I am a beginner so I do not know much about programming other than if...else statements and different data types.

        Console.WriteLine("Welcome to the simple calculator! The four operators of this calculator are +, -, *(multiply), and /(divide)");
        Console.Write("Number: ");
        string number = Console.ReadLine();
        Console.Write("Second Number: ");
        string secondNumber = Console.ReadLine();
        Console.Write("Operator: ");
        string operatorType = Console.ReadLine();

        var numberConversion = Convert.ToInt64(number);
        var secondNumberConversion = Convert.ToInt64(secondNumber);
        var sum = numberConversion + secondNumberConversion; //Result of addition
        var difference = numberConversion - secondNumberConversion; //Result of subtraction
        var product = numberConversion * secondNumberConversion; //Result of multiplication
        var quotient = numberConversion / secondNumberConversion; //Result of division

        if (operatorType == "+")
        {
            Console.WriteLine(sum);
        } else if (operatorType == "-")
        {
            Console.WriteLine(difference);
        } else if (operatorType == "*")
        {
            Console.WriteLine(product);
        } else if (operatorType == "/")
        {
            Console.WriteLine(quotient);
        } else
        {
            Console.WriteLine("Please enter the correct operator");
        }


texts:
I came across a mock interview question in which the candidate is asked to generate the powerset of a given set.

The input set is represented as a unique array of integers.

There was no solution provided in this instance, so I tried to see what i could come up with on my own. I did struggle my way to a solution and I'm not particularly dissatisfied with it, but I'm not particularly satisfied either.

I took a recursive approach. Essentially, I generated a tree, depth first, with the uppermost level consisting of the original set and each successive lower level consisting of the immediate subsets of the parent node.

Here's my code. I am using ES5.

    var result = generate_powerset([1, 2, 3, 4]);
    console.log(result);

    function generate_powerset(set) {
      var powerset = generate_subsets(set);
      powerset.push(set);
      return powerset;
    }

    function generate_subsets(set) {
      var subsets = [];
      set.forEach(function(element, i) {
        var immediate_subset = remove_index(set, i);
        maybe_push(subsets, immediate_subset);
        var extended_subsets = generate_subsets(immediate_subset);
        extended_subsets.forEach(function(extended_subset) {
          maybe_push(subsets, extended_subset);
        });
      });
      return subsets;
    }

    function remove_index(array, i) {
      return array.filter(function(el, j) {
        return i != j;
      });
    }

    function maybe_push(set, non_member) {
      var already_member = false;
      set.forEach(function(member) {
        if (are_identical(member, non_member)) already_member = true;
      })
      if (!already_member) set.push(non_member);
    }

    function are_identical(set1, set2) {
      return (JSON.stringify(set1.sort()) == JSON.stringify(set2.sort()));
    }

I'm looking for ways to:

Make this algorithm more efficient
Make this code easier to understand
Make my code shorter

I'm also just generally curious if this approach is considered orthodox or unorthodox.


texts: Bash script to install vim configuration files

texts:
For the first time ever I decided to write a bash script. It works fine, but I'm feeling that I didn't write the most efficient code in order for future extension of the script. I also don't really get a good feeling on the look of the code. Any suggestions on how to improve the script?

Purpose of the script:
To pull a vim configuration located on github and then copy the files to the home directory and create some directories needed by the vim configuration.

dirs=( "~/.vim/undo" "~/.vim/swap" "~/.vim/backup" )
function error_exit
{
  printf '[failed\n]'
  exit 1
}

printf '   vim_config by Roel0                \n'
printf '   version 1.0                       \n'

printf 'Updating vim configuration ... '
if !(git pull > /dev/null;) then
  error_exit
fi
printf '[OK]\n'

printf 'Installing vim configuration ... '
if !(cp -r ./.vim* ~/) then
  error_exit
fi
printf '[OK]\n'

printf 'Creating configured directories ... '
for i in "${dirs[@]}"
do
  if !(mkdir -p $i) then
    error_exit
  fi
done
printf '[OK]\n'


texts: Setting various types of properties on a JCR node

texts:
This code checks value's type and cast it into appropriate type, then puts it into a javax.jcr.Node.

The checking looks long and boring. Is there a way to refactor it?  I'm using Java 7.

/**
 * Set node's property.
 */
public static void setProperty(Node node, String propertyName, Object propertyValue) throws RepositoryException {
    if (node == null) {
        throw new IllegalArgumentException("Something wrong");
    }
    if (propertyName == null) {
        throw new IllegalArgumentException("Property name is invalid");
    }

    if (propertyValue == null) {
        node.setProperty(propertyName, (Value) null);
    } else if (propertyValue instanceof Value) {
        node.setProperty(propertyName, (Value) propertyValue);
    } else if (propertyValue instanceof Node) {
        node.setProperty(propertyName, (Node) propertyValue);
    } else if (propertyValue instanceof Binary) {
        node.setProperty(propertyName, (Binary) propertyValue);
    } else if (propertyValue instanceof Calendar) {
        node.setProperty(propertyName, (Calendar) propertyValue);
    } else if (propertyValue instanceof Date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime((Date) propertyValue);
        node.setProperty(propertyName, cal);
    } else if (propertyValue instanceof BigDecimal) {
        node.setProperty(propertyName, (BigDecimal) propertyValue);
    } else if (propertyValue instanceof String) {
        node.setProperty(propertyName, (String) propertyValue);
    } else if (propertyValue instanceof Long) {
        node.setProperty(propertyName, ((Long) propertyValue).longValue());
    } else if (propertyValue instanceof Double) {
        node.setProperty(propertyName, (Double) propertyValue);
    } else if (propertyValue instanceof Boolean) {
        node.setProperty(propertyName, (Boolean) propertyValue);
    } else if (propertyValue instanceof InputStream) {
        node.setProperty(propertyName, inputStreamToBinary((InputStream) propertyValue));
    } else if (propertyValue instanceof Collection) {
        CollectionFactory factory = CollectionFactoryImpl.getInstance();
        ArrayList<Value> values = new ArrayList<Value>();
        for (Object value : (Collection<Object>) propertyValue) {
            values.add(createValue(value, factory));
        }
        node.setProperty(propertyName, values.toArray(new Value[values.size()]));
    } else {
        throw new IllegalArgumentException("Something wrong");
    }
}

@Test
public void test() {
    Node node = createNode("test");
    setProperty(node, "name", "name");
}


texts:
I'm starting with Kotlin recently and am hoping to improve.

I wrote a small app to parse the list of free Springer books and download the books into your chosen local folder.

Comments around obvious mistakes, unidiomatic Kotlin, any other points of improvements will be greatly appreciated. Thank you.

Gradle dependencies:

    implementation("org.apache.poi:poi:4.1.2")
    implementation("org.apache.poi:poi-ooxml:4.1.2")
    implementation("org.jsoup:jsoup:1.13.1")

Kotlin code:

package dev.rayfdj.kotlinutils.springer

import org.apache.poi.ss.usermodel.WorkbookFactory
import org.jsoup.Jsoup
import java.io.File
import java.io.FileOutputStream
import java.net.URL
import java.nio.channels.Channels
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths

data class Book(val title: String, val author: String, val edition: String, val year: String,
                val category: String, val url: String) {
    fun suggestedFileName(): String { return "$title, $edition - $author.pdf" }
}

fun extractBooksFromExcelFile(xlsxFile: File): List<Book> {
    // drop(1): skip the first row because it contains the headers
    return WorkbookFactory.create(xlsxFile).getSheetAt(0).drop(1).map {
        Book(it.getCell(0).stringCellValue, it.getCell(1).stringCellValue,
                it.getCell(2).stringCellValue, it.getCell(4).numericCellValue.toString(),
                it.getCell(11).stringCellValue, it.getCell(18).stringCellValue)
    }
}

fun deriveFullLocalPathForBook(downloadFolder: String, book: Book): Path {
    val fullLocalFileName = arrayOf(
            downloadFolder,
            book.category,
            book.suggestedFileName()).joinToString(separator = File.separator)
    return Paths.get(fullLocalFileName)
}

fun createDirectoriesAndFile(fullLocalFilePath: Path) {
    Files.createDirectories(fullLocalFilePath.parent)
    if(!Files.exists(fullLocalFilePath)) { Files.createFile(fullLocalFilePath) }
}

fun getBookDownloadURL(book: Book): URL {
    val bookPage = Jsoup.connect(book.url).get()
    val bookCanonicalURL = bookPage.select("link[rel=canonical]").attr("href")

    val bookCanonicalPage = Jsoup.connect(bookCanonicalURL).get()
    val bookPDFRelativeURL = bookCanonicalPage.select("a[href^=\"/content/pdf/\"]").attr("href")

    return URL("https://link.springer.com${bookPDFRelativeURL}")
}

fun downloadAndSaveBook(bookDownloadURL: URL, fullLocalFilePath: Path) {
    Channels.newChannel(bookDownloadURL.openStream()).use { inChannel ->
        FileOutputStream(fullLocalFilePath.toFile()).channel.use { outChannel ->
            print("Saving $bookDownloadURL to $fullLocalFilePath... ")
            outChannel.transferFrom(inChannel, 0, Long.MAX_VALUE)
            println("DONE.")
        }
    }
}

fun main(args: Array<String>) {
    if(args.size != 2) {
        println("Please pass <full_path_to_springer_excel_file> and <full_path_to_download_folder")
        kotlin.system.exitProcess(-1)
    }
    val (excelFile, downloadFolder) = args

    val books = extractBooksFromExcelFile(File(excelFile))

    books.forEach { book ->
        val fullLocalFilePath = deriveFullLocalPathForBook(downloadFolder, book)
        createDirectoriesAndFile(fullLocalFilePath)
        val bookDownloadURL = getBookDownloadURL(book)
        downloadAndSaveBook(bookDownloadURL, fullLocalFilePath)
    }
}


texts:
I have about a hundred Rake tasks that are creating Rails models for me from a legacy datafile. Each task shares some setup and teardown code; all that sets them apart is the code in the middle. For example:

task countries: setup do
  rows = rows_from_file("system/countries", 2)
  bar = RakeProgressbar.new(rows.length)
  info "» Importing countries"
  rows.each do |row|
    Country.new(
      alpha2: row[0],
      name: row[1]
    ).save!
    bar.inc
  end
  bar.finished
end

task telephone_number_types: setup do
  rows = rows_from_file("system/telephone_number_types", 1)
  bar = RakeProgressbar.new(rows.length)
  info "» Importing telephone number types"
  rows.each do |row|
    TelephoneNumberType.new(
      name: row[0]
    ).save!
    bar.inc
  end
  bar.finished
end

task occupations: setup do
  rows = rows_from_file("system/occupations", 3)
  bar = RakeProgressbar.new(rows.length)
  info "» Importing occupations"
  rows.each do |row|
    Occupation.new(
      id: row[1],
      name: row[2]
    ).save!
    bar.inc
  end
  bar.finished
end

How could I extract the progress bar stuff so I don’t keep repeating it? I had thought of writing some generic method that takes the array of rows and some code block (which would contain the Model.new(attrs).save! code) and wraps that stuff with the progress bar stuff, but I can’t quite make it work.


texts: Simple arithmetic operations in MASM using dosbox

texts:
This program does simple arithmetic calculation (+. -, *, /, %) in masm. I've tested the code.

disp_str macro msg     ;print a string
    lea dx, msg
    mov ah, 09h
    int 21h
endm

input macro            ;move values to ax & bx for execution
    call clear_reg
    mov ax, num1
    mov bx, num2
endm

output macro msg, num  ;display numerical values
    disp_str msg
    mov ax, num
    call write
endm

.model small
.stack
.data
    msg1 db 0Ah,0Dh, "Enter the first number > $"
    msg2 db 0Ah,0Dh, "Enter the second number > $"
    msum db 0Ah,0Dh, "Sum = $"
    mdif db 0Ah,0Dh, "Difference = $"
    mprd db 0Ah,0Dh, "Product = $"
    mquo db 0Ah,0Dh, "Quotient = $"
    mrem db 0Ah,0Dh, "Remainder = $"

    num1 dw ?
    num2 dw ?
    temp dw 0
    rslt dw 0

.code
    mov ax, @data
    mov ds, ax
    main proc
        disp_str msg1
        call read
        mov num1, ax

        disp_str msg2
        call read
        mov num2, ax

        input
        add ax, bx
        mov rslt, ax
        output msum, rslt

        input
        sub ax, bx
        mov rslt, ax
        output mdif, rslt

        input
        mul bx
        mov rslt, ax
        output mprd, rslt

        input
        div bx
        mov rslt, ax
        mov temp, dx
        output mquo, rslt
        output mrem, temp

        mov ah, 4Ch
        int 21h
    main endp

    read proc
        mov ax, 00h
        mov cx, 04h
    L1:
        mov dl, 0Ah
        mul dx
        mov temp, ax
        mov ah, 01h
        int 21h
        sub al, 30h
        mov ah, 00h
        mov bx, temp
        add ax, bx
        loop L1
        ret
    read endp

    write proc
        mov bx, 0Ah
        mov cx, 00h
    L2:
        mov dx, 00h
        inc cx
        div bx
        push dx
        cmp ax, 00h
        jne L2
    L3:
        pop dx
        add dl, 30h
        mov ah, 02h
        int 21h
        loop L3
        ret
    write endp

    clear_reg proc    ;clears all the registers
        xor ax, ax
        xor bx, bx
        xor cx, cx
        xor dx, dx
        ret
    clear_reg endp
end

Output:

Also how does the procedure read & write work?


texts: Is_permutation() on sequence containers in O(n) complexity - follow-up

texts:
This question is a continuation of my previous question:

Check is_permutation on a pair of same sized arrays.

I improved the implementation to generalize for all sequence containers. Please let me know how I can improve this implementation again.

#include<iostream>
#include<algorithm>
#include<unordered_map>
#include<array>
#include<list>

template < typename T1 >
std::unordered_map< int, int > count_frequency( T1 first, T1 last )
{
    std::unordered_map< int, int > temp_unordered_map;
    auto temp_unordered_map_end = std::end( temp_unordered_map );
    while( first != last )
    {
        auto it_temp_unordered_map = temp_unordered_map.find( *first );
        if( it_temp_unordered_map == temp_unordered_map_end )
        {
            temp_unordered_map.emplace( *first, 1 );
        }
        else
        {
            ++( it_temp_unordered_map->second );
        }
        ++first;
    }
    return temp_unordered_map;
}

template < typename T1, typename T2 >
bool is_permutation( const T1 first1, const T1 last1, const T2 first2, const T2 last2 )
{
    if( std::distance( first1, last1 ) != std::distance( first2, last2 ) )
    {
        return false;
    }
    std::unordered_map< int, int > first_map = count_frequency( first1, last1 );
    std::unordered_map< int, int > second_map = count_frequency( first2, last2 );

    std::pair<std::unordered_map< int, int >::iterator,std::unordered_map< int, int >::iterator > myPair=
        std::mismatch( std::begin( first_map ), std::end( first_map ), std::begin( second_map ),
        []( std::pair< const int, int >& seed1, std::pair< const int, int > & seed2)
        { return seed1.second == seed2.second; }
        );

    return  myPair.first == first_map.end() && myPair.second == second_map.end();
}

int main()
{
    const std::array< int, 5> array1 { { 1, 3, 2, 4, 5 } };
    const std::array<int,4> array2 { { 1, 2, 4, 3 } };

    if( ::is_permutation( std::begin( array1 ), std::end( array1 ), std::begin( array2 ), std::end( array2 ) ) )
    {
        std::cout<< " Elements are permutation of each other\n";
    }
    else
    {
        std::cout<< " Elements are not permutation of each other\n";
    }

    const std::vector< int > vec1 { { 1, 3, 2, 4 } };
    const std::vector< int > vec2 { { 1, 2, 4, 3 } };

    if( ::is_permutation( std::begin( vec1 ), std::end( vec1 ), std::begin( vec2 ), std::end( vec2 ) ) )
    {
        std::cout<< " Elements are permutation of each other\n";
    }
    else
    {
        std::cout<< " Elements are not permutation of each other\n";
    }

    const std::list< int > list1 { { 1, 3, 2, 4 } };
    const std::list< int > list2 { { 1, 2, 4, 3 } };

    if( ::is_permutation( std::begin( list1 ), std::end( list1 ), std::begin( list2 ), std::end( list2 ) ) )
    {
        std::cout<< " Elements are permutation of each other\n";
    }
    else
    {
        std::cout<< " Elements are not permutation of each other\n";
    }
    return 0;
}


texts: Deleting a node from a binary search tree

texts:
I have read about it at a few places and tried to write my own version.  I would like to get it reviewed.

class Node {
    private int value;
    private Node left;
    private Node right

    // getters and setters
}

public class DeleteNodeBST {

    Node parent = null;

    boolean deleteNodeBST(Node node, int value) {
        if (node == null) {
            return false;
        }
        if (node.getValue() == value) {

            if ((node.getLeft() == null) && (node.getRight() == null)) {
                // leaf node
                node = null;
                return true;
            }

            if ((node.getLeft() != null) && (node.getRight() != null)) {
                // node with two children
                node.setValue(findMinimumAndReturnWithDelete(node.getRight()));
                return true;
            }

            // either left child or right child
            if (node.getLeft() != null) {
                parent.setLeft(node.getLeft());
                node = null;
                return true;
            }

            if (node.getRight() != null) {
                parent.setRight(node.getRight());
                node = null;
                return true;
            }
        }
        parent = node;
        if (node.getValue() > value) {
            return deleteNodeBST(node.getLeft(), value);
        } else {
            return deleteNodeBST(node.getRight(), value);
        }
    }

    int findMinimumAndReturnWithDelete(Node node) {
        if (node.getLeft() == null) {
            int v = node.getValue();
            node = null;
            return v;
        }
        return findMinimumAndReturnWithDelete(node.getLeft());
    }
}


texts: FizzBuzz example in Python for game manual

texts:
I'm developing an implementation of the FizzBuzz game as part of an edutainment game for a retro video game platform. In its manual, I want to mention the history of writing a bot for the FizzBuzz game as a programmer screening test since Jeff Atwood's blog post, including sample answers in a few popular programming languages. But I don't want to confuse readers with poorly written code.

So is there anything unclear or unpythonic about my approach to FizzBuzz?

# Each of several divisors has a name. For each number,
# print the names of all divisors that divide the number,
# if any.  Otherwise print the number itself.
divs = [
    (3, "fizz"),
    (5, "buzz"),
]
for n in range(1, 101):
    # Make a string containing names of divisors of n
    ndivs = ''.join(name for (divisor, name) in divs
                    if n % divisor == 0)
    # If the string is empty, print the number instead
    print(ndivs or n)


texts:
This code works, but I feel like it's really hacky and could be done a lot better. Can anyone give some advice on how this could be neater?

$scope.arrays = function() {
        $scope.committees = [];
        $scope.employees = [];

        $http({method: 'GET', url: 'data.php'}).success(function(data) {
            angular.forEach(data, function(value, key) {
                $scope.committees.push(value);
            })

            $http({method: 'GET', url: 'data2.php'}).success(function(data){
                angular.forEach(data, function(value, key) {
                    $scope.employees.push(value);
                })
                $scope.arr = new Array();
                for (var i = 0, committee; committee = $scope.committees[i]; i++) {
                    for (var j = 0, employee; employee = $scope.employees[j]; j++) {
                            if (committee.code === employee.code){
                                $scope.arr.push({
                                    "committee" : committee.name,
                                    "color": committee.color,
                                    "members": committee.members,
                                    "femaleAnnual" : employee.femaleAnnual,
                                    "maleAnnual" : employee.maleAnnual,
                                    "totalAnnual" : employee.totalAnnual,
                                })
                            }
                    }
                }
            })
        })
    }

    $scope.arrays();

Edit: Sorry I should have been clearer! What I'm trying to do here is merge 2 arrays if they have the same value for 'code' - and then push that array to the scope.


texts:
I'm doing my first major jQuery development. It's a Widget for recurring events, and is as such a fairly complex beast. The full code is available at https://github.com/collective/jquery.recurrenceinput.js for those who want to check it out. I appreciate any kind of feedback about any part of the code, so anyone who wants to take a look at it, that would be awesome.

I have a couple of specific questions, and it seems best to put them as separate posts, so here is the first one:

Does my directory layout fit with what a jQuery developer would expect? Is it "best practice"?

The directory structure is this (somewhat simplified):

demo // Files to run the demo/tests:
    delete.png
    jquery.recurrenceinput.css
    overlays.css
    undelete.png
    input.html
    jquery.tools.dateinput.css
    pb_close.png

lib // jQuery files:
    jquery-1.4.2.js
    jquery.tmpl-beta1.js
    jquery.tools.dateinput-1.2.5.js
    jquery.tools.overlay-1.2.5.js
    jquery.utils.i18n-0.8.5.js

src // Actual code
    jquery.recurrenceinput.display.js
    jquery.recurrenceinput.form.js
    jquery.recurrenceinput.js

tests // Tests and supporting files

    jslint.js
    qunit.css
    qunit.js
    test.html
    tests.js

README.rst


texts:
This task is taken from Leetcode -

  Given an unsorted array of integers, find the length of the longest
  consecutive elements sequence.

  Your algorithm should run in \$O(n)\$ complexity.

  Example:

Input: [100, 4, 200, 1, 3, 2]

Output: 4

/** Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4. */

My solution

/**
 * @param {number[]} nums
 * @return {number}
 */
var longestConsecutive = function(nums) {
  const set = new Set(nums);
  let longestStreak = 1;
  let max = 0;
  set.forEach(x => {
    if (!set.has(x - 1)) {
      let num = x;
      while(set.has(++num)) { ++longestStreak; }
      max = Math.max(max, longestStreak);
      longestStreak = 1;
    }
  });
  return max;
};

Time complexity is \$O(2n)\$ which is still in the range of \$O(n)\$ time complexity.


texts: Find the closest number to each given number

texts:
I have a program which works but it is a bit too slow with big numbers.

nbBlocs contains the size of the array, it can be up to 20000 and I enter the value inside on each position.

nbQ is the number of queries (at most 20000 queries).  For each query, it looks inside the array and tells me which is the closest value to it (by absolute difference). So, if my array is [0,2,5,11,24,32] and the query is 10, it returns 11 because absolute difference (10-11) is the smallest.

Input example

7                    (size of array)
41 32 11 17 24 8 16  (all the values inside array)
4                    (nbQ)
9 20 28 11           (four queries)

Output

8 17 24 11

Here is my code :

#include <iostream>
#include <cmath>
#include <vector>
#include <algorithm>
using namespace std;

int main(){
    int nbBlocs;
    cin >> nbBlocs;
    int dens;
    std::vector<int> tab(nbBlocs);
    for(int i=0; i<nbBlocs; i++){
        cin >> dens;
        tab[i]=dens;
    }
    sort(tab.begin(), tab.end());
    int nbQ;
    cin >> nbQ;
    int quest;
    for(int j = 0; j<nbQ; j++){
        cin >> quest;
    int valSup=-1;
    int valInf=-1;
    int reponse=-1;
        for(unsigned int i=0;i<tab.size();i++){
            if(quest < tab[i]){
                    valSup = tab[i];
                if(i!=0)
                        valInf = tab[i-1];
                    else
                         valInf = valSup;
                }

        if(i==(tab.size()-1) && valSup == -1){
            valSup = tab[tab.size()-1];
            valInf = valSup;
        }
        if(valSup != -1 && valInf != -1){
            if(std::abs(quest - valSup) < (std::abs(quest - valInf))){
                reponse = valSup;
                break;
            }
            else if (std::abs(quest - valSup) == (std::abs(quest - valInf))){
                reponse = valInf;
                break;
            }
            else{
                reponse = valInf;
                break;
            }
        }
    }
        if (reponse != -1)
        cout << reponse << endl;
    }

}


texts:
I am currently reading Uncle Bob's Clean Code and wonder what would be the "cleaner" implementation of the following:

Let's say I want to implement a HTTPRequest class which handles the execution of (well, obviously) http requests.

This was my initial implementation:

class HTTPRequest(object):
    def __init__(self, url, method, **kwds):
        self.logger = logging.getLogger(__name__)
        self.url = url
        self.method = method
        self.request_kwds = kwds
        self.execution_time_seconds = 0.0
        self.response = None
        self.logger.debug("Created instance %s" % self)

    def execute(self):
        self.logger.debug("%s starting request" % self)
        start_time = time.time()
        self.response = HTTPResponse(
            request=self,
            request_response=requests.request(url=self.url, method=self.method, **self.request_kwds)
        )
        self.execution_time_seconds = time.time() - start_time
        self.logger.debug(
            "%s received response %s after %.4f seconds" % (self, self.response, self.execution_time_seconds)
        )
        self.response.raise_for_status()
        return self.response

The execute method currently does two things: issuing the request and capturing the response, and measuring the execution time.
So first of all, this would be a violation of the Single Responsibility Principle.
Furthermore, it is very detailed and on a low level of abstraction.

Now, I could split this up in different sub methods, like this:

class HTTPRequest(object):
    def __init__(self, url, method, **kwds):
        self.logger = logging.getLogger(__name__)
        self.url = url
        self.method = method
        self.request_kwds = kwds
        self._start_time = 0
        self.execution_time_seconds = 0.0
        self.response = None
        self.logger.debug("Created instance %s" % self)

    def execute(self):
        self.logger.debug("%s starting request" % self)
        self._start_time_measurement()
        self._execute_request()
        self._stop_time_measurement()
        self.logger.debug(
            "%s received response %s after %.4f seconds" % (self, self.response, self.execution_time_seconds)
        )
        return self.response

    def _start_time_measurement(self):
        self._start_time = time.time()

    def _execute_request(self):
        self.response = HTTPResponse(
            request=self,
            request_response=requests.request(url=self.url, method=self.method, **self.request_kwds)
        )
        self.response.raise_for_status()

    def _stop_time_measurement(self):
        self.execution_time_seconds = time.time() - self._start_time

Besides having separated the logic of time measurement and request execution, from what I've read so far this version should be considered "cleaner".

But I have two concerns about it:

This class is still extremely simple. This refactoring made it significantly longer (replacing two single line statements with a call to a function which takes up two lines (+1 for spacing). Doing this kind of refactoring to a "real" class with a lot of business logic could blow it up indefinitely (which is then again considered "unclean")
The original version was - in my eyes - already readable enough, as it used intention-revealing names for the variables, making it clear that there is some kind of time measurement going on during the request.

So the question is:
which version do you prefer, and why? How much extraction of logic into sub methods is too much?

For the sake of completeness, here is a (stripped down version of) the HTTPResponse class and necessary imports to make the code executable:

import time
import logging

import requests

class HTTPResponse(object):
    def __init__(self, request, request_response):
        self.request = request
        self._response = request_response

    def raise_for_status(self):
        self._response.raise_for_status()

class HTTPRequest(object):
    # one of the two versions from above


texts:
I have a query consisting of UNIONs.

 SELECT CONCAT("You sent track request to ",u.username) AS ACTION, h.`dateTime`  FROM login_user u
LEFT JOIN
history h ON u.id = h.`toUserId` WHERE h.`fromUserId`=28 AND h.`Action`="Request"
UNION
SELECT CONCAT("You Accepted track request from ",u.username) AS ACTION, h.`dateTime`  FROM login_user u
LEFT JOIN
history h ON u.id = h.`toUserId` WHERE h.`fromUserId`=28 AND h.`Action`="Accept"
UNION
SELECT CONCAT("You Denied track request from ",u.username) AS ACTION, h.`dateTime`  FROM login_user u
LEFT JOIN
history h ON u.id = h.`toUserId` WHERE h.`fromUserId`=28 AND h.`Action`="Deny"
UNION
SELECT CONCAT(u.username, " sent you Track Request") AS ACTION, h.`dateTime`  FROM login_user u
LEFT JOIN
 history h ON u.id = h.FromUserId WHERE h.`toUserId`=28 AND h.`Action`="Request"
  UNION
 SELECT CONCAT(u.username, " accepted your track request") AS ACTION, h.`dateTime`  FROM login_user u
 LEFT JOIN
 history h ON u.id = h.`fromUserId` WHERE h.`toUserId`=28 AND h.`Action`="Accept"
 UNION
 SELECT CONCAT(u.username, " Denied your track request") AS ACTION, h.`dateTime`  FROM login_user u
 LEFT JOIN
 history h ON u.id = h.`fromUserId` WHERE h.`toUserId`=28 AND h.`Action`="Deny"

Since all the constituent queries are almost same, I was wondering if I can use CASE or something to shorten and optimize the query?


texts:
I have REST API written on laravel and front end on vue.js. It is a dashboard for an ecommerce store where you can connect to post shipment service API to upload order shipment data and get tracking number (with .png label). So after I receive tracking number label from post service API I need possibility to show it in front end from the REST API response.

I have route on front end shipments/:id/tracking/label which should show some shipment data and tracking label image.

I got 2 solutions for this. Which is better and why?

Send image content as base64 string and shipment data in one backend route GET shipments/{id}/tracking/label

Backend

    public function getTrackingLabel(Shipment $shipment, LabelIsraelPostService $service)
    {
        $data = [
            'label' => $service->getTrackingLabel($shipment->label_path),
            'shipment' => $shipment
        ];

        return response()->json(['shipment' => $data]);
    }

Frontend

    <v-card>
        <v-card-title>
            Order id : {{ shipment.order_id }}
        </v-card-title>

        <v-img
            max-width="700"
            :src="`data:image/png;base64,${shipment.link}`"
        >
        </v-img>
    </v-card>

Use 2 different backend routes GET shipments/{id} for all shipment data and another one for only image GET shipments/{id}/tracking_label which will return image with headers.

Backend

For get all shipment data

    public function show(Shipment $shipment)
    {
        return response()->json(['shipment' => $shipment])
    }

For get shipment tracking label image

    public function getTrackingLabel(Shipment $shipment, LabelIsraelPostService $service)
    {
        return response(Storage::cloud()->get($path))->header('content-type', 'image\png')
    }

Front end

    <v-card>
        <v-card-title>
            Order id : {{ shipment.order_id }}
        </v-card-title>

        <v-img
            max-width="700"
            :src="`${BASE_API_URL}/shipments/${shipment.id}/tracking/label`"//or use axios for this request
        >
        </v-img>
    </v-card>

Which will upload the image in a browser from the API route and send another request to get all shipment data and show it on the front end.

I like solution #2 but if I will have 10 shipments for show tracking number label, I will have 10 api calls for get image for each of them, and also one for get array of shipments data by ids. In solution #1 I can get only one API call for all shipments with data and base64 image for each of them.

What is best practice to send image as the REST API response and show it with JS front end?


texts: Rebol View layout compose, seek minima notation

texts:
I am attempting to break down a Rebol View into a Forth style 'divide and conquer' word set, to optimize readability and organization, and to segregate the business logic from the view layout inner workings.

Business intelligence

Field

declaration
initialization
processing

Software intelligence

view layout

Is there a way to simplify the following code?

    REBOL[]

    Result: "Test"

    field1.Process: [
                alert join  "You typed: "
                Result: field1/text
                ]

    field1.Initialize: [do [field1/text: Result]]

    field1.Declare: compose/deep [
            field1: field
            [(field1.Process)]
            (field1.Initialize)
        ]

    block:     compose [
            (field1.Declare)
            field
            field
            ]

    view layout (block)

Layout block structure being

field: field-type [field-process]     [field-initialize]

I seek to optimize notation

field1.Process: []
field1.Initialize: [do []]

field1.Declare: compose/deep [
        field1: field
        [(field1.Process)]
        (field1.Initialize)
    ]

Towards minima

field1.Process: []
field1.Initialize: []

field1.Declare: compose/deep [
        field1: field
        [field1.Process]
        [field1.Initialize]
    ]


texts: Find and print all prime numbers (less than 10000)

texts:
I want to improve my JS skills by doing challenges. My current challenge is: Write a script which allow user to enter number and then print all prime numbers from 0 to that number.

const PrimeFinder = (function() {

  const PRIMES = [];
  const MAX_RANGE = 10000;

  // cache DOM
  const EL_FIND = document.getElementById('find');
  const EL_RESULT = document.getElementById('result');
  const EL_SEARCH = document.getElementById('search');

  // bind events
  EL_FIND.addEventListener('click', findPrimes);

  function _renderResult() {
    for (let i = 0; i < PRIMES.length; i++) {
      const EL_PRIME = EL_RESULT.appendChild(document.createElement('div'));
      EL_PRIME.textContent = PRIMES[i];
    }
  }

  function _resetResult() {
    PRIMES.length = 0;
    EL_RESULT.textContent = '';
  }

  function _validUserInput(N) {
    return !isNaN(parseFloat(N)) &&
      isFinite(N) &&
      N >= 0 &&
      N <= MAX_RANGE;
  }

  function isPrime(n) {
    let start = 2;
    while (start <= Math.sqrt(n)) {
      if (n % start++ < 1) return false;
    }
    return n > 1;
  }

  function findPrimes(val) {
    const USER_INPUT = (typeof val === 'number') ? val : EL_SEARCH.value;
    _resetResult();

    if (_validUserInput(USER_INPUT)) {
      for (let i = 2; i <= USER_INPUT; i++) {
        if (isPrime(i)) PRIMES.push(i);
      }
      _renderResult();

      return PRIMES;
    }
  }

  const publicAPI = {
    isPrime: isPrime,
    findPrimes: findPrimes
  }

  return publicAPI;

})();
body,
html {
  padding: 0;
  margin: 0;
}

.container {
  max-width: 320px;
  margin: 0 auto;
}

#search,
#find {
  background: #fff;
  color: #000;
  height: 26px;
  line-height: 26px;
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  border: 1px solid #666;
}

#find {
  width: 120px;
}

#search {
  width: 190px;
}

#result {
  margin: 10px 0;
}

#result>div {
  width: 20%;
  float: left;
  box-sizing: border-box;
  text-align: center;
  color: #fff;
  line-height: 48px;
  background: coral;
  border: 2px solid #fff;
}

#result div:hover {
  background-color: red;
}

Prime Number Finder

  <input placeholder="" id="search" type="number">
  <button id="find">Find</button>

I would like to know what could be done better and why.


texts:
I have a repository called PostsRepository:

public class PostsRepository : IPostsRepository
{
    private readonly DatabaseContext context = new DatabaseContext();

    public IEnumerable<Post> All()
    {
        return
            context.Posts
                   .OrderBy(post => post.PublishedAt);
    }

    public IEnumerable<Post> AllPublishedPosts()
    {
        return
            context.Posts
                   .OrderBy(post => post.PublishedAt)
                   .Where(post => !post.Draft);
    }

    public Post Find(string slug)
    {
        return context.Posts.Find(slug);
    }

    public void Create(Post post)
    {
        post.Slug = SlugConverter.Convert(post.Slug);
        post.Summary = Summarize(post.Content);
        post.PublishedAt = DateTime.Now;
        AttachTags(post);

        if (context.Posts.Find(post.Slug) != null)
        {
            throw new Exception("tag already exists. choose another.");
        }

        context.Posts.Add(post);
        context.SaveChanges();
    }

    public void Update(Post post)
    {
        post.Slug = SlugConverter.Convert(post.Slug);
        post.Summary = Summarize(post.Content);
        AttachTags(post);

        if (context.Posts.Find(post.Slug) != null)
        {
            throw new Exception("tag already exists. choose another.");
        }

        context.Posts.Add(post);
        context.SaveChanges();
    }

    public void Delete(Post post)
    {
        context.Posts.Remove(post);
        context.SaveChanges();
    }

    private void AttachTags(Post post)
    {
        foreach (var tag in post.Tags)
        {
            if (context.Tags.Any(x => x.Name == tag.Name))
            {
                context.Tags.Attach(tag);
            }
        }
    }

    private static string Summarize(string content)
    {
        // contrived.
        return content;
    }
}

I am worried that I might have wound up with a design that is not very testable as it is not apparent to me how to test this code.

I am going to ask another question on SO as to how to unit test this class soon but before I peruse this implementation I would like to ask that you please review my repository implementation.

Particular areas of concern:

Testability
I have read countless opinions about what a repository should do. Are there any pragmatic reasons why my implementation might be bad?
The PostsRepository needs to access the Tags database set. Am I allowing this in the correct way? Know that I plan to implement a TagsRepository in the future.
I throw an exception when the slug (which must be unique) is occupied. Should I return a bool to indicate failure instead? Would this not violate the command-query segregation principle?
I am aware that the Update method is hard to reason about and I am working on that. It is for this reason that my code does not currently adhere to DRY.


texts:
I'm learning the ropes of Java. So far everything is going good. Can you please review my code and tell me what I can do to make it cleaner - or what I need to improve on?. I'll appreciate it so much.
This program:
The user inputs are the gross income and number of dependents. The program calculates the income tax based on the inputs and the tax law and then displays the income tax.
Here's a screen shot of the code in the IDE and a flowchart.
(IDE)

(Flowchart)

import java.util.*;
public class lab4 {
    public static void main(String args[]) {
        Scanner input = new Scanner(System. in);

        System.out.println("Enter gross income: ");
        double grossIncome;
        grossIncome = input.nextDouble();

        System.out.println("Enter the number of dependents: ");
        double dependents;
        dependents = input.nextDouble();

        final double TAX_RATE = 0.2;
        final double STANDARD_DEDUCTION = 10000.00;
        final double DEPENDENT_DEDUCTION = 2000.0;
        final double grossIncomeafterdeduction = grossIncome - (STANDARD_DEDUCTION + DEPENDENT_DEDUCTION * dependents);

        double incomeTax;
        incomeTax = grossIncomeafterdeduction * TAX_RATE;

        double grossincometax;
        grossincometax = grossIncome - incomeTax;

        System.out.println("The income tax is $ " + incomeTax);

        System.out.println("The gross income after tax $ " + grossIncometax);
    }
}


texts:
I was tinkering around with C++ after about 3 days of learning and decided to make a random phone number generator.

This is the code I came up with

#include <iostream>
#include <string>
#include <ctime>
#include <cstdlib>

using namespace std;
int getrandomdigit();

int main()
{
    srand(time(NULL));
    string input;
    int digit1_1;
    int digit1_2;
    int digit1_3;

    int digit2_1;
    int digit2_2;
    int digit2_3;
    int digit2_4;

    cout << "Enter three digits(area code): ";
    getline(cin, input);
    cout << "\n";
    cout << "\tAvailable numbers in your area.";
    cout << "\n\t******************************";

    cout << "\n\n";

    for(int i = 0; i < 10; ++i)
        cout << "\nPhone number: " << input << "-" << getrandomdigit() << getrandomdigit()
        << getrandomdigit() << "-" << getrandomdigit()
        << getrandomdigit() << getrandomdigit() << getrandomdigit();

    cout<<"\n";
    return 0;

}

int getrandomdigit()
{
    return rand() % 10;
}

So I believe I understand the logic of how the random number generation works. But before I added the function getrandomdigit(), I was using the manually defined "digit" vars in an attempt to generate pseudorandom numbers. So my question remains, why does it occur when you use the integers that the numbers AREN'T randomly generated. For instance, if you were to enter an area code, it would just print the same 2 prefixes 10 times, but when you use the function, it gives you a completely random var every time the counter is run until 10.

Here's a visual example of using the digit vars

Enter three digits(area code): 203

        Available numbers in your area.
        ******************************

Phone number: 203-523-3023
Phone number: 203-523-3023
Phone number: 203-523-3023
Phone number: 203-523-3023
Phone number: 203-523-3023
Phone number: 203-523-3023
Phone number: 203-523-3023
Phone number: 203-523-3023
Phone number: 203-523-3023
Phone number: 203-523-3023

Then here is an example of using the getrandomdigit function

Enter three digits(area code): 203

        Available numbers in your area.
        ******************************

Phone number: 203-696-3428
Phone number: 203-832-2940
Phone number: 203-293-9390
Phone number: 203-483-3935
Phone number: 203-616-6955
Phone number: 203-089-8674
Phone number: 203-953-6456
Phone number: 203-516-2123
Phone number: 203-800-7836
Phone number: 203-624-7130


texts:
Expression trees are the bread and butter of functional programming but when it comes to adding additional information to an established tree it can be difficult to incorporate such changes without breaking the existing interface. I have attempted to solve the problem with this example which demonstrates two different enhancements with a common evaluation function.

Comments would be appreciated on the overall structure and especially the ASTBuilder instance for ExpLine which currently relies on UndecidableInstances and the definition of removeHoles.

> {-# LANGUAGE DeriveFunctor, ViewPatterns,  PatternSynonyms, GeneralizedNewtypeDeriving, MultiParamTypeClasses, FlexibleInstances, FunctionalDependencies, FlexibleContexts, UndecidableInstances #-}

> import Control.Monad.State
> import Control.Applicative

The basic parameterised type

> data ExpF a =
>     AddF a a
>   | NumF Int deriving (Show, Functor)
>
> data Exp  = Exp (ExpF Exp) deriving (Show)
> data ExpH = Holey (Either Hole (ExpF ExpH)) deriving (Show)
> data ExpLine = Line Int (ExpF (ExpLine)) deriving (Show)
>
> data Hole = Hole deriving (Show)

View Typeclass. There isn't an instance which makes sense for ExpH

> class ASTView a where
>   view :: a -> ExpF a
>
> instance ASTView Exp where
>   view (Exp x) = x
>
> instance ASTView ExpLine where
>   view (Line _ x) = x

Generic pattern matches - note that we maintain the interface!

> pattern Add a b <- (view -> (AddF a b))
> pattern Num n <- (view -> (NumF n))

Building type class

> class ASTBuild a  where
>   construct :: ExpF a -> a
>
> instance ASTBuild Exp where
>   construct x = Exp x
>
> instance MonadState Int m => ASTBuild (m ExpLine)  where
>   construct (AddF a b) = do
>     n <- get
>     a' <- a
>     b' <- b
>     return $ (Line n (AddF a' b'))
>   construct (NumF v) = do
>     n <- get
>     inc
>     return $ (Line n (NumF v))
>
> inc :: MonadState Int m => m ()
> inc = modify (+1)
>
> instance ASTBuild ExpH where
>   construct = Holey . Right

Generic Constructors, direct drop in for functions in the builder

> add :: ASTBuild f => f -> f  -> f
> add a b = construct (AddF a b)
>
> num :: ASTBuild f => Int -> f
> num n = construct (NumF n)

Examples

1. Normal

> example1 :: Exp
> example1 = (num 5) `add` (num 6)

2. Holey - Allows you to leave holes in the structure to fill in later.
This could be a direct replacement to the fmonad.

> holeExample :: ExpH
> holeExample = add (num 6) hole
>
> example2 :: Exp
> example2 = removeHoles holeExample
>
> hole :: ExpH
> hole = Holey (Left Hole)
>
> removeHoles :: ExpH -> Exp
> removeHoles (Holey (Left Hole)) = num 5
> removeHoles (Holey (Right k)) = recurse removeHoles k

> -- This is a fold
> recurse :: (a -> Exp) -> ExpF a -> Exp
> recurse f (AddF e1 e2) = add (f e1) (f e2)
> recurse _ (NumF n) = num n

3. Adding additional information is also easy, this example labels each leaf with a unique number. Could be used for attrs on every node or keeping track of line numbers.

> leafCounter :: State Int ExpLine
> leafCounter = add (num 5) (num 6)
>
> example3 :: ExpLine
> example3 = evalState leafCounter 0

All 3 examples are then evaluated with the same function

> eval :: (ASTView v) => v -> Int
> eval (Add a b) = eval a + eval b
> eval (Num n) = n
>
> main :: IO ()
> main =
>   do
>     print (eval example1)
>     print (eval example2)
>     print (eval example3)


texts: Implementing factory design pattern with generics

texts:
In this new project I'm working on I need to create objects on runtime by data from the DB, right now I have two groups of classes, each group implementing a different interface.

I started working on a factory class, which will map id to a type, an abstract one so I can extend with a factory for each group.

The constructor parameter is the type of the interface common to all implementors of the group.

abstract class Factory
   {
    private Dictionary<int, Type> idsToTypes;
    private Type type;

    public Factory(Type _type)
    {
        idsToTypes = new Dictionary<int, Type>();
        type = _type;
    }

    protected Object GetProduct(int id, params object[] args)
    {
        if (idsToTypes.ContainsKey(id))
        {
            return Activator.CreateInstance(idsToTypes[id], args);
        }
        else
        {
            return null;
        }
    }

    public void RegisterProductType(int id, Type _type)
    {
        if (_type.IsInterface || _type.IsAbstract)
            throw new ArgumentException(String.Format("Registered type, {0}, is interface or abstract and cannot be registered",_type));

        if (type.IsAssignableFrom(_type))
        {
            idsToTypes.Add(id, _type);
        }
        else
        {
            throw new ArgumentException(String.Format("Registered type, {0}, was not assignable from {1}",_type,type));
        }

    }

Then I noticed both extending factories look the same, and in the end with the use of generics I got to this class:

 class GenericSingletonFactory<T> : Factory
    {
        static public GenericSingletonFactory<T> Instance = new GenericSingletonFactory<T>();

    private GenericSingletonFactory()
        : base(typeof(T)) { }

    public T GetObject(int id, params object[] args)
    {
        Object obj = base.GetProduct(id, args);
        if (obj != null)
        {
            T product = (T)obj;
            return product;
        }
        else return default(T);
    }
}

So I can just use like so:

GenericSingletonFactory<ISomething>.Instance.RegisterProductType(1, typeof(ImplementingISomething));
ISomething something = GenericSingletonFactory<ISomething>.Instance.GetObject(1);

It seems ok... but am I missing something here? is this a good way to do this kind of things?
I'm a little weary that this will fall apart on runtime somehow...


texts:
Given a number, for example, \$6\$, this Python function should print hashes in the following format:

     #
    ##
   ###
  ####
 #####
######

This is the function used to accomplish this:

def hash_print(number):
    for i in range(number):
        hashes='#' *(i+1)
        spaces=' '*(number -(i+1))
        print("%s%s") %(spaces,hashes)

Is there any way that this can be improved?


texts: Proper implementation of generic repository

texts:
What can be done better in this code?  I am sure it's not missing much.

You can copy and paste the whole thing in LinqPad; it's all there.

public interface IRep<T>
{
    List<T> GetAll();
}

public interface IEntity
{
    int Id{get;set;}
}

public class Customer: IEntity
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
}

public class Product: IEntity
{
    public int Id { get; set; }
    public string Code { get; set; }
    public decimal Price {get;set;}
}

public class RepProduct: IRep<Product>
{
    public List<Product> GetAll()
    {
        List<Product> list = new List<Product>();
        list.Add(new Product() {Id=1, Code = "burger", Price = 2.99M});
        list.Add(new Product() {Id=1, Code = "fries", Price = 1.99M});
        list.Add(new Product() {Id=1, Code = "pepsi", Price = 1.99M});
        return list;
    }
}

public class RepCustomer: IRep<Customer>
{
    public List<Customer> GetAll()
    {
        List<Customer> list = new List<Customer>();
        list.Add(new Customer() {Id=1,Name="Fred", Age=44   });
        list.Add(new Customer() {Id=2,Name="Victoria", Age=13   });
        list.Add(new Customer() {Id=3,Name="Kiefer", Age=10 });
        return list;}
}

void Main()
{

    IRep<IEntity> rep = null;

}


texts: Find elements occurring even number of times in an integer array

texts:
I came across an interview question, which is like this:

  You have an array of integers, such that each integer is present an odd number of time, except 3 of them. Find the three numbers.

I tried implementing it using a HashMap<Integer, Integer>, by mapping each integer element to a number that would identify if that number occurs even number of times. I used the XOR logic for that. 5 ^ 5 = 0, and 5 ^ anyNumberOtherThan5 != 0.

Here's my code:

public static void findEvenOccurringNum(int[] arr) {
    Map<Integer, Integer> map = new HashMap<Integer, Integer>();

    for (int num: arr) {
        if (map.containsKey(num)) {
            map.put(num, map.get(num) ^ 1);
        } else {
            map.put(num, 1);
        }
    }

    for (Entry<Integer, Integer> entry: map.entrySet()) {
        if (entry.getValue() == 0) {
            System.out.println(entry.getKey());
        }
    }
}

What I don't like about this solution is the 2nd iteration. That would iterate over all the unique numbers in the array. Can there be any possible improvement here? May be a solution that avoids using a map? Or is it the best I can do?


texts:
I am trying to get my head around exceptions, and implement exception handling that ultimately gets logged, since my code runs as a remote job and reviewing a txt log is the best means of reviewing results. Currently I have an issue where "unexpected" exceptions only show up in the console, so my focus right now is dealing with that.

So... here I have a first pass at trying to catch an unexpected exception and provide output that shows me script name and line, the exception message, and the exception type so I can potentially go back and add "expected" exception handling by specific type, and log those slightly differently.

class PxUnexpectedException : Exception {
    #PxUnexpectedException() {}
    PxUnexpectedException([string] $message) : base($message) {}
    #PxUnexpectedException([string] $message, [Exception] $inner) : base($message, $inner) {}

    static [array] ReviseTrace ([string]$path, [array]$trace) {
        $scriptPath = ", $(Split-Path $path -parent)\"
        $revisedTrace = $trace -replace [Regex]::Escape($scriptPath), ' in '
        return $revisedTrace
    }
}

function Test ($path) {
    try {
        Test-Path $path -errorAction:stop > $null
    } catch {
        # Standard Px error trap
        $trace = [PxUnexpectedException]::ReviseTrace($_.InvocationInfo.ScriptName, $_.ScriptStackTrace)
        throw [PxUnexpectedException] "[$($_.Exception.GetType().fullname)] $($_.Exception.Message)`n$trace"
    }
}

function ConvertException ([Exception]$exception) {
    foreach ($line in ($exception.Message -split "`n")) {
        Write-Host "$line" -ForegroundColor:red
    }
}

CLS
$path = '\\Server\InvalidFolder|'
try {
    Test $path
} catch [PxUnexpectedException] {
    ConvertException $_.Exception
}

My issue at this point is all the work needed to get a good message for throw [PxUnexpectedException]. I will have this same two lines (the $trace = and the throw) perhaps hundreds of times, and it feels like I SHOULD be able to instantiate my own exception but pass the entire error item to my constructor. Something like throw [PxUnexpectedException] $_ and handle creating the message within the constructor.

Am I really getting this all wrong? Or is duplication of code just the way this will have to be done?
Also, in the .NET examples I have adapted my class from, all three constructors are there. But it seems to me that, assuming this IS the only way to build the message, the only constructor I will ever need is the one that takes the single $message argument, so simplification is best hear. Am I missing something and not having all three constructors is really going to come back to bite me?


texts:
I wrote a method that takes an array T[] array (T is a type parameter) and a second array int[] indices. The method should remove those entries from array, whose indices are stored in indices. Then, the resulting array will be "returned" as an out-parameter T[] rest. Finally, there is a second out parameter T[] removed that contains the removed items.

public static void RemoveViaIndex<T>(this T[] array, int[] indices, out T[] rest, out T[] removed)
{
    int arrayLength = array.Length;
    int indicesLength = indices.Length;

    if (indicesLength == 0 || arrayLength == 0)
    {
        rest = array;
        removed = new T[0];
        return;
    }

    rest = new T[arrayLength - indicesLength];
    removed = new T[indicesLength];

    int copyBegin = 0;
    int copyEnd = -1;

    // We will only iterate over the index-array once
    // Therefore, the indices have to be in ascending order
    Array.Sort(indices);

    for (int indexForIndices = 0; indexForIndices < indicesLength; indexForIndices++)
    {
        // Copying elements in a chunk that ends at the
        // next index that has to be removed
        copyEnd = indices[indexForIndices];
        Array.Copy(sourceArray: array, sourceIndex: copyBegin,
            destinationArray: rest, destinationIndex: copyBegin - indexForIndices,
            length: copyEnd - copyBegin);
        removed[indexForIndices] = array[copyEnd];
        copyBegin = copyEnd + 1;
    }

    if (copyEnd < arrayLength - 1)
    {
        // Copy the final chunk that the loop did not take (if there is one)
        Array.Copy(array, copyBegin, rest, copyEnd - indicesLength + 1, arrayLength - copyBegin);
    }
}

I am assuming that all the indices in same-named array are valid indices for array. Are there any further border cases that I did not cover?

Furthermore, I wonder if this way is faster than an if statement that is contained within a for loop that iterates over the source array since the if-currentIndex-in-indices-then-remove branch disappears:

for (*every index in source*)
{
    if (*current-index-in-indices-to-remove*)
    {
        *remove-and-put-to-target-array*
    }
}


texts: React mixin to declaratively get Bacon.js event steams

texts:
I wrote a mixin to declaratively get a Bacon.js event stream.  So instead of onChange={this.handleChange}, you can do changeStream={this.handleStream}, and this.handleStream will be passed an onChange Bacon.js event stream.  My big concern is that I have to override React.createElement in order to make it work.  I'm wondering how hacky/dangerous this is.

function pushToStream(handlerFn, event) {
   event.persist();
   handlerFn.__stream.push(event);
 }

 function getEventFromStreamName(prop) {
   var match = prop.match(/(\w+)Stream$/);
   if (!match || !match[1]) return null;
   return 'on' + capitalize(match[1]);
 }

 function capitalize(s) {
   return s && s[0].toUpperCase() + s.slice(1);
 }

 var BaconMixin = {
   componentWillMount: function() {
     if (React.createElement.__custom) return;

     var _createElement = React.createElement;
     React.createElement = function(el, props) {
       Object.keys(props || {}).forEach(function(prop) {
         var eventName = getEventFromStreamName(prop);
         if (!eventName) return;

         var handlerFn = props[prop];
         var context = handlerFn.__reactBoundContext;

         handlerFn.__stream = handlerFn.__stream || new Bacon.Bus();
         handlerFn.__pushFn = handlerFn.__pushFn || pushToStream.bind(null, handlerFn);

         props[eventName] = handlerFn.__pushFn;
       });

       return _createElement.apply(this, arguments);
     }

     React.createElement.__custom = true;

     return {};
   },
   componentDidMount: function() {
     var self = this;
     Object.keys(this).forEach(function(prop) {
       if (self[prop] && self[prop].__stream) {
         self[prop](self[prop].__stream);
       }
     });
   },
   componentWillUnmount: function() {
     var self = this;
     Object.keys(this).forEach(function(prop) {
       if (self[prop] && self[prop].__stream) {
         self[prop].__stream.end();
       }
     });
   }
 }

 /* Usage:

 var UsernameInput = React.createClass({

   mixins: [BaconMixin],

   searchAvailability: function(eventStream) {
    // eventStream is a Bacon.Bus instance
     eventStream
       .debounce(500)
       .map('.target.value')
       .makeAjaxRequest
       .onValue(function(isAvailable) {
         // update state
       }.bind(this));
   },

   render: function() {
     return (

         Username:
         <input type="text" name="username" keyUpStream={this.searchAvailability} />

     );
   }
 });

 React.render(<UsernameInput />, document.body);

*/


texts:
I made this random password script. It works, but i think it is kind of bloated. The part where random characters are being added is the area where I think it needs work. I don't want to declare if and else statement for every combination of lowercase list, uppercase list and digits list(I am taking input from user whether they want uppercase,lowercase,digits or any possible combination of these three). Is there any possible way in which I can just check which of these three values are yes and then just use only those.
 Also what is more efficient using lower() to turn the list called using string module into lower case or just calling the lowercase list itself.
import random
from  string import ascii_letters ,digits
while True:
    userchoice_size = int(input("Enter the length of the password : ")) # Asks for length of password
    userchoice_syntax_lower = input("Do you want lower case letter?(y or n) ")
    userchoice_syntax_upper = input("Do you want upper case letter?(y or n) ")
    userchoice_syntax_number = input("Do you want numbers?(y or n) ")
    counter=0
    password='' # String which stores the password
    choice_list=[1,2,3]
    while counter <= userchoice_size:
        choice_number = random.choice(choice_list)
        if choice_number == 1:
            if userchoice_syntax_upper == 'y': # Uppercase list
                password = password + str(random.choice(ascii_letters.upper()))
                counter += 1
        if choice_number == 2:
            if userchoice_syntax_number=='y': # Digits list
                password = password + str(random.choice(digits))
                counter += 1
        if choice_number == 3:
            if userchoice_syntax_lower == 'y': # Lower case list
                password= password + str(random.choice(ascii_letters.lower())) # Converts all letters into lowercase then randomly select and store in list
                counter += 1
    print (password)


texts: Accessing an unreturned list within a function in Python without disturbing Scipy

texts:
Here is the code I'm working on. I'm trying to find the optimum alpha value to get the minimum MAE/MAD. With scipy.optimize, it works quite well. However, when scipy.optimize achieves the optimum alpha, it also achieves the forecast values that essentially I'm trying to get to. Is there a way to return or access and store those forecast values named yPredList without disturbing the work scipy.optimize is doing? Because otherwise I'm going to have to do the forecast calculations from scratch, which is unnecessary. Thanks.

import scipy.optimize as spop
ObservedSpeeds = [85, 64, 97 ,82, 12, 30, 47, 20, 45, 90, 60, 42, 50, 67, 28] #This is not the actual dataset, I actually have a data set of 525,600.
def ErrorCalc(alpha,ObservedSpeeds):
    yPredList = [0,ObservedSpeeds[0]] #First prediction is 0 and the second prediction is the first observation
    for iters in range(2,len(ObservedSpeeds)):
        yPredList.append(np.multiply((1-alpha),yPredList[iters-1]) + np.multiply(alpha,ObservedSpeeds[iters-1]))
    NewList = [np.abs(y-o) for y,o in zip(yPredList,ObservedSpeeds)]
    NewError = np.mean(NewList)
    return NewError

result = spop.minimize_scalar(ErrorCalc,bounds=[0,1],args=ObservedSpeeds,method='bounded')
alpha = result.x


texts:
For Prof. Yorgey's 2013 Haskell course, I'm working on a homework to simulate a Risk battle.

type Army = Int

data Battlefield = Battlefield { attackers :: Army, defenders :: Army }
                    deriving (Show, Eq)

In addition, Prof. Yorgey implement the following code to simulate the random throwing of dice:

newtype DieValue = DV { unDV :: Int }
  deriving (Eq, Ord, Show, Num)

first :: (a -> b) -> (a, c) -> (b, c)
first f (a, c) = (f a, c)

instance Random DieValue where
  random           = first DV . randomR (1,6)
  randomR (low,hi) = first DV . randomR (max 1 (unDV low), min 6 (unDV hi))

die :: Rand StdGen DieValue
die = getRandom

The second homework question asks to implement the battle function:

  which simulates a single battle (as explained above) between two
  opposing armies. That is, it should simulate randomly rolling the
  appropriate number of dice, interpreting the results, and updating the
  two armies to reflect casualties. You may assume that each player will
  attack or defend with the maximum number of units they are allowed.

And then for my implementation:

battle :: Battlefield -> Rand StdGen Battlefield
battle bf = return $ battleOneRound bf

battleOneRound :: Battlefield -> Battlefield
battleOneRound bf = updateArmy bf (compete a_dice d_dice)
  where
    a_dice = rollDieN . getLegalAttackers $ (attackers bf)
    d_dice = rollDieN . getLegalDefenders $ (defenders bf)

rollDieN :: Army -> [DieValue]
rollDieN n
  | n <= 0     = []
  | otherwise = evalRand die (mkStdGen (1000*n)) : rollDieN (n-1)

type AttackersDice = [DieValue]
type DefendersDice = [DieValue]

-- defender must have at least 2 left at base
getLegalDefenders :: Army -> Army
getLegalDefenders n
  | n >= 4    = 2
  | n == 3    = 1
  | otherwise = 0

-- attackers must have at least 1 left at base
getLegalAttackers :: Army -> Army
getLegalAttackers n
  | n >= 4    = 3
  | n == 3    = 2
  | n == 2    = 1
  | otherwise = 0

Testing

ghci> let bf = battle $ Battlefield 10 20

ghci> (evalRand bf) $ mkStdGen 10
Battlefield {attackers = 8, defenders = 20}

ghci> (evalRand bf) $ mkStdGen 5
Battlefield {attackers = 8, defenders = 20}

ghci> (evalRand bf) $ mkStdGen 444444
Battlefield {attackers = 8, defenders = 20}

As you can see, the actual StdGen argument does not appear to have any impact on the battle results. That's because rollDieN uses mkStdGen (1000*n) to simulate random die throws.

Please critique this implementation. I'm not sure if I've achieved randomness in the battle function.


texts:
I have been playing around with numpy and matplotlib.
My little project was to create a scatter plot ranging from -1 to 1 on both X and Y, but where the shading is done with the XOR scheme.
The following is the code that I have implemented (it is in a cell of a jupyter notebook, hence the trailing ; after plt.scatter):
arr_size = 2000

X = np.random.uniform(low=-1.0, high=1.0, size=(arr_size, arr_size))

colour = np.zeros(arr_size)

for i in range(arr_size):
    if X[0, i] > 0 and X[1, i] < 0:
        colour[i] = 1
    elif X[0, i] < 0 and X[1, i] > 0:
        colour[i] = 1

plt.scatter(X[0], X[1], c=colour);

The output that I generated was:

Which is the desired output.
However, I am on a bit of a campaign to make my numpy code run faster (I am on an ML course and we have been taught to remove for loops wherever possible). Can anyone show me how to make this code more efficient?
Cheers


texts:
I want to associate an error message to a Validator and not have to in the html check for a specific error. aka *ngIf="controls.name.required".  I've seen generic error message helpers that build up an javascript object with an index and a message that goes with that index.  What I want is to actually associate the error message with the validation result.

This only works for ReactiveForms but I'm wrapping the Validator Result and tagging in the message into the ValidationErrors result.

import { ValidatorFn, ValidationErrors, AbstractControl, AsyncValidatorFn } from '@angular/forms';
import { map, filter, take } from 'rxjs/operators';
import { Observable } from 'rxjs';

function isObservable(observerable: ValidationErrors | Observable<ValidationErrors>): observerable is Observable<ValidationErrors> {
  return observerable.pipe && typeof observerable.pipe === 'function';
}

// @dynamic
export class ValidatorHelpers {
  // Validator that wraps another validator and adds a message property to the ValidationErrors payload
  static addMessage(innerValidator: ValidatorFn, message: string | ((validationErrors: ValidationErrors) => string)): ValidatorFn {
    return (control: AbstractControl) => {
      const result = innerValidator(control);
      if (result) {
        if (typeof message !== 'string') {
          const func = message as ((validationErrors: ValidationErrors) => string);
          message = func(result);
        }
        const newObj: ValidationErrors = Object.assign({}, ...Object.keys(result)
          .filter((k) => result[k])
          .map(k => ({ [k]: { ...result[k], message } })));
        return newObj;
      }
      return null;
    };
  }

  static asyncAddMessage(innerValidator: AsyncValidatorFn, message: string | ((validationErrors: ValidationErrors) => string)): AsyncValidatorFn {
    return async (control: AbstractControl) => {
      const innerResult = await innerValidator(control);
      if (innerResult) {
        const getMessage = (errors: ValidationErrors): string => {
          if (typeof message !== 'string') {
            const func = message as ((validationErrors: ValidationErrors) => string);
            return func(errors);
          } else {
            return message;
          }
        };

        const result = (errors: ValidationErrors): ValidationErrors => {
          return Object.assign({}, ...Object.keys(errors)
            .filter(x => errors[x])
            .map(x => ({ [x]: { ...errors[x], message: getMessage(errors), value: control.value } })));
        };
        if (isObservable(innerResult)) {
          return innerResult.pipe(
            filter(x => Boolean(x)),
            map(x => result(x)),
            take(1)).toPromise();
        } else {
          return result(innerResult);
        }
      }
      return null;
    };
  }
}

Now when validation comes back it has a new property called message to the ValidationErrors. when I build my FormGroup I can add validation message as

ngOnInit() {
  this.createFormGroup = this.fb.group({
    name: ['', [ValidationHelpers.addMessage(Validators.required, 'Name is required')]]
  })
}

In the html I can get the error for each field as so

<div *ngIf="(controls.name.dirty || controls.name.touched) && controls.name.invalid" class="invalid-feedback d-block">
  <div data-error-for="name" *ngFor="let error of controls.name.errors | keyvalue">
    {{error.value.message}}
  </div>
</div>

This way when validations get changed don't have to update html or a error to message mapping object and the message gets returned back with the error.


texts:
Is there a better way to write this code.
Suppose I have 10 files to delete and I have to repeat code (public function destroy() ) 10 times.

First remove the database entry.
List item, then remove the file.

OOP - "don't repeat yourself", it works but I repeat the code.

public function image_path() {
        return $this->upload_dir .DS.  $this->filename;
    }

    public function image_path2() {
        return $this->upload_dir .DS.  $this->filename2;
    }

    public function destroy() {
        if($this->delete()) {
            $target_path = PUBLIC_PATH.DS.'public'.DS.$this->image_path();
            return unlink($target_path) ? true : false;
        } else {
            return false;
        }
    }

    public function destroy2() {
        if($this->delete()) {
            $target_path2 = PUBLIC_PATH.DS.'public'.DS.$this->image_path2();
            return unlink($target_path2) ? true : false;
        } else {
            return false;
        }
    }

delete_photo.php

  // Delete photo
  $result = $photo->destroy();
  $result = $photo->destroy2();

photo class

public function delete() {
        global $database;

        $sql = "DELETE FROM " . self::$table_name . " ";
        $sql .= "WHERE id='" . $database->escape_value($this->id) . "' ";
        $sql .= "LIMIT 1";
        $result = $database->query($sql);
        return $result;
    }

protected static $db_fields=array('id', 'filename', 'filename2', 'type', 'type2','size', 'size2', 'caption');
    public $id;
    public $filename;
    public $filename2;
    public $type;
    public $type2;
    public $size;
    public $size2;
    public $caption;


texts:
I am just getting into the world of javascript, coming from the world of classical inheritance. The following is a library I wrote to track when a webapp is idling and I wrote it like I write classical inheritance. But what I have heard about javascript is you have to completely forget how classical inheritance works.

I would love to see how a real javascript developer would write the following using prototypes and the likes.

var IdleListeners = new function(){
  var self = this;

  window.onmousemove = resetTimer;
  window.onmousedown = resetTimer;
  window.onclick = resetTimer;
  window.onscroll = resetTimer;
  window.onkeypress = resetTimer;

  function resetTimer() {
    for (var i = 0; i < self.listeners.length; i++) {
        self.listeners[i].reset();
    }
  }
}

IdleListeners.listeners = [];

IdleListeners.add = function(idleFunction, timeout){
  this.listeners.push(new IdleListener(idleFunction, timeout));
}

var IdleListener = function(idleFunction, timeout){
  this.idleFunciton = idleFunction;
  this.timeout = timeout;

  this.reset = function(){
    if (this.hasOwnProperty('interval')){
      clearInterval(this.interval);
    };
    this.interval = setInterval(this.idleFunciton, this.timeout);
  }
}

It is used by simply calling the following in your html/js file

IdleListeners.add(function(){
    console.log("Idle!")
}, 1000);

"Idle!" would be called once every 1000 miliseconds when the mouse hasn't moved or no keys have been pressed.


texts:
I'm trying to alternate if a button is checked. I've come up with this, which works but its feels unnecessary to write 70 lines of code for such a simple task.

How would I go about to shorten this up, is there any way I can call the base toolStripButton and tell it to uncheck other buttons when clicked on and check it self?

private void toolStripButton1_Click(object sender, EventArgs e)
{
    if (toolStripButton1.Checked == true)
    {
        toolStripButton2.Checked = false;
        toolStripButton3.Checked = false;
        toolStripButton4.Checked = false;
        toolStripButton5.Checked = false;
        toolStripButton6.Checked = false;
    }
}
private void toolStripButton2_Click(object sender, EventArgs e)
{
    if (toolStripButton2.Checked == true)
    {
        toolStripButton1.Checked = false;
        toolStripButton3.Checked = false;
        toolStripButton4.Checked = false;
        toolStripButton5.Checked = false;
        toolStripButton6.Checked = false;
    }
}

private void toolStripButton3_Click(object sender, EventArgs e)
{
    if (toolStripButton3.Checked == true)
    {
        toolStripButton1.Checked = false;
        toolStripButton2.Checked = false;
        toolStripButton4.Checked = false;
        toolStripButton5.Checked = false;
        toolStripButton6.Checked = false;
    }
}

private void toolStripButton4_Click(object sender, EventArgs e)
{
    if (toolStripButton4.Checked == true)
    {
        toolStripButton2.Checked = false;
        toolStripButton3.Checked = false;
        toolStripButton1.Checked = false;
        toolStripButton5.Checked = false;
        toolStripButton6.Checked = false;
    }

}

private void toolStripButton5_Click(object sender, EventArgs e)
{
    if (toolStripButton5.Checked == true)
    {
        toolStripButton2.Checked = false;
        toolStripButton3.Checked = false;
        toolStripButton1.Checked = false;
        toolStripButton4.Checked = false;
        toolStripButton6.Checked = false;
    }
}

private void toolStripButton6_Click(object sender, EventArgs e)
{
    if (toolStripButton6.Checked == true)
    {
        toolStripButton2.Checked = false;
        toolStripButton3.Checked = false;
        toolStripButton1.Checked = false;
        toolStripButton5.Checked = false;
        toolStripButton4.Checked = false;
    }

}


texts:
I created the following code to solve a simple ODE. It is clear enough? Is it efficient code? I really want to read opinions because I want to make all my exercise solutions the same way (same structure of the program), so I need to make sure that this code is really clear and efficient.

#include <iostream>
#include <fstream>
#include <string>
#include <vector>

class step
{
public:
    step()
        : time(0.), velocity(0.) {}
    step(const double& t, const double& v)
        : time(t), velocity(v) {}

    double time;
    double velocity;
};

void calculate(
    std::vector<step>& steps,
    double g,
    double t_max,
    double dt)
{
    int iterations(t_max / dt + 1);

    steps.resize(iterations);

    for(int i(0); i <= iterations; i++)
    {
        steps[i+1].time = steps[i].time + dt;
        steps[i+1].velocity = steps[i].velocity - g * dt;
    }
}

void save(
    const std::vector<step>& steps,
    const std::string& filename)
{
    std::ofstream out(filename);

    for(int i(0); i < steps.size(); i++)
    {
        out << steps[i].time << ' ' << steps[i].velocity << std::endl;
    }
}

int main()
{
    double g(9.81);
    double t_max(10.);
    double dt(0.01);

    step initial_conditions(0.,0.);
    std::vector< step > steps({initial_conditions});

    calculate(steps, g, t_max, dt);
    save(steps, "ex_1.1.dat");

    return 0;
}


texts:
Is my implementation of quicksort efficient, in-place, pythonic ?

def quicksort(array, lo, hi):
    if hi - lo < 2:
        return
    key = random.randrange(lo, hi)
    array[key], array[lo] = array[lo], array[key]
    y = 1 + lo
    for x in xrange(lo + 1, hi):
        if array[x] <= array[lo]:
            array[x], array[y] = array[y], array[x]
            y += 1
    array[lo], array[y - 1] = array[y - 1], array[lo]
    quicksort(array, lo, y - 1)
    quicksort(array, y, hi)

a = map(int, raw_input().split())
quicksort(a, 0, len(a))


texts: Self-hosting WCF in Windows Forms without another Windows process

texts:
I have a Windows application and want to self-host a WCF in it. This MSDN article walks you through how to self-host WCF in a console. Jason Henderson's article demonstrates how to call the service. But the problem is, I don't want to host my service in another Windows process. I want to host it in my client application.

Here is my workaround:

CtrlF5 to run the service
Add service reference to my client
application

Then I can start my service in my client like this:

static void Main()
{
    ServiceHost host = new ServiceHost(typeof(MyService));
    host.Open();
    Application.Run(new Form1());
    host.Close();
}

It works, but I wonder if there are any simpler ways to do this.


texts: Ask user for a number, and count from that number up to 300

texts:
I'm learning Javascript and created the below to take input from a user. If the number is between 150 and 300 it will print out the numbers from that number up till and including 300 in sequential order.

var num1;
conDition();

function conDition(){

 num1 = prompt("Please enter a number: ");

 if(num1 >= 150 && num1 <= 300){

     outNum();

 }else if(num1 < 150){
  alert("The number is too low for this function.");
  num1 = 0;
  conDition();

 }else if(num1 > 300){
  alert("The number is too high for this function.");
  num1 = 0;
  conDition();

 }else{
  alert("That is not a number!");
  num1 = 0;
  conDition();
 }
}

function outNum(){
 do
 {
     document.write(num1 + "
");
     num1++;
 }while (num1 <= 300);

 document.write("############################
");
 return true;
}

Can you help me make this better (more efficient)?


texts: Multiple files data processing in Clojure

texts:
I have made a small script which grabs data into a map from 80 CSV files and calculates some statistics like average, standard deviation etc. It's also adding some additional data to map from filename.

Can you please check if it is a correct way to do so? The idea is to get a list of files in the folder using file-seq, map this to function which reads file lazy, while skipping the first line, convert all text to decimals using read-string, multiply all the data by 1e9 and then calculates all the necessary statistics.

The script works perfectly. I am just concerned about the right style to write programs in Clojure since I am pretty new to it.

Data in CSV files is just numbers in scientific format like "1.721e-9" written in one column.

(def data
  (map (fn [fsc]
     (->> (io/reader fsc)
          (line-seq)
          (rest)
          (map read-string)
          (map #(* % 1e9))
          ((fn [se]
             (let [x se
                   x2 (map #(* % %) se)

                   n (count se)
                   sum-x (reduce + x)
                   sum-x2 (reduce + x2)
                   average (/ sum-x n)
                   variance (-
                              (/ sum-x2 n)
                              (math/expt average 2))]
               (merge {:n n
                       :average average
                       :variance variance
                       :st-dev (math/sqrt variance)
                       :st-dev-sample (math/sqrt
                                        (/ (* n variance)
                                           (- n 1)))}
                      (-> (.getName fsc)
                          (clojure.string/split #"\s")
                          ((partial zipmap [:type :color :voltage :temperature]))
                          (#(assoc % :voltage (read-string (re-find #"[+-]?\d+" (% :voltage)))))
                          (#(assoc % :temperature (read-string (% :temperature))))
                          )))))))

 (->> (clojure.java.io/file "data")
      (file-seq)
      (rest))))


texts:
Here is my solution for CodeWars - Highest Scoring Game

  Given a string of words, you need to find the highest scoring word.

  Each letter of a word scores points according to its position in the alphabet: a = 1, b = 2, c = 3 etc.

  You need to return the highest scoring word as a string.

  If two words score the same, return the word that appears earliest in the original string.

  All letters will be lowercase and all inputs will be valid

  Example:

  Input: 'man i need a taxi up to ubud'

  Output: 'taxi'

This is my solution:

def word_value(input_word):
      values = {
        'a': 1,
        'b': 2,
        'c': 3,
        'd': 4,
        'e': 5,
        'f': 6,
        'g': 7,
        'h': 8,
        'i': 9,
        'j': 10,
        'k': 11,
        'l': 12,
        'm': 13,
        'n': 14,
        'o': 15,
        'p': 16,
        'q': 17,
        'r': 18,
        's': 19,
        't': 20,
        'u': 21,
        'v': 22,
        'w': 23,
        'x': 24,
        'y': 25,
        'z': 26
      }
      value = 0
      for letter in input_word:
          value += values[letter]
      return value

def high(x):
    word_list = x.split(" ")

    word_values = []
    for word in word_list:
        word_values.append(word_value(word))

    max_value = max(word_values)
    index_of_max = word_values.index(max_value)

    return word_list[index_of_max]

The solution passed the test suite but I think I can improve the part where I store all the letters matched with their value. Is there any suggestions for this and in general the entire code?

Thank you.


texts:
I wrote this program to do a simple Caesar shift by a user inputted key, and then deshift.
I'm really enjoying it, but I've run out of ideas on improvements!  Can you think of anything?

def decrypt():
    a=raw_input("Give me the word to decrypt:")
    number=input("What was it shifted by?")
    b=list(a)
    str(b)
    c=[ord(x)for x in(b)]
    d=[]
    for i in c:
        d.append(i-number)
    e=[chr(i) for i in (d)]
    e="".join(e)
    print "Decryption Successful, your word is",e,"!"

def encrypt():
    a=raw_input("Give me a word:")
    number=input("Give me a number:")
    b=list(a)
    str(b)
    c=[ord(x)for x in(b)]
    d=[]
    for i in c:
        d.append(i+number)
    e=[chr(i) for i in (d)]
    e="".join(e)
    print "Your Caesar shifted result (ascii code) is:",e,"!"
    print "Your key is", number, ",remember that!"

def menu():
    print "\n\n\nWelcome to the Caesar Shifter."
    print "What would you like to do?"
    print "Option 1:Encrypt Word"
    print "Option 2:Decrypt Word"
    print "If you would like to quit, press 0."
    choice=input("Pick your selection:")
    if choice==1:
        run=encrypt()
        run
        menu()
    elif choice==2:
        derun=decrypt()
        derun
        menu()
    elif choice==0:
        quit
    else:
        print"That is not a correct selection, please pick either 1, or 2."

menu()


texts:
I'm writing a simple table-oriented storage for objects. The schema of a table is stored in the columns-array and the data in the rows-array.

// example: table "employees"
var columns = ["id", "name"]
var rows = [[1, "Alice"], [2, "Bob"]];

I wrote a function to convert a row-array into an object:

function convertRowToObject(row) {
    var result = {};
    for (var i = 0; i < columns.length; i++) result[columns[i]] = row[i];
    return result;
}

Now I can get an employee-object where I can access the fields by name, not by index.

// [1, "Alice"] -> { id: 1, name: "Alice" }

Is there any way to get the convertRowToObject function any smaller? I think there should be a way to get rid of the loop and make this with a single line of code.


texts:
I have read CLRS Introduction to Algorithms book, now I'm on Elementary data structure chapter. I read about queue concept and try to implement in c.
I have tested a lot it work fine, but I have a little doubt on its working. Please tell me this implementation is correct or not.

#include <stdio.h>
#include <stdlib.h>
#define MAX 4
struct queue {
    int array[MAX];
    int head;
    int tail;
};
void ENQUEUE(struct queue* p,int data) {
// error checking for overflow
    if((p->tail == MAX-1 && p->head == 0 ) || (p->head == p->tail+1)) {
        printf("\nQUEUE IS FULL!!   ");
        return;
    }
    p->array[p->tail] = data;
    if(p->tail == MAX-1)
        p->tail = 0;
    else
        p->tail = p->tail+1;
    printf("\n%d data is added",data);
}

int DEQUEUE(struct queue* p) {
    if(p->head == p->tail) {
        printf("\nQUEUE IS EMPTY!!");
        return -1;
    }
    int x = p->array[p->head];
    if(p->head == MAX-1)
        p->head = 0;
    else
        p->head = p->head+1;
    printf("\n%d data is removed",x);
    return x;
}
void SHOWQUEUE(struct queue* p) {
    int i = 0;
    i = p->head;
    printf("p->head = %d & p->tail = %d",p->head,p->tail);
    printf("\nQUEUE ELEMENTS:");

    while(i != p->tail) {
        printf("%d ",p->array[i]);
        if(i == (MAX-1))
            i = 0;

        else
            i = i+1;
    }
}
int main() {
    struct queue* Q;
    Q = (struct queue*) malloc(sizeof (struct queue));
    if(Q == NULL) {
        printf("Memory allocation failed");
        return -1;
    }
    Q->head = 1;
    Q->tail = 1;
/*  ENQUEUE(Q,1);
    SHOWQUEUE(Q);
    DEQUEUE(Q);
    SHOWQUEUE(Q);
    ENQUEUE(Q,1);
    ENQUEUE(Q,1);
    SHOWQUEUE(Q);

    ENQUEUE(Q,1);
    ENQUEUE(Q,1);
    ENQUEUE(Q,1);
    SHOWQUEUE(Q);
    printf("head = %d & tail = %d ",Q->head,Q->tail);
*/
    ENQUEUE(Q,98);
    ENQUEUE(Q,20);
    ENQUEUE(Q,16);
    ENQUEUE(Q,2);
//  ENQUEUE(Q,1);
//  ENQUEUE(Q,2);
    SHOWQUEUE(Q);
    DEQUEUE(Q);
    DEQUEUE(Q);
    SHOWQUEUE(Q);
    ENQUEUE(Q,5);
    SHOWQUEUE(Q);
    ENQUEUE(Q,3);
    SHOWQUEUE(Q);
    ENQUEUE(Q,10);
    SHOWQUEUE(Q);
    DEQUEUE(Q);
    SHOWQUEUE(Q);
    ENQUEUE(Q,12);
    DEQUEUE(Q);
    SHOWQUEUE(Q);
    ENQUEUE(Q,2);
    DEQUEUE(Q);

    SHOWQUEUE(Q);
    ENQUEUE(Q,1);
    SHOWQUEUE(Q);
    DEQUEUE(Q);
    SHOWQUEUE(Q);
    DEQUEUE(Q);
    SHOWQUEUE(Q);
    DEQUEUE(Q);
    SHOWQUEUE(Q);
    DEQUEUE(Q);
    SHOWQUEUE(Q);
    return 0;
}


texts:
I would like to ask about possible improvement of this code. I have created very simple code using MVC pattern. Is there any logic or anything to change? I tried to keep MVC idea.

This is model, class Customer:

package customereditor;

public class Customer {

    private int ID;
    private String name;
    private String surname;

    public int getID() {
        return ID;
    }

    public void setID(int ID) {
        this.ID = ID;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSurname() {
        return surname;
    }

    public void setSurname(String surname) {
        this.surname = surname;
    }

}

This is view, class CustomerView:

package customereditor;

public class CustomerView {

    public void displayCustomer(int customerID, String customerName, String customerSurname) {

        System.out.println("ID: " + customerID);
        System.out.println("Name: " + customerName);
        System.out.println("Surname: " + customerSurname);
    }

}

This is controller, class CustomerController:

package customereditor;

public class CustomerController {

    Customer model;
    CustomerView view;

    public CustomerController(Customer model, CustomerView view) {
        this.model = model;
        this.view = view;
    }

    public void setCustomerID(int customerID) {
       model.setID(customerID);
    }

    public int getCustomerID() {
        return model.getID();
    }

    public void setCustomerName(String customerName) {
       model.setName(customerName);
    }

    public String getCustomerName() {
        return model.getName();
    }

    public void setCustomerSurname(String customerSurname) {
       model.setSurname(customerSurname);
    }

    public String getCustomerSurname() {
        return model.getSurname();
    }

    public void displayCustomer() {
        view.displayCustomer(model.getID(),model.getName(),model.getSurname());
    }

}

And this is class with main method, class MainCustomer:

package customereditor;

public class MainCustomer {

    public static void main(String[] args) {

        Customer model = new Customer();
        CustomerView view = new CustomerView();
        CustomerController controller = new CustomerController(model, view);

        controller.setCustomerID(1);
        controller.setCustomerName("John");
        controller.setCustomerSurname("Doe");
        controller.displayCustomer();
    }
}