texts: Do I need Generics for these node and tree classes?

texts:
I want to implement KD tree. I have defined class Node as follows:

public static class Node{
    int id;
    public double x;
    public double y;
    public Node leftChild;
    public  Node rightChild;
    Node(int id, double x, double y){
        this.id = id;
        this.x = x;
        this.y = y;
        leftChild = null;
        rightChild = null;
    }
}

Then I have defined class KDTree in which I want to implement method contains(Node t):

public static class KDTree<T extends Node>{
    Node root;
    KDTree(Node root){
        this.root = root;
    }
    boolean contains(Node t){
        if (t == null)
            return false;
        if (t.x == root.x && t.y == root.y)
            return true;
        else
            return ...; //something else
    }
}

Do I need to use generics in class KDTree? I'm not aware of when it is a good practice to use generics and when it is not? It would be nice if someone can recommend me an article on when we have to use generics and when we don't have to.

As far as I read the declaration public static class KDTree<T extends Node> means "class KDTree contains objects that extends type Node". Is there any way to declare that class KDTree contains only objects of type Node?

Class Node represents a point in the plane, given by its x and y coordinate. Class KDTree is a tree-structure that stores the points in such a way that it is easy to answer queries of the type: give me m nearest points to my point p(x1, y1). This is the method that I use to construct KDTree:

public static Node buildKDTree(List<Node> list, boolean depth, int begin, int end){
    int middle = median(list, depth, begin, end);
    Node root = list.get(middle);
    root.leftChild = buildKDTree(list, !depth, begin, middle-1);
    depth = !depth;
    root.rightChild = buildKDTree(list, !depth, middle+1, end);
    return root;
}


texts: PHP pages with multiple conditionally displayed search elements

texts:
I'm tasked with building a PHP web application where the content displayed on each page depends on a number of variables & must be re-usable across multiple pages.

A simple example of this is a search page with multiple elements:

A "basic search" div, displayed to all users.
An "advanced search" div, displayed to some users.
A "previous search history" div, displayed to all users, relevant to only their search history. This element should auto-refresh every 60 seconds.

I need each element to be re-usable & have the ability to be refreshed independent of all other elements on the page, thus decoupled from the overall page view.

For example, on a "user_info.php" page, I may want to display the same "previous search history" div. This means I can't build everything into "search.php", otherwise I'd have to build or include "previous search history" twice - once in "search.php" and again in "user_info.php". Since the search history must auto-update, an "include" statement won't work if we use a single page view.

The approach I'm leaning towards is to start by drawing a "search template" containing a bunch of placeholders which will then be populated with HTML via XHR calls.

I'm hoping to get feedback on this approach. Please note that this is a VERY basic example which illustrates how it works. The full implementation will be more complex (ie using proper route mapping, authentication, interval timers for auto div refresh if needed, etc).

If no $_GET variables are set, let's say index.php draws this page template (assuming jQuery & Bootstrap are loaded):

        <?php if ($advancedSearchAccess) { ?>

        <?php } ?>

Then once the page has finished loading, we populate each placeholder:

$(".contentPlaceholder").each(function(e) {
    $(this).load("index.php?route=" + $(this).data("route"));
});

The divs will be populated as determined in index.php if $_GET["route"] is set. Example:

switch($_GET["route"]) {
    case "basicSearch":
        include ("basicSearch.php");
        break;
    case "advancedSearch":
        include ("advancedSearch.php");
        break;
    case "userSearchHistory":
        include ("userSearchHistory.php");
        break;
}

Now on any page I can simply include the .contentPlaceholder with the relevant data-route and that element will be displayed wherever I want, with the ability to have it re-loaded without redrawing the entire page.

I'm keen to hear any feedback on this approach; is there a better way to do this? Please keep in mind the client has requested any frameworks (React, Angular, Laravel, etc etc) not be used (Bootstrap + jQuery are allowed, hence used in my example). Also I'm aware of maximum simultaneous XHR requests; this application should have no more than 6 at a time anyway.


texts:
I have been working on a web application that produces an image out of colours. Having multiple divs works, but the load time is slow and until the image loads it's time-taking. I would like to make a table like image with lots of colors extracted from an image and display them inside a web page. I don't know which language to use to create a color box other than the code I have, But I would like to get rid of divs and possibly make the GUI not in HTML but have it available in a browser!

My working code:

<?PHP
$im = imagecreatefrompng('image.png');// open an image
$image = Array(); //array of colors
$image_x = 480; //image width
$image_y = 272; //image height
$x = 0; //x pixel in image
$y = 0; //y pixel im image
while ($x < $image_x && $y < $image_y) {
$start_x = $x;
$start_y = $y;
$color_index = imagecolorat($im, $start_x, $start_y);
$color_tran = imagecolorsforindex($im, $color_index);// make it human readable
array_push($image, join(',', $color_tran));
$x++;
if ($x > $image_x-1) {$x = 0;$y++;}
}
$i = 0;
foreach ($image as $color) {
$rgb = explode(",", $color);
if ($i > $image_x-1) {$i = 0;echo "
";}
echo "

";
$i++;
}
?>


texts:
I have implemented a java class for minHeap but it is not working as fast as I want . I want some help to change it to work faster in insertion or deleting the minimum node.

Here is my implementation:

public class MinHeap {
    private static final int d = 2;
    private int heapSize;
    private long[] heap;

    MinHeap(int capacity) {
        heapSize = 0;
        heap = new long[capacity + 1];
        Arrays.fill(heap, -1);
    }

    boolean isEmpty() {
        return heapSize == 0;
    }

    boolean isFull() {
        return heapSize == heap.length;
    }

    private int parent(int i) {
        return (i - 1) / d;
    }

    private int kthChild(int i, int k) {
        return d * i + k;
    }

    void insert(long x) {
        if (isFull())
            throw new NoSuchElementException("Overflow Exception");
        heap[heapSize++] = x;
        bubbleUp(heapSize - 1);
    }

    long findMin() {
        if (isEmpty())
            throw new NoSuchElementException("Underflow Exception");
        return heap[0];
    }

    void deleteMin() {
        delete(0);
    }

    void delete(int ind) {
        if (isEmpty())
            throw new NoSuchElementException("Underflow Exception");
        heap[ind] = heap[heapSize - 1];
        heapSize--;
        bubbleDown(ind);
    }

    private void bubbleUp(int childInd) {
        long tmp = heap[childInd];
        while (childInd > 0 && tmp < heap[parent(childInd)]) {
            heap[childInd] = heap[parent(childInd)];
            childInd = parent(childInd);
        }
        heap[childInd] = tmp;
    }

    private void bubbleDown(int ind) {
        int child;
        long tmp = heap[ind];
        while (kthChild(ind, 1) < heapSize) {
            child = minChild(ind);
            if (heap[child] < tmp)
                heap[ind] = heap[child];
            else
                break;
            ind = child;
        }
        heap[ind] = tmp;
    }

    private int minChild(int ind) {
        int bestChild = kthChild(ind, 1);
        int k = 2;
        int pos = kthChild(ind, k);
        while ((k <= d) && (pos < heapSize)) {
            if (heap[pos] < heap[bestChild])
                bestChild = pos;
            pos = kthChild(ind, k++);
        }
        return bestChild;
    }

}

Thanks in advance for your help!


texts:
I have a class like this one:

class EmailClass
{
    public string MailAdresse { get; set; }
    public string MailAdresseCC { get; set; }
}

Through a JSON deserialization I obtain a List<EmailClass> and two other strings anotherMailAddress and justAnotherMailAddress.

I need to join all those adresses in one big string (the separator is ";"). For this purpose I wrote this code:

// this one is populated in another section but it
// is put there for the sake of knowing the  variable name
List<EmailClass> splittedList

List<string> listOfAdresses = new List<string>();
string joinedAdresses = String.Empty;

listOfAdresses.AddRange(splittedList.Select(x => x.MailAdresse));
listOfAdresses.AddRange(splittedList.Select(x => x.MailAdresseCC));
listOfAdresses.Add(anotherMailAddress);
listOfAdresses.Add(justAnotherMailAdresses);

joinedAdresses = String.Join(";", listOfAdresses.Distinct().ToArray());

Now, is there a more polished way to obtain this result?
How much will Distinct() affect the performance on medium result set (~100.000 adresses)? I've read that the complexity of the function should be O(n), is this true?


texts: Linq C# pulling from table row into input fields

texts:
Today is the first time I've used Linq, so I wanted to get a code review on this and make sure I'm going about it correctly.

I'm filling text boxes and dropdown lists from a table row.

protected void Page_Load(object sender, EventArgs e)
        {

            using (DBContext da = new DBContext())
            {
                string dob;
                var detail = from a in da.tblPatients
                             where a.ID == 1198
                             select a;
                foreach (var d in detail)
                {

                    txtFirstName.Text = d.FirstName;
                    txtLastName.Text = d.LastName;
                    txtPreferredName.Text = d.PreferredName;
                    dob = d.DOB;
                    if(!String.IsNullOrEmpty(dob))
                    {
                        try
                        {
                            int lastindexofdob = 0;
                            string month = "";
                            string day = "";
                            string year = "";
                            lastindexofdob = dob.LastIndexOf("/");
                            month = dob.Substring(0, dob.IndexOf("/"));
                            day = dob.Substring(month.Length + 1, (dob.LastIndexOf("/") - month.Length) - 1);
                            year = dob.Substring(dob.Length - 4);

                            ddlDOBMonth.SelectedIndex = ddlDOBMonth.Items.IndexOf(ddlDOBMonth.Items.FindByValue(month));
                            ddlDOBDay.SelectedIndex = ddlDOBDay.Items.IndexOf(ddlDOBDay.Items.FindByText(day));
                            ddlDOBYear.SelectedIndex = ddlDOBYear.Items.IndexOf(ddlDOBYear.Items.FindByText(year));
                        }
                        catch { //error catching will go here}

                    }
                    txtAddress.Text = d.Address;
                }
            }

        }

There are actually about 20 more input fields to do, but I wanted a code review at this point.


texts: CSS animation of ravens flying in a circle

texts:
I just made a little experiment on codepen with this animation.

But I get some performance issues: sometimes it's not as smooth as it should be.

Does someone know some practice I could use to improve it?

@import url("https://fonts.googleapis.com/css?family=IM+Fell+Great+Primer");
* {
  box-sizing: border-box;
}

html, body {
  width: 100%;
  height: 100%;
  background: white;
  overflow: hidden;
}

#poem {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

p {
  font-family: "IM Fell Great Primer", serif;
  font-size: 15px;
  letter-spacing: 0.1pt;
  word-spacing: 1pt;
  line-height: 1;
  padding: 0 20px;
}

#ravens-circle {
  position: absolute;
  top: 50%;
  left: 50%;
  *width: 100%;
  *height: 100%;
  *border: solid 1px black;
  will-change: transform;
  animation: turn 20s linear infinite;
}

.ravens {
  position: absolute;
  top: 50%;
  left: 50%;
  margin: -50px;
  width: 100px;
  height: 100px;
  *border: dotted 1px black;
  background: url("https://image.noelshack.com/fichiers/2017/42/2/1508268549-crow-sprite.jpg") left center;
  animation: sprite 0.7s steps(4) infinite;
  transform: rotate(var(--a, 0deg)) translateY(-220px);
}
.ravens:nth-child(2) {
  --a: 30deg;
}
.ravens:nth-child(3) {
  --a: 60deg;
}
.ravens:nth-child(4) {
  --a: 90deg;
}
.ravens:nth-child(5) {
  --a: 120deg;
}
.ravens:nth-child(6) {
  --a: 150deg;
}
.ravens:nth-child(7) {
  --a: 180deg;
}
.ravens:nth-child(8) {
  --a: 210deg;
}
.ravens:nth-child(9) {
  --a: 240deg;
}
.ravens:nth-child(10) {
  --a: 270deg;
}
.ravens:nth-child(11) {
  --a: 300deg;
}
.ravens:nth-child(12) {
  --a: 330deg;
}

@keyframes sprite {
  100% {
    background-position: -400px;
  }
}
@keyframes turn {
  100% {
    transform: rotate(360deg);
  }
}

Huginn and Muginn

Ravens black
On wings of night
Nine worlds circled
In their flight

One-eyed Father
Hears their call-
Tidings brought
To Asgard's hall.

Thought as fast
As lightning's flash.
Mem'ry old
As sacred Ash.

Huginn and Muninn
See and hear.
Whisper all
In Odin's ear.


texts: Extracting numbers from a string into an ArrayList

texts:
This first stores a string as input, loops through it to extract all of the numbers into an ArrayList, then prints all of these numbers along with their sum and product.

How would I decompose this Java program into multiple methods?

public class Assignment1 {
    public static void main(String[] args){

        // Creates scanner for storing input string
        Scanner numScanner = new Scanner(System.in);
        String input;
        System.out.println("Enter a string of numbers to compute their sum and product:");
        System.out.println("(Enter '.' to terminate program)");
        input = numScanner.nextLine();

        // Terminates the program if there is no input
        if (input.length() == 0){
            System.out.println("Invalid input: Not enough characters");
            System.exit(-1);
        }

        // Terminates the program if the first character is '.'
        if (input.charAt(0) == '.'){
            System.out.println("Thank you for using numberScanner!");
            System.exit(-1);
        }

        // Defines all of the variables used in the loops
        int index = 0;
        int sum = 0;
        int product = 1;
        Integer start = null;
        int end = 0;
        ArrayList<Integer> numbers = new ArrayList<>();

        // Loop that extracts all numbers from the string and computes their sum and product
        while (index < input.length()){
            if (input.charAt(index) >= 'A' && input.charAt(index) <= 'Z' && start == null){
                index++;
            }else if (input.charAt(index) >= '1' && input.charAt(index) <= '9' && start == null){
                start = index;
                index++;
            }else if (Character.isDigit(input.charAt(index))){
                index++;
            }else{
                end = index;
                numbers.add(Integer.parseInt(input.substring(start,end)));
                sum += Integer.parseInt(input.substring(start,end));
                product *= Integer.parseInt(input.substring(start,end));
                index++;
                start = null;
            }
        }

        // For the last number, the end is greater than the length of the string
        // This prints the last number without using the end
        if (index == input.length()){
            numbers.add(Integer.parseInt(input.substring(start)));
            sum += Integer.parseInt(input.substring(start));
            product *= Integer.parseInt(input.substring(start));
            index++;
        }

        // Prints the Numbers, Sum and Product beside each other
        System.out.print("Numbers: ");
        for (Object a : numbers) {
            System.out.print(a.toString() + " ");
            }
        System.out.println("Sum: " + sum + " Product: " + product);
    }
}


texts: Shell script to detect router slider status

texts:
I have an openwrt router (TP-Link MR3040) and on boot I have it check the slider (AP, WISP, 3G/4G mode). The goal was to have it execute the current "slider status" vs the old one, or do nothing if it's the same (before reboot). I just want a critique on making it more elegant.

#!/bin/sh

test=$(cat /root/logs/sliderstatus)
status=""
if grep -qe "sw1.*in  hi" /sys/kernel/debug/gpio ; then
        if grep -qe "sw2.*in  hi" /sys/kernel/debug/gpio ; then

                # AP
                logger "Configure AP"
                status="AP"

        else
                # WISP
                logger "Configure WISP"
                status="CLIENT"
        fi
else

        # 3G
        logger "Configure 3G"
        status="CUSTOM"

fi

if [ $status != $test ] ; then

case $status in

CLIENT) echo "status is client, executing now"
        #sh /root/scripts/shell/CLIENT_MODE.sh &
        ;;

