texts: n-dimensional Euclidean space calculation templates

texts:
I have been working with C++11 code that uses std::vector[] to store coordinates. Most often this code uses 2D or 3D but it occurred to me that it may be generally useful for n-dimensional Euclidean distance calculations.

Because these calculations are used within a simulation, they should be as fast as practical without sacrificing generality.

// euclid.h
#include <vector>
#include <algorithm>
#include <stdexcept>

template <typename T>
std::vector<T> operator+(const std::vector<T>& a, const std::vector<T>& b)
{
    if (a.size() != b.size())
        throw std::domain_error("vector addition must have equal length vectors");
    std::vector<T> result;
    result.reserve(a.size());
    std::transform(a.begin(), a.end(), b.begin(),
                   std::back_inserter(result), std::plus<T>());
    return result;
}

template <typename T>
std::vector<T> operator-(const std::vector<T>& a, const std::vector<T>& b)
{
    if (a.size() != b.size())
        throw std::domain_error("vector subtraction must have equal length vectors");
    std::vector<T> result;
    result.reserve(a.size());
    std::transform(a.begin(), a.end(), b.begin(),
                   std::back_inserter(result), std::minus<T>());
    return result;
}

template <typename T>
T squared_distance(const std::vector<T>& a, const std::vector<T>& b)
{
    if (a.size() != b.size())
        throw std::domain_error("squared_distance requires equal length vectors");
    return std::inner_product(a.begin(), a.end(), b.begin(), T(0),
        std::plus<T>(), [](T x,T y){return (y-x)*(y-x);});

}

Here is some driver code to demonstrate usage.

// points.cpp
#include <iostream>
#include <vector>
#include "euclid.h"

template <typename T>
std::ostream& operator<<(std::ostream& out, const std::vector<T> &v)
{
    out << "{ ";
    for (auto p : v)
        out << p << ' ';
    return out << "}";
}

#define say(x) std::cout << "" #x " = " << (x) << std::endl
int main()
{
    std::vector<double> origin{0, 0, 0}, a{3, 4, 5}, b{-1, -2, -3},g{0,0,0,0};
    say(origin);
    say(a);
    say(b);
    say(a+b);
    say(a-b);
    say(b-a);
    say(squared_distance(origin,a));
    say(squared_distance(origin,b));
}

The output from the program looks like this:

origin = { 0 0 0 }
a = { 3 4 5 }
b = { -1 -2 -3 }
a+b = { 2 2 2 }
a-b = { 4 6 8 }
b-a = { -4 -6 -8 }
squared_distance(origin,a) = 50
squared_distance(origin,b) = 14

I'm interested in general ideas for improvement or criticism of the existing code, but I also have some specific questions:

can the squared_distance calculation be made more efficient?
is there a nice way to reduce code duplication in the + and - operators?
I've tested with int, float, double and std::complex.  What else might be useful?
is there any point to accommodating unsigned types?
should I do anything about possible numeric overflow or underflow?
is there any point to having an #ifndef header guard in this file?


texts:
This is the Matrix Rotation problem from hackerrank.com.

  You are given a 2D matrix, \$a\$, of dimension \$M×N\$ and a positive integer
  \$R\$. You have to rotate the matrix R times and print the resultant
  matrix. Rotation should be in anti-clockwise direction.

  Rotation of a \$4×5\$ matrix is represented by the following figure. Note
  that in one rotation, you have to shift elements by one step only
  (refer sample tests for more clarity).

  It is guaranteed that the minimum of \$M\$ and \$N\$ will be even.

  Input

  First line contains three space separated integers, \$M\$, \$N\$ and \$R\$, where \$M\$ is the number of rows, \$N\$ is number of columns in matrix, and \$R\$ is the number of times the matrix has to be rotated. Then \$M\$ lines follow, where each line contains \$N\$ space separated positive integers. These \$M\$ lines represent the matrix.

  Output

  Print the rotated matrix.

  Constraints

  \$2 \le M, N \le 300\$
  \$1 \le R \le 10^9\$
  \$\min(M, N) ≡ 0 \pmod 2\$
  \$1 \le a_{ij} \le 10^8\$, where \$i \in [1\ldots M]\$ and \$j \in [1\ldots N]\$

  Sample Input #00

4 4 1
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16

  Sample Output #00

2 3 4 8
1 7 11 12
5 6 10 16
9 13 14 15

  Sample Input #01

4 4 2
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16

  Sample Output #01

3 4 8 12
2 11 10 16
1 7 6 15
5 9 13 14

Following is how I tried to solve the problem, but it runs just too slow:

from copy import deepcopy

aM, aN, R = map(int, input().split())

pivots = min(aM, aN)//2
refMat = []
baseMat = []

for i in range(aM):
    readInput = list(map(int, input().split()))
    baseMat.append(readInput)

refMat = deepcopy(baseMat)

for i in range(pivots):
    cLimit = (aN - 1) - i
    rLimit = (aM - 1) - i
    loopLength = (aM + aN - 2 - 4*i)*2
    nbrOfRotations = R%loopLength

    for rotnIndex in range(nbrOfRotations):

        # Corner movements
        # Pivot
        refMat[i][i] = baseMat[i][i + 1]
        # Column End
        refMat[i][cLimit] = baseMat[i + 1][cLimit]
        # Row End
        refMat[rLimit][i] = baseMat[rLimit - 1][i]
        # Pivot diagonal
        refMat[rLimit][cLimit] = baseMat[rLimit][cLimit - 1]

        # Top movement
        for j in range(i+1, cLimit):
            refMat[i][j] = baseMat[i][j + 1]

        # Bottom movement
        for j in range(i+1, cLimit):
            refMat[rLimit][j] = baseMat[rLimit][j - 1]

        # Left movement
        for j in range(i+1, rLimit):
            refMat[j][i] = baseMat[j - 1][i]

        # Right movement
        for j in range(i+1, rLimit):
            refMat[j][cLimit] = baseMat[j + 1][cLimit]

        baseMat = deepcopy(refMat)

for i in refMat:
    for e in i:
        print(e, end = " ")
    print()

Note: No advanced libraries such as NumPy, SciPy etc. are allowed. However, I would love to know if they offer a better workaround.


texts: Building object from unusually custom object

texts:
Say we have this method which is my main concern for this question. It's really not optimal way to get values out of it. Each time I'm running through list twice for to just get one field value for NotificationSettingsDto

private NotificationSettingsDto notificationSettingsCustomPairToDto(List<CustomPair> notificationSettingsCustomPair) {
    return NotificationSettingsDto.builder()
            .campaignEvents(notificationSettingsCustomPair.stream()
                    .anyMatch(customPair -> customPair.getKey().equals("campaignEvents")) ?
                    (Boolean) notificationSettingsCustomPair.stream().filter(customPair -> customPair.getKey().equals("campaignEvents")).collect(Collectors.toList()).get(0).getValue() : null)
            .drawResultEvents(notificationSettingsCustomPair.stream()
                    .anyMatch(customPair -> customPair.getKey().equals("drawResultEvents")) ?
                    (Boolean) notificationSettingsCustomPair.stream().filter(customPair -> customPair.getKey().equals("drawResultEvents")).collect(Collectors.toList()).get(0).getValue() : null)
            .transactionEvents(notificationSettingsCustomPair.stream()
                    .anyMatch(customPair -> customPair.getKey().equals("transactionEvents")) ?
                    (Boolean) notificationSettingsCustomPair.stream().filter(customPair -> customPair.getKey().equals("transactionEvents")).collect(Collectors.toList()).get(0).getValue() : null)
            .userWonEvents(notificationSettingsCustomPair.stream()
                    .anyMatch(customPair -> customPair.getKey().equals("userWonEvents")) ?
                    (Boolean) notificationSettingsCustomPair.stream().filter(customPair -> customPair.getKey().equals("userWonEvents")).collect(Collectors.toList()).get(0).getValue() : null)
            .build();
}

And I'm passing following List which consists of CustomPair

List<CustomPair> notificationSettingsCustomPair = Arrays.asList(
        new CustomPair<>("campaignEvents", true),
        new CustomPair<>("drawResultEvents", true),
        new CustomPair<>("transactionEvents", true),
        new CustomPair<>("userWonEvents", true));

List can also have different shapes for example like this :

   List<CustomPair> notificationSettingsCustomPair = Arrays.asList(
        new CustomPair<>("campaignEvents", true),
        new CustomPair<>("transactionEvents", false));

Or like this, you get the idea it can be in any order, with any of these 4 different fields:

     List<CustomPair> notificationSettingsCustomPair = Arrays.asList(
        new CustomPair<>("transactionEvents", true));

Model for CustomPair :

public class CustomPair<K, V> {
private K key;
private V value;
}

Model for NotificationSettingsDto :

@Builder
public class NotificationSettingsDto {

private Boolean campaignEvents;
private Boolean drawResultEvents;
private Boolean transactionEvents;
private Boolean userWonEvents;
}


texts: Simple winform that randomizes images in a picturebox

texts:
I wrote this code for a simple app that gives us random images. The code works, but I feel like I'm doing something wrong. And one thing I would love to know is instead of grabbing from a folder called "resources", we would actually grab from a custom folder inside my exe. So there's no need to add any folder to a different computer, all works inside the exe.

Is that possible to do ?

I'm slowly learning C#. Thank you for your time in reading my post.

P.S I'm very new in using the Lambda expression.

 public partial class Menu : Form
{
    private string[] files;
    private string[] files2;
    private string[] files3;
    private string[] files4;
    private int currentIndex = 0;
    private int currentIndex2 = 0;
    private int currentIndex3 = 0;
    private int currentIndex4 = 0;
    Random rnd = new Random();

    public Menu()
    {
        InitializeComponent();
    }

    private void initializeImages()
    {
        string appRoot = System.IO.Path.GetDirectoryName(Application.ExecutablePath);
        files = System.IO.Directory.GetFiles(appRoot + @"\Resources");
        files2 = System.IO.Directory.GetFiles(appRoot + @"\Resources");
        files3 = System.IO.Directory.GetFiles(appRoot + @"\Resources");
        files4 = System.IO.Directory.GetFiles(appRoot + @"\Resources");
        files = files.OrderBy(x => rnd.Next()).ToArray();
        files2 = files.OrderBy(x => rnd.Next()).ToArray();
        files3 = files.OrderBy(x => rnd.Next()).ToArray();
        files4 = files.OrderBy(x => rnd.Next()).ToArray();
    }

    private void setImage()
    {
        pictureBox1.ImageLocation = files[currentIndex];
        pictureBox2.ImageLocation = files2[currentIndex2];
        pictureBox3.ImageLocation = files3[currentIndex3];
        pictureBox4.ImageLocation = files4[currentIndex4];
    }

    private void nextImage()
    {
        currentIndex = currentIndex < files.Length - 1 ? currentIndex + 1 : files.Length - 1;
        setImage();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        initializeImages();
        nextImage();
    }

}


texts:
This is my palindrome-checker that is doing what it should do. If you have any additional suggestions, please let me know.

# -*- coding: utf-8 -*-

