texts: Proper techniques for allowing many views to subscribe to window.unload?

texts:
I would like to execute code for many views whenever the window is unloaded.

For instance, I could have something like this in a view's initialize:

initialize: function() {
    $(window).unload(this.stopListening.bind(this));
}

I'm wondering if it would be better to have a manager which aggregates all of the view's requests into one event like:

define(function () {
    'use strict';

    var ForegroundViewManager = Backbone.Model.extend({

        defaults: function () {
            return {
                views: []
            };
        },

        initialize: function() {
            $(window).unload(function () {
                this.allViewsStopListening();
            }.bind(this));
        },

        allViewsStopListening: function() {
            _.each(this.get('views'), function(view) {
                view.stopListening();
            });
        },

        subscribe: function (view) {
            var views = this.get('views');
            var index = views.indexOf(view);

            if (index === -1) {
                views.push(view);
                console.log("Subscribed a view:", view, views.length);
            } else {
                console.log("Already subscribed!");
            }
        },

        unsubscribe: function (view) {
            var views = this.get('views');
            var index = views.indexOf(view);

            if (index > -1) {
                views.splice(index, 1);
            }
        }

    });

    return new ForegroundViewManager();
});

The second way is a lot more code, but results in just one unload event being bound to the window and then iterating over a collection. Is this preferred? Or is it better to have each view bind itself to window.unload?


texts:
This is not meant to solve any insane real world problems. I just want to make sure my Set logic is right and the code looks okay. It feels weird implementing it with a Dictionary of dummy values but it seems that's how most languages do it anyway. What do you think?

public class Set : IEnumerable
    {
        private readonly Dictionary<object, bool> _items;

        public Set()
        {
            _items = new Dictionary<object, bool>();
        }

        public void Add(object item)
        {
            if (!_items.ContainsKey(item))
            {
                _items.Add(item, true);
            }
        }

        public void Remove(object item)
        {
            if (_items.ContainsKey(item))
            {
                _items.Remove(item);
            }
        }

        public bool Contains(object item)
        {
            return _items.ContainsKey(item);
        }

        public int Count()
        {
            return _items.Keys.Count;
        }

        public void Clear()
        {
            _items.Clear();
        }

        public void UnionWith(Set input)
        {
            foreach (var item in input.Cast<object>().Where(item => !_items.ContainsKey(item)))
            {
                _items.Add(item, true);
            }
        }

        public void IntersectWith(Set input)
        {
            var newSet = new Set();
            foreach (var item in _items.Keys.Where(input.Contains))
            {
                newSet.Add(item);
            }
            Clear();
            foreach (var item in newSet)
            {
                _items.Add(item, true);
            }
        }

        public void DifferenceWith(Set input)
        {
            var newSet = new Set();
            foreach (var item in _items.Keys.Where(item => !input.Contains(item)))
            {
                newSet.Add(item);
            }
            Clear();
            foreach (var item in newSet)
            {
                _items.Add(item, true);
            }
        }

        public bool IsSubsetOf(Set input)
        {
            return _items.Keys.All(input.Contains);
        }

        public IEnumerator GetEnumerator()
        {
            return _items.Keys.GetEnumerator();
        }
    }


texts:
I need some advice on writing clean code for an Angular directive. I feel things could be written better, and would love some feedback and suggestions.

'use strict';

angular.module('aCollectiveApp.dashboard')
    .directive('adminDashboard', ($document) => {
        return {
            restrict: 'EA',
            link: (scope, elem, attrs) => {

                let dropdownElem = angular.element(elem.parent().children()[2]),
                    isOpen = false;

                elem.bind('click', (e) => {

                    e.stopPropagation();
                    isOpen = true;

                    if (dropdownElem.hasClass('active')) {
                        dropdownElem.removeClass('active');
                    } else {
                        dropdownElem.addClass('active');
                    }
                });

                $document.bind('click', () => {
                    if (isOpen) {
                        dropdownElem.removeClass('active');
                    } else {
                        isOpen = false;
                    }
                })
            }
        };
    })

.directive('circleMenu', () => {
    return {
        restrict: 'EA',
        link: (scope, elem, attrs) => {

            let menu = angular.element(elem.parent().children()[0]);

            elem.bind('mouseenter', () => {

                // Slide Out Button
                elem.addClass('fade-out');

                // Slide In Menu
                menu.addClass('fade-in');
            })

            menu.bind('mouseleave', () => {
                elem.removeClass('fade-out');
                menu.removeClass('fade-in');
            });

        }
    }
})


texts:
I have a CLI wrapper for https://yakuake.kde.org/.

Python 3.4.*.

#! /usr/bin/env python
# coding: utf-8

import click
import subprocess

def get_postfix(title):
    file_path = '/tmp/yakuake_{}_postfix'.format(title)

    try:
        with open(file_path, 'r') as f:
            postfix_number = int(f.readline())
        postfix_number += 1
    except FileNotFoundError:
        postfix_number = 1

    with open(file_path, 'w') as f:
        f.write(str(postfix_number))

    return '{:02}'.format(postfix_number)

@click.command()
@click.argument('title')
def set_yakuake_title(title):
    """
    Set Yakuake title for current active tab.
    """
    qbus_cmd = 'qdbus org.kde.yakuake'

    compound_title = '**{title}-{postfix}**'.format(
        title=title,
        postfix=get_postfix(title)
    )
    session_id_cmd = '{qbus} {active_session}'.format(
        qbus=qbus_cmd,
        active_session='/yakuake/sessions org.kde.yakuake.activeSessionId'
    )
    set_tab_title_cmd = '{qbus} {tab_title} `{session_id}` "{title}"'.format(
        qbus=qbus_cmd,
        tab_title='/yakuake/tabs setTabTitle',
        session_id=session_id_cmd,
        title=compound_title
    )

    subprocess.call(set_tab_title_cmd, shell=True)

if __name__ == '__main__':
    set_yakuake_title()

Does this code follow common best practices?


texts:
My quick searching did not reveal anyone sharing their solution to this exercise, so am not sure if there are other (and better) approaches to mine:

package main

import (
    "code.google.com/p/go-tour/wc"
    "strings"
)

func WordCount(s string) map[string]int {
    foo := strings.Fields(s)
    m := make(map[string]int)
    for i := 0; i < len(foo); i++ {
        v, ok := m[foo[i]]
        if ok {
            m[foo[i]] = v + 1
        }
        m[foo[i]] = v + 1
    }
    return m
}

func main() {
    wc.Test(WordCount)
}


texts:
Pretty straightforward, I implemented the popular fizz buzz challenge in Haskell.

import qualified Data.Map as M

factorWords = M.fromList [(3, "fizz"), (5, "buzz")]

factors :: Int -> [Int]
factors x = filter (\y -> x `mod` y == 0) factorKeys
    where factorKeys = M.keys factorWords

fizzbuzz :: Int -> String
fizzbuzz x = if null fs then show x
                        else concatMap ((M.!) factorWords) fs
    where fs = factors x

main = mapM_ (putStrLn . fizzbuzz) [1..100]

I'm guessing people are going tell me that using Data.Map and concatMap is overkill for a program of this size and complexity, but it seemed the most natural way to do it in Haskell for whatever reason. Any advice, particularly regarding my use of data structures?


texts:
I am trying to generate LCM by prime factorization. I have already done the other way around to generate LCM using GCD but I am trying to achieve it using prime factorization.

I am getting right prime factors but the problem is that to generate LCM we need to multiply each factor the greatest number of times it occurs in either number's factors. Reference

Now I don't like the code I come up with to achieve this. The logic is to retrieve factors of both numbers and then create a hash/counter for each factor. Finally multiply the factor with the result so far and the greatest number of times in each hash counter list.

I would like to request to review my all methods IsPrime, PrimeFactors, LeastCommonMultipleByPrimeFactorization etc. In particular the main LeastCommonMultipleByPrimeFactorization method. Please feel free to pass your comments and suggestions. I would be happy to see some simplest way to achieve this.

Code snippet:

    public static bool IsPrime(int n)
    {
        for (int i = 2; i <= n; i++)
        {
            if (n % i == 0)
            {
                if (i == n)
                    return true;
                else
                    return false;
            }
        }
        return false;
    }

    public static int[] PrimeFactors(int n)
    {
        var factors = new List<int>();
        for (int i = 2; i <= n; i++)
        {
            while (n % i == 0 && IsPrime(i))
            {
                factors.Add(i);
                n = n / i;
            }
        }
        return factors.ToArray();
    }

    public static int LeastCommonMultipleByPrimeFactorization(int m, int n)
    {
        //retrieve prime factors for both numbers
        int[] mFactors = PrimeFactors(m);
        int[] nFactors = PrimeFactors(n);

        //generate hash code to get counter for each factor
        var mFactorsCountHash = CreateCounterHash(mFactors);
        var nFactorsCountHash = CreateCounterHash(nFactors);

        var primeFactors = new List<int>();
        primeFactors.AddRange(mFactors);
        primeFactors.AddRange(nFactors);

        int result = 1;

        //On each distinct factor... check either which number factors
        foreach (int factor in primeFactors.Distinct())
        {
            int mfactorCount = 0;
            int nfactorCount = 0;
            if (mFactorsCountHash.ContainsKey(factor))
            {
                mfactorCount = mFactorsCountHash[factor];
            }

            if (nFactorsCountHash.ContainsKey(factor))
            {
                nfactorCount = nFactorsCountHash[factor];
            }

            int numberOfCount = mfactorCount > nfactorCount ? mfactorCount : nfactorCount;
            result = factor * result * numberOfCount;
        }

        return result;
    }

    private static Dictionary<int, int> CreateCounterHash(IEnumerable<int> mFactors)
    {
        Dictionary<int, int> hash = new Dictionary<int, int>();
        foreach (var factor in mFactors)
        {
            if (hash.ContainsKey(factor))
                hash[factor]++;
            else
                hash.Add(factor, 1);
        }
        return hash;
    }

To test method, I am using following code

[Test]
    public void LeastCommonMultipleByPrimeFactorizationPositiveTest()
    {
        Assert.AreEqual(42, ArthmeticProblems.LeastCommonMultipleByPrimeFactorization(21, 6));

        Assert.AreEqual(12, ArthmeticProblems.LeastCommonMultipleByPrimeFactorization(4, 6));
    }

  Note: This is just for fun and revision of my basic concepts


texts:
I am solving some programming challenges for learning Javascript. The challenge I chose is:

  Given the head of a singly linked list, reverse it in-place.

Here is my implementation in JS

// Given the head of a singly linked list, reverse it in-place.
const ReverseLinkedList = {
    reverseLinkedList: (/** @type{ListNode} */ head) => {
        if (head === undefined) {
            return undefined;
        }

        if (head.next === undefined) {
            return head;
        }

        let temp = head;
        let tail = head.next.next;

        head = temp.next;
        head.next = temp;
        head.next.next = undefined;

        while (tail !== undefined) {
            let tempNext = tail.next;

            temp = head;
            head = tail;
            head.next = temp;

            tail = tempNext;
        }

        return head;
    },
    ListNode: function ListNode(/** @type{ListNode} */ next, val) {
        return {
            next: next,
            val: val
        }
    }
};

module.exports = ReverseLinkedList;

and my test class

const expect = require('chai').expect;
const reverseLinkedList = require('../../src/reverseLinkedList');

let head;
let node_01;
let node_02;
let reversed;

node_02 = reverseLinkedList.ListNode(undefined, 2);
node_01 = reverseLinkedList.ListNode(node_02, 1);
head = reverseLinkedList.ListNode(node_01, 0);

reversed = reverseLinkedList.reverseLinkedList(head);
expect(reversed.val).to.equal(2);
expect(reversed.next.val).to.equal(1);
expect(reversed.next.next.val).to.equal(0);
expect(reversed.next.next.next).to.equal(undefined);

node_01 = reverseLinkedList.ListNode(undefined, 1);
head = reverseLinkedList.ListNode(node_01, 0);
head.next = node_01;

reversed = reverseLinkedList.reverseLinkedList(head);
expect(reversed.val).to.equal(1);
expect(reversed.next.val).to.equal(0);
expect(reversed.next.next).to.equal(undefined);

head = reverseLinkedList.ListNode(undefined, 0);
reversed = reverseLinkedList.reverseLinkedList(head);
expect(reversed.val).to.equal(0);
expect(reversed.next).to.equal(undefined);

Being a Javascript newbie, any comments on the styling and best practices? Also any comments on the algorithm itself is highly appreciated.


texts: Deterministic finite automaton in Java - follow-up

texts:
(See the initial and first iteration for description and motivation.)

Now I have incorporated all the remarks made by Tunaki, and it looks like this:

TransitionFunction.java:

package net.coderodde.dfa;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.stream.IntStream;

/**
 * This class implements a transition function.
 *
 * @author Rodion "rodde" Efremov
 * @version 1.6 (Apr 2, 2016)
 */
public class TransitionFunction {

    private final Map<Integer, Map<Character, Integer>> function =
          new HashMap<>();

    public void addTransition(Integer startState,
                              Integer goalState,
                              char character) {
        function.computeIfAbsent(startState, (k) -> new HashMap<>())
                .put(character, goalState);
    }

    public Optional<Integer> process(Integer startState, char character) {
        return Optional.ofNullable(
                function.getOrDefault(startState,
                                      Collections.emptyMap()).get(character));
    }

    public Optional<Integer> processAll(Integer startState, char[] characters) {
        return IntStream
                .range(0, characters.length)
                .boxed()
                .reduce(Optional.of(startState),
                       (o, i) -> o.flatMap(s -> process(s, characters[i])),
                       (o1, o2) -> o1.map(Optional::of).orElse(o2));
    }
}

DFA.java:

package net.coderodde.dfa;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Objects;
import java.util.Scanner;
import java.util.Set;

/**
 * This class implements a
 *
 * deterministic finite automaton.
 *
 * @author Rodion "rodde" Efremov
 * @version 1.6 (Apr 2, 2016)
 */
public class DFA {

    private final TransitionFunction transitionFunction;
    private final int startState;
    private final Set<Integer> acceptingStates;

    public DFA(TransitionFunction transitionFunction,
               int startState,
               Set<Integer> acceptingStates) {
        this.transitionFunction =
                Objects.requireNonNull(transitionFunction,
                                       "Transition function is null.");
        this.startState = startState;
        this.acceptingStates =
                Objects.requireNonNull(acceptingStates,
                                       "Accepting state set is null.");
    }

    public boolean matches(String text) {
        return transitionFunction.processAll(startState, text.toCharArray())
                                 .map(acceptingStates::contains)
                                 .orElse(false);
    }

    public static void main(String[] args) {
        // A regular language over binary strings with even number of 1's.
        TransitionFunction transitionFunction = new TransitionFunction();

        transitionFunction.addTransition(0, 0, '0');
        transitionFunction.addTransition(1, 1, '0');
        transitionFunction.addTransition(0, 1, '1');
        transitionFunction.addTransition(1, 0, '1');

        Set<Integer> acceptingStates = new HashSet<>(Arrays.asList(0));
        DFA dfa = new DFA(transitionFunction, 0, acceptingStates);

        Scanner scanner = new Scanner(System.in);

        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();

            if (line.trim().equals("end")) {
                break;
            }

            System.out.println(dfa.matches(line));
        }
    }
}

Any critique much appreciated.


texts: Benchmarking copy semantics vs. move semantics

texts:
I am still in the process of learning modern C++, and decided to write this dummy program for actually benchmarking copy semantics vs. move semantics:

#include <chrono>
#include <iostream>
#include <cstdint>

using std::cout;
using std::endl;

class List {
public:
    void push_back();
    List() : sz{0}, head{nullptr}, tail{nullptr} { }

    List(List&& lst) : head{lst.head}, tail{lst.tail}, sz{lst.sz} {
        cout << "Move constructor" << endl;
        lst.head = nullptr;
        lst.tail = nullptr;
        lst.sz = 0;
    }

    List(const List& lst)
    {
        cout << "Copy constructor" << endl;
        for (size_t i = 0; i != lst.sz; ++i)
        {
            push_back();
        }
    }

    List& operator=(List&& lst)
    {
        cout << "Move assignment" << endl;
        head = lst.head;
        tail = lst.tail;
        sz = lst.sz;
        lst.head = nullptr;
        lst.tail = nullptr;
        lst.sz = 0;
        return *this;
    }

    List& operator=(const List& lst)
    {
        cout << "Copy assignment" << endl;
        head = nullptr;
        tail = nullptr;
        sz = 0;

        for (size_t i = 0; i != lst.sz; ++i)
        {
            push_back();
        }

        return *this;
    }

private:

    struct ListNode {
        ListNode* next;
    };

    ListNode* head;
    ListNode* tail;
    size_t sz;
};

void List::push_back()
{
    ListNode* new_node = new ListNode;
    new_node->next = nullptr;

    if (head == nullptr)
    {
        head = new_node;
    }
    else
    {
        tail->next = new_node;
    }

    tail = new_node;
    ++sz;
}

class CurrentTime {
    std::chrono::high_resolution_clock m_clock;

public:
    uint64_t milliseconds()
    {
        return std::chrono::duration_cast<std::chrono::milliseconds>
            (m_clock.now().time_since_epoch()).count();
    }
};

List createList(CurrentTime& ct)
{
    List lst;
    constexpr size_t HUNDRED_MILLION = 100 * 1000 * 1000;

    auto start = ct.milliseconds();
    for (size_t i = 0; i != HUNDRED_MILLION; ++i)
    {
        lst.push_back();
    }
    auto end = ct.milliseconds();

    cout << "createList in " << (end - start) << " milliseconds." << endl;

    return lst;
}

int main() {
    CurrentTime ct;

    auto start = ct.milliseconds();
    List list;
    list = createList(ct);
    auto end = ct.milliseconds();

    cout << "Duration: " << (end - start) << " milliseconds." << endl;

    start = ct.milliseconds();
    List list2(list);
    end = ct.milliseconds();

    cout << "Duration: " << (end - start) << " milliseconds." << endl;

    start = ct.milliseconds();
    List list3(std::move(list));
    end = ct.milliseconds();

    cout << "Duration: " << (end - start) << " milliseconds." << endl;
}

Did I manage to capture the idiomatic use of move facilities in this demonstration program? Tell me anything that comes to mind.


texts: Getting value from session if available, if not, take from the database

texts:
This method is a constructor that has to decide which URL to add to the response header as Allow-Origin. i am actually adding the Allow-Origin later according to the value of PermittedOrigion variable. I am using Session to eliminate database access.

Could i write it more efficient?  I am working with asp.net webform

public ResponseAsJson(HttpRequest request, int affiliateId)
    {
        string cacheKeyName = $"PermittedOrigion_{affiliateId.ToString()}";
        const string notDefined = "N";
        object ValueFromCache = HttpContext.Current.Cache[cacheKeyName];

        if (!String.IsNullOrWhiteSpace(ValueFromCache?.ToString()))
        {
            if (ValueFromCache.ToString() == notDefined)
                return;

            PermittedOrigion = ValueFromCache.ToString();
            return;
        }

        string actualOrigion = null;

        if (request.UrlReferrer != null)
           actualOrigion = request.UrlReferrer.GetLeftPart(UriPartial.Authority);

        string[] strFromDB = RM.BL.Affiliate.Instance(affiliateId).LUAffiliate.AccessControlAllowOriginJsonResult.Split(';');

        if (!String.IsNullOrWhiteSpace(actualOrigion) && strFromDB.Contains(actualOrigion))
        {
            PermittedOrigion = actualOrigion;
        }
        else
        {
            string strLocalhost = strFromDB.Where(x => x.ToLower().StartsWith("http://localhost")).FirstOrDefault();

            if (!String.IsNullOrWhiteSpace(strLocalhost))
                PermittedOrigion = strLocalhost;
        }

        if (PermittedOrigion == null)
        {
            HttpContext.Current.Cache[cacheKeyName] = notDefined;
        }
        else
        {
            HttpContext.Current.Cache[cacheKeyName] = PermittedOrigion;
        }

    }


texts: Measuring the time for the bubble sort algorithm

texts:
I created a program that measures the time for the bubble sort algorithm to sort a list of numbers:

#include <iostream>
#include <fstream>
#include <vector>
#include <time.h>

std::vector<int> FiletoVector()
{
    std::ifstream SortFile("Number_Sort.input");

    std::vector<int> vector;
    int read;

    while(SortFile >> read)
    {
        vector.push_back(read);
    }

    return vector;
}

void PrintTime(std::string sorttype, std::vector<int> funcinput(std::vector<int>), std::vector<int> vecinput)
{
    //Start Time
    float time = clock();

    funcinput(vecinput);

    //End Time
    time = (clock() - time) / CLOCKS_PER_SEC;

    std::cout << sorttype << " took " << time << " seconds!" << std::endl;
}

std::vector<int> BubbleSort(std::vector<int> vecinput)
{
    for(int i = 0; i < vecinput.size(); i++)
    {
        for(int n = 0; n < vecinput.size(); n++)
        {
            //std::cout << vecinput[n] << " " << vecinput[n + 1] << std::endl;
            if(vecinput[n] > vecinput[n + 1])
            {
                int a = vecinput[n];
                int b = vecinput[n + 1];

                vecinput[n] = b;
                vecinput[n + 1] = a;
            }
        }
    }

    return vecinput;
}

int main()
{
    std::vector<int> nums = FiletoVector();

    //REMEMBER FUNCTION IN PARAMETER HAS NO ()
    PrintTime("Bubble Sort", BubbleSort, nums);

    /*
    //Print Ordered List and Time (Bubble)
    for(int i = 0; i < vecBubble.size(); i++)
    {
        std::cout << vecBubble[i] << std::endl;
    }
    std::cout << time << " seconds!" << std::endl;
    */
}

As you can see the first function is to take the file (Number_Sort.input) and make it into a vector (since it can change size in elements). Then my second function is prints out the time it takes for the sorting algorithm to sort all of its data. Finally my last function is the bubble sort algorithm.

The reason I put my code in this fashion is that so I can later on learn other algorithms and put them in here, and then compare the speed that they execute them with different data sets.

But my code feels a bit messy, I feel like I can further make it more readable, specifically the PrintTime function and all of those parameters. I am not even sure if I did the funcinput(std::vector<int>) in a proper way. I had to make the input of the bubble sort function as a separator parameter (I could not do PrintTime("Bubble Sort", BubbleSort(nums)). And all of that std::vector<int> is gonna kill me! Is there any way to clean that mess too?


texts: Mac Bash: how to combine the open and str subtract to one line code?

texts:
new to bash , I use the following code to open the super folder with a file path.

function openUp(){
  cd $(echo $1 | sed 's@\(.*\)/.*@\1@' );
  open ..
}

like drag a file to terminal, then open the super folder conveniently.

  openup /Users/de/Downloads/32/S01E32-array-arrayslice-collection-collections-1-master.zip

How to combine the two line code to one line?

I originally think open directly without changing directory.


texts: Python Making Bruteforce Password Crack Faster

texts:
I made a simple password cracker using Python. But it's extremely slow. Here is my code:

import itertools
import string
import sys
import socket

def connection(ip, user, passw, port):
    s = socket.socket()
    s.connect((ip, int(port)))
    data = s.recv(1024)
    s.send(('USER ' + user + '\r\n').encode())
    data = s.recv(1024)
    s.send(('PASS ' + passw + '\r\n').encode())
    data = s.recv(1024)
    s.send(('quit\r\n').encode())
    s.close()
    return data
def crack(ip, user, port):
    chars = string.digits + string.ascii_letters
    for password_length in range(1, 9):
        for guess in itertools.product(chars, repeat = password_length):
            guess = ''.join(guess)
            p = connection(ip, user, guess, port)
            if '230'.encode() in p:
                print('Username : ' + user + '\nPassword : ' + guess)
                sys.exit(1)
if len(sys.argv) != 4:
    print('Usage: ./passcracker.py <IP> <Username> <Port>')
    sys.exit(1)
crack(sys.argv[1], sys.argv[2], sys.argv[3])

I want to make it faster. Also if there is any wrong part in code, please tell me.


texts: Swift: arrayToTree() where array contains int and nil

texts:
I am learning tree on Leetcode. Need to prepare the testing data.

It is easy to convert the array to an organized node, where its elements are integers.

such as [3, 9, 20, 15, 7]

Here is my code:

extension Array where Element == Int{

func arrayToTree() -> TreeNode{
    var nodes = [TreeNode]()
    for num in 0..<self.count{
         nodes.append(TreeNode(self[num]))
    }

    var i = 0
    repeat{
        nodes[i].left = nodes[2 * i + 1]
        if self.count > 2 * i + 2 {
             nodes[i].right = nodes[2 * i + 2]
        }
        i+=1
    }while i < (self.count)/2

    return nodes.first!
  }
}

When the last level contains some nils , such as [3, 9, 20, nil, nil, 15, 7]

Here is the code:

extension Array where Element == Int?{

    func arrayToTree() -> TreeNode?{

        guard self.count > 0 else{
            return nil
        }
        var nodes = [TreeNode?]()
        for num in 0..<self.count{
            if let num = self[num]{
                nodes.append(TreeNode(num))
            }
            else{
                nodes.append(nil)
            }
        }
        var i = 0
        repeat {
            nodes[i]?.left = nodes[2 * i + 1]
            if self.count > 2 * i + 2 {
                nodes[i]?.right = nodes[2 * i + 2]
            }
            i += 1
        } while i < (self.count) / 2

        return nodes.first!
    }

}

How can I refactor this?

Such as combine them together using Swift Generic with some Protocol.


texts: Check if a given integer is power of two

texts:
Given an integer, check if it's the power of two.

class Main {
  static class Solution {
    private final boolean answer;

    Solution(int num) {
      if (num <= 0) {
        answer = false;
      }
      else if ((num & (num - 1)) == 0) {
        answer = true;
      }
      else {
        answer = false;
      }
    }

    public boolean isPowerOfTwo() {
      return answer;
    }
  }

  public static void runTests() {
    // Falsy
    System.out.println(new Solution(-1).isPowerOfTwo());
    System.out.println(new Solution(0).isPowerOfTwo());
    System.out.println(new Solution(Integer.MAX_VALUE).isPowerOfTwo());
    System.out.println(new Solution(Integer.MIN_VALUE).isPowerOfTwo());

    //Truthy
    System.out.println(new Solution(1).isPowerOfTwo());
    System.out.println(new Solution(128).isPowerOfTwo());
    System.out.println(new Solution(1024).isPowerOfTwo());
  }

  public static void main(String[] args) {
    runTests();
  }
}


texts:
I have a method that checks to see if a hash of given items should have discounts applied and if so, determines and returns the discount:

def get_discounts
  @items.each do |name, attr|
    @specials.each do |special|
      while name == special.sale_item && attr[:quantity] >= special.quantity
        @discounts << special.discount
        attr[:quantity] = attr[:quantity] - special.quantity
      end
    end
  end
  determine_discount
end

def determine_discount
  if @discounts.empty?
    @discounts = 0
  else
    @discounts = @discounts.inject(:+)
  end
end

This works perfectly, but is there a more concise way to write it?  I'm looking especially at the two each loops.  I'm also a bit iffy about the while loop - it was an if statement (if name == special.sale_item) but it felt like too much so I combined it into the while loop.


texts:
I have to create a table that will allow users to upload different documents for each of the entry in the table. To be more exact, each row will contain a unique ID on first column, followed by 3 inputs (upload) for video, text and image, and a save button (each on next column of the row).

The problem is that I have a pretty big number of rows in the table, so creating the table in HTML code is pretty much out of the question.

The code I made generates HTML code in the code behind, and prints it in a literal, so basically it looks like this:

foreach (row tempR in allRows)
        {
            dataToShow += "
";
            dataToShow += "" + tempR.IDrow + "	";
            dataToShow += "<input type=\"file\" id=\"uploadVideo" + tempR.IDrow + "\" runat=\"server\" />	";
            dataToShow += "<input type=\"file\" id=\"uploadPDF" + tempR.IDrow + "\" runat=\"server\" />	";
            dataToShow += "<input type=\"file\" id=\"uploadImg" + tempR.IDrow + "\" runat=\"server\" />	";
            dataToShow += "<button runat=\"server\" class=\"btn\" id=\"btnSave_" + tempR.IDrow + "\">Save</button>	";
            dataToShow += "
";
        }
litDoc.Text = dataToShow;

My problem is that I am pretty sure this is the worst possible way in achieving the desired result, but sadly I can't find another way I can achieve it. Also now if I want to handle the click events of the save buttons I need to get the id of the button with jquery and call with ajax a server side method that will handle that event, which I believe is not pretty great either.

Any advices you could give me would be greately appreciated! (the project is in ASP.NET WebForms)


texts: Web service to add a phone number with SMS validation

texts:
I'm new to Clojure. How can I make this more idiomatic Clojure code? Among other things, there are three (do) blocks and I don't think using (def) as many times as I do is a recommended idea.

(defn add-phone
  "Add a phone number to a given service. There are a few steps we have to take:
    - Validate the service name and token
    - Validate the phone number
    - Send a text message to the number
    - Store the number in the database
  Arguments:
    request - an authorized HTTP request
  Returns:
    201 Resource Created - phone number added to a service
    400 Bad Request - invalid phone number or bad request"
  [request auth-type]
  (do
    (println "Url requested is " (:request-method request) " " (:uri request))
    (println request)
    (def auth-header ((:headers request) "authorization"))
    (def auth-map (utils/get-auth-header auth-type auth-header))
    (if (model/invalid-user-and-pass auth-map auth-type)
        {:status 401,
         :headers {"WWW-Authenticate" "Basic realm=\"smsauth.herokuapp.com\""}}
      (do
        (def raw-phone-no (:phone_number (:params request)))
        (def service-name (:service-name auth-map))
        (if raw-phone-no
          (do
            (def valid-phone-no (utils/parse-phone-no raw-phone-no))
            ; XXX get the service id some other way.
            (def service-map (model/service-in-db service-name))
            (def service-id (service-map :id))
            ; XXX check that service doesn't already have phone number
            (model/store-phone-no :numbers service-id valid-phone-no)
            (twilio/send-sms-verify twilio/sms-url valid-phone-no service-name)
            ; XXX jsonify this, send more information, document it.
            {:status 201,
             :body (json/json-str {
                      :service_name service-name,
                      :phone_number valid-phone-no,
                      :status "active",
                      :uri (:uri request)
                      ; should have some kind of unique id for the phone number
                      ; here.
                      ; also return the date
                    })})
          {:status 400,
            :body (json/json-str {:error "Please include a phone_number."})})))))


texts: Calculating 24 from 4 numbers (math Poker game)

texts:
This is a game of math in Poker. Two people each have a pile of cards. They then each place 2 cards on the table at the same time. Every card is treated as a number. The players need to find a way to calculate 24 from the numbers. For example, you are given 3 5 4 8, and you can get 24 by (3+8-5) * 4, or 8*4-5-3. This code tries to solve this problem.

Can anyone help me to improve it?

comp()

def comp( nums,i,j,exps,op):
    nums0=[];
    for x in range(0,len(nums)):
        if not (x==i or x==j):
            nums0.append(nums[x])

    if(op=='+'):
        tmp = nums[i]+nums[j];
    elif(op=='*'):
        tmp = nums[i]*nums[j];
    elif(op=='-'):
        tmp = nums[i]-nums[j];
    elif(op=='/'):
        if(nums[j]<0.0001 and nums[j]>-0.0001 ):
            tmp=100000;
        else:
            tmp = nums[i]*1.0/nums[j];
    elif(op=='^'):
        return comp(nums,j,i,exps,'-');
    elif(op=='%'):
        return comp(nums,j,i,exps,'/');

    exps.append(str((nums[i],op,nums[j])));
    nums0.append(tmp);
    return nums0

cal()

def cal(nums, exps):
    if(len(nums)==1):
        return (nums[0]>23.9999 and nums[0]<24.0001);
    pairs = {};
    for i in range(0,len(nums)):
        for j in range(i+1,len(nums)):
            tmp_key= str((min(nums[i],nums[j]),max(nums[i],nums[j])));
            #print tmp_key
            if(pairs.has_key(tmp_key)):
                continue;
            #print 'put '+tmp_key
            pairs[tmp_key]=''
            for op in ('+','-','*','/','^','%'):
                nums0 = comp(nums,i,j,exps,op)
                if(cal(nums0,exps)):
                    print str(exps);
                exps.pop();

cal([3,9,10,7],[]);

cal([5,5,5,1],[]);

cal([10,9,4,1],[]);


texts: Playframework Java application with Couchbase database, retrieve and lock the document while saving

texts:
I am retrieving a document(UserDetails) from Couch with a lock of 5 sec, than updating the document and saving it. Code is working, but I am not sure whether it will work in real time scenario (in case of conflict) or not. How to handle TemporaryLockFailureException? I also want feedback to refactor the method.

@Override
public void submitUsersDetails(DashboardRequest request) {
    logger.debug("inside submitDashboardDetails");
    CompletableFuture.runAsync(() -> {
        try {
            bucket = cluster.openBucket(config.getString(PctConstants.COUCHBASE_BUCKET_NAME),
                    config.getString(PctConstants.COUCHBASE_BUCKET_PASSWORD));
            String documentID = PctConstants.USER_PROFILE;
            JsonDocument retrievedJsonDocument = bucket.getAndLock(documentID, 5);
            if (retrievedJsonDocument != null) {
                JsonNode json = Json.parse(retrievedJsonDocument.content().toString());
                UserDetails userDetails = Json.fromJson(json, UserDetails.class);
                // UPDATING userDetails
                JsonObject jsonObject = JsonObject.fromJson(Json.toJson(userDetails).toString());
                bucket.replace(JsonDocument.create(documentID, jsonObject, retrievedJsonDocument.cas()));
                logger.info("Successfully entered record into couchbase");
            } else {
                logger.error("Fetching User_details unsuccessful");
                throw new DataNotFoundException("User_details data not found");
            }
        } catch (TemporaryLockFailureException e) {
            try {
                logger.debug("Inside lock failure **************************");
                Thread.sleep(5000);
                String documentID = PctConstants.USER_PROFILE;
                JsonDocument retrievedJsonDocument = bucket.getAndLock(documentID, 5);
                if (retrievedJsonDocument != null) {
                    JsonNode json = Json.parse(retrievedJsonDocument.content().toString());
                    UserDetails userDetails = Json.fromJson(json, UserDetails.class);
                    // UPDATING userDetails
                    JsonObject jsonObject = JsonObject.fromJson(Json.toJson(userDetails).toString());
                    bucket.replace(JsonDocument.create(documentID, jsonObject, retrievedJsonDocument.cas()));
                    logger.info("Successfully entered record into couchbase");
                    submitDashboardDetails(request);
                } else {
                    logger.error("Fetching User_details unsuccessful");
                    throw new DataNotFoundException("User_details data not found");
                }
            } catch (InterruptedException e1) {
                e1.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
            try {
                throw e;
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
    }, ec.current()).join();
}


texts: Naming for unit tests for controller to edit posts

texts:
I am relatively new to TDD and am trying to adopt better names for my tests.

I wrote the following tests abruptly and have since refactored them to the best of my ability, but despite my best efforts, the test names are still (mostly) abysmal.

I am here today to ask that you review my test names.

[Test]
public void Edit_ReturnsCorrectView()
{
    var actual = controller.Edit("dynamic-contagion-part-one") as ViewResult;

    Assert.NotNull(actual);
    Assert.That(actual.ViewName, Is.EqualTo("Edit"));
}

[Test]
public void Edit_ReturnsCorrectModel()
{
    var viewResult = (ViewResult) controller.Edit("dynamic-contagion-part-one");
    var actual = viewResult.Model as PostInputModel;

    Assert.NotNull(actual);
    Assert.That(actual.Title, Is.EqualTo("Dynamic contagion, part one"));
}

[Test]
public void Edit_NonExistentPost_ReturnsNotFound()
{
    var actual = controller.Edit("non-existent-slug") as HttpNotFoundResult;

    Assert.NotNull(actual);
    Assert.That(actual.StatusDescription,
        Is.EqualTo("You cannot edit a post that does not exist."));
}

[Test]
public void Edit_Post_ReturnsCorrectView()
{
    var actual = controller.Edit(post) as ViewResult;

    Assert.NotNull(actual);
    Assert.That(actual.ViewName, Is.EqualTo("Edit"));
}

[Test]
public void Edit_EditsPostContent()
{
    post.Content = "arbitrary content.";
    controller.Edit(post);

    var amendedPost =
        repository.Object.Posts.First(p => p.Slug == "dynamic-contagion-part-one");
    Assert.That(amendedPost.Content, Is.EqualTo("arbitrary content."));
}

[TestCase("foo", ExpectedResult = "foo")]
[TestCase("foo\r\nbar", ExpectedResult = "foo")]
public string Edit_EditsPostSummary(string content)
{
    post.Content = content;
    controller.Edit(post);

    var amendedPost =
        repository.Object.Posts.First(p => p.Slug == "dynamic-contagion-part-one");
    return amendedPost.Summary;
}

[Test]
public void Edit_EditsPostSlug()
{
    post.Title = "Hello, World";
    controller.Edit(post);

    repository.Object.Posts.First(p => p.Slug == "hello-world");
}

[Test]
public void Edit_Post_NonExistentPost_ReturnsNotFound()
{
    var model =
        new PostInputModel {Title="Non Existent Slug",Slug="non-existent-slug"};

    var actual = controller.Edit(model) as HttpNotFoundResult;

    Assert.NotNull(actual);
    Assert.That(actual.StatusDescription,
        Is.EqualTo("You cannot edit a post that does not exist."));
}

[Test]
public void Edit_InvalidModel_ReturnsCorrectModel()
{
    controller.ModelState.AddModelError("", "");
    var model = new PostInputModel();

    var actual = controller.Edit(model) as ViewResult;

    Assert.NotNull(actual);
    Assert.That(actual.ViewName, Is.EqualTo("Edit"));
    Assert.AreEqual(model, actual.Model);
}

[Test]
public void Edit_OccupiedSlug_ReturnsCorrectView()
{
    var model = new PostInputModel
    {
        Title = "Lowering in language design, part two",
        Content = "arbitrary content."
    };

    var actual = controller.Edit(model) as ViewResult;

    Assert.NotNull(actual);
    Assert.That(
        controller.ModelState[""].Errors[0].ErrorMessage,
        Is.EqualTo("You have previously published a post with this title. " +
                   "Please choose another one."));
}

I welcome all feedback regarding this segment of code but in an attempt to be more specific, something that makes me particularly nauseous are these test names:

Edit_ReturnsCorrectView
Edit_Post_ReturnsCorrectView

Here I am trying to differentiate which action method I am testing according to the HTTP verb which is clearly ambiguous and generally yucky.

I am also concerned about the Edit_EditsX convention that I have developed and wonder if there is a better approach to testing that data in my (fake) repository is updated accordingly.


texts:
Question:

  Difference between the Sum of squares from 1 to 100 and the square of sums of 1 to 100.

Answer in Ruby:

range.inject(:+) ** 2 - range.map{|x| x ** 2}.inject(:+)

This one seems pretty straightforward but welcome any improvements to make it more elegant!


texts:
I just had this question in an interview.  I had to write some code to find all the common elements in two arrays.  This is the code I wrote.  I could only think of a 2-loop solution, but something tells me there must be a way to accomplish this with only 1 loop.  Any ideas?

public List<Integer> findCommonElements(int[] arr1, int[] arr2) {
    List<Integer> commonElements = new ArrayList<>();

    for (int i = 0; i < arr1.length; i++) {
        for (int j = 0; j < arr2.length; j++) {
            if (arr1[i] == arr2[j]) {
                commonElements.add(arr1[i]);
                break;
            }
        }
    }

    return commonElements;
}


texts: Should this code be in the code behind or separate class?

texts:
I'm developing a log-on page where users either select or create an associated organization when they sign up.  There can be either 1 user per organization or many users per organization, this is specified at runtime via web.config.

I have a separate project that handles all user account creation. I don't know if this code should be in the Webforms project or the user account creation project since it is driven by the user's selection in the GUI?

    private IpasLogOnManagement.IpasOrganization EnsureOrganizationExists()
    {
        IpasLogOnManagement.IpasOrganization organization = null;

        if (OrganizationsSeparateFromUsers)
        {
            if (lstOrganizations.SelectedIndex == -1)
            {
                try
                {
                    organization = organizationProvider.SearchForOrganizationByName(txtOrganizationName.Text);
                }
                catch (IndexOutOfRangeException)
                {
                    //Organization does not exist, so create it
                    organization = manager.CreateOrganization(txtOrganizationName.Text);
                }
            }
            else
            {
                string selectedName = lstOrganizations.Items[lstOrganizations.SelectedIndex].Text;
                organization = organizationProvider.SearchForOrganizationByName(selectedName);
            }
        }
        else
        {
            organization = manager.CreateOrganization(txtEmail.Text);
        }
        return organization;
    }


texts:
I've implemented a C++ version of Java ArrayList. It doesn't contain all the functionalities such as AddAll and iterators and such, but I still would appreciate criticism to my code correctness, style and flow and such

template <typename T>
class ArrayList
{
    public:
        ArrayList();
        ~ArrayList();
        ArrayList(const ArrayList<T>& other);
        ArrayList<T>& operator= (const ArrayList<T>& other);

        void add(const T& item); //Add item to end of array
        void add(const T& item, int index);
        void remove(const T& item); //Remove ALL occurrences of item from array
        void remove(int index);

        T& get(int index);
        void set(int index, const T& item);

    private:
        T* arr;
        int allocatedSize;
        int actualSize;
        const int INCREMENT = 10;
};

template<typename T>
ArrayList<T>::ArrayList()
{
    arr = new T[INCREMENT];
    allocatedSize = INCREMENT;
    actualSize = 0;
}

template<typename T>
ArrayList<T>::~ArrayList()
{
    delete[] arr;
}

template<typename T>
ArrayList<T>::ArrayList(const ArrayList<T>& other)
{
    arr = new T[other.allocatedSize];
    allocatedSize = other.allocatedSize;
    actualSize = other.actualSize;

    for(int i = 0; i<other.actualSize; i++)
        arr[i] = other.arr[i];
}

template<typename T>
ArrayList<T>& ArrayList<T>::operator= (const ArrayList<T>& other)
{
    delete[] arr;
    arr = new T[other.allocatedSize];
    allocatedSize = other.allocatedSize;
    actualSize = other.actualSize;

    for(int i = 0; i<other.actualSize; i++)
        arr[i] = other.arr[i];

    return *this;
}

//Add item to end of array
template<typename T>
void ArrayList<T>::add(const T& item)
{
    if(actualSize < allocatedSize)
    {
        actualSize++;
        arr[actualSize-1] = item;
    }
    else
    {
        allocatedSize += INCREMENT;

        T*cpy = new T[allocatedSize];

        for(int i=0; i<actualSize; i++)
            cpy[i] = arr[i];

        actualSize++;
        cpy[actualSize-1] = item;

        delete[] arr;
        arr = cpy;
    }
}

template<typename T>
void ArrayList<T>::add(const T& item, int index)
{
    if(index < actualSize - 1)
        return;

    allocatedSize = (actualSize < allocatedSize) ? allocatedSize : allocatedSize + INCREMENT;

    T*cpy = new T[allocatedSize];

    for(int i=0; i<index; i++)
        cpy[i] = arr[i];

    cpy[index] = item;

    for(int i = index; i<actualSize; i++)
        cpy[i+1] = arr[i];

    actualSize++;
    delete[] arr;
    arr = cpy;
}

//Remove ALL occurrences of item from array
template<typename T>
void ArrayList<T>::remove(const T& item)
{
    if(actualSize <= 0)
        return;

    T*cpy = new T[allocatedSize];
    T*cpyStart = cpy;
    T*arrStart = arr;

    for(int i = 0; i<actualSize; i++)
    {
        if(arr[i] != item)
        {
            *cpy = *arr;
            cpy++;
        }

        arr++;
    }

    cpy = cpyStart;
    arr = arrStart;

    delete[] arr;
    arr = cpy;
}

template<typename T>
void ArrayList<T>::remove(int index)
{
    if(index > actualSize - 1)
        return;

    for(int i = 0; i<actualSize; i++)
    {
        if(i>=index)
            arr[i] = arr[i+1];
    }
}

template<typename T>
T& ArrayList<T>::get(int index)
{
    return arr[index];
}

template<typename T>
void ArrayList<T>::set(int index, const T& item)
{
    if(index > actualSize - 1)
        return;

    arr[index] = item;
}


texts:
I have a ton of jQuery onClick events. onClick I hide/show different UI elements. I was wondering, how can I tidy the code up and make multiple onClick events more readable?

$('.info_2').on('click', function() {
  $('#nav-wrapper').toggleClass('hidden_nav');
  $('#card-wrapper').toggleClass('centre_share');
  $('.E_info').toggleClass('display');
  $('#info-btn').css('opacity', '0');
  $('#nav-wrapper').delay(300).toggleClass('hidden');
  $('#nav-wrapper').removeClass('display_nav');
  $('#nav-wrapper').removeClass('display');
});

$('.info_back').on('click', function() {
  $('#nav-wrapper').removeClass('hidden_nav');
  $('#nav-wrapper').addClass('display_nav');
  $('#nav-wrapper').addClass('display');
  $('#info-btn').css('opacity', '1');
  $('#nav-wrapper').removeClass('hidden');
  $('.E_info').removeClass('display');
  $('.E_info').addClass('hidden');
  $('#card-wrapper').removeClass('centre_share');
});

$('#info-btn').on('click', function(){
  $('#info-btn').toggleClass('close_btn');
  $('.o-card_border').toggleClass('info_display card_active');
  $('.start_title').toggleClass('hidden remove_flow')
  $('#svg_full').attr('class', 'test');
  $('#svg_top').attr('class', 'test');
  $('#svg_bot').attr('class', 'test');
  $('#svg_bot_bot').attr('class', 'test');
  $('#svg_bot_right').attr('class', 'test');
  $('.rectangle_style_frame3 display').toggleClass('hidden');
  $('.triangle_style').toggleClass('hidden');

  $('.bg-info').toggleClass('display');
  $('.info_CharactersInvolved').toggleClass('display');
  $('.info_themes').toggleClass('display');
  $('.E_info').toggleClass('display');
});

The code works fine. I just think it looks really ugly. And the readability of it is painful, especially if you're trying to jump onto the project and learn the codebase.


texts: Find the length of a frequency-change cycle (Advent of Code 2018)

texts:
I tried to do the second part of the 1. December challenge of Advent of Code in Haskell. I'm fairly new to Haskell but I have plenty of experience in other (procedural) languages. I struggled with the challenge for hours because the program would hang and it wouldn't produce any output although I couldn't find a problem in my code. Eventually it turned out that my programm worked correctly but it just took very long. To be exact the program took 2 minutes and 40 seconds. According to Advent of Code every challenge should able to execute within 15 seconds though.

So what makes my code so slow?

The task:

  You notice that the device repeats the same frequency change list over and over. To calibrate the device, you need to find the first frequency it reaches twice.

  For example, using the same list of changes above, the device would
  loop as follows:

Current frequency  0, change of +1; resulting frequency  1.
Current frequency  1, change of -2; resulting frequency -1.
Current frequency -1, change of +3; resulting frequency  2.
Current frequency  2, change of +1; resulting frequency  3.
(At this point, the device continues from the start of the list.)
Current frequency  3, change of +1; resulting frequency  4.
Current frequency  4, change of -2; resulting frequency  2, which has already been seen.

  In this example, the first frequency reached twice is 2. Note that
  your device might need to repeat its list of frequency changes many
  times before a duplicate frequency is found, and that duplicates might
  be found while in the middle of processing the list.

  Here are other examples:

+1, -1 first reaches 0 twice.
+3, +3, +4, -2, -4 first reaches 10 twice.
-6, +3, +8, +5, -6 first reaches 5 twice.
+7, +7, -2, -7, -4 first reaches 14 twice.

  What is the first frequency your device reaches twice?

My code:

module DayOnePartTwo where

    import System.IO
    import Data.Maybe

    inputFileName = "input.txt"

    input :: String -> [Integer]
    input contents = toNum (cleanNumbers (splitNumbers contents))
        where
            cleanNumbers strs = map removeLeadingPlus strs
            splitNumbers string = words string
            toNum numbers = map read numbers
            removeLeadingPlus str = if str !! 0 == '+' then tail str else str

    accumulate :: [Integer] -> [Integer]
    accumulate list = accumulator list 0
        where
            accumulator :: Num a => [a] -> a -> [a]
            accumulator (x:xs) state = (x + state) : accumulator xs (x + state)
            accumulator [] state = []

    duplicate :: [Integer] -> Maybe Integer
    duplicate list = dup list [0]
        where
            dup (x:xs) visited =
                if elem x visited
                    then Just x
                    else dup xs (x:visited)
            dup [] _ = Nothing

    firstCyclicDuplicate :: [Integer] -> Maybe Integer
    firstCyclicDuplicate list = duplicate (accumulate cycledList)
        where
            cycledList = cycle list

    main :: IO ()
    main = do
        contents <- readFile inputFileName
        case (firstCyclicDuplicate (input contents)) of
            Just a -> print (show a)
            Nothing -> print "There is no first duplicate"

This seems to be related to slow advent of code 2018 day 1 part 2 solution in haskell although my algorithm is different.


texts: How can this swift, firebase image fetching, function be made more concise?

texts:
I am trying to fetch a group of images within a place in Firebase database ref. I then loop through each image adding it to an array which is then supposed to be added to a tableview cell. I was wondering if it could be more concise? am i doing anything unnecessary?

    func fetchAllUserFristImage() {
    Database.database().reference().child(“Posts”).observe(.childAdded, with: {(snapshot) in
        if snapshot.value as? [String: AnyObject] != nil {
            let user = snapshot.key
            self.databaseRef = Database.database().reference()
            let usersPostRef2 = self.databaseRef.child(“Posts”).child(user)
            usersPostRef2.observe(.value, with: {(postXSnapshots) in
                if let postDictionary2 = postXSnapshots.value as? [String:AnyObject] {
                    for (p) in postDictionary2 {
                        if let posts = p.value as? [String:AnyObject] {
                            //to get back to where i was delete the below for i
                            for (i) in posts {

                                if let imageUrlString = i.value as? [String:AnyObject], let postUrl = imageUrlString[“image1”] as? String {
                                    self.feedArray.append(Post(fetchedImageURL: postUrl))
                                    let imageUrl = URL(string: “\(postUrl)“)
                                    do {
                                        print(try Data(contentsOf: imageUrl!))
                                    } catch {
                                        print(error)
                                    }
                                    if let imageDataL = try? Data(contentsOf: imageUrl!) {
                                        let image = UIImage(data: imageDataL)
                                        self.tableData.append(UserImage(image: image!, postNum: p.key, userID: user))
                                        self.tableView.reloadData()
                                    } else {print(“users had no posts, was nil”)}
                                }
                            }
                        }
                    }
                }
            })
            //below shud stay same
            DispatchQueue.main.async {
                self.tableView.reloadData()
            }
        }
    })
}

Edit: Posibly I could do somthing wit this postsSnap.childSnapshot(forPath: "ImageUrl").childSnapshot(forPath: "image1") to make it more consise
Thanks!


texts:
Flask comes with built-in static file serving, but compression support is completely missing. I think the way whitenoise implements it and compress files during builds. The following should serve the compressed static files.

import os

from flask import current_app, request, safe_join

def send_compressed_file(filename, formats=[('br', 'br'), ('gzip', 'gz')]):
    if not current_app.has_static_folder:
        raise RuntimeError('No static folder for the current application')
    accept_encoding = request.headers.get('Accept-Encoding', None)
    if not accept_encoding:
        return current_app.send_static_file(filename)
    encodings = [encoding.trim() for encoding in accept_encoding.split(',')]
    for format, extension in formats:
        compressed = filename + extension
        if format in encodings and os.path.exists(safe_join(current_app.static_folder, compressed)):
            return current_app.send_static_file(compressed)
    return current_app.send_static_file(filename)

Than I would simply hook it into the Flask object.

def production():
    app.view_functions['static'] = send_compressed_file
    return app

Because it is very performance critical (every static file request hits this function) I would like to get some performance suggestions. Promblems that I encountered myself:

I think os.path.exists is not efficient? How could I store file paths better?


texts: Preparing and executing MySQL SELECT query from parameters

texts:
I am trying to make a function for Select statements. It will give result based from the parameters passed. I tried using it and it gives the results I am expecting.

I know that it is still unpolished but I would like to know what are the critical things in it that should be fixed or improved so that it would be ready for usage.

Below is the parameter passed:

 $parameters = array(
    'select' => 'user_id, username, password',
    'type' => 'i',
    'from' => 'users',
    'where_column' => 'user_id',
    'where_row' => '4'
);

And here is the function:

function select_query($parameter){
    require('database.php');

    $select = $parameter['select'];
    $type = $parameter['type'];
    $from = $parameter['from'];

    $columns = '';
    $column_array = explode(', ', $select);
    foreach ($column_array as $value) {
        $columns .= '$'. $value .', ';
    }

    //prepares the WHERE section of the SQL statement if the WHERE parameter exist
    $where = '';
    $wc = '';
    $wr = '';

    if(isset($parameter['where_column']) && isset($parameter['where_row'])){
        $wc = $parameter['where_column'];
        $wr = $parameter['where_row'];

        $where = " WHERE $wc = ?";
    }

    /* create a prepared statement */
    if ($stmt = $conn->prepare("SELECT $select FROM $from". $where)) {

        if($where != ''){
            /* bind parameters for markers */
            $stmt->bind_param($type, $wr);
        }

        /* execute query *Returns TRUE on success or FALSE on failure. * */
        $stmt->execute();

        /* bind result variables *Returns a resultset or FALSE on failure.* */
        $res = $stmt->get_result();

        /* fetch value */
        if($res->num_rows > 0){
            while($row = $res->fetch_assoc()){ // fetch_assoc *returns NULL if there are no more rows in resultset.*
                $results[] = $row;
            }
            return $results;
        }else{
            return false;
        }

        /* close statement */
        $stmt->close();
    }

    /* close connection */
    $conn->close();
}


texts: Small bash script to start and stop named services

texts:
I've been working on ubuntu since many years but not quite familiar with bash scripting. My development tools involve servers like nginx and apache, the mysql database and beanstalkd. Obviously, I just can't keep all these services running always and overwhelm my CPU capacity!, so I need a way of starting a bunch of these services without having to write poetry like:

sudo service apache2 start
sudo service mysql start
..blah blah..

Hence I've written this script called kick (no laughs!), so I can just pass it some parameters and say:

kick start apache2 mysql
# OR
kick stop nginx php-fpm

Since the starting mechanism of each of these services are different, I had to deal each one in a separate if condition. I would like to know from you bash experts whether this is the correct way to do it:

filename: kick

#!/bin/bash

function docmd()
{
    #echo 'func',"$1","$2"
    if [ "$1" = "nginx" ];
    then
        if [ "$2" = "sh" ]; then
            /home/prahlad/programs/nginx-1.6.0/sbin/nginx  -s stop
        elif [ "$2" = "re" ]; then
            /home/prahlad/programs/nginx-1.6.0/sbin/nginx
            sleep 1
            /home/prahlad/programs/nginx-1.6.0/sbin/nginx  -s stop
        else
            /home/prahlad/programs/nginx-1.6.0/sbin/nginx
        fi
    elif [ "$1" = "php-fpm" ]
    then
        if [ "$2" = "sh" ]; then
            pkill php-fpm
        elif [ "$2" = "re" ]; then
            pkill php-fpm
            sleep1
            /home/prahlad/programs/php-5.4/sbin/php-fpm
        else
            /home/prahlad/programs/php-5.4/sbin/php-fpm
        fi
    elif [ "$1" = "apache2" ]
    then
        if [ "$2" = "sh" ]; then
            sudo service apache2 stop
        elif [ "$2" = "re" ]; then
            sudo service apache2 restart
        else
            sudo service apache2 start
        fi
    elif [ "$1" = "mysql" ]
    then
        if [ "$2" = "sh" ]; then
            sudo service mysql stop
        elif [ "$2" = "re" ]; then
            sudo service mysql restart
        else
            sudo service mysql start
        fi
    else
        echo "Unrecognized verb",$1,$2
    fi
}

cmd=""
if [ "$1" == "restart" ]; then
    cmd="re"
elif [ "$1" == "stop" ]; then
    cmd="sh"
elif [ "$1" == "start" ]; then
    cmd="st"
fi

for name in $@
do
    if [ "$name" != "start" ] && [ "$name" != "stop" ] && [ "$name" != "restart" ]; then
        docmd $name $cmd
    fi
done


texts:
I found a problem on here that ask to find an MD5 hash whose hexdigits starts like decimal digits of Pi. Is there a faster program or method to solve this than my program? This uses brute force search. The site says that a has with 12 first digits like Pi exists but I was unable to find 10 correct digits from the beginning. How can one optimize this program?

# -*- coding: utf-8 -*-
import calendar
import time
import hashlib

def next_string(s):
    strip_zs = s.rstrip('z')
    if strip_zs:
        return strip_zs[:-1] + chr(ord(strip_zs[-1]) + 1) + 'a' * (len(s) - len(strip_zs))
    else:
        return 'a' * (len(s) + 1)

starttime = calendar.timegm(time.gmtime())
fo = open("testfile.txt", "r+")
a = fo.readline()
print("Putkaposti Piinkova salasana thus 39b.")
print("Find a MD5-hash whose hexrepresentation starts like the decimal representation of pi.")
print("Let us continue from the string "+a+".")
print("Ctrl+C quits the program and saves the results to the file result.txt.")
try:
    while True:
# Let us save the results every half an hour.
     now = calendar.timegm(time.gmtime())
     if now - starttime > 30*60:
        f = open("testfile.txt","w")
        f.write(a)
        f.close()
        starttime = now

     if str(hashlib.md5(a.encode('utf-8')).hexdigest())[0:10] == "3141592653":
        f = open("result.txt","w")
        f.write(a)
        f.close()
        print("Found! Print result to the screen and to the file result.txt.")
        print(a)
     a = next_string(a)
except KeyboardInterrupt:
    f = open("testfile.txt","w")
    f.write(a)
    f.close()


texts: A generic REST API consuming Python library

texts:
I wrote this, which essentially acts as a single library for all possible REST services.

Here is the main file, as of alpha version 1:

import requests, json

class RestConsumer(object):

    def __init__(self,base_url,append_json=False,**kwargs):
        self.base_url = base_url
        self.uriparts = []
        self.append_json = append_json
        self.kwargs = kwargs

    def __getattr__(self,k):
        if k=='spc':
            return self.spc
        if not k[0] == '_':
            self.uriparts.append(k)
        else:
            if k[1:3]=='in':
                self.uriparts.append(k[3:])
            elif k[1:3] == 'uh':
                self.uriparts.append(k.replace('_','-'))
        return self

    def spc(self,k):
        self.uriparts.append(k)
        return self

    def __call__(self, **kwargs):
        uri_constructed = '/'.join(self.uriparts)
        self.uriparts = []
        self.uri_constructed = "%s%s"%(uri_constructed,'.json') if self.append_json else uri_constructed
        self.url = '/'.join([self.base_url,self.uri_constructed])
        return self.get(self.url,**kwargs)

    def get(self,url,**kwargs):
        print url
        r = requests.get(url,**kwargs)
        return json.loads(r.content)

    def post(self,**kwargs):
        r = requests.post(**kwargs)
        return json.loads(r.content)

if __name__=='__main__':
    from pprint import pprint
    t = RestConsumer(base_url='https://api.twitter.com/1',append_json=True)
    public_timeline = t.statuses.public_timeline()
    pprint(public_timeline)

    g = RestConsumer(base_url='https://api.github.com')
    repos = g.users.kennethreitz.repos()
    pprint(repos)

    s = RestConsumer(base_url='http://api.stackoverflow.com/1.1')
    sr = s.users.spc('55562').questions.unanswered()
    pprint(sr)

    sr2 = s.tags.python.spc('top-answerers').spc('all-time')()
    pprint(sr2)

The rationale and usage is all explained in the README.

Please critique the library, the idea, implementation and shed light on alternatives.


texts: Adding a List to SQL database (Entity Database)

texts:
I got a database with members, each member has a list of sports they do.
now I want to loop through a listbox and add every selected item to my database.

This is my database :

And this is my code :

foreach (var item in sportCheckedListBox.CheckedIndices)
            {
                int sportindex = Convert.ToInt32(item.ToString()) + 1;
                var queryResult = from sp in context.Sports
                                  where sp.sportnr == sportindex
                                  select sp;
                foreach (var sport in queryResult)
                {
                    myMember.Sports.Add(sport);
                }
            }

This looks kinda 'shady', how could I do this better ?


texts: Compute shortest distance between point and a rectangle

texts:
I want to compute the shortest distance between a position (x,y) and a rectangular box defined by (x_min, y_min) and (x_max, y_max). See the picture below with some examples. I know that in two dimensions there are 9 cases I have to take into account.

Since this part of my code is used very often, I would like to know what is the fastest possible way to do that? Here is what I have done so far:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#define sqr(x) ((x)*(x))

double distanceBoxParticle2D(double x, double y, double x_min, double y_min, double x_max, double y_max);

int main(){
    double x = -6;
    double y = -6;
    double x_min = -5;
    double x_max = 5;
    double y_min = -5;
    double y_max = 5;

    double distance = distanceBoxParticle2D(x, y, x_min, y_min, x_max, y_max);
    printf("distance = %f\n", distance);

}

double distanceBoxParticle2D(double x, double y, double x_min, double y_min, double x_max, double y_max){
    double r = 0;

    if(x < x_min){
        if(y < y_min){
            return r = sqrt( sqr(x_min-x) + sqr(y_min-y) );
        }else if(y > y_max){
            return r = sqrt( sqr(x_min-x) + sqr(y_max-y) );
        }else if((y >= y_min) && (y <= y_max)){
            return r = x_min - x;
        }
    }else{
        if((x > x_min) && (x < x_max)){
            if(y < y_min){
                return r = y_min - y;
            }else if(y > y_max){
                return r = y - y_max;
            }
        }else{
            if(x > x_max){
                if(y < y_min){
                    return r = sqrt( sqr(x_max-x) + sqr(y_min-y) );
                }else if(y > y_max){
                    return r = sqrt( sqr(x_max-x) + sqr(y_max-y) );
                }else if((y >= y_min) && (y <= y_max)){
                    return r = x - x_max;
                }
            }
        }
    }

    return r = 0; // if (x,y) is inside of the box
}

The example is only for two dimensions. Later I want to do the same in 3D. There I have to consider 27 cases, which is a lot. Is there any smart and fast solution for this case or do I have to hard-code every case?


texts:
I'm trying to teach myself C. I've managed to make this program I call HappyToYou.c (inspired by this video):

#include <stdio.h>
//#include <stdlib.h> //malloc would need this.
#include <string.h>
#include <err.h>

void sing(char *start, char *end){
    printf("%s%s.\n", start, end);
}

int main(int argc, char *argv[]){
    if(argc!=3) errx(1, "Give a holiday and a name as arguments.");

    char *happy="Happy ";
    char start[strlen(happy)+strlen(argv[1])+1];
    strcpy(start, happy);
    strcat(start, argv[1]);
    char *to=" to you";

    char *dear=" dear, ";
    char person[strlen(dear)+strlen(argv[2])+1];
    strcpy(person, dear);
    strcat(person, argv[2]);

    sing(start, to);
    sing(start, to);
    sing(start, person);
    sing(start, to);

    return 0;
}

I think it is free from bugs (as far as I know). I'm pretty sure it can be trimmed down but I'm not sure how.


texts:
I wanted a pattern to manage web.config appsettings. I want to be able to have a default setting if the config setting was missing. I also wanted the check for the value in the config file to happen only once, not each time the the value is retrieved.

Public NotInheritable Class ExternalReportRequestBL

    ''' <summary>
    ''' The default value for max number of request attempts
    ''' </summary>
    ''' <remarks></remarks>
    Private Shared _ReportRequestMaxExecuteAttemptDefault As Integer

    Shared Sub New()
        If Not Integer.TryParse(ConfigurationManager.AppSettings("ReportRequestMaxExecuteAttempt"), ExternalReportRequestBL._ReportRequestMaxExecuteAttemptDefault) Then
            _ReportRequestMaxExecuteAttemptDefault = 10
        End If
    End Sub

    Friend Shared ReadOnly Property MaxNumberOfTries As Integer
        Get
            Return ExternalReportRequestBL._ReportRequestMaxExecuteAttemptDefault
        End Get
    End Property
End Class

Now, I can access the variable from anywhere in the assembly:

ExternalReportRequestBL.MaxNumberOfTries

What are your thoughts?


texts: meta predicates fixedpoint/3 and fixedpointlist/3

texts:
What about the following meta-predicate "fixed point"?

fixedpoint(P_2,X0,X) :-
   call(P_2,X0,X1),
   if_(X0 = X1, X = X0, fixedpoint(P_2,X1,X)).

fixedpointlist(P_2,X0,[X0|Xs]) :-
   call(P_2,X0,X1),
   if_(X0 = X1, Xs = [], fixedpointlist(P_2,X1,Xs)).

The implementation is based, in part, on if_/3 and reified term equality (=)/3 by @false.

Are above definitions useful idioms?


texts:
I implemented a simple version of echo(1) command utility. The program works as described in the man page: it writes to the standard output all command line arguments, separated by a whitespace and end with a newline. It can process the option -n that avoid to print the newline.

About my implementation, it is not complete, because it doesn't interpret common backslash-escaped characters (for example \n, \c, and so forth). i used a StringBuilder object to build the output string, because I'm not sure that the standard output is buffered. I also make some checks so the program can work without specifying any arguments.

You can compile the program with javac JEcho and run it with java JEcho <...>.

JEcho.java

/**
 * JEcho writes any command line argument to the standard output; each argument
 * is separated by a single whitespace and end with a newline (you can
 * specify '-n' to suppress the newline).
 *
 * This program doesn't interpret common backslash-escaped characters (for
 * exampe '\n' or '\c').
 */
public class JEcho {
    public static void main(String[] args) {
        boolean printNewline = true;
        int posArgs = 0;

        if (args.length > 0 && args[0].equals("-n")) {
                printNewline = false;
                posArgs = 1;
        }

        StringBuilder outputBuilder = new StringBuilder();

        for (; posArgs < args.length; posArgs++) {
            outputBuilder.append(args[posArgs]);
            outputBuilder.append(" "); // Separator.
        }

        // Remove the trailing whitespace at the end.
        int outputLength = outputBuilder.length();
        if (outputLength > 0)
            outputBuilder.deleteCharAt(outputBuilder.length() - 1);

        String output = outputBuilder.toString();

        if (printNewline)
            System.out.println(output);
        else
            System.out.print(output);
    }
}


texts:
When giving away or selling a PC, one should be careful not to send personal data with it. I'm in such a situation and was using dd if=/dev/urandom of=/dev/sdb bs=8M, but it was only averaging 22MB/s. Way too slow since I have to drop it at the post office next morning. So I decided to write my own and see what kinds of results I would get.

First I dropped /dev/urandom in favor of hashing a secret key and feeding back the output as state. The second thing I did was to use O_DIRECT to avoid buffering.

My program reports an average of 48MiB/s, much better than what I got with plain old dd unless it has a bug.

#define _GNU_SOURCE 1

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <time.h>
#include <stdint.h>
#include <string.h>
#include <unistd.h>
#include <openssl/sha.h>

#define BLOCK_SIZE (1024 * 1024 * 8)
#define ALIGNMENT 512

typedef struct {
  unsigned char state[64];
  unsigned char key[32];
  __uint128_t counter;
} RandomCtx;

static void _xor64(uint64_t* a, uint64_t* b)
{
  for(int i = 0; i < 8; ++i)
    *a++ ^= *b++;
}

static void _cipher(RandomCtx* ctx, unsigned char* data, unsigned int len)
{
  unsigned int runs = len >> 6;
  while(runs){
    // get value to XOR
    unsigned char x[64];
    SHA512((unsigned char const*)ctx, sizeof(RandomCtx), x);

    // XOR with data
    _xor64((uint64_t*)data, (uint64_t*)x);

    // feed the XORed result back as state and update counter
    memcpy(ctx->state, data, 64);
    ++ctx->counter;

    // move on
    data += 64;
    --runs;
  }
}

int main(int argc, char* argv[])
{
  if(2 != argc){
    fprintf(stderr, "Usage: %s /dev/sdb\n", argv[0]);
    return EXIT_FAILURE;
  }

  // open disk
  int disk = open(argv[1], O_WRONLY|O_DIRECT);
  if(-1 == disk){
    perror("open()");
    return EXIT_FAILURE;
  }

  // allocate memory enough
  char* raw = malloc(BLOCK_SIZE + ALIGNMENT - 1);
  if(!raw){
    perror("malloc()");
    return EXIT_FAILURE;
  }

  // align
  unsigned char* aligned = (unsigned char*)
                           ((size_t)(raw + (ALIGNMENT-1)) & ~(ALIGNMENT-1));

  // open random source
  int urandom = open("/dev/urandom", O_RDONLY);
  if(-1 == urandom){
    perror("open()");
    return EXIT_FAILURE;
  }

  // init random ctx
  RandomCtx ctx;
  if(sizeof ctx != read(urandom, &ctx, sizeof ctx)){
    perror("read()");
    return EXIT_FAILURE;
  }

  // init buffer
  if(BLOCK_SIZE != read(urandom, aligned, BLOCK_SIZE)){
    perror("read()");
    return EXIT_FAILURE;
  }

  // we are done with urandom
  close(urandom);

  // now run until there's no more space
  time_t ti0 = time(NULL);
  size_t to0 = 0;
  size_t to1 = 0;
  int gib = 0;
  while(BLOCK_SIZE == write(disk, aligned, BLOCK_SIZE)){
    to1 += BLOCK_SIZE;
    if((to1 - to0) >= (1024*1024*1024)){
      to0 = to1;
      ++gib;
      size_t secs = time(NULL) - ti0;
      printf("Total: %d GiB in %zu secs. %.2f MiB/s\n", gib, secs,
             (double)gib*1024/secs);
    }

    _cipher(&ctx, aligned, BLOCK_SIZE);
  }
}


texts:
I build a cart for an ecommerce website, and I want to know if I did well.

I want to record the changes in the DB and display the information from the DB to the customer. To be sure that what he sees is the good information. I use an ajax request and JSON to do so.

Please give me your comments. I especially want to know is my code safe?

The client side:

    function save_to_db(cartId, newQuantity) {
  $.ajax({
    url: "updateCart.php",
    data: "cartId=" + cartId + "&newQuantity=" + newQuantity + "&memberId=" + <?php echo $memberId?>,
    type: 'post',
    dataType: "json",
    success: function(response) {
      if (response === "Empty cart") {
        $("#total-quantity").text(0);
        $("#total-price").text(0);
        $("#shopping-cart-table").html("
Your cart is empty.
");
      }

      if (newQuantity == 0) {
        $("#item-container-" + cartId).remove();
      }

      var totalQuantity = 0;
      var totalItemPrice = 0;
      $.each(response, function(key, cartDetails) {
        totalItemPrice = totalItemPrice + parseInt(cartDetails.price) * parseInt(cartDetails.quantity);
        totalQuantity = totalQuantity + parseInt(cartDetails.quantity);

        if (cartDetails.cartId == cartId) {
          $("#input-quantity-" + cartId).val(cartDetails.quantity);
          $("#cart-price-" + cartId).text("$" + cartDetails.price * cartDetails.quantity);
        }
      });

      $("#total-quantity").text(totalQuantity);
      $("#total-price").text(totalItemPrice);
      $("#total-price-foot").text(totalItemPrice);
    }
  });
}

The server side:

    <?php
require 'connectDB.php';

$memberId = $_POST["memberId"];

if($_POST["newQuantity"] == 0){
    $stmt = mysqli_prepare($conn,"DELETE FROM tbl_cart WHERE id = ? AND member_id = ?");

    mysqli_stmt_bind_param($stmt, "ii", $_POST["cartId"], $memberId);
    mysqli_stmt_execute($stmt);
    mysqli_stmt_close($stmt);
}
elseif ($_POST["newQuantity"] == 1 || $_POST["newQuantity"] == -1) {
    $stmt = mysqli_prepare($conn,"UPDATE tbl_cart SET quantity =
        (CASE WHEN quantity + ? > 0 THEN quantity + ? ELSE quantity END)
        WHERE id= ? AND member_id = ?");

        mysqli_stmt_bind_param($stmt, "iiii",
            $_POST["newQuantity"],
            $_POST["newQuantity"],
            $_POST["cartId"],
            $memberId);
        mysqli_stmt_execute($stmt);
        mysqli_stmt_close($stmt);
    }

    if ($stmt = mysqli_prepare($conn,"SELECT tbl_product.id, tbl_product.price, tbl_cart.quantity, tbl_cart.id
        AS cartId FROM tbl_product, tbl_cart WHERE tbl_product.id = tbl_cart.product_id AND tbl_cart.member_id = ?")) {

            mysqli_stmt_bind_param($stmt, "i", $memberId);
            mysqli_stmt_execute($stmt);

            $result = mysqli_stmt_get_result($stmt);
            while ($row = mysqli_fetch_assoc($result)){
                $cartDetails[] = $row;
            }

            mysqli_stmt_close($stmt);
        }

        if(isset($cartDetails)){
            $response = json_encode($cartDetails);
            echo $response;
        }
        else{
            $response = json_encode("Empty cart");
            echo $response;
        }
        ?>


texts: Simplifying Code for Drop-Down-Box in JQuery and HTML

texts:
I'm trying to come up with a way to make a drop down box that is displayed through a jquery mouse hover event and with nested dropdown boxes displayed through hovering over elements of the original drop down box. I wrote some terribly inefficient code and I'm struggling to find ways of simplifying it. If anyone has any suggestions that will help me shorten this code and get a better idea of how to take advantage of functions of JQuery, please help.

here is the link:

http://cs-dev.dreamhosters.com/dropd.php

$(document).ready(function(){
$(".tab, .drop").hover(function(){
$(".tab").css("color","#FF7722");
$(".drop").css("display","block");
$("#tv, .droptv").hover(function(){
        $(this).css("color","#FF7722");
        $(".droptv").css("display","block");
        $(".droptv").hover(function(){
                $("#tv, .droptv").css("color","#FF7722");
                },function(){
                $(".droptv").css("color","#005BAB");
                });
        },function(){
        $(this).css("color","#005BAB");
        $(".droptv").css("display","none");
        });
$("#interact").hover(function(){
        $(this).css("color","#FF7722");
        },function(){
        $(this).css("color","#005BAB");
        });
$("#online").hover(function(){
        $(this).css("color","#FF7722");
        },function(){
        $(this).css("color","#005BAB");
        });
$("#vod, .dropvod").hover(function(){
        $(this).css("color","#FF7722");
        $(".dropvod").css("display","block");
        $(".dropvod").hover(function(){
                $("#dai").hover(function(){
                    $(this).css("color","#FF7722");
                    },function(){
                    $(this).css("color","#005BAB");
                    });
                $("#iguide").hover(function(){
                    $(this).css("color","#FF7722");
                    },function(){
                    $(this).css("color","#005BAB");
                    });
                $("#vod").css("color","#FF7722");
                },function(){
                $(".dropvod").css("color","#005BAB");
                });
        },function(){
        $(this).css("color","#005BAB");
        $(".dropvod").css("display","none");
        });
$("#tablet").hover(function(){
        $(this).css("color","#FF7722");
        },function(){
        $(this).css("color","#005BAB");
        });
$("#mobile").hover(function(){
        $(this).css("color","#FF7722");
        },function(){
        $(this).css("color","#005BAB");
        });
},function(){
$(".tab").css("color","#005BAB");
$(".drop").css("display","none");
 });
});


texts: Selenium Framework using a lot of statics

texts:
I am writing a Selenium framework that should be really easy for a tester with relatively little Java knowledge to use and write tests for. In order to keep the framework as user friendly as possible, I've noticed that I am writing a lot of statics so that the tester doesn't have to instantiate the page objects and methods every time. This of course goes against the principles of OOP. Before I get in too deep with this I'd like to see if there are viable alternatives to my approach. I'm including below the login page class that instantiates a webdriver Singleton, has a username/password field, and a login button. There are 2 tests for this page that are run using TestNG. All code to follow:

LoginPage.java

public class LoginPage {

    public static WebDriver driver;
    private static String username_selector = "username";
    private static String password_selector = "password";
    private static String login_button_selector = "#loginbutton > input";
    private static String fail_message_selector = "error";

    public static void goTo(String environment_url){
        driver = Driver.getDriver();
        driver.get(environment_url);
    }

    public static void loginAs(String username, String password){
        WebElement user = driver.findElement(By.name(username_selector));
        user.clear();
        user.sendKeys(username);
        WebElement pass = driver.findElement(By.name(password_selector));
        pass.clear();
        pass.sendKeys(password);
        WebElement loginBtn = driver.findElement(By.cssSelector(login_button_selector));
        loginBtn.click();
    }

    public static boolean loginErrorDisplayed(){
        WebElement failMessageContainer = driver.findElement(By.className(fail_message_selector));
            if(failMessageContainer.isDisplayed()){
                return true;
            }
            else return false;
    }

    public static String getLoginErrorMessage(){
        WebElement failMessageContainer = driver.findElement(By.className(fail_message_selector));
        String failMessage = failMessageContainer.getText();
        return failMessage;
    }

}

Driver.java

public class Driver {
    public static WebDriver driver = null;

    public static WebDriver getDriver(){
        if(driver == null){
            driver = new FirefoxDriver();
        }

        return driver;
    }

    public static void killDriver(){
        driver.quit();
    }
}

LoginTest.java

public class LoginTest {

@Test(priority = 0)
public void loginfail() {
    LoginPage.goTo("http://127.0.0.1:8080/login");
    LoginPage.loginAs("wrong username", "wrongpassword");
    boolean didLoginFail = LoginPage.loginErrorDisplayed();
    Assert.assertTrue(didLoginFail == true, "Bad login was successful");
    if (didLoginFail){
        LoginPage.getLoginErrorMessage();
    }
}

@Test(priority = 1)
public void loginsuccess() {
    LoginPage.loginAs("correct_username", "correctpass");
    boolean didLoginFail = LoginPage.loginErrorDisplayed();
    Assert.assertTrue(didLoginFail == false, "Valid Login was unsuccessful");
}

}


texts: Character Picture Grid (from Automate the Boring Stuff)


texts:
Challenge:

  Write a program that will clean up the words from extra numbers and symbols.

Specifications:

  The first argument is a path to a file.
  Each line includes a test case with a list of words: letters are both lowercase and uppercase, and are mixed with extra symbols.
  Print the words separated by spaces in lowercase letters.
  The length of a test case together with extra symbols can be in a range from 10 to 100 symbols.
  The number of test cases is 40.

Solution:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class CleanWords {
    public static void main(String[] args) {
        try (Scanner input = new Scanner(new File(args[0]))) {
            while(input.hasNextLine()) {
                System.out.println(sanitize(input.nextLine()));
            }
        } catch (FileNotFoundException fnfe) {
            System.out.println(args[0] + " doesn't exist");
        }
    }

    private static String sanitize(String input) {
        StringBuilder result = new StringBuilder();
        for (String s : input.split("[^a-zA-Z]+")) {
            result.append(' ').append(s);
        }
        return result.toString().toLowerCase().trim();
    }
}

Sample Input:

(--9Hello----World...--)
Can 0$9 ---you~
13What213are;11you-123+138doing7

Sample Output:

hello world
can you
what are you doing

I'm wondering if:

It would be more efficient to call trim within the loop?
If there's a less costly way than looping twice between calling both toLowerCase and trim

These may seem like givens, but it's been a long time since I did one of these, and I wanted to get back into it with a seemingly simple one. I passed on the first try which I largely have CR to thank for. For those interested, the source is CodeEval.com.


texts:
Basic idea is to use a Class, with static methods to add and remove references in a static vector, that keeps track of these references, and check that vector upon exit.

The class is detecting intentional leaks that I create, but maybe you can find a case where it does not detect the leak, that I am not seeing

#include <iostream>
#include <stdexcept>
#include <memory>
#include <vector>
#include <cstdlib> // for REM_LEAKt
#include <algorithm> // for std::remove

void checkLeakStack();
class LeakDbg
{
private:
    LeakDbg()
    {
        /// Constructor will only be called once,
        /// since it's a singlton class
        std::atexit( checkLeakStack );
    }

public:
    struct Pair
    {
        std::string name;
        void* ref;
        bool operator==( const Pair &other ) const { return ref == other.ref; }

    };
    static bool locked;
    static std::vector<Pair> stack;
    static LeakDbg& instance()
    {
        static LeakDbg INSTANCE;
        return INSTANCE;
    }

    static void addRef(const std::string& nm, void* ptr)
    {
        stack.push_back(Pair{ nm, ptr });
    }
    static void remRef(void* ptr)
    {
        /// If it's not enabled, it means
        /// it's OK to remove a ref
        if( !LeakDbg::locked ){
            Pair search = Pair{"",ptr};
            std::vector<Pair> vect;
//            std::remove(vect.begin(), vect.end(), search);
            stack.erase(std::remove(stack.begin(), stack.end(), search), stack.end());
        }
    }

};

bool LeakDbg::locked = false;
std::vector<LeakDbg::Pair> LeakDbg::stack = std::vector<LeakDbg::Pair>();

void checkLeakStack()
{
    /// Here the stack should be emoty
    /// you can print or assert if the stack is not empty
    std::cout << "There are " << LeakDbg::stack.size() << " leaks ..." "\n";
    for ( LeakDbg::Pair pair : LeakDbg::stack) {
        const std::string msg = pair.name + " is leaked";
        std::cout << msg << std::endl;
    }
}

Add defines

#define ADD_LEAK(msg, ptr) LeakDbg::addRef(msg, ptr);
#define REM_LEAK(ptr) LeakDbg::remRef(ptr);
#define CREATE_LEAK_DET() LeakDbg::instance();
#define LCK_LEAK_DET(st) LeakDbg::locked = st;

// ADD_LEAK         -> Add it in a class constructor
// REM_LEAK         -> Add it in a class destructor
// CREATE_LEAK_DET  -> Call it once to make sure "std::atexit" is called
// LCK_LEAK_DET     -> If set to "true", all objects destructed after,
//                  -> will be considered a leak

Test

struct Test {
    Test() {
        ADD_LEAK( "Cls",  this )
    }
    ~Test() {
        REM_LEAK( this )
    }

};

int main() {
    CREATE_LEAK_DET()
    Test *obj1 = new Test();
    Test *obj2 = new Test();
    Test *obj3 = new Test();
    delete obj2;
    LCK_LEAK_DET( true )
}

Update 12/12/2019
If anybody is interested, I refactored the code to be reusable and less intrusive. Github


texts: Building an efficient bubble sort function

texts:
I've been asked to create a bubble sort function that checks whether the array has been filled sorted before all passes are complete, thereby avoiding unnecessary passes. This is to involve "remembering" the last sort.

Below is the code I have for just a normal bubble sort that goes through all passes, and is quite inefficient. The parameter variables are 'a' for the generic array itself and n, which is the number of passes. In this case we're doing a full set of passes for the array, which is 10 integers in length.

public static void main(String[] args) {

    Integer[] myArray = new Integer[10];
    System.out.println("Iterative Bubble Sort - Ch 8, Ex 8a on page 265");
    generateRandonNumbers(myArray);
    display(myArray);
    bubbleSort(myArray,10);
    display(myArray);
    System.out.println("Recursive Bubble Sort - Ch 8, Ex 8b on page 265");
    generateRandonNumbers(myArray);
    display(myArray);
    recursiveBubbleSort(myArray,10);
    display(myArray);
    System.out.println("Better Bubble Sort - Ch 8, Ex 10 on page 266");
    generateRandonNumbers(myArray);
    display(myArray);
    betterBubbleSort(myArray,10);
    display(myArray);

}
public static void display(Integer[] array)
{
    for(int i=0; i<array.length; i++)
    {
        System.out.print(array[i] + " ");
    }
    System.out.println();
}
public static void generateRandonNumbers(Integer[] array)
{
    Random randomNum = new Random();
    for(int i=0; i<array.length; i++)
    {
        array[i] = randomNum.nextInt(100);
    }
}
public static <T extends Comparable<? super T>> void bubbleSort(T[] a, int n)
{
    int k = 0;
    while (k <= n)
    {
        k++;

    for (int i = 0; i < a.length - k; i++)

            {
                if (a[i].compareTo(a[i+1]) > 0)
                {
                    T data = a[i];
                    a[i] = a[i + 1];
                    a[i + 1] = data;

                }
            }
    }
}

The test results are:

9 36 59 60 40 28 71 95 90 56

(unsorted, displaying all values from the array)

9 28 36 40 56 59 60 71 90 95

(now sorted from the bubbleSort function)

How do I go about turning this into a more efficient sort function by avoiding unnecessary passes? I'm supposed to get the program to remember the last sort and I'm not sure how to go about doing this.


texts:
I am making a basic program just for a local machine so I do not need to create anything fancy but I am finding that my code is going to become quite lengthy. Any tips on how to improve it so I am not repeating code? I have additional code to add in respect to client data etc but I am primarily concentrating on the foundation first.

from tkinter import *
from PIL import ImageTk, Image

root = Tk()
root.withdraw()

def login(event):
    if ent1.get() == 'admin' and ent2.get() == 'password':
        root.iconify()
        top.destroy()

def client_data(event):
    root.withdraw()
    top = Toplevel()
    top.title('Client Data')
    top.geometry('800x500')
    top.configure(background='grey')
    client1 = Message(top, text='Random skeleton', bg='grey', width=350)
    client1.pack()
    x = Button(top, text='Close', bg='red', command=top.destroy)
    root.iconify()
    x.pack()

image1 = ImageTk.PhotoImage(Image.open('ileye.png'))
top = Toplevel()
top.title('Login')
top.configure(background='grey')
photo = Label(top, image=image1)
photo.pack()
user = Label(top, text='User name', bg='grey')
user.pack()
ent1 = Entry(top, bg='grey')
ent1.pack()
pwd = Label(top, text='Password', bg='grey')
pwd.pack()
ent2 = Entry(top, show='*', bg='grey')
ent2.bind('<Return>', login)
ent2.pack()
ex = Button(top, text='EXIT', command=root.quit)
ex.pack()
check = Checkbutton(top, text='Remember me', bg='grey')
check.pack()

root.title('Main Screen')
root.attributes('-zoomed', True)
menu_drop = Menu(root)
root.config(menu=menu_drop)
file = Menu(menu_drop)
menu_drop.add_cascade(label='Options', menu=file)
file.add_command(label='New', command=root.quit)  ## New Function
client = Button(root, text='Client list')
file.add_separator()
file.add_command(label='Close App', command=root.quit)
client.bind('<Button-1>', client_data)
client.pack()
exi = Button(root, text='EXIT', command=root.quit)
exi.pack()

root.mainloop()


texts:
Please tell me if I'm doing this right, and what else is needed to make this hardened.

It seems like it's too simple, like there's almost nothing I'm actually doing.  For example, there are 4 or 5 stacked using statements!

Here is the code to review:

class Program
{
    static void Main(string[] args)
    {
        var enc = true;
        var fileIn = string.Empty;
        var fileOut = string.Empty;

        /* parse command line to populate enc, fileIn, fileOut */

        Console.Write("key: ");
        var key = Encoding.UTF8.GetBytes(Console.ReadLine());
        Console.Write("IV: ");
        var iv = Encoding.UTF8.GetBytes(Console.ReadLine());

        using (var aes = AesManaged.Create())
        using (var md5 = MD5.Create())
        using (var readStream = File.OpenRead(fileIn))
        using (var writeStream = File.OpenWrite(fileOut))
        using (var cryptoStream = new CryptoStream(
            enc ? writeStream : readStream,
            enc
                ? aes.CreateEncryptor(md5.ComputeHash(key), md5.ComputeHash(iv))
                : aes.CreateDecryptor(md5.ComputeHash(key), md5.ComputeHash(iv)),
            enc ? CryptoStreamMode.Write : CryptoStreamMode.Read))
        {
            if (enc) { readStream.CopyToAsync(cryptoStream).Wait(); }
            else { cryptoStream.CopyToAsync(writeStream).Wait(); }
        }
    }
}


texts:
This is my first ever created program I've made. It's not very good but I'm pretty proud of it.
If you have any suggestions I could add into the calculator I would gladly do that.
using System;
using System.IO;
using System.Linq;
using System.Collections.Generic;

namespace CSharp_Shell
{
    public static class Program
    {
        public static void Main()
        {
           try
           {
                Console.WriteLine("--------------------------------");
                Console.WriteLine("Operators:");
                Console.WriteLine("+ = Add");
                Console.WriteLine("- = Subtract");
                Console.WriteLine("* = Multiply");
                Console.WriteLine("/ = Divide");
                Console.WriteLine("^ = Power");
                Console.WriteLine("--------------------------------");

                Console.Write("Enter operator: ");

                string op = (Console.ReadLine());

                Console.Write("Enter First Number: ");
                double num1 = Convert.ToDouble(Console.ReadLine());

                Console.Write("Enter Second Number: ");
                double num2 = Convert.ToDouble(Console.ReadLine());
                Console.WriteLine("--------------------------------");

                if (op == "+")
                {
                   Console.WriteLine(num1 + num2);
                   Console.WriteLine("--------------------------------");
                }
                else if (op == "-")
                {
                   Console.WriteLine(num1 - num2);
                   Console.WriteLine("--------------------------------");
                }
                else if (op == "/")
                {
                   Console.WriteLine(num1 / num2);
                   Console.WriteLine("--------------------------------");
                }
                else if (op == "*")
                {
                   Console.WriteLine(num1 * num2);
                   Console.WriteLine("--------------------------------");
                }
                else if (op == "^")
                {
                   double value1 = Math.Pow(num1, num2);
                   Console.WriteLine("{0}", value1);
                   Console.WriteLine("--------------------------------");
                }
                else
                {
                   Console.ForegroundColor = ConsoleColor.Red;
                   Console.WriteLine("error");

                   Console.ForegroundColor = ConsoleColor.White;
                   Console.WriteLine("--------------------------------");
                }
           }
           catch
           {
            Console.ForegroundColor = ConsoleColor.White;
                Console.WriteLine("--------------------------------");

            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine("error");

            Console.ForegroundColor = ConsoleColor.White;
                Console.WriteLine("--------------------------------");
           }
           Console.ForegroundColor = ConsoleColor.Gray;
           Console.Write("Press any key to stop the program");
           Console.ReadKey();
        }
    }
}