AP) echo "status is AP, executing now"
        #sh /root/scripts/shell/AP_MODE.sh &
        ;;

CUSTOM) echo  "status is CUSTOM, executing now"
        ;;

*) echo "ERROR status does not match ERROR"
        ;;

esac

elif [ $status == $test ] ; then

        echo " Status: $status and Slider $test are the same"

else
        echo "You shouldn't have seen this"

fi


texts: Rebase values in an array to match the chart scale

texts:
I have 2 long[24] arrays. Both of them contain values for each hour of a day. One of them has hit count and other queue times. Now queue times in ms are 5 digit numbers, counts are 2 digit numbers. I want to show them in one chart, because queue times are to some degree corresponding with hits, but the scale is totally different. So what I came up with is that I take the max value from one list and recalculate all the values from second array using that maximum.

var count = new long[24]; // values similar to [0, 9, 25, 65 ..]
var waitings = new long[24]; // values similar to [34111, 65321, 5003 ..]
count = NormalizeDataset(count, waitings.Max());
// ... skipped
@functions {

    private long[] NormalizeDataset(long[] count, long max)
    {
        long countMax = count.Max();
        var returnable = new long[24];
        for (int i = 0; i < count.Length; i++)
        {
            var l = (count[i] * max) / countMax;
            returnable[i] = l;

        }
        return returnable;
    }

}

Does doing it like this make sense? How is this problem usually solved?


texts: Avoiding dynamic RegEx creation in JavaScript

texts:
This function's job is to replace several text smilies, e.g. :D, :), :love with the appropriate smiley image.
In my opinion my code has several issues, yet the main problem is that a lot of quite similar regexes are created dynamically: one for each different smilie replaced.
As you might expect, replacing smilies in a text is a job done kindly often, so this is indeed code that is executed a lot of time, therefore I think optimizing that makes sense.

Well, why didn't I just call text.replace()?
I don't want the smilies to be replaced if they are enclosed by backticks: `

var replaceTextSmilies = function() {
    var smiliesShortcut = {};
    smiliesShortcut[':)'] = 'smile.png';
    /* adding much more */

    var smiliesWordy = {};
    smiliesWordy[':angry'] = 'angry.png';
    /* adding much more */

    function escapeRegExp(str) {
        return str.replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1");
    }

    return function(text) {
        Object.keys(smiliesWordy).forEach(function(entry) {
            var image = '';

            if(text.indexOf(entry) !== -1) {
                var regex = new RegExp('('+ escapeRegExp(entry) +')(?=(?:(?:[^`]*`){2})*[^`]*$)', 'g');
                text = text.replace(regex, image);
            }
        });
        Object.keys(smiliesShortcut).forEach(function(entry) {
            var image = '';

            if(text.indexOf(entry) !== -1) {
                var regex = new RegExp('('+ escapeRegExp(entry) +')(?=(?:(?:[^`]*`){2})*[^`]*$)', 'g');
                text = text.replace(regex, image);
            }
        });
        return text;
    };
}();


texts: Using Roslyn to find interfaces within a solution

texts:
The intent of the below code is to find all interfaces within a solution whose fully-qualified names match the given predicate. It seems to work, but as I am new to Roslyn I'm guessing there are things that could be improved. I'd appreciate any pointers.

public async Task<IImmutableList<INamedTypeSymbol>> GetMatchingInterfacesInSolution(string solutionPath, Func<string, bool> predicate)
{
    var workspace = MSBuildWorkspace.Create();
    var solution = await workspace.OpenSolutionAsync(solutionPath);
    var compilations = await Task.WhenAll(solution.Projects.Select(x => x.GetCompilationAsync()));

    return compilations
        .SelectMany(x => x.SyntaxTrees.Select(y => new { Compilation = x, SyntaxTree = y }))
        .Select(x => x.Compilation.GetSemanticModel(x.SyntaxTree))
        .SelectMany(
            x => x
                .SyntaxTree
                .GetRoot()
                .DescendantNodes()
                .OfType<InterfaceDeclarationSyntax>()
                .Select(y => x.GetDeclaredSymbol(y)))
        .Where(x => predicate(x.ToDisplayString()))
        .ToImmutableList();
}

Here's another approach I tried. I couldn't really see any benefit to doing it this way. It's more verbose and difficult to follow:

public static async Task<IImmutableList<INamedTypeSymbol>> GetMatchingInterfacesInSolution(string solutionPath, Func<string, bool> predicate)
{
    var workspace = MSBuildWorkspace.Create();
    var solution = await workspace.OpenSolutionAsync(solutionPath);
    var compilations = await Task.WhenAll(solution.Projects.Select(x => x.GetCompilationAsync()));

    return compilations
        .Select(x => x.Assembly.GlobalNamespace)
        .SelectMany(x => FindInterfacesRecursive(x, predicate))
        .ToImmutableList();
}

private static IEnumerable<INamedTypeSymbol> FindInterfacesRecursive(INamespaceSymbol @namespace, Func<string, bool> predicate)
{
    foreach (var member in @namespace.GetMembers())
    {
        var childNamespace = member as INamespaceSymbol;

        if (childNamespace != null)
        {
            foreach (var @interface in FindInterfacesRecursive(childNamespace, predicate))
            {
                yield return @interface;
            }

            continue;
        }

        var namedType = member as INamedTypeSymbol;

        if (namedType == null || namedType.TypeKind != TypeKind.Interface)
        {
            continue;
        }

        if (predicate == null || predicate(namedType.ToDisplayString()))
        {
            yield return namedType;
        }
    }
}


texts: Finding solutions on GitHub and Stack Overflow

texts:
The first part of the code opens Chrome and navigates to GitHub. If I don't find my solution, I open a new tab with ctrlt. Then my code goes to Stack Overflow and searches there for solutions.
from selenium import webdriver
from selenium.webdriver.common.keys import *
import time
import keyboard

q = input("what is your programming question : ")+(' python')
class github :
    path = "c:/users/admin/appdata/local/programs/python/python38-32/chromedriver.exe"
    driver = webdriver.Chrome(path)

    driver.get("https://github.com/")
    question = driver.find_element_by_name("q")
    time.sleep(3)

    question.send_keys(q)
    question.send_keys(Keys.RETURN)

    while True:
        if keyboard.is_pressed("ctrl+t"):
            driver.switch_to_window(driver.window_handles[-1])
            driver.get("https://stackoverflow.com/")
            question_2 = driver.find_element_by_name("q")

            question_2.send_keys(q)
            question_2.send_keys(Keys.RETURN)
            break


texts: Simple SQL query to get phrase pairs from a translations table

texts:
This is probably the noobiest SQL question ever, and I'm almost positive there's a JOIN or something in PostgreSQL for this, but I can't find it so I'm using a naive method. Here's a bit about my schema:

phrases:

CREATE TABLE phrases
(
  phrase_id bigserial NOT NULL,
  language character varying(4) NOT NULL,
  text text NOT NULL,
  CONSTRAINT phrases_pk PRIMARY KEY (phrase_id)
)

translations:

CREATE TABLE translations
(
  source_id bigint NOT NULL,
  destination_id bigint NOT NULL,
  CONSTRAINT translations_pk PRIMARY KEY (source_id, destination_id)
)

I use the following query to get 100 phrases (for two language pairs). This requires limiting the results to the language pairs, then finding their translations in the translations table:

SELECT P1.phrase_id, P1.language, P1.text, P2.phrase_id, P2.language, P2.text
FROM phrases P1, phrases P2, translations T
WHERE (P1.language = 'eng' AND P2.language = 'fra'
    AND P1.phrase_id = T.source_id
    AND P2.phrase_id = T.destination_id)
LIMIT 100

For what it's worth, the query runs in 34 ms with ~7.5m rows in the translations table, and 1m rows in the phrases table. I'll end up doing full text searches on the phrases table though, so I want to make the translation lookup as efficient as possible (as the translations table will grow ~5x faster than phrases). Lookup in translations is also the most common operation in this database.

Are there any fancy methods of accomplishing this more elegantly/efficiently in PostgreSQL?

P.S. - There is no foreign key constraint in the translations table because I am still in the process of sanitizing the database and removing old records. Importing into Postgres was impossible with the FK due to entries missing from phrases.


texts:
I wrote code to filter for duplicate elements in an array. I'd like to know your opinion, whether it's efficient at all, or if there's too many objects created, use of both array and list. That's in preparation for an interview. I'm not interested in lambdas (distinct) or helper methods, I'd like to see where I can improve and understand what's efficient or not in what I wrote, also without using Set, HashSet.
public class Duplicate {
    public static void main (String [] args){
        // filter duplicate elements
        int [] arr = {5,4,3,5,4,6,7,8,6};
        Arrays.sort(arr);
        int length = arr.length;
        List<Integer> list = new ArrayList<>();
        list.add(arr[0]);
        for(int i =0; i <length-1;i++){
            if(arr[i] != arr[i+1]){
                list.add(arr[i+1]);
            }
        }
        System.out.println(Arrays.toString(list.toArray()));
    }
}


texts: Element selectors for a RepeatButtonView

texts:
I have a large application with a wide-reaching amount of views and sub-views. I have a need to decorate DOM elements with identifiers so that my framework of choice can bind views to the DOM elements.

In attempting to choose a robust convention for naming these selectors, I've encountered a few problems:

id selectors: it's difficult to maintain unique ID selectors across a large amount of views. Prefixing IDs can help alleviate this issue, but is overly verbose.
class selectors: normally classes are used just for CSS decoration. This CSS best practices guide suggests prefixing JavaScript-only CSS classes with js- to indicate there is no CSS decoration. This helps alleviate the issue, but can lead to confusing/error-prone code due to a mixture of js- and unprefixed classes.
data selectors: I can't see any reason to not use these for this purpose aside from being very non-standard. I haven't seen this used in any production code I've looked at.

Here are examples of the three scenarios above using Backbone.Marionette. The examples should be simple enough for the framework to not matter, though.

Does anyone have additional experience/opinions to contribute to the matter? Anything incorrect about the data selector route?

id selector

Too verbose and doesn't work on collections:

var RepeatButtonView = Marionette.ItemView.extend({
    id: 'repeatButton',
    template: _.template('<div id=<%= viewId %>-repeatSingleIcon>
<div id=<%= viewId %>-repeatAllIcon>
'),
    templateHelpers: function(){
        return {
            viewId: this.id
        };
    },

    ui: function(){
        return {
           repeatSingleIcon: '#' + this.id + '-repeatSingleIcon',
           repeatAllIcon: '#' + this.id + '-repeatAllIcon'
        };
    }
});

class selector

use js- prefix to indicate class is only used for JavaScript. Potentially weird UI declaration when some classes have CSS.

var RepeatButtonView = Marionette.ItemView.extend({
    id: 'repeatButton',
    template: _.template('

'),
    ui: {
        repeatSingleIcon: '.js-repeatSingleIcon',
        repeatAllIcon: '.repeatAllIcon'
    }
});

.repeatAllIcon {
    pointer-events: all;
}

data selector

potentially confusing due to rarity of implementation

var RepeatButtonView = Marionette.ItemView.extend({
    id: 'repeatButton',
    template: _.template('

'),
    ui: {
        repeatSingleIcon: '[data-ui*=repeatSingleIcon]',
        repeatAllIcon: '[data-ui*=repeatAllIcon]'
    }
});


texts: Function returning higher order function

texts:
For the below given exercise:

  Define a function cycle which takes in three functions as arguments: f1, f2, f3. cycle will then return another function. The returned fuction should take in an integer argument n and do the following:

  return a function that takes in an argument x and does the following:

  if n is 0, just return x

  if n is 1, apply the first function that is passed to cycle to x

  if n is 2, the first function passed to cycle is applied to x, and then the second function passed to cycle is applied to the result of that (i.e. f2(f1(x))).

  If n is 3, apply the first, then the second, then the third function (i.e. f3(f2(f1(x))))

  if n is 4, apply the first, then the second, then the third, then the first function (i.e. f1(f3(f2(f1(x)))))

  And so forth

  Hint: most of the work goes inside the most nested function.

def cycle(f1, f2, f3):
    """ Returns a function that is itself a higher order function
    >>> add1 = lambda x: x+1
    >>> times2 = lambda x: 2*x
    >>> add3 = lambda x: x+3
    >>> my_cycle = cycle(add1, times2, add3)
    >>> identity = my_cycle(0)
    >>> identity(5)
    5
    >>> add_one_then_double = my_cycle(2)
    >>> add_one_then_double(1) # semanitcally the same as times2(add1(1))
    4
    >>> do_all_functions = my_cycle(3)
    >>> do_all_functions(2) # semantically the same as add3(times2(add1(2)))
    9
    >>> do_more_than_a_cycle = my_cycle(4)
    >>> do_more_than_a_cycle(2) # semantically the same as add1(add3(times2(add1(2))))
    10
    >>> do_two_cycles = my_cycle(6) # semantically the same as add3(times2(add1(add3(times2(add1(1))))))
    >>> do_two_cycles(1)
    19
    """

    " *** YOUR CODE HERE *** "

Here is the solution:

def cycle(f1, f2, f3):
    """ Returns a function that is itself a higher order function
    >>> add1 = lambda x: x+1
    >>> times2 = lambda x: 2*x
    >>> add3 = lambda x: x+3
    >>> my_cycle = cycle(add1, times2, add3)
    >>> identity = my_cycle(0)
    >>> identity(5)
    5
    >>> add_one_then_double = my_cycle(2)
    >>> add_one_then_double(1) # semanitcally the same as times2(add1(1))
    4
    >>> do_all_functions = my_cycle(3)
    >>> do_all_functions(2) # semantically the same as add3(times2(add1(2)))
    9
    >>> do_more_than_a_cycle = my_cycle(4)
    >>> do_more_than_a_cycle(2) # semantically the same as add1(add3(times2(add1(2))))
    10
    >>> do_two_cycles = my_cycle(6) # semantically the same as add3(times2(add1(add3(times2(add1(1))))))
    >>> do_two_cycles(1)
    19
    """
    def f(n):
        tple = (f1, f2, f3)
        def g(x, count = n):
            if count == 0:
                return x
            else:
                return g(tple[(n-count)%3](x), count-1)
        return g
    return f

My question:

The above solution is written in the functional paradigm. Please let me know if the code style breaks the functional paradigm.
Can the code be optimized without default valued second parameter of function g and tuple tple?

Note: In python, I do not like lambda and decorators


texts:
I've created a class that holds an EAN13 code. This class is an attribute of the Product class.

In the Ean13 class, the string that represents the EAN code is passed as a parameter to the constructor and the validation is performed in the constructor. I created some utility methods in that class, like sumEven, sumOdd, and isOdd, but I'm not sure if would be better to move it to a separated utility class.

@Embeddable
public class Ean13 {
    private static final RuntimeException NOT_VALID_EAN_EXCEPTION = new RuntimeException("NOT VALID EAN CODE");

    @Column(name = "ean_code", nullable = true, length = 13)
    private String code;

    public Ean13() {
    }

    public Ean13(String code) {
        validate(code);
        this.code = code;
    }

    private void validate(String code) {
        if (code == null || code.length() != 13) {
            throw NOT_VALID_EAN_EXCEPTION;
        }
        if (!CharMatcher.DIGIT.matchesAllOf(code)) {
            throw NOT_VALID_EAN_EXCEPTION;
        }
        String codeWithoutVd = code.substring(0, 12);
        int pretendVd = Integer.valueOf(code.substring(12, 13));
        int e = sumEven(codeWithoutVd);
        int o = sumOdd(codeWithoutVd);
        int me = o * 3;
        int s = me + e;
        int dv = getEanVd(s);
        if (!(pretendVd == dv)) {
            throw NOT_VALID_EAN_EXCEPTION;
        }
    }

    private int getEanVd(int s) {
        return 10 - (s % 10);
    }

    private int sumEven(String code) {
        int sum = 0;
        for (int i = 0; i < code.length(); i++) {
            if (isEven(i)) {
                sum += Character.getNumericValue(code.charAt(i));
            }
        }
        return sum;
    }

    private int sumOdd(String code) {
        int sum = 0;
        for (int i = 0; i < code.length(); i++) {
            if (!isEven(i)) {
                sum += Character.getNumericValue(code.charAt(i));
            }
        }
        return sum;
    }

    private boolean isEven(int i) {
        return i % 2 == 0;
    }

    @Override
    public String toString() {
        return code;
    }
}

@Entity
@Table(name = "tb_produtos")
public class Product implements Serializable {

    public Product() {
    }

    @Id
    @GeneratedValue
    private Integer id;

    @ManyToOne
    @JoinColumn(name = "ID_FABRICANTE")
    private Manufacturer manufacturer;

    @Column(name = "DESCRICAO")
    private String description;

    @Column(name = "URL")
    private String url;

    @Embedded
    private Ean13 ean;

    @Transient
    private Keywords keywords;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public void setCode (String code){
        ean = new Ean13(code);
    }

    public Manufacturer getManufacturer() {
        return manufacturer;
    }

    public void setManufacturer(Manufacturer manufacturer) {
        this.manufacturer = manufacturer;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public Keywords getKeywords() {
        return keywords;
    }

    public void setKeywords(Keywords keywords) {
        this.keywords = keywords;
    }

}


texts: Contiguous elements of the list sum to K

texts:
The task:

  Given a list of integers and a number K, return which contiguous
  elements of the list sum to K.

  For example, if the list is [1, 2, 3, 4, 5] and K is 9, then it should
  return [2, 3, 4].

My solution

// init
const arr = [1, 2, 3, 4, 5];
const K = 9;

// main
const getContiguousElementsSum = (arr, K) => {
  if (arr.length === 0 || K < 0) {
    return null;
  }
  let sum = 0;
  const returnResult = [];
  const found = arr.some(x => {
    sum += x;
    returnResult.push(x);
    return sum === K;
  });
  // exit case
  if (found) {
    return returnResult;
  }
  // recursive case
  return getContiguousElementsSum(arr.slice(1), K);
};
console.log(getContiguousElementsSum(arr, K));

Is there a shorter and/or more readable solution?


texts: Is there any faster way instead of using preg_match in the following code?

texts:
this code finds if there is the string 2004 in <date_iso></date_iso> and if it is so, I echo some data from that specific element that the search string was found.

I was wondering if this is the best/fastest approach because my main concern is speed and the XML file is huge. Thank you for your ideas.

this is a sample of the XML

<entry ID="4406">
    <id>4406</id>
    <title>Book Look Back at 2002</title>
    <link>http://www.sebastian-bergmann.de/blog/archives/33_Book_Look_Back_at_2002.html</link>
    <description></description>
    <content_encoded></content_encoded>
    <dc_date>20.1.2003, 07:11</dc_date>
    <date_iso>2003-01-20T07:11</date_iso>
    <blog_link/>
    <blog_title/>
</entry>

this is the code

<?php
$books  = simplexml_load_file('planet.xml');
$search = '2004';
foreach ($books->entry as $entry) {
    if (preg_match('/' . preg_quote($search) . '/i', $entry->date_iso)) {
        echo $entry->dc_date;
    }
}
?>


texts: Goroutine wait select operation on multiple channels

texts:
I'm trying to understand an SO answer for this question Golang select statement with channels and waitgroup.

The author of the now accepted answer goes on to say that OP's code is almost similar to this, when the function is replaced with the actual code

package main

import (
    "errors"
    "fmt"
)

func main() {
    errs := make(chan error, 1)
    success := make(chan bool, 1)
    errs <- errors.New("Some error")
    success <- true

    select {
    case err := <-errs:
        fmt.Println("error", err)
    case <-success:
        fmt.Println("success")
    }

    select {
    case err := <-errs:
        fmt.Println("error", err)
        // panic(err)
    case <-success:
        fmt.Println("success")
    }
}

What I don't understand is why are there two select wait operations? I understand that both the error and bool channels are written at the same time and there could be one handled by the select at any time, but why does OP have two instances select? Would like to understand the reason behind possibly a better way to achieve the same functionality.


texts: Converting std::chrono::time_point to/from std::string

texts:
Consider these functions that allow to convert std::chrono::time_point to/from std::string with a predefined date-time format.

constexpr size_t log10(size_t xx) { return xx == 1 ? 0 : 1 + log10(xx/10); }

template < typename Double, size_t Precision = std::numeric_limits<Double>::digits10, typename TimePoint >
requires (TimePoint::period::den % 10 != 0) && std::is_floating_point_v<Double> && Precision <= std::numeric_limits<Double>::digits10
inline bool toString(const TimePoint& timePoint, std::string& str)
{
    Double seconds = timePoint.time_since_epoch().count();
    (seconds *= TimePoint::period::num) /= TimePoint::period::den;
    auto zeconds = std::modf(seconds,&seconds);
    time_t tt = seconds;
    std::ostringstream oss;
    oss << std::put_time(std::localtime(&tt), "%Y-%m-%d %H:%M:")
        << std::setw(Precision+3) << std::setfill('0') << std::fixed << std::setprecision(Precision) << (tt%60)+zeconds;
    return oss && (str = oss.str(), true);
}

template < typename TimePoint > requires (TimePoint::period::den % 10 == 0)
inline bool toString(const TimePoint& timePoint, std::string& str)
{
    uint64_t feconds = timePoint.time_since_epoch().count() * TimePoint::period::num;
    time_t tt = feconds / TimePoint::period::den;
    std::ostringstream oss;
    oss << std::put_time(std::localtime(&tt), "%Y-%m-%d %H:%M:%S.")
        << std::setw(log10(TimePoint::period::den)) << std::setfill('0') << feconds % TimePoint::period::den;
    return oss && (str = oss.str(), true);
}

template < typename TimePoint >
bool fromString(TimePoint& timePoint, const std::string& str)
{
    std::istringstream iss(str);
    std::tm tm{};
    if (!(iss >> std::get_time(&tm, "%Y-%m-%d %H:%M:%S")))
        return false;
    timePoint  = {};
    timePoint += std::chrono::seconds(std::mktime(&tm));
    if (iss.eof())
        return true;
    if (iss.get() != '.')
        return false;
    std::string zz;
    if (!(iss >> zz))
        return false;
    static_assert(std::chrono::high_resolution_clock::period::num == 1 && std::chrono::high_resolution_clock::period::den % 10 == 0);
    zz.resize(log10(std::chrono::high_resolution_clock::period::den),'0');
    size_t zeconds = 0;
    try { zeconds = std::stoul(zz); } catch (const std::exception&) { return false; }
    timePoint += std::chrono::high_resolution_clock::duration(zeconds);
    return true;
}

with usage:

        std::string str;
        auto now = std::chrono::system_clock::now();
        toString(now,str); std::cerr << "==== " << str << std::endl;
        using DD = std::chrono::duration<size_t,std::ratio<2,3>>;
        using TP = std::chrono::time_point<std::chrono::system_clock,DD>;
        toString<double>(TP(DD(0)),str); std::cout << "==== " << str << std::endl;
        toString<double>(TP(DD(1)),str); std::cout << "==== " << str << std::endl;
        toString<double>(TP(DD(2)),str); std::cout << "==== " << str << std::endl;
        toString<double>(TP(DD(3)),str); std::cout << "==== " << str << std::endl;

        std::chrono::system_clock::time_point tp;
        str = "2017-Mar-01";                          fromString(tp,str); toString(tp,str); std::cerr << "---- " << str << std::endl;
        str = "1969-Dec-31 19:00:00.666666666666667"; fromString(tp,str); toString(tp,str); std::cerr << "---- " << str << std::endl;

Any suggestions to make them faster, c-functions free or more compact?

As the objective is to do conversions with a predefined date-time format the std::locale support of std::ostringstream and std::istringstream is useless and it is a significant slowdown. But how can I avoid this?


texts: How to search for a word in a sorted text file efficiently?

texts:
I want to write my own program to search for a word in a sorted text file. In the text file each word is in one line. I want to write this myself because I did not find any simple program (without libraries such as boost) which can provide suggestion word which means a word with most similarity. Here is my code but I don't know if I am in the right or wrong track. Appreciate any suggestion.

#include<cstdlib>
#include<fstream>
#include<iostream>
using namespace std;

int main(){

  ifstream fin;
  fin.open("/usr/dict/words");
  if(!fin.good()){cout<<"No dictionary file!\n"; exit(1);}

  fin.seekg(0,ios::end);
  int last = fin.tellg();

  fin.seekg(0,ios::beg);
  int first = fin.tellg();

  string word = "book";
  int middle = 0;
  string search;
  bool found = false;
  while(!fin.eof())
  {
        middle=(first+last)/2;
        cout<<first<<" "<<last<<" "<<" "<<middle;  //**
        fin.seekg(middle);
        fin>>search;

        cout<<search<<endl;  //**
        if(search<word)
        {
            first=middle+1;
            cout<<"a";  //**
        }
        else if(search>word)
        {
            last=middle-1;
            cout<<"b";  //**
        }
        else
        {
            found=true;
            break;
        }
        cout<<first<<" "<<last<<" "<<" "<<middle<<endl;  //**

  }

  return 0;
}


texts:
I read a bit about log and throw and anti-pattern and so on, but I still not get exactly what's the problem.

I'm using entity framework and I want to log every exception appearing with its complete stacktrace. Since this is just an API, I'm not really interested in handling it in the context.
So, this is my database-context:

public class DatabaseContext : DbContext
{
    private readonly ILog _logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

    public DatabaseContext()
        : base(Db.ConnectionString)
    {
        Database.Log = log => _logger.Debug(log);
    }

    public override async Task<int> SaveChangesAsync()
    {
        try
        {
            return await base.SaveChangesAsync();
        }
        catch (Exception exception)
        {
            _logger.Error(exception);
            throw;
        }
    }

    public override int SaveChanges()
    {
        try
        {
            return base.SaveChanges();
        }
        catch (Exception exception)
        {
            _logger.Error(exception);
            throw;
        }
    }
}

my question is: is it really bad practice to do this?


texts: JavaScript coding tips on creating a string from variables tags

texts:
To familiarize myself with Javascript (and in particular NodeJS) I embarked on a concrete project.
In this project I need to "build" the URLs of different IP cameras.
All Cameras Information are in a JSON file
Everything works correctly, but I think to use some "bad" coding part and that there is certainly better to do (not always easy to adapt and learning to a new language)
Today I therefore submit my code to you for your criticism/advice/Optimization/...
Extract from the URL creation code:
const cameras_cfg = require("./cfg/cameras.json");
const replaceAllTagsToValue = (obj, chaine) => obj.reduce((f, s) => `${f}`.replace(new RegExp(Object.keys(s)[0], 'g'), s[Object.keys(s)[0]]), chaine)

makeCameraUrl = function (camera, type, flux, user) {
    var url = camera.url;
    var Obj = {
        "@@login@@": user.login,
        "@@passwd@@": user.passwd,
        "@@ip@@": camera.ip,
        "@@stream@@": camera.flux[type].stream,
        "@@port@@": camera.flux[type].port,
        "@@flux@@": camera.flux[type][flux]
    };
    return replaceAllTagsToValue(Obj, url)
}

let cam_id = "102";
let url = makeCameraUrl(cameras_cfg.devices[cam_id], "rtsp", "hd", cameras_cfg.users.view);
console.log("Url:", url);

Extract from the cameras JSON file:
{
    "users": {
        "admin": {
            "login": "admin",
            "passwd": "xxxxx"
        },
        "view": {
            "login": "user",
            "passwd": "yyyyyy"
        }
    },
    "devices": {
        "102": {
            "id": 102,
            "name": "Cam 102 PTZ",
            "ip": "192.168.0.102",
            "url": "@@stream@@://@@login@@:@@passwd@@@@@ip@@:@@port@@/@@flux@@",
            "flux": {
                "rtsp": {
                    "stream": "rtsp",
                    "port": 554,
                    "hd": "1",
                    "sd": "2"
                }
            }
        },

        ../..

        "106": {
            "id": 106,
            "name": "Cam 106",
            "ip": "192.168.0.106",
            "url": "@@stream@@://@@ip@@:@@port@@/user=@@login@@&password=@@passwd@@&@@flux@@",
            "flux": {
                "rtsp": {
                    "stream": "rtsp",
                    "port": 554,
                    "hd": "channel=1&stream=0.sdp",
                    "sd": "channel=2&stream=0.sdp"
                }
            }
        }
    }
}

Thank you in advance for helping me to progress in the right techniques !


texts:
For a while I was thinking of a way I could have multiple objects of different types that related to each other be included in a tree.

For example, say I have CEO, Manager, Representative which all implement interface IEmployee.

I have a tree:

class ObjectNode<T> : IEnumerable<ObjectNode<T>>
{
    private object _obj;
    private Type _type;
    private readonly ICollection<ObjectNode<T>> _children = new LinkedList<ObjectNode<T>>();

    public ObjectNode<T> Parent { get; set; }

    public ObjectNode(T data)
    {
        _obj = data;
        _type = data.GetType();
    }

    public ICollection<ObjectNode<T>> Children
    {
        get { return _children; }
    }

    public ObjectNode<T> AddChild(T data)
    {
        ObjectNode<T> childNode = new ObjectNode<T>(data) { Parent = this };
        _children.Add(childNode);
        return childNode;
    }

    public void AddChildren(params T[] children)
    {
        int len = children.Length;
        for (int i = 0; i < len; ++i)
        {
            AddChild(children[i]);
        }
    }

    // The generics are necessary here in order to properly typecast object.
    // CS0693: Type parameter "T" has the same name as the type paramater from outer type "File.ObjectNode<T>"
    #pragma warning disable 0693
    public T Object<T>()
    {
        return (T)_obj;
    }
    #pragma warning restore 0693

    public new Type GetType()
    {
        return _type;
    }

    // IEnumerable implementation.
}

I can't do var employee = new ObjectNode<IEmployee>(new CEO()); and
then use employee.CEOMethod(); because employee is of type IEmployee.
I can't make employee ObjectNode<CEO> because then AddChild(T)
will be expecting type CEO. And that limits my data type to only one.
It also will not properly take my methods, since it'll be
expecting methods under File.ObjectNode<File.CEO>.

And say I wanted to add a child of CEO, the subordinates, which are of type Manager. How did I solve this problem? I added a "layer of abstraction."

If I wanted to access a CEO method, I could just do:
employee.Object<CEO>().CEOMethod(); and it would do as I need how I need.

If I wanted to add children to CEO, I could use:
var manager = employee.AddChild(new Manager { Field = 1; }) and do this X amount of times, loop through employee.Children and type check using GetType() like so:

foreach (var child in employee.Children)
        {
            if (child.GetType() == typeof(Manager))
            {
                child.Object<Manager>().ManagerMethod();
            }
            if (child.GetType() == typeof(Representative))
            {
                child.Object<Representative>().RepresentativeMethod();
            }
        }

Or simply manager.Object<Manager>.DoSomething();.

My design also allows me to have multitudes of types of IEmployee under CEO, not just Manager. CEO can have children such as AccountManager, TeamManager, etc., and the same would apply to AccountManager and TeamManager's children.

Am I doing something horribly wrong? Is this design bad? Is there a better approach that's just as flexible and allows me to traverse it like a tree? I'm trying to achieve a more efficient "data group" design implementation for entities that subordinate other entities. I feel this is almost "hacky."

NOTE: The code here is the real implementation, but the use of "Manager", "Employee", and "Representative" were examples of how it can be used.


texts: Recording user response times for a quiz

texts:
I am working on a simple quiz-type game in which the user basically is asked a series of questions and needs to provide an answer.

I'm trying to find a solid/robust way of recording how long it takes for the user to answer each question. This is a web-based game so I am using JavaScript and PHP. I am very inexperienced, so I suspect this is not the best way to do it; at least I hope it's not because it seems very weak. I would appreciate any suggestions as to how to go about making a more full-proof solution. It's not critical that the time be accurate to the millisecond I'm just looking to build something that will be consistent and accurate to within a second or two.

The reason I'm doing it like this rather than just recording the time in the browser is because, as I understand it, the data could theoretically be altered by the user. This is also why I don't send that correct and answers to the browser until the user provides an answer.

Here is my current approach:

<?php
/* get_game_data.php
 *
 * user clicks button to start game
 * and triggers ajax request sent to this file
 */
session_start();

if($_SERVER['REQUEST_METHOD'] === 'GET')
{
    if(isset($_GET['gamesettings'])){///check certian user defined game options are set

        require 'classes/Database.php';

        date_default_timezone_set("UTC");

        $_SESSION['app_start'] = new DateTime('NOW');////store time at which game/first question starts
        $_SESSION['app_index'] = 0;

        if($_GET['app'] === 'aural') {

           $db = new Database();

           $gameData = getGameData($db);///just an example
           //etc...
           //query database for game data, i.e. the questions,
           echo json_encode($gameData['questions]);//then send back to browser

           $_SESSION['right_answers'] = $gameData['answers'];///store the right answers to varify against user answers later

        }

    }
}
?>

<?php
/* post_game_data.php
 *
 * user answers question in a textbox etc.
 * then clicks a submit button which posts the answer to
 * this file via ajax again
 */
session_start();

function getTimeTaken($startDTO) {

    $endDTO     = new DateTime('NOW');
    $timeDiff   = $startDTO->diff($endDTO);
    $timeTaken  = $timeDiff->format('%s');

    return $timeTaken;
}

date_default_timezone_set("UTC");

if($_SERVER['REQUEST_METHOD'] === 'POST')
{
    if(
       isset($_POST['user_answer']) &&
       isset($_SESSION['app_index'])
    )
    {
        $index = $_SESSION['app_index'];///current question in the game
        $len = count($_SESSION['words']);///number of questions in the game
        $userAns = $_POST['user_answer'];
        $rightAns = $_SESSION['right_answers'];

        if(isset($_SESSION['app_start']))////if this is the first question
        {
            $responseTime = getTimeTaken($_SESSION['app_start']);
            unset($_SESSION['app_start']);
            $_SESSION['question_start'] = new DateTime('NOW');
        }
        else if(isset($_SESSION['question_start']))///not the first question
        {
            $responseTime = getTimeTaken($_SESSION['question_start']);
            $_SESSION['question_start'] = new DateTime('NOW');
        }

        if($index < $len)
        {
            $crtAns = $rightAns[$index];
            $mark = ($userAns == $crtAns)?1:0;///check user answer against correct answer
            $_SESSION['app_index']++;
            echo json_encode(array($crtAns, $mark, $responseTime));////send right answer to broswer with mark and response time
        }

    }

}
?>

This works pretty much as I would like it to right now but I don't have a live server to test it on, only Apache local host.


texts:
Here's a few line written for web scraping using CasperJS. The code does what it should, but how can I improve it? For example, how can I make it more reusable? It could be also nice if I could remove the for loop?

It extracts some shop names, and their coordination points, from a page that keeps all the coordinates in a global JavaScript array, called ALLshops, and the shop names in h3 headers in a div called #shoplist, then puts them together in an array like string and saves it to hard disk.

    var shopNames = [];
    var casper = require('casper').create({
    verbose: false,
    logLevel: 'debug',
    pageSettings: {
        loadImages:  false,
        loadPlugins: false
        }
});
var fs = require('fs');
function getShopNames() {
    var shopNames = document.querySelectorAll('#shop-list h3');

    return Array.prototype.map.call(shopNames, function(e) {

        // return all the names
        return e.textContent.replace("Address ","");
    });
}

// I just removed the url
casper.start('PAGE_URL_HERE_', function() {
});

casper.then(function() {
   var shopsCoords,
       i,
       j,
       shopsTotal,
       outputString,
       savePath,
       fname = 'aleksi13.txt';
       finalList = [];

    var shopsCoords = casper.evaluate(function() {
        return ALLShops;
    });

    shopNames = this.evaluate(getShopNames);

  shopsTotal = shopsCoords.length;
  for(i = 0; i < shopsTotal; i++) {
          finalList.push('['+ shopsCoords[i].coordinates.lat,shopsCoords[i].coordinates.lng, JSON.stringify(shopNames[i]) + ']');

  }
    outputString = 'The Locations Are: \n ['+finalList+']';
    savePath = fs.pathJoin(fs.workingDirectory, 'output',fname);
    fs.write(savePath, outputString, 'w');
});

casper.run();


texts: Back end validation as front end validation

texts:
I am trying to use the back end validation for front end validation and this is what I got. Maybe there is a better way to do this? If someone knows please share the knowledge.

HTML:

<form id="post-store-form" action="posts/store" method="POST">

        <input id="post-title" type="text" name="title" class="form-control" placeholder="Title">

        <textarea id="post-content" name="content"></textarea>

        <input type="submit" value="Save" class="btn btn-primary btn-block">

</form>

JS:

$('#post-store-form').submit( function(e) {

    if (!isValid()) {
        e.preventDefault();
    }
});

function isValid() {

    var formIsValid = false;
    var fields = jQuery.param({
        title: $('#post-title').val(),
        content: $('#post-content').val()
    });

    $.ajax({
        async: false,
        type: "POST",
        url: "/posts/store",
        data: fields,
        dataType: 'json',
        success: function(){
            formIsValid = true;
        },
        error: function(result) {
            var messages = [];

            $.each(result.responseJSON.errors, function( index, value ) {
                messages.push('
' + value);
            });

            bootbox.alert("" + messages + "");
        }
    });

    return formIsValid;
}

PHP Controller:

public function postStore()
{
    $headers = apache_request_headers();
    $is_ajax = (isset($headers['X-Requested-With']) && $headers['X-Requested-With'] == 'XMLHttpRequest');

    $parameters = $this->formParams;
    $validationRules = [
        'title'     => 'required|alnum',
        'content'   => 'required',
    ];

    // if validation fails return back with error messages
    if ($this->validatorFails($parameters, $validationRules)) {
        if ($is_ajax) {
            $errors = $this->getValidatorErrors($validationRules);
            http_response_code(422);
            echo json_encode(['errors' => $errors]);
            die;
        }
    }

    // if no errors and ajax, return 200
    if ($is_ajax) {
        http_response_code(200);
        echo json_encode([]);
        die;
    }

    // create new user in DB
    $this->createPostFromParams($parameters);

    Session::put('success', 'Successfully created a post.');

    return redirect('posts');
}

Is there a better way to integrate the backend validation to be also the front end validation?


texts:
Project Euler problem 48

  The series, \$1^1 + 2^2 + 3^3 + ... + 10^{10} = 10405071317\$.

  Find the last ten digits of the series, \$1^1 + 2^2 + 3^3 + ... + 1000^{1000}\$.

I made two different implementations of this problem, and added a benchmark, using rolfl's UBench library.

The code:

public class ProjEuler48 {

    private static final int DIGITS = 10;
    private static final BigInteger MOD = BigInteger.TEN.pow(DIGITS);

    public static void main(String[] args) {
        final int max = 1000;
        UBench bench = new UBench(ProjEuler48.class.getSimpleName());
        Predicate<BigInteger> predicate = value -> value.longValue() == 9110846700L;
        bench.addTask("Loops", () -> selfPowerSumMod(max, MOD), predicate);
        bench.addTask("Streams", () -> selfPowerSumModStreams(max, MOD), predicate);
        bench.report("RESULTS", bench.press(1000));
    }

    private static BigInteger selfPowerSumModStreams(int max, BigInteger mod) {
        return IntStream.rangeClosed(1, max)
                .parallel()
                .mapToObj(i -> BigInteger.valueOf(i))
                .map(bi -> bi.modPow(bi, MOD))
                .reduce(BigInteger.ZERO, BigInteger::add, BigInteger::add)
                .mod(mod);
    }

    public static BigInteger selfPowerSumMod(int max, BigInteger mod) {
        BigInteger sum = BigInteger.ZERO;
        for (int i = 1; i <= max; i++) {
            sum = sum.add(selfPower(i)).mod(mod);
        }
        return sum;
    }

    public static BigInteger selfPower(int i) {
        BigInteger result = BigInteger.valueOf(i);
        return result.modPow(result, MOD);
    }

}

Benchmark results on my machine:

RESULTS
=======

Task ProjEuler48 -> Loops: (Unit: MILLISECONDS)
  Count    :     1000      Average  :   2.5267
  Fastest  :   2.0137      Slowest  :  35.8331
  95Pctile :   4.2812      99Pctile :   8.3346
  TimeBlock : 4.718 2.646 2.801 2.280 2.191 2.128 2.119 2.124 2.132 2.127
  Histogram :   936    53    10     0     1

Task ProjEuler48 -> Streams: (Unit: MILLISECONDS)
  Count    :     1000      Average  :   0.8798
  Fastest  :   0.3701      Slowest  :  37.6239
  95Pctile :   2.7441      99Pctile :   5.5763
  TimeBlock : 3.032 1.041 1.285 0.596 0.476 0.485 0.467 0.473 0.464 0.479
  Histogram :   802    75    86    27     9     0     1

How is this code in terms of Project Euler, Java 8, performance and everything?


texts:
I have write a normal programm "Transpose the matrix" in go. Suppose input are always correct. I also read the article An Efficient Matrix Transpose in CUDA C/C++. So I keen to know how I can use Go-routines or another efficient way to problem in go way

package main

import (
    "fmt"
)

func main() {
    a := [][]int{{1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4}}
    r := transpose(a)
    fmt.Println(r)
}

func transpose(a [][]int) [][]int {
    newArr := make([][]int, len(a))
    for i := 0; i < len(a); i++ {
        for j := 0; j < len(a[0]); j++ {
            newArr[j] = append(newArr[j], a[i][j])
        }
    }

    return newArr
}


texts:
I am trying to build a function to find the highest number in a list without using the built-in functions of "apply" and "max".

I created the following code:

(define (highest-num lst)
  (define (iter lst accu)
    (cond ((null? lst) accu)
          ((< accu (first lst)) (iter (rest lst) (+ accu (- (first lst) accu))))
          (else (iter (rest lst) accu))))
  (iter lst 0))

However, I bet this could be better. Any suggestions?


texts:
I recently did a little task for fun that required me to create a class to determine if a word is a palindrome or not. I know this is quite simple, but I'd be interested to know if a real developer (I'm not a programmer) would approach the task in the same way, or if I make any amateur mistakes/do anything stupid.

My code passed the automated tests on the website, but I understand those aren't perfect.

class Palindrome
{
    public static function isPalindrome($word)
    {
        $word = strtolower($word);
        $wordLength = strlen($word);
        $wordSplitPoint = ceil($wordLength / 2);

        if ($wordLength % 2 == 0) {
            $firstHalf = substr($word, 0, $wordSplitPoint);
            $secondHalf = substr($word, $wordSplitPoint, $wordSplitPoint);
        } else {
            $firstHalf = substr($word, 0, $wordSplitPoint-1);
            $secondHalf = substr($word, $wordSplitPoint, $wordSplitPoint);
        }

        $secondHalfReversed = strrev($secondHalf);

        if ($firstHalf == $secondHalfReversed) {
            return TRUE;
        } else {
            return FALSE;
        }
    }
}

echo Palindrome::isPalindrome('Deleveled');


texts:
I am designing a class which (among other things) acts as a vertex in an undirected graph.

#include <iterator>
#include <string>

class Node
{
public:
    explicit Node(const std::string& name);
    Node(const Node&);
    Node(Node&&);

    class iterator
        : public std::iterator<std::random_access_iterator_tag, const Node>
    {
        //...
    };
    class container_proxy
    {
    public:
        iterator begin() const;
        iterator end() const;
    private:
        //...
    };

    container_proxy neighbors() const;

    add_link(Node& other);

    //...

private:
    //...
};
// to support: for (const Node& neighbor : node.neighbors())
Node::iterator begin(const Node::container_proxy&);
Node::iterator end(const Node::container_proxy&);

Now I want to define a function link_complete which:

takes any number of arguments
allows non-const Node lvalues (parameter type Node&)
allows non-const Node rvalues (parameter type Node&&)
does not allow any other parameter type.

An example usage:

Node ret_by_value();

void example_test(Node& x, Node&& y)
{
    link_complete(x, ret_by_value(), std::move(y), Node("test"));
}

Here's the solution I came up with:

#include <initializer_list>
#include <type_traits>

class Node {
    //...
public:
    static void link_complete(std::initializer_list<Node*> node_list);
};

template <typename ... Types>
struct template_all; // UNDEFINED

template <>
struct template_all<>
  : public std::true_type {};

template <typename ... Types>
struct template_all<std::false_type, Types...>
  : public std::false_type {};

template <typename ... Types>
struct template_all<std::true_type, Types...>
  : public template_all<Types...>::type {};

template <typename ... Args>
auto link_complete(Args&& ... args) ->
  typename std::enable_if<
    template_all<
      typename std::is_same<
        typename std::remove_reference<Args>::type,
        Node
      >::type ...
    >::value,
    void
  >::type
{
    Node::link_complete( { &args... } );
}

It seems to work as required, but I'm wondering if there was a simpler or "prettier" way to do it, or maybe a way to improve that template_all helper type.  All C++11, TR1, and Boost features are welcome.  I did notice boost::mpl::and_ looks similar to my template_all helper type, but Boost MPL seems like a tricky learning curve and/or overkill for this problem.


texts: Using goto with DataReader to get sproc return value

texts:
I want to get a second-opinion on my use of goto.

SqlCommand and SqlDataReader only read the RETURN-value of a Stored Procedure after the SqlDataReader has been closed. This is a problem if you want to interrogate the return-value to make a decision regarding how you want to read the data.

In my case, the stored procedure I'm calling returns multiple output data tables followed by an integer return value. The number of output data tables is variable.

// ret is a POCO domain entity object: a strongly-typed representation of the sproc's returned data
using( DbDataReader rdr = cmd.ExecuteReader() ) {

    if( !rdr.Read() )
        goto readReturnValue;

    ret.Foo  = ReadFoo( rdr );

    //////////

    if( !rdr.NextResult() )
        goto readReturnValue;

    List<Bar> bars = new List<Bar>();
    while( rdr.Read() ) bars.Add( ReadBar( rdr ) );
    ret.Bars = bars.ToArray();

    //////////

    if( !rdr.NextResult() )
        goto readReturnValue;

    ret.Qux = ReadQux( rdr );

    //////////

    if( !rdr.NextResult() )
        goto readReturnValue;

    List<Blargh> blarghs = new List<Blargh>();
    while( rdr.Read() ) blarghs.Add( ReadBlargh( rdr, ) );
    ret.Blarghs = blarghs.ToArray();

    // repeat a few more times...
}

readReturnValue:
Int32 returnValue = (Int32)returnParameter.Value;
switch( returnValue ) {
    case 0: // do stuff
    case 1: // do other stuff
    case ...
}

The first alternative that comes to mind is to remove the negation operator (!) from each if( !rdr.NextResult() ) and move each subsequent operation to a branch under the if, but this results in code many layers deep as there's about 8 or more result sets.

Another alternative is to replace goto readReturnValue with a throw and throw my own custom exception, e.g. throw new NoNextResultException() and in the catch block that surrounds the using I would swallow the exception and have the return-value interrogation code in the finally block, or in code immediately following the try block:

try {
    using( DbDataReader rdr = cmd.ExecuteReader() ) {

        if( !rdr.Read() )
            throw new NoNextResultException();

        ret.Foo  = ReadFoo( rdr );
        ...
    }
} catch(NoNextResultException) {
}
Int32 returnValue = (Int32)returnParameter.Value;
switch( returnValue ) {
...

But the problem with that is that throw statements don't define where the exception lands: so removing the catch statement means the program will compile, but crash due to an unhandled exception when it runs, whereas removing the goto label readReturnValue means the program won't compile, which is safer. Furthermore it avoids the expensive cost of throwing and catching exceptions as well as sticking to the mantra of "use exceptions for exceptional circumstances, not for program flow" - which is what it would be if I did convert it to a try/throw/catch.

Is my use of goto then justified?


texts: Create a random string with a set prefix

texts:
I was curious on how I could create a random string and have it have a set prefix.  Lets say, as an example, 3456.  This question is more referring to how I would join two strings together, my prefix and my random string.
To give a more comprehensive exmaple of what i'm looking for, let's say I generate the string "ab8897fjs".  I would like to add my prefix to that string to make it "3456ab8897fjs".
Thank you!
Add: This is my code for string generation.
char *randstring(size_t length) {

    static char charset[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789,.-#'?!";
    char *randomString = NULL;

    if (length) {
        randomString = malloc(sizeof(char) * (length +1));

        if (randomString) {
            for (int n = 0;n < length;n++) {
                int key = rand() % (int)(sizeof(charset) -1);
                randomString[n] = charset[key];
            }

            randomString[length] = '\0';
        }
    }

    return randomString;
}


texts: Parsing potentially nonexistant JSON fields in JavaScript

texts:
Context: I'm currently toying with the Google Geocode API to break down address strings into a more machine-friendly format. The problem is that neither the user input or API output are 100% consistent, and I would receive less entries in the JSON response than expected. For example, requesting "Times Square NY" gives me 6 address components

"address_components" : [
        {
           "long_name" : "Manhattan",
           "short_name" : "Manhattan",
           "types" : [ "political", "sublocality", "sublocality_level_1" ]
        },
        {
           "long_name" : "New York",
           "short_name" : "New York",
           "types" : [ "locality", "political" ]
        },
        {
           "long_name" : "New York County",
           "short_name" : "New York County",
           "types" : [ "administrative_area_level_2", "political" ]
        },
        {
           "long_name" : "New York",
           "short_name" : "NY",
           "types" : [ "administrative_area_level_1", "political" ]
        },
        {
           "long_name" : "United States",
           "short_name" : "US",
           "types" : [ "country", "political" ]
        },
        {
           "long_name" : "10036",
           "short_name" : "10036",
           "types" : [ "postal_code" ]
        }

But, for some reason, "Times Circle NY" gives me 8 address components (notice, for example, how "Times Square NY" does not contain a route entry):

{
           "long_name" : "10",
           "short_name" : "10",
           "types" : [ "street_number" ]
        },
        {
           "long_name" : "Columbus Circle",
           "short_name" : "Columbus Cir",
           "types" : [ "route" ]
        },
        {
           "long_name" : "Manhattan",
           "short_name" : "Manhattan",
           "types" : [ "political", "sublocality", "sublocality_level_1" ]
        },
        {
           "long_name" : "New York",
           "short_name" : "New York",
           "types" : [ "locality", "political" ]
        },
        {
           "long_name" : "New York County",
           "short_name" : "New York County",
           "types" : [ "administrative_area_level_2", "political" ]
        },
        {
           "long_name" : "New York",
           "short_name" : "NY",
           "types" : [ "administrative_area_level_1", "political" ]
        },
        {
           "long_name" : "United States",
           "short_name" : "US",
           "types" : [ "country", "political" ]
        },
        {
           "long_name" : "10019",
           "short_name" : "10019",
           "types" : [ "postal_code" ]
        }

My code: To work with the JSON in a more reasonable format, for ex. getting rid of the short_name or accessing a field by component type, I've written an object constructor that goes like this:

class Address {
constructor(googleJson) {
    try {
        this.state= googleJson["results"][0]["address_components"].filter(el => JSON.stringify(el["types"]) === JSON.stringify(["administrative_area_level_1", "political"]))[0]["short_name"];
    }
    catch (e) {
        this.state= "";
    }
    try {
        this.city= googleJson["results"][0]["address_components"].filter(el => JSON.stringify(el["types"]) === JSON.stringify(["administrative_area_level_2", "political"]))[0]["long_name"];
    }
    catch (e) {
        this.city= "";
    }
    try {
        this.lat = googleJson["results"][0]["geometry"]["location"]["lat"].toString();
    }
    catch (e) {
        this.lat = "";
    }
    // And so on...

And it works perfectly fine, does its job, but half of my code is just these try/catch pairs. Is there any smarter way to attempt to read multiple potentially empty JSON fields without so much code repetition?

Also, since I'm here, I found the filter I wrote inside each try/catch to be quite legible, but I fear the constructor as a whole would be \$O(n \times m)\$. What other way could I read the JSON in \$O(n + m)\$ and maintain legibility?


texts:
The full problem description can be found here, a slightly trimmed version below:

A car driver is travelling on an isolated road (no gas stations, houses, or cell phone coverage). The driver glances at their fuel gauge: there is exactly half a tank left. They stop and see that the fuel tank is leaking.
The driver cannot repair the leak. Using a container of known volume and a wristwatch, they measure the rate of fuel loss at  gallons per hour. They empty the container back into the tank.
The driver checks the manual and sees the fuel tank capacity is  gallons. There's also a table resembling the one below, showing declining fuel efficiency in miles per gallon (MPG) as driving speed in miles per hour (MPH) increases. They must trade one against the other in an attempt to reach the nearest gas station  miles away before nightfall.
Speed (MPH)  Fuel Efficiency (MPG)
         55                   22.0
         60                   21.3
         65                   20.2
         70                   18.3
         75                   16.9
         80                   15.8

The driver assumes manuals authors are experts, and has an aversion to interpolation (and extrapolation), they decide to drive at exactly one of the 6 speeds listed. That way, the distance travelled before running out of gas will be 100% predictable.
Can the driver reach the gas station before running out of fuel? If so, what is the maximum speed they can drive?

Examples:

Input
Output

18 0.5 16055 22.060 21.365 20.270 18.375 16.980 15.8
YES 60

16 0.07 16055 20.4960 18.4065 17.7870 17.1075 16.3880 15.60
NO

main.rs
use std::io::{self, BufRead};

#[derive(Debug)]
struct Car {
    capacity: f32,
    rate_of_loss: f32,
    remaining: f32,
    efficiancy: Vec<MPG>,
}

#[derive(Debug)]
struct MPG {
    mph: f32,
    mpg: f32,
}

impl Car {
    fn in_range(&self, distance: f32) -> f32 {
        let mut res: f32 = -1.0;
        let volume = self.capacity * self.remaining;
        for entry in &self.efficiancy {
            let time = distance / entry.mph;
            let total_loss = time * self.rate_of_loss;
            let max_distance = (volume - total_loss) * entry.mpg;
            if max_distance > distance {
                res = res.max(entry.mph);
            }
        }
        res
    }
}

fn main() {
    let remaining: f32 = 0.5;
    let mut c: f32 = 0.0;
    let mut x: f32 = 0.0;
    let mut m: f32 = 0.0;
    let mut efficiancies: Vec<MPG> = Vec::new();

    let stdin = io::stdin();
    for (i, line) in stdin.lock().lines().map(|x| x.unwrap()).enumerate() {
        let nums: Vec<f32> = line
            .split_whitespace()
            .map(|n| n.parse().unwrap())
            .collect();
        if i == 0 {
            c = nums[0];
            x = nums[1];
            m = nums[2];
        } else {
            efficiancies.push(MPG {
                mph: nums[0],
                mpg: nums[1],
            });
        }
    }
    let car = Car {
        capacity: c,
        rate_of_loss: x,
        remaining: remaining,
        efficiancy: efficiancies,
    };
    let y = car.in_range(m);
    if y > 0.0 {
        println!("YES {:.0}", y);
    } else {
        println!("NO");
    }
}

I did initially write a smaller version that did everything in the main function, but I wanted to try using struct and impl. I primarily use python, so I'm mostly looking for pointers on style/idiomatic rust and intermediate/advanced topics that I could try out. Any advice is welcome :)


texts: Fantasy league tracker for Game of Thrones

texts:
So I've just started learning about MySQL and PHP to create a fantasy league tracker for Game of Thrones for my office. I got it to technically work fine, but I think it's way clunkier than it has to be, with a lot of repeated code, and I'd like to know how to clean it up and streamline things.

I'd also ideally like to find a way to sort the tables by the final points tally, which I just don't see as possible the way I have it set up. The code that is here is only for one player and their chosen characters, but there would be about 9 other players. All of that info is in the database where the characters and players share an id to match them up.

Here's the PHP:

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Cosmic Game of Thrones</title>
    <link rel="stylesheet" href="styles.css">

<?php
$servername = "cosmicgot.dev";
$username = "root";
$password = "root";
$dbname = "gameofthrones";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT a.name,a.active,a.survived,a.dead,a.killer,b.playername, a.player_id FROM characters AS a LEFT JOIN player AS b ON a.player_id = b.player_id";
$result = $conn->query($sql);

#Andrew
echo "
". "Andrew". "
";
echo "
";
echo "
Character	Active	Survivor	Dead	Murderer	Total
";

while ($row = mysqli_fetch_array($result)) {

    $row["killer"] = $row["killer"] * 10;
    $row["survived"] = $row["survived"] * 10;

    if($row['player_id'] == 1) {
    echo "
";
    echo "" . $row["name"] . "	";

        if ($row['active'] == 1) {
            echo "" . "Active" . "	";
        }
        if ($row['active'] == 0){
            echo "" . "Not Active" . "	";
        }

    echo "" . $row["survived"] . "	";

    if ($row['dead'] == 0) {
            echo "" . $row['dead'] . "	";
        }
    if ($row['dead'] == 1) {
            $row['dead'] = $row['dead'] - 11;
            echo "" . $row['dead'] . "	";
        }

    echo "" . $row["killer"] . "	";

    $totals = $row["killer"] + $row["survived"] + $row["dead"];
    echo "" . $totals . "	";

    echo "
";
    }
}
    echo "
";

    mysqli_data_seek($result, 0);

?>

And here are the schemas

USE gameofthrones;

DROP TABLE IF EXISTS player;
CREATE TABLE player
(
    player_id               int unsigned NOT NULL auto_increment, #unique player id
    playername      varchar(40) NOT NULL, #player name

    PRIMARY KEY     (player_id)
);

DROP TABLE IF EXISTS characters;
CREATE TABLE characters
(
    name            varchar(40) NOT NULL, #character name
    active          tinyint(1) unsigned NOT NULL, #char active status
    survived        smallint unsigned NOT NULL, #char alive status
    dead            smallint unsigned NOT NULL, #char dead status
    killer          smallint unsigned NOT NULL, #char killed amount
    player_id       int unsigned NOT NULL, #assign player id to character

    PRIMARY KEY     (name)
);


texts:
Can you please check my code if it is correct for the problem 100 doors?

This is the problem:

  You have 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, you visit every door and toggle the door (if the door is closed, you open it; if it is open, you close it). The second time you only visit every 2nd door (door #2, #4, #6, ...). The third time, every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
  Question: What state are the doors in after the last pass? Which are open, which are closed?

static void Main(string[] args)
    {
        bool[] doors = new bool[100];

        bool test = true;
        bool temp1 = false;
        bool temp2 = true;
        bool temp;

        for (int i = 1; i <= 100; i++) {

            if (i == 3) {
                temp = temp1;
                temp1 = temp2;
                temp2 = temp;
            }

            if (test == true) {

                for (int a = 1; a <= 100; a++) {

                    if (a % i == 0) {

                        doors[a - 1] = temp1;
                    }
                    else if(a % i != 0)
                        doors[a - 1] = temp2;
                }
            }
            else if (test == false) {

                for (int c = 0; c < 100; c++) {

                    doors[c] = true;

                }
                test = true;
            }
        }
        for (int d = 0; d < 100; d++) {
            Console.WriteLine(doors[d]);
        }

            Console.ReadKey();
    }
}


texts: Sorting a numbered table of contents and the contents associated with it

texts:
Given a numbered table of contents with headers and the content of each section, I wanted to sort them correctly according to only the numeric value.

The first challenge: section numbers can be tricky to sort (i.e. sorted(["1.1.1", "1.1.2", "1.1.10"]) results in: ["1.1.1", "1.1.10", "1.1.2"] which is alphabetically correct, but not what I want).

Thankfully, this problem is already solved here.

Using similar logic, I want to make an OrderedDict that has for key a list of headers (where each header is a string concatenation of the section number and its title) and for value the contents of each section.

I came up with the following solution, but I want some feedback, because it seems convoluted (although it seems to be doing what I want):

from collections import OrderedDict
import re

headers = ['4.2.10 Context 4', '4.2.11 Context 5', '4.2.0 Context 1', '4.2.1 Context 2', '4.2.2 Context 3']
sections = ['C4', 'C5', 'C1', 'C2', 'C3']

def section_sort(t):
    section = t[0]
    numbering_pattern = re.compile('\d.\d[.\d]*')

    if numbering_pattern.match(section.split(' ')[0]):
        s_nbr = section.split(' ')[0]
        return [int(_) for _ in s_nbr.split('.')]

contents = OrderedDict(sorted(zip(headers, sections), key=section_sort))

for k, v in contents.items():
    print('{header}\n\t{section}'.format(header=k, section=v))

Output:

4.2.0 Context 1
  C1
4.2.1 Context 2
  C2
4.2.2 Context 3
  C3
4.2.10 Context 4
  C4
4.2.11 Context 5
  C5

What's your take on this?


texts: Displaying a single record based on DocID

texts:
I have a table with ~900,000 records. I need to display a single record based on DocID using this query. The record is the latest record that got modified by another program.

This piece of query run ~7 seconds:

SELECT        TOP 1 t.Register
FROM            PxStats AS s INNER JOIN Therapy AS t ON s.ID = t.ID
WHERE        (s.Date = DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE()))) AND (t.DocID = 1)
ORDER BY s.Time DESC

I do not have access to modify the tables design, the table is indexed by ID, but I can't filter the record based on ID because the latest iD is not guaranteed the latest record modified.


texts: Program Arcade Games: Ch 16 Worksheet 2D-Array Algorithm

texts:
The check_celebrity() function below takes an n*n grid as its parameter and prints the celebrity if there is one.
A celebrity is a person who is known by everybody but doesn't know anybody except himself.
If grid [ i ] [ j ] equals 1,  "i" knows "j".
If grid [ i ] [ j ] equals 0,  "i" doesn't know "j".
However, I am not satisfied with this one because there are too many loops inside loops and if checks. Are there any ways I can improve it?
def check_celebrity(grid):
    known = 0
    unknown = 0

    for i in range(len(grid)):
       ## Reset these variable for every person i
        known = 0
        unknown = 0
        for j in range(len(grid)):
            if grid[i][j] == 0:
                unknown += 1

            ## if he doesn't know anybody,
            ## check if every other "j" knows him
            if unknown == len(grid)-1:
                for j in range(len(grid)):
                    if grid[j][i] == 1:
                        known += 1

                    if known == len(grid):
                        print("#{} is the one.".format(i))
                        break

#These can be used as test cases

##  0 is a celebrity.
grid = [ [1, 0, 0, 0],
         [1, 0, 0, 0],
         [1, 0, 1, 0],
         [1, 0, 1, 0] ]

## 2 is a celebrity
grid = [ [0, 0, 1, 0, 0],
         [0, 1, 1, 0, 1],
         [0, 0, 1, 0, 0],
         [0, 0, 1, 0, 0],
         [1, 0, 1, 1, 1] ]


texts:
I needed to create a mortgage calculator for an intro to CS class. As part of the assignment, with an interest rate of 6% needs to change to 7% after 3 years hence that if statement. The char dummy line at the end is a requirement from my professor.

I'm mainly looking for ways to clean it up or if I missed anything. I'm required to use namespace std, and I know a lot of you don't care for it.

#include <iostream>
using namespace std;

int main()
{
    double monthlyPayment;
    double balance;
    double interestRate;
    double interestPaid;
    double initialBalance;
    double termOfLoan;
    double month = 1;

    cout.setf(ios::fixed);
    cout.setf(ios::showpoint);
    cout.precision(2);

    cout << "Enter the current balance of your loan: $";
    cin >> balance;
    cout << "Enter the initial yearly interest rate : ";
    cin >> interestRate;
    cout << "Enter the desired monthly payment : $";
    cin >> monthlyPayment;

    initialBalance = balance;

    while (interestRate >= 1)       /*Converts the interest rate to a decimal if the user inputs
                                                      in percentage form*/
    {
        interestRate = interestRate / 100;
    }

    if(month >= 36);
    {
        if(interestRate=.06)
        {
            interestRate=.07;
        }
    }
    balance = balance * (1 + interestRate / 12) - monthlyPayment;

    cout << "After month 1 your balance is $" << balance << endl;

    while (balance > 0)
    {
        if (balance < monthlyPayment)
        {
            balance = balance - balance;
        }
        else
        {
            balance = balance * (1 + interestRate / 12) - monthlyPayment;
        }

        month = month++;
        month = month + 1;
        month += 1;

        cout << "After month " << month << ", your balance is : $" << balance << endl;
        }
        cout << "You have paid off the loan at this point. Congratulations!" << endl;

        termOfLoan = month;

interestPaid = (monthlyPayment * termOfLoan) - initialBalance;

/*I believe the formula above would work if only there was
 a way to calculate how many months it took to pay
off the loan, but since it varies, I don't know how to
calculate "termOfLoan". */

            cout << "You paid a total ammount of $" << interestPaid << " in intrest." << endl;
            cout << "Total number of months = " << month << "." << endl;

char dummy;
cout << "Enter any key to quit." << endl;
cin >> dummy;
}


texts:
I'm creating a WPF application with a DataGrid. I'd like some advice on the code I've written:

<DataGrid  Margin="0,10,10,10" LoadingRow="DataGrid_LoadingRow"    Name="user_view" EnableRowVirtualization="False" Grid.Column="2"    CanUserReorderColumns="True" CanUserResizeColumns="True"  CanUserResizeRows="True" CanUserSortColumns="True"
    AlternatingRowBackground="Gainsboro" CanUserAddRows="False" CanUserDeleteRows="False" IsReadOnly="True" AutoGenerateColumns="False" IsSynchronizedWithCurrentItem="True">
    <DataGrid.Columns>
        <DataGridTextColumn  Header="Name" Width="*" Binding="{Binding name}" ></DataGridTextColumn>
        <DataGridTextColumn Header="Surname" Width="*" Binding="{Binding surname}"></DataGridTextColumn>
        <DataGridTextColumn Header="Address" Width="*" Binding="{Binding address}"></DataGridTextColumn>

 // and so on
 // and so on
 // and so on

...are all the cells that I bound my SQL View to.

Now, to fill the DataGrid:

public void LoadView()
{
    try
    {
        SQLiteCommand command = new SQLiteCommand(connection);
        command.CommandText = MyApk.Properties.Resources.user_datagrid;

        DataSet DST = new DataSet();
        DataTable DT = new DataTable();
        SQLiteDataAdapter SDA = new SQLiteDataAdapter(command);
        SDA.Fill(DT);
        this.user_view.ItemsSource = DT.AsDataView();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

And the query to create the view is basically:

CREATE VIEW IF NOT EXISTS user_details AS SELECT name,surname,address //more stuff here

The specific points I'd like addressed are:

Is this the right way to fill the DataGrid?
Is it hard coded?
How can I make it even better?


texts:
I'm currently populating my drop downlists like this...

  public  List<NewLogin> GetRolesForDDL()
    {
        using (database db = new database())
        {
            return (from r in db.UserRole
                    select new NewLogin
                    {
                        UserRole = r.Role,
                        RoleID = r.RoleID
                    }).ToList();
        }
    }
    public  NewLogin RoleDDL()
    {
        NewLogin nl = new NewLogin();
        using (database db = new database())
        {                               // populates ddl
            nl.RoleList = new SelectList(GetRolesForDDL(), "RoleID", "UserRole");
        }
        return nl;
    }

The part I don't like in particular is where nl.RoleList = new SelectList(GetRolesForDDL()
Is there a better way I can do this, by keeping within the same style and bypassing that method and using a quick and easy lambda expression instead?

Also another quick question is...

@Html.DropDownListFor(u => u.RoleID, Model.RoleList)
When I pass this to the controller I get the RoleID value, but my RoleName(text of ddl)
get's passed as null. Can I access both RoleName and ID without fetching it in the backend?

I know this doesn't work, but I'm thinking it would have to be something like

DDLFor(u => u.RoleID, u.RoleName)


texts:
I am new to Python and am trying to optimize the following code:

import sys
import numpy as np

def LSMPut(T, r, sigma, K, S0, TimeSteps, Paths, k):
    dt = T/TimeSteps
    t = np.arange(0, T+dt, dt).tolist()

    z=[np.random.standard_normal() for _ in range(Paths)]
    w = (r-sigma**2/2)*T + sigma*np.sqrt(T)*np.array(z)

    S = S0*np.exp(np.array(w))
    P=np.maximum(K-np.array(S),0)

    for i in range(TimeSteps-1, -1, -1):
        z=[np.random.standard_normal() for _ in range(Paths)]
        w = t[i]*np.array(w)/t[i+1] + sigma*np.sqrt(dt*t[i]/t[i+1])*np.array(z)

        S = S0*np.exp(np.array(w))
        itmPaths = [index for index,value in enumerate(K-np.array(S)) if value > 0]

        itmS = S[itmPaths]
        Pt = K - np.array(itmS)

        itmDiscP = P[itmPaths]*np.exp(-r*dt)

        A = BasisFunct(itmS, k)
        beta = np.linalg.lstsq(A,itmDiscP)[0]
        C = np.dot(A,beta)

        exPaths = [itmPaths[i] for i, value in enumerate(zip(Pt, C)) if value[0] > value[1]]
        restPaths = np.setdiff1d(np.arange(0, Paths-1, 1).tolist(), exPaths) # Rest of the paths

        P[exPaths] = [Pt[i] for i, value in enumerate(zip(Pt, C)) if value[0] > value[1]]
        P[restPaths] = np.array(P[restPaths])*np.exp(-r*dt)

        u=np.mean(P*np.exp(-r*dt))

    return u

def BasisFunct(X, k):
    Ones=[1 for _ in range(len(X))]
    if k == 1:
        A = np.column_stack((Ones,1 - np.array(X)))
    elif k == 2:
        A = np.column_stack((Ones,1 - np.array(X),1/2*(2-4*np.array(X) + np.array(X)**2)))
    elif k == 3:
        A = np.column_stack((Ones,1 - np.array(X),1/2*(2-4*np.array(X) + np.array(X)**2), 1/6*(6-18*np.array(X) + 9*np.array(X)**2-np.array(X)**3)))
    elif k == 4:
        A = np.column_stack((Ones,1 - np.array(X),1/2*(2-4*np.array(X) + np.array(X)**2), 1/6*(6-18*np.array(X) + 9*np.array(X)**2-np.array(X)**3),1/24*(24 - 96*np.array(X) + 72*np.array(X)**2 - 16*np.array(X)**3 + np.array(X)**4)))
    elif k == 5:
        A = np.column_stack((Ones,1 - np.array(X),1/2*(2-4*np.array(X) + np.array(X)**2), 1/6*(6-18*np.array(X) + 9*np.array(X)**2-np.array(X)**3),1/24*(24 - 96*np.array(X) + 72*np.array(X)**2 - 16*np.array(X)**3 + np.array(X)**4),1/120*(120-600*np.array(X)+600*np.array(X)**2-200*np.array(X)**3+25*np.array(X)**4-np.array(X)**5)))
    else:
            sys.exit("Too many basis functions requested")
    return A

print(LSMPut(1, 0.06, 0.15, 100, 90, 20, 1000000, 5))

The purpose of the code is to calculate the price of an American put option. The time to execute if Paths > 1,000,000 takes a long time, especially if I perform a sensitivity analysis. I would like to find out if there is any way for me to optimize the code or accelerate the processing time. Thank you.


texts:
I recently had a programming interview, where I had to create an Api Gateway. The description is as follows:

You need to create a gateway in which it only allows certain number of callers to call api and rest of them will be blocked within the given timeframe.
For eg : If the time window is 1 minute. You need to allow only 6 calls to be called within that 1 minute window and rest of them will be blocked and will be only allowed in the next window of 1 minute.
In short every window will only allow 6 api calls.

I was not able write a proper code during 30 min round, since my brain started rushing towards all kinds of solutions.
But I tried to do it once I was done with an interview and below is my solution. Please let me know if there is anyway that I can improve in the implementation, in terms of performance or any other aspects.
public class APIGateway {
    private Employee emp;
    private int count = 0;
    private Timer timer;

    public APIGateway(Employee emp) {
        this.emp = emp;
        this.timer = new Timer(this);
        Thread t = new Thread(timer);
        t.start();
    }

    public synchronized void create() {
        while (!isAccessible()){
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        emp.create();
        count++;
    }

    private synchronized boolean isAccessible() {
        if(count<6){
            return true;
        }
        return System.currentTimeMillis()<=timer.getElapsetime();
    }

    private synchronized void unblock(){
        count = 0;
        notifyAll();
    }

    private class Timer implements Runnable {
        private long startTime;
        private APIGateway gateway;

        Timer(APIGateway gateway){
            startTime = System.currentTimeMillis();
            this.gateway = gateway;
        }

        private long getElapsetime() {
            return startTime + 6000;
        }

        @Override
        public void run() {
            while (true) {
                try {
                    Thread.sleep(60000);
                    startTime = System.currentTimeMillis();
                    gateway.unblock();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    public void delete() {
        // same like create
    }

    public void update() {
        // same like create
    }
}

// Assume this is the api calls.
interface Employee {
    void create();
    void delete();
    void update();
}


texts: Uncompressing a list with some run-length-encoded elements

texts:
Regarding the following code

;; ANSI CL - p37
;; Run length encoding: expansion

;; > (uncompress '((3 1) 0 1 (4 0) 1))
;; (1 1 1 0 1 0 0 0 0 1)
(defun uncompress (lst)
  (if (null lst)
      nil
      (let ((elt (car lst))                     ; [1]
            (rest (uncompress (cdr lst))))      ; [2]
        (if (consp elt)
            (append (apply #'list-of elt) rest) ; [3]
            (cons elt rest)))))                 ; [4]

(defun list-of (n elt)
  (if (zerop n)
      nil
      (cons elt (list-of (- n 1) elt))))

;; [1] the compressed form, whether atom or list.
;; [2] uncompress the rest. recursion happens here. curious.
;; [3] compressed form, so expand it, & append to uncompressed rest.
;; [4] not a compressed form, so just cons it.

Left to my own devices, I would have written uncompress like so

;; How my intuition would have said to write it, with the recursive
;; calls made where their results are used:
(defun uncompress (lst)
  (if (null lst)
      nil
      (let ((elt (car lst)))
        (if (consp elt)
            (append (apply #'list-of elt) (uncompress (cdr lst)))
            (cons elt (uncompress (cdr lst)))))))

Question

Computing the value of rest in the let in the first example appears to alter the path of the recursion.  Is that correct? Or are let forms merely substituted into later code where they are used?