texts: Handling Firebase's asynchronous calls Android

texts:
I have written a helper class to manage callbacks from Firebase's asynchronous calls. Can this be implemented in a better way?

public class FirebaseHelper {
    private static String TAG = FirebaseHelper.class.getSimpleName();

    private static FirebaseHelper mFirebaseHelper;
    private DatabaseReference mDatabase;
    private DataSnapshot cachedDataSnapshot = null;

    // Create a pool of 3 threads
    private final ExecutorService pool = Executors.newFixedThreadPool(3);

    /**
     * used to get object of FirebaseHelper class via singleton pattern
     * @return FirebaseHelper object
     */
    public static FirebaseHelper getInstance(){
        if(mFirebaseHelper == null){
            mFirebaseHelper = new FirebaseHelper();
        }
        return mFirebaseHelper;
    }

    /**
     * Used to register the root object of database from where data is to be accessed
     * @param databaseRoot
     */
    public void registerDatabaseRoot(String databaseRoot){
        mDatabase = FirebaseDatabase.getInstance().getReference(databaseRoot);
    }

    /**
     * get the current root
     * @return
     */
    public DatabaseReference getDatabaseRoot(){
        return mDatabase;
    }

    /**
     * get the closed lead disposition data
     * @return a dummy object until data is retrieved from firebase database
     */

    public Future<ArrayList<CLDP>> getLeadDisposition(final String Id){
        registerDatabaseRoot(FirebaseConstants.MASTER_DATA);

        return pool.submit(new Callable<ArrayList<CLDP>>() {

            @Override
            public ArrayList<CLDP> call() throws Exception {
                final Query query = mDatabase.child(FirebaseConstants.LEADS_DISPOSTION).
                        orderByChild("FLAG").equalTo("1");
                final ArrayList<CLDP> data = new ArrayList<>();

                query.addListenerForSingleValueEvent(new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {
                        cachedDataSnapshot = dataSnapshot;
                    }

                    @Override
                    public void onCancelled(DatabaseError databaseError) {
                        Log.e(TAG, "getCLDPId:onCancelled", databaseError.toException());

                    }
                });
                Iterable<DataSnapshot> snapshots = cachedDataSnapshot.getChildren();
                for (DataSnapshot d : snapshots){
                    if((d.child("TC_TypeId").getValue()).equals(Id)) {
                        CLDP cldData = new CLDP();
                        cldData.setId((String) d.child("TC_DispId").
                                getValue());
                        cldData.setName((String) d.child("Name").getValue());
                        data.add(cldData);
                    }
                }
                return data;
            }
        });
    }
}


texts:
I'm working on writing a Java class library which includes the following implementation of a counting bloom filter:

package sj224.lib.util;

import java.util.function.Predicate;
import java.util.Random;

public class BloomFilter<V> implements Predicate<V>{
    private final int size;
    private int count;
    private final int bpe;
    private final int[] data;
    public int hashCode(){
        long t=count;
        for(int i=0;i<size;i++){
            t+=(long)((data[i]%2)*Math.pow(2, i%64));
        }
        return new Random(t).nextInt();
    }
    public String toString(){
        return size+"-bit Bloom Filter containing "+count+" elements (hash code "+hashCode()+")";
    }
    public BloomFilter(int space){
        data=new int[space];
        size=space;
        bpe=Math.max(3, Math.min(size/8,(int)Math.sqrt(size)));
        count=0;
    }
    public int size(){
        return count;
    }
    private int[] hash(V v){
        Random r=new Random(v.hashCode());
        int[] keys=new int[size];
        for(int i=0;i<bpe;i++){
            keys[r.nextInt(size)]=1;
        }
        return keys;
    }
    public BloomFilter(){
        this(64);
    }
    public BloomFilter(Iterable<V> source){
        this(64);
        for(V i:source)insert(i);
    }
    public boolean remove(V v){
        int[] a=hash(v);
        for(int i=0;i<size;i++){
            if(data[i]<a[i])return false;
        }
        for(int i=0;i<size;i++){
            data[i]-=a[i];
        }
        count--;
        return true;
    }
    public void clear(){
        for(int i=0;i<size;i++)data[i]=0;
    }
    public void insert(V v){
        int[] a=hash(v);
        for(int i=0;i<size;i++){
            data[i]+=a[i];
        }
        count++;
    }
    public boolean contains(V v){
        int[] a=hash(v);
        for(int i=0;i<size;i++){
            if(data[i]<a[i])return false;
        }
        return true;
    }

    public boolean test(V v){
        return contains(v);
    }
}

Is there anything here that can reasonably be improved?


texts:
I am working on this assignment to draw the flag of Liberia for my essentials of computer programming class.

I finished it but had extra time to kill and noticed that a couple similar blocks of code are not very concise and could be shortened with a loop, but right now I can't seem to form the code just right!

Below I have included one of the methods that I would like to shorten:

public static void flagOfLiberia(Graphics g) {
    Expo.setBackground(g,Expo.black);
    for (int d = 1; d <= numDots; d++) {
        int x = Expo.random(0,1000);
        int y = Expo.random(0,650);

        if (x < 300 && y < 300)
            Expo.setColor(g,Expo.darkBlue);
        else if (y < 50)
            Expo.setColor(g,Expo.red);
        else if (y < 100)
            Expo.setColor(g,Expo.white);
        else if (y < 150)
            Expo.setColor(g,Expo.red);
        else if (y < 200)
            Expo.setColor(g,Expo.white);
        else if (y < 250)
            Expo.setColor(g,Expo.red);
        else if (y < 300)
            Expo.setColor(g,Expo.white);
        else if (y < 350)
            Expo.setColor(g,Expo.red);
        else if (y < 400)
            Expo.setColor(g,Expo.white);
        else if (y < 450)
            Expo.setColor(g,Expo.red);
        else if (y < 500)
            Expo.setColor(g,Expo.white);
        else if (y < 550)
            Expo.setColor(g,Expo.red);
        else if (y < 600)
            Expo.setColor(g,Expo.white);
        else if (y < 650)
            Expo.setColor(g,Expo.red);

        drawDot(g,x,y);
        Expo.setColor(g,Expo.white);
        Expo.fillStar(g,150,150,100,5);
    }
    showName(g,"Liberia");
}


texts:
Problem

  Your friend John uses a lot of emoticons when you talk to him on
  Messenger. In addition to being a person who likes to express himself
  through emoticons, he hates unbalanced parenthesis so much that it
  makes him go :(

  Sometimes he puts emoticons within parentheses, and you find it hard
  to tell if a parenthesis really is a parenthesis or part of an
  emoticon.

  A message has balanced parentheses if it consists of one of the
  following:

  An empty string ""
  One or more of the following characters: 'a' to 'z', ' ' (a space) or ':' (a colon)
  An open parenthesis '(', followed by a message with balanced parentheses, followed by a close parenthesis ')'.
  A message with balanced parentheses followed by another message with balanced parentheses.
  A smiley face ":)" or a frowny face ":("
  Write a program that determines if there is a way to interpret his message while leaving the parentheses balanced.

I'm working on this balanced smileys checking algorithm, and my current solution is very naive, just enumerate all possible ways to interpret :) and :(. I'm wondering if any smarter ideas in terms of algorithm time complexity perspective.

def procee_raw_string(source):
    result = []
    for i,v in enumerate(source):
        if v == '(':
            if i > 0 and source[i-1] == ':':
                result.append(source[i-1:i+1])
            else:
                result.append(v)
        elif v == ')':
            if i>0 and source[i-1] == ':':
                result.append(source[i-1:i+1])
            result.append(')')
    return ''.join(result)

def check_balance(source):
    stack = []
    for s in source:
        if s == '(':
            stack.append(s)
        else: # s is ')'
            if len(stack) == 0 or stack[-1] != '(':
                return False
            else:
                stack.pop(-1)
    if len(stack) > 0:
        return False
    return True

def generate_balance_string(source, index, prefix, result):
    if index >= len(source):
        result.append(prefix[:])
        return
    if source[index] == ':' and source[index+1] == '(':
        prefix.append('(')
        generate_balance_string(source, index+2, prefix, result)
        prefix.pop(-1)
        generate_balance_string(source, index+2, prefix, result)
    elif source[index] == ':' and source[index+1] == ')':
        prefix.append(')')
        generate_balance_string(source, index+2, prefix, result)
        prefix.pop(-1)
        generate_balance_string(source, index+2, prefix, result)
    elif source[index] == '(':
        prefix.append('(')
        generate_balance_string(source, index+1, prefix, result)
        prefix.pop(-1)
    elif source[index] == ')':
        prefix.append(')')
        generate_balance_string(source, index+1, prefix, result)
        prefix.pop(-1)

if __name__ == "__main__":
    raw_smile_string = 'abc(b:)cdef(:()'
    process_string = procee_raw_string(raw_smile_string)
    result = []
    generate_balance_string(process_string, 0, [], result)
    for r in result:
        print check_balance(r)

Additional thoughts,

I am not sure if we could do such simple check for balance?

If number of close parenthesis (excluding the smileys) are ever more than the number of open parenthesis, then parentheses are not balanced.
If number of open parenthesis at the end (excluding the frowns) are more than the close ones, then also the parentheses are not balanced.


texts:
I'm getting started with Docker, and I've set up a very simple image built from a Dockerfile. It's based FROM the ubuntu image, and I'm downloading and building apache from source.

I'm just curious if I'm on the right tracks, if there's a more "Docker" way of doing what I'm doing, or any other things that I could be doing different/better.

It's running in the default VM that Kitematic adds for me, and I'm building the image with docker build -t webserver ., then testing with docker run -p 80:80 -i -t webserver /bin/bash

FROM ubuntu:latest

RUN apt-get -qq  update -y
RUN apt-get -qq install build-essential -y

RUN mkdir install-files
WORKDIR /install-files
RUN mkdir apache
WORKDIR /install-files/apache
RUN apt-get -qq install wget -y >/dev/null
RUN wget http://mirrors.ukfast.co.uk/sites/ftp.apache.org//apr/apr-1.5.2.tar.gz >/dev/null
RUN tar -xvzf apr-1.5.2.tar.gz >/dev/null
WORKDIR /install-files/apache/apr-1.5.2
RUN ./configure >/dev/null
RUN make >/dev/null
RUN make install >/dev/null

WORKDIR /install-files/apache
RUN wget http://apache.mirror.anlx.net//apr/apr-util-1.5.4.tar.gz >/dev/null
RUN tar -xvzf apr-util-1.5.4.tar.gz >/dev/null
WORKDIR /install-files/apache/apr-util-1.5.4
RUN ./configure --with-apr=/usr/local/apr/ >/dev/null
RUN make >/dev/null
RUN make install >/dev/null

WORKDIR /install-files/apache/
RUN apt-get -qq install libpcre3 libpcre3-dev >/dev/null
RUN wget http://mirror.ox.ac.uk/sites/rsync.apache.org//httpd/httpd-2.4.18.tar.gz >/dev/null
RUN tar -xvzf httpd-2.4.18.tar.gz >/dev/null
WORKDIR /install-files/apache/httpd-2.4.18
RUN ./configure --with-apr=/usr/local/apr/ >/dev/null
RUN make >/dev/null
RUN make install >/dev/null

RUN mkdir /tech
RUN ln -s /usr/local/apache2/ /tech/httpd

RUN apt-get -qq install nano -y
ADD startup.sh /root/startup.sh
RUN chmod 777 /root/startup.sh

WORKDIR /


texts:
public class WmSync : IDisposable
{
    public WmSync()
    {
        var sync = new Control();
        sync.Handle.GetHashCode(); // ensure handle is created
        _sync = sync;
        Thread.MemoryBarrier();
    }

    public void Dispose()
    {
        _sync.Dispose();
    }

    public void BeginInvoke(Action action)
    {
        _sync.BeginInvoke(action);
    }

    public void Invoke(Action action)
    {
        _sync.Invoke(action);
    }

    public bool InvokeRequired
    {
        get { return _sync.InvokeRequired; }
    }

    private readonly Control _sync;
}

The idea is to create this object in the main thread and use it from background threads to execute pieces of code in the main thread.

For example:

// somewhere in the very beginning of the program, in the main thread
static WmSync SyncQueue = new WmSync();

// somewhere in a background thread
SyncQueue.Invoke(
    () =>
    {
        if (_settingsForm != null)
            _settingsForm.Show();
    });

This is just an artificial sample, but it should give you idea. Is this code thread safe?


texts:
I have ported the code from my previous question "Generate a random numbers class" to C++14 and made a few modifications.

How can I improve it further?

#include <iostream>
#include <random>

template<typename T>
class Random
{
    template <typename U>
    static auto dist() -> typename std::enable_if_t<std::is_integral<U>::value, std::uniform_int_distribution<U>>{};

    template <typename U>
    static auto dist() -> typename std::enable_if_t<std::is_floating_point<U>::value, std::uniform_real_distribution<U>>{};

public:
    Random()
        : mRandomEngine(std::random_device()())
    {}

    auto operator()(T max)
    {
        decltype(dist<T>()) uniformDistribution(0, max - 1);
        return uniformDistribution(mRandomEngine);
    }

    auto operator()(T min, T max)
    {
        decltype(dist<T>()) uniformDistribution(min, max);
        return uniformDistribution(mRandomEngine);
    }

private:
    std::mt19937            mRandomEngine;
};

int main()
{
    Random<int> random;
    for (int i = 0; i < 9; ++i)
        std::cout << random(1, 8) << '\n';

    Random<float> randomf;
    for (int i = 0; i < 9; ++i)
        std::cout << randomf(1.f, 8.f) << '\n';
}


texts: Guess Number Game - Console based game using Java

texts:
This game is pretty common for beginner projects. I wrote a version of this before all in Main - so here I challenge myself to recreate it in a more OO style.
I wanted to take a more OO approach, so any feedback on where I could do better or am making some errors is appreciated. I also have some personal confusion if in some parts I'm coding this procedurally. I might be mistaken but I think this code is a bit of both styles, and if so, can someone help explain the distinctive differences? Is there too much recursion in some parts? How does the readability appear? What are your thoughts?
The game will generate a random secret number and ask the user to input their guesses within the given number of attempts Code below:
import java.util.InputMismatchException;
import java.util.Random;
import java.util.Scanner;

public class GuessGame {

    private static final Scanner SC = new Scanner(System.in);
    private static final Random R = new Random();
    private static int secret = R.nextInt(100) + 1;
    private static final int GIVEN_ATTEMPTS = 10;
    private int attempts = 0;

    public void playGame() {
        promptGuess();
    }

    private int promptGuess() {
        try {
        printLine("Guess a number from 1-100");
        int guess = SC.nextInt();
            if (guess < 1) {
                promptGuess();
            } else {
                return compare(guess);
            }
        } catch(InputMismatchException e) {
            printLine("Only numbers please");
            SC.nextLine();
            promptGuess();
        }
        return 0;
    }

    private int compare(int guess) {
        attempts++;
        if (attempts == GIVEN_ATTEMPTS) {
            return promptResult(4);
        }
        int difference = secret - guess;

        if (difference > 0) {
            return promptResult(1);
        } else if (difference < 0) {
            return promptResult(2);
        } else {
            return promptResult(3);
        }
    }

    private int promptResult(int n) {
        switch (n) {
            case 1:
                printLine("Guess was too low, try again");
                promptGuess();
                break;
            case 2:
                printLine("Guess was too high, try again");
                promptGuess();
                break;
            case 3:
                printLine("You got it! Nice guess! The number was " + secret);
                printLine("In " + attempts + " attempts");
                printLine("Game Over");
                attempts = 0;
                secret = R.nextInt(100) + 1;
                playAgain();
            case 4:
                printLine("Too many guesses! " + GIVEN_ATTEMPTS + "/" + GIVEN_ATTEMPTS + " used.");
                printLine("Secret number was: " + secret + " Game Over");
                attempts = 0;
                secret = R.nextInt(100) + 1;
                playAgain();

        }
        return 0;
    }

    private void printLine(String s) {
        System.out.println(s);
    }

    private void playAgain() {

        printLine("Play again? (Enter Y for yes or N for no)");
        String reply = SC.next();
        if (reply.equalsIgnoreCase("Y")) {
            playGame();
        } else if (reply.equalsIgnoreCase("N")) {
            printLine("Thanks for playing");
            System.exit(0);
        } else {
                System.out.println("Please enter a valid answer");
                playAgain();
            }
        }
    }

    public class Main {

    public static void main(String[] args) {
        GuessGame g = new GuessGame();

        g.playGame();
    }
}


texts: Delay and queue animation in a function - how can I optimise this by removing duplicate code?

texts:
I have this script that moves a box around the screen and the loops the second part of the movement. I have altered the code to drop another three boxes (4 in total) into the animation so the boxes follow each other around the screen.

I want it to work exactly like it does, but I'm sure there's a much better way of doing this:

Here's a js fiddle: http://jsfiddle.net/NF6LU/

JS

function animateNode() {
    $('.node').animate({top: '425px'}, { duration: 1800, easing : 'linear', queue: true });
    $('.node2').animate({top: '425px'}, { duration: 1800, easing : 'linear', queue: true });
    $('.node3').animate({top: '425px'}, { duration: 1800, easing : 'linear', queue: true });
    $('.node4').animate({top: '425px'}, { duration: 1800, easing : 'linear', queue: true });
    $('.node').animate({marginLeft: '-284px'}, { duration: 2500, easing : 'linear', queue: true });
    $('.node2').animate({marginLeft: '-284px'}, { duration: 2500, easing : 'linear', queue: true });
    $('.node3').animate({marginLeft: '-284px'}, { duration: 2500, easing : 'linear', queue: true });
    $('.node4').animate({marginLeft: '-284px'}, { duration: 2500, easing : 'linear', queue: true });
    $('.node').animate({top: '157px'}, { duration: 1800, easing : 'linear', queue: true });
    $('.node2').animate({top: '157px'}, { duration: 1800, easing : 'linear', queue: true });
    $('.node3').animate({top: '157px'}, { duration: 1800, easing : 'linear', queue: true });
    $('.node4').animate({top: '157px'}, { duration: 1800, easing : 'linear', queue: true });
    $('.node').animate({marginLeft: '264px'}, { duration: 2500, easing : 'linear', queue: true });
    $('.node2').animate({marginLeft: '264px'}, { duration: 2500, easing : 'linear', queue: true });
    $('.node3').animate({marginLeft: '264px'}, { duration: 2500, easing : 'linear', queue: true });
    $('.node4').animate({marginLeft: '264px'}, { duration: 2500, easing : 'linear', queue: true });
}
$('.node').delay(1500).animate({top: '157px'}, { duration: 1000, easing : 'linear', queue: true });
$('.node2').delay(3000).animate({top: '157px'}, { duration: 1000, easing : 'linear', queue: true });
$('.node3').delay(4500).animate({top: '157px'}, { duration: 1000, easing : 'linear', queue: true });
$('.node4').delay(6000).animate({top: '157px'}, { duration: 1000, easing : 'linear', queue: true });
$('.node').animate({marginLeft: '264px'}, { duration: 1500, easing : 'linear', queue: true });
$('.node2').animate({marginLeft: '264px'}, { duration: 1500, easing : 'linear', queue: true });
$('.node3').animate({marginLeft: '264px'}, { duration: 1500, easing : 'linear', queue: true });
$('.node4').animate({marginLeft: '264px'}, { duration: 1500, easing : 'linear', queue: true });
$(function(){
    animateNode();
    setInterval(animateNode, 2000);
});

HTML

CSS

span.node, span.node2, span.node3, span.node4{
    height: 16px;
    width: 16px;
    background-color: black;
    position: absolute;
    top: 60px;
    left: 50%;
    margin-left: -9px;
}


texts:
This fasm x64 (Linux) code seems very crude and repetitive, but it gets the job done. How could I perform this task in a more idiomatic manner?

format ELF64 executable 3

segment readable executable

entry $

prompt_user:
mov edx,prompt_len
lea rsi,[prompt] ;<------ String
mov edi,1       ; STDOUT
mov eax,1       ; sys_write
syscall

get_user_input:
mov rax, 0 ; sys_read
mov rdi, 0 ; STDIN
lea rsi, [bit_string] ; <----- defined memory location
mov rdx, 2 ; <---- # of chars to read
syscall

;DEBUG CODE:
;lea rax, [bit_string]
;mov [rax], byte 'A'
;mov [rax+1], byte 'B'
lea rax, [bit_string]
cmp [rax], byte '0'
je load_0
cmp [rax], byte '1'
je load_1
cmp [rax], byte '2'
je load_2
cmp [rax], byte '3'
je load_3
cmp [rax], byte '4'
je load_4
cmp [rax], byte '5'
je load_5
cmp [rax], byte '6'
je load_6
cmp [rax], byte '7'
je load_7
cmp [rax], byte '8'
je load_8
cmp [rax], byte '9'
je load_9
cmp [rax], byte 'A'
je load_A
cmp [rax], byte 'B'
je load_B
cmp [rax], byte 'C'
je load_C
cmp [rax], byte 'D'
je load_D
cmp [rax], byte 'E'
je load_E
cmp [rax], byte 'F'
je load_F
load_0:
lea rsi, [n0]
jmp print_nibble
load_1:
lea rsi, [n1]
jmp print_nibble
load_2:
lea rsi, [n2]
jmp print_nibble
load_3:
lea rsi, [n3]
jmp print_nibble
load_4:
lea rsi, [n4]
jmp print_nibble
load_5:
lea rsi, [n5]
jmp print_nibble
load_6:
lea rsi, [n6]
jmp print_nibble
load_7:
lea rsi, [n7]
jmp print_nibble
load_8:
lea rsi, [n8]
jmp print_nibble
load_9:
lea rsi, [n9]
jmp print_nibble
load_A:
lea rsi, [nA]
jmp print_nibble
load_B:
lea rsi, [nB]
jmp print_nibble
load_C:
lea rsi, [nC]
jmp print_nibble
load_D:
lea rsi, [nD]
jmp print_nibble
load_E:
lea rsi, [nE]
jmp print_nibble
load_F:
lea rsi, [nF]
jmp print_nibble

nibble_two:
lea rax, [bit_string]
cmp [rax+1], byte '0'
je load_0
cmp [rax+1], byte '1'
je load_1
cmp [rax+1], byte '2'
je load_2
cmp [rax+1], byte '3'
je load_3
cmp [rax+1], byte '4'
je load_4
cmp [rax+1], byte '5'
je load_5
cmp [rax+1], byte '6'
je load_6
cmp [rax+1], byte '7'
je load_7
cmp [rax+1], byte '8'
je load_8
cmp [rax+1], byte '9'
je load_9
cmp [rax+1], byte 'A'
je load_A
cmp [rax+1], byte 'B'
je load_B
cmp [rax+1], byte 'C'
je load_C
cmp [rax+1], byte 'D'
je load_D
cmp [rax+1], byte 'E'
je load_E
cmp [rax+1], byte 'F'
je load_F

print_intro:
mov edx,intro_len
lea rsi,[intro]
mov edi,1       ; STDOUT
mov eax,1       ; sys_write
syscall
ret

print_nibble:
cmp [position], 0 ; If were on first iter, then print intro
jne skip_intro
push rsi
call print_intro
pop rsi

skip_intro:
mov rax, 1
cmp al, [position]
jl go_out
mov edx, 4

mov edi,1       ; STDOUT
mov eax,1       ; sys_write
syscall
add [position], 1
jmp nibble_two

go_out:
mov edx,1

lea rsi,[nl]
mov edi,1       ; STDOUT
mov eax,1       ; sys_write
syscall

xor edi,edi     ; exit code 0
mov eax,60      ; sys_exit
syscall

segment readable writeable
prompt db 'Enter a byte in the format: F6', 0xA
prompt_len = $ - prompt
nl db 0xA
intro db 'In binary: ', 0
intro_len = $ - intro
bit_string rb 2
position db 0
n0 db '0000', 0
n1 db '0001', 0
n2 db '0010', 0
n3 db '0011', 0
n4 db '0100', 0
n5 db '0101', 0
n6 db '0110', 0
n7 db '0111', 0
n8 db '1000', 0
n9 db '1001', 0
nA db '1010', 0
nB db '1011', 0
nC db '1100', 0
nD db '1101', 0
nE db '1110', 0
nF db '1111', 0


texts:
The overall project is about generating routes for an API. Advice on styling, syntax, methodology, general approach to the problem, simply good coding practices pointers would help a bunch.

GitHub

const requestParser = {
  parseReqData: parseReqData
}

function parseReqData(req) {
  const resources = getRouteEndpoints(req);
  let resources_count = 0;
  let properties = [];

for (let key in resources) {
    getReqIds(req, key, data => {
        if (data) {
            properties.push(key);
            resources_count++;
            resources[key] = data;
        }
    });
}

let index = resources_count -1;
let key = properties[index];

getRedBody(req, key, data =>{
    if(data){
        resources[key]["data"] = data;
    }
})

if (resources_count > 1) {
    return resources;
}
else {
    return resources[Object.keys(resources)];
     }
}

function getRouteEndpoints(req) {
const resources = {};

const route = req.path();
const reg = /[^\w\s]/gi;
const routeEndpoints = route.split(reg).filter(routeEndpoint =>        routeEndpoint !== "" && routeEndpoint !== "api");

routeEndpoints.forEach(endpoint => {
    if (!endpoint.match(/\d/)) {
        resources[endpoint] = {};
       }
   });

   return resources;
}

function getReqIds(req, resourceName, cb) {

let data = {};

if (req.params.id) {
    data.id = req.params.id;
    }
if (req.params[resourceName + '-id']) {
    data.id = req.params[resourceName + '-id'];
   }

   cb(data);
}
function getRedBody(req, resourceName, cb) {
let data = {};

if (req.body) {
    for (let key in req.body) {
        data[key] = req.body[key];
      }
   }

  cb(data);
}

module.exports = requestParser;

The ReqParser is used in RouteHandler:

const reqestParser = require('./requestParser');

class RouteHandler {
constructor(middlewears) {
    this.middlewears = middlewears;
    }

runMiddlewear(req, res, next) {
    this.middlewears.forEach(middlewear => {
        for (let key in middlewear) {
            middlewear[key](req, res, next);
        }
    })
}
getResponse(req, res, action) {
    let actionParams = reqestParser.parseReqData(req);
    action(actionParams, result => {
        return response(res, result);
     });

   }
}

function response(res, result) {
if (result) {
    res.send(success(result));
   }
else {
    res.send(error());
   }
}

function success(result) {
if (result === 200) {
    return { statsu: 200, message: "success" };
}
else {
    return { status: 200, message: "success", data: result };
    }
}

function error() {
    return { status: 404, message: "No matching resource" };
}

module.exports = RouteHandler;

The action used in RouteHandler is really a method of controller for a route used like this:

api/users
getAll(params, response) {
    User.find({}, function (err, users) {
        if (err) { response(err); }
        response(users);
    });
}

api/users/:user-id/dogs
 create(resources, response) {
    Dog.create({
        name: resources.dogs.data.dogName,
        owner: resources.users.id
    }, function (err) {
        if (err) { response(err); }
        response(200);
    });


texts: Deciding when to update an image in the database

texts:
I have written a method which is used to determine whether or not I need to update an image stored in a database with an image stored on a local machine.  The criteria for when an image needs to be updated are as follows (only one must be met):

The image field is empty.
The modified (stores when the image was last updated) field is empty.
The file on the disk is newer than what is stored in the database.

Here is my implementation:

bool __fastcall TPatHelper::NeedUpdatePatImage( String FileName )
{
    if( !FileExists( FileName ) )
    {
        return false;
    }

    String  Img = TSql()
                    .Select( "[IMAGE]" )
                    .From( "IMG" )
                    .Where( "RECORD_ID", FPAT_ID )
                    .Exec()
                    .AsText;

    if( Img.IsEmpty() )
    {
        return true;
    }

    String DateTimeStr = TSql()
                            .Select( "MODIFIED" )
                            .From( "IMG" )
                            .Where( "RECORD_ID", FPAT_ID )
                            .Exec()
                            .AsText;

    if( DateTimeStr.IsEmpty() )
    {
        return true;
    }

    TDateTime * DBModifiedDT = new TDateTime( DateTimeStr );

    TDateTime * FileModifiedDT = new TDateTime();
    FileAge( FileName, *FileModifiedDT, true );

    bool update = FileModifiedDT > DBModifiedDT;

    delete DBModifiedDT;
    delete FileModifiedDT;

    return update;
}

In addition to just general critique, I am specifically wondering if it would be more efficient to select both records from the IMG table at once, even though one may not be used, rather than doing this with two queries.


texts: Image processing using Python OOP library

texts:
I am trying to learn OOP by refactoring my existing code (functions only). This example works but I am not sure whether it is pythonic and good practice.

I have a shared library which consist of several file with functions:

color_spaces.py

import cv2

def rgb_to_hsv(image):
    print ('hsv')
    hsv_image = cv2.cvtColor(image, cv2.COLOR_RGB2HSV)
    hue, sat, val = hsv_image[:, :, 0], hsv_image[:, :, 1], hsv_image[:, :, 2]
    return hsv_image, hue, sat, val

def rgb_to_lab(image):
    lab_image = cv2.cvtColor(image, cv2.COLOR_RGB2LAB)
    l_chan, a_chan, b_chan = lab_image[:, :, 0], lab_image[:, :, 1], lab_image[:, :, 2]
    return lab_image, l_chan, a_chan, b_chan

thresholding.py

import cv2

def treshold_otsu(gray_image):
    ret, thresholded_image = cv2.threshold(gray_image, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)
    return thresholded_image

def global_threshold(gray_image):
    ret, thresholded_image = cv2.threshold(gray_image, 127, 255, cv2.THRESH_BINARY)
    return thresholded_image

My class which uses functions of the shared library:

pipline01.py

import cv2
from color_spaces import rgb_to_hsv, rgb_to_lab
from thresholding import treshold_otsu, global_threshold

class Segmentation1(object):
    def __init__(self, filename, path, procedure):
        self.filename = filename
        self.path = path
        self.procedure = procedure

    def start_pipline(self):
        # Read image
        image = cv2.imread(self.path + self.filename)

        # Do segmentation procedure depending on procedure
        if self.procedure == 'test01':
            source = rgb_to_hsv(image)[1]
            binary = treshold_otsu(source)
        elif self.procedure == 'test02':
            source = rgb_to_lab(image)[1]
            binary = global_threshold(source)

        # Save image
        cv2.imwrite(self.path + self.filename.split('.')[0] + '_' + self.procedure + '.png', binary)

Then I call the class in a batch mode by looping over a folder with images:

batch_pipline01.py

import os
import argparse
from pipline01 import Segmentation1

parser = argparse.ArgumentParser(description = 'Test.')
parser.add_argument('-d', '--img_dir', required = True,
                    help = 'directory containing images to segment.')
parser.add_argument('-p', '--procedure', required = True,
                    help = 'procedure to run.')

args = parser.parse_args()
print(args)
img_dir = args.img_dir
procedure = args.procedure
images = os.listdir(img_dir)
#images = [img[2:] for img in args.images]

# Start segmentation for each image
for img in images:
    os.chdir(img_dir)
    print('SEGMENTING ' + img)
    segmenter = Segmentation1(img, img_dir, procedure)
    obj = segmenter.start_pipline()
    del obj

Can I improve my code and design?


texts: Understanding interface with animal classes

texts:
I made this small program to demonstrate to myself an example of interface.  I wanted to confirm whether it is correct and if there is anything more I should know about interfaces other than the importance of implementing polymorphism and multiple inheritance.

//program.cs
class Program
{
    static void Main(string[] args)
    {
        Dog oDog = new Dog();
        Console.WriteLine(oDog.Cry());

        Cat oCat = new Cat();
        Console.WriteLine(oCat.Cry());

        Console.ReadKey();
    }

//IAnimal.cs
interface IAnimal
{
    string Cry();
}

//Dog.cs
class Dog : IAnimal
{
    public string Cry()
    {
        return "Woof!";
    }
}

//Cat.cs
class Cat : IAnimal
{
    public string Cry()
    {
        return "Meow!";
    }
}


texts:
My Code
import shutil
import os
from pathlib import Path
from datetime import datetime

DOWNLOAD_DIR = Path("/Users/my_name/Desktop/Zip Test/g_2020-12-10_3/")
ZIPPED_DIR = Path("/Users/my_name/Desktop/Zip Test/g_2020-12-10_3.zip")
ZIPPED_DIR.mkdir(exist_ok=True)

def make_archive(source, destination):
    delivery_file_name = destination.split("/")[-1]
    delivery_name = delivery_file_name.split(".")[0]
    format = delivery_file_name.split(".")[1]
    archive_from = os.path.dirname(source)
    archive_to = os.path.basename(source.strip(os.sep))
    shutil.make_archive(delivery_name, format, archive_from, archive_to)
    shutil.move(
        "%s.%s" % (delivery_name, format),
        "/Users/my_name/Desktop/Zip Test/zipped_content",
    )

make_archive(str(DOWNLOAD_DIR), str(ZIPPED_DIR))

Description
I am very new to python so i had a very hard time getting shutil.make_archive to do what i want. This code is finally working and i feel it is a little hard to read so i was wondering if someone can help me refactor this to simplify it. I don't want to loose the functionality of what i am doing. In my code i basically go to my /Users/my_name/Desktop/Zip Test and inside it is a folder called g_2020-12-10_3 which contains the contents i want to zip up so i do that.
When i unzip the contents it unzips folder named g_2020-12-10_3 and inside it are the contents.
I want to keep this functionality but at the same time simplify the code below and any help would be appreciated here.


texts: Modularize more efficiently in an if/else setup

texts:
I wrote a program for one of my Object Oriented Programming in Java classes(Program 2) and I got docked off because my method was too long, which I'm not complaining about.

I got the note: "Modularize more, method too long."

I was wondering what any of you more experienced programmers would do to simplify/shorten my code for future sake so that I learn how to shorten this sort of code.

public void run() throws java.io.IOException
{
   stdin = new Scanner(System.in);
   String input;
   String fraction;
   int numPerLine;
   boolean inList = false;
   input = stdin.next(); // Get the read

  while(!input.equalsIgnoreCase("Q"))
  {
     if(input.equalsIgnoreCase("A"))
     {
        fraction = stdin.next(); // Get the fraction read
        thisFract = new Fraction(fraction);
        list.add(thisFract);
        System.out.println(thisFract.toString() + " was added "
              + "to the list.");
     }
     else if (input.equalsIgnoreCase("D"))
     {
        fraction = stdin.next();
        thisFract = new Fraction(fraction);
        inList = list.delete(thisFract);

        if(inList == true)
           System.out.println(thisFract.toString() + " was removed "
                 + "from the list.");
        else
           System.out.println(thisFract.toString() + " is not in the"
                 + " list.");
     }
     else if(input.equalsIgnoreCase("S"))
     {
        System.out.println("The sum of the list is: " + list.sum());
     }


texts:
I was given the following exercise as part of a job interview process. I submitted my code and received the feedback that my solution is "close" but not "correct". My code executes just fine and displays the desired results. Can somebody please tell me what would have made my code more "correct"? or - did I misunderstand the requirements? (I realize that the Constructor is no longer needed but Codepen was complaining without it).

Requirements:

Using data variable implement a small Form using checkboxes

[x] Sonia
[ ] Maria
[ ] John
[x] Michael

On every form change on any checkbox print its current state, which should look like data.

const data = {
  sonia: true,
  maria: false,
  john: false,
  michael: true
};

My solution:

class App extends React.Component{

    constructor() {
        super();

        this.state = {
            data: {
                Sonia: false,
                Maria: false,
                John: false,
                Michael: false
            }
        };

        this.handleClick = this.handleClick.bind(this);
    }

    handleClick(event) {

        let data = this.state.data;

        const target = event.target;
        const value = target.type === 'checkbox' ? target.checked : target.value;
        const name = target.name;

        data = this.state.data;

        for (const i in data) {
            if (i === name) {
                data[i] = value
            }
        }
        this.setState( {data:data});
    }

    render() {
        return (

                <form>
                  {Object.keys(this.state.data).map((key, index) =>

                            <input
                                name={key}
                                id={index}
                                type="checkbox"
                                checked={this.state.data[key].value}
                                onChange={(event) => this.handleClick(event)} />

                                    {key}

                    )}
                </form>

Current State:

                        {Object.keys(this.state.data).map((key, index) =>

{ `${key}:  ${this.state.data[key]}`}

                        )}

        );
    }
}
ReactDOM.render(<App />, document.getElementById('app'));


texts:
I have written a program to test whether a password contains upper-case, digits and a $.

#include <stdio.h>
#include <conio.h>
#include <ctype.h>
#include<string.h>

int main()
{

    char pass[20];                      //Declaring the array to store pass
    int i,flag1=0, flag2=0, flag3=0;

    printf("Please enter a password having a Upper case letter, a number and also a $ sign \n");
    scanf("%s",&pass);

        {
            for(i=0;i<=strlen(pass);i++)
            if( isupper(pass[i]) )
            flag1=1;
            else if(isdigit(pass[i]))               //Loop to check if all element in pass has a digit, alpha & '$'
            flag2=1;
            else if(pass[i]=='$')
            flag3=1;
        }
                {
                    if((flag1==1) && (flag2==1) && (flag3==1))      //All condition true
                    {
                    printf("\nNice Password!");
                    }
                    else
                        {
                        printf("\nPassword must contain a upper case letter, a number and a $ sign");  //Something missing
                        }
                }

            return 0;
}


texts: Extract logic applied in a sequence of integers

texts:
I've done it in C# before but thought that a functional language would be a good fit for this kind of thing.

From this ascending list of integers:

  [100,103,106,112,118,121]

I had to calculate the difference between two consecutive numbers and group them while the result doesn't change. The final output must be a string like this:

  "(group.length x difference)+(next group.length + next diff)+.."

Note that a same difference can appear multiple times in the sequence if it's not consecutive.

For this sample: "2x3+2x6+1x3"

import Data.List

countDelta :: [[a]] -> [(Int,a)]
countDelta [] = []
countDelta [[]] = []
countDelta ( (y:zs) : (bs) ) =  (length zs + 1, y) : countDelta bs

groupByDelta :: [Int] -> [(Int,Int)]
groupByDelta (xs) = countDelta ( group [b-a | (a:b:_) <- tails xs] )

printTuples :: [(Int, Int)] -> String
printTuples [] = ""
printTuples [(x,y)] = show x ++ "x" ++ show y
printTuples (x:xs) = printTuples [x] ++ "+" ++ printTuples xs

getSequenceLogic :: [Int] -> String
getSequenceLogic [] = ""
getSequenceLogic [x] = printTuples [(1,0)]
getSequenceLogic (xs) = printTuples (groupByDelta xs)

Sample call:

getSequenceLogic [100,103,106,112,118,121]

I get the expected result but is there any obvious error?


texts: Click handlers for edit and save buttons

texts:
I have the following code from a JavaScript file:

$("body").on("click",".edit",function(){
    var list=$(this).closest("a").data("list");
    var seira=$(this).closest("a").data("order");
    //alert(navbar_edit[list][seira]);
    var edit=navbar_edit[list][seira];
    navbar_edit[list][seira]=prompt("Change property",edit);
    exportLists();

});
$("body").on("click",".edit-save",function(){
    var property=$(this).closest("a").text();
    property=property.substring(0,property.length-4);
    alert(property);
    var list=$(this).closest(".list-group").attr("id");
    list=list.substring(list.length-1);
    navbar_edit[list].push(property);
    exportLists();
});

As you can see, I use $("body") 3 times to execute 3 different actions. Is there any way to use it only once so I can reduce my code?


texts:
There is a Min-Heap implementation in Java. BubbleUp() and BubbleDown() could have been coded using recursion but I prefer without recursion. Would there be a major difference if had used recursion?

package heap;

import interfaces.queue.PriorityQueue;
import java.util.Arrays;
import java.util.stream.Collectors;

public class Heap<T extends Comparable<T>> implements
PriorityQueue<T>
{
    private T[] elements;
    private int size;
    private int capacity;

    public Heap()
    {
        this(500);
    }

    public Heap(int capacity)
    {
        this.capacity = capacity;
        size = 0;
        elements = (T[]) new Comparable[this.capacity];
    }

    public int size()
    {
        return size;
    }

    public boolean isEmpty()
    {
        return size() == 0;
    }

    @Override
    public void add(T data) throws Exception
    {
        if(size() >= capacity) throw new Exception("Heap is full");
        elements[size++] = data;
        bubbleUp();
    }

    private void bubbleUp()
    {
        int child = size() - 1;
        int parent = (child-1)/2;

        while(parent >= 0 && elements[child].compareTo(elements[parent]) < 0)
        {
            swap(child, parent);
            child = parent;
            parent = (child-1)/2;
        }
    }

    @Override
    public T removeMin() throws Exception
    {
        if(isEmpty()) throw new Exception("Empty heap");
        T root = elements[0];
        swap(size()-1, 0);
        elements[size()-1] = null;
        size--;
        bubbleDown();
        return root;
    }

    private void bubbleDown()
    {
        int parent = 0;
        int leftChild = 2*parent + 1;
        int rightChild = 2*parent + 2;

        int choice = compareAndPick(leftChild, rightChild);

        while(choice != -1)
        {
            swap(choice, parent);
            parent = choice;
            choice = compareAndPick(2*choice+1, 2*choice+2);
        }
    }

    private int compareAndPick(int leftChild, int rightChild)
    {
        if(leftChild >= capacity || elements[leftChild] == null) return -1;
       if((elements[leftChild].compareTo(elements[rightChild]) <= 0)|| (elements[rightChild] == null))
            return leftChild;
        return rightChild;
    }

    private void swap(int child, int parent)
    {
        T t = elements[child];
        elements[child] = elements[parent];
        elements[parent] = t;
    }

    @Override
    public String toString()
    {
         return Arrays.stream(elements)
                 .filter(element -> element != null)
                 .collect(Collectors.toList()).toString();
    }
}


texts:
Is it possible to shorten the Isnull checking?

It would be great to shorten this code and only have to put the datarow once.

This code imports data details (usually there would be more .x = IIF.... statements)

 Public Class apPropertyFunctions

        Public Function GetProperty(ByVal sUPRN As String) As apProperty
            'Public Function GetProperty(ByVal sUPRN As String, ByVal sUCARN As String) As apProperty
            Try

                Dim vIP As String = HttpContext.Current.Request.ServerVariables("REMOTE_ADDR")
                Dim oDetails As New apProperty

                Dim sConnString As String = System.Web.Configuration.WebConfigurationManager.ConnectionStrings("SQL_DEMO").ConnectionString
                Dim dsNames As SqlDataSource

                dsNames = New SqlDataSource

                dsNames.ConnectionString = sConnString
                Dim sSQL As String
                sSQL = "spGetProperty"
                dsNames.SelectCommand = sSQL
                dsNames.SelectCommandType = SqlDataSourceCommandType.StoredProcedure
                dsNames.SelectParameters.Clear()
                dsNames.SelectParameters.Add("ID", ID)

                For Each datarow As Data.DataRowView In dsNames.Select(DataSourceSelectArguments.Empty)

                    With oDetails
                        .ID= datarow("ID").ToString
     .BuildingNo = IIf(datarow("BuildingNo").Equals(DBNull.Value), "", datarow("BuildingNo").ToString)
                    End With

                    '  End If
                Next

                dsNames = Nothing

                Return oDetails

            Catch ex As Exception
                Return Nothing
            End Try

        End Function


texts: Function to take a positive integer and return the next bigger number formed by the same digits

texts:
I've written a solution to a Codewars challenge:

  You have to create a function that takes a positive integer number and returns the next bigger number formed by the same digits:

  12 ==> 21; 513 ==> 531; 2017 ==> 2071

I am getting the following error on Codewars: "Execution Timed Out (12000 ms)". I am a rookie, and would appreciate if anyone could give me some suggestions on optimizing my code, as this is something I know very little about.

I've made some minor tweaks but nothing that really reconstructs the solution from the ground up.

//takes a num and finds the next biggest num composed of the same digits.

function nextBigger(num) {
  let newNum = 0;
  let otherNum = 0;
  let indicator = 0;
  while (num > newNum) {
    if (indicator === 0) {
      otherNum = num;
      indicator++;
      continue;
    }

    if (
      String(num)
        .split("")
        .sort()
        .join("") ===
      String(otherNum)
        .split("")
        .sort()
        .join("")
    ) {
      if (otherNum > num) {
        newNum = otherNum;
      }
    }

    otherNum++;
  }

  return newNum;
}


texts: Copy Excel file and make multiple daily versions

texts:
Every month my department has to generate blank upload files (xlsx) for each day of the month.

The following code helps this process by copying a template, iterating through the number of days of the current month, and generating a file for each of those days from the template.

I found the copy_rename function which helped a ton.

I'm looking for any feedback pertaining to:

Can I avoid the format_Num function somehow?
Do I need to .close() the file, since I didn't open it?
Layout of the code: can I have my functions at the very bottom so that the code comes up first?

# checks whether a number is single digit or not
def format_Num(num):
num = str(num)

if len(num) == 1:
    return(str(0) + str(num))
else:
    return str(num)

#function copies a file from one dir, to another

def copy_rename(old_file_name, new_file_name):
    src_dir= "C:\\a\\dir\\Desktop"
    dst_dir= "C:\\a\\different\\dir\\TESTPYTHONFILES"
    src_file = os.path.join(src_dir, old_file_name)
    shutil.copy(src_file,dst_dir)

dst_file = os.path.join(dst_dir, old_file_name)
new_dst_file_name = os.path.join(dst_dir, new_file_name)
os.rename(dst_file, new_dst_file_name)

from calendar import monthrange
import shutil
import os
import datetime

now = datetime.datetime.now()
curr_year = now.year #2018
curr_month  = now.month #04

total_month_days = monthrange(curr_year, curr_month)[1] + 1
filepath = "C:\\a\\dir\\Desktop"
template = "Template.xlsx"

for day in range(1, total_month_days):

wb_Name = "workFeed" + str(curr_year) + format_Num(curr_month) + format_Num(day) + ".xlsx"
path_n_fileName = os.path.join(filepath + wb_Name)

# verifies that the file does not exist
if os.path.isfile(path_n_fileName) != True:
    copy_rename(template, wb_Name)


texts: Use functional-programming to convert a tree of parent:children objects to array

texts:
Having some trouble with a code I'm trying to refactor, where I need to go over a 'tree' of items, filter some invalid items, and create a new array of filtered items which takes properties from both parent and child objects.

To demo the problem I made a quick snippet -

const items = [
  {
    name: 'Shirley Hardin',
    isValid: true,
    children: [
      {
        name: 'Mildred Mata',
        isValid: true,
      },
      {
        name: 'Christopher Herring',
        isValid: false,
      },
    ],
  },

  {
    name: 'Tad M. Colbert',
    isValid: false,
    children: [
      {
        name: 'James J. Spencer',
        isValid: true,
      },
    ],
  }
];

function toParentChildModel(parent, child) {
  return {
    parentName: parent.name,
    childName: child.name,
  };
}

function getValidChildParent(list) {
  const validParentChild = [];
  for (let i=0; i<list.length; i++) {
    const parent = list[i];
    if (parent.isValid) {
      for (let j=0; j<parent.children.length; j++) {
        const child = parent.children[j];
        if (child.isValid) {
          validParentChild.push(toParentChildModel(parent, child));
        }
      }
    }
  }
  return validParentChild;
}

function print(list) {
  console.log(list);
}

print(getValidChildParent(items));

The code can also be found at here

How would you refactor this code, specifically the 'getValidChildParent' function, in a functional way?


texts:
Suppose I have some expensive function expensive_computation which takes a long time to compute but it always returns the same value.

I want to avoid paying the cost of computing this function because it may never be called.

Here is my solution to this, is there a more obvious or clean way to do it? Or maybe even some function from the standard library?

def lazy(function):

  internal_state = None

  def lazy_evaluation():
    nonlocal internal_state
    if internal_state is None:
      internal_state = function()
    return internal_state

  return lazy_evaluation

@lazy
def expensive_computation():
  print("Working ...")
  return "that was hard"

print(expensive_computation())
print(expensive_computation())

Which prints:

Working ...
that was hard
that was hard


texts: Prim's Algorithm using heapq module in python

texts:
Implementing Prim's with a \$O(m\log n)\$ run time using heaps, similar to Dijkstra heap implementation. Where \$n\$ is the number of nodes, and \$m\$ is the number of edges. Using the heapq library I tried to create a delete function for my heap ('unexplored') so that this heap only stores crossing edges at every iteration of outer While loop. That didn't work, I got amazing runtime but wrong result, so I just cut corners and used heapify and inf. But now the run time is around \$O(nm)\$, but I do get the correct answer now though.

graph is a dict, which contains adjacency lists of an undirected graph as:

{v1: [[v2, cost2], [v3, cost3],... ]... }

from math import inf
from heapq import heappush, heappop, _siftup, _siftdown, heapify
from time import time

def prims(graph):
    start = list(graph)[0]
    explored, treeCosts = set([start]), []

    unexplored = []
    for v in graph[start]:
        heappush(unexplored, [v[1], v[0]])

    while explored != set(graph):
        winner = heappop(unexplored)

        explored |= set([winner[1]])
        treeCosts.append(winner[0])

        #deleting edges which have head at 'winner'
        for v in unexplored:
            if v[1] == winner[1]:
                v[0] = inf
                '''i = unexplored.index(v)
                unexplored[i], unexplored[-1] = unexplored[-1], unexplored[i]
                unexplored.pop()
                if i < len(unexplored):
                    _siftup(unexplored, i)
                    _siftdown(unexplored, 0, i)'''
        heapify(unexplored)

        #adding the new crossing edges to heap
        for v in graph[winner[1]]:
            if v[0] not in explored:
                heappush(unexplored, [v[1], v[0]])

    return sum(treeCosts)

if __name__ == '__main__':
    draft, graph = open('undirectedGraph (weighted, 500).txt').read().splitlines(), {}

    for line in draft[1:]:
        edge = list(map(int, line.split()))
        if edge[0] not in graph:
            graph[edge[0]] = []
        if edge[1] not in graph:
            graph[edge[1]] = []

        graph[edge[0]].append(edge[1:])
        graph[edge[1]].append([edge[0], edge[2]])

    startTime = time()
    print('Good prims: ' + str(prims(graph)) + ', ' + 'Time: ' + str(time() - startTime))


texts: HTTP redirects after login, registration, and logout

texts:
I am using following classes/interface to redirect user (after login, register, logout etc.)

File: RedirectInterface.php

interface RedirectInterface
{
    public function getUrl($customerId = null);
}

File: LoginRedirect.php

class LoginRedirect implements RedirectInterface
{
    public function getUrl($customerId = null)
    {
        // do some business logic here to get url
        $url = '/account/some-customer';
        return $url;
    }
}

File: RegisterRedirect.php

class RegisterRedirect implements RedirectInterface
{
    public function getUrl($customerId = null)
    {
        // do some business logic here to get url
        $url = '/welcome/some-customer';
        return $url;
    }
}

File: RedirectFactory - Creational design pattern (static factory)

class RedirectFactory
{
    public static function build($type, $customerId)
    {
        if ($type == 'login') {
            return new LoginRedirect($customerId);
        } else if ($type == 'register') {
            return new RegisterRedirect($customerId);
        }
        throw new InvalidArgumentException ('Invalid redirect type.');
    }
}

Usage:

// 1. Usage: Somewhere in customer registration code
$redirectUrl = RedirectFactory::build('register', 102)->getUrl();
header('Location: ' . $redirectUrl);

// 2. Usage: Somewhere in customer login code
$redirectUrl = RedirectFactory::build('login', 102)->getUrl();
header('Location: ' . $redirectUrl);

If you were given a chance to refactor this code. How would you have re-developed it?


texts: Gaining better performance when screen scraping is required

texts:
I have a website on which for every request, the scraping of other websites is done to get accurate data. While it works well, it has a slight impact on the performance.

public ActionResult Index(int id)
{
    Product product = pe.Products.Where(p => p.Id == id).First();
    foreach (var pricing in product.Retailer_Product_Prices)
    {
        switch (pricing.RetailerId)
        {
            case 1:
                pricing.Price = PriceCompareStatic.GetFlipKart(pricing.Url);
                if (pricing.Url.Contains("?"))
                    pricing.Url = pricing.Url + "&affid=pankajupad";
                else
                    pricing.Url = pricing.Url + "?affid=pankajupad";
                break;
            case 3:
                pricing.Price = PriceCompareStatic.GetHomeShop(pricing.Url, "//span[@class='pdp_details_hs18Price']");
                break;
            .
            .
            .  // Removed for brevity
            default:
                break;
        }
        product.BasePrice = product.Retailer_Product_Prices.Min(p => p.Price);
    }
    return View(product);
}

PriceCompareStatic

public static decimal GetFlipKart(string url)
{
    var baseUrl = new Uri(url);
    HtmlAgilityPack.HtmlDocument document = new HtmlDocument();
    try
    {
        WebClient client = new WebClient();
        document.Load(client.OpenRead(baseUrl));
        var div = document.DocumentNode.SelectNodes("//meta[@itemprop='price']").FirstOrDefault();
        HtmlAttribute att = div.Attributes["content"];
        string modPrice = att.Value.Replace("Rs. ", "");
        return Convert.ToDecimal(modPrice);
    }
    catch (Exception)
    {
        return 123456789;
    }
}

public static decimal GetSpanFromWebSite(string url, string identification)
{
    var baseUrl = new Uri(url);
    HtmlAgilityPack.HtmlDocument document = new HtmlDocument();
    try
    {
        WebClient client = new WebClient();
        document.Load(client.OpenRead(baseUrl));
        var div = document.DocumentNode.SelectNodes(identification).FirstOrDefault();
        return Convert.ToDecimal(div.InnerHtml);
    }
    catch (Exception)
    {
        return 123456789;
    }
}
.
.
. // Removed for brevity

Do you think shifting from shared hosting to ones own server will help with such requirements?


texts: Saving a submitted Mongoose model, possibly with an uploaded image

texts:
I have some code which saves a mongoose model from the submitted form data. However the user might also upload an image along with the form, which needs to be saved on the server (moved from the buffer).

Here is my first attempt:

// Save a new job to the database.
exports.save = function(req, res, next) {
  // If the request contains a file, generate a file name for it.
  if (req.file) req.body.logoImage = generateFileName(req.file.mimetype)

  // Save the job to the database.
  Job.create(req.body)
    .then(job => {
      // Move the file from the buffer to the uploads folder.
      if (job.logoImage) {
        moveFile(req.file.buffer, job.logoImage).then(() => {
          res.json({ status: 'Uploaded job successfully.' })
        })
      } else {
        res.json({ status: 'Uploaded job successfully.' })
      }
    })
    .catch(error => next(error))
}

I would like to avoid having to write duplicate code for sending the response.

The problem is that moveFile return a Promise so simply doing this won't work, because the response will be sent before the file is moved (and moving it might fail)!

if (job.logoImage) {
    moveFile(req.file.buffer, job.logoImage)
}
res.json({ status: 'Uploaded job successfully.' })

To get around this, I came up with the following code:

// Save a new job to the database.
exports.save = function(req, res, next) {
  // If the request contains a file, generate a file name for it.
  if (req.file) req.body.logoImage = generateFileName(req.file.mimetype)

  // Save the job to the database.
  Job.create(req.body)
    .then(job => {
      // Move the file from the buffer to the uploads folder.
      if (job.logoImage) {
        return moveFile(req.file.buffer, job.logoImage)
      }
      return Promise.resolve()
    })
    .then(() => {
      res.json({ status: 'Uploaded job successfully.' })
    })
    .catch(error => next(error))
}

Would there be a better way maybe?


texts: Proportional sorting of web scrape results

texts:
If you have a given list of lists what's the best way to sort them proportionally? Is there a better way to do this?

The idea is that in a case of web scraping, you would want to avoid hitting google all the time and want to distribute calls so that they are as even as possible.

Is this a thing that can be done more efficiently than this terribad code that I wrote?

urls = [
        ['http://google.com/search','redirect.com', 0],
        ['http://duckduckgo.com/search','redirect.com', 0],
        ['http://google.com/search','redirect.com', 0],
        ['http://bing.com/search','redirect.com', 0],
        ['http://yahoo.com/search','redirect.com', 0],
        ['http://yahoo.com/search','redirect.com', 0],
        ['http://google.com/search','redirect.com', 0],
        ['http://bing.com/search','redirect.com', 0],
        ['http://google.com/search','redirect.com', 0],
        ['http://google.com/search','redirect.com', 0],
        ['http://yahoo.com/search','redirect.com', 0],
        ['http://altavista.com/search','redirect.com', 0],
        ['http://google.com/search','redirect.com', 0],
        ['http://yahoo.com/search','redirect.com', 0],
        ['http://google.com/search','redirect.com', 0],
        ['http://altavista.com/search','redirect.com', 0],
        ['http://google.com/search','redirect.com', 0]
    ]

def get_domain( url ):
    domain = ''
    parts = tldextract.extract( url )
    if parts.subdomain != '' and parts.subdomain != 'www':
        domain = parts.subdomain + '.' + parts.domain + '.' + parts.suffix
    else:
        domain = parts.domain + '.' + parts.suffix
    return domain

def proportional_sort( urls ):
    doms = [get_domain(url[0]) for url in urls]
    dom_set = set(doms)

    matrix = {}
    for domain in dom_set:
        sublist = [item for item in urls if get_domain(item[0]) == domain]
        # print sublist
        random.shuffle(sublist)
        if len(sublist) in matrix:
            matrix[len(sublist)][domain] = sublist
        else:
            matrix[len(sublist)] = {}
            matrix[len(sublist)][domain] = sublist

    # print matrix.keys()

    map_vector = []

    for key in matrix:
        map_vector += [key] * key * len(matrix[key])
        map_vector = sorted(map_vector, key=int)

    # print map_vector

    proportionally_sorted = []

    for pos in map_vector:
        if pos in matrix:
            rand_pos = [pos]
            for key in matrix.keys():
                if key % pos == 0:
                    rand_pos.append(key)
            for position in rand_pos:
                rand_keys = matrix[position].keys()
                random.shuffle(rand_keys)
                for key in rand_keys:
                    rand = rand_keys.pop()
                    if matrix[position][rand]:
                        proportionally_sorted.append(matrix[position][rand].pop())
                        break
                    else:
                        continue

    return proportionally_sorted


texts:
So, I am learning Swift and as a little exercise I tried to implement a BruteForce algorithm. That algorithm is pretty simple however it is a bit slow too... Well, I am new to Swift, so maybe some optimisations are possible ?
Let's start with some useful prerequisites:
extension String {
    var digits:      String { return "0123456789" }
    var lowercase:   String { return "abcdefghijklmnopqrstuvwxyz" }
    var uppercase:   String { return "ABCDEFGHIJKLMNOPQRSTUVWXYZ" }
    var punctuation: String { return "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~" }
    var letters:     String { return lowercase + uppercase }
    var printable:   String { return digits + letters + punctuation }

    mutating func replace(at index: Int, with character: Character) {
        var stringArray = Array(self)
        stringArray[index] = character
        self = String(stringArray)
    }
}

Let's now implement the BruteForce algorithm
func indexOf(character: Character, _ array: [String]) -> Int {
    return array.firstIndex(of: String(character))!
}

func characterAt(index: Int, _ array: [String]) -> Character {
    return index < array.count ? Character(array[index])
                               : Character("")
}

func generateBruteForce(_ string: String, fromArray array: [String]) -> String {
    var str: String = string

    if str.count <= 0 {
        str.append(characterAt(index: 0, array))
    }
    else {
        str.replace(at: str.count - 1,
                    with: characterAt(index: (indexOf(character: str.last!, array) + 1) % array.count, array))

        if indexOf(character: str.last!, array) == 0 {
            str = String(generateBruteForce(String(str.dropLast()), fromArray: array)) + String(str.last!)
        }
    }

    return str
}

Now we can use it that way
import Foundation

let ALLOWED_CHARACTERS:   [String] = String().printable.map { String($0) }
let MAXIMUM_PASSWORD_SIZE:   Int   = 3

var password: String = ""

// Will strangely ends at 0000 instead of ~~~
while password.count <= MAXIMUM_PASSWORD_SIZE { // Increase MAXIMUM_PASSWORD_SIZE value for more
    password = generateBruteForce(password, fromArray: ALLOWED_CHARACTERS)
    // Your stuff here
    print(password)
    // Your stuff here
}

It will print
0
1
2
[...]
{
|
}
~
00
01
and so on...


texts: Fibonacci number function: convert to tail-recursion?

texts:
I've been implementing a function for calculating the nth Fibonacci number in F#.  So far the best implementation I could come up with is this:

let fib n =
    let rec fib =
        function
        | 0 -> 0I, 1I
        | n ->
            let f1, f2 = fib (n / 2)
            let f1' = f1 * (2I * f2 - f1)
            let f2' = f2 * f2 + f1 * f1
            if n % 2 = 0 then
                (f1', f2')
            else
                (f2', f1' + f2')
    fib n |> fst

Can it be improved or written in a more F#-idiomatic way?

Also, as a separate question, can it be rewritten to be tail-recursive?


texts:
I am working on a Windows project using C++03 (C++11 is not an option), and without using Boost. I have several resources that are accessed by multiple threads at various times - a queue, for example, with data added by one thread and removed by another.  Individual methods of the involved classes generally perform locking internally.  However in some cases I need to lock the entire resource to perform a sequence of actions without another thread getting in the way.

Without the phrases "use Boost" and "use C++11", does the posted code for RAII-style locking of a resource look correct and safe, or is there something I've missed?

To this end I have written a simple RAII-style locking class, so that the following can be performed:

void somefunction(void) {
    GetLock<LockableClass> lock(queue);
    ...
}

Here the only requirement of LockableClass is that is has Lock() and Unlock() methods.  Specialisations of the class are provided for CRITICAL_SECTION, etc.

However, in the case of there being several queues, only some of which need to be locked at one time, I would like the following to be possible:

void somefunction(void) {
    list<GetLock<LockableClass> > locks;
    for (vector<LockableClass>::iterator its = queues.begin(); queues.end() != its; ++its)
        if (some_condition)
            locks.push_back(GetLock<LockableClass>(*its));
    ...
}

In order to achieve this I've added a copy-constructor to GetLock.  This creates the requirement that any lockable object has to have some kind of reference counting.  It also limits me to using a std::list as the container for the locks - at least in my version of Visual Studio (2008 - yes, yes, I know).  std::vector appears to default-construct, then assign.

The following is the code for GetLock, along with a specialisation for CRITICAL_SECTION:

template <typename TLOCKABLE>
class GetLock {
private:
    TLOCKABLE& lock;
    GetLock();
public:
    GetLock(TLOCKABLE& plock) : lock(plock) {
        lock.Lock();
    }
    GetLock(TLOCKABLE* plock) : lock(*plock) {
        lock.Lock();
    }
    GetLock(const GetLock<TLOCKABLE>& plock) : lock(plock.lock) {
        lock.Lock();
    }
    ~GetLock(void) {
        lock.Unlock();
    }
};

template <>
class GetLock<CRITICAL_SECTION> {
private:
    CRITICAL_SECTION& lock;
    GetLock();
public:
    GetLock(CRITICAL_SECTION& plock) : lock(plock) {
        EnterCriticalSection(&lock);
    }
    GetLock(const GetLock<CRITICAL_SECTION>& plock) : lock(plock.lock) {
        EnterCriticalSection(&lock);
    }
    ~GetLock(void) {
        LeaveCriticalSection(&lock);
    }
};

// There is also a specialisation for HANDLE, to cope with mutexes...
// This presents its own issues as HANDLE is used everywhere in Windows,
// but differentiating between a Mutex and something else is a question
// for StackOverflow.

Does the code look safe? Is there something I've missed? Is making the assumption of using recursively-lockable objects a foolhardy thing to do? What could I do better?


texts:
I have this number returned from an Ajax request: 015-0011-00001. I want to increment the last part of the number (00001) on document load. What I did was get the last number and increment it then combine the numbers again. Is there a cleaner way of incrementing this number without slicing the number into many parts?

DEMO

var data = [{"code":"456100010011","incrementingnumber":"015-0011-00001"}];

var code = data[0].code;
var inc = data[0].incrementingnumber;
var res = code.slice(-4);
var inc1 = inc.slice(-4);
//alert(inc1);
var inc2 = parseInt(inc1) + 1;

var incrementvalue = ("00000" + inc2).slice(-5); // -> result: "0001"

console.log("015-" + res + "-" + incrementvalue);


texts: Loading the resource identified by a script element's src attribute

texts:
I have a function to load the resource identified by a <script> element's src attribute.

I need it to:

Be as universal as possible.
Work on file-to-file requests (from file:// to file://), if the browser allows to.

This is the code I have so far:

var asyncGetContents = function(node,listener){
   var hasRun = false;
   if(node.src){
      var httpRequest = new XMLHttpRequest();
      httpRequest.onreadystatechange = function() {
         if(httpRequest.responseText){
            if(hasRun){return;}
            hasRun = true;
            listener(httpRequest.responseText);
            httpRequest.onreadystatechange=undefined;
         }
      };
      httpRequest.open('GET', node.src);
      if(node.type){
         httpRequest.overrideMimeType(node.type);
      }
      httpRequest.send();
   }else{
      listener(node.textContent);
   }
};

Is this code well-formed?
Are there any aspects that I could've possibly missed?
Is there any way to do it without the variable hasRun? Removing the onReadyStateChange event listener doesn't seem to work - listener function runs twice.


texts: Is there a way to eliminate the repetition in this linq query?

texts:
This is a query to return search results, but I feel it could be cleaned up a little.  I just don't know how.

var queryResult = (from r in dc.Retailers
                    where
                        (string.IsNullOrEmpty(firstName) ||
                        SqlFunctions.PatIndex(firstName.Trim(), r.FirstName.Trim()) > 0) &&
                        (string.IsNullOrEmpty(lastName) ||
                        SqlFunctions.PatIndex(lastName.Trim(), r.LastName.Trim()) > 0) &&
                        (string.IsNullOrEmpty(companyName) ||
                        SqlFunctions.PatIndex(companyName.Trim(), r.CompanyName.Trim()) > 0) &&
                        (string.IsNullOrEmpty(phone) ||
                        SqlFunctions.PatIndex(phone.Trim(), r.Phone.Trim()) > 0) &&
                        (string.IsNullOrEmpty(email) ||
                        SqlFunctions.PatIndex(email.Trim(), r.Email.Trim()) > 0) &&
                        (string.IsNullOrEmpty(city) ||
                        SqlFunctions.PatIndex(city.Trim(), r.City.Trim()) > 0) &&
                        (string.IsNullOrEmpty(zip) ||
                        SqlFunctions.PatIndex(zip.Trim(), r.Zip.Trim()) > 0) &&
                        (string.IsNullOrEmpty(state) ||
                        SqlFunctions.PatIndex(state.Trim(), r.State.Trim()) > 0) &&
                        (string.IsNullOrEmpty(country) ||
                        SqlFunctions.PatIndex(country.Trim(), r.Country.Trim()) > 0)
                    select r
    );

Update: For those confused by the query.  Here is another version, which is probably better because it only builds the where parts when necessary.  But I would still like to reduce the repetition.

var queryResult = (from r in dc.Retailers select r);
if (!string.IsNullOrEmpty(firstName))
    queryResult = queryResult.Where(ex => SqlFunctions.PatIndex(firstName.Trim(), ex.FirstName.Trim()) > 0);
if (!string.IsNullOrEmpty(lastName))
    queryResult = queryResult.Where(ex => SqlFunctions.PatIndex(lastName.Trim(), ex.LastName.Trim()) > 0);
if (!string.IsNullOrEmpty(companyName))
    queryResult = queryResult.Where(ex => SqlFunctions.PatIndex(companyName.Trim(), ex.CompanyName.Trim()) > 0);
if (!string.IsNullOrEmpty(phone))
    queryResult = queryResult.Where(ex => SqlFunctions.PatIndex(phone.Trim(), ex.Phone.Trim()) > 0);
if (!string.IsNullOrEmpty(email))
    queryResult = queryResult.Where(ex => SqlFunctions.PatIndex(email.Trim(), ex.Email.Trim()) > 0);
if (!string.IsNullOrEmpty(city))
    queryResult = queryResult.Where(ex => SqlFunctions.PatIndex(city.Trim(), ex.City.Trim()) > 0);
if (!string.IsNullOrEmpty(zip))
    queryResult = queryResult.Where(ex => SqlFunctions.PatIndex(zip.Trim(), ex.Zip.Trim()) > 0);
if (!string.IsNullOrEmpty(country))
    queryResult = queryResult.Where(ex => SqlFunctions.PatIndex(country.Trim(), ex.Country.Trim()) > 0);
if (!string.IsNullOrEmpty(state))
    queryResult = queryResult.Where(ex => SqlFunctions.PatIndex(state.Trim(), ex.State.Trim()) > 0);


texts: Angular wrapper for SignalR event aggregator

texts:
I created a little wrapper for one of my JavaScript libraries to enable Angular functionality. Are there any pitfalls I should be wary of with my code?

angular.module("signalR.eventAggregator", [])
    .run([
        "$rootScope", function($rootScope) {
        function createScope(scope) {
            scope.$on('$destroy', function() {
                signalR.eventAggregator.unsubscribe(scope);
            });

            return {
                subscribe: function(type, handler, constraint) {
                    signalR.eventAggregator.subscribe(type, function(e) {
                        handler(e);
                        if (scope.$$phase == null) {
                            scope.$digest();
                        }
                    }, scope, constraint);
                },
                publish: function(event) {
                    signalR.eventAggregator.publish(event);
                }
            }
        }

        $rootScope.eventAggregator = function() {
            return this.__eventAggregator = this.__eventAggregator || createScope(this);
        };
    }
]);

More info on the code itself here.

It's used like this:

$scope.eventAggregator().subscribe(MyApp.MyEvent, onEvent);

Other scenarios it supports are

Generic events, (all events are server events proxied to javascript through a dynamic Owin javascript)

$scope.eventAggregator().subscribe(MyApp.MyGenericEvent.of("System.String"), onEvent);

Constraints, in this case listen to all events with id 5

$scope.eventAggregator().subscribe(MyApp.MyEvent, onEvent, { id: 5 });

It wraps an event-driven library, and when an event is triggered, I use digest to update the view, and it's this part of the code that I wonder about.

handler(e); could return a promise that I currently ignore. I tested the ng-click directive and it also ignores any promise returned from the click handler. So at least it's consistent with the existing event handlers in Angular.


texts:
Here's a function:

func checkIfObjectsHaveCoordinates() {
    PFQuery(className: "Products").findObjectsInBackgroundWithBlock {
        (objects: [PFObject]?, error: NSError?) -> in
        if error == nil && objects != nil {
            for object in objects! {
                if object["Latitude"] == nil || object["Longitude"] == nil {
                    self.convertObjectLocationToCoordinates(object)
                }
                object.pinInBackground()
            }
        } else {
            print(error)
        }
}

It checks if objects have a latitude or a longitude. If they don't, they will be passed to the convertObjectLocationToCoordinates function. Either way, I save them locally, and this is why I think my function should't have side effects. I feel like this code is hardcoded in some way:

if myObject["Latitude"] == nil || myObject["Longitude"] == nil || myObject["Latitude"] as! Float == 0 || myObject["Longitude"] as! Float == 0

Does this function look good to you?  Should I avoid side effects in my function?


texts: Vertically placing the words in a string

texts:
Please let me know a better approach to solve below problem:

Problem: Vertically arrange the words in a string and print on console.

Sample Input:

Hello Jack

Output:

H J
e a
L c
L k
o

My solution:

public static void toVerticalWords(String str){

        //split the words by whitespace
        String[] strArr = str.split("\\s");
        int maxWordLen = 0;

        //get the longest word length
        for(String strTemp : strArr) {
            if(strTemp.length() > maxWordLen)
                maxWordLen = strTemp.length();
        }

        //make a matrix of the words with each character in an array block
        char[][] charArr = new char[strArr.length][maxWordLen];
        for(int i=0; i<strArr.length; i++) {
            int j=0;
            for(char ch : strArr[i].toCharArray()){
                charArr[i][j] = ch;
                j++;
            }
        }

        //print the vertical word pattern, or transpose of above matrix (2D array)
        for(int j=0; j<maxWordLen; j++) {
            for(int i=0; i<strArr.length; i++) {
                if (i!=0)
                    System.out.print(" ");
                System.out.print(charArr[i][j]);
            }

            System.out.println();
        }
    }


texts: Prefered Style Container for the Components in the DataTemplate

texts:
The following XAML is a close (tidied up) version of what I have use in my WPF application. If you have noticed there are two Styles applied to the same component (Border in this example.)

I would like to know how can I merge the 2nd Style into 1st to make it apply to all the Borders included in the DataTemplate.

<DataTemplate DataType="{x:Type m:myFoo}">
  <DataTemplate.Resources>
    <!-- 1) Style Applied to the Border -->
    <Style TargetType="Border">
      <Setter Property="Margin" Value="1"/>
    </Style>
  </DataTemplate.Resources>
  <Border>
    <Grid>
      <Border>
        <!-- Guts -->
      <Border>
    </Grid>
    <Border.Style>
      <!-- 2) Style Applied to the Border -->
      <Style TargetType="Border">
        <Style.Triggers>
          <DataTrigger Binding="{Binding Path=Active}">
            <Setter Property="Background" Value="OrangeRed"/>
          </DataTrigger>
        </Style.Triggers>
      </Style>
    </Border.Style>
  </Border>
</DataTemplate>

I am familiar with the fact that 2nd Style will only apply to its own component unlike the 1st which will be applied to any Border included in the DataTemplate.


texts:
I am learning python and want to improve my skills in it. So could someone advice of how to improve the code below (this is a simple programming problem taken from one of the web sites). I feel like my code is not really Pythonic.

Problem: Using the Python language, have the function LetterChanges(str) take the str parameter being passed and modify it using the following algorithm. Replace every letter in the string with the letter following it in the alphabet (ie. c becomes d, z becomes a). Then capitalize every vowel in this new string (a, e, i, o, u) and finally return this modified string.

from sets import Set

def LetterChanges(str):
   vowels = Set(['a', 'e', 'i', 'o', 'u'])
   new_str = ''
   for i in str:
      cur_char = i.lower()
      if cur_char == 'z':
         new_str += 'A'
      elif ord(cur_char) >= 97 and ord(cur_char) < 122:
         new_char = chr(ord(i) + 1)
         new_str += (new_char if new_char not in vowels else new_char.upper())
      else:
         new_str += i
   return new_str

if __name__=='__main__':
   print(LetterChanges(raw_input()))


texts:
I am trying to optimise my remove-erase functions by using some attributes of C++ containers. This function should delete all indices defined in std::set form given vector. I am pretty sure that algorithm is functionality-wise working, but every time I see STL implementation or any code using STL I see a lot of checks around which I cannot come up when I am writing my own code.
I decided to practise by trying so I hope for some tips or tricks on how to improve my code-writing skills.
The algorithm is trying to prevent unnecessary copies. So it is copying just the elements that are supposed to survive. It goes by two iterators. One for a destination where the next element should be copied and second the next element that should "survive". When it arrives at the end of the vector minus the number of deleted elements it stops and leaves the rest for erase() function.
//=================================================================================
// Deletes all indexes defined in set from vector. Leverages the advantage of set being
// sorted from the smallest to the highest number and continuity of vector storage.
template <class T, class IdxT>
typename std::vector<T>::iterator remove_indices(std::vector<T>& vector, const std::set<IdxT>& set)
{
    if (set.empty())
    {
        return vector.end();
    }

    auto       nextDelete       = set.begin();
    const auto destinationIndex = *nextDelete;
    auto       destination      = vector.begin();
    auto       source           = vector.begin();
    std::advance(destination, destinationIndex);
    std::advance(source, destinationIndex + 1);
    ++nextDelete;
    auto sourceIndex = destinationIndex + 1;
    while (destination != vector.end() - set.size())
    {
        while (nextDelete != set.end())
        {
            if (sourceIndex == *nextDelete)
            {
                ++source;
                ++nextDelete;
                ++sourceIndex;
            }
        }
        *destination = std::move(*source);
        ++destination;
        ++source;
        ++sourceIndex;
    }
    return destination;
}


texts:
My task is to write a simple shop. The requirements are :

It can have multiple items
Each item its own price and quantity
Each customer basic identifier such as full name
Each customer receives clear receipt
Shop keeps the shopping history

It's meant to be flexible, easy to expand, high performance considered. I'd be grateful if someone could review it and point out what can/should be improved or changed. Thanks!

#include <iostream>
#include <vector>
#include <set>
#include <map>
#include <list>

using namespace std;

class receipt {
private:
    string prodName;
    int quant;

public:
    receipt(const string& prdNm, int qnt)
          : prodName(prdNm), quant(qnt)
    {}
    string getProdName() const { return prodName; }
    int    getQuant() const { return quant; }

};

class client {
private:
    string name;
    vector<receipt> receipts;

public:
    client(const string& n): name(n) {}
    string getName() const { return name; }

    void takeReceipt (const string& prodName, int quant){
        receipts.push_back( receipt(prodName, quant) );
    }

    void printReceipts(int num) const {
        // printing receipts
    }

    bool operator< (const client& c) const {
        return name < c.name;
    }
};

class product {
private:
    string name;
    int price;

public:
    product(const string& n, int p): name(n), price(p) {}
    string getName() const { return name; }
    int getPrice() const { return price; }

    bool operator< (const product& p) const {
        return name < p.name;
    }
};

class record {
private:
    string clientName;
    string prodName;
    int quant;

public:
    record(const string& clNm, const string& prdNm, int qnt)
          : clientName(clNm), prodName(prdNm), quant(qnt)
    {}
    string getClientName() const { return clientName; }
    string getProdName() const { return prodName; }
    int    getQuant() const { return quant; }

};

class shop {
private:
    set<client> clients;
    map<product, int> products;
    list<record> records;

public:
    void addClient(const client& cli) {
        clients.insert(cli);
    }

    void removeClient(const client& cli) {
        clients.erase(cli);
    }

    void addProduct(const product& pr, int quant) {
        products[pr] += quant;
    }

    void removeProduct(const product& pr, int quant) {

        if (products[pr] <= quant)
            products[pr] = 0;
        else
            products[pr] -= quant;
    }

    void doTransaction(client& cli, const product& prod, int quant) {

        if ( clients.find(cli.getName()) == clients.end() )
        {
            // client is not on the list of valid clients.
            return;
        }

        if (products[prod] >= quant)
        {
            // client is buying
            products[prod] -= quant;
            records.push_back( record(cli.getName(), prod.getName(), quant) );
            cli.takeReceipt(prod.getName(), quant);
        }
        else
        {
            // product not available in the quantity
        }
    }

    void printClients() const {
        // printing all the clients
    }

    void printRecords(int num) const {
        // Printing last records of previous transactions
    }

    void printProducts() const {
        // Printing all the available products
    }
};

int main(){

    shop s;
    client cm("Mike"), cj("John"), ca("Andy");
    product pot("potatoe", 5), app("apple", 7), nut("nut", 3);

    s.addClient(cm);
    s.addClient(cj);
    s.addClient(ca);
    s.addProduct(pot, 100);
    s.addProduct(app, 50);
    s.addProduct(nut, 20);

    s.removeClient(ca);
    s.removeProduct(pot, 20);
    s.removeProduct(nut, 20);

    s.doTransaction(cm, pot, 30);
    s.doTransaction(cj, app, 10);
    s.doTransaction(cm, nut, 5);
    s.doTransaction(cm, app, 5);

    return 0;
}


texts: Partition array in at most k subarrays that minimize a function

texts:
I have 2 values \$N\$ and \$K\$ (\$1 \le K \lt N \le 1.000\$), where \$N\$ indicates a number of values (\$0 \le \text{value}2 \le ... \le \text{value}N \le 1,000,000\$) to be read from input. The first value isn't on the input and will always be 0.

All \$N\$ values need to be organized on at most \$K\$ groups where the sum of the groups size is minimized.

The size of a group is defined by the distance between the two most distant values in the group (MAX_VALUE - MIN_VALUE). If the group consists of only one value, its size is zero.

What is the minimum total value for the sum of the groups size if the values are organized optimally?

Here is an input sample:

5 2
1 2 5 6

Output sample:

3

My solution is a brute force search. This is a known problem. How can I do better than this solution?

#include <cstdio>
#include <queue>
#include <vector>
#include <limits>
#include <algorithm>

using groups = std::vector< std::vector<int> >;

int getTotalGroupsSize(groups &g){
    unsigned long k = g.size();

    int total = 0;

    for (unsigned long i = 0; i < k; ++i) {
        int max = std::numeric_limits<int>::min();
        int min = std::numeric_limits<int>::max();

        std::vector<int> &subGroup = g[i];

        for (int j = 0; j < subGroup.size(); ++j) {
            max = std::max(max, subGroup[j]);
            min = std::min(min, subGroup[j]);
        }

        total += (max - min);

    }

    return total;
}

int getOptimallSum(std::queue<int> &q, groups &g){

    if(q.empty())
        return getTotalGroupsSize(g);

    int front = q.front();
    q.pop();

    int minDiff = std::numeric_limits<int>::max();
    for (int i = 0; i < g.size(); ++i) {
        g[i].push_back(front);
        minDiff = std::min(minDiff,getOptimallSum(q, g));
        g[i].pop_back();
    }

    q.push(front);
    return minDiff;
}

int main(void){
    int n,k;

    while (scanf("%d",&n) != EOF) {
        scanf("%d",&k);

        std::queue<int> q;
        q.push(0);
        for (int i = 1; i < n; ++i) {
            int value;
            scanf("%d",&value);
            q.push(value);
        }

        if(k >= n){
            puts("0");
            continue;
        }

        groups g(k);
        printf("%d\n",getOptimallSum(q,g));

    }
    return 0;
}


texts: Multiply all elements in an array except one

texts:
The problem is: loop through a list of numbers and for each one of them get the product of all the others and return a new array.

For example in [1,2,3,4,5] the third element should be 40 because 1 × 2 × 4 × 5 = 40

I'm looking for feedback on efficiency and good practices.

function main(numbers) {
    var result = [];
    for (var i in numbers) {
        var n = 1;
        for (var j in numbers) {
            if (i != j) {
                n *= numbers[j];
            }
        }
        result.push(n);
    }
    return result;
}

var a = [2, 6, 9, 31, 55];

console.log(main(a).toString());


texts: Coffee machine that adds condiments dynamically

texts:
I want to make a coffee machine class which can produce coffee with condiments I like, and the price of the final coffee can be easily calculated.

I chose decorator pattern in my design. I've tried making the fields private to follow the principle of making scope as small as possible, but when I implemented the concrete decorator, the getName() caused trouble, I can not use getName() of the beverage in getName() of Milk(ConcreteDecorator). So finally I chose protected.

I've considered this post about using private over protected, but I don't know which one should be better in my implementation. This is a small program but I need some advice about the big picture which I should keep in mind.

So, any advice about any layer of the design of my code is appreciated.

public abstract class Beverage {
    protected final String name;

    public Beverage(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public abstract Double getCost();
}

public class HouseBlend extends Beverage {
    public HouseBlend() {
        super("HouseBlend");
    }

    @Override
    public Double getCost() {
        return 1.5;
    }
}

public abstract class Dairy extends Beverage {
    protected final Beverage beverage;

    public Dairy(String name, Beverage beverage) {
        super(name);
        this.beverage = beverage;
    }

    public Beverage getBeverage() {
        return beverage;
    }

    public abstract String getName();
}

public class Milk extends Dairy {
    public Milk(Beverage beverage) {
        super("Milk", beverage);
    }

    @Override
    public String getName() {
        return name + "-flavored " + beverage.getName();
    }

    @Override
    public Double getCost() {
        return 1.0 + beverage.getCost();
    }
}

public class Butter extends Dairy {
    public Butter(Beverage beverage) {
        super("Butter", beverage);
    }

    @Override
    public String getName() {
        return name + "-above " + beverage.getName();
    }

    @Override
    public Double getCost() {
        return 0.5 + beverage.getCost();
    }
}

public abstract class Sweet extends Beverage {
    protected final Beverage beverage;

    public Sweet(String name, Beverage beverage) {
        super(name);
        this.beverage = beverage;
    }

    public Beverage getBeverage() {
        return beverage;
    }

    public abstract String getName();
}

public class Sugar extends Sweet {

    public Sugar(Beverage beverage) {
        super("Sugar", beverage);
    }

    @Override
    public String getName() {
        return "Strong-" + name + "ed " + beverage.getName();
    }

    @Override
    public Double getCost() {
        return 0.2 + beverage.getCost();
    }
}

UML:


texts:
I'm building a web interface for a home monitoring sensor array, and fetching JSON from the backend framework. I want to start putting statistics together for monitoring different areas of the home, inside and outside.

Each thermal sensor provide the reading, in regular intervals, of temperature and time of day, so I end up with a JSON object looking like this:

{
"sensor_1" :    [
    {
    "location" : "garage_east",
    "temp_f" :  [{
                    "value" : "71.2",
                    "timestamp" : "2017-05-01T08:15:00"
                },
                {
                    "value" : "70.8",
                    "timestamp" : "2017-05-01T08:30:00"
                },
                {
                    "value" : "72.6",
                    "timestamp" : "2017-05-01T08:45:00"
                }
        ]}],

"sensor_2" : [{
    "location" : "kitchen",
    "temp_f" : [{
                    "value" : "78.2",
                    "timestamp" : "2017-05-01T08:15:00"
                },
                {
                    "value" : "78.8",
                    "timestamp" : "2017-05-01T08:30:00"
                },
                {
                    "value" : "78.6",
                    "timestamp" : "2017-05-01T08:45:00"
                }]
}]}

and so on, with multiple sensors each displaying pretty large JSON objects for the reporting periods.

I want to derive the highest and lowest temperatures around the house, and at what time they occurred, using JavaScript (with AngularJS). Currently, I'm looking to optimize this (which does work):

/* The entire array of data, within time frame set by the user
*   and for the sensors defined by the user
*   from the RESTful API (params)
*/

api.sensor_data.get(params, function(data){

  $scope.sensorStats = {
    "kitchen" : {},
    "garage" : {}
  }
  /* find the highest temperature for a single sensor */
  let hightemp_kitchen = Math.max.apply(Math, data.sensor_1.temp_f.map(function(t){
        return t.value;
  }));
  /* grab the associated timestamp and put them both into an object */
  $scope.sensorStats.kitchen.high = data.sensor_1.temp_f.find(function(obj){
      return obj.value == hightemp_kitchen;
  });
  /* Repeat for each sensor of concern (user defined in params) */
  etc...
 });
}, ...

and then I use the in the DOM the expression {{ sensorStats.kitchen.high }} to display the high temp and date/time to the user for the kitchen.

Like I say, this works, but I'm doing this for each of the 15+ sensors in the array around the property. This method not the easiest to read and maintain - I think it can be faster and more efficient to maintain, but I don't have the lexicon to know what to research.

Is this efficient? Is there a "better" or more efficient way to filter out the data and return the temp and time? I'm reading up on ES6, and discovered the filter() method, but it seems to be useful only on arrays and not objects.


texts:
I have this code that compares all version numbers of servers. (The version numbers are stored in an XML file) Before the code would compare the current version number with the previous. This caused some problems because in the cluster of servers, one has a different version number than the rest. If my code happened to connect to that server, it would think it was a change. So then I made it compare the three previous version numbers. The same issue was happening. So I got frustrated and made it load all the version numbers in a list and check the current one against the list. Will this cause a huge performance decrease (the list would be 50 elements at most)? Is there a better way?

#Loads all version numbers in list,
#starts at index 1 because the the first
#element in the XML file is has version number of 0

def loadAllVersions(self, hist):
    historyLength = len(hist)
    l =[]
    for i in range(historyLength):
        if i >= 1:
            l.append(hist[len(hist)-i].get("version"))
    return l

#Checks the current version number to each element
#in the list to see if it is the same. If there is a
#match then the it is not a newer version number,
#otherwise it is a new version number and the function
#returns True.

def checkAllVersions(self, currentVersion, allHist):
    historyLength = len(allHist)
    for i in range(historyLength):
        if(allHist[i] == currentVersion):
            return False
    return True

def compareVersions(self,parent,componentTarget, write):
    componentsTree = parent.findall("component")
    currentVersion = self.componentVersions[self.components.index(componentTarget)]

    for comp in componentsTree:
        if(comp.get("id") == componentTarget):
            hist = comp.findall("history")
            allHist = self.loadAllVersions(hist)
            isNewVersion = self.checkAllVersions(currentVersion, allHist)
            if isNewVersion:
                if write and currentVersion != None and self.getComponentURL(componentTarget) != None:
                        event = ET.SubElement(comp,"history")
                        event.set("time",str(int(time.time())))
                        event.set("version",currentVersion)
                        event.set("sourceUrl",self.getComponentURL(componentTarget))
                        event.set("pretty",self.componentsPretty[self.components.index(componentTarget)])
                return True
    return False


texts: Asynchronously extract title from URLs using Python

texts:
The following code asynchronously extract title from URLs (saved in book-urls.txt).
from bs4 import BeautifulSoup
import grequests

links = list()

file1 = open("book-urls.txt", "r")
Lines = file1.readlines()
for line in Lines:
    links.append(line)
file1.close()

reqs = (grequests.get(link) for link in links)
resp = grequests.map(reqs)

for r in resp:
    try:
        soup = BeautifulSoup(r.text)
        print(soup.title.string)
    except:
        pass

The input is:

https://learning.oreilly.com/library/view/a-reviewers-handbook/9781118025635/
https://learning.oreilly.com/library/view/accounting-all-in-one-for/9781119453895/
https://learning.oreilly.com/library/view/business-valuation-for/9780470344019/
https://learning.oreilly.com/library/view/the-business-of/9780470444481/

The output is:
A Reviewer's Handbook to Business Valuation: Practical Guidance to the Use and Abuse of a Business Appraisal [Book]
Accounting All-in-One For Dummies, with Online Practice, 2nd Edition [Book]
Business Valuation For Dummies [Book]
The Business of Value Investing: Six Essential Elements to Buying Companies Like Warren Buffett [Book]

Is grequests the best option or should I use something else?
Please give some suggestion on how I can make this code better.


texts:
I have to clone some Entity, then I wrote this piece of code.

public override object Clone()
{
  var CloneUser = base.Clone() as FMSUser;

  CloneUser.Username = this.Username;
  CloneUser.IsEnabled = this.IsEnabled;
  CloneUser.IsNeedPasswordReset = this.IsNeedPasswordReset;
  CloneUser.LastName = this.LastName;
  CloneUser.FirstName = this.FirstName;
  CloneUser.MiddleName = this.MiddleName;
  CloneUser.DistributorID = this.DistributorID;
  CloneUser.IsLocked = this.IsLocked;

  return CloneUser;
}

But then my coworker sent me this code, saying it's better to clone this way, but can't tell me why :

public FMSUser(FMSUser user)
  : EntityBase(user)
{
  this.Username = user.Username;
  this.IsEnabled = user.IsEnabled;
  this.IsNeedPasswordReset = user.IsNeedPasswordReset;
  this.LastName = user.LastName;
  this.FirstName = user.FirstName;
  this.MiddleName = user.MiddleName;
  this.DistributorID = user.DistributorID;
  this.IsLocked = user.IsLocked;
}
public override object Clone()
{
  return new FMSUser(this);
}

Can anynone explain me why the second way is better?