def palindrome_verif():
    Mot = raw_input("Tapez votre mot \n")

    Comptage = len(Mot)
    Lett_Sep = list(Mot)
    Decompte = 0
    Der_Lett = Comptage

    if ((Comptage % 2) == 1):
        ImmPair = (Comptage / 2)+1
        #print(str(Decompte)," et ",str(Der_Lett))
        #print(str(Decompte)," et ",str(ImmPair))
        while Decompte < ImmPair:
            print(str(Decompte)," et ",str(Der_Lett))
            if Lett_Sep[Decompte] == Lett_Sep[Der_Lett-1]:
                print("Même lettre")
                Decompte += 1
                Der_Lett -= 1
            else:
                print("Ceci n'est pas un palindrome")
                return 0000
                #break
    elif ((Comptage % 2) == 0):
        Pair = Comptage / 2
        while Decompte < Pair:
            print(str(Decompte)," et ",str(Der_Lett))
            if Lett_Sep[Decompte] == Lett_Sep[Der_Lett-1]:
                print("Même lettre")
                Decompte += 1
                Der_Lett -= 1
            else:
                print("Ceci n'est pas un palindrome")
                return 0000
                #break


texts:
I have a solution, which compares 2 given strings and returns the number of total matching characters.

I know I haven't initialized the variables and arrays and that this (correctly) yields warnings. I know the variables aren't self-explanatory as they should be.

function commonCharacterCount($s1, $s2) {
    $a = (strlen($s1) > strlen($s2)) ? $s2 : $s1;
    $b = (strlen($s1) > strlen($s2)) ? $s1 : $s2;

    foreach(count_chars($a, 1) as $i => $v) {
        $c[chr($i)] = $v;
    }

    foreach (count_chars($b, 1) as $i => $v) {
        $d[chr($i)] = $v;
    }

    $t = 0;
    foreach($c as $k => $v) {
        if($c[$k] <= $d[$k]) {
            $t += $c[$k];
        } else {
            $t += $d[$k];
        }
    }
    return $t;
}

For instance, I have the two strings:

$s1 = "abacadeee"; and $s2 = "aabbccddee";, the expected output would be 7.

As required, this solution works so far and you can test it here:
sandbox

Which steps are unnecessary and how can I improve this algorithm?


texts: Given a list of coordinates check if 4 points make a line

texts:
I was doing some preparation for coding interviews and I came across the following question:

  Given a list of coordinates "x y" return True if there exists a line containing at least 4 of the points (ints), otherwise return False.

The only solution I can think about is in \$O(n^2)\$. It consist of calculating the slope between every coordinate: Given that if \$\frac{y_2-y_1}{x_2 –x_1} = \frac{y_3-y_2}{x_3-x_2}\$  then these three points are on the same line. I have been trying to think about a DP solution but haven't been able to think about one.

Here is the current code:

def points_in_lins(l):
    length = len(l)
    for i in range(0,length -1):
        gradients = {}
        for j in range(i+1, length):
            x1, y1 = l[i]
            x2, y2 = l[j]
            if x1 == x2:
               m = float("inf")
            else:
               m = float((y2 -y1) / (x2 - x1))
            if m in gradients:
                gradients[m] += 1
                if gradients[m] == 3:
                   return(True)
            else:
                gradients[m] = 1

    return(False)


texts: How to stop a Python script if the input values do not make sense within the environment in which they will be analyzed?

texts:
I am not a developer, but I needed to write a script.

So I wrote it. Since I can't find an accessible tool that fulfills the same purpose, which I think may be helpful to others, I decided to publish it: https://github.com/gabriel-de-luca/simil/blob/master/simil.py

I am open to review it completely, but I would particularly like to consult on the way I am checking the validity of the data.

The main function is called process and has two positional parameters: source_points and target points, of array_like (numpy) type.

The first thing I do is convert the inputs into numpy arrays and transpose them, because all the code requires one row per coordinate (X, Y and Z) and one column per point.

In addition to transposing it, I verify that it has three coordinates, and if it has just two coordinates I allow myself to fill the Z with zeroes.

import numpy as np

def _get_coords(points):
    coords = np.array(points, dtype=float, ndmin=2).T
    if coords.shape[0] != 3:
        if coords.shape[0] == 2:
            coords = np.concatenate((coords, np.zeros((1, coords.shape[1]))))
        else:
            raise
    return coords

def process(source_points, target_points, alpha_0=None, scale=True, lambda_0=1):
    """
    Find similarity transformation parameters given a set of control points
    """

    print('Processing...')

    # false outputs to return if an exception is raised

    false_lambda_i = 0
    false_r_matrix = np.array([[0, 0, 0],
                               [0, 0, 0],
                               [0, 0, 0]])
    false_t_vector = np.array([[0], [0], [0]])

    # checks

    try:
        source_coords = _get_coords(source_points)
    except:
        print('ERROR:\n' +
              f'source_points = {source_points}' +
              '\n could not be broadcasted as a numerical array' +
              '\n with shape = (n, 3).')
        return false_lambda_i, false_r_matrix, false_t_vector

Then, the code continues to do other checkups, and if everything goes well, it returns valid values in the output variables:

    print('Done.')

    return lambda_i, r_matrix, t_vector

If I did not do this check, many errors of different types could occur in other private functions when the data is processed.

I run this script from other scripts, and this is what happens if I send invalid data:

import simil

source_points = [[0]]

target_points = [[1]]

m, r, t = simil.process(source_points, target_points)

print('\nm value returned = ' + str(m))

Returns:

Processing...
ERROR:
source_points = [[0]]
 could not be broadcasted as a numerical array
 with shape = (n, 3).

m value returned = 0

It works fine to me, because I can check if m == 0 in the other script to stop it, but I am publishing my script and I don't know if this is the right way to handle the exception, or how to improve it.


texts:
I've been reading about pure methods and immutability in Java. I have a current application and want to convert all the methods to pure methods.

My app takes payment from users. I first create a payment in the DB:

Payment payment = new Payment();
payment = createPayment(orderId, status, address1, address2, country, state, price);

// createPayment() creates a row in the database table, saving orderId, status, address1, address2, country, state, price
// state is the inital state of the payment, in this cased INITIATED
createPayment() returns a Payment model

// make the payment with the payment processor
PaymentResult paymentResult = paymentService.pay(payment);

PaymentResult contains properties such as authCode, pspReference, resultCode, refusalReason.

The Payment model also contains authCode etc. properties. I now want to update my Payment model, including its status. I currently have:

paymentService.updatePaymentFromPaymentResultOnAuthorise(paymentResult, payment);

And updatePaymentFromPaymentResultOnAuthorise is:

public void updatePaymentFromPaymentResultOnAuthorise(PaymentResult paymentResult, Payment payment) throws PaymentException {

    try {

        boolean success = !isNullOrEmpty(paymentResult.getAuthCode());

        if (success) {
            payment.setLastStatus(payment.getStatus());
            payment.setStatus(PaymentStatus.PAID);
        }

        payment.setPspReference(paymentResult.getPspReference());
        payment.setAuthCode(paymentResult.getAuthCode());
        payment.setResultCode(String.valueOf(paymentResult.getResultCode()));
        payment.setRefusalReason(paymentResult.getRefusalReason());

        paymentDAO.updatePayment(payment);

    } catch (Exception e) {
        throw new PaymentException(String.format("there was an error updating the payment with paymentId %s", payment.getId()));
    }
}

As you can see, updatePaymentFromPaymentResultOnAuthorise is not a pure method as it changes the argument payment. This pattern is repeated throughout the app.

Is the only way to make this method pure to create a copy of payment within updatePaymentFromPaymentResultOnAuthorise and return this new object? This seems expensive and it will need to be done in many places throughout my app. But is that my only option?


texts:
pointer_traits is a lightweight trait that provides a uniform interface to builtin pointers and user-defined fancy pointers. That said, things like element_type require
template metaprogramming techniques to determine. This makes pointer_traits a good exercise.

Here's my re-implementation under the name my_std::pointer_traits, put in a separate header pointer_traits.hpp because <memory> is way too comprehensive:

// C++17 pointer_traits implementation

#ifndef INC_POINTER_TRAITS_HPP_60HzB0lbek
#define INC_POINTER_TRAITS_HPP_60HzB0lbek

#include <cstddef>     // for std::ptrdiff_t
#include <memory>      // for std::addressof
#include <type_traits> // for std::add_lvalue_reference

namespace my_std {

  template <class Ptr>
  struct pointer_traits;

  namespace pt_detail {

    template <class Tmpl>
    struct get_first_param { };
    template <template <class, class...> class Tmpl, class T, class... Args>
    struct get_first_param<Tmpl<T, Args...>> {
      using type = T;
    };
    template <class Tmpl>
    using get_first_param_t = typename get_first_param<Tmpl>::type;

    template <class Tmpl, class U>
    struct rebind_first_param { };
    template <template <class, class...> class Tmpl, class T, class... Args, class U>
    struct rebind_first_param<Tmpl<T, Args...>, U> {
      using type = Tmpl<U, Args...>;
    };
    template <class Tmpl, class U>
    using rebind_first_param_t = typename rebind_first_param<Tmpl, U>::type;

    template <class Ptr>
    auto element(int) -> typename Ptr::element_type;
    template <class Ptr>
    auto element(long) -> get_first_param_t<Ptr>;

    template <class Ptr>
    auto diff(int) -> typename Ptr::difference_type;
    template <class Ptr>
    auto diff(long) -> std::ptrdiff_t;

    template <class Ptr, class U>
    auto rebind(int) -> typename Ptr::template rebind<U>;
    template <class Ptr, class U>
    auto rebind(long) -> rebind_first_param_t<Ptr, U>;

  }

  template <class Ptr>
  struct pointer_traits {
    using pointer = Ptr;
    using element_type = decltype(pt_detail::element<Ptr>(0));
    using difference_type = decltype(pt_detail::diff<Ptr>(0));

    template <class U>
    using rebind = decltype(pt_detail::rebind<Ptr, U>(0));

    static pointer pointer_to(std::add_lvalue_reference<element_type> r)
    {
      return Ptr::pointer_to(r);
    }
  };

  template <class T>
  struct pointer_traits<T*> {
    using pointer = T*;
    using element_type = T;
    using difference_type = std::ptrdiff_t;

    template <class U>
    using rebind = U*;

    static pointer pointer_to(std::add_lvalue_reference<element_type> r)
    {
      return std::addressof(r);
    }
  };

}

#endif

I used N4659 as a reference.


texts:
While implementing auto refreshing div in jQuery that fetches updates on posts periodically as can be seen on Twitter, Facebook etc.

I had to think about making the refresh as efficient as possible. I decided to send a request to the server every 30 seconds - 1 minute. And, the request will be sent only if the browser window is active.

var postUpdateIntervalID;
var interval = 30000;

$(window).load(function(){
    if (!postUpdateIntervalID) {
        postUpdateIntervalID = setInterval(function() {
            updatePostsList();
        }, interval);
    }
});

$(window).focus(function(){
    if (!postUpdateIntervalID) {
        updatePostsList();
        postUpdateIntervalID = setInterval(function() {
            updatePostsList();
        }, interval);
    }
});

$(window).blur(function() {
    clearInterval(postUpdateIntervalID);
    postUpdateIntervalID = 0;
});

function updatePostsList() {
    // Sends a request to the server to fetch new posts.
}

On load, set interval of 30 seconds to call updatePostsList.
On focus, call updatePostsList immediately. Then, set interval as above.
On blur, reset the interval.


texts:
I wrote a simple multithread server to use as a base class for other different types of multithread servers. I haven't had a lot of opportunities to get code critique from other people, so I wanted to post here to see how much coding style was. Any constructive feedback on how to improve my code would be appreciated! I'm personally looking more for code style and quality rather than compilability (since it does compile and work)

define.h

#pragma once

#define DEBUG
#ifndef DEBUG
#define _(x)
#else
#define _(x) x
#endif

Server.h

#pragma once

#include <iostream>
#include <netinet/in.h>
#include <unistd.h>
#include <string.h>
#include <thread>
#include <map>
#include "define.h"

class Server{
    private:
        virtual void handle_connection(int sockfd);
    public:
        Server() {}
        void initialize(int port);
        void start_listening(int socket);
        void authenticate(int sockfd);
        void sendMessage(int sockfd, std::string prompt);
        ~Server() {}
};

Server.cpp

#include "server.h"

void Server::initialize(int port){
    int sockfd;
    struct sockaddr_in serv_addr;

    //Create socket
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if(sockfd < 0){
        perror("Error: Failed to initialize socket.\n");
        exit(1);
    }

    //Bind socket
    bzero((char *) &serv_addr, sizeof(serv_addr));
    serv_addr.sin_family        = AF_INET;
    serv_addr.sin_port      = htons(port);
    serv_addr.sin_addr.s_addr   = INADDR_ANY;
    if(bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0){
        perror("Error: Failed to bind socket to address.\n");
        exit(1);
    }

    start_listening(sockfd);
    return;
}

void Server::start_listening(int socket){
    while(1){
        int newsockfd = -1;
        struct sockaddr_in cli_addr;
        socklen_t clilen = sizeof(cli_addr);

        listen(socket, 5);
        newsockfd = accept(socket, (struct sockaddr *) &cli_addr, &clilen);

        if(newsockfd < 0){
            perror("Error: Failed to connect to incoming connection.\n");
        }

        //Start new thread to handle request
        std::thread t1 (&Server::handle_connection, this, newsockfd);
        t1.detach();
    }
}

void Server::handle_connection(int sockfd){
    char buffer[256];
    std::string response = "Thank you for your response.\n";
    const char* responseChar = response.c_str();
    authenticate(sockfd);
    while(recv(sockfd, buffer, 255, 0) > 0){
        std::cout << buffer;
        send(sockfd, (void*)responseChar, strlen(responseChar), MSG_NOSIGNAL);
        bzero(buffer, 256);
    }
    close(sockfd);
    return;
}

void Server::sendMessage(int sockfd, std::string prompt){
    const char * promptChar = prompt.c_str();
    send(sockfd, (void*)promptChar, strlen(promptChar), MSG_NOSIGNAL);
}


texts:
I just finished this code for my own practice purpose.  This code works just fine but I understand there still a lot insidious problems.  Any advice for improvement would be appreciated.  So here it goes:

Package DS;

import java.util.*;

public class basic_Array {

public static void main(String[] args) {

    int option;

    System.out.println("Welcome to basic array test, please choose your testing subject: ");

    Scanner user_option = new Scanner(System.in);

    do{

        System.out.println("Option 1: Simple one dimensional array.");
        System.out.println("Option 2: Simple two dimensional array. (under construction)");
        System.out.println("Option 0: Exit program");

        option = user_option.nextInt();
        System.out.println("current option is: " + option);

        switch(option){

        case 1:
            //simple array input method
            simple_a1();
            break;
        case 2:
            simple_a2();
            break;
        }

    }while(option != 0);

    System.out.println("Program terminated...");
    user_option.close();

}

private static void simple_a1() {

    int[] a1 = new int[5];

    int in_num;                                                             //redundant but clear.

    Scanner user_input = new Scanner(System.in);

    for(int i = 0; i < 5; i++){

        System.out.println("Request input for item " + i);
        in_num = user_input.nextInt();
        a1[i] = in_num;
        System.out.println("Got it, next one ");
    }

    System.out.println("The numbers in a1 are: ");

    for(int i2: a1){
        System.out.print(i2 + " ");
    }

    System.out.println("\nEnd of testing 1, back to main menu...");

}

private static void simple_a2() {

    System.out.println("This function still under construction, back to main menu...");
}

}

Edit in 2/26/2017:

Thanks for EBrown and others input, I've modified my program structure and added a few new functions.

I also have a question on multiple scanners I've put in my program. I did some search on it and many people says this is also a bad practice that may confuse the programmer in long run.  I think it cause the error when I trying to close the scanner object in simple_a1 method, so I only close the user_option scanner (located in main method).  So my question is: will it still cause resource leak?


texts: Error handling in express without middlewares and using class structure

texts:
This is a simple implementation of Django's sample project "Poll" using and express.

The controller code:

export default class AuthController {
    private db: AuthDb;

    constructor(db: AuthDb) {
        this.db = db;
    }

    login = async (user: User) => {
        try {
            userValidator(user);
            const { username, password } = user;
            const originalUser = await this.db.getUser(username);
            await checkPassword(password, originalUser.password);
            const token = createToken(originalUser.id);
            return ResourceRetrieved({ token });
        } catch (err) {
            return errorHandler(err);
        }
    };

    register = async (user: User) => {
        try {
            userValidator(user);
            const userToCreate = await getHashedUser(user);
            await this.db.createUser(userToCreate);
            return ResourceCreated('User');
        } catch (err) {
            return errorHandler(err);
        }
    };
}

Each method receives the input, and runs validation logic that is outside of the Controller class, each of them can throw a predefined error object that are handled by the errorHandler() function, the Controller class just executes the steps of the action, but it doesn't know what kind of errors can happen.

ErrorHandler method

export default function errorHandler(err: ApiResponse) {
    // Checks if err is not an Api Response
    if (err.code == null || err.data == null) {
        return InternalServerError;
    }
    return err;
}

It just checks for unexpected errors, returning a Internal Server Error if the error is not an ApiResponse object.

For example, the checkPassword method:

async function checkPassword(password: string, hash: string) {
    const isPasswordRight = await compare(password, hash);
    if (!isPasswordRight) {
        throw Forbidden('Wrong password');
    }
}

The Forbidden object code

const Forbidden = (msg: string) => ({
    code: 403,
    data: {
        error: {
            type: 'forbidden',
            msg
        }
    }
});

The database is treated the same way

export default class AuthDb {
    createUser = async (user: User) => {
        try {
            const { password, username } = user;
            await query(createUserSQL, [username, password]);
            return;
        } catch (err) {
            if ((err.code = '23505')) {
                throw Forbidden('Username already in use');
            }
            throw InternalServerError;
        }
    };

    getUser = async (username: string) => {
        const { rows } = await query(getUserSQL, [username]);
        if (rows.length === 0) {
            throw ResourceNotFound('user');
        }
        return rows[0] as User;
    };
}

Database errors are handled and re-trowed as a recognized error object rather than
PostgreSQL default error objects so the controller method does not need to know what happens in the database class.

All errors are sent as responses and they all have the same pattern, with a status code and a data object.

The AuthHandler class is just a adapter for express and AuthController

export default class AuthHandler {
    private controller: AuthController;

    constructor(controller: AuthController) {
        this.controller = controller;
    }

    login = async (req: Request, res: Response) => {
        const { body } = req;
        const result = await this.controller.login(body);
        return handleResult(result, res);
    }

    register = async (req: Request, res: Response) => {
        const { body } = req;
        const result = await this.controller.register(body);
        return handleResult(result, res);
    }
}

It receives the output of controller's methods and returns a response regardless of being an error or a normal response.

Is is an usual solution for error handling?, i'm in doubt if it is easy to comprehend and maintainable.


texts:
I'm currently using a scientific information management system that employs a RESTful API. I've never used this API with PHP, and I had a hard time finding best practice examples online. After some reading and experimenting, I came up with the following proof-of-concept procedure to retrieve data from the API and then upload the XML object, slightly modified, in order to change information in the system.

I'm most concerned with PHP best practices here: is my PHP efficient, robust, and secure? Is there any code I can remove or make more efficient? I'm using PHP v5.3.8

<!DOCTYPE html>

<?php
$uriPrefix = 'http://[user:pass]@[path_to_web_app:port]/api/v2/';

//Open up a connection to the API
//for the container:
$containerSuffix = 'containers/27-95';
$containerUri = $uriPrefix . $containerSuffix;
$containerCurl = curl_init($containerUri);

//for the sample:
$sampleSuffix = 'samples/DOR6A12';
$sampleUri = $uriPrefix . $sampleSuffix;
$sampleCurl = curl_init($sampleUri);

//API-specific settings
curl_setopt($containerCurl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($sampleCurl, CURLOPT_RETURNTRANSFER, true);

//get the yummy data
$containerResult = curl_exec($containerCurl);
$containerXml = new SimpleXMLElement($containerResult);
$sampleResult = curl_exec($sampleCurl);
$sampleXml = new SimpleXMLElement($sampleResult);

//close the API connection
curl_close($containerCurl);
curl_close($sampleCurl);

echo '
Some XML for a LIMS Container:
';
echo htmlentities($containerXml->asXML());
echo '
Some XML for a LIMS Sample:
';
echo htmlentities($sampleXml->asXML());

//Now let's infer the project ID for the sample from the XML result
$limsId = $sampleXml->project['limsid'];
echo "
The project ID for the sample is $limsId
";

//Now let's change the sample name
$newName = 'New Sample Name';
$oldName = (string)$sampleXml->name;
$sampleXml->name = $newName;

$changeSampleCurl = curl_init($sampleUri);
curl_setopt($changeSampleCurl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($changeSampleCurl, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($changeSampleCurl, CURLOPT_POSTFIELDS,$sampleXml->asXML());

$changeSampleResult = curl_exec($changeSampleCurl);
echo '
The submitted XML
';
echo htmlentities($changeSampleResult);

curl_close($changeSampleCurl);

echo "
The old sample name was $oldName
";
echo "
It should now be $newName
";
?>


texts:
I've written this JQuery program for checking whenever caps lock is turned on.

$("input[type='password']").keypress(function(e) {
    var kc = e.which; //get keycode
    var isUp = (kc >= 65 && kc <= 90) ? true : false; // uppercase
    var isLow = (kc >= 97 && kc <= 122) ? true : false; // lowercase
    // event.shiftKey does not seem to be normalized by jQuery(?) for IE8-
    var isShift = ( e.shiftKey ) ? e.shiftKey : ( (kc == 16) ? true : false ); // shift is pressed

    // uppercase w/out shift or lowercase with shift == caps lock
    if ( (isUp && !isShift) || (isLow && isShift) ) {
        capLock(); // alerts "CAPSLOCK is ON"
    }

});
function capLock() {
 alert('CAPSLOCK is ON');
}


texts: Binary permissions system with bitwise operators + properties

texts:
I've written a simple permissions system that I need to be rather fast, yet useable by other developers who primarily use Java. Is a bitwise permissions system with properties a good compromise. Any suggested speed improvements would be greatly appreciated.

class AppliancePerms(object):
    """Permissions for the Appliance class."""
    _cmd_right = 2 ** 0
    _rest_right = 2 ** 1
    _ssh_right = 2 ** 2
    _num_of_rights = 3

    _all_rights = _cmd_right + _rest_right + _ssh_right

    def __init__(self, perm_digits=None):
        # default to all rights
        if perm_digits is None:
            self._perms = AppliancePerms._all_rights
        else:
            self._perms = perm_digits

    @property
    def permissions(self):
        # zfill to show the total number of permissions even when left most right isn't True
        return bin(self._perms)[2:].zfill(AppliancePerms._num_of_rights)

    @permissions.setter
    def permissions(self, perm_digits):
        """
        Set all permissions at once with a number.
        Suggested syntax is AppliancePermOInst.permissions(int('111', 2))
        """
        self._perms = perm_digits

    @permissions.deleter
    def permissions(self):
        self._perms = 0

    @property
    def rest(self):
        return self._perms & AppliancePerms._rest_right

    @rest.setter
    def rest(self, boolean):
        if boolean:
            self._perms |= AppliancePerms._rest_right
        else:
            del self.rest

    @rest.deleter
    def rest(self):
        if self._perms & AppliancePerms._rest_right:
            self._perms -= AppliancePerms._rest_right

    @property
    def ssh(self):
        return self._perms & AppliancePerms._ssh_right

    @ssh.setter
    def ssh(self, boolean):
        if boolean:
            self._perms |= AppliancePerms._ssh_right
        else:
            del self.ssh

    @ssh.deleter
    def ssh(self):
        if self._perms & AppliancePerms._ssh_right:
            self.perms -= AppliancePerms._ssh_right

    @property
    def cmd(self):
        return self._perms & AppliancePerms._cmd_right

    @cmd.setter
    def cmd(self, boolean):
        if boolean:
            self._perms |= AppliancePerms._cmd_right
        else:
            del self.cmd

    @cmd.deleter
    def cmd(self):
        if self._perms & AppliancePerms._cmd_right:
            self._perms -= AppliancePerms._cmd_right


texts:
I have been using Scala as a means to learn Functional Programming and writing better code. However, I have some questions regarding some exercises or if there's a better way to approach them.

In the exercises below, I have already defined the functions foldLeft, foldRight,append, sum, product, head and tail.

  HARD - Write a function that concatenates a list of lists into a single list. Its runtime should be linear in the total length of all lists. Try to use functions we have already defined.

My solution:

//concatenates list of lists in a single list
def concatLists(x: List[List[Int]]):List[Int] = x.foldLeft( List[Int]() )( (x,y)=> x ++ y )

I have the feeling that the use of foldLeft and the concatenation operator is the right way to go and the runtime feels linear because we are appending one element at a time to the result of the fold, so the time is linear in the input size, am I right? Or is the ++ operator not efficient due to the List being implemented as a linked list? If not, how can I improve this?

  EXERCISE 16: Write a function that transforms a list of integers by adding 1
  to each element. (Reminder: this should be a pure function that returns a new
  List !)

//Adds one - exercise 16
def add1(x:List[Int]):List[Int]= for(elem <- x) yield elem+1

  EXERCISE 18: Write a function map , that generalizes modifying each element in a list while maintaining the structure of the list. Here is its signature: def map[A,B](l: List[A])(f: A => B): List[B]

//implements map - exercise 18
def map[A,B](l: List[A])(f: A => B): List[B]=for(elem <- l) yield f(elem)

I've used yield before in some "toy exercises" in sites like hackerrank and similar and from my understanding, it is used in sequence comprehensions and adds a new element to the resulting sequence, much like in Python and the sequence assumes the return type declared in the function signature, is this correct?

What I want to know is if these implementations are correct in functional terms or if there are other/better ways of writing them.


texts:
I'm working on figuring out what the current 'business' day of the month it is. For instance, if it's the 20th, but there are 3 weekends, it would be the 14th business day of the month.

Is there a better way of doing this?

var first = DateTime.Today.FirstDayOfMonth();
var businessDayOfMonth = 0;
for (var i = first; i <= DateTime.Today; i = i.AddDays(1))
{
    if (i.DayOfWeek != DayOfWeek.Saturday && i.DayOfWeek != DayOfWeek.Sunday)
        businessDayOfMonth++;
}


texts: EF6 Code First unit of work pattern with IoC/DI

texts:
I'm trying to implement the unit of work pattern with dependency injection / inversion of control and entity framework version 6.1.1 Code First, in an asp.net-mvc project.

public interface IGenericRepository<T> : where T : class
{
    IQueryable<T> AsQueryable();

    IEnumerable<T> GetAll();
    IEnumerable<T> Find(Expression<Func<T, bool>> predicate);
    T Single(Expression<Func<T, bool>>  predicate);
    T SingleOrDefault(Expression<Func<T, bool>> predicate);
    T First(Expression<Func<T, bool>> predicate);
    T GetById(int id);

    void Add(T entity);
    void Delete(T entity);
    void Attach(T entity);
}

public interface IUnitOfWork : IDisposable
{
    IGenericRepository<Order> OrderRepository { get; }
    IGenericRepository<Customer> CustomerRepository { get; }
    IGenericRepository<Employee> EmployeeRepository { get; }

    void Commit();
}

public class EfUnitOfWork : DbContext, IUnitOfWork
{
    private readonly EfGenericRepository<Order> _OrderRepo;
    private readonly EfGenericRepository<Customer> _customerRepo;
    private readonly EfGenericRepository<Employee> _employeeRepo;

    public DbSet<Order> Orders { get; set; }
    public DbSet<Customer> Customers { get; set; }
    public DbSet<Employee> Employees { get; set; }

    public EfUnitOfWork()
    {
        _orderRepo = new EfGenericRepository<Order>(Orders);
        _customerRepo = new EfGenericRepository<Customer>(Customers);
        _employeeRepo = new EfGenericRepository<Employee>(Employees);
    }

    #region IUnitOfWork Implementation

    public IGenericRepository<Order> OrderRepository
    {
        get { return _orderRepo; }
    }

    public IGenericRepository<Customer> CustomerRepository
    {
        get { return _customerRepo; }
    }

    public IGenericRepository<Employee> EmployeeRepository
    {
        get { return _employeeRepo; }
    }

    public void Commit()
    {
        this.SaveChanges();
    }

    #endregion
}

public class EfGenericRepository<T> : IGenericRepository<T>
                                      where T : class
{
    private readonly DbSet<T>_dbSet;

    public EfGenericRepository(DbSet<T> dbSet)
    {
        _dbSet = dbSet;
    }

    #region IGenericRepository<T> implementation

    public virtual IQueryable<T> AsQueryable()
    {
        return _dbSet.AsQueryable();
    }

    public IEnumerable<T> GetAll()
    {
        return _dbSet;
    }

    public IEnumerable<T> Find(Expression<Func<T, bool>> predicate)
    {
        return _dbSet.Where(predicate);
    }

    // And so on ...

    #endregion
}

And this is how I'm using it in a controller:

public HomeController(IUnitOfWork unitOfWork) { ..... }

But I've read that EF6 already has Unit of Work out of the box. How would that fit in this picture?

Also, with which dependency injector should I go with?


texts: Calculate percentage based on dummy variable in Pandas

texts:
Today I had a simple task: I have products, quantities and a dummy, and I needed to know which percentage of the total quantities of that product the dummy represented. My DataFrame looked like this:

Product    Qty    Dummy
   A        10      0
   B        15      0
   B        5       1
   C        5       0
   D        5       0
   D       20       1

And I needed to get there:

Product    Qty_pct
   B        0.25
   D        0.8

So, I only needed the percentage when the dummy takes value = 1

I managed to do it, like this:

df2=df.pivot_table(columns='Dummy',index='Product',aggfunc='sum',values=['Qty']).reset_index()
df2['Qty_pct']=df2['Qty'][1]/(df4['Qty'][1]+df2['Qty'][0])
df2.columns=df2.columns.get_level_values(0)

To me it seems like a very indirect way to achieve my goal and I feel this can be done in a way more elegant way. What would you do?


texts:
I try to create a private chat with Python but I don't know best practice.

It's only for study purpose, I'd like understand the logic behind a simple private chat with socket and the best mode to implement it with no framework.

For now, It's not important to check for example if username has > or other, only socket procedure and send messages to specific client.

This is my code for client:

import socket
from thread import *
from time import sleep
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('127.0.0.1', 8889))
u = raw_input('Username: ')
print 'To send: recipient>message'
def se(s):
    while 1:
        s.send(u + '>' + raw_input())
        print s.recv(1024)
def re(s):
    while 1:
        s.send(u + '>show>')
        r = s.recv(1024)
        if r != 'No messages':
            print r
        sleep(0.05)
start_new_thread(se ,(s,))
start_new_thread(re ,(s,))
while 1:
    pass

and server:

import socket
from thread import *
import string
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('127.0.0.1', 8889))
s.listen(10)
c = {}
def clientthread(conn):
    while 1:
        data = conn.recv(1024)
        e = data.split('>')
        if len(e) == 3:
            if e[1] == 'show':
                try:
                    m = ''
                    for i in range(0, len(c[e[0]])):
                        m = m + c[e[0]][i]
                        if i != (len(c[e[0]])-1):
                            m = m + '\n'
                        if m == '':
                            data = 'No messages'
                        else:
                            data = m
                    del c[e[0]]
                except:
                    data = 'No messages'
            else:
                try:
                    c[e[1]]
                except:
                    c[e[1]] = []
                c[e[1]].append(e[0]+'>'+e[2])
                data = 'Ok'
        else:
            data = 'Error'
        conn.send(data)
    conn.close()
while 1:
    conn, addr = s.accept()
    start_new_thread(clientthread ,(conn,))
s.close()

With this code every user can send and recive messages.
For example if there are 2 users (2 clients with server active): max and paul; if max writes paul>hello paul recives max>hello.

Program uses dictionary and lists for send message to particular client.
I don't know if this way is correct.


texts: A class with a function pointer instead of a generator

texts:
I am building TiKZ files, one pdf for each image I have. The purpose is to add text to each separately. The images are legion, so I created a script to generate the text files instead of generating each TeX using copy/paste.

So I created a tree mapping the section to the images.

This map is in the form of a YAML file I read using python.

chapters:
- ConfigurationAndOperation:
        sections:
            - StartupParameters:
                subsections:
                    - GeneralSettings:
                        subsubsections:
                            - SystemSettings:
                                images: [90]
                            - FacilitySettings:
                                images: [93]

And I iterate it and assemble the required information for each part in the following manner:

import ConversionLibrary.ConfigurationHandling as config
import collections

TexNode = collections.namedtuple('TexNode', "level name")
class TexElement(TexNode):
    __slots__ = ()
    def __str__(self):
        return str(self.level)+ " " + str(self.name)

class StubHandler(config.ConfigurationHandler):
    """ Handle the config file that indexes the images
    """

    def __init__(self, config_file, filesystem_hint = None, filesystem_folder = None):
        super(StubHandler, self).__init__(config_file, filesystem_hint, filesystem_folder)
        self.manual_levels = { 1 : 'chapters',
                               2 : 'sections',
                               3 : 'subsections',
                               4 : 'subsubsections',
                               5 : 'paragraphs' }
        self.images = 'images'
        self.elements = list()
        self.image_map = list()

    def BuildTexSkeletons(self):
        self.__iterate_tree(self.config, 1, None);

    def __iterate_tree(self, tree, level = 1, method_delegate = None):
        document_part = self.manual_levels[level]
        if document_part in tree:
            for element in tree[document_part]:
                element_name = element.iterkeys().next()
                element_values = element.itervalues().next()
                self.__process_element_parents(level, element_name)
                self.__process_level(element_name, element_values, level, method_delegate)

    def __process_level(self, current_name, element, level, method_delegate = None):
        if element:
            if self.images in element:
                if method_delegate is None:
                    print [self.elements, element[self.images]]
                else:
                    method_delegate([self.elements, element[self.images]])
            if level != 5:
                self.__iterate_tree(element, level+1, method_delegate)

    def __process_element_parents(self, level, current_element):
        if not self.elements:
            self.elements.append(TexElement(level, current_element))
        else:
            if level == self.elements[-1].level:
                del self.elements[-1]
            elif level < self.elements[-1].level:
                new_trim = (self.elements[-1].level - level) + 1
                del self.elements[-new_trim:]
            self.elements.append(TexElement(level, current_element))

if __name__ == "__main__":
TREST = StubHandler("SHELL.yml")
TREST.BuildTexSkeletons()

As you can see I am using a method delegate, this method delegate gets passed down to the __process_level method.

The line that calls the delegate is:

method_delegate([self.elements, element[self.images]])

This is the thing I will be using to assemble my TeX files.

What I would like to improve

I put a stop to this because I want to keep moving forward. But something is bothering me.

Is there a way to implement this with a generator and that the iteration returns the same [self.elements, element[self.images]]?

I think with a generator it would be cleaner, since I could use the StubHandler in another higher level that has the Output methods.


texts:
I am trying to fill values based on group, in my case id. I would like to fill the missing values according to the available date info for each id.

   id  date
1   1 23-04
2   1 23-04
3   1  <NA>
4   1  <NA>
5   2 24-04
6   2  <NA>
7   2  <NA>
8   2  <NA>
9   3 23-04
10  3  <NA>
11  3  <NA>
12  3  <NA>
13  4  <NA>
14  4  <NA>
15  4  <NA>
16  4  <NA>

What I need is:

    id  date
1   1 23-04
2   1 23-04
3   1 23-04
4   1 23-04
5   2 24-04
6   2 24-04
7   2 24-04
8   2 24-04
9   3 23-04
10  3 23-04
11  3 23-04
12  3 23-04
13  4  <NA>
14  4  <NA>
15  4  <NA>
16  4  <NA>

I figured out a loop, but I would like to avoid it because my data has 23 millions rows:

for(i in 2:nrow(dta)){
  if(dta$id[i-1] == dta$id[i])
  {
    dta$date[i] = dta$date[i-1]
  }
}

I cannot figure out how to translate this into dplyr syntax:

dta = structure(list(id = structure(c(1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L,
3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L), .Label = c("1", "2", "3", "4"
), class = "factor"), date = structure(c(1L, 1L, 1L, 1L, 2L,
2L, 2L, 2L, 1L, 1L, 1L, 1L, NA, NA, NA, NA), .Label = c("23-04",
"24-04"), class = "factor")), .Names = c("id", "date"), row.names = c(NA,
-16L), class = "data.frame")


texts: Is this a good way of writing contains method in Java?

texts:
I want to check if the structure that I use contains an object. To do so I wrote the following contains method:

boolean contains(Topic t){
        if (t == null)
            return false;
        if (t.equals(root))
            return true;
        else
            return false;
    }

Is this a good way of writing? Is it better to write:

boolean contains(Topic t){
        if (t == null)
            return false;
        if (t.x == root.x && t.y == root.y)
            return true;
        else
            return false;
    }


texts: Avoiding code duplication for reading in similar values for each derived class

texts:
I am designing a program that handles many types of grooves TKY, VSingle under GrooveType.

Each of this groove is paired with its specific parameter SimulationParam (e.g. TKY will pair with SimulationParamTKY, which inherits from SimulationParam) under the Dictionary simParams. As such, if i want to include more types of grooves, I can add it under this dictionary.

SimulationParam contains ProcessParam, which has the parameters probeStartAngle and probeStartDist. These parameters are similar(in meaning) for both TKY and VSingle.

However, in the dialog, I want the user to be able to select which particular groove they want. When that particular option is selected, the respective values for probeStartAngle and probeStartDist is read in from their respective text box. For example, if Use TKY is selected, the ProcessParam.probeStartAngle value will be read from tbTKYStartAngle.

As such, when I extend this program to even more grooves (say 10 more), under btnProcess_Click(), a lot of code will actually be repeated.

Is there a better way to write this code to reduce the repetitions? Assuming the requirement is that the textboxes for each groove cannot be merged into a single one. (i.e. meaning i cannot read from the same textbox for say ProcessParam.probeStartAngle)

public partial class GrooveDialog : Form
    {
        public enum GrooveType : int
        {
            TKY = 0,
            VSingle = 1,
        }

        Dictionary<GrooveType, SimulationParam> simParams = new Dictionary<GrooveType, SimulationParam>();

        public GrooveDialog()
        {
            simParams.Add(GrooveType.TKY, new SimulationParamTKY());
            simParams.Add(GrooveType.VSingle, new SimulationParamVSingle());
        }

        private void btnProcess_Click(object sender, EventArgs e)
        {
            if (rbUseTKY.Checked)
            {
                var simParamTKY = (SimulationParamTKY)simParams[GrooveType.TKY];

                simParamTKY.processParam.probeStartAngle = Convert.ToDouble(tbTKYAngle.Text);
                simParamTKY.processParam.probeStartDist = Convert.ToDouble(tbTKYDist.Text);
            }
            else if (rbUseVSingle.Checked)
            {
                var simParamVSingle = (SimulationParamVSingle)simParams[GrooveType.VSingle];

                simParamVSingle.processParam.probeStartAngle = Convert.ToDouble(tbVSingleAngle.Text);
                simParamVSingle.processParam.probeStartDist = Convert.ToDouble(tbVSingleDist.Text);
            }
    }

public class ProcessParam
    {
        public ProcessParam() { }
        public double probeStartAngle { get; set; }
        public double probeStartDist { get; set; }
    }

    public class SimulationParam
    {
        public ProcessParam processParam { get; set; }
    }

    public class SimulationParamTKY : SimulationParam
    {
        public double alpha, theta;

        public SimulationParamTKY()
        {
            this.processParam = new ProcessParam();
        }

        public SimulationParamTKY(ProcessParam parameters)
            : this()
        {
            this.processParam = parameters;
        }
    }

    public class SimulationParamVSingle : SimulationParam
    {
        public double deta, eta;

        public SimulationParamVSingle()
        {
            this.processParam = new ProcessParam();
        }

        public SimulationParamVSingle(ProcessParam parameters)
            : this()
        {
            this.processParam = parameters;
        }
    }


texts:
I'm try to get the public IP address from my FreeBSD machine and use it for the rest of my code.

Is this implementation good? Can it be optimized more? Can you see some gaps here? Something that maybe sometimes will throw an error?

GET.CPP

    char g_szPublicIP[16] = "0";
    char g_szInternalIP[16] = "0";

bool GetIPInfo()
{
    struct ifaddrs* ifaddrp = NULL;

    if (0 != getifaddrs(&ifaddrp))
    {
        return false;
    }

    for( struct ifaddrs* ifap = ifaddrp ; NULL != ifap ; ifap = ifap->ifa_next )
    {
        struct sockaddr_in * sai = (struct sockaddr_in *) ifap->ifa_addr;

        if (!ifap->ifa_netmask ||  // ignore if no netmask
                sai->sin_addr.s_addr == 0 || // ignore if address is 0.0.0.0
                sai->sin_addr.s_addr == 16777343) // ignore if address is 127.0.0.1
        {
            continue;
        }

        char * netip = inet_ntoa(sai->sin_addr);

        if (!strncmp(netip, "10.", 3))
        {
            strlcpy(g_szInternalIP, netip, sizeof(g_szInternalIP));
            fprintf(stderr, "INTERNAL_IP: %s interface %s\n", netip, ifap->ifa_name);
        }
        else if (g_szPublicIP[0] == '0')
        {
            strlcpy(g_szPublicIP, netip, sizeof(g_szPublicIP));
            fprintf(stderr, "PUBLIC_IP: %s interface %s\n", netip, ifap->ifa_name);
        }
    }

    freeifaddrs( ifaddrp );

    if (g_szPublicIP[0] != '0')
    {
        return true;
    }
    else
    {
        return false;
    }
}

    int main()
    {
        if (!GetIPInfo()) // Check is getIpInfo
        {
            fprintf(stderr, "Can not get public ip adress (1)-GetIpInfo\n");
            exit(1);
        }

        if(g_szPublicIP[0] == '0') // Check is
        {
            fprintf(stderr, "Can not get public ip address (2)-EndGetIpInfo\n");
            exit(1);
        }
    }


texts: Performance of List representation of MonadPlus versus Tree representation

texts:
I am working on a code where I represent a MonadPlus using a Tree data structure and then explore it, summing over all of the leaves (whose type must be an instance of Monoid);  I need to use a Tree representation to do this (rather than using the List representation) because as I explore the tree I want to manually keep track of things like my position in the Tree for checkpointing and workload balancing purposes.

My problem is that using a Tree data structure is slower than using the List data structure by a factor of ~ 4 for small depths (~ 1-10) and ~ 2.5 for higher depths (~15), and I am having trouble understanding exactly why this is;  in particular I am wondering if there are tricks that I can employ to make my code faster.

The remainder of this question will be some code that I wrote to benchmark Tree versus List. I will present my code in sections.  First, the prelude:

{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}

import Control.DeepSeq
import Control.Monad
import Control.Monad.Operational

import Criterion.Main

import Data.Functor.Identity
import Data.Monoid

My Tree type is defined using functionality in the operational package by specifying the type of instructions and then use operational to obtain a Program monad from this.

data TreeTInstruction m α where
    Choice :: TreeT m α -> TreeT m α -> TreeTInstruction m α
    Null :: TreeTInstruction m α

newtype TreeT m α = TreeT { unwrapTreeT :: ProgramT (TreeTInstruction m) m α } deriving (Monad)

type Tree = TreeT Identity

instance Monad m => MonadPlus (TreeT m) where
    mzero = TreeT . singleton $ Null
    left `mplus` right = TreeT . singleton $ Choice left right

The following two functions respectively build a perfect binary tree with Sum Int at all the leaves (which can be any type that is an instance MonadPlus) and explore a given Tree.

makeTree :: MonadPlus m => Int -> m (Sum Int)
makeTree 0 = return (Sum 1)
makeTree d = makeTree (d-1) `mplus` makeTree (d-1)

exploreTree :: Tree (Sum Int) -> Sum Int
exploreTree v =
    case view (unwrapTreeT v) of
        Return x -> x
        Choice left right :>>= k ->
            let x = exploreTree $ left >>= TreeT . k
                y = exploreTree $ right >>= TreeT . k
                xy = mappend x y
            in xy

As a technicality we need to write an instance of NFData for Sum Int for the benchmarking code.

instance NFData (Sum Int) where
    rnf s@(Sum x) = x `seq` s `seq` ()

Finally, we have the benchmarking code.  First, it benchmarks using makeTree to construct a tree using the List monad and then using mconcat to sum over all the results, and second, it benchmarks using makeTree using the Tree monad and sums over all the leaves using the exploreTree function.

main = defaultMain
    [bench "list" $ nf (mconcat . makeTree) depth
    ,bench "tree" $ nf (exploreTree . makeTree) depth
    ]
  where
    depth = 1 -- this is a knob that controls the tree size

For benchmarks, the list and tree times were as follows on my machine:

       List    Tree  Tree/List
 1:   140ns   460ns  3.3x
 2:   330ns  1300ns  4.0x
 4:  1600ns  6300ns  3.9x
 8:    32us   130us  4.0x
10:   150us   600us  4.0x
12:   990us  2900us  2.9x
14:   4.6ms    12ms  2.6x
16:    24ms    55ms  2.3x
17:    50ms   110ms  2.2x

(17 is the largest depth because after that exploring the list causes a stack overflow.)

If anyone has advice on exactly what the cause is of this slow down and if anything can be done about it then I would greatly appreciate it.


texts: Beginner user registration and login program

texts:
I'm new to coding and C++, this is one of my first pieces of "software". Could anyone give me some constructive criticism?

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

using namespace std;

bool IsLoggedIn()
{
    string user, pass, un, pw;
    cout << "Username: " << endl;
    cin >> user;
    cout << "Password: " << endl;
    cin >> pass;

    ifstream read(user + ".txt");
    getline(read, un);
    getline(read, pw);

    if (un == user && pw == pass)
        return true;
    else
        return false;

}

inline bool does_file_exist(const string& name)
{
    ifstream filename(name +".txt");
    if(!filename)
        return false;
    else
        return true;
}

int main()
{
    system("clear");

    int input;
    cout << "(1) Create Account \n" << "(2) Log in \n"<< "(3) Change password" << endl;
    cin >> input;
    if (input == 1 || input == 2 || input == 3)
    {
        if (input == 1)
        {
            system("clear");

            string user, pass;

            cout << "Create Account \n" << endl;
            cout << "Username: " << endl;
            cin >> user;

            if (does_file_exist(user))
            {
                cout << "Username already registered \n" << "Press enter to retry...";
                cin.ignore();
                cin.get();
                main();
            }

            cout << "Password: " << endl;
            cin >> pass;

            ofstream file;
            file.open(user + ".txt");
            file << user << endl << pass;
            file.close();

            main();
        }

        else if (input == 2)
        {
            system("clear");

            cout << "Log In \n" << endl;

            bool status = IsLoggedIn();

            if (!status)
            {
                cout << "Incorrect username or password!" << endl << "Press enter to retry...";
                cin.ignore();
                cin.get();
                main();
                return 0;
            }
            else
            {
                cout << "Successfully logged in!" << endl;
                cin.get();
                return 1;
            }

        }

        else if (input == 3)
        {
            system("clear");

            string user, pass;

            cout << "Change password \n" << endl;
            cout << "Username: " << endl;
            cin >> user;
            if (does_file_exist(user))
            {
                cout << "New Password: " << endl;
                cin >> pass;

                ofstream file;
                file.open(user + ".txt");
                file << user << endl << pass;
                file.close();

            main();
            }
            else
            {
                cout << "Username not registered \n" << "Press enter to retry...";
                cin.ignore();
                cin.get();
                main();
            }

        }
    }
    else
    {
        system("clear");
        cout << "Invalid input" << endl;
        main();
    }
}


texts:
Below are a collection of classes that compose my buff/debuff system. The largest flaw in my design that I couldn't overcome is the base class Effect having an enum filled with the different types of buffs and debuffs. If there is a workaround that could clean up that part of the code I'd be really grateful. Otherwise, I'm simply looking for suggestions on potential bugs, mishaps, inefficient methods, etc.

The base class for Effects

public abstract class Effect {

    public static enum Type { NIL, ATTACKBUFF, ATTACKBREAK, DEFENSEBUFF, DEFENSEBREAK }

    private Effect.Type type;

    public Effect(Effect.Type type) {

        this.type = type;

    }

    public abstract void apply();
    public abstract void expire();
    public abstract void update();

    public static Effect newEffect(Effect.Type type, Monster monster, int duration) {

        Effect effect;

        switch(type) {
        default:
        case NIL:
            effect = new NilEffect();
            break;
        case ATTACKBUFF:
            effect = new AttackBuff(monster, duration);
            break;
        case ATTACKBREAK:
            effect = new AttackBreak(monster, duration);
            break;
        case DEFENSEBUFF:
            effect = new DefenseBuff(monster, duration);
            break;
        case DEFENSEBREAK:
            effect = new DefenseBreak(monster, duration);
            break;
        }

        return effect;

    }

    public Effect.Type getType() {

        return type;

    }

}

A class for specific StatModifiers

abstract class StatModifier extends Effect {

    protected final Monster monster;
    protected final Stat originalStat;
    protected final Stat.Type statType;
    protected final double modifier;

    private int duration;

    public StatModifier(Monster monster, Effect.Type effectType, Stat.Type statType, double modifier, int duration) {

        super(effectType);

        this.monster = monster;
        this.statType = statType;
        originalStat = monster.getStat(statType);
        this.modifier = modifier;
        this.duration = duration;

    }

    @Override
    public void apply() {

        final int augmentedBaseStatValue = (int) Math.ceil(originalStat.getAugmentedStat() * modifier);
        final Stat stat = new Stat(augmentedBaseStatValue, 0, 0);
        monster.setStat(statType, stat);

    }

    @Override
    public void expire() {

        monster.setStat(statType, originalStat);

    }

    @Override
    public void update() {

        duration--;

        if(duration <= 0) {

            expire();

        }

    }

}

An example of a StatModifier class

public final class AttackBuff extends StatModifier {

    public AttackBuff(Monster monster, int duration) {

        super(monster, Effect.Type.ATTACKBUFF, Stat.Type.ATTACK, 1.5 ,duration);

    }

}

The Monster class (partial)

public class Monster {

    private final Map<Effect.Type, Effect> effects;

    public Monster() {

        effects = new HashMap<>();

    }

    public void addEffect(Effect.Type type, int duration) {

        if(effects.containsKey(type)) {

            effects.get(type).expire();
            effects.remove(type);

        }

        Effect effect = Effect.newEffect(type, this, duration);
        effect.apply();
        effects.put(effect.getType(), effect);

    }

    public void updateEffects() {

        effects.values()
               .parallelStream()
               .forEach(effect ->

                   effect.update()

               );

    }

}


texts: Cache with limited size; If full remove the oldest

texts:
Here is a class that stores a single value into the limited cache. If cache is full, it will remove the oldest element to make a space for a new value.
I'm using 2 structures to accomplish this because I need a fast lookup. I'm not very confident this is the best approach.
Cache will contain a small amount of data (lets say 1000 elements).

#include <unordered_set>
#include <queue>

template <class T>
class Cache{

private:
    int _maxSize;
    std::unordered_set<T> _set;
    std::queue<T> _queue;

public:
    explicit Cache(int maxSize) : _maxSize(maxSize){}

    bool add(T value){
        if(_set.find(value) == _set.end()){ // // if not exists in set
            if(_set.size() == _maxSize){ // if set is 'full'
                _set.erase(_queue.front()); // delete the oldest value from the set
                _queue.pop(); // delete oldest value from queue
            }
            _queue.push(value); // push new value into queue
            _set.insert(value);  // insert new value into set
            return true;
        }
        return false;
    }

    int size(){
        return static_cast<int>(_set.size());
    }
};


texts: Message queue with multiple producer, single consumer and no duplicates

texts:
I had to make a message queue in an android app which my thread takes messages from and processes them. There can be multiple producers and duplicate messages should be avoided. Rate of insertion is erratic but not fast. Rate of consumption is slow. I came up with the following :

public class MessageQueueHolder<T> {

    public MessageQueueHolder(int initialSize) {
        messageSet = Collections.newSetFromMap(new ConcurrentHashMap<T, Boolean>());
    }
    public MessageQueueHolder() {
        messageSet = Collections.newSetFromMap(new ConcurrentHashMap<T, Boolean>());
    }
    private final Set<T> messageSet;

    /**
     * @param message to be inserted
     * @return if message already present returns false
     */
    public boolean insertMessage(T message) {
        return messageSet.add(message);
    }

    /**
     * @return returns the optional message and removes it
     */
    public Optional<T> takeMessage() {
        final Iterator<T> iterator = messageSet.iterator();
        if(!iterator.hasNext())
            return Optional.absent();
        final T message = iterator.next();
        iterator.remove();
        return Optional.of(message); //message can't be null
    }

    /**
     * Clear the message set
     */
    public void clear() {
        messageSet.clear();
    }
}

It seems to work just fine but I would appreciate some feedback :)


texts:
I wrote this function last year to convert between the two encodings and just found it. It takes a text buffer and its size, then converts to UTF-8 if there's enough space.

What should be changed to improve quality?

int iso88951_to_utf8(unsigned char *content, size_t max_size)
{
    unsigned char *copy;
    size_t conversion_count; //number of chars to convert / bytes to add

    copy = content;
    conversion_count = 0;

    //first run to see if there's enough space for the new bytes
    while(*content)
    {
        if(*content >= 0x80)
        {
            ++conversion_count;
        }
        ++content;
    }
    if(content - copy + conversion_count >= max_size)
    {
        return ERROR;
    }

    while(content >= copy && conversion_count)
    {
        //repositioning current characters to make room for new bytes
        if(*content < 0x80)
        {
            *(content + conversion_count) = *content;
        }
        else
        {
            *(content + conversion_count)   = 0x80 | (*content & 0x3f); //last byte
            *(content + --conversion_count) = 0xc0 |  *content >> 6;    //first byte
        }
        --content;
    }
    return SUCCESS;

}


texts:
There is a big number with N digits and Q questions.

  In each question, find if the number formed by the string between
  indices Li and Ri is divisible by 7 or not.

  Input: First line contains the number consisting of N digits. Next line contains Q, denoting the number of questions. Each of the next Q
  lines contains 2 integers a and b.

  Output: For each question, print "YES" or "NO", if the number formed by the string between indices a and b is divisible by 7.

  Constraints: 1≤N≤105, 1≤Q≤105, 1≤a,b≤N

Full question

def is_divisible_by_7(num):

    if num - num / 7 * 7 == 0:

        return True
    else:

        return False

N = raw_input()

Q = int(raw_input())

for x in xrange(Q):

    a, b = map(int, raw_input().split())

    if is_divisible_by_7(int(N[a - 1:b])):
        print "YES"
    else:
        print "NO"


texts: Using built-in type Decimal or Entity type Advance, to hold AdvanceAmount

texts:
In a wage processing system which employees MVP pattern We have Model classes WageInfo,  EarningInfo, DeductionInfo and AdvanceInfo and entity class Advance. (With several other classes)

EarningInfo and DeductionInfo has a composition relationship with WageInfo (contained in WageInfo) and also since Advance amount is a part of wages (paid in advance)  I've modeled the relationship of Advance with DeductionInfo as aggregation because finally it becomes a deduction to the wages (advance amount should be deducted from wages).

public class DeductionInfo
{
    public int EmployeeID { get; set; }
    public string Name { get; set; }
    public decimal LoanInstalmentAmount { get; set; }
    public decimal UniformInstalmentAmount { get; set; }
    public decimal InsuranceInstalmentAmount { get; set; }
    public decimal AdvanceAmount { get { return Advance.Amount; } set { Advance.Amount = value; } }

    public Advance Advance = new Advance();
}

 public class Advance
{
    public int AdvanceID { get; set; }
    public decimal Amount { get; set; }
    public DateTime EnteredDate { get; set; }
}

So when I create a DeductionInfo object I simply assign a value to AdvanceAmount property and I'm not initializing other properties of Advance class in this instance.

My question are...

Is the way I've modeled these class relationships logical and correct?
Whether I've properly implemented aggregation in DeductionInfo?
Since the advance amount is just a amount is it worth to use decimal type instead?


texts:
I am trying to update my server to let it know that the user had some activity in the past 15 minutes. In order to do that, I made this implementation:

var page = {

    updated: false,

    change_state: function(e)   {
        var self = this;
        if(!this.updated){
            debugConsole.log('Moved mouse');
            setTimeout(function(){
                self.updated = false;
            },  //                10000); //10 seconds
                120000); //2 minutes
            this.updated = true;
            $.ajax({
                url: 'comet/update.php',
                success: function(data){
                    debugConsole.log('Moved mouse at: ' + data);
                }
            })
        }
    },

    mouse_click: function(e)    {
        this.updated = false;
    }

}

$("*").live('mousemove',function(e){
    e.stopPropagation();
    page.change_state(e); });

$("*").live('click',function(e){
    page.mouse_click(e); });

I made it so that it only takes effect after 2 minutes from the last action, unless the last action was a click.

Is this the best way of doing it?


texts: To make the decision structure loose or structured?

texts:
I would write the code this way:
function getPayAmount() {
  if (isDead) return deadAmount();
  else if (isSeparated) return separatedAmount();
  else if  (isRetired) return retiredAmount();
  else return normalPayAmount();
}

but a person with a different opinion insists the more proper way is:
function getPayAmount() {
  if (isDead) return deadAmount();
  if (isSeparated) return separatedAmount();
  if (isRetired) return retiredAmount();
  return normalPayAmount();
}

And he mentioned it is about Replace Nested Conditional with Guard Clauses.
My argument is that it really is like a fork on the road and there are 4 branches. So the first style is exactly very clear to follow for the whole structure. The second style is more like 4 loose statements and it is somewhat harder to follow (than just one well organized structure).
So if using my style, it would be:
function getValue(flag) {
  if (flag) return something();
  else return somethingElse();
}

and his style:
function getValue(flag) {
  if (flag) return something();
  return somethingElse();
}

Would this be just a personal style or would style one or two actually has clear advantage and is more preferred?


texts: Generate a unique numeric identifier for each instance of a class

texts:
I want to generate a unique ID for every instance of a given class.

The ID is of type unsigned long
When an instance is deleted, the ID is freed (can be reused)

Now, I've come up with the following implementation:

Class Foo
{
public:

  static unsigned std::set<unsigned long> s_usedID;

  static unsigned long generateID() // Generate a valid ID
  {
    static unsigned long id = 0;

     while (Foo::isIDUsed(id)) // If all ID are taken, create an infinite loop!
        ++id;

     return id;
  }

  static void addID(unsigned long id) // Add a given ID to the set of used ID
  {
    s_usedID.insert(id);
  }

  static void removeID(unsigned long id) // Remove a given ID from the set of used ID
  {
    s_usedID.erase(id);
  }

  static bool isIDUsed(unsigned long id)
  {
    return s_usedID.count(id) == 1 ? true:false;
  }

  explicit Foo() : m_id(Foo::generateID())
  {
    Foo::addID(m_id); // ID is now taken
  }

  virtual ~Foo()
  {
    Foo::removeID(m_id); // Free the ID
  }

private:

  unsigned long m_id;

};

Now for me, this logically works.

Is there a better way to implement this?
Are there any optimizations that I could make?


texts: Simple login form with vanilla HTML markup

texts:
This is just a simple login form with a very vanilla HTML markup, but  I just wanted to get some professional feedback. I know about jslint and try to adhere to there principals where possible.

<script>
//event listeners
$('#sign_in_button').on('click', sign_in);
$('#create_new_account').on('click', create);
$('#create_signup_form').on('click', modal);

function modal() {
    $('#error_box2').text('').hide();
}

function login_success() {
    linkLocation = 'home.html';
    $("body").fadeOut(3000, redirect_page);
}

function redirect_page() {
    window.location = linkLocation;
}

function login_error() {
    var msg = 'Error logging in';
    error(msg);
}

function get_form_input(id,validator) {
    var check ='',
        type =$(id).attr('type');

    if(type != 'checkbox' ) {
        check = $(id).val();
    } else if (type == 'checkbox') {
        check = $(id).attr('checked');
    }

    if(validator(check)){
        return check;
    } else {
        return false;
    }
    return false;
}

///validation functions
function validate_username(id) {
    var username_regex = /^[A-Za-z](?=[A-Za-z0-9_.]{3,20}$)[a-zA-Z0-9_]*\.?[a-zA-Z0-9_]*$/;
    var msg;
    if (!username_regex.test(id)) {
        if ((id.length) > 21){
            msg = "under 20 characters.";
        } else if((id.length) < 4) {
            msg = " more than 4 characters.";
        }else {
            msg = "You can use 4-20 characters, including underscores and one dot.";
        }
        return error(msg);
    }
    return username_regex.test(id);
}

function validate_password(pass) {
    var msg;
    var password_regex = /^.{8,20}$/;

    if (password_regex.test(pass)) {
        return true;
    } else if (pass.length <8) {
        msg = "Passwords should be 8 characters or more.";
        return error(msg);
    } else if (pass.length >21) {
        msg= "twenty character max";
        return error(msg);
    }
    else if (!password_regex.test(password)) {
        msg= "Passwords can be  8-20 characters";
        return error(msg);
    }
}

function validate_email(email) {
      var email_regex = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
      var msg;
      if (!email_regex.test(email)) {
          msg = "Not a valid email.";
          return error(msg);
      }
     return email;
}

function error(msg) {
    $('#error_box1').slideDown();
    $('#error_box1').text(msg);

    return false;
}

function create_success() {
    login_success();
}

function create_error() {
    var msg = 'Error logging in';
    error(msg);
}

function sign_in() {
    var send = {
        'password' : get_form_input('#password', validate_password),
        'username' : get_form_input('#username', validate_username),
    };
    var url = "http://";

    if (send.username && send.password) {
    console.log(send);
        $.when($.post(url,send)).then(login_success, login_error);
    } else {
        return;
    }

}

function create() {
    var send = {
        'password' : get_form_input('#new_password', validate_password),
        'username' : get_form_input('#new_username', validate_username),
        'email'    : get_form_input('#new_email', validate_email)
    };

    var url = "http://";

    if (send.username && send.password && send.email) {
        console.log(send);
        $.when($.post(url,send)).then(create_success, create_error);
    } else {
        //return error('Error logging in. Try again soon.');
    }
}

</script>

What is the non-quick fix for the name space issue?
Why couldn't a heavy, more complicated application not function effectively with procedural code?


texts: Asynchronous query to load products from laravel controller

texts:
The following code works fine. When a user clicks on an element, an AJAX request is made, which will return the query result. The results are being displayed in a view. I read many articles where everyone is doing HTML code in controller when getting data with AJAX and show in view as same I did. Any good suggestions to avoid HTML code in controller make controller view and script separate.

Controller:

public function ajax(Request $request){

// $data = $request->all();

$data['products'] = Product::select('products.id', 'products.name', 'products.banner')->get();

foreach ($data['products'] as $product){
    echo $product->name;
}

// dd($data);
// if($request->ajax()){
//     return "AJAX";
// }
// return "HTTP";

// $data['products'] = Product::select('products.id', 'products.name', 'products.banner')->get();
// return $data;

}

Script

view

    @foreach($leedManufacturers as $leedsManufacturer)
                    {{-- @foreach($leedManufacturers as $leedsManufacturer)  --}}

                            {{str_limit($leedsManufacturer['name'], 300)}}
                                    <input type="checkbox">

                        {{-- for load more script --}}
                    {{-- <input type="hidden" id="row" value="0"> --}}

                    {{-- <input type="hidden" id="all" value="{{$total_manufacturers}}"> --}}
                    @endforeach


texts: Implementing JQuery style 'deferred' and 'promise' in C#

texts:
I like the pattern of the jQuery Deferred object.

I like how you can call Resolve any number of times, but the listening objects will only be notified once. I also like how you can attach a listening object after Resolve has already been called, and the listening object will still get the notification. If you're programming in an uncertain multithreaded environment, it greatly reduces the amount of thinking you have to do.

I couldn't find an equivalent in the C# library, so here is my implementation (a basic subset so far):

using System;
using System.Collections.Concurrent;
using System.Threading;

interface IPromise
{
    void Done(Action action);
}

sealed class Deferred : IPromise
{
    readonly ConcurrentBag<Action> _actions = new ConcurrentBag<Action>();
    // using an int instead of a bool
    // so we can use Interlocked
    private int _isResolved = 0;

    internal void Resolve()
    {
        Interlocked.Exchange(ref _isResolved, 1);
        InvokeActions();
    }

    void IPromise.Done(Action action)
    {
        _actions.Add(action);
        if (_isResolved == 1)
        {
            InvokeActions();
        }
    }

    void InvokeActions()
    {
        Action action = null;
        while (_actions.TryTake(out action))
        {
            action();
        }
    }
}

For this code to be usable, it has to be completely 100% thread safe. Can anyone see a hole in it?

Also, am I just re-implementing something that already exists in some corner of the .NET base class library?

For the sake of context I'll provide a practical use: there's a long running application, and some code that must execute if a file exists. The file might exist when the code first runs, or might come to exist later, or might never exist at all.
I invoke it like this:

 string fullPath = GenerateWatchedFilePath();
 FileSystemWatcherUtils
      .WhenFileAppears(fullPath)
         .Done(() =>
                {
                    using (var stream = File.OpenRead(fullPath))
                    {
                       // etc
                    }
                }
              );

And my implementation of WhenFileAppears:

public static IPromise WhenFileAppears(string fullPath)
{
   Deferred returnPromise = new Deferred();
   if (File.Exists(fullPath))
   {
      returnPromise.Resolve();
      return returnPromise;
   }
   string subFolder = Path.GetDirectoryName(fullPath);
   // This code assumes the subFolder exists
   // An exception will be thrown if it does not
   var fileSystemWatcher = new FileSystemWatcher(subFolder);
   int onceOnlyFlag = 0;
   Action disposeOfWatcherAndResolve = () =>
   {
      if (Interlocked.Exchange(ref onceOnlyFlag, 1) == 0)
      {
          fileSystemWatcher.Dispose();
          returnPromise.Resolve();
      }
   };
   FileSystemEventHandler watcherHandler = (sender, args) =>
     {
        if (args.FullPath == fullPath)
        {
           disposeOfWatcherAndResolve();
        }
     };
   fileSystemWatcher.Created += watcherHandler;
   fileSystemWatcher.Renamed += (sender, args) => watcherHandler(sender, args);
   fileSystemWatcher.EnableRaisingEvents = true;
   // Dealing with a race condition:
   // if the file came to exist between the last check
   // and the creation of the fileSystemWatcher
   if (File.Exists(fullPath))
   {
      disposeOfWatcherAndResolve();
   }
   return returnPromise;
}


texts: Inline assembly correctness (especially __volatile__)

texts:
Here's my inline-assembly functions, which is used my x86 32bit kernel.

static inline uint8_t ckPortInByte(uint16_t port)
{
    uint8_t ret;
    __asm__ __volatile__ ( "in %1, %0" : "=a"(ret) : "d"(port) );
    return ret;
}

static inline void ckPortOutByte(uint16_t port, uint8_t data)
{
    __asm__ __volatile__ ( "out %0, %1" : : "a"(data), "d"(port) );
}

static inline uint32_t ckAsmGetEFlag()
{
    uint32_t ret;
    __asm__ __volatile__ ( "pushfl \n pop %0" : "=g"(ret) );
    return ret;
}

static inline void ckAsmSetEFlag(uint32_t eflag)
{
    __asm__ __volatile__ ( "push %0 \n popfl" : : "g"(eflag) );
}

static inline uint32_t ckGetCr0()
{
    uint32_t ret;
    __asm__ ( "mov %%cr0, %0" : "=r"(ret) );
    return ret;
}

static inline void ckSetCr0(uint32_t value)
{
    __asm__ ( "mov %0, %%cr0" : : "r"(value) );
}

static inline uint32_t ckGetCr3()
{
    uint32_t ret;
    __asm__ ( "mov %%cr3, %0 " : "=r"(ret) );
    return ret;
}

static inline void ckSetCr3(uint32_t value)
{
    __asm__ ( "mov %0, %%cr3" : : "r"(value) );
}

static inline void ckAsmCpuid(uint32_t code, CpuidStruct *cs)
{
    __asm__
    (
        "cpuid"
        : "=a"(cs->eax), "=b"(cs->ebx), "=c"(cs->ecx), "=d"(cs->edx)
        : "a"(code)
    );
}

static inline void ckAsmCli()
{
    __asm__ __volatile__ ( "cli" );
}

static inline void ckAsmSti()
{
    __asm__ __volatile__ ( "sti" );
}

static inline void ckAsmStiHlt()
{
    __asm__ __volatile__ ( "sti \n hlt" );
}

static inline void ckAsmHlt()
{
    __asm__ __volatile__ ( "hlt" );
}

It seems that everything is ok.

However, recently I had a bug, which is related to these functions, especially __volatile__ correctness. (Can you see __volatile__ in ckPortInByte and ckPortOutByte? They didn't exist before I fixed it...)

So, I'm really afraid now - Is there anything wrong? (i.e. unnecessary or missing __volatile__)


texts:
I am writing C++ code to enumerate the whole HDD and drive listing.  However, it takes more than 15 minutes to complete the disk enumeration of all drives (HDD capacity of 500GB) and compile the response in a binary file.

However, I have a 3rd party executable which gives me the listing of the whole disk in just less than two minutes.  Can you please look into my code and suggest some performance improvement techniques?

EnumFiles(CString FolderPath, CString SearchParameter,WIN32_FIND_DATAW *FileInfoData)
{
         CString SearchFile = FolderPath + SearchParameter;
         CString FileName;

        hFile = FindFirstFileW(SearchFile, FileInfoData); //   \\?\C:\*

            if (hFile == INVALID_HANDLE_VALUE)
            {
                // Error
            }
          else
         {
                do
                {
                    FileName = FileInfoData->cFileName;
                    if (FileInfoData->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
                    {
                        if (! (FileName == L"." || FileName == L".."))
                        {
                                        // Save the Folder Information
                          EnumFiles(FolderPath + FileName +(L"\\"), SearchParameter,FileInfoData);
                        }
                    }
                    else
                   {
                     // Save the File Parameters
                    }

              } while (FindNextFileW(hFile, FileInfoData));
}
           FindClose(hFile);
       }


texts: Parse copied data from Excel using AutoHotkey

texts:
Code Objective

I'm writing an AutoHotkey script which takes in department data copied to the clipboard from a Microsoft Excel spreadsheet. It then uses this data to auto-fill forums in the web-app Kronos Workforce Central.

Source Data

When data is copied from Microsoft Excel, each cell in a row is stored in the clipboard as strings delimited by tabs \t, with each row separated by newlines \r\n.

DeptID     Job Name           Abbreviation     Service Line
0368       Administrator      ADMIN            OPS
3945       Programmer         PRGRM            NON NRSG
4596       Software Engineer  SFTWRE-ENG       NON NRSG

Current Method

Currently, I'm parsing this copied-data by splitting the data into an array of rows with StrSplit(), then using a second StrSplit() inside a for-loop to parse my data.

; Autofill data from clipboard
#d::
   addLocationsWindow := "Add Locations"
   WinActivate, %addLocationsWindow%        ; Window MUST be active

   rowArray := StrSplit(Clipboard, "`r`n")  ; Split copied rows from Excel by newlines
   for index, row in rowArray {
      tempArray := StrSplit(row, "`t")      ; Split each row by tabs
      deptID := tempArray[1]
      jobName := tempArray[2]

      If (deptID == "")                     ; skip empty cells
         continue

      IfWinNotActive(addLocationsWindow)  ; check for active window
      {
         MsgBox '%addLocationsWindow%' window not found. Stopping script...
         Exit, 1
      }

      ; DoStuff(jobName, deptDisplayName, index)
   }
Return

The Issue

My method of string parsing feels hacky and unintuitive. It means I can only manipulate a single row at a time, as each each row's data is only split temporarily. I would need to re-run the costly StrSplit() to access data from a row again.

In Java, I could store my Excel data in a single 2D array. Unfortunately, arrays are a bit tricky to use in AutoHotkey, which is why my current code is a bit messy.


texts: Minimize boilerplate code in Action class

texts:
I perform an if-check (commented in the code) to determine whether a user can access certain actions or not. The user will be redirected to the index page if they try to access the login.action while already logged in.

I have this kind of if-check in many of my Action classes (containsKey() or !containsKey(), depending on the action) and it is looking very redundant.

How can I improve on what I am trying to achieve?

public String execute() throws Exception {
    // redirect if user is already logged in
    if(session.containsKey("currentId")) {
        return "index";
    }

    Integer currentId = mm.getCurrentId(member.getMemberId());
    String currentAccessType = mm.getMemberInfo("member_access_type", member.getMemberId());

    System.out.println("Current ID: " + currentId);
    System.out.println("Current Access Type: " + currentAccessType);

    session.put("currentId", currentId);
    session.put("currentAccessType", currentAccessType);

    System.out.println("You have logged in!");

    return SUCCESS;
}


texts: Filter to convert duration to hours — in controller or model?

texts:
I have this before_action method :
  def convert_duration_reminder
    allowed_duration_units = %(hour day)
    if allowed_duration_units.include? params[:store][:store_setting_attributes][:reminder_unit]
      store_settings_params = params[:store][:store_setting_attributes]
      @duration_reminder = store_settings_params[:reminder_duration].to_i.send(store_settings_params[:reminder_unit]).to_i / 3600
    else
      redirect_to store_settings_store_path(id: current_store.id)
    end
  end

I have a little bit of logic inside. The @duration_reminder is after used in an update_attributes.
Does it belongs in the controller or the model? I think it belongs in the controller because I'm using params and I have a redirect and methods are short (except line length...) and it doesn't process any data in database.
In the book Rails 4 action, it says:

Models contain the domain logic of your application. This logic
dictates how the records in your database are retrieved, validated, or
manipulated. In Rails appli- cations, models define the code that
interacts with the database’s tables to retrieve and set information
in them. Domain logic also includes things such as validations or
particular actions to be performed on the data.

Controllers interact with the models to gather information to send to the view. They’re the
layer between the user and the database. They call methods on the
model classes, which can return single objects representing rows in
the data- base or collections (arrays) of these objects. Controllers
then make these objects available to the view through instance
variables. Controllers are also used for permission checking, such as
ensuring that only users who have special permission to perform
certain actions can perform those actions, and users without that
permission can’t.


texts: Simplify & Reduce steps in the IsDistinct function

texts:
Because I often have to deal with two Variants that may or may not be Null, we need a null-safe equality test, so I came up with IsDistinct which works but I have some issues with the code:

When I tried to keep it terse, the readability was harmed.
When I tried to expand the logic for readability, it still makes for some thinking.
I looked for potentials to short-circuit or otherwise result the number of steps to arrive at a result. In this case, it all takes 2 evaluations, unless both sides are non-null, in which case we have 3 evaluations.1

Can we do better?

Public Function IsDistinct(LeftValue As Variant, RightValue As Variant) As Boolean
    If IsNull(LeftValue) Then
        If IsNull(RightValue) Then
            IsDistinct = False
        Else
            IsDistinct = True
        End If
    Else
        If IsNull(RightValue) Then
            IsDistinct = True
        Else
            IsDistinct = Not (LeftValue = RightValue)
        End If
    End If
End Function

Inputs & Expected Outputs

LeftValue RightValue Result
 1         1          False
 1         0          True
 Null      1          True
 0         Null       True
 Null      Null       False
 ""        ""         False
 ""        Null       True

Note that it doesn't have to be just 0 and 1; it could be text, dates, or numbers. It's more important that when either inputs are Null, it should automatically be True since Null will always be "distinct" from any non-Null values. However, when both inputs are Null, then it's always False because we are considering them "equal" in this situation.2

The special case of an empty string and a Null is arguably problematic. I've swung both ways; sometimes I want empty string to be considered "equal" to a Null, sometimes I don't. In the IsDistinct as defined, they are not considered equal.3

1) In one of iterations, I considered starting with Result = (LeftValue = RightValue) and doing additional evaluation if the Result was Null, signaling that either or both inputs were Null. But IIRC, I found that it made for more steps since I had to evaluate each inputs with IsNull to determine whether both were Null and thus not distinct.

2) As a matter of fact, when I look at the first 3 lines:

If IsNull(LeftValue) Then
    If IsNull(RightValue) Then
        IsDistinct = False

My instinct is to go "wait, that's not right.", thinking about it and realize it IS correct. The fact that I stumble on that even more than once tells me that it's quite hard to read. Boo.

3) Thanks to @Ryan Wildry for pointing this blind spot out!


texts:
If you have a Gmail ID, then you can also receive emails on the same account even if you add extra dots in the username or add '+' and some characters.

Say your Gmail ID is montypython@gmail.com.  You will receive emails on same account even if it is sent to:

monty.python@gmail.com
montypython+python@gmail.com
m.o.nty.p.y.t.hon@gmail.com

Following is the code, which gives me back username removing dots and characters after '+' symbol. Do note that I really don't care if user enters an invalid Gmail ID.

import re

def return_gmail_user(email):
    username = email.split('@')[0]
    domain = email.split('@')[1]
    valid_email_char = '[\w\d\.]+'
    # check if email is of gmail
    if domain != 'gmail.com':
        return False
    # get username
    m = re.match(valid_email_char, username)
    if m:
        username = m.group(0)
        #print username
        return "".join(username.split('.'))
    return False

def main():
    assert('my' == return_gmail_user('my@gmail.com'))
    assert('my' == return_gmail_user('m.y@gmail.com'))
    assert('avinassh' != return_gmail_user('avinassh@reddit.com'))
    assert('avinassh' == return_gmail_user('avinassh+reddit@gmail.com'))
    assert('avinassh' == return_gmail_user('av.ina.s.sh@gmail.com'))
    assert('avinassh' == return_gmail_user('avi.na.ss.h+reddit@gmail.com'))
    assert('avinassh' == return_gmail_user('avi.na.ssh+red+dit@gmail.com'))

if __name__ == '__main__':
    main()