texts: Makefile for a C++ project using Boost, Eigen, and htslib

texts:
I had a Makefile but it doesn't meet the "industry-standard expectation". That was feedback from my client. The old Makefile was rejected. Thus, I'm making a new one.

Here is the repository for my project.

My old Makefile:

# Boost C++ library
BOOST = /usr/local/include/boost_1_64_0

# Linear-algebra library
EIGEN = /usr/local/Cellar/eigen/3.2.8/include/eigen3

# HTSLIB library for BAM files
HTSLIB = /Users/tedwong/Sources/QA/htslib

# Where the header are
INCLUDE = src

EXEC         = anaquin
SOURCES      = $(wildcard src/*.cpp src/tools/*.cpp src/analyzers/*.cpp src/RnaQuin/*.cpp src/VarQuin/*.cpp src/MetaQuin/*.cpp src/data/*.cpp src/parsers/*.cpp src/writers/*.cpp src/stats/*.cpp src/cufflinks/*.cpp)
OBJECTS      = $(SOURCES:.cpp=.o)
OBJECTS_TEST = $(SOURCES_TEST:.cpp=.o)
SOURCES_LIB  = $(wildcard src/htslib/cram/*.c)
OBJECTS_LIB  = $(SOURCES_LIB:.c=.o)

$(EXEC): $(OBJECTS) $(OBJECTS_TEST) $(OBJECTS_LIB)
    g++ $(OBJECTS) $(OBJECTS_TEST) $(OBJECTS_LIB) -DBACKWARD_HAS_BFD -g -lpthread -lz -lhts -L $(HTSLIB) -o $(EXEC)

%.o: %.c
    gcc -g -c -DBACKWARD_HAS_BFD -I src/htslib -I $(INCLUDE) -I $(EIGEN) -I ${BOOST} $< -o $@

%.o: %.cpp
    g++ -g -DK_HACK -DBACKWARD_HAS_BFD -c -std=c++11 -I src/htslib -I src/stats -I $(INCLUDE) -I $(EIGEN) -I ${BOOST} $< -o $@

clean:
    rm -f $(EXEC) $(OBJECTS) $(OBJECTS_TEST)

My new Makefile:

#
# Please modify only BOOST, EIGEN and HTSLIB. You should be able to leave all other options intact. C++ compiler with C++11 support is mandatory.
#

# Boost C++ library
BOOST = /usr/local/include/boost_1_64_0

# Linear-algebra library
EIGEN = /usr/local/Cellar/eigen/3.2.8/include/eigen3

# HTSLIB library for reading BAM files
HTSLIB = /Users/tedwong/Sources/QA/htslib

CC     = g++
CFLAGS = -g -O2
CPPFLAGS = -c -std=c++11
DFLAGS =
#DFLAGS = -DBACKWARD_HAS_BFD # https://github.com/bombela/backward-cpp
LIBS   = -lpthread -lz -lhts

# Where the header are (no need to modify this)
INCLUDE = src

EXEC         = anaquin
SOURCES      = $(wildcard src/*.cpp src/tools/*.cpp src/analyzers/*.cpp src/RnaQuin/*.cpp src/VarQuin/*.cpp src/MetaQuin/*.cpp src/data/*.cpp src/parsers/*.cpp src/writers/*.cpp src/stats/*.cpp src/cufflinks/*.cpp)
OBJECTS      = $(SOURCES:.cpp=.o)
OBJECTS_TEST = $(SOURCES_TEST:.cpp=.o)
SOURCES_LIB  = $(wildcard src/htslib/cram/*.c)
OBJECTS_LIB  = $(SOURCES_LIB:.c=.o)

$(EXEC): $(OBJECTS) $(OBJECTS_TEST) $(OBJECTS_LIB)
    $(CC) $(OBJECTS) $(OBJECTS_TEST) $(OBJECTS_LIB) $(CFLAGS) $(DFLAGS) $(LIBS) -L $(HTSLIB) -o $(EXEC)

%.o: %.c
    $(CC) $(CFLAGS) -c $(DFLAGS) -I $(INCLUDE) -I $(EIGEN) -I ${BOOST} $< -o $@

%.o: %.cpp
    $(CC) $(CFLAGS) $(DFLAGS) $(CPPFLAGS) -I $(HTSLIB) -I src/stats -I $(INCLUDE) -I $(EIGEN) -I ${BOOST} $< -o $@

clean:
    rm -f $(EXEC) $(OBJECTS) $(OBJECTS_TEST)


texts:
I'm looking to let people define arbitrarily nested lists of lists and return a random json document for them. Right now the assumption is that if you have a structure like this:

[item1, item2, [item3, item4]]

The desired document is:

{item1: value,
item2: {
    item3: value,
    item4: value
    }
}

This is my current solution:

def random_document(document_layout, type_, **kwargs):
    document_layout.append("dummy_item")
    doc = lambda l:{l[i]:doc(l[i+1]) if isinstance(l[i+1],list) else random_item(type_,**kwargs) for i in range(len(l)-1)}
    return doc(document_layout)

as a one line fetishist, I feel like the middle line is beautiful, but I think the general hack of adding a dummy element to the end is hackish. Any thoughts on how to make this more elegant?

Also, not looking for deeply readable, this is just for my own private use and isn't going to spread out in any meaningful way, so I would just like to preempt the commentary about it not being readable.

Here's a more "readable" version:

def random_document(document_layout, type_, **kwargs):
    document_layout.append("dummy_item")
    full_dict = {}
    def internal_comprehension(document):
        for i in range(len(document)-1):
            if isinstance(document[i+1], list):
                full_dict.update({document[i]: internal_comprehension(document[i+1])})
            else:
                full_dict.update({document[i]: random_item(type_, **kwargs)})
    return internal_comprehension(document_layout)


texts: ReactiveCocoa implementation of async function

texts:
I would like a review of the RAC implementation for the function setGist()
I've posted the code on GitHub for easier reading.

Description:

You create an instance of GistService()
let gistService = GistService()
Then use public functions .resetGist() -> Bool and .setGist(string: String)  -> SignalProducer<(URL: String, gistID: String), ConnectionError>

gistService.setGist(content: content!)
    .on(next: {
        app.userNotification.pushNotification(openURLAction: $0.URL) //this is an NSUserNotification
    })
    .on(error: print)
    .start()

The function uses the Gists API

import Cocoa
import ReactiveCocoa
import SwiftyJSON

enum ConnectionError: ErrorType {

    case Bad(String)
    case Worse(String)
    case Terrible(String)
}

/**
- TODO: Add OAuth2 towards GitHub as a protocol
- TODO: Make it RAC
- TODO: Store gistID in NSUserDefaults
*/
public final class GistService: NSObject {

    //MARK:- Properties
    var userDefaults: NSUserDefaults
    var gistAPIURL: NSURL
    var gistID: String?

    //MARK:- Initialisation

    override init() {
        userDefaults = NSUserDefaults.standardUserDefaults()
        gistAPIURL = NSURL(string: "https://api.github.com/gists")!
        super.init()
    }

    convenience init(apiURL: String) {
        self.init()
        self.gistAPIURL = NSURL(string: apiURL)!
    }

    //MARK:- Public API

    func resetGist() -> Bool {
        //    userDefaults.removeObjectForKey("gistID")
        self.gistID = nil

        return !gistUpdate()
    }

    func setGist(content content: String,
        isPublic: Bool = false, fileName: String = "Casted.swift") // defaults
        -> SignalProducer<(URL: String, gistID: String), ConnectionError> {

            return SignalProducer {sink, disp in

                let gitHubHTTPBody = [
                    "description": "Generated with Cast (cast.lfaoro.com)",
                    "public": isPublic,
                    "files": [fileName: ["content": content]],
                ]

                let request: NSMutableURLRequest
                if self.gistUpdate() {
                    let updateURL = NSURL(string: self.gistAPIURL.path! + self.gistID!)!
                    request = NSMutableURLRequest(URL: updateURL)
                    request.HTTPMethod = "PATCH"
                } else {
                    request = NSMutableURLRequest(URL: self.gistAPIURL)
                    request.HTTPMethod = "POST"
                    request.HTTPBody = try! JSON(gitHubHTTPBody).rawData()
                }

                let session = NSURLSession.sharedSession()
                let task = session.dataTaskWithRequest(request) { (data, response, error) in
                    if let data = data {
                        let jsonData = JSON(data: data)
                        if let url = jsonData["html_url"].string, id = jsonData["id"].string {
                            sendNext(sink, (url, id))
                            sendCompleted(sink)
                        } else {
                            sendError(sink, ConnectionError.Bad("URL or ID Invalid"))
                        }
                    } else {
                        sendError(sink, ConnectionError.Worse(error!.localizedDescription))
                    }
                }
                task.resume()
            }
    }

    //MARK:- Helper functions

    func gistUpdate() -> Bool {
        guard let _ = self.gistID else { return false }
        return true
    }
}


texts: Right way to handle, log and display exceptions

texts:
I repost my question here because it has been closed on stack overflow

This question could sound stupid but I am new to the logging, displaying and handling exceptions.
Because before I was just doing a big try catch (Exception ex) to get exceptions (test softwares)

But now I am doing a "real" software, which will have a public release.
And I am asking what is the right way of doing those things.

I am using WPF with the .NET Framework 4.7.2, and i'm also using NLog

For now, I did a little code, and I am just asking like a review / advices.
I put that code at startup, so in the app.xaml.cs with a protected override OnStartup()

using System;
using System.IO;
using System.Windows;
using WPFTemplate.Classes;
using WPFTemplate.Classes.Core;

namespace WPFTemplate {

    public partial class App : Application {

        /// <summary>
        /// Logger
        /// </summary>
        private static readonly NLog.Logger Log = NLog.LogManager.GetCurrentClassLogger();

        /// <summary>
        /// Application starting point
        /// </summary>
        protected override void OnStartup(StartupEventArgs e) {

            // ---- Application

            // -- Directory
            try {

                // Create application main directory
                Directory.CreateDirectory(Reference.AppPath);

            } catch (Exception ex) {

                // Log
                Log.Error(ex);

                // The path isn't valid/found (ex: with network name)
                if (ex is DirectoryNotFoundException || ex is IOException || ex is NotSupportedException) {
                    MessageBox.Show(string.Format("The application path '{0}' isn't valid..\nPlease check if the path is valid", Reference.AppPath), Reference.AppName, MessageBoxButton.OK, MessageBoxImage.Error);
                }
                // The user hasn't the permission to write (then need to run the application as administrator)
                else if (ex is UnauthorizedAccessException) {
                    MessageBox.Show(string.Format("The application hasn't the right to write data in the application path '{0}'..\nPlease start the application as administrator", Reference.AppPath), Reference.AppName, MessageBoxButton.OK, MessageBoxImage.Error);
                }
                // Path is too long (max: 256 chars)
                else if (ex is PathTooLongException) {
                    MessageBox.Show(string.Format("The application path '{0}' is too long..\nPlease install the application in another place", Reference.AppPath), Reference.AppName, MessageBoxButton.OK, MessageBoxImage.Error);
                }

                // Shutdown
                Application.Current.Shutdown();

            }

        }

        protected override void OnExit(ExitEventArgs e) {

            // -- Logs

            Log.Info("Stopping the application");

            NLog.LogManager.Shutdown();

        }

    }

}

I did a custom message for every exceptions, and it's a little bit long

So i'm waiting for your reviews/advices and thanks a lot i'm still a beginner in that x)


texts: Dynamically call lambda based on stream input: Try 2

texts:
Originally asked here: Dynamically call lambda based on stream input

The following version is based heavily on the answer provided by @iavr, though I hope that I have done enough more to make it worth reviewing again.

A way to clean parameters of all declarations:

template<typename Decorated>
struct CleanType
{
    typedef typename std::remove_reference<Decorated>::type     NoRefType;
    typedef typename std::remove_const<NoRefType>::type         BaseType;
};

Get Caller traits of a functor:

template <typename T>
struct CallerTraits
    : public CallerTraits<decltype(&T::operator())>
{};

template<typename C, typename ...Args>
struct CallerTraits<void (C::*)(Args...) const>
{
    static constexpr int                                        size = sizeof...(Args);
    typedef typename std::make_integer_sequence<int, size>      Sequence;
    typedef std::tuple<typename CleanType<Args>::BaseType...>   AllArgs;
};
// Notice the call to `CleanType` to get the arguments I want.
// So that I can create objects of the correct type before passing
// them to the functor:

The actual calling of the functor based on reading data from a stream (via ResultSetRow (but I am sure that can be easily generalized)).

Done in 2 parts:

This is the part you call:

template<typename Action>
void callFunctor(Action action, Detail::ResultSetRow& row)
{
    // Get information about the action.
    // And retrieve how many parameters myst be read from
    // the stream before we call `action()`
    typedef CallerTraits<decltype(action)>  Trait;
    typedef typename Trait::Sequence        Sequence;

    doCall2(action, row, Sequence());
}

Part 2:

Here we extract the parameters from the stream then call the action.

template<typename Action, int... S>
void doCall2(Action action, Detail::ResultSetRow& row, std::integer_sequence<int, S...> const&)
{
    // Create a tupple that holds all the arguments we need
    // to call the functior `action()`
    typedef CallerTraits<decltype(action)>  Trait;
    typedef typename Trait::AllArgs         ArgumentTupple;

    // Use the template parameter pack expansion
    // To read all the values from the stream.
    // And place them in the tuple.
    ArgumentTupple  arguments(row.getValue1<typename std::tuple_element<S, ArgumentTupple>::type>()...);

    // Use the template parameter pack expansion
    // To call the function expanding the tupple into
    // individual parameters.
    action(std::get<S>(arguments)...);
}

Example usage:

// Using `ResultRowSet` from below.
int main()
{
    std::stringstream    stream("1 Loki 12.3 2.2");
    Detail::ResultRowSet row(stream);
    callFunctor([](int ID, std::string const& person, double item1, float item2){
        std::cout << "Got Row:"
                  << ID     << ", "
                  << person << ", "
                  << item1  << ", "
                  << item2  << "\n";
    }, row);
}

Here it will read an int (ID), a std::string (person) a double (item1) and a float (item2) from the stream (represented by row), then call the lambda provided.

This is not the actual implementation of Detail::ResultSetRow. But for code review purposes you can think of it as:

namespace Detail
{
    class ResultRowSet
    {
        std::istream&   stream;

        public:
            ResultRowSet(std::istream& s)
                : stream(s)
            {}
            template<typename T>
            T getValue1()
            {
                  T  val;
                  stream >> val;
                  return val;
            }
    };
}


texts:
Can anyone suggest any improvements?  I already applied here the suggestions that was made for my first program (Guess the Number) that I posted.

import java.util.Scanner;

public class Temp { // convertion of fahrenheit to celcius and vise versa

    public static void main(String[] args) {
        double celcius, fahrenheit;
        Scanner in = new Scanner(System.in);

        System.out.print("Enter the value of temperature in degree celcius: ");
        celcius = in.nextDouble();
        fahrenheit = celcius * 9 / 5 + 32; // convertion formula for celcius to fahrenheit
        System.out.printf(celcius+" °C = %.1f °F\n", fahrenheit);

        System.out.print("Now enter the value of temperature in degree fahrenheit: ");
        fahrenheit = in.nextDouble();
        celcius = (fahrenheit - 32) * 5 / 9; // formula of fahrenheit to celcius
        System.out.printf(fahrenheit +" °F = %.1f °C\n", celcius);
    }
}


texts:
I'm doing a hacker rank challenge with this one called "Repeated String". I attempted this challenge in my weaker language java. The goal is to print out the occurrences of the letter a. First you're given a string "aba" then a number 10. The new string generated would be abaabaabaa and you need to count the a. The solution below works but is it as simple as it should be? I've looked around and my solution looks good but still I'm terrified I'm over complicating this.

// Complete the repeatedString function below.
static long repeatedString(String s, long n) {
    final long quotient = n/s.length();
    final long remainder = n%s.length();
    long aCount = 0;

    if((s.length() == 1) && (s.charAt(0) == 'a')){
        return n;
    }
    for(int i=0; i<s.length(); i++){
        if(s.charAt(i) == 'a'){
            aCount++;
        }
    }
    aCount = aCount * quotient;
    for(int i=0; i<remainder; i++){
        if(s.charAt(i) == 'a'){
            aCount++;
        }
    }
    return aCount;
}


texts: Producing a matrix class that supports any size

texts:
I'm doing exercise 11.8 from Scala for impatient, asking to write a matrix class:

  Provide a class Matrix - you can choose whether you want to implement 2
  x 2 matrices, square matrices of any size, or m x n matrices. Supply operations + and *. The latter should also work with scalars, for example mat * 2. A single element should be accessible as mat(row, col).

The code is working, but may be there can be improvements to make code more functional or more stable:

class Matrix(val n: Int, val m: Int, fun: (Int, Int) => Double) {
  private val matrix = Array.tabulate[Double](n,m)(fun)

  def +(another: Matrix) = {
    if (n != another.n || m != another.m)
      throw new IllegalArgumentException("Sizes of arrays don't match.")
    else
      new Matrix(n, m, (i, j) => this(i)(j) + another(i)(j))
  }
  def *(another: Matrix) = {
    if (m != another.n)
      throw new IllegalArgumentException("Sizes of arrays don't match.")
    else
      new Matrix(n, another.m, (i,j) => { var sum = 0.0;
                                          for (k <- matrix(i).indices) sum += matrix(i)(k) * another(k)(j);
                                          sum }
      )
  }
  def *(k: Int) = new Matrix(n, m, k * matrix(_)(_) )

  def apply(i: Int)(j: Int) = matrix(i)(j)

  override def toString = {
    var result = ""
    for (row <- matrix) {
      for (value <- row)
        result += value + "  "

      result += "\n"
    }
    result
  }
}


texts:
I'm relatively new to programming, but am really enjoying it. I have taken a couple of classes but mostly code for fun (for now). I decided to make a program implementing some basic functions, switch statements, and user input. Please leave any feedback on how to make this program better.

I understand that I am not actually using the defined functions (add, subtract, etc.), but I put them in there with the intent of using them, I just don't know how.

#include <iostream>
using namespace std;

int add (int x, int y){
return x+y;
};

int divide (int x, int y){
return x/y;
}

int multiply (int x, int y){
return x*y;
}

int subtract (int x, int y){
return x-y;
}

int main(){

int n1;
int n2;
int user14 = 0;

SomeLine:
cout << "Enter your 2 numbers: "<< endl;
cin >> n1;
cin >> n2;

cout << "Ok, now what do you want to do with those numbers? "<< endl;

cout << "1) Add: " << endl;
cout << "2) Divide: "<<endl;
cout << "3) Multiply: "<< endl;
cout << "4) Subtration: "<< endl;

cin >> user14;

switch (user14)
{
    case 1:
    cout << n1+n2 << endl;
        break;
    case 2:
    cout << n1/n2 << endl;
        break;
    case 3:
    cout << n1*n2<< endl;
        break;
    case 4:
    cout << n1-n2 << endl;
        break;

}

char userchoice;
cout << "Would you like to perform any other operations? y/n "<< endl;

cin >> userchoice;

if (userchoice=='y'){
    goto SomeLine;
}
else if(userchoice=='n'){
    goto Exit;
}

Exit:
return 0;

};


texts:
Purpose

I wanted to try and implement a very basic Singly Linked List as a data structure exercise.

Implementation Discussion

I know that the Java LinkedList API is quite
extensive. However, in this basic implementation, I just wanted to implement the addAtIndex, removeAtIndex, and
get methods (with the add and remove methods delegating to the addAtIndex and removeAtIndex methods).

Things that I could improve

For the addAtIndex and removeAtIndex methods I special-case when the index is 0 - is there a more elegant solution?
Do the exceptions make sense?

For the remove method should I check to see if the list is empty and then throw an
IllegalStateException before calling the removeAtIndex method? Same thing for the get method?
Should I replace the IllegalArgumentExceptions with IndexOutOfBoundExceptions?

Implementation

import java.util.Objects;

public class SinglyLinkedList<T> {

    public static class Node<E> {
        private final E data;
        private Node<E> next;

        public Node(E data, Node<E> next) {
            this.data = data;
            this.next = next;
        }

        public E getData() {
            return this.data;
        }

        public Node<E> getNext() {
            return this.next;
        }

        public void setNext(Node<E> next) {
            this.next = next;
        }

        @Override
        public int hashCode() {
            return Objects.hash(this.data, this.next);
        }

        @Override
        public boolean equals(Object obj) {
            if (obj == this) {
                return true;
            }

            if (!(obj instanceof Node)) {
                return false;
            }

            Node node = (Node) obj;

            return Objects.equals(this.data, node.data) &&
                    Objects.equals(this.next, node.next);
        }
    }

    private Node<T> head = null;
    private int size = 0;

    public SinglyLinkedList() {
    }

    public int getSize() {
        return this.size;
    }

    public boolean isEmpty() {
        return this.getSize() == 0;
    }

    public Node<T> getHead() {
        return this.head;
    }

    public void add(T data) {
        this.addAtIndex(data, this.size);
    }

    public void remove() {
        this.removeAtIndex(this.size - 1);
    }

    public void addAtIndex(T data, int index) {
        if (index > this.size || index < 0) {
            throw new IllegalArgumentException("Invalid index value");
        }

        Node<T> currentNode = this.head;

        if (index == 0) {
            this.head = new Node<>(data, currentNode);
        } else {
            for (int i = 0; i < index - 1; i++) {
                currentNode = currentNode.getNext();
            }

            Node<T> nextNode = new Node<>(data, currentNode.getNext());
            currentNode.setNext(nextNode);
        }

        this.size++;
    }

    public void removeAtIndex(int index) {
        if (index < 0 || index >= this.size) {
            throw new IllegalArgumentException("Invalid index value");
        }

        Node<T> currentNode = this.head;

        if (index == 0) {
            this.head = currentNode.getNext();
        } else {
            for (int i = 0; i < index - 1; i++) {
                currentNode = currentNode.getNext();
            }

            currentNode.setNext(currentNode.getNext().getNext());
        }

        this.size--;
    }

    public T get(int index) {
        if (index < 0 || index >= this.size) {
            throw new IllegalArgumentException("Invalid index value");
        }

        Node<T> currentNode = this.head;

        int count = 0;
        while (count < index) {
            currentNode = currentNode.getNext();
            count++;
        }

        return currentNode.getData();
    }

}


texts:
The original question can be seen here: Stack implementation in C++ using linked list

Changes (with the help of Martin):

Added copy constructor and assignment operator overload
Changed return type of peek() to const T& rather than T (this prevents unnecessary copying of data)
Changed return type of pop() to void; it now only removes the top item rather than returning it on top. The user can call peek() and then call pop() to retrieve and then delete the item. This means we don't have to return T by value, and also maintains the "Strong Exception Guarantee".
Fixed a bug in pop() where the new head is deleted rather than the old one

#ifndef TEST_STACK_H
#define TEST_STACK_H

#include <stdexcept>

template <class T>
class stack {

    struct node {
        T data;
        node* previous;

        node(T data, node *previous) : data(data), previous(previous) {}
    };

    node* head = nullptr;

    int size = 0;
    int max = -1; // -1 so isFull() == false when default constructor used

public:
    stack() = default;

    stack(int max) {
        if (max <= 0) throw std::out_of_range("stack size must be > 0");
        this->max = max;
    }

    // copy constructor

    stack(stack const& rhs) :
        head(copyList(rhs.head)),
        size(rhs.size),
        max(rhs.size) {}

    // assignment operator

    stack& operator = (stack const& rhs)
    {
        stack tmp(rhs);
        swap(tmp);

        return *this;
    }

    ~stack() {
        node* n = head;

        while (n != nullptr) {
            node* previous = n->previous;
            delete n;

            n = previous;
        }
    }

    void push(const T &object) {
        if (isFull()) throw std::overflow_error("cannot push to a full stack");

        head = new node(object, head);
        ++size;
    }

    const void pop() {
        if (head == nullptr) throw std::underflow_error("cannot get item from empty stack");

        node* old = head;
        head = head->previous;

        --size;
        delete old;
    }

    T peek() {
        if (head == nullptr) throw std::underflow_error("cannot get item from empty stack");
        return head->data;
    }

    int getSize() {
        return size;
    }

    bool isFull() {
        return size == max;
    }

    bool isEmpty() {
        return head == nullptr;
    }

    void swap(stack& other) noexcept
    {
        using std::swap;
        swap(head, other.head);
        swap(size, other.size);
        swap(max,  other.max);
    }

private:
    node* copyList(node* l)
    {
        if (l == nullptr) {
            return nullptr;
        }
        return new node{l->data, copyList(l->previous)};
    }
};

#endif


texts: Optimizing solution of Sum of Pairs: Codewars in Python

texts:
I need help to optimize my code for huge lists with approx. 10000000 elements. Is there a way to improve my algorithm or should I try to build a new one using a completely different approach?
Task: given a list of integers and a single sum value, return the first two values (parse from the left please) in order of appearance that add up to form the sum.
def sum_pairs(ints, s):
    lst1 = []
    for n in ints:
        if n in lst1:
            return [s-n, n]
        lst1.append(s-n)

lst3 = list(range(1,10000000))

sum_pairs(lst3, 20000000)

*Times out :(

#Using set() every time we add new item to the list doesn't help

def sum_pairs(ints, s):
    lst1 = []
    for n in ints:
        lst2 = set(lst1)
        if n in lst2:
            return[s-n, n]
        lst1.append(s-n)


texts:
As I understand it, blowfish (actually eksblowfish, as it's used one way) is generally seen a secure hashing algorithm, even for enterprise use (correct me if I'm wrong). Because of this, I created functions to create and check secure password hashes using this algorithm, and using the (also deemed cryptographically secure) openssl_random_pseudo_bytes function to generate the salt.

<?php
/*
 * Generate a secure hash for a given password. The cost is passed
 * to the blowfish algorithm. Check the PHP manual page for crypt to
 * find more information about this setting. Returns null on failure.
 */
function generate_hash($password, $cost=11){
    /* To generate the salt, first generate enough random bytes. Because
     * base64 returns one character for each 6 bits, the we should generate
     * at least 22*6/8=16.5 bytes, so we generate 17. Then we get the first
     * 22 base64 characters
     */
    $salt=substr(base64_encode(openssl_random_pseudo_bytes(17,$secure)),0,22);
    /* If the random generation was not secure enough, do not continue
     */
    if(!$secure) return null;
    /* As blowfish takes a salt with the alphabet ./A-Za-z0-9 we have to
     * replace any '+' in the base64 string with '.'. We don't have to do
     * anything about the '=', as this only occurs when the b64 string is
     * padded, which is always after the first 22 characters.
     */
    $salt=str_replace("+",".",$salt);
    /* Next, create a string that will be passed to crypt, containing all
     * of the settings, separated by dollar signs
     */
    $param='$'.implode('$',array(
            "2y", //select the most secure version of blowfish (>=PHP 5.3.7)
            str_pad($cost,2,"0",STR_PAD_LEFT), //add the cost in two digits
            $salt //add the salt
    ));

    /* Now do the actual hashing
     */
    $hash=crypt($password,$param);
    if(strlen($hash)!=60) return null;
    return $hash;
}

/*
 * Check the password against a hash generated by the generate_hash
 * function.
 */
function validate_pw($password, $hash){
    /* Regenerating the with an available hash as the options parameter should
     * produce the same hash if the same password is passed.
     */
    return crypt($password, $hash)===$hash;
}
?>


texts:
I am currently working on a Python 3.4.3 project which includes solving the Traveling Salesman Problem using different algorithms. I have just written a brute force algorithm and I would love some feedback. Now I understand that the number of operations increases by the factorial of the route length so brute forcing is not considered feasible, but for my project I need a standard brute force.

My overarching question is: How can I make this as fast and efficient as possible?

import itertools

def distance(p1, p2):
        #calculates distance from two points
        d = (((p2[0] - p1[0])**2) + ((p2[1] - p1[1])**2))**.5
        return int(d)

def calCosts(routes, nodes):
    travelCosts = []

    for route in routes:
        travelCost = 0

        #Sums up the travel cost
        for i in range(1,len(route)):
            #takes an element of route, uses it to find the corresponding coords and calculates the distance
            travelCost += distance(nodes[str(route[i-1])], nodes[str(route[i])])

        travelCosts.append(travelCost)

    #pulls out the smallest travel cost
    smallestCost = min(travelCosts)
    shortest = (routes[travelCosts.index(smallestCost)], smallestCost)

    #returns tuple of the route and its cost
    return shortest

def genRoutes(routeLength):
    #lang hold all the 'alphabet' of nodes
    lang = [ x for x in range(2,routeLength+1) ]

    #uses built-in itertools to generate permutations
    routes = list(map(list, itertools.permutations(lang)))
    #inserts the home city, must be the first city in every route
    for x in routes:
        x.insert(0,1)
    return routes

def main(nodes=None, instanceSize=5):
    #nodes and instanceSize are passed into main() using another program
    #I just gave them default values for this example

    #The Node lookup table.
    Nodes = {
        '1': (565.0, 575.0),
        '2': (25.0, 185.0),
        '3': (345.0, 750.0),
        '4': (945.0, 685.0),
        '5': (845.0, 655.0),
        '6': (880.0, 660.0),
        '7': (25.0, 230.0),
        '8': (525.0, 1000.0),
        '9': (580.0, 1175.0),
        '10': (650.0, 1130.0),
        '11': (1605.0, 620.0),
        '12': (1220.0, 580.0),
        '13': (1465.0, 200.0),
        '14': (1530.0, 5.0),
        '15': (845.0, 680.0)
    }

    routes = genRoutes(instanceSize)
    shortest = calCosts(routes, Nodes)

    print("Shortest Route: ", shortest[0])
    print("Travel Cost: ", shortest[1])

if __name__ == '__main__':
    main()


texts: Showing Or Hiding AdMob Banners - Purchased vs Not-Purchased IAP Banner Non-Consumable

texts:
I have the following code that displays a standard AdMob banner depending on whether the user has purchased an ad-free (banner-free) non-consumable In-App Purchase or not (i.e. If purchased, no banners)

UITableViewController - static cells (1 section, X no of rows):

import UIKit
import GoogleMobileAds

class WorkoutForehead1Exercise1TVC: UITableViewController, GADBannerViewDelegate {

    let defaults = NSUserDefaults.standardUserDefaults()
    var product_id: NSString?;

    var banner : GADBannerView!

override func viewDidLoad() {
    super.viewDidLoad()

    product_id = "someFunkyProductName.FullAccess";

    //Check if product is purchased
    if (defaults.boolForKey("purchased"))

    { print("User has purchased ad-free experience") }

    else

    { print("User has not purchased - load banner");

        loadBanner()
    }

}

func loadBanner(){
    banner = GADBannerView(adSize: kGADAdSizeSmartBannerPortrait)
    banner.adUnitID = "ca-app-pub-xxxxxx/xxxxxx"
    banner.rootViewController = self
    let req : GADRequest = GADRequest()

    let request = GADRequest()
    request.testDevices = ["dcf33ab873fb56fdf5ff94bd7a5f3fde", "cd6c1283ff903813bc128342d61521bf"]

    banner.loadRequest(req)
    banner.frame = CGRectMake(0, view.bounds.height - banner.frame.size.height, banner.frame.size.width, banner.frame.size.height)
    self.view.addSubview(banner)
}

I have also added a modification to relative TableView cell heights depending on whether the banner (dimensions 320x50) is shown or otherwise. Essentially, I want Row 0 to return 4 pixel height and Row 2 to return 70 pixel height, and Row 1 ("filmstrip") to be variable and fill the rest of the visible screen.

// Shrink or increase flimstrip height depending on show banner = true/false:
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {

    if (!defaults.boolForKey("purchased")) {

        print("show banner, reduce filmstrip");
        var height: CGFloat = 0
        switch indexPath.row {
        case 0: height = 4
        case 2: height = 70
        default: height = tableView.frame.size.height - 219
        }
        return height }

        else {

        print("hide banner, increase filmstrip");
        var height: CGFloat = 0
        switch indexPath.row {
        case 0: height = 4
        case 2: height = 70
        default: height = tableView.frame.size.height - 169
        }
        return height
        }
    }

Everything seems to run perfectly well in a physical device simulator, but I have the following questions:

Can my code be 'neater' or more efficient?
Do I need to handle GADBannerViewDelegate protocol's optional -  adViewDidReceiveAd and didFailToReceiveAdWithError methods? As per Apple app-approval requirements?


texts: Python code to find greatest common divisor of multiple numbers

texts:
Hmm, I know this has been implemented countless times, and Python 3.9.5 math standard library has a built-in gcd() method that does exactly this, but this is how I do this, I think completing simple programming challenges using new ways will let gain experience that will help me find ingenious ways to overcome unprecedented practical programming challenges, so bear with me.
This implementation uses prime factorization method, it has three functions: factors(), gcd() and main(), the first function returns a dictionary object, the keys of the dictionary are the base prime factors of the inputted number, the values are the powers (how many times the factor should multiply by itself) of the keys, the dictionaries are created with one key{'1': 1};
And the second function accepts two numbers, uses each number as inputs to the first function, the compares the resultant dictionaries, removes keys of the first dictionary not contained in the second dictionary, and reduces the values of keys of the first dictionary to their respective values in the second dictionary if their values in first dictionary is greater than the second dictionary.
Then the second function gets the product of all keys ^ values of the first dictionary.
The third function applies gcd() recursively to the list of numbers if there are more than two numbers.
This is the code, it is fully functional, and works properly if the inputs are valid:
import math
import sys

def factors(n):
    factors = {'1': 1}
    f = 2
    while f <= int(math.sqrt(n)):
        while n % f == 0:
            if f'{f}' in factors.keys():
                factors.update({f'{f}': factors[f'{f}'] + 1})
            else:
                factors[f'{f}'] = 1
            n = int(n / f)
        f += 1
    if n > 1: factors[f'{n}'] = 1
    return factors

def gcd(x, y):
    f1 = factors(x)
    f2 = factors(y)
    for f in f1.copy().keys():
        if f not in f2.keys():
            f1.pop(f)
        elif f1[f] > f2[f]:
            f1[f'{f}'] = f2[f]
    cd = 1
    for f in f1.keys():
        cd *= int(f) ** f1[f]
    return cd

def main(args):
    args = list(map(int, args))
    cd = gcd(args[0], args[1])
    if len(args) > 2:
        for i in args[2:]:
            cd = gcd(cd, i)
    print(cd)

args = sys.argv[1:]
main(args)

Currently I think two areas need be improved:
1, I need a better way than dictionaries to keep track of the divisors, so that I can easily find divisors not contained in the other number and find the lower power of the same divisor.
2, make the gcd() function do what main() function does internally so that the main() function isn't needed, currently I can't figure out a way to do this.
How can this script be improved?


texts:
It took me a lot of poking around and unit testing to get the code to look like it is right now. So I have a XML file which in part looks like this

<FunctionKeys>
    <Name>F13</Name>
    <Name>F14</Name>
    <Name>F15</Name>
    <Name>F16</Name>
</FunctionKeys>

and So I want to take that data and put it back into my class.

This is in part what I have

    public override void Load(string elementText)
    {
        var ele = XElement.Parse(elementText);
        if (ele.Element("FunctionKeys").HasElements)
        {
            var funcs = ele.Element("FunctionKeys")
                .Descendants("Name")
                .Select(x=>x.Value)
                .ToList();

            foreach (string s in funcs)
            {
                dliUnit.FunctionKeyList.Add(
                    (System.Windows.Forms.Keys)System.Enum.Parse(typeof(System.Windows.Forms.Keys),
                    s));
            }
        }
    }

Class to save to

public class DLIUnit
{
    public List<Keys> FunctionKeyList
    {
        get;set;
    }
    //Other Members
}

Somethign about the way that I parse the string back to the Enum (well the entire process really) doesn't sit well with me. I'm very bad at LINQ but have been trying hard to learn it and use it more and more when I play with XML. Is there a better/cleaner way to parse the FunctionKeys?

EDIT

I forgot to mention that I can change any portion of the code or XML file. Right now this is a new idea and can be changed to make it better.


texts:
Is there any way I could improve this script, such as by writing it in fewer lines (more efficient)? I'm very interested in keeping my code dry and fast! Also, if there is a way to make it more dynamic don't hesitate to tell me!

  <?php
    /* Connect to an MYSQL database Using credentials and PDO(PHP DATA OBJECT) */
    $dsn = 'mysql:host=**;dbname=**';
    $user = '**';
    $password = '**';
    $connection = new PDO($dsn, $user, $password);
    $table = $_POST['table'];
    $querySQL = "";
    $datum = $_POST['datum'];

    //SELECT content,author FROM quote LIMIT 10
    //INSERT INTO birthday (date,name) VALUES ('2012-05-05','henk')

    switch ($table) {
        case "quote":
            $querySQL = "SELECT content,author FROM quote WHERE datum = ? LIMIT 10";
            $stmt = $connection->prepare($querySQL);
            $stmt->execute(array($datum));
            break;
        case "birthday":
            $querySQL = "SELECT date,name FROM birthday LIMIT 10 WHERE datum = ? LIMIT 10";
            $stmt = $connection->prepare($querySQL);
            $stmt->execute(array($datum));
            break;
        case "facts":
            $querySQL = "SELECT content from facts WHERE datum = ? AND category = ? LIMIT 10";
            $categorie = $_POST['categorie'];
            $stmt = $connection->prepare($querySQL);
            $stmt->execute(array($datum, $categorie));
            break;
        case "lifehacks":
            $querySQL = "SELECT content from lifehacks WHERE datum = ? LIMIT 10";
            $stmt = $connection->prepare($querySQL);
            $stmt->execute(array($datum));
            break;
    }
    if(isset($stmt)) {
        $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
        $json = json_encode($results);
        echo $json;
    }
    ?>


texts:
I am using a std::priority_queue to implement Dijkstra's algorithm:

while(!Q.empty())
{
    u = Q.top().first;
    Q.pop();
    int size=G[u].size();
    for(int i=0; i<size; i++)//tle
    {
        v = G[u][i].first;
        w = G[u][i].second;
        //cout<<u<<" "<<v<<" "<<w<<endl;
        if(d[v] > d[u] + w)
        {
            d[v] = d[u] + w;
            Q.push(pp(v,d[v]));

        }
    }
}

But I think it is a bit slow for competitive programming (\$O(e + v*v)\$).  How can I improve my implementation?


texts:
Learn You a Haskell offers the findKey function:

Here's the book's implementation:

findKey :: (Eq k) => k -> [(k,v)] -> v
findKey key xs = snd . head . filter (\(k,v) -> key == k) $ xs

I implemented it with $:

findKey' :: (Eq k) => k -> [(k,v)] -> v
findKey' k xs = snd $ head $ filter ((== k) . fst) xs

As far as I can tell, it's a stylistic choice here to select . over $?

Lastly, is there a way to write findKey such that the [(k,v)] is curried & thus not required in the signature of findKey key xs?


texts:
I am in the process of learning basic C++ and one of the practice questions I came across was to write a function to open a file in C++.

I did understand how to use the streams but I think I went overboard a little bit by making sure that it works. I would appreciate any feedback on my code. The objective was also to keep prompting the user to open a file if it doesn't work in the first go.

Code:

void OpenFile(std::ifstream& inputFileStream) {
    while(true) {
        inputFileStream.clear();
        std::stringstream fileNameStream;
        std::string fileName;
        std::cout << "Enter the file name to open: ";
        if(!getline(std::cin, fileName)) {
            std::cout << "Please enter a valid name." << std::endl;
        } else {
            fileNameStream << fileName;
            std::string fileToOpen;
            std::string remaining;
            if(fileNameStream >> fileToOpen) {
                if(fileNameStream >> remaining) {
                    std::cout << "Unexpected character: " << remaining << std::endl;
                } else {
                    inputFileStream.open(fileToOpen.c_str());
                    if (!inputFileStream.is_open()) {
                        std::cout << "File could not be opened. Please try again.";
                        std::cout << std::endl;
                    } else {
                        break;
                    }
                }
            }
        }
    }
}


texts: Script to remove .vb files from a directory

texts:
I wrote a script to remove .vb code files when there are corresponding .cs files in a certain directory structure.  But I felt like there were some extra statements that I had to put in there that didn't feel natural.  Is there a better way to do this check and then action?

Specifically, having to do the foreach at the end didn't seem right to me.  I also didn't know if there was a more PowerShell-y way to do the change extension and test-path.

ls . -include *.vb -recurse
    | ? { $cs = [System.IO.Path]::ChangeExtension($_.FullName, ".cs"); Test-Path $cs }
    | % { rm $_ -force }


texts: C# basic dictionary (hash) implementation

texts:
I have implemented a very basic hash data structure with basic set/retrieve methods.
A good example of use of this implementation would be a phone-book.
I have used as underneath storage structure an array consisting of linked lists.

Please a code review within these requirements.

public class MyHash
{
    private LinkedList<string>[] storage;

    public MyHash()
    {
        storage = new LinkedList<string>[26]; //english alphabet
    }

    private int HashFunction(string key)
    {
        //maps first character of name to a 0:25 index
        return key.ToLower().ToCharArray()[0] - 97;
    }

    public string this[string key]
    {
        get {
            var list = storage[HashFunction(key)];
            if (list != null)
            {
                foreach (var item in list)
                {
                    if (item.Split(':')[0] == key)
                        return item.Split(':')[1];
                }
            }
            return "Not found!";
        }
        set {
            if (storage[HashFunction(key)] == null)
                storage[HashFunction(key)] = new LinkedList<string>();
            storage[HashFunction(key)].AddLast(key + ":" + value);
        }
    }
}


texts: Factory to construct a FineTime out of many kinds of objects

texts:
Any suggestions to help refactor this method? I thought maybe some kind of factory to allocate the right type?

public static FineTime getFineTime(Object o) {
    if (o == null) {
        return null;
    }
    //FineTime
    if (o instanceof FineTime) {
        return (FineTime ) o;
    }
    //Long
    if (o instanceof Long) {
        return new FineTime((Long ) o);
    }
    //Int
    if (o instanceof Integer) {
        return new FineTime((Integer ) o);
    }
    //Date
    if (o instanceof Date) {
        try {
            return DateConverter.dateToFineTime((Date ) o);
        } catch (IllegalArgumentException iae) {
            //Try another converter
            LOGGER.log(Level.FINE, "DateConverter.dateToFineTime(Date) failed", iae);
        }
    }
    //String
    if (o instanceof String) {
        String date = (String ) o;
        //TAI
        try {
            return _stfFormatTai.parse(date);
        } catch (IllegalArgumentException iae) {
            //Try another converter
            LOGGER.log(Level.FINE, "_stfFormatTai.parse(String) failed", iae);
        }
        //UTC
        try {
            return _stfFormatUtc.parse(date);
        } catch (IllegalArgumentException iae) {
            //Try another converter
            LOGGER.log(Level.FINE, "_stfFormatUtc.parse(String) failed", iae);
        }
        //dd-MMM-yyyy HH:mm:ss
        try {
            return DateConverter.dateToFineTime(_sdfFormat1.parse(date));
        } catch (ParseException pe) {
            //Try another converter
            LOGGER.log(Level.FINE, "DateConverter.dateToFineTime(_sdfFormat1.parse(String) failed", pe);
        } catch (IllegalArgumentException iae) {
            //Try another converter
            LOGGER.log(Level.FINE, "DateConverter.dateToFineTime(_sdfFormat1.parse(String) failed", iae);
        }
        //dd-MM-yyyy HH:mm:ss
        try {
            return DateConverter.dateToFineTime(_sdfFormat2.parse(date));
        } catch (ParseException pe) {
            //Try another coverter
            LOGGER.log(Level.FINE, "DateConverter.dateToFineTime(_sdfFormat2.parse(String) failed", pe);
        } catch (IllegalArgumentException iae) {
            //Try another converter
            LOGGER.log(Level.FINE, "DateConverter.dateToFineTime(_sdfFormat2.parse(String) failed", iae);
        }
    }
    LOGGER.info("Could not convert " + StringUtil.asString(o) + " to FineTime");
    //No converter found, return 'null'
    return null;
}


texts: Async Log4net logging handler - High CPU usage on async call

texts:
I've got a LoggingMessageHandler that incoming requests on my WebApi application filter through.

public class LoggingMessageHandler : DelegatingHandler
{
    public ILogManager LogManager { get; set; } //injected

    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
    {
        var logger = SetupLogger(request);

        var correlationId = request.GetCorrelationId().ToString();

        var requestInfo = await LogRequest(request, logger, correlationId);

        var response = await base.SendAsync(request, cancellationToken);

        await LogResponse(response, logger, correlationId, requestInfo);

        response.Headers.Add("X-Correlation-Id", correlationId);

        return response;
    }

    private ILogger SetupLogger(HttpRequestMessage request)
    {
        var loggerName = request.RequestUri.AbsolutePath.Replace("/", "-");
        var logger = LogManager.GetLogger(loggerName);
        return logger;
    }

    private async Task<string> LogRequest(HttpRequestMessage request, ILogger logger, string correlationId)
    {
        var requestInfo = string.Format("{0} {1}", request.Method, request.RequestUri);

        var requestMessage = "";

        if (request.Content != null)
            requestMessage = await request.Content.ReadAsStringAsync();

        await LogMessageAsync(logger, "Request", correlationId, requestInfo, requestMessage);
        return requestInfo;
    }

    private async Task LogResponse(HttpResponseMessage response, ILogger logger, string correlationId, string requestInfo)
    {
        var responseMessage = string.Empty;

        if (response.IsSuccessStatusCode)
        {
            if (response.Content != null)
                responseMessage = await response.Content.ReadAsStringAsync();
        }
        else
            responseMessage = response.ReasonPhrase;

        await LogMessageAsync(logger, "Response", correlationId, requestInfo, responseMessage);
    }

    private async Task LogMessageAsync(ILogger logger, string type, string correlationId, string requestInfo, string body)
    {
        await Task.Run(() => logger.Info("{0} - {1} - API - {2}: \r\n{3}", correlationId, requestInfo, type, body));
    }
}

When I run ANTS profiler, and test my application, > 70% of the CPU time is spent on this one line:

await Task.Run(() => logger.Info("{0} - {1} - API - {2}: \r\n{3}", correlationId, requestInfo, type, body));

Is that expected?

Am I doing something wrong?


texts:
The zlib library is a venerable piece of C software. The copyright for the decompression routine goes back to 1995, with the last rewrite in 2002. It is used daily by millions.

To be perfect, the decompression routine should not invoke undefined behavior, even if passed a maliciously crafted buffer. I have the opportunity to detect a number of places where it is not obvious that the library does not invoke undefined behavior on some input. Would users of this site help me in confirming these issues? We would improve an already great piece of Open Source software, and there is always something to learn in reading code that has passed the test of time.

Assuming this is okay, for my first post, I would like to suggest looking at function inflate() in version 1.2.7 of the library.

int ZEXPORT inflate(strm, flush)
z_streamp strm;
int flush;
{
    struct inflate_state FAR *state;
    state = (struct inflate_state FAR *)strm->state;
/*** strm->state was previously allocated with malloc(), apparently.
Function malloc(), when it succeeds,
returns an uninitialized block of memory. */
...
    for (;;)
        switch (state->mode) {
...
        case MATCH:
            if (left == 0) goto inf_leave;
            copy = out - left;
            if (state->offset > copy) {         /* copy from window */
/*** It is unclear if state->offset always contains initialized contents
at this point, line 1125 in inflate.c.
*/
...

So my question is, is it possible to reach line 1125 in inflate.c without having initialized state->offset?

I linked the library with the following main() function to identify the possible issue, so I guess that an input vector, if one exists, could be based on this main(), simply initializing array in[] to values that cause the issue. This main() is using the library correctly, I hope, otherwise the flagged issue may be meaningless.

#include "zlib.h"

#define CHUNK 100

z_stream strm;
unsigned char in[CHUNK];
unsigned char out[CHUNK];
int ret;

main(){
  int i;

  /* allocate inflate state */
  strm.zalloc = Z_NULL;
  strm.zfree = Z_NULL;
  strm.opaque = Z_NULL;
  strm.avail_in = 0;
  strm.next_in = Z_NULL;
  ret = inflateInit(&strm);
  if (ret != Z_OK)
    return ret;

  for (i=0; i<CHUNK; i++)
    in[i] = any();

  strm.next_in = in;
  strm.avail_in = CHUNK;
  strm.next_out = out;
  strm.avail_out = CHUNK;

  ret = inflate(&strm, Z_NO_FLUSH);
}

Of course, if the apparently dangerous access at line 1125 is in fact safe, then a great answer would be an explanation why.


texts: Cryptopals first challenge - hexadecimal to base64

texts:
I've just started the cryptopals-challenge, and now wanted to show my solution to the first challenge here:

public class Challenge1_1 {

    public static void main(String[] args) {
        String hex = "49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d";
        String base64 = hextobase64(hex);
        System.out.println(base64);
        String test = "SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t";
        boolean t = base64.equals(test);
        System.out.println(t);
    }

    public static String hextobase64(String hex) {

        String[] hex_array = new String[hex.length()/2];

        //Splits up the hex String into substring with length 2
        for(int i = 0; i < hex_array.length; i++) {
            int x = 2 * i;
            int y = x + 2;
            hex_array[i] = substring(hex, x, y);
        }

        //Conversion to binary system
        String binary = "";
        String bin = "";
        for(int i = 0; i < hex_array.length; i++) {
            bin = conversion(hex_array[i]);
            while(bin.length()<8){
                bin = "0" + bin;
            }
            binary = binary + bin;
        }

        //Split up to strings of length 6
        String[] binary6 = new String[binary.length()/6];
        for(int i = 0; i < binary6.length; i++) {
            int x = i * 6;
            int y = x + 6;
            binary6[i] = substring(binary, x, y);
        }

        //Conversion to base64
        String out = "";
        String character = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
        String[] base64 = {
                "000000", "000001", "000010", "000011", "000100", "000101", "000110", "000111", "001000", "001001", "001010", "001011", "001100", "001101", "001110", "001111",
                "010000", "010001", "010010", "010011", "010100", "010101", "010110", "010111", "011000", "011001", "011010", "011011", "011100", "011101", "011110", "011111",
                "100000", "100001", "100010", "100011", "100100", "100101", "100110", "100111", "101000", "101001", "101010", "101011", "101100", "101101", "101110", "101111",
                "110000", "110001", "110010", "110011", "110100", "110101", "110110", "110111", "111000", "111001", "111010", "111011", "111100", "111101", "111110", "111111"
        };
        for(int i = 0; i < binary6.length; i++) {
            for(int j = 0; j < base64.length; j++) {
                if(binary6[i].equals(base64[j])){
                    out = out + character.charAt(j);
                }
            }
        }
        return(out);
    }

    public static String conversion(String hex) {
        //hex-system to decimal system
        String hex_numbers = "0123456789ABCDEF";
        hex = hex.toUpperCase();
        int value = 0;
        for (int i = 0; i < hex.length(); i++)
        {
            int d = hex_numbers.indexOf(hex.charAt(i));
            value = 16*value + d;
        }

        //decimal to binary
        String out = "";
        while(value != 0){
            int mod = value%2;
            String m = mod + "";
            value = value/2;
            out = m + out;

        }
        return out;

    }

    public static String substring(String str, int start, int end) {

        String out = "";
        if (start > end) {
            return out;
        }

        if (start < 0) {
            start = 0;
        }

        if (end > str.length() - 1) {
            end = str.length();
        }

        while (start < end) {
            out = out + str.charAt(start);
            start = start + 1;
        }

        return out;

    }
}

I've tried to all do it manually instead of using some kind of java-package.
I would appreciate any suggestions to improve the code.


texts: Removing key/value pairs in list of dicts

texts:
I have a list of dicts that all have the same keys. If a key's value is None in all dicts then I want to remove them (A solution that creates a new dict is fine as well).

I'm concerned about my Big O complexity of 2n2 (correct me if I'm wrong). Are there better solutions to what I have below?

dicts = [{'a': 1, 'b': None, 'c': 4},
         {'a': 2, 'b': None, 'c': 3},
         {'a': None, 'b': None, 'c': 3}]

expected = [{'a': 1, 'c': 4}, {'a': 2, 'c': 3}, {'a': None, 'c': 3}]

keys = dicts[0].keys()
keep_keys = []

for key in keys:
    vals = []
    for d in dicts:
        if d[key] is not None:
            vals.append(d[key])

    if len(vals) != 0:
        keep_keys.append(key)

for d in dicts:
    for k in d.keys():
        if k not in keep_keys:
            del d[k]

print dicts == expected


texts:
The output result is perfect to what I wanted, but takes a tad bit too long to pull data then render into a graph.  Is there a better way to rewrite this code to speed up the process?

CASE "TestGrid":
    $SnapArrayResult = array();
    $PlayArrayResult = array('A','B','C','D');
    echo "
\n";
    echo "
Data on Alliance
\n";

    $SnapResult = $db-> query("SELECT snap FROM scSVR WHERE hex(alliance) IN (hex('A'),hex('B'),hex('C'),hex('D')) GROUP BY snap ORDER BY snap ASC");
    while ($SnapRow = $db-> fetch_assoc($SnapResult)){ $SnapArrayResult[] = $SnapRow['snap']; }

    echo "

	\n";
    foreach($SnapArrayResult as $SAR){ echo "".DTConvS($SAR)."	\n"; }
    echo "

\n";
    echo "
";
    foreach($PlayArrayResult as $PAR){
        echo "
".$PAR."	";
        foreach($SnapArrayResult as $SAR){
            $PlayerResult = $db-> query("SELECT COALESCE(count(*),0) as pCnt FROM scSVR WHERE hex(alliance) = hex('".$PAR."') AND snap = ".$SAR);
            $PlayerRow = $db-> fetch_assoc($PlayerResult);
            echo "".$PlayerRow['pCnt']."	\n";
        }
        echo "
";
    }
    echo "

";
    break;


texts: Marking a rectangular region in a NumPy array as an image mask

texts:
I'm currently working on creating a mask for an image. I have initialized a two-dimensional numpy zeros array. I now want to replace the values of the mask corresponding to pixels following some conditions such as x1< x < x2 and y1 < y < y2 (where x and y are the coordinates of the pixels) to 1.

Is there an easier way to do it (maybe through slicing) without looping through the mask like below

clusterMask = np.zeros((h, w))
for x in range(h):
    for y in range(w):
        if x <= clusterH + 2 * S and x >= clusterH - 2*S and y <= clusterW + 2*S and y >= clusterW - 2*S:
            clusterMask[x][y] = 1


texts:
I'm trying to write a function that will work out the length of two string char arrays, using pointer arithmetic. It seems to be working but I'm still getting used to pointers and addresses etc and would be grateful if you could let me know what you think. If possible could tell me if my understanding is correct in thinking that, when finding the length of a string char array, you're actually finding how many bytes it is? Thank you.

Here is the code:

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

int cmpstr(const char *,const char *);

int main()
{

    const char hello[10] = "hello";
    const char world[10] = "world";

    printf("%d", cmpstr(hello, world));

    return 0;
}

int cmpstr(const char *s1, const char *s2)
{
    int start1 = s1; // start address for s1 string

    while(*s1 != '\0')
    {
        s1++;        // increase address until the end
    }

    s1 = s1-start1;  // subtract start address from end address

    int start2 = s2; // start address for s1 string

    while(*s2 != '\0')
    {
        s2++;       // increase address until the end
    }

    s2 = s2-start2; // subtract start address from end address

    if(s1==s2)      // if s1 string is equal to s2 string
    {
        return 0;
    }
    else if(s1>s2)  // if s1 string is greater than s2 string
    {
        return 1;
    }
    else if(s1<s2)  // if s1 string is less than s2 string
    {
        return -1;
    }

}


texts: Custom UI - Seeing which control has focus

texts:
I'm trying to make a simple UI to better understand how interfaces and the System.Windows.Forms Controls behave.

Like the above namespace, I will be able to get and set the Focus on a particular control, with a helper method to drill down to see which Control (or child Control) actually has the focus. I'm pretty rubbish for recusion.

Here's what I have so far:

public class Control
{
    public bool CanFocus { get; set; }
    public bool HasFocus { get; set; }

    public Control GetFocus()
    {
        if (HasFocus)
            return this;

        foreach (Control c in Children)
        {
            if (c.HasFocus)
                c.GetFocus();
        }

        return null;
    }

}

My thought process is that it should return the immediate control if it has focus. If not, it will recurse through each of its children. If that child has the focus, it will return that child, and if not, will find the next one, repeating until a default case (null) is reached.

I had thought about a ContainsFocus field as well, but it "sort of" overlaps with what I'm doing here. I considered a helper method with the signature bool FindFocus(out Control result), but it felt unwieldy. Also, I am concerned with invoking foreach within a recursive function.

I appreciate any insight into this.


texts: Get an array of strings separating a string on N character incrementally

texts:
So I asked a question over here, and even though I placed it in the wrong place (it should have been here), Redu was nice enough to give me a nice answer to my question.

Here is the original question for reference:

given the following input:

"/bob/ross/is/awesome/squirrels"

I would like to end up with:

[
    "/bob/ross/is/awesome/squirrels",
    "/bob/ross/is/awesome",
    "/bob/ross/is",
    "/bob/ross",
    "/bob"
]

The answer that Redu was nice enough to post was as follows:

res = s => s.length ? [s].concat(res(s.match(/.*(?=\/.+$)/)[0])) : [];

However he also commented the following:

  I honestly wouldn't advise recursion in JS, however since you have asked for it, i have provided a recursive answer down below.

Which makes me wonder, is there a better way to do this without recursion, but just as succinctly?

My original non-recursive function is as follows:

getWords = function( string ){

    // Get an array of all words in the provided string separating on "/"
    let words = string.split("/");

    // Filter out empty strings from leading/trailing "/" characters
    words = words.filter( function(a){return a !== ""} );

    // Create an array to store results in
    let results = [];

    // Create an iteration for each word in the array
    for (var i=0, j=words.length; i<j; i++){

        // Create a string to concatenate to
        let result = "";

        // Loop over each word in the array minus the current iteration of "i"
        for (var k=0, l=words.length - i; k<l; k++){

            // Contatenate using the special character plus the current word
            result += "/" + words[k];
        }

        // Push the resulting string to the results array
        results.push(result);
    }

    // Set the results to display
    resultsDisplay.innerHTML = results.toString().replace(/,/g, " -- ");

    // Return the results array
    return results;
}

input = document.getElementsByTagName("input")[0];
resultsDisplay = document.getElementsByClassName("results")[0];
input.addEventListener("input", function(){
getWords(input.value)
});
getWords(input.value);
<input value="bob/ross/is/awesome/squirrels" />

This code is, admittedly, awful, hence my original post.


texts:
When I work with SqlDataAdapter, I usually follow this pattern. Especially note the using/fill combination, which is basically a one-liner. The other stuff is just the facility around it.

private void PopulateData(DataTable table, long index)
{
  SqlCommand command = new SqlCommand(
    commandText.Replace("{ID}", "" + index), Connection);

  using (SqlDataAdapter adapter = new SqlDataAdapter(command))
    adapter.Fill(table);
}

Now, I'll be getting a number of scalars, so naturally I'm prone to use the appropriate method for that. However, I'm not certain how to make the code shorter without affecting readability.

private String GetString(long index)
{
  String output;
  using (SqlCommand command = new SqlCommand(CommandText, Connection))
  {
    command.Connection.Open();
    output = command.ExecuteScalar() as String;
    command.Connection.Close();
  }
  return output;
}

Preferably I'd like to get using/returning of the scalar value to be done as a one-liner too. Is it at all possible?

Or is the pattern of open-get-close inside the using-scope the best way to go? Perhaps it depends on the different circumstances? In such case - which?


texts:
Any suggestions on how to improve the code shown below for the Go-tour exercise?

Exercise description:

  There can be many different binary trees with the same sequence of
  values stored at the leaves.  A function to check whether two binary
  trees store the same sequence is quite complex in most languages.
  We'll use Go's concurrency and channels to write a simple solution.

  This example uses the tree package, which defines the type:

type Tree struct {
    Left  *Tree
    Value int
    Right *Tree
}

  Implement the Walk function.
  Test the Walk function.

  The function tree.New(k) constructs a randomly-structured binary tree
  holding the values k, 2k, 3k, ..., 10k.

  Create a new channel ch and kick off the walker:

  go Walk(tree.New(1), ch) Then read and print 10 values from the channel. It should be the numbers 1, 2, 3, ..., 10.
  Implement the Same function using Walk to determine whether t1 and t2 store the same values.
  Test the Same function.

  Same(tree.New(1), tree.New(1)) should return true, and Same(tree.New(1), tree.New(2)) should return false.

  Code skeleton:

package main

import "golang.org/x/tour/tree"

// Walk walks the tree t sending all values
// from the tree to the channel ch.
func Walk(t *tree.Tree, ch chan int)

// Same determines whether the trees
// t1 and t2 contain the same values.
func Same(t1, t2 *tree.Tree) bool

func main() {
}

Solution:

package main

import (
    "code.google.com/p/go-tour/tree"
    "fmt"
)

// Walk walks the tree t sending all values
// from the tree to the channel ch.
func Walk(t *tree.Tree, ch chan int) {
    if t.Left != nil {
        Walk(t.Left, ch)
    }
    ch <- t.Value
    if t.Right != nil {
        Walk(t.Right, ch)
    }
}

// Same determines whether the trees
// t1 and t2 contain the same values.
func Same(t1, t2 *tree.Tree) bool {
    c1 := make(chan int, 10)
    c2 := make(chan int, 10)
    go Walk(t1, c1)
    go Walk(t2, c2)
    for i := 0; i < 10; i++ {
        x, y := <-c1, <-c2
        fmt.Printf("x: %v, y: %v\n", x, y)
        if x != y {
            return false
        }
    }
    return true
}

func main() {
    fmt.Println(Same(tree.New(1), tree.New(1)))
    fmt.Println(Same(tree.New(1), tree.New(2)))
}


texts: Can people understand my form validation code?

texts:
I've just finished creating this form validation but I want to make it public for beginner 'contact us forms'.

I was wondering if I can have some peoples' input on if they can understand/read my JavaScript. Although I know my JS works, it's better to be safe than to have 20 people asking what this does.  It's just input feedback.

What I'm trying to achieve in my code is making fields required with JavaScript.

The following fields are REQUIRED:

First Name
Last Name
Email
Phone

Most of the functions such as alphaNumeric only allows numbers and onlyAlphameric only allows letters.

E.g for each function or what not, add a comment saying what it does.

For example, adding a comment:

This function does this and triggers that and so on.

JavaScript:

function elem(id) {
    return document.getElementById(id);
};

window.onload = function () {
    document.querySelector("#RadioGroup1_0").click();

    var form = document.getElementById('form');
    form.onsubmit = function (e) {
        var rules = [
        ['first-name', elem('first-name').value.length > 0],
        ['last-name', elem('last-name').value.length > 0],
        ['email', elem('email').value.length > 0 && /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(elem('email').value)],
        ['phone', elem('phone').value.length > 7 && elem('phone').value.length < 11 && /^(\+\d{1,2})?[\d ()-]+$/.test(elem('phone').value)]

    ];

    function myFunction()
{
document.getElementById("myForm").reset();
}

        function alpha(e) {
            var k;
            document.all ? k = e.keyCode : k = e.which;
            return ((k > 64 && k < 91) || (k > 96 && k < 123) || k == 8);
        }

        var valid = true;
        var firstFocus = null;
        for (var i = 0; i < rules.length; i++) {
            var parent = elem(rules[i][0]).parentNode;
            if (!rules[i][1]) {
                valid = false;
                parent.children[2].style.display = "inline";
                if (firstFocus == null) firstFocus = parent.children[1];
            } else {
                parent.children[2].style.display = "none";
            }

        }
          if (!valid) {
            firstFocus.focus();
            return false;
        }

        return true;
    };
};

function onlyAlphabets(e, t) {
    try {
        if (window.event) {
            var charCode = window.event.keyCode;
        } else if (e) {
            var charCode = e.which;
        } else {
            return true;
        }
        if ((charCode > 64 && charCode < 91) || (charCode > 96 && charCode < 123) || (charCode === 8)) return true;
        else return false;
    } catch (err) {
        alert(err.Description);
    }
}

var specialKeys = new Array();
specialKeys.push(8); //Backspace
function IsNumeric(e) {
    var keyCode = e.which ? e.which : e.keyCode
    var ret = ((keyCode >= 48 && keyCode <= 57) || specialKeys.indexOf(keyCode) != -1);
    //document.getElementById("phone").style.display = ret ? "none" : "inline";
    return ret;
}


texts: Hiding and revealing toggle responds very slow

texts:
I have a list of 6 items, and each one on click reveals a div that runs 100% wide under the row of list items. The code works, but the div opens very slowly and kind of choppy. Is there anything I can do to help it run more smoothly?

My HTML is set up as such:

Here is my jscript:

 $(document).ready(function(){
 $(".artist-box").hide();
$(".artist-logo").click(function(e) {
e.preventDefault();
// get the clicked element
var clicked = $(this);

// get the selected element
var taggedWithSelect = $('.selected-artist');
// get the corresponding divs
var clickPartner = $(clicked.attr('href'));
var selectPartner = $(taggedWithSelect.attr('href'));
var notClicked = $('.artist-logo').not(clicked);

        // we either want to close this one or open this one and close any others
        // if this one is open, it should be tagged with select
if( clicked.hasClass('selected-artist') ) {
    clicked.removeClass('selected-artist');
    notClicked.removeClass('blur-logo');
} else {
  clicked.addClass('selected-artist');
  taggedWithSelect.removeClass('selected-artist');
  selectPartner.slideToggle();
  notClicked.addClass('blur-logo');
  clicked.removeClass('blur-logo');
}

clickPartner.slideToggle();

});

});


texts: Building a lot of individual programs from one Makefile

texts:
I have written a non-recursive Makefile that almost does the job I want. Apart from not full-fillng all my goals it doesn't look good. There should ways to solve the issues and also to improve/clean the makefile itself.

My setup

Several thousands of src files should each be built into individual programs.
The src files are grouped in several directories. Think 10 dirs with 400 files each.
Each file has a unique name.
Each of the programs are dependent on the same set of common files.

My goals

Non-recursive
Each program shall be gzipped
The build of each program shall use a separate object directory
The output of each program build, including the build commands themselves (CC, LD), should be captured in a log file. The logfile shall be unique for each build.
As the build of each program uses several rules via dependencies, the logfile name has to be communicated from the top rule to the dependencies.
All programs should be built in one go. Failing to build one program should not stop the build of the other programs.
The logfile of each build should be placed in a “passed” or “failed” dir depending on build success.

My problems
(using the numbers above)
Refer to the Makefile below when needed.

I calculated the name of the dependedcy in the rule '$(BINDIR)/%.gz:' with mix of secondary expansion ($$*) and %. Is this correct?
I only capture the output of the commands, not the command themselves.
I don't decide on the name of the log file in the top rule '$(BINDIR)/%.gz:' and communicate it to the dependencies. I calculate it in each rule, knowing what the directory structure looks like. This is prone to error. I would like to do it with a pattern-specific macro in the top rule. This way It is only calculated once for the build of one program.
I use 'MAKEFLAGS += --keep-going'. It will let the top rule '$(BINDIR)/%.gz:' try and link the program even if a compilation failed. I would like to keep that from happening for the build of this program, while keep building the other programs.
Here I don't have a solution.

Makefile

#############################################
# TOOLS
MKDIR := mkdir -p
ifeq ($(VERBOSE),yes)
   LOG := |& tee -a
else
   LOG := &>>
endif
LOG0 := |& tee -a
GZIP := gzip -c
#############################################

MAKEFLAGS += --keep-going -j8

.SUFFIXES:
.SECONDARY:
.SECONDEXPANSION:

SRCDIR := source
OBJDIR_ROOT := obj
BINDIR   := bin

SRCDIRS := $(wildcard $(SRCDIR)/*.dir)
SRCFILES := $(foreach dir,$(SRCDIRS),$(wildcard $(dir)/*.cpp))
PROGS := $(foreach srcfile,$(SRCFILES),$(BINDIR)/$(basename $(notdir $(srcfile))).gz)

# Common files
COMMON_SRCDIR := common/src
COMMON_OBJDIR := $(OBJDIR_ROOT)/common
COMMON_OBJECTS := $(COMMON_OBJDIR)/common1.o
COMMON_OBJECTS += $(COMMON_OBJDIR)/common2.o

vpath %.cpp $(SRCDIRS)
vpath %.c $(COMMON_SRCDIR)

.PHONY: progs

progs: $(PROGS)

%.o: $$(notdir $$*).cpp
    @$(MKDIR) $(dir $@)
    $(eval RES_FILE := $(dir $@)/$(notdir $*).res)
    @echo Compiling $< $(LOG0) $(RES_FILE)
    @$(CXX) $(CXXFLAGS) $(CCFLAGS) -o $@ $< $(LOG) $(RES_FILE)

%.o: $$(notdir $$*).c
    @$(MKDIR) $(dir $@)
    $(eval RES_FILE := $(dir $@)/$(notdir $*).res)
    @echo Compiling $< $(LOG0) $(RES_FILES)
    @$(CC) $(CCFLAGS) -o $@ $< $(LOG) $(RES_FILE)

$(BINDIR)/%.gz: $(OBJDIR_ROOT)/$(notdir $$*)/%.o $(COMMON_OBJECTS)
    @$(MKDIR) $(dir $@)
    $(eval OBJDIR=$(OBJDIR_ROOT)/$*)
    $(eval EXENAME=$*)
    $(eval ELFFILE=$(OBJDIR)/$(EXENAME).elf)
    $(eval RES_FILE=$(OBJDIR)/$*.res)

    @echo "--- Linking $@" $(LOG0) $(RES_FILE)
    @$(LD) $(LDRFLAGS) $^ -o $(ELFFILE) $(LOG) $(RES_FILE)

    @echo "--- gzipping $(ELFFILE)" $(LOG0) $(RES_FILE)
    @$(GZIP) $(ELFFILE) >> $@


texts:
I've just started to learn Scala and decided to implement small graph library to train.
Here is the basic version, that describes graph and nodes structure and also provides implementation of DFS to find some path from one node to other.

class Graph[A] {

  var nodes = Set.empty[Node[A]]

  def addNode(n: Node[A]) = nodes = nodes + n

  def DFS(from: Node[A], to: Node[A]): List[Node[A]] = {
    var visited = Set.empty[Node[A]]
    @tailrec
    def _DFS(from: Node[A], to: Node[A], path: List[Node[A]]): List[Node[A]] = {
      visited = visited + from
      if (from.equals(to)) path
      else {
        from.outgoing.find(n => !visited.contains(n)) match {
          case Some(n) => _DFS(n, to, n :: path)
          case None => path match {
            case n :: Nil => List.empty[Node[A]]
            case _ :: n :: ns => _DFS(n, to, n :: ns)
          }
        }
      }
    }
    _DFS(from, to, List(from)).reverse
  }

}

class Node[A](val i: A) {
  var incoming = Set.empty[Node[A]]
  var outgoing = Set.empty[Node[A]]

  def addIncoming(n: Node[A]) = incoming = incoming + n
  def addOutgoing(n: Node[A]) = outgoing = outgoing + n
}

I'm actively writing code in Java, so my primary goal is to not write Java code in Scala syntax. Hence, first and main question is: does my code looks like typical Scala code? If not, what should I change?
Next thing bothering me, is that my Node is too loosely coupled with Graph. I could invoke DFS only on instance of Graph, but apart from this, I don't really use Graph abstraction: I could just create instances of Node and link them.
That leads me to another problem. Suppose now I want to define weighted graph. For Graph itself I could define Weighted trait, but then I need to replace inner Node with NodeWithWeightedEdges, and I don't understand how.


texts: Python Reverse the binary equivalent of input and output the integer equivalent of the reverse binary

texts:
Am supposed to capture user input as an integer, convert to a binary, reverse the binary equivalent and convert it to an integer.Am getting the right output but someone says the solution is wrong. Where is the problem?

x  = 0

while True:

    try:
        x = int(raw_input('input a decimal number \t'))

        if x in xrange(1,1000000001):

            y = bin(x)

            rev = y[2:]

        print("the reverse binary soln for the above is %d") %(int('0b'+rev[::-1],2))
            break

    except ValueError:
        print("Please input an integer, that's not an integer")
        continue


texts:
I was trying to solve a task on leetcode, where I need to find if a positive integer is the sum of squares of two other integers. My solution is below, but it fails due to exceeding time limit.

var judgeSquareSum = function(c) {
    let output = false;
    for(let i = c; i >= 0; i--) {
      for(let y = 0; y <= i; y++) {
        let sum = i*i + y*y;
        if (sum == c)
                output = true;
      }
    }

    return output;
};

How can I make this so that is efficient, and without two iterations?


texts:
I have partial view which update data on server.
Partial view contains list of configurations (can be check box or text box depends on type).
This code is working, and I would like to know how to implement this better.

Main question is related to "@Html.HiddenFor".
Is this correct way to implement update?
Without "@Html.HiddenFor" my model data is not ok.

Action:

  public async Task<IActionResult> UpdateConfiguration(List<ConfigurationModel> configurations)
        {
            logger.LogInformation("Update configurations");

            using (var client = new HttpClient())
            {
                SetToken(client, this.HttpContext);
                var configUrl = Helper.GetUrlManagerApi(env, "Configuration");
                var response = await client.PutAsync(configUrl, configurations.ToJson());
                HandleResponseError(response, logger);
                return RedirectToAction("Index", "Home");
            }
        }

Partial view:

@using Microsoft.EntityFrameworkCore.Metadata.Internal
@using Bluebox.Common.Models
@using Bluebox.Common.Helper
@using Microsoft.AspNetCore.Mvc.Localization
@using SettingsApp.Models;

@inject IViewLocalizer Localizer
@model List<ConfigurationModel>

@using (Html.BeginForm("UpdateConfiguration", "ManagerSettings"))
{

                @Localizer["Property"]

                    @Localizer["Edit"]

        @for (var i = 0; i < Model.Count(); i++)
        {

                    @Localizer[Model[i].LocalizeId.ToString()]
                    @Html.HiddenFor(model => model[i].Id, @Model[i].Id)
                    @Html.HiddenFor(model => model[i].LocalizeId, @Model[i].LocalizeId)
                    @Html.HiddenFor(model => model[i].Key, @Model[i].Key)
                    @Html.HiddenFor(model => model[i].Type, @Model[i].Type)

                    @if (Model[i].Type == PropertyType.Boolean)
                    {
                        @Html.CheckBoxFor(model => model[i].ValueBool, Model[i].Value == "true")
                    }
                    else if (Model[i].Type == PropertyType.Number)
                    {
                        @Html.TextBoxFor(model => model[i].ValueNum, new { style = "width:50px;", @type = "number" })

                    }
                    else if (Model[i].Type == PropertyType.Text)
                    {
                        @Html.TextBoxFor(model => model[i].Value, new { style = "width:250px;" })

                    }

        }

        <input type="submit" class="button" value='@Localizer["Update"]' />

}

Result:


texts: Base Class Interface for Parent/Child tree hierarchy

texts:
I have a class named Object, which is a common interface for all its derived class.

The following rules apply to all Object instances.

As zero or one parent.
As zero or more child.
Can not be the parent of one of its ancestor, nor itself.
Deletes its children on destruction.
Children can leave and join new parent.
Parents can not abandon a child, nor adopt a new one without its consent.

Object.hpp

#ifndef OBJECT_HPP
#define OBJECT_HPP

#include <unordered_set>

namespace Foo
{
class Object
{
public:

  explicit Object() : m_parent(nullptr), m_children() {}

  explicit Object(Object* parent);

  // Copy constructor is not allowed
  Object(const Object& orig) = delete;

  // Assignation operator is not allowed
  Object& operator =(const Object& orig) = delete;

  virtual ~Object();

  int countChildren() const;

  const Object* getParent() const;

protected:

  void joinParent(Object* parent);

  void quitParent();

private:

  // data members

  std::unordered_set<Object*> m_children;

  Object* m_parent;

  // methods

  void addChild(Object* child);

  void removeChild(Object* child);

};
}

#endif // OBJECT_HPP

Object.cpp

#include "Object.hpp"

using namespace Foo;

// constructor/destructor

Object::Object(Object* parent) : m_parent(nullptr), m_children()
{
  joinParent(parent);
}

Object::~Object()
{
  quitParent(); // Notify its parent

  // Delete all its children. Rule 4.
  while (!m_children.empty())
  {
    delete *(m_children.begin());
  }
}

// public methods

int Object::countChildren() const
{
  return m_children.size();
}

const Object* Object* getParent() const
{
  return m_parent;
}

// protected methods

void Object::joinParent(Object* parent)
{
  Object* ancestor = parent;

  // Check if respect tree hierarchy. Rule 3.
  while (ancestor != nullptr)
  {
    if (ancestor == this)
      // Foo::Error derived from std::runtime_error
      throw Foo::Error("No respect of tree hierarchy");

    ancestor = ancestor->m_parent;
  }

  quitParent(); // Rule 1.
  m_parent = parent;
  m_parent->addChild(this);
}

void Object::quitParent()
{
  if (m_parent != nullptr)
  {
    m_parent->removeChild(this); // Notify its parent.
    m_parent = nullptr;
  }
}

// private methods

/*
 *Methods addChild and removeChild are private
 *to ensure that rules 5 and 6 are respected.
 */

void Object::addChild(Object* child)
{
  m_children.insert(child);
}

void Object::removeChild(Object* child)
{
  m_children.erase(child);
}

After testing my interface, I've come with the following conclusions.

Auto deletation of children can result in dangling pointers.
Stack instances have undefined behavior, resulted of deleting children. (one time in parent destructor, second time when out of scope)

Now the questions

Is there a way to change my interface so that its more safe?
Should I remove rule 4?
Is there any leak in my tree hierarchy logic? (e.g possible circular hierarchy)

Remark :
I use c++11 standard. However, I'm open to see any answer with higher standard.


texts: C++ Read istream into string with exceptions

texts:
Did I cover all the bases? Can this be improved (best practice)?

Edit... I've come up with some improvements. When I tried edit the code, the software complained about too much code and too little blather (paraphrasing). So, here I am blathering. When I have blathered enough, the code below will be the new stuff.

//#include <libdj/istream.h>

#include <istream>
#include <string>
#include <stdexcept>

namespace dj {
    inline
    void append_istream_onto_string(std::istream& inp, std::string &outp) {
        // Uses inp.seekg(), and inp.tellg() to determine size
        // Throws (std::) invalid_argument, runtime_error, bad_alloc, length_error
        if (!inp.good()) {
            throw std::invalid_argument
              ("Input stream is not valid. (read_istream_into_string)");
        }
        if (!inp.seekg(0, std::ios::end)) {
            throw std::runtime_error
            ("Cannot deduce length of input stream. (read_istream_into_string)");
        }
        outp.reserve(outp.size() + inp.tellg()); // Throws bad_alloc and length_error
        if (!inp.seekg(0, std::ios::beg)) {
            throw std::runtime_error
              ("Input stream seek failed. (read_istream_into_string)");
        }
        outp.append((std::istreambuf_iterator<char>(inp)),
            std::istreambuf_iterator<char>());
    }

    inline
    std::string to_string(std::istream& inp) {
        std::string ret;
        append_istream_onto_string(inp, ret);
        return ret;
    }
}
#include <fstream>

int main() {

    std::ifstream inp("junk.txt");

    std::string buffer;
    buffer = "// junk.txt\n";
    try {
        //dj::append_istream_onto_string(inp, buffer);
        buffer = dj::to_string(inp);
    } catch (const std::exception &ex) {
        std::cout << ex.what() << std::endl;
    }
    std::cout << buffer << std::endl;
}


texts: Finding the first pair of prime numbers that have some specified difference

texts:
I tried printing the first pair of prime number in between a list of numbers with a particular difference. But my run time is still too high (for large range of numbers). I want to reduce the run time by using any method from standard library like itertools.
def prime(x):
    """To generate prime number"""
    a = x // 2 + 1
    for i in range(2, x):
        if x % i == 0:
            return False
        elif i == a:
            return True

def gap(p, q, m):
    """To generate gap in between two prime numbers"""
"""p is the difference,q is the lower limit where the list of numbers in between which prime is filtered,m is the upper limit"""
    b = []
    a = b.append
    c = prime
    q = (q // 2) * 2 + 1
    for i in range(q, m + 1, 2):
        if c(i) == True:
            a(i)
            if len(b) > 1:
                if b[-1] - b[-2] == p:
                    return [b[-2], b[-1]]


texts: Scraping and printing titles from Craigslist

texts:
I've written a very tiny script using class to scrape some titles of products from craigslist. My intention is to make use of __str__() method so that my script can print the result without explicitly calling that very method.

However, when I execute my script in the following way, I get the desired results.

Is this the only way I can print the result or there is anything better to print the result through dunder str method?

import requests
from bs4 import BeautifulSoup

URL = "http://bangalore.craigslist.co.in/search/rea?s=120"

class DataSourcer:

    def __init__(self,link):
        self.link = link
        self.datalist = []

    def fetch(self):
        res = requests.get(self.link)
        soup = BeautifulSoup(res.text,"lxml")
        for ilink in soup.select("li.result-row a[data-id]"):
            self.datalist.append(ilink.text)

        # return self.datalist #I do not wish to return "self.datalist" here

    def __str__(self):
        return self.datalist

if __name__ == '__main__':
    crawler = DataSourcer(URL)
    crawler.fetch()
    print(crawler.__str__()) #I found it working this way


texts:
I was reading binary search from an interview book and changed some part of the algorithms.

It is working for all the values I tested with: i.e. all the values in array and outside the array extremes. I would appreciate another person's glance on my use of lower <= upper condition. Any other opinion is welcome, too.

std::pair<bool,size_t> BinarySearch(const std::vector<int>& array, int key) {

auto lower = array.begin();
auto upper = array.end()-1;
while (lower <= upper) {
    auto mid = lower + (upper-lower) /2;
    if(key == *mid)
    {
        return {true,std::distance(array.begin(),mid)};
    }
    if(key < *mid)
        upper = mid-1;
    else
        lower = mid+1;
}

return {false,std::distance(array.begin(),lower)};
}

Usage is as follows:

int main(int argc, const char * argv[]) {

std::vector<int> arr {2,5,11,15};
auto result = BinarySearch(arr,5);
if(result.first)
    std::cout << result.second << std::endl;
else
    std::cout << "Not found " << std::endl;
return 0;

}


texts:
In my solution I've implemented transaction-like methods of uploading posts media. For example I'm adding new post with photo. I want to have 700x700, 200x200, 70x70, 10x10 px sizes in my storage and original in device album. And when all images are uploaded, then save new post info to database. But this code is not beautiful at all. How can I improve it?

// MARK: - Christmas tree
// Like transaction :)
// Bad view actually
static func uploadVideoForPost(with videoURL: URL, for postForUpdate: PostItem,
                              screenShot: UIImage,
                              completion: @escaping (_ hasFinished: Bool, _ postWithRefs: PostItem?) -> Void) {
  var post = postForUpdate // we will insert refs to media to this object
  // upload screenshots
  upload(screenShot, for: post, withSize: 700.0)
  { (hasFinishedSuccessfully, url) in

     if hasFinishedSuccessfully {
        post.mediaRef700 = url

        upload(screenShot, for: post, withSize: 200.0)
        { (hasFinishedSuccessfully, url) in

           if hasFinishedSuccessfully {
              post.mediaRef200 = url

              upload(screenShot, for: post, withSize: 70.0)
              { (hasFinishedSuccessfully, url) in

                 if hasFinishedSuccessfully {
                    post.mediaRef70 = url

                    upload(screenShot, for: post, withSize: 10.0)
                    { (hasFinishedSuccessfully, url) in

                       if hasFinishedSuccessfully {
                          post.mediaRef10 = url

                          // upload video
                          upload(with: videoURL, for: post)
                          { (hasFinishedSuccessfully, url) in

                             if hasFinishedSuccessfully {
                                post.videoRef = url

                                let path = videoURL.path

                                if UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(path) {
                                   UISaveVideoAtPathToSavedPhotosAlbum(path, nil, nil, nil)
                                }
                                completion(true, post) // after this func i will save post data to db in other func.
                             } else {
                                completion(false, nil)
                             }
                          }
                       }else {
                          completion(false, nil)
                       }
                    }
                 } else {
                    completion(false, nil)
                 }
              }
           } else {
              completion(false, nil)
           }
        }
     } else {
        completion(false, nil)
     }
   }
}

Upload func is just a func of uploading with completion handler.


texts:
The AI I'm making is really simple, however it might be a bit too inefficient for what it is doing. The chart below shows speed differences between various arithmetic and math operations. sin, cos and especially atan are really inefficient. It's tested in C++ but should still hold true to JavaScript.

Is it possible to achieve the same result with more efficient math?

Chart Source

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');

let targetX = 50;
let targetY = 50;

let obstacleX = 150;
let obstacleY = 50;

let aiX = 250;
let aiY = 51;

function loop() {
    // Distance between the vector points
    let disTargetX = targetX - aiX;
    let disTargetY = targetY - aiY;

    let disObstacleX = obstacleX - aiX;
    let disObstacleY = obstacleY - aiY;

    // Moves to target by default
    const angleTarget = Math.atan2(disTargetY, disTargetX);
    let moveAngle = angleTarget;

    // If near obstacle, adjust course and try to avoid it
    if (Math.sqrt(disObstacleX * disObstacleX + disObstacleY * disObstacleY) < 60) {
        const angleObstacle = Math.atan2(disObstacleY, disObstacleX);
        moveAngle += angleTarget - angleObstacle;
    }

    // Move the vector to desired location
    aiX += Math.cos(moveAngle);
    aiY += Math.sin(moveAngle);

    //Drawing
    ctx.clearRect(0, 0, 600, 200);

    ctx.beginPath();
    ctx.fillStyle = "teal";
    ctx.arc(aiX, aiY, 10, 0, Math.PI * 2, true);
    ctx.fill();

    ctx.beginPath();
    ctx.fillStyle = "purple";
    ctx.arc(obstacleX, obstacleY, 10, 0, Math.PI * 2, true);
    ctx.fill();

    ctx.rect(targetX - 20, targetY - 20,40,40);
    ctx.stroke();

    requestAnimationFrame(loop);
}

requestAnimationFrame(loop);
<canvas id="canvas" width="600" height="200"></canvas>


texts: Print binary search tree by levels function implementation

texts:
I do not like this implementation as is seems too much complicated.  My idea was to implement some BFS algorithm variant.

Some points to notice:

I use one queue.
In the begining put the tree root in the queue and dummy treeNode delimiter which is recognized by its data == -1.
(I need this for distiguishing between tree levels).
After each level I assign -1 to the queue.

Any suggestions of how to simplify it?  (Currently seem to work good)

public void printTreeByLevels() // Should be BFS variant implementation
{
    int levelCounter = 0;
    boolean currNodeHasChild = false;
    Queue<TreeNode> q = new ArrayDeque<TreeNode>();

    q.add(m_Root);
    q.add(new TreeNode(-1));
    System.out.print("Level:" + levelCounter+ " ");

    while (!q.isEmpty())
    {
        TreeNode currentNode = q.poll();
        currNodeHasChild = false;
        if(currentNode.m_Data == -1)
        {
            TreeNode nextQueueNode = q.peek();
            while(nextQueueNode!= null && currentNode.m_Data == -1)
            {
                currentNode = q.poll(); //bypassing delimiters
            }

            if(currentNode.m_Data != -1)
            {
                levelCounter++;
                System.out.println();
                System.out.print("Level:" + levelCounter+" ");
            }
            else if(nextQueueNode == null)
            {
                break;
            }

        }

        System.out.print("\t"+currentNode.m_Data);

        if(currentNode.m_LeftNode!= null)
        {
            q.add(currentNode.m_LeftNode);
            currNodeHasChild = true;
        }

        if(currentNode.m_RightNode!=null)
        {
            q.add(currentNode.m_RightNode);
            currNodeHasChild = true;
        }

        if(currNodeHasChild)
        {
            q.add(new TreeNode(-1)); // sign of next level
        }
    }
}


texts:
At my workplace, we changed string type (which holds internationalized characters) for from std::wstring to std::u16string after VS 2015(Update 3) compiler upgrade.

Due to this, we are seeing loads of performance regressions such as this.

The profiler analysis reveals that std::u16string's std::char_traits<char16_t> operations such as copy, compare, find and assign are the most hit and are taking longer than std::wstring's std::char_traits<wchar_t> counterparts.

These std::char_traits<wchar_t> operations are written in terms of std::wmem* and std::char_traits<char16_t> operations are written in terms of for loops.

If we change these traits operations for char16_t type (or std::u16string) to use our own customized traits, we are seeing performance improvements with performance comparable to std::wstring.

We are planning to write our own custom traits (until MS fixes it for next version of VS) as follows

struct string_custom_traits : public std::char_traits<char16_t>
{
    static const char16_t * copy(char16_t* dest, const char16_t* src, size_t count)
    {
        return (count == 0 ? src : (char16_t*)std::memcpy(dest, src, count * sizeof(char16_t)));
    }

 };

Would that be OK? Are there any problems with this approach ?