texts: VBA: Calling one sub repeatedly and scope of variables

texts:
My code as a whole works for me without issues, but what I want to improve is a small part right out of the middle of it. I hope it's ok to post a simplified snippet here that just shows the structure (it's not something you can copy paste and it works), but I'll try to explain what it is about. If this is against the rules, let me know.

I have a workbook that functions as a database (wbDB). I look for the number of an object (objectNumber) and, if found, add it to a sheet (wsTest) in another workbook via Sub AddObject.

Option Explicit

Public Const fRowType As Long = 4
Public Const fRowClosing As Long = fRowType + 1
Public Const fRowLoan As Long = fRowType + 4
'[there are about 30 of those fRow variables; they are needed in another _
 module, that's why they are public]

Dim wbDB As Workbook
Dim wsDB As Worksheet, wsTest As Worksheet

Dim lColTest As Long

Sub AddObject(ByVal objectNumber As String, ByVal rngObjects As Range)
    Const colType As String = "A"
    Const colClosing As String = "BN"
    Const colLoan As String = "CD"
    '[same as fRows, I have over 30 of these "col"-variables]

    Dim rowObject As Long
    Dim foundCell As Range

    Set wbDB = Application.Workbooks("Database.xlsx")
    Set wsDB = wbDB.Sheets(2)
    Set wsTest = ActiveSheet

    '---Find object in rngObjects and set rowObject to respective row
    Set foundCell = rngObjects.Find(What:=objectNumber, LookAt:=xlWhole)
    If foundCell Is Nothing Then
        MsgBox "Object " & objectNumber & "wasn't found and will be skipped."
        Exit Sub
    Else
        rowObject = foundCell.Row
    End If

    lColTest = wsTest.Cells(12, wsTest.Columns.Count).End(xlToLeft).Column
'Type
    Call ImportData(rowObject, colType, fRowType)
'Closing
    Call ImportData(rowObject, colClosing, fRowClosing)
'Loan
    Call ImportData(rowObject, colLoan, fRowLoan)
'[again, there are 30+ of these calls]

End Sub

Sub ImportData(ByVal rowDB As Long, ByVal colDB As String, ByVal fRowSection As Long)
    wsTest.Cells(fRowSection, lColTest + 1).Value = wsDB.Cells(rowDB, colDB).Value
End Sub

If you look at Sub ImportData: It requires lColTest, a module-wide variable, which I initialize in Sub AddObject. On the other hand, rowObject is needed just as often, but I put it as one of the parameters of ImportData. What is better practice? From what I've read is that the wider the scope of a variable, the less desirable it is. However, if it is one of the parameters, I currently copy paste it about 30 times with every Call and every additional parameter makes it a little less readable too.

My idea as the "cleanest" solution would be: put it in as parameter and instead of typing out every Call, I loop through it. Would you agree with that? If the answer is yes, I'd need an array or something similar.

What's the best option here since I need always need a pair of values (column and first row)?
Is there an efficient or readable way to fill the array with all these variables?


texts:
I've the following d3 chart which is both grouped and each grouped contains a stacked bar. But somehow, I feel this is not a proper way to implement and little complicated. If there was only stacked bar chart, I would have used d3.stack(). Is there anyway I can still use the d3.stack() with current setup. Can someone let me know is there any better way to do this?

Snippet as follows

var data = [
  {
    Category: "cat1",
    type1: 300,
    type2: 450,
    type3: 120
  },
  {
    Category: "cat2",
    type1: 400,
    type2: 100,
    type3: 200
  },
  {
    Category: "cat3",
    type1: 400,
    type2: 100,
    type3: 200
  },
  {
    Category: "cat4",
    type1: 400,
    type2: 100,
    type3: 200
  }
];

var margin = { top: 20, right: 20, bottom: 30, left: 40 },
  width = 500 - margin.left - margin.right,
  height = 500 - margin.top - margin.bottom;
var barWidth = 40;
var x0 = d3.scaleBand().range([0, width]);

var x1 = d3.scaleBand();

var y = d3.scaleLinear().range([height, 0]);

var xAxis = d3.axisBottom(x0);

var yAxis = d3.axisLeft(y).tickFormat(d3.format(".2s"));

var color = d3.scaleOrdinal().range(["#98abc5", "#8a89a6", "#7b6888"]);

var svg = d3
  .select("body")
  .append("svg")
  .attr("width", width + margin.left + margin.right)
  .attr("height", height + margin.top + margin.bottom)
  .append("g")
  .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

var yBegin;

var innerColumns = {
  column1: ["type1", "type2"],
  column2: ["type3"]
};
var columnHeaders = d3.keys(data[0]).filter(function(key) {
  return key !== "Category";
});
color.domain(
  d3.keys(data[0]).filter(function(key) {
    return key !== "Category";
  })
);
var groupData = data.forEach(function(d) {
  var yColumn = new Array();
  d.columnDetails = columnHeaders.map(function(name) {
    for (ic in innerColumns) {
      if (innerColumns[ic].indexOf(name) >= 0) {
        if (!yColumn[ic]) {
          yColumn[ic] = 0;
        }
        yBegin = yColumn[ic];
        yColumn[ic] += +d[name];
        return {
          name: name,
          column: ic,
          yBegin: yBegin,
          yEnd: +d[name] + yBegin
        };
      }
    }
  });
  d.total = d3.max(d.columnDetails, function(d) {
    return d.yEnd;
  });
});

//console.log(data);
x0.domain(
  data.map(function(d) {
    return d.Category;
  })
);
x1.domain(d3.keys(innerColumns)).range([0, x0.bandwidth()]);

y.domain([
  0,
  1.15 *
    d3.max(data, function(d) {
      return d.total;
    })
]);

svg
  .append("g")
  .attr("class", "x axis")
  .attr("transform", "translate(0," + height + ")")
  .call(xAxis);

svg
  .append("g")
  .attr("class", "y axis")
  .call(yAxis);

var stackedbar = svg
  .selectAll(".stackedbar")
  .data(data)
  .enter()
  .append("g")
  .attr("class", "g")
  .attr("transform", function(d) {
    return "translate(" + x0(d.Category) + ",0)";
  });

stackedbar
  .selectAll("rect")
  .data(function(d) {
    return d.columnDetails;
  })
  .enter()
  .append("rect")
  .attr("width", barWidth)
  .attr("x", function(d) {
    return x1(d.column) + (x1.bandwidth() - barWidth) / 2;
  })
  .attr("y", function(d) {
    return y(d.yEnd);
  })
  .attr("height", function(d) {
    return y(d.yBegin) - y(d.yEnd);
  })
  .style("fill", function(d) {
    return color(d.name);
  });
body {
  font: 10px sans-serif;
}

.axis path,
.axis line {
  fill: none;
  stroke: #000;
  shape-rendering: crispEdges;
}

.bar {
  fill: steelblue;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.6.0/d3.min.js"></script>


texts:
I have just started learning how to build websites, and I have been experimenting by creating a contact form.

Here is what I currently have - can anyone suggest and recommend ways enhance my current contact form system?

JavaScript:

$("#contactForm").submit(function (event) {

    /* stop form from submitting normally */
    event.preventDefault();

    /* get some values from elements on the page: */
    var $form = $(this),
        $submit = $form.find('button[type="submit"]'),
        name_value = $form.find('input[id="name"]').val(),
        email_value = $form.find('input[id="email"]').val(),
        message_value = $form.find('textarea[id="message"]').val(),
        url = $form.attr('action');

    /* send the data using post */
    var posting = $.post(url, {
        name: name_value,
        email: email_value,
        message: message_value,
        ajax: 1
    });

    posting.done(function (data) {
        $form.find('span.error').remove();

        if (data == "1") {

            /*Change the button text.*/
            $submit.text('Sent. Thank You!');
            $submit.addClass("sent");

        } else {
            $submit.after('Failed to send the message, please check your entries and try again.');
            /*Change the button text.*/
            $submit.text('Try Again');
        }
    });
});

PHP

<?php

    if(isset($_POST['name']) && $_POST['email'] && $_POST['message']) {

    $name = $_POST['name'];
    $email = $_POST['email'];
    $message = $_POST['message'];

    $to = "email@website.com";
    $subject = "New Message From: $name";
    $message .= "$messege";

    $headers  = 'MIME-Version: 1.0' . "\r\n";
    $headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";
    $headers .= 'From: '.$email . "\r\n";
    $mailed = ( mail($to, $subject, $message, $headers) );

    if( isset($_POST['ajax']))
        $response = ($mailed) ? "1" : "0";
    else
        $response = ($mailed) ? "
Success!
" : "
Error! There was a problem with sending.
";
        echo $response;
        }
    else
        {
        echo "Form data error!";
    }
?>

HTML:

<form id="contactForm" action="email.php" method="post" name="contactForm">

        Your Name
        <input id="name" type="text" placeholder="Enter Name" required>

        Email Address
        <input id="email" type="email" placeholder="Enter Email" required>

        Message
        <textarea id="message" required></textarea>

    <button id="submit" type="submit">Send</button>
</form>


texts: Code dealing with files and separate lines in them

texts:
I have been using similar piece of code since a while. I have read some issues regarding treating mapped memory as a string. I am not sure about that though, so I just use strndup(3) to avoid it anyway.

It's often said to use fopen, fwrite and all those f* functions over read(2), write(2) etc. The reason being, these functions handle the reading and writing quite well by intermediate buffering and are quite well organised too. But in my personal opinion, dealing with files with mmap(2) generally tends to be faster, gives nice control over the data because of MAP_* flags and making a structure yourself can organise data pretty well too. These things hold true except in some cases.

I wanted some reviews on this code and this way of working with files:

#include <sys/mman.h>
#include <sys/stat.h>

#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct MyFile {
    const char *filename;
    int fd;
    size_t size;
    char *contents;
};

int setup_myfile(const char *filename, struct MyFile *file);
void clean_myfile(struct MyFile file);

int
main(int argc, char *argv[])
{
    if (argc != 2) {
        fprintf(stderr, "usage: %s filename\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    struct MyFile my_file;
    char *contents, *line, *to_free;

    int err = setup_myfile(argv[1], &my_file);

    if (err == -1) {
        fprintf(stderr, "setup_myfile() failed\n");
        exit(EXIT_FAILURE);
    }

    to_free = contents = strndup(my_file.contents, my_file.size);

    if (to_free == NULL) {
        perror("strndup(3)");
        exit(EXIT_FAILURE);
    }

    while ((line = strsep(&contents, "\n")) != NULL) {

        // Print line by line or do anything with line
        printf("%s", line);
    }

    free(to_free);
    clean_myfile(my_file);

    return 0;
}

int
setup_myfile(const char *filename, struct MyFile *file)
{
    struct stat st;

    file->filename = filename;
    file->fd = open(file->filename, O_RDONLY);

    if (file->fd == -1) {
        perror("open(2)");
        return -1;
    }

    if (fstat(file->fd, &st) == -1) {
       perror("fstat(2)");
       return -1;
    }

    file->size = st.st_size;

    file->contents = mmap(NULL, file->size, PROT_READ | PROT_WRITE, MAP_PRIVATE, file->fd, 0);

    if (file->contents == MAP_FAILED) {
        perror("mmap(2)");
        return -1;
    }

    return 0;
}

void
clean_myfile(struct MyFile file)
{
    munmap(file.contents, file.size);
    close(file.fd);
}


texts: Create several homogeneous arrays from a larger heterogenous array efficiently

texts:
I have a list of aircraft returned from a REST call which describes the status of each aircraft. In order to make the UI templating simpler, this single list is split into four homogeneous lists in order to group by status.

My primary concern is that we iterate over the primary array \$s\$ times which, while still in polynomial \$O(n \times s)\$ time, feels needlessly inefficient.

Perhaps there is a way to more efficiently split this array in a single pass?

Here is a representative code sample:

let aircraft = [
    {
        tail: "9736968",
        status: "DRAFT"
    },
    {
        tail: "5114419",
        status: "SERVICEABLE"
    },
    {
        tail: "8395671",
        status: "OUTOFSERVICE"
    },
    {
        tail: "332273",
        status: "SERVICEABLE"
    },
    {
        tail: "6123961",
        status: "UNSERVICEABLE"
    },
]

let serviceable = [];
let unserviceable = [];
let outOfService = [];
let draft = [];

function splitLists(aircraftStatusList) {
    serviceable = aircraftStatusList
                    .filter(aircraft => aircraft.status === 'SERVICEABLE');

    unserviceable = aircraftStatusList
                    .filter(aircraft => aircraft.status === 'UNSERVICEABLE');

    outOfService = aircraftStatusList
                    .filter(aircraft => aircraft.status === 'OUTOFSERVICE');

    draft = aircraftStatusList
                    .filter(aircraft => aircraft.status === 'DRAFT');
}

splitLists(aircraft);


texts:
I've made a few functions to check form input for an AJAX request. I am still getting used to JavaScript and some of these AJAX requests. I am looking for any suggestions to better work with JavaScript functions, and passing variables through a function level scoping.

//Form Handler
$("#form-submit").submit(function(e) {
    e.preventDefault();
    $.ajax({
        beforeSend: function(){
            return (checkAll());
            return (passwordCheck());
        },
        complete: function(){
        },
           type: "POST",
           url: '',
           data: $("#form-submit").serialize(),
           success: function(data)
           {
           //window.location = '/dashboard.php';
           // Set Session Php Etc
           alert('php ran');
           return true;
           }
         });
});

//Pushing all Input Values to an Array
function checkAll() {
    var arr = [];
    $('#form-submit :input').each(function() {
        arr.push($(this).val());
    });
    return (checkArray(arr));
}

//Checks Array for empty strings
function checkArray(arr){
    for(var i=0; i < arr.length; i++) {
        console.log(arr[i]);
        if (arr[i].trim() == '') {
            alert('Please Enter All Fields');
            return false;
        } else {
            return true;
        }
    }
}

//Matches Password
function passwordCheck() {
    var pass1 = $('#password').val();
    var pass2 = $('#password-check').val();
    if(pass1 != pass2) {
        $('#password').addClass('highlight');
        $('#password-check').addClass('highlight');
        alert("Passwords don't match");
        return false;
    } else {
        $('#password').removeClass('highlight');
        $('#password-check').removeClass('highlight');
        return true;
    }
}


texts:
I'm trying to make this Householder method run as quickly as possible. It runs fine now, but I'm still a bit new to java, is there anything you guys see to make this run faster?

public static ArrayList<double[][]> householder(double[][] A) {
    int m = A.length; // rows
    int n = A[0].length; // cols
    byte sign;
    double sum, A0,tmp;
    ArrayList<double[][]> QR = new ArrayList<>();
    double[] v = new double[m];
    double[][] Q = identity(m);
    for(int k = 0; k < n; k++) {
        sum = 0;
        sign = 1;
        A0 = A[k][k];
        if(A0 < 0){
            sign = -1;
        }
        for(int i = k; i < m; i++) {
            sum += A[i][k]*A[i][k];
        }
        tmp = sign*Math.sqrt(sum);
        v[k] = tmp + A0;
        tmp = Math.sqrt(2*(sum + A0*tmp));
        v[k] /= tmp;
        for(int i = k+1; i < m; i++) {
            v[i] = A[i][k]/tmp;
        }
        for(int j = 0; j < n; j++) {
            sum = 0;
            for(int i = k; i < m; i++) {
                sum += v[i]*A[i][j];
            }
            for(int i = k; i < m; i++) {
                A[i][j] -= 2*v[i]*sum;
            }
        }
        for(int j = 0; j < m; j++) {
            sum = 0;
            for(int i = k; i < m; i++) {
                sum += v[i]*Q[i][j];
            }
            for(int i = k; i < m; i++) {
                Q[i][j] -= 2*v[i]*sum;
            }
        }
    }
    QR.add(transpose(Q));
    QR.add(A);
    return QR;
}

I'm mostly concerned with the portion of the code that multiplies the vectors to get the Q and A matrices.

Here are some ideas I had but wasn't sure would help much.

if there's a better way to return the values than arraylist, like if double[][][] would be faster. I have had issues with recasting double[][][] arrays to double[][] however.
changing all the ints to shorts, i was concerned with casting
I only need sign to be a bit
should I write sum = 0.0?
should I initialize the for loop int i's and j's outside of the loop to save memory?


texts: Python script for sorting a huge log file based on timestamps

texts:
I want to write a python script to sort a huge file, say 2 GB in size, which contains logs in the following format -

Jan 1 02:32:40 other strings but may or may not unique in all those lines
Jan 1 02:32:40 other strings but may or may not unique in all those lines
Mar 31 23:31:55 other strings but may or may not unique in all those lines
Mar 31 23:31:55 other strings but may or may not unique in all those lines
Mar 31 23:31:55 other strings but may or may not unique in all those lines
Mar 31 23:31:56 other strings but may or may not unique in all those lines
Mar 31 23:31:56 other strings but may or may not unique in all those lines
Mar 31 23:31:56 other strings but may or may not unique in all those lines
Mar 31 23:31:57 other strings but may or may not unique in all those lines
Mar 31 23:31:57 other strings but may or may not unique in all those lines
Mar 31 23:31:57 other strings but may or may not unique in all those lines
Mar 31 23:31:57 other strings but may or may not unique in all those lines
Feb 1 03:52:26 other strings but may or may not unique in all those lines
Feb 1 03:52:26 other strings but may or may not unique in all those lines
Jan 1 02:46:40 other strings but may or may not unique in all those lines
Jan 1 02:44:40 other strings but may or may not unique in all those lines
Jan 1 02:40:40 other strings but may or may not unique in all those lines
Feb 10 03:52:26 other strings but may or may not unique in all those lines

I want to sort them basted on the timestamp.

I was able to get this working but for my code to succeed, I need to load the WHOLE file into a list.. this means it will be extremely inefficient from a memory utilization point of view.

Can you please suggest if there is a more efficient way where I can sort this by reading the file line by line or perhaps some other approach that I am not aware of ?

Here is my code -

# convert the log into a list of strings
with open("log.txt", 'r') as f:
    lines = f.read().splitlines()

# writing the method which will be fed as a key for sorting
def convert_time(logline):
    # extracting hour, minute and second from each log entry
    h, m, s = map(int, logline.split()[2].split(':'))
    time_in_seconds = h * 3600 + m * 60 + s
    return time_in_seconds

sorted_log_list = sorted(lines, key=convert_time)

''' sorted_log_list is a "list of lists". Each list within it is a representation of one log entry. We will use print and join to print it out as a readable log entry'''
for lines in sorted_log_list:
    print lines


texts:
I'm creating multiple Django apps with vote possibilities, so I made an app vote to handle all this votes. In my templates I'm including an ajax-function named vote. To know on which model I'm liking I add app_name and model_name to the vote function (I made some templatetags to get these values). In my views.py I use model = apps.get_model(app_name, model_name) to get the model class. But now I'm worried a hacker could do something with the app_name and model_name values.

vote/ajax.html (only function):

function vote(bool){
    $.ajax({
        type: "post",
        timeout: 8000,
        url: '{% url 'ajax:vote' %}',
        dataType: 'json',
        data: {
            'csrfmiddlewaretoken': getCookie('csrftoken'),
            'model_name': "{{ model|get_model_name }}",
            'app_name': "{{ model|get_app_name }}",
            'voted': bool,
            'id': "{{ model.id }}",
        },
        success: function(data) {
            if (!data.error){
                if (bool){
                    $(".half .fa-thumbs-up").removeClass("far").addClass("fas");
                    $(".half #count").text(parseInt($(".half #count").text()) + 1);
                } else {
                    $(".half .fa-thumbs-down").removeClass("far").addClass("fas");
                    $(".half #count").text(parseInt($(".half #count").text()) - 1);
                }
            }
        }
    });
}

ajax/views.py:

def vote(request):
    try:
        app_name = request.POST.get("app_name")
        model_name = request.POST.get("model_name")
        id = request.POST.get("id")
        votedFor = True if request.POST.get("voted") == "true" else False
    except ValueError:
        return JsonResponse({"error": True})

    model = apps.get_model(app_name, model_name)

    if model is None or id is None:
        return JsonResponse({"error": True})

    try:
        usable_model = model.objects.get(id=id)
    except model.DoesNotExist:
        return JsonResponse({"error": True})

    try:
        usable_model.vote._meta.get_field("votes")
    except FieldDoesNotExist:
        return JsonResponse({"error": True})

    usable_model.vote.vote(request, votedFor)
    return JsonResponse({"error": False})

vote/functions:

def vote(self, request, votedFor):
    if request.user.is_authenticated:
        if not UserVoted.objects.filter(User=request.user, Vote=self).exists():
            UserVoted.objects.create(User=request.user, Vote=self, votedFor=votedFor)
            self._like_or_dislike(votedFor)
            return True
        return False
    ip = get_client_ip(request)
    if ip:
        if not UserVoted.objects.filter(ip=ip, Vote=self).exists():
            UserVoted.objects.create(ip=ip, Vote=self, votedFor=votedFor)
            self._like_or_dislike(votedFor)
            return True
        return False
    return False

def _like_or_dislike(self, votedFor):
    if votedFor is not None:
        Vote.objects.filter(id=self.id).update(votes=F('votes') + 1) if votedFor else Vote.objects.filter(id=self.id).update(votes=F('votes') - 1)
        return True
    return False

I already manipulated app_name and model_name and the server didn't crash but I don't know what a hacker can do. Can he crash my server when he manipulate these values? (maybe "ajax-injection" or something like this?)


texts: AngularJS shopping cart using local storage

texts:
Two weeks ago I started writing some Javascript and AngularJS code for a customer. As a proud newby I must also be aware of the dangers on the big bad Internet. In particular vulnerabilities such as XSS attacks.

I've already performed a vulnerability scan and this showed I didn't restrict session cookies to httponly. However nothing about the Javascript or AngularJS scripting.

My familiarity with JavaScript and AngularJS is somewhat limited.

var kvv = angular.module('kvv', ['ngStorage']);

kvv.controller('CartController', ["$scope", "$localStorage", "$sessionStorage", "$timeout", function($scope, $localStorage, $sessionStorage, $timeout) {

if ($localStorage.items === undefined) {
    $localStorage.items = [];
};

$scope.localStorage = $localStorage

$scope.remove = function(index) {
  $localStorage.items.splice(index, 1);
};

$scope.checked = false;

$scope.addToCart = function(index, title, desc, price, timeout) {

  $scope.checked = true;
  var found = false;
  angular.forEach($localStorage.items, function(items) {
      if (items.id  === index) {
        $timeout(function() {
          (items.quantity++);
          $scope.checked = false;
        }, 750);
        found = true;
    }
  });
  if (!found) {
    $timeout(function() {
        $localStorage.items.push(angular.extend({
        id: index,
        title: title,
        quantity: 1,
        price: price}, index))
        $scope.checked = false;
        },750);
    }
};

$scope.itemWithoutBtw = function(index) {
    var itemWithoutBtw = 0;
    angular.forEach($localStorage.items, function(items) {
        itemWithoutBtw += items.price / 106 * 100;
    })
    return itemWithoutBtw;
};

$scope.total = function(index) {
        var total = 0;
        angular.forEach($localStorage.items, function(items) {
            total += items.quantity * items.price;
        })
        return total;
};

$scope.totalBtw = function(index) {
        var totalBtw = 0;
        var total = $scope.total();
        angular.forEach($localStorage.items, function(items) {
            totalBtw = total / 106 * 6;
        })
        return totalBtw;
};

$scope.totalWithBtw = function(index) {
        var totalWithBtw = 0;
        angular.forEach($localStorage.items, function(items) {
            totalWithBtw += (items.quantity * items.price) + (items.quantity * items.price  / 100 * 6);
        })
        return totalWithBtw;
};
$scope.totalWithoutBtw = function(index) {
        var total = $scope.total();
        var totalBtw = $scope.totalBtw();
        var totalWithoutBtw = 0;
        angular.forEach($localStorage.items, function(items) {
            totalWithoutBtw = total - totalBtw;
        })
        return totalWithoutBtw;
};

$scope.orderTotal = function(index) {
        var orderTotal = 0;
        angular.forEach($localStorage.items, function(items) {
            orderTotal += items.quantity;
        })
        return orderTotal;
};

$scope.orderDelete = function(index) {
    delete $localStorage.items;
    $localStorage.items = [];
    $('html, body').animate({scrollTop: 0}, 2500);
};

}]);


texts: Singleton implementation of Cache Dependency Manager

texts:
I am trying to implement a singleton CacheDependencyManager, by combining  this CacheDependencyManager from Steve Greatrex with a singleton pattern from Jon Skeet (example 6).

I'd really appreciate any feedback on it's correctness and / or suggestions for improvement.

ExplicitCacheDependency

public class ExplicitCacheDependency : CacheDependency
{
    private string _uniqueId;

    public ExplicitCacheDependency(string uniqueId)
        : base(new string[0]) //no file system dependencies
    {
        _uniqueId = uniqueId;
    }

    public override string GetUniqueID()
    {
        return _uniqueId;
    }

    // CacheDependency has a protected NotifyDependencyChanged method that will notify the caching framework that the cached item is no longer valid.
    // In most implementations this would be invoked in some callback, but for our purposes we can just add a new Invalidate method and invoke it directly
    public void Invalidate()
    {
        base.NotifyDependencyChanged(this, EventArgs.Empty);
    }
}

CacheDependencyManager

public sealed class CacheDependencyManager
{
    private static readonly Lazy<CacheDependencyManager> lazy =
        new Lazy<CacheDependencyManager>(() => new CacheDependencyManager());

    public static CacheDependencyManager Instance { get { return lazy.Value; } }

    private CacheDependencyManager()
    {
    }

    private Dictionary<string, ExplicitCacheDependency> _dependencies
        = new Dictionary<string, ExplicitCacheDependency>();

    public CacheDependency GetCacheDependency(string key)
    {
        if (!_dependencies.ContainsKey(key))
            _dependencies.Add(key, new ExplicitCacheDependency(key));

        return _dependencies[key];
    }

    public void InvalidateDependency(string key)
    {
        if (_dependencies.ContainsKey(key))
        {
            var dependency = _dependencies[key];
            dependency.Invalidate();
            dependency.Dispose();
            _dependencies.Remove(key);
        }
    }
}


texts: Check if a Binary Tree  is aBinary Search Tree

texts:
I'm understanding the question, but I want to know whether or not my implementation is correct.

The question is:

  Write a method that accepts as its argument a BinaryTree object and
  returns true if the argument tree is a binary search tree. Examine
  each node in the given tree only once.

This is my implementation:

public boolean isBST (BinaryTree<String> tree)
{
    BinaryNode Node = new BinaryNode (tree.getRootData);
    if(tree == null || Node.isLeaf() )
        return true;

    if(Node.getData > Node.getLeftChild && Node.getData < Node.getRightChild)
    {
        boolean leftTree = isBST(new BinaryTree(Node.getLeftChild));
        boolean rightTree = isBST(new BinaryTree(Node.getRightChild));
        return leftTree && rightTree ;
    }
    else return false ;
}


texts: DOMDocument grouping nodes, with clone, nodeClone, importNode, fragment... What the better way?

texts:
A "DOMNodeList grouper" (groupList() function below) is a function that envelopes a set of nodes into a tag. Example:

INPUT

  <root>101202</root>

OUTPUT of groupList($dom->getElementsByTagName('a'),'G')

  <root>10
     <G>12</G>
  20</root>

There are many ways to implement it, what is the better?

  // my "in use" version
  function groupList(DOMDocument &$dom, DOMNodeList &$list, $tag, $place=0) {
       $n = $list->length;
       if ($n && $place<$n) {
          $rmList=array();
          $T = $dom->createElement($tag);
          for($i=0; $i<$n; $i++) {
              $T->appendChild( clone $list->item($i) );
              if ($i!=$place) $rmList[]=$list->item($i);
          }
          $dom->documentElement->replaceChild($T,$list->item($place));
          foreach($rmList as $e)
              $dom->documentElement->removeChild($e);
        }//if
        return $n;
  }//func

  function groupList_v2(DOMDocument &$dom, DOMNodeList &$list, $tag, $place=0) {
       // use iterator_to_array, Fragment, cloneNode, and replaceChild at end.
       $n = $list->length;
       if ($n && $place<$n) {
          $list=iterator_to_array($list);
          $T = $dom->createDocumentFragment();
          $T->appendChild($dom->createElement($tag));
          for($i=0; $i<$n; $i++)
              $T->firstChild->appendChild( $list[$i]->cloneNode() );
          for($i=0; $i<$n; $i++)
              if ($i!=$place) $dom->documentElement->removeChild($list[$i]);
          $dom->documentElement->replaceChild($T,$list[$place]);
        }//if
        return $n;
  }//func

  function groupList_v3(DOMDocument &$dom, DOMNodeList &$list, $tag, $place=0) {
       // use importNode
       $n = $list->length;
       if ($n && $place<$n) {
          $rmList = array();
          $d2 = new DOMDocument;
          $T = $d2->createElement($tag);
          for($i=0; $i<$n; $i++) {
              $e = $list->item($i);
              $T->appendChild( $d2->importNode($e, true) );
      if ($i!=$place)  $rmList[] = $e;
          }
          foreach($rmList as $e)
             $dom->documentElement->removeChild($e);
          $dom->documentElement->replaceChild(
                $dom->importNode($T, true),
                $list->item($place)
          );
        }//if
        return $n;
  }//func

The little problems  and dilemmas about "best decisions" are summarized here.


texts: SYNTAX QUERY - HTML and CSS responsive navigation bar using FlexBox

texts:
I've created my own take on a navigation bar using FlexBox (currently not refined for smaller screen media queries). I would just like someone to go through my code notes and see if I am going about it correctly.

It seems to work but am I doing this inefficiently? Should i be using other methods? Have I aligned using the best procedures etc?

Ignore the fact I haven't used classes please.

    *{
      margin: 0;
      padding: 0;
    }

    body{
      background-color: #FFF;
      font-size: 1.2em;
    }

    header{
      display: grid;
      grid-template-columns: 20% 60% 20%; /*used to keep the grey bar along the whole of the top, but keep navigation selection area squashed in slightly*/
      width: 100%;
      background-color: #A6A6A6;
    }

    nav{
      grid-column: 2;

    }

    nav ul{
      display: flex;
      min-width: 500px; /*stops list items overlapping when smaller screen - will later include media query to fix*/
      margin: auto;
      /*do not use 'justify content' this causes gaps between each list item, and i want seamless link to lin kwhen hovering*/
    }

    nav ul li{
      width: 20%; /*width of each flex item is 20% as there are 5 items*/
      text-align: center; /*move text to center of individual list item*/
      list-style: none;
    }

    nav ul li a{
      display: block; /*devault is set to inline which does not expand the 'link area' to fill the list element*/
      color: #FFF;
      padding: 20px; /*this padding changes size of parent list item too*/
      text-decoration: none;
      border-right: solid #FFF 1px;
    }

    /* border decoration-------------------------------------*/
    nav ul li:hover{
      background-color: #767676;
    }

    nav ul li:first-child{
      border-left: solid #FFF 1px;
    }
    <!DOCTYPE html>

      <meta charset="utf-8">
      <link rel="stylesheet" type="text/css" href="styles/style.css" />
      <meta name="viewport" content-type="width=device-width initial-scale=1" />
      <title>NavBar Examples</title>

Home

Services

Products

Contact

About


texts:
I am brushing up on my Python, and since I would like to learn a bit about encryption, I figured I would give PyCrypto a try. I obviously wouldn't implement encryption in any production environment, but I am curious to see if I made any obvious mistakes from a security perspective, and also if my code could be optimized or made more pythonic.

PyCryptodome 3.4.6
quantumrandom 1.9.0
pyscrypt 1.6.2

from Crypto.Cipher import AES
import quantumrandom
import hmac
import hashlib
import pyscrypt

HMAC_KEY = "738525cf1f8acd06beb4cf6cd816d1dc"

class AuthenticationError(Exception):
    pass

def gen_key(password):
    """Derives a key from input string using SCrypt and returns it hex encoded."""
    hashed = pyscrypt.hash(
        password=password,
        salt="2df2e24c76d4d7b37e7ffcdf787e426b",
        N=16384,
        r=8,
        p=1,
        dkLen=16)

    return hashed.encode('hex')

def encrypt(plaintext, password):
    """Takes plaintext input and returns hex encoded ciphertext
    with hex encoded HMAC-SHA-512 hash appended."""

    key = gen_key(password)
    iv = quantumrandom.binary()[:16]
    cipher = AES.new(key, AES.MODE_CFB, iv)
    data = iv.encode("hex") + cipher.encrypt(plaintext).encode("hex")
    sig = hmac.new(HMAC_KEY, data, hashlib.sha512).digest().encode("hex")

    ciphertext = data + sig

    return ciphertext

def decrypt(ciphertext, password):
    """Takes ciphertext and password input, splits it into MAC hash and message
    data, verifies the hash and returns message plaintext if successful."""

    sig = ciphertext[-128:]
    data = ciphertext[:-128]

    if hmac.new(HMAC_KEY, data, hashlib.sha512).digest().encode("hex") != sig:
        raise AuthenticationError("Message Authentication failed!")

    iv = data[:32].decode("hex")
    message = data[32:].decode("hex")
    key = gen_key(password)
    cipher = AES.new(key, AES.MODE_CFB, iv)

    return cipher.decrypt(message)

SHARED_SECRET = "correct horse battery staple"
plaintext = "If You're Typing the Letters A-E-S Into Your Code You're Doing It Wrong"
ciphertext = encrypt(plaintext, SHARED_SECRET)

print "Ciphertext:", ciphertext

print "Decrypted:", decrypt(ciphertext, SHARED_SECRET)


texts:
I'm working on learning C++ coming from python. I'm doing some projects to help me out understanding the language a bit more.

My code works I just want to know if there is anything that I can improve on it or best practices in C++, maybe something that I should have done differently.

// Ceaser Cipher implementation

#include <iostream>
#include <string>

char shiftF(char ch, int shift, const char type)
{
    if (type == 'e')
    {
        return ch == 'z' || ch == 'Z' ? ch - 25 : ch + shift;
    }
    else if (type == 'd')
    {
        return ch == 'z' || ch == 'Z' ? ch - 25 : ch - shift;
    }
}

std::string encode(std::string str, int shift, char type)
{
    std::string tempMsg;
    for (auto ch : str)
    {
        if (isalpha(ch))
        {
            tempMsg += shiftF(ch, shift, type);
        }
        else if (isspace(ch))
        {
            // There is probably a better way to do this.
            tempMsg += " ";
        }
        else if (isalnum(ch))
        {
            continue;
        }
    }
    return tempMsg;
}

int main(int argc, char *argv[])
{
    int choice;
    std::cout << "What do you want to do? 1.Encrypt, 2.Decrypt: ";
    std::cin >> choice;
    std::string result;
    const char dec = 'd';
    const char enc = 'e';

    if (choice == 1)
    {
        int key;
        std::cout << "Enter encryption shift: ";
        std::cin >> key;

        std::string msg;
        std::cout << "Enter a message: ";

        // This doesn't work for some reason?
        // std::cin.clear();
        // std::cin.sync();

        std::cin.ignore();
        std::getline(std::cin, msg);

        result = encode(msg, key, enc);
    }

    else if (choice == 2)
    {
        int key;
        std::cout << "Enter decryption shift: ";
        std::cin >> key;

        std::string msg;
        std::cout << "Enter a message: ";

        std::cin.ignore();
        std::getline(std::cin, msg);

        result = encode(msg, key, dec);
    }
    else
    {
        std::cout << "Wrong option, exiting!";
    }

    std::cout << "Message encoded: " << result;
}


texts:
I  wrote a stack class in C++ using arrays of fixed width. Could anyone review my code ? I didn't comment on any of the functions, because I thought class itself is self explanatory. Is it a wrong approach or which kind of comments can I write?

#include <stdlib.h>
#include <iostream>

template <class T>
class Stack {
  public:
    Stack(void);    //ctor
    void push(const T& item);
    T pop(void);
    void clear(void);
    T top(void) const;
    bool empty(void) const;
    bool full(void) const;
    void print(void) const;
  private:
    static const int MAX = 50;
    T list[MAX];
    int topPtr;
};

template <class T>
Stack<T>::Stack(void) {
    this->topPtr = -1;
}

template <class T>
void Stack<T>::push(const T& item) {

    if(this->topPtr == this->MAX - 1) {
        std::cerr << "Stack overflow. Can't push" << '\n';
    } else {
        this->topPtr += 1;
        this->list[topPtr] = item;
    }
}

template <class T>
T Stack<T>::pop(void) {
    if(this->topPtr < 0) {
        std::cerr << "Stack is empty. Can't pop" << '\n';
    } else {
        T r_value = this->list[this->topPtr];
        this->topPtr -= 1;
        return r_value;
    }
}

template <class T>
void Stack<T>::clear(void) {
    this->topPtr = -1;
}

template <class T>
T Stack<T>::top(void)const {
    if(this->topPtr < 0) {
        std::cerr << "Stack is empty. No top element." << '\n';
    } else {
        return this->list[topPtr];
    }
}

template <class T>
bool Stack<T>::empty(void) const {
    return (this->topPtr == -1);
}

template <class T>
bool Stack<T>::full(void) const {
    return (this->topPtr == this->MAX -1);
}

template <class T>
void Stack<T>::print(void) const {
    for (int i = this->topPtr; i >= 0; i--)
        std::cout << this->list[i] << '\n';
}

```


texts:
We have some json template files that get deployed to our prod, QA, integration, dev servers. Various fields need to be changed depending on the server being deployed to. Right now, this is done manually on a per deployment and per server basis. I'm trying to develop a quick python script that will pull the hostname of the machine and populate the key value pair as a post deployment task before starting the app.

What's the better option. The first set of with open() directives or the nested ones.

from socket import gethostname
import json

MAPPING = {
    "HOSTNAME1":    'URL1',
    'HOSTNAME2':    'URL2',
    'HOSTNAME3':    'URL3',
    'HOSTNAME4':    'URL4'
}

def main():
    HOSTNAME = gethostname()
    FILE1 = 'D:/PATH/TO/webhook-config.json.tpl'
    FILE2 = 'D:/PATH/TO/WHERE/IWANT/IT/SAVED/webhook-config.json'
    with open(FILE1, 'r') as config_tpl, open(FILE2, 'w') as config:
        cfg = json.load(config_tpl)
        cfg['WebhooksURL'] = 'http://{URL}:3000'.format(URL=MAPPING[HOSTNAME])
        config.write(json.dumps(config, indent=4))

    with open('C:/inetpub/wwwroot/scripts/bgreportexec.json.tpl', 'r') as bg_tpl:
        bg = json.load(bg_tpl)
        bg['HOSTNAME_URL'] = 'https://{URL}'.format(URL=MAPPING[HOSTNAME])

        with open('C:/inetpub/wwwroot/scripts/bgreportexec.json', 'w') as bg_cfg:
            bg_cfg.write(json.dumps(bg_cfg, indent=4))

if __name__ == '__main__':
    main()


texts: Join() equivalent function for F# sequences

texts:
I am porting C# code to F# that makes use of LINQ's Join() extension method. Just as I use that in method call chains, I would of course like to have an F# function to pipe into. However, there is no equivalent in the Seq module, and while the same result could also be achieved with a nested lambda using Seq.where, I'd also want something that tells me by name that it is in fact a join.

I came up with this function using a simple query expression:

let seqJoin innerKeySelector outerKeySelector resultSelector (innerSequence : 'b seq) (outerSequence : 'a seq) =
    query {
            for outer in outerSequence do
            join inner in innerSequence on
                (outerKeySelector outer = innerKeySelector inner)
            select (resultSelector outer inner)
    }

While this works, I'm not sure about the idiomaticity of the API.

LINQ's Join() method has this signature:

public static IEnumerable<TResult> Join<TOuter, TInner, TKey, TResult>(
    this IEnumerable<TOuter> outer,
    IEnumerable<TInner> inner,
    Func<TOuter, TKey> outerKeySelector,
    Func<TInner, TKey> innerKeySelector,
    Func<TOuter, TInner, TResult> resultSelector)

Parameters are 'logically' ordered by importance, the first being the sequence on which the method is (syntactically) called. In F#, in order to be able to pipe the 'original' sequence into the function, that argument needs to be last instead of first, which requires shuffling the whole signature around a bit.

In order to keep the two sequences next to each other, I moved innerSequence to the second to last position, and to stay in line with their order, I also switched outerKeySelector and innerKeySelector. I wonder, though, whether once I've changed it that far, it might be more idiomatic to go all the way and make it the full reverse of the "C# version", in part because now the resultSelector parameter separates the sequences from their key selector functions and looks a bit out of place in that position. What would be the most 'natural'/idiomatic way to arrange those parameters?

As for the query itself, is that the proper way to do it with regards to laziness and expression trees that will be used under the cover? Will the seq type annotations break anything in that respect? Those were necessary to actually allow for using seq and list values as inputs.

(This is of course supposed to become an extension for the Seq module; I just haven't bothered to do that yet.)


texts: Finding anagrams in a word list using Python

texts:
##open file and create a dictionary of {"word":"sorted word"}

word_file = open("word_list(1).txt","r")
word_list = {}
for text in word_file:
    simple_text = ''.join(sorted(text.lower().strip()))
    word_list.update({text.lower().strip():simple_text})

##lowercase and sort the user input word
def simplify_entered_word():
    lower_word = ''.join(sorted(input_word.lower().strip())) #Creates a list with the lowercase, sorted letters.
    return lower_word

#Compare the sorted user input with the values of the dictionary to find the anagrams.
def find_in_dict(entered_word):
    for key,val in word_list.items():
        if val == entered_word:
            print(key,input_word)

##main loop

while True:
    input_word = input("Input the word for anagram checking: ")
    find_in_dict(simplify_entered_word())


texts:
I'm brand new to programming (in general) and C++ (in particular).  I'm learning the basics of classes and objects.

I'm trying to do the following:

Create a class called X.  It has 4 member functions, with 0 arguments, 1 argument, 2 arguments and 3 arguments, respectively.
In main(), make an object of this X class that calls each of these 4 member functions.
Modify the class so that it has a single member function with all of the arguments defaulted.

#include "stdafx.h"
#include <iostream>
#include <cmath>
using namespace std;

class X
{
public:

    void setNum_1(int);
    void setNum_2(int);
    void setNum_3(int);
    void setNum_4(int);

    double getNum_1();
    double getNum_2(int num_1);
    double getNum_3(int num_1, int num_2);
    double getNum_4(int num_1, int num_2, int num_3);

private:
    int num_1;
    int num_2;
    int num_3;
    int num_4;
};

int _tmain(int argc, _TCHAR* argv[])
{
    X testObject;

    int lNum_1 = 0;
    int lNum_2 = 0;
    int lNum_3 = 0;
    int lNum_4 = 0;

    cout << endl;
    cout << "Please enter an integer: ";
    cin >> lNum_1;

    cout << "Please enter an integer: ";
    cin >> lNum_2;

    cout << "Please enter an integer: ";
    cin >> lNum_3;

    cout << "Please enter an integer: ";
    cin >> lNum_4;

    testObject.setNum_1(lNum_1);
    testObject.setNum_2(lNum_2);
    testObject.setNum_3(lNum_3);
    testObject.setNum_4(lNum_4);

    cout << endl;
    cout << "The 1st number returned is: " << testObject.getNum_1() << endl;
    cout << "The 2nd number returned is: " << testObject.getNum_2(lNum_1) << endl;
    cout << "The 3rd number returned is: " << testObject.getNum_3(lNum_1, lNum_2) << endl;
    cout << "The 4th number returned is: " << testObject.getNum_4(lNum_1, lNum_2, lNum_3) << endl;
    cout << endl;

    return 0;
}

void X::setNum_1(int n_1)
{
    num_1 = n_1;
}

void X::setNum_2(int n_2)
{
    num_2 = n_2;
}

void X::setNum_3(int n_3)
{
    num_3 = n_3;
}

void X::setNum_4(int n_4)
{
    num_4 = n_4;
}

double X::getNum_1()
{
    return num_1;
}

double X::getNum_2(int num_1)
{
    return num_1 + num_1;
}

double X::getNum_3(int num_1, int num_2)
{
    return num_1 + num_2;
}

double X::getNum_4(int num_1, int num_2, int num_3)
{
    return num_1 + num_2 + num_3;
}

I was wondering if you can recommend some ways that I can improve this code (or let me know if I've totally botched something, which is likely the case!).


texts:
The objective was to see what numbers can be multiplied to equal 100.

Example:

1 x 1 = 1 //no match
5 x 20 = 100 //match

The objective (as I'm learning) was only to use an array as I wanted to practice how it functioned. There are probably other classes I could have used which would have been better, for example, an ArrayList to store a match rather than an array defined of [100].

I'm pretty new to programming and would like your opinion on my following block of code.

public class ArraySearchTest
{

    public ArraySearchTest()
    {
        doTest();
    }

    public void doTest()
    {
        int [] array = new int[100];
        int [] bbb = new int[11];
        int [] ans = new int[100];

        for(int i = 0; i < array.length; i++)
        {
            for(int p = 0; p < bbb.length; p++)
            {
                if( p * i == 100)
                {
                    ans[p] = (p + i);
                    System.out.println(p + " x " + i + " Equals 100");
                }
            }
        }
    }
}


texts:
Can anyone give me feedback please? I used what I have learnt so far, mainly methods, loops and arrays. I would like you view based on these topics, however, comments on how to improve are welcome.

/*ask the user for 10 numbers
store them in an array
print them "your numbers are:"
print them "Average"
print them "Max"
print them "Min"*/

import javax.swing.*;

public class homeworkArrayWFunctionstest5
{
    public static void main(String[] args) throws Exception
    {
        String listOfNums = "";
        int sum = 0;
        int population = 0;
        int average = 0;
        int maxValue = 0;
        int minValue = 0;
        String [] numsStringInput = new String[10];
        population = numsStringInput.length;
        int [] arrayNumInt = new int[population];

        numsStringInput     = UserInputs(numsStringInput,population);
        arrayNumInt         = StringToInt(numsStringInput,population);
        listOfNums          = OneLineList(numsStringInput, population);
        sum                 = TotalCalc(arrayNumInt,population);
        average             = AvarageCalc(sum, population);
        maxValue            = MaxValueCalc(arrayNumInt,population);
        minValue            = MinValueCalc(arrayNumInt,population);

        Output(listOfNums,average,minValue,maxValue);
    }

    public static String [] UserInputs(String []numsStringInput,int population)
    {
        for (int i = 0; i<population; i++)
        {
            numsStringInput [i] = JOptionPane.showInputDialog(null,"Please Input number " + (i+1) + " of " + population + " numbers","Input Table",JOptionPane.QUESTION_MESSAGE);
        }

        return numsStringInput;
    }

    public static int [] StringToInt(String[] numsStringInput,int population)
    {
        int [] arrayNumInt = new int[population];

        for (int i = 0; i<population; i++)
        {
            arrayNumInt [i] = Integer.parseInt(numsStringInput [i]);
        }
        return arrayNumInt;
    }

    public static String OneLineList(String[] numsStringInput,int population)
    {
        String listOfNums = "";
        for (int i = 0; i<population; i++)
            {
                listOfNums = listOfNums + numsStringInput [i] + " ";
            }

        return listOfNums;
    }

    public static int TotalCalc(int []arrayNumInt,int population)
    {
        int total = 0;
        for(int i=0;i < population;i++)
        {
            total = total + arrayNumInt[i];
        }
        return total;
    }

    public static int AvarageCalc(int sum,int population)
    {
        int avarage = sum / population;
        return avarage;
    }

    public static int MaxValueCalc(int []arrayNumInt,int population)
    {
        int maxValue = arrayNumInt[0];
        for(int i=1;i < population;i++)
        {
            if(arrayNumInt[i] > maxValue)
            {
              maxValue = arrayNumInt[i];
            }
        }
        return maxValue;
    }

    public static int MinValueCalc(int []arrayNumInt,int population)
    {
        int minValue = arrayNumInt[0];
        for(int i=1;i < population;i++)
        {
            if(arrayNumInt[i] < minValue)
            {
              minValue = arrayNumInt[i];
            }
        }
        return minValue;
    }

    public static void Output(String listOfNums, int average, int minValue,int maxValue )
    {
        String text = "";

        String messageText[] = new String [] {"The number you have entered are:","Average is: ","Minimum number is: ","Maximum number is: "};
        int [] textNum = new int[] {0,average,minValue,maxValue};

        text = messageText[0]+ "\n" + listOfNums;

        for (int i = 1; i<messageText.length; i++)
        {
            text = text + "\n" + messageText[i] + textNum[i];
        }
        JOptionPane.showMessageDialog(null,text,"Output Table" ,JOptionPane.INFORMATION_MESSAGE);
    }
}


texts: Generate 6 random numbers for lottery in PHP

texts:
This program generates 6 random numbers between 0 and 45 and the numbers cannot be repeated. Can this code be improved?

$numbers = [];

$i = 1;

while($i <= 6)
{
    $number = mt_rand(0, 45);

    if(!in_array($number, $numbers))
    {
        array_push($numbers, $number);
        $i++;
    }
}

sort($numbers);

echo implode(" - ", $numbers);


texts: Better way to write this branch with an exceptional retry in an embedded C environment?

texts:
A while back I wrote the following code (target is embedded C code on an 8 bit atmel device):

    bool received;
tryAgain:
    received = radioReceive(radiogram, MatchTree, CycleClock, duration);
    if (received && radiogram->timeSlit == SolicitMask)
        goto tryAgain; // not interested in recursion and the (stack) problems that could come with it
    return received;

I rarely rarely use a goto. Sometimes in embedded land, I talk myself into it. I'm aware that goto is bad, let's skip that issue. The real goal of the code flow was to capture 3 cases:

the radioReceive timed out, so we pass the false back up
it returned, but what was heard was basically a false positive, so try some more (this is somewhat exceptional)
otherwise it was good and we return true

Then we refacatored the timeSlit test to include some other conditions that we felt were false positives (new function named radiogramIsValidSync()), but we got the logic backwards. At which point, we concluded this code was screwy and should be rewritten. But we diverged on how to best express those 3 conditions.

We came up with:

do {
    bool received = radioReceive(radiogram, MatchTree, CycleClock, duration);
    if (received == false) return false;
    else if (radiogramIsValidForSync(radiogram)) return true;
} while (1);

This is terse, but I'm not a fan of meaningless while()'s (would rather use empty for conditions). I also don't care for the fact that 2 of the 3 conditions are explicit, but the other is implicit.

A more explicit version is

    bool received
tryAgain:
    received = radioReceive(radiogram, MatchTree, CycleClock, duration);
    if (received)
    {
        if (radiogramIsValidForSync(radiogram))
            return true;
        else
            goto tryAgain;
    }
    else
    {
        return false;
    }

But this still includes the goto. A terse version is:

do
{
    if (!radioReceive(radiogram, MatchTree, CycleClock, duration))
        return false;
} while (!radiogramIsValidForSync(radiogram));
return true;

It gets rid of a named variable (which could be good or bad), my real issue with this is that it has multiple logic negation points, so you have to think "backwards" in both of the important points. Finally, a for variant:

for ( ; ; )
{
    received = radioReceive(radiogram, MatchTree, CycleClock, duration);
    if (received == false)
        return false;
    else if (radiogramIsValidForSync(radiogram))
        return true;
}

But this isn't really any better than the do/while(1) variant. And at the end of that we found ourselves feeling unexcited about any of them. Is this just a case of the Law of Conservation of Ugly? Or is there a good/clear way to write this?


texts: segment tree for adding a array with single index updates

texts:
I have written a program to sum up a value between a range using segment tree and this tree also supports single index updates.
I am wondering if I have followed all the python rules for names and other pythonic nuances. Please let me know your comments.

Tree has below functions:

Modify - helps in modifying the individual array elements.
Query - given a range this function will return the sum of all the elements in the range. Such as given [3, 7) will sum up index 3 to 6 excluding 7.

def next_power_2(n):
    n -= 1
    n |= n >> 1
    n |= n >> 2
    n |= n >> 4
    n |= n >> 8
    n |= n >> 16
    n += 1
    return n

class segment_tree(object):
    def __init__(self, n, data):
        self.total_elements = n
        self.n = next_power_2(n) #segment tree is always balanced binary tree
        self.tree = [0] * self.n + data + [0] * (self.n - n)

    def build(self):
        for i in range(self.n-1, 0, -1):
            self.tree[i] = self.tree[2*i] + self.tree[2*i+1]

    def modify(self, pos, val):
        if pos < 0 or pos >= self.total_elements:
            print("check your inputs")
            return -1
        pos = pos + self.n
        self.tree[pos] = val
        while pos/2 > 0:
            self.tree[pos/2] = self.tree[pos] + self.tree[pos^1]
            pos = pos/2

    def query(self, left, right):
        if left > self.total_elements or left < 0:
            print("check your inputs")
            return -1
        if right > self.total_elements or right < 0:
            print("check your inputs")
            return -1
        left = self.n + left
        right = self.n + right
        s = 0
        while left < right:
            if left&1:
                s += self.tree[left]
                left += 1
            if right&1:
                right -= 1
                s += self.tree[right]
            left /= 2
            right /= 2
        return s

    def __repr__(self):
        return " ".join(str(i) for i in self.tree)

print("enter the number of elements")
n = int(raw_input())
print("enter the elements as space seperated integer values")
data = [int(i) for i in raw_input().split()]
st = segment_tree(n, data)
st.build()
print("enter the position and value which you want to modify as space seperated integer values")
pos, val = map(int, raw_input().split())
print("pos", pos, "value", val)
st.modify(pos, val)
print("enter the left and right range as space seperated integer values")
left, right = map(int, raw_input().split())
print("left", left, "right", right)
print("sum for the given range is:", st.query(left, right))
print(st)


texts: Find the intersection of ArrayList elements inside an ArrayList

texts:
So the structure is {{Dog,Cat,Human},{Human,Dog,Whale,rabbit,Cow},{Monkey,Human,Dog}}.

Output should be: Dog,Human.

I have to find the intersection of ArrayList elements (Strings, for now. Could be integers as well) inside the bigger ArrayList. Previously, I have seen codes of finding the intersection of separate ArrayLists, but not sure how I could do it inside the same ArrayList.

For separate ArrayLists a code like the following works. But how do I make it work for multiple ArrayLists inside one ArrayList? I was asked this in an interview. Worked for separate lists, but when the interviewer asked this, I couldn't code it out for the same ArrayList.

public class Test {

    public <String> List<String> intersection(List<String> list1, List<String> list2) {
        List<String> list = new ArrayList<String>();

        for (String t: list1) {
            if(list2.contains(t)) {
                list.add(t);
            }
        }

        return list;
    }
public static void main(String[] args) throws Exception {

        List<String> list1 = new ArrayList<String>(Arrays.asList("Dog", "Cat", "Human"));
        List<String> list2 = new ArrayList<String>(Arrays.asList("Human", "Dog", "Whale", "rabbit", "Cow"));

        System.out.println(new Test().intersection(list1, list2));

    }
}

This produces correct output for two separate ArrayLists.


texts: Finding palindromes and the longest word in a string

texts:
I have two little projects that I've been working on.

One is to find all palindromes:

function palindrome(str) {
  var replaceStrChr = str.replace(/\W/g,'').replace(/ /g,'').replace(/_/g,'').toLowerCase();
  var arrayifyStr = replaceStrChr.split('').reverse();
  var stringifyStr = arrayifyStr.join('');

  if (replaceStrChr === stringifyStr){
    return true;
  } else {
    return false;
  }
}

And the other one is to find the longest word in a string:

function findLongestWord(str){
    var arrayify = str.split(' ');
    var longest = 0;

    for(var x = 0; x < arrayify.length; x++){
        if (arrayify[x].length > longest){
            longest = arrayify[x].length;
        }
    }
    return longest;
}

What I'm looking for is a better way to do these, shortcuts, better syntax, etc.


texts: A recursive sort and filter for a nested object

texts:
I have a nested object which I need to filter and sort.

I have a nested Object where some keys like app1 are nested inside another object.
I need to be able to filter out objects with the status of True.
I also need to be able to sort by date irrespective of how deep the object is nested.

This is the expected result.

[
  "appsd",
  {
    "appsf": {
      "date": "2017-01-05T17:13:53.956Z",
      "status": false
    }
  }
] [
  "appse",
  {
    "apps1": {
      "date": "2017-02-05T17:13:53.956Z",
      "status": false
    }
  }
] [
  "apps5",
  {
    "date": "2017-03-11T15:15:39.027Z",
    "status": false
  }
] [
  "apps4",
  {
    "date": "2017-04-11T15:15:39.027Z",
    "status": false
  }
] [
  "apps2",
  {
    "date": "2017-05-11T15:15:39.027Z",
    "status": false
  }
] [
  "appsf",
  {
    "apps1": {
      "date": "2017-07-05T17:13:53.956Z",
      "status": false
    }
  }
] [
  "appb",
  {
    "apps1": {
      "date": "2017-08-05T17:13:53.956Z",
      "status": false
    }
  }
] [
  "appsa",
  {
    "apps1": {
      "date": "2017-09-05T17:13:53.956Z",
      "status": false
    }
  }
]

From this original object

var object = {
  appsa: {
    apps1: {
      date: "2017-09-05T17:13:53.956Z",
      status: false
    }
  },
  appb: {
    apps1: {
      date: "2017-08-05T17:13:53.956Z",
      status: false
    }
  },
    appsf: {
    apps1: {
      date: "2017-07-05T17:13:53.956Z",
      status: false
    }
  },
  apps2: {
    date: "2017-05-11T15:15:39.027Z",
    status: false
  },

  apps3: {
    date: "2017-06-11T15:36:33.063Z",
    status: true
  },
  apps4: {
    date: "2017-04-11T15:15:39.027Z",
    status: false
  },
  apps5: {
    date: "2017-03-11T15:15:39.027Z",
    status: false
  },
   appse: {
    apps1: {
      date: "2017-02-05T17:13:53.956Z",
      status: false
    }
  },
   appsd: {
    appsf: {
      date: "2017-01-05T17:13:53.956Z",
      status: false
    }
  },
};

Concerns about my code.

recursive style.
pushing order and deeply nested object
am also not doing any recursion on the filter.
variable naming efficiency and clarity

var object = {
  appsa: {
    apps1: {
      date: "2017-09-05T17:13:53.956Z",
      status: false
    }
  },
  appb: {
    apps1: {
      date: "2017-08-05T17:13:53.956Z",
      status: false
    }
  },
  appsf: {
    apps1: {
      date: "2017-07-05T17:13:53.956Z",
      status: false
    }
  },
  apps2: {
    date: "2017-05-11T15:15:39.027Z",
    status: false
  },

  apps3: {
    date: "2017-06-11T15:36:33.063Z",
    status: true
  },
  apps4: {
    date: "2017-04-11T15:15:39.027Z",
    status: false
  },
  apps5: {
    date: "2017-03-11T15:15:39.027Z",
    status: false
  },
  appse: {
    apps1: {
      date: "2017-02-05T17:13:53.956Z",
      status: false
    }
  },
  appsd: {
    appsf: {
      date: "2017-01-05T17:13:53.956Z",
      status: false
    }
  },
};

let apps = Object.entries(object)
  .filter(([key, value]) => !value.status)
  .sort((val=> (a, b) => {
    let temp = [];
    let sortMatch = root => {
      if (root.date) {
        temp.push(root.date);
      }
      for (let key in root) {
        if (typeof root[key] === "object") {
          sortMatch(root[key]);
        }
      }
    };
    sortMatch({
      a: a,
      b: b
    });
    val['tempB'] = temp.pop();
    val['tempA'] = temp.pop();
    return val.tempA.localeCompare(val.tempB);
  })({}));

console.log(...apps);
.as-console-wrapper {
  max-height: 100% !important;
  top: 0;
}


texts:
This is a data structure that supports the push(), pop() and isEmpty() operations and returns the least element on every pop(). In a sense, this works like a PriorityQueue, only in \$O(n)\$ runtime against the \$O(log n)\$ runtime of a PriorityQueue.

My implementation:

public class SortedStack<T extends Comparable<T>> {

    private int size;
    private  Stack<T> s1;
    private Stack<T> s2;

    public SortedStack(){

        s1 = new Stack<>();
        s2 = new Stack<>();
        size = 0;
    }
    public int compareTo(T other){
        return compareTo(other);
    }
    public void push(T item){

        size++;
        if(s1.getHead() == null){
            s1.push(item);
            return;
        }

        while(!s1.isEmpty()){
            if(s1.peek().compareTo(item) < 0){
                s2.push(s1.pop());
            }else if((s1.peek().compareTo(item) > 0) || (s1.peek().compareTo(item) == 0)){
                s1.push(item);
                break;
            }
        }
        while(!s2.isEmpty()){
            s1.push(s2.pop());
        }

    }

    public T pop(){
        size--;
        return s1.pop();

    }

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

}

The Stack implementation that it uses is as follows:

public class Stack<T>{
    private Node head;

    private class Node<T>{
        private T data;
        private Node next;

        public Node(T data){
            this.data = data;
            next = null;
        }
    }
    public Node getHead(){
        return head;
    }

    public void push(T item){
        Node p = new Node((Comparable) item);
        if(head == null){
            head = p;
            return;
        }
        p.next = head;
        head = p;

    }
    public T pop(){
        if(head == null){
            System.out.println("Popping off an empty stack!!!");
            System.exit(-1);
        }
        T item = (T) head.data;
        head = head.next;
        return item;

    }

    public T peek(){
        if(head == null){
            System.out.println("Empty Stack!!");
            System.exit(-1);
        }
        return (T) head.data;
    }

    public boolean isEmpty(){
        return head == null;
    }
}


texts:
First attempt at writing Rust code.  What do you think of the formatting?  I think the type conversions are pretty messy.  How can I make it more idiomatic?

fn quicksort(array: &mut[isize], first: usize, last: usize) {
    if first < last {
        let midpoint = partition(array, first, last);
        quicksort(array, first, midpoint - 1);
        quicksort(array, midpoint + 1, last);
    }
}

fn partition(array: &mut[isize], first: usize, last: usize) -> usize {
    let pivot = array[last];

    let i: isize = first as isize;
    let mut i: isize = i - 1;

    let mut j = first;
    while j < last - 1 {
        if array[j] < pivot {
            i = i + 1;
            let k: usize = i as usize;
            swap(array, k, j);
        }
        j = j + 1;
    }

    let k: isize = i + 1;
    let k: usize = k as usize;
    if array[last] < array[k] {
        swap(array, k, last);
    }
    return k;
}

fn swap(array: &mut[isize], a: usize, b: usize) {
    let temp = array[a];
    array[a] = array[b];
    array[b] = temp;
}

fn main() {
    let mut array = [3, 5, 1, 4, 2];
    quicksort(&mut array, 0, 4);

    println!("{:?}", array);
}


texts:
I've written this scala code and I cannot work out how/if it is possible to remove the asInstance in the definition of class Problem.

The basic idea is that there are two hierarchies

Problem
SpecificProblem
ConcreteSpecificProblem

and

SolutionFinder
SpecificSolutionFinder
ConcreteSpecificSolutionFinder

These hierarchies will branched in the future, but at the moment there is only one concrete class and its direct parents.

SolutionFinder classes operate on Problem classes, and on construction of a Problem we provide a SolutionFinder instance that we will operate on it. The type declaration of the Problem class/subclasses specifies which SolutionFinder subclass be used on it, and the SolutionFinder type declaration specifies which Problem classes it be applied to.

The aim is to be able to just call solve on any kind of Problem and have it use the appropriate methods.

As it stands, the code works fine for all the examples I have tried.

I think that it is correct to say in the type declaration of Problem, it is implicit (in the non-scala-keyword sense) that S = S[S,T] = Problem[S,T]. The compiler does not recognise this, perhaps because I'm wrong about this and perhaps because this level of recursive type definition is beyond it's capabilities. To get around this I have told it to convert this to an S using asInstance, which is a faux-pas which I would like to avoid.

So, is there a better way of doing it. Should I be prepared for unforeseen consequences?

object test {

  abstract class SolutionFinder[T <: Problem[S, T], S <: SolutionFinder[T, S]] {
    def findSolution(problem: T): Unit
  }

  abstract class SpecificSolutionFinder[T <: SpecificProblem[S, T], S <: SpecificSolutionFinder[T, S]]
    extends SolutionFinder[T, S] {
    def findSolution(specificProblem: T): Unit = findSpecificSolution(specificProblem)
    def findSpecificSolution(specifProblem:T): Unit
  }

  class ConcreteSpecificSolutionFinder
    extends SpecificSolutionFinder[ConcreteSpecificProblem,ConcreteSpecificSolutionFinder] {
    def findSpecificSolution(specificProblem: ConcreteSpecificProblem): Unit = {
      // Actual solution to problem goes here
    }
  }

  abstract class Problem[T <: SolutionFinder[S, T], S <: Problem[T, S]](solutionFinder: T) {
    def solve(): Unit = solutionFinder.findSolution(this.asInstanceOf[S]) // I WANT TO AVOID THIS
  }

  abstract class SpecificProblem[T <: SpecificSolutionFinder[S, T], S <: SpecificProblem[T, S]](specificSolutionFinder: T)
    extends Problem[T, S](specificSolutionFinder) {
    // Problem specific fields and methods
  }

  class ConcreteSpecificProblem(concreteSpecificSolutionFinder: ConcreteSpecificSolutionFinder)
    extends SpecificProblem[ConcreteSpecificSolutionFinder,ConcreteSpecificProblem](concreteSpecificSolutionFinder) {
    // Problem specific fields and methods with values
  }

  def main(args: Array[String]): Unit ={
    val solutionFinder = new ConcreteSpecificSolutionFinder
    val problem = new ConcreteSpecificProblem(solutionFinder)

    // The aim of the codes structure is to avoid writing
    solutionFinder.findSolution(problem) // (which works, but is not appropriate for how this is used)
    // and write
    problem.solve()
    // instead
  }
}


texts:
Sometimes we have this code blocks that is repeated in the same controller again and again, I reviewed the Repository Pattern but I didn't understand how to deal with some kind of these duplication.

Here is a sample of what I got here:

$orders = ( new OrderList() )
            ->where( 'order_state_id', '!=', null )
            ->where( 'address_id', '!=', null )
            ->where( 'user_id', '!=', null )
            ->where( 'id', '>', $this->idLimitation )
            ->whereHas( 'orderDetail', function ( $query ) use ( $supplier_mega ) {
                //In case he is not the super user supplier check for conditions
                if ( Auth::guard( 'supplier' )->user()->super_user != 1 ) {
                    if ( Auth::guard( 'supplier' )->user()->role == 1 ) {
                        $query->where( 'supplier_id', Auth::guard( 'supplier' )->user()->id );
                    } elseif ( in_array( Auth::guard( 'supplier' )->user()->role, [ 2, 3, 4 ] ) ) {
                        $supplier_id = ( new Supplier() )->where( 'id', Auth::guard( 'supplier' )->user()->accountant_id )->first();
                        $query->where( 'supplier_id', $supplier_id->id );
                    }
                }

Now starting from ->whereHas( 'orderDetail', function ( $query ) use ( $supplier_mega ) { is repeated in this controller about 6 times but the rest of the function is not.

How can I deal with such duplication?

Another example here (upload multiple images):

if ( $request->hasFile( 'side_image' ) ) {
            foreach ( $request->side_image as $side_image ) {
                $input['campaign_ads_id'] = $campaignAdsId;
                $filename                 = Str::random( 10 ) . '.' . $side_image->getClientOriginalExtension();
                Image::make( $side_image )->save( 'images/campaignAds/' . $filename );
                $input['side_image'] = $filename;
                ( new CampaignAdsImage() )->create( $input );
            }
        }

This code is repeated in my code twice but of-course the some parts is different like the path where I store the images for instance.


texts:
I'm trying to develop code to filter my e-mail with JavaMail, but I doubt it's the best way of doing this. And I want to collect all messages without attachment.

package service.forkinjoin;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.RecursiveAction;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.internet.MimeBodyPart;

import service.FileUtil;

public class ForkSortMessages extends RecursiveAction {

    private static final long serialVersionUID = -1092415796824205832L;
    private List<Message> listMessages;
    private List<Message> listMessagesToDelete;

    public ForkSortMessages(List<Message> listMessages, List<Message> listMessagesToDelete) {
        this.listMessages = listMessages;
        this.listMessagesToDelete = listMessagesToDelete;
    }

    @Override
    protected void compute() {

        List<RecursiveAction> actions = new ArrayList<>();

        if (this.listMessages.size() <= Runtime.getRuntime().availableProcessors()) {
            try {
                this.separateMessages();
            } catch (MessagingException | IOException e) {
                e.printStackTrace();
            }
        } else {

            int end = this.listMessages.size() / 2;
            actions.add(new ForkSortMessages(this.listMessages.subList(0, end), this.listMessagesToDelete));
            end += this.listMessages.size() % 2 == 0 ? 0 : 1;
            actions.add(new ForkSortMessages(this.listMessages.subList(end, this.listMessages.size()), this.listMessagesToDelete));
            invokeAll(actions);
        }
    }

    private void separateMessages() throws MessagingException, IOException {

        for (Message message : this.listMessages) {

            if ((this.hasNoAttachment(message.getContentType()) || (this.hasNoXmlAttachment(message)))) {
                listMessagesToDelete.add(message);
            }
        }
    }

    private boolean hasNoAttachment(String content) {
        return !content.contains("multipart/MIXED");
    }

    private boolean hasNoXmlAttachment(Message message) throws IOException, MessagingException {

        Multipart multipart = (Multipart) message.getContent();

        for (int i = 0; i < multipart.getCount(); i++) {

            MimeBodyPart mimeBodyPart = (MimeBodyPart) multipart.getBodyPart(i);

            if (Part.ATTACHMENT.equalsIgnoreCase(mimeBodyPart.getDisposition())) {

                if (FileUtil.isXmlFile(mimeBodyPart.getFileName())) {
                    return false;
                }
            }
        }

        return true;
    }
}

So what can I do to improve my code? I've tried to do like Oracle tutorial but I can't.


texts: A simple stop watch which I want to extend

texts:
I am making a very simple stopwatch functionality as below.

New will start the timer.
Pause will suspend the watch.
Start will restart again.
Session will return the duration.

#include<chrono>
#include<vector>

class Timer {
  using cppTimer  =  std::chrono::high_resolution_clock;
  using seconds   =  std::chrono::seconds;
  std::vector< int64_t > mvSession;
  cppTimer::time_point mtpNow;
  cppTimer::time_point mtPause;
  seconds mtRestart;
  bool mbIsPause;
public:

  enum Units {
    sec,
    min,
    hrs,
    end
  };

  Timer() noexcept: mbIsPause(false), mtRestart{} ,mvSession(3) {
  }

  inline void Now() noexcept {
    mtpNow    = cppTimer::now();
    mbIsPause = false;
    mtRestart = seconds(0);
  }

  inline void Pause() noexcept {
    if(!mbIsPause) {
      mtPause = cppTimer::now();
      mbIsPause = true;
    }

  }

  inline void Start() noexcept {
    if(mbIsPause) {
      mtRestart += std::chrono::duration_cast<std::chrono::seconds>(cppTimer::now() - mtPause);
      mbIsPause = false;
    }

  }

  std::vector< int64_t > SessionTime() {

    auto now   =  cppTimer::now();
    auto delay =  std::chrono::duration_cast<std::chrono::seconds>(now - mtpNow);

    if(mbIsPause) {
      mtRestart += std::chrono::duration_cast<std::chrono::seconds>(cppTimer::now() - mtPause);
    }

    auto tp =  std::chrono::duration_cast<std::chrono::seconds>(delay - mtRestart);   //+ mtRestart ;// SecondsTp(cppTimer::now()) - SecondsTp(mtpNow) + SecondsTp(mtRestart);

    mvSession[sec] = tp.count()%60;
    mvSession[min] = std::chrono::duration_cast<std::chrono::minutes>(tp).count()%60;
    mvSession[hrs] = std::chrono::duration_cast<std::chrono::hours>(tp).count();

    return mvSession;
  }

};


texts:
I am working on an interview question where I need to return the k most frequent elements given a non-empty array of integers.

Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]

Here is my code:

  public static void main(String[] args) {
    System.out.println(topKFrequent(new int[] {1, 1, 1, 2, 2, 3, 3}, 1));
  }

  private static List<Integer> topKFrequent(int[] nums, int k) {
    // freq map
    Map<Integer, Integer> freq = new HashMap<Integer, Integer>();
    for (int n : nums) {
      freq.put(n, freq.getOrDefault(n, 0) + 1);
    }
    // bucket sort on freq
    List<Integer>[] bucket = new ArrayList[nums.length + 1];
    for (int i = 0; i < bucket.length; i++)
      bucket[i] = new ArrayList<>();
    for (int key : freq.keySet()) {
      bucket[freq.get(key)].add(key);
    }
    // gather result
    List<Integer> res = new ArrayList<>();
    for (int i = bucket.length - 1; i >= 0; i--) {
      res.addAll(bucket[i]);
      if (res.size() >= k)
        break;
    }
    return res;
  }

I wanted to check whether there is any improvement/optimization can be made in this code?


texts:
I'm a beginner to Haskell (intermediate in web-dev stuff and JavaScript) and I'm not really sure what I could do better for Homework 1 of CIS194 that I'm taking online.
The problem statement is as follows (shortened):

Validate a credit card number by the following steps:

Double the value of every second digit from the right
Take the sum of the digits of the new values
Check whether the sum modulo 10 is 0.

Write the functions toDigits, toDigitsRev and doubleEveryOther for the first task, sumDigits for the second, and validate for the third.

toDigits :: Integer -> [Integer]
toDigits x
    | x <= 0       = []
    | divBy10 < 10 = [divBy10, remainder]
    | otherwise    = toDigits divBy10 ++ [remainder]
    where remainder = x `mod` 10
        divBy10   = x `div` 10

toDigitsRev :: Integer -> [Integer]
toDigitsRev x = reverse (toDigits x)

doubleEveryOther :: [Integer] -> [Integer]
doubleEveryOther xs = reverse $ doubleEveryOther' (reverse xs)
    where   doubleEveryOther' []       = []
            doubleEveryOther' (x:[])   = [x]
            doubleEveryOther' (x:y:[]) = [x, y*2]
            doubleEveryOther' (x:y:xs) = [x, y*2] ++ doubleEveryOther' xs

sumDigits :: [Integer] -> Integer
sumDigits xs = sum $ map sum $ map toDigits xs

validate :: Integer -> Bool
validate x = ((sumDigits (doubleEveryOther (toDigits x))) `mod` 10) == 0


texts:
Two integers a and b are relatively prime if and only if there are no integers:

  x > 1, y > 0, z > 0 such that a = xy and b = xz.

I wrote a program that determines how many positive integers less than n are relatively prime to n.  But my program works too slowly because the number is sometimes too big.

My program should work for n <= 1000000000.

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

int main()
{
    long long int n;
    int cntr = 0, cntr2 = 0;
    cin >> n;
    if (!n) return 0;
    vector <int> num;
    for (int i = 2; i < n; i++)
    {
        if (n % i != 0)
        {
            if (num.size()>0)
            {
                for (int j = 0; j < num.size(); j++)
                {
                    if (i % num[j] != 0)
                        cntr2++;
                }
                if (cntr2 == num.size())
                    cntr++;
                cntr2 = 0;
            }
            else
                cntr++;
        }
        else
            num.push_back(i);
    }
    cout << cntr + 1 << endl;
}


texts:
From times to times I stumble over the following situation:

I have got a class with a property that's only used if another property has a particular value, for instance:

public enum enum_ConnectionType
{
    Local,
    Server
}

public class Session
{
    private enum_ConnectionType _connectionType;
    private string _serverName; // It only makes sense if _connectionType == enum_ConnectionType.Server

    public Session(enum_ConnectionType connectionType, string serverName)
    {
        _connectionType = connectionType;
        _serverName = serverName;
    }
}

There's something that does not feel right to me.
What is your common approach on this kind of situations?

EDIT

I think both Jeff and Leonid answers are valid depending on the situation.


texts:
The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be:

1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...

Let us list the factors of the first seven triangle numbers:

1: 1
 3: 1,3
 6: 1,2,3,6
10: 1,2,5,10
15: 1,3,5,15
21: 1,3,7,21
28: 1,2,4,7,14,28
We can see that 28 is the first triangle number to have over five divisors.

What is the value of the first triangle number to have over five hundred divisors?

Here is my code :

package coderbyte;

public class Java {

    public static void main(String[] args) {

        long start = System.nanoTime();

        int number = 0;
        int index = 0;
        boolean found = false;

        while (!found) {
            int counter = 0;
            index++;
            number = index * (index + 1) / 2;
            for (int i = 1; i * i <= number; i++) {

                if (number % i == 0) {
                    counter = (number % i == i ? counter + 1 : counter + 2);
                    if (counter > 500) {
                        found = true;
                        break;
                    }
                }

            }

        }

        System.out.println(number);

        System.out.println(System.nanoTime() - start);
    }
}

Any tips on how to improve the runtime and possible shorten the code.


texts: Run a timer while waiting for user input

texts:
I am making a C# console maths test where the user answers maths questions.

I am trying to add a timer to the test, I have managed to make a timer but when I run my code it becomes a mess!

Here is some example code:

class Program
{
    public static OtherCode()
    {
        \\*other code for test
    }
    public class Timer
    {
        public static int Timers(int timeLeft)
        {
            do
            {
                Console.Write("\rtimeLeft: {0} ", timeLeft);
                timeLeft--;
                Thread.Sleep(1000);
            } while (timeLeft > 0);
            Console.Write(Environment.NewLine);
            return timeLeft;
        }
    }

    public static void Main(string[] args)
    {
        int numberOfSeconds = 30;
        Thread thread = new Thread(new ThreadStart(() => {
                TimerClass.Timers(numberOfSeconds);
            }));
        thread.Start();

        \\other code
        OtherCode();
    }
}

Here is my full code:
https://github.com/CrazyDanyal1414/mathstester

This is what it looks like when I run the code and try to type an answer to a question:

As you can see my timer code is overlapping my question code.

If I use Console.SetCursorPosition(), my timer doesn't move but When I try to type an answer to a maths question my code makes me write it on the same line as the timer like so:

Any help appreciated!


texts:
I have ended up with the following code in order to filter out some bad elements from a std::vector:

#include <iostream>
#include <vector>
#include <algorithm>

typedef struct mystruct {
    int id;
    std::string name;
};

int main()
{
    std::vector<mystruct> all_items = {{151, "test1"}, {154, "test4"}, {152, "test2"}, {151, "test1"}, {151, "test1"}, {153, "test3"}};
    std::vector<int> bad_ids = {151, 152};
    std::vector<mystruct> filter_items;

    for (const auto& item : all_items) {
        if ( std::find(bad_ids.begin(), bad_ids.end(), item.id) != bad_ids.end() ) {
            std::cout << "id: " << item.id << " is bad" << std::endl;
        } else {
            std::cout << "id: " << item.id << " is good item" << std::endl;
            filter_items.emplace_back(item);
        }
    }

    for (auto f : filter_items) {
        std::cout << "Good item: " << f.id << std::endl;
    }
}

Is there any more efficient way? Can the std::remove_copy_if or Boost be used here and how?


texts: Identifying an object pointer by generating and using a unique ID

texts:
I have an image class and a table class. To each image a single table can be "attached". Each <image, table> pair should be identified with an ID, which can later be used to get the pointer of image or table associated with that ID. Images in this "map" should be unique. Below is my solution, please let me know if it can be improved. Thanks.

browserInfo.h

#include <vector>
#include <tuple>

class BrowserInfo
{
public:
    // Returns a unique ID for the <image, table> pair
    /*
        @param  img The image file pointer
        @param  tbl     The table view pointer
        @return         A unique ID for the input pair
    */
    unsigned getId(image *img, table *tbl) const;

    /// Returns a image pointer for the given ID
    /*
        @param  uId The ID of <image, table> pair
        @return     A pointer to image file if ID exists, otherwise nullptr
    */
    image *getImage(unsigned uId) const;

    /// Returns a table pointer for the given ID
    /*
        @param  uId The ID of <image, table> pair
        @return     A pointer to table if ID exists, otherwise nullptr
    */
    table *getTable(unsigned uId) const;

private:
    // alias for the type
    using imageTableToId = std::tuple<image *, table *, unsigned>;

    // This vector keeps track of all unique <image, table> pair IDs
    mutable std::vector<imageTableToId> m_vecImageTableIds;

    // The current ID
    mutable unsigned m_iCurrentId = 0;

}; // class BrowserInfo

browserInfo.cpp

unsigned BrowserInfo::getId(image *img, table *tbl) const
{
    // first, try to see if we have worked with the provided image before
    for (auto &tuple : m_vecImageTableIds)
    {
        if (std::get<0>(tuple) == img)
        {
            // we support a single table view for each image.
            // therefore, if we find that the image is already stored
            // in our vector, we just need to update the corresponding
            // table pointer and return a new unique ID for this pair
            std::get<1>(tuple) = tbl;
            std::get<2>(tuple) = ++m_iCurrentId;

            return m_iCurrentId;
        }
    }

    // if we got here it means the image pointer wasn't stored before
    // so we can just insert a new tuple into the vector
    m_vecImageTableIds.push_back(std::make_tuple(img, tbl, ++m_iCurrentId));
    return m_iCurrentId;
}

image *BrowserInfo::getImage(const unsigned uId) const
{
    for (const auto &tuple : m_vecImageTableIds)
    {
        if (std::get<2>(tuple) == uId)
            return std::get<0>(tuple);
    }

    return nullptr;
}

table *BrowserInfo::getTable(const unsigned uId) const
{
    for (const auto &tuple : m_vecImageTableIds)
    {
        if (std::get<2>(tuple) == uId)
            return std::get<1>(tuple);
    }

    return nullptr;
}


texts:
Recently I got test task at the project, it is fairly simple:

const _ = require('underscore');

// Challenge:
//
// Write a function that accepts as argument a "function of one variable", and returns a new
// function.  The returned function should invoke the original parameter function on every "odd"
// invocation, returning undefined on even invocations.
//
// Test case:
//  function to wrap via alternate(): doubleIt, which takes a number and returns twice the input.
//  input to returned function: 1,2,3,4,9,9,9,10,10,10
//  expected output: 2, undefined, 6, undefined, 18, undefined, 18, undefined, 20, undefined

const input = [1,2,3,4,9,9,9,10,10,10];
const doubleIt = x => x * 2;

const alternate = (fn) => {
  // Implement me!
  //
  // The returned function should only invoke fn on every
  // other invocation, returning undefined the other times.
}

var wrapped = alternate(doubleIt)

_.forEach(input, (x) => console.log(wrapped(x)))
// expected output: 2, undefined, 6, undefined, 18, undefined, 18, undefined, 20, undefined

And my solution was:

const alternate = (fn) => {
  let odd = false;

  return (x) => {
    odd = !odd;

    if (odd) {
      return fn(x);
    }

    return undefined;
  };
};

// An alternate solution if ternary operator (?) is allowed according to coding standards used on the project.
// Sometimes it's treated as bad practise.
const alternateShort = (fn) => {
  let odd = false;

  return (x) => (odd = !odd) ? fn(x) : undefined;
};

And I got the reply that tech lead didn't like my solution at all and I'm not hired to the project.
I'm really confused, do you have any idea what else he could expect?
Do you see here any alternative solutions?


texts: Function to find a substring within a string

texts:
I've just completed an exercise in which I had to create a program that searches for a string within another bigger string.

If the substring exists then it is outputted to confirm and the starting index is given where the first character can be found.

Aside from printf and scanf, I am not allowed to use any other functions unless I write them myself.

My code works, however I'm concerned that I've written far more code than is necessary. WITHOUT using pointers (something I'll learn next), could I have considerably cut down the amount of code I wrote?

#include <stdio.h>
#include <stdbool.h>

int findString(char mom[], char babe[]);
int stringLength(const char string[]);
bool equalStrings(const char s1[], const char s2[]);

int main(void)
{
    char mommy[80];
    char baby[80];
    int index;

    printf("Which string do you want to search?\n");
    scanf("%s", mommy);

    printf("What do you want to search for?\n");
    scanf("%s", baby);

    index = findString(mommy, baby);

    if(index >= 0)
        printf("Yup, baby was found in mommy at index %i\n", index);
    else
        printf("Sorry, baby not found\n");

    return 0;
}

int findString(char mom[], char babe[])
{
    int index, i, j;
    int momLength = stringLength(mom);
    int babeLength = stringLength(babe);
    char test[babeLength + 1];

    for(i = 0; i <= babeLength-1; i++)
    {
        for(j = 0; j <= momLength; j++)
        {
            if(babe[i] == mom[j])
            {
                test[i] = babe[i];

                if(babe[0] == mom[j])
                    index = j;
            }
        }
    }

    test[babeLength] = '\0';

    if(equalStrings(test, babe) == true)
        return index;
    else
        return -1;
}

int stringLength(const char string[])
{
    int count = 0;

    while(string[count] != '\0')
        count++;

    return count;
}

bool equalStrings(const char s1[], const char s2[])
{
    int i = 0;
    bool areEqual;

    while(s1[i] == s2[i] && s1[i] != '\0'){
        i++;
        if(s1[i] == '\0' && s2[i] == '\0')
        {
            areEqual = true;
        }
        else
        {
            areEqual = false;
        }
    }
    return areEqual;
}


texts: Advent of Code 2 - Intcode Interpreter in Haskell

texts:
Problem

The problem definition is here. For a quick summary:

an IntCode program is an array of ints
the program counter starts from index 0, where it reads an opcode, followed by 0 or more arguments at the next indices, then proceeds to the index after the last argument
opcode 1 takes 3 arguments, a, b, and z, and sets program[z] = program[a] + program[b]
opcode 2 does the same but multiplies instead
opcode 99 takes 0 arguments and halts the program

In part 1, we take the input, replace index 1 with 12 and index 2 with 2 (restore 12 2), run the program and return index 0.

In part 2 (not shown in the link unless you solve part 1), we find which ints to replace index 1 and 2 with to produce a result where index 0 equals 19690720.

My thoughts on this code are that it could probably be simpler. I tried to separate the program counter logic from the instruction execution logic (interpret vs step), but it seems like that resulted in the need for a strange combinator whileWith. I was wondering whether there are better combinators to express this kind of loop, or if there's another approach entirely.

I considered wrapping step in ContT or ExceptT, which would allow some of the nesting to be flattened by using early exit instead, but I wasn't sure which way is best in terms of extensibility.

Any suggestions on this code are welcome, including style, structure, algorithm, etc!

Code

import Control.Arrow (second)
import Control.Monad
import Control.Monad.ST
import Data.Array
import Data.Array.ST
import Data.List (find)

data Status = InvalidOp | Terminated | Running | InvalidAddress
  deriving (Show, Eq)

newtype Program = Program {
  getInts :: Array Int Int
} deriving (Show)

-- Execute the instruction starting at `start`
step :: STArray s Int Int -> Int -> Int -> ST s Status
step arr len start = do
  op <- readArray arr start
  case op of
    99 -> return Terminated
    _ -> do
      [i, j, store] <- forM [start+1..start+3] (readArray arr)
      if not $ all inBounds [i, j, store] then
        return InvalidAddress
      else do
        [a, b] <- forM [i, j] (readArray arr)
        case op of
          1 -> writeArray arr store (a+b) >> return Running
          2 -> writeArray arr store (a*b) >> return Running
          _ -> return InvalidOp

  where inBounds ix = 0 <= ix && ix < len

interpret :: Program -> Program
interpret (Program prog) = Program $ runSTArray $ do
  let len = succ . uncurry subtract $ bounds prog
  mArr <- thaw prog
  whileWith (== Running) [0, 4..len-1]
    (step mArr len)
  return mArr

readProgram :: String -> Program
readProgram str =
  let nums = fmap read $ split ',' str
  in
  Program $ listArray (0, length nums - 1) nums

restore :: Int -> Int -> Program -> Program
restore a b = Program . (// [(1, a), (2, b)]) . getInts

-- pt 2

findNounVerb :: Program -> Int -> Maybe (Int, Int)
findNounVerb prog target =
  find ((== target) . (! 0) . getInts . interpret . ($ prog) . uncurry restore) $
      [(n, v) | n <- [0..1000], v <- [0..n]]

-- util --

split :: Eq a => a -> [a] -> [[a]]
split _ [] = []
split k xs = curr : split k rest
  where (curr, rest) = second (drop 1) $ span (/= k) xs

whileWith :: (Monad m) => (ret -> Bool) -> [inp] -> (inp -> m ret) -> m ()
whileWith _ [] _ = return ()
whileWith pred (x:xs) step = do
  res <- step x
  when (pred res) $
    whileWith pred xs step

-- end util --

main :: IO ()
main = do
  prog <- readProgram <$> getContents

  -- pt 1:
  putStrLn "Part 1:"
  let output = (! 0) . getInts . interpret . restore 12 2 $ prog
  putStrLn $ "Output: " ++ show output
  putStrLn ""

  -- pt 2:
  putStrLn "Part 2:"
  let Just (noun, verb) = findNounVerb prog 19690720
  putStrLn $ "Noun: " ++ show noun ++ "\n" ++ "Verb: " ++ show verb
  print $ 100*noun + verb


texts:
I have an array of objects:

const dataset = [
  {name: 'Marie', year: 12, country: 'Canada'},
  {name: 'Jeff', year: 18, country: 'France'},
  {name: 'Joss', year: 10, country: 'Spain'},
  {name: 'Carrie', year: 45, country: 'Belgium'},
  {name: 'Linda', year: 32, country: 'France'},
]

I want two array: one with names and one with countries:

const names = ['Marie', 'Jeff', 'Joss', 'Carrie', 'Linda']
const countries = ['Canada', 'France', 'Spain', 'Belgium', 'France']

So, I usually do:

const names = dataset.map(e => e.name)
const countries = dataset.map(e => e.country)

Is there a simplest way possibly using a single loop?


texts: Control the input of the user according to a sample string and get some info from it

texts:
I made this Python code that prints a sample string and ensures that the input of the user agrees with the sample, and then do an action with this inputted string, in this case a multiplication table.

I've made this code to practice some Python concepts, and I do not know if I did everything correctly and "in a pythonic way". I'd like to know if there's anything in this code that can be improved and things I could have done otherwise.

import re
from time import sleep

class StringController(object):
    def __init__(self, *args, **kwargs):
        self.regexp = re.compile('(?i)^show me the multiplication table of [0-9]* from [0-9]* to [0-9]*$')

    def __enter__(self, *args, **kwargs):
        print('Example string: show me the multiplication table of 10 from 5 to 20')
        self.inputedstring = input('Input: ')
        print('-'*50)
        sleep(1)
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        if exc_type:
            print('{}: {}'.format(exc_type.__name__, 'You must use the provided string'))
        else:
            print('-'*50)
        del self.inputedstring

if __name__ == '__main__':
    myobject = StringController()
    while True:
        try:
            with myobject as strcon:
                multiplication_table = list(range(int(myobject.inputedstring.split(' ')[8]), int(myobject.inputedstring.split(' ')[10])+1))
                results = list(map(lambda x : x*int(myobject.inputedstring.split(' ')[6]), multiplication_table))

                if myobject.regexp.match(myobject.inputedstring):
                    print('\n'.join(str(results) for results in results))
                else:
                    raise UserWarning('You must use the provided string')

        except (ValueError, IndexError) as WrongInput:
            print("\n")
            del WrongInput

        finally:
            del strcon

Output: