texts: Simple pattern matching between two string inputs using Java (Google interview challenge)

texts:
The interview question is:

Write a function isMatch (without using java.util.Regex) that takes two strings as arguments:

s (a string to match), and
p (a regular expression pattern).

It should return a Boolean denoting whether s matches p.
p can be composed of alphabetic characters and '*' (denoting that the previous character matches 0 or more times).

This is the code I have written:
    private boolean isNextCharStarred(String s) {
         return s.length() >= 2 && s.charAt(1) == '*';
     }

     private boolean recIsMatch(String s, String p, boolean hasPatternBeenEaten) {
         if (p.length() == 0) {
             return true;
         }
         if (s.length() == 0) {
             if (isNextCharStarred(p)) {
                 return recIsMatch(s, p.substring(2), true);
             }
             return p.length() == 0;
         }
         if (isNextCharStarred(p)) {
             if (s.charAt(0) != p.charAt(0)) {
                 return recIsMatch(s, p.substring(2), true);
             }
             return recIsMatch(s.substring(1), p, hasPatternBeenEaten)
|| recIsMatch(s, p.substring(2), true);
         }
         if (s.charAt(0) == p.charAt(0)) {
             return recIsMatch(s.substring(1), p.substring(1), true);
         }
         if (hasPatternBeenEaten) {
             return false;
         }
         return recIsMatch(s.substring(1), p, hasPatternBeenEaten);
     }

     public boolean isMatch(String s, String p) {
         return recIsMatch(s, p, false);
     }

Are there any bugs? How could it be improved?


texts: Plugin for WordPress and Foundation Reveal

texts:
I figure that someone here probably knows a much better way to do this. I'm still figuring out AJAX and jQuery, so I consider that I still need to master quite a bit of knowledge.

My function extends Foundation 4 Reveal's functionality in a few ways:

Uses WordPress AJAX to dynamically pull in content to populate a modal div.
Centers the modal div and allows it to be variable width.
Adds paging navigation from the modal window that when triggered will close the open modal window, then open the previous/next modal content.

While I feel like I've managed to figure out a lot on my own, my code isn't optimal; I would greatly appreciate any feedback or insights on ways to improve it, or things that I should avoid.

(function($) {

$.fn.displayPost = function() {

event.preventDefault();

var post_id = $(this).data("id");
var id = "#" + post_id;

// Check if the reveal modal for the specific post id doesn't already exist by checking for it's length
if($(id).length == 0 ) {
    // We'll add an ID to the new reveal modal; we'll use that same ID to check if it exists in the future.
    var modal = $('
').attr('id', post_id ).addClass('reveal-modal').appendTo('body');
    var ajaxURL = MyAjax.ajaxurl;
     $.ajax({
        type: 'POST',
        url: ajaxURL,
        data: {"action": "load-content", post_id: post_id },
        success: function(response) {
            modal.empty().html(response).append('&#215;').foundation('reveal', 'open');
            modal.bind('opened', function() {
                // Reset visibility to hidden and set display: none on closed reveal-modal divs, for some reason not working by default when reveal close is triggered on .secondary links
                $(".reveal-modal:not('.reveal-modal.open')").css({'visibility': 'hidden', 'display' : 'none'})
                // Trigger resize
                $(window).trigger('resize');
            return false;
            });
        }
    });
}
 //If the div with the ID already exists just open it.
 else {
     $(id).foundation('reveal', 'open');
 }

 // Recalculate left margin on window resize to allow for absolute centering of variable width elements
 $(window).resize(function(){
     var left;
        left = Math.max($(window).width() - $(id).outerWidth(), 0) / 2;
        $(id).css({
            left:left + $(window).scrollLeft()
        });
 });
}

 })(jQuery);

 // Apply the function when we click on the .reveal link
 // (document).ready won't work on any reveal-modal divs added subsequently
 // after page load via AJAX so use .on instead.
 jQuery(document).on("click", ".reveal,.secondary", function() {
  jQuery(this).displayPost();

 });

  // Close open modal via secondary paging links; target parent div id.
  jQuery(document).on("click", ".secondary", function() {
    var id = jQuery(this).closest("div").attr("id");
  jQuery(id).foundation('reveal', 'close');
  });


texts:
I find this Substring Leetcode challenge online. Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity \$O(n^2)\$ or  \$O(n)\$ (optimized).

Input: S = "ADOBECODEBANC", T = "ABC"

Output: "BANC"

I did the following approach. Moving Window problems. I also test my code on repl.it.

function minimumWindowSubstring(S, T) {

  let result = [0, Infinity]
  let counts = {};
  let missingCharacters = T.length;

//   Create the counts hash table
  for(let i = 0; i < T.length; i++) {
    counts[T[i]] = 0;
  }

  let slow = 0;

  for(let fast = 0; fast < S.length; fast++) {

//     Check if character at fast index is incounts hash
    if(S[fast] in counts) {

//     If you haven't seen that character before
      if(counts[S[fast]] === 0) {

//         Decrement number of missing characters
        missingCharacters -= 1;
      }

//       And add one to its counts value
      counts[S[fast]] += 1
    }

//     Shrink window until you have an incomplete set
    while(missingCharacters === 0) {

//       Updates result range if smaller than previous range
      if((fast - slow) < (result[1] - result[0])) {
        result[0] = slow
        result[1] = fast
      }

      if(S[slow] in counts) {
        counts[S[slow]] -= 1
        if(counts[S[slow]] === 0) {
          missingCharacters += 1
        }
      }
      slow += 1;
    }
  }

  return result[1] === Infinity ? "" : S.slice(result[0], result[1] + 1);
}

console.log(minimumWindowSubstring("ADOBECODEBANC", "ABC")) //  "BANC"


texts:
I need to compare some values of a Javascript object. If they fail to be identical, I want to pretty print to console.log the mismatch.

The initial code I have written which I find fugly after a JS beautify looks like:

function assert(a, b, message) {
if (a != b) {
    console.log("Failed to match " + message + " " + a + " != " + b);
    return false;
}
return true;
}

    if (!assert(parsedInput.protocol, cu.protocol, "protocol")) {
        continue;
    }
    if (!assert(parsedInput.port, cu.port, "port")) {
        continue;
    }
    if (!assert(parsedInput.hostname, cu.hostname, "hostname")) {
        continue;
    }
    if (!assert(parsedInput.hash, cu.hash, "hash")) {
        continue;
    }

Please tell me I've missed the plot and I could write this a lot better. Feel free to critique the rest of the code. Thank you!


texts: Optimising this simple jQuery script that vertically centers elements on pages

texts:
This is a simple jQuery script that I use to vertically center elements on pages. It's quite simple, but I would love to know if there is room for improvement.

(function( $ ){

    $.fn.flexVerticalCenter = function( onAttribute, verticalOffset, parentSelector ) {

        return this.each(function() {

            var $this           = $(this);                          // store the object
            var attribute       = onAttribute || 'margin-top';      // the attribute to put the calculated value on
            var offset          = parseInt(verticalOffset) || 0;    // the number of pixels to offset the vertical alignment by
            var parent_selector = parentSelector || null;           // a selector representing the parent to vertically center this element within

            // recalculate the distance to the top of the element to keep it centered
            var resizer = function () {
                var parent_height = (parent_selector) ? $this.parents(parent_selector).first().height() : $this.parent().height();

                $this.css(
                    attribute, ( ( ( parent_height - $this.height() ) / 2 ) + offset )
                );
            };

            // Call once to set.
            resizer();

            // Call on resize. Opera debounces their resize by default.
            $(window).resize(resizer);

            // Apply a load event to images within the element so it fires again after an image is loaded
            $this.find('img').load(resizer);

        });
    };
})( jQuery );


texts: More idiomatic way to move item from one dict value(list) to another?

texts:
Is there a more idiomatic way to handle the following scenario? I'm open to lodash, etc. if needed. This does what I want, but I feel that there is probably a shortcut I'm missing:

const migrateValues = (obj, srcKey, destKey, value) => {
    updatedSrc = [];
    obj[srcKey].forEach(x => {
        if (x !== value) {
            updatedSrc.push(x);
        }
    });
    obj[destKey].push(value);
    obj[srcKey] = updatedSrc;
    return obj;
}

obj = {
    "key1": [1, 2, 3],
    "key2": [4, 5, 6],
    "key3": [7, 8, 9],
    "key4": [10, 11, 12]
};
valueToMove = 11;
srcKey = "key4";
destKey = "key2";

console.log(obj);
console.log(migrateValues(obj, srcKey, destKey, valueToMove));


texts:
I looked into possible ways to raise an error to generate an error when a slug already exist.

This is the model:

# models.py
from django.db import models
class Question(models.Model):
    title = models.CharField(max_length=100)
    slug = models.SlugField(max_length=100, db_index=True, unique=True)

for which I use a generic view:

# views.py
from .models import Question
class QuestionCreate(generic.CreateView):
    model = Question
    fields = ['title', 'text']
    def form_valid(self, form):
        instance = form.save(commit=False)
        slug = slugify(form.cleaned_data['title'])
        if Question.objects.filter(slug=slug).exists():
             form.add_error("title","This Question already exist")
             return self.form_invalid(form)

The slug is generated from the question title.

Then it was brought to my attention that I don't need to save the form first:

class QuestionCreate(generic.CreateView):
    model = Question
    fields = ['title', 'text']
    def form_valid(self, form):
        slug = slugify(form.cleaned_data['title'])
        if Question.objects.filter(slug=slug).exists():
             form.add_error("title","This Question already exist")
             return self.form_invalid(form)

Is this the best practice?

Other possibilities I considered:

# models.py
from django.db import models, IntegrityError
from django.forms import ValidationError
class Question(models.Model):
    title = models.CharField(max_length=100)
    slug = models.SlugField(max_length=100, db_index=True, unique=True)
    def save(self):
        slug = slugify(self.title)
        try:
            self.slug = slug
            super().save()
        except IntegrityError:
            raise ValidationError("Question already exist")

but it seems not possible to display this error message to the user.

The final option I considered:

# models.py
from .forms import QuestionForm
class QuestionCreate(generic.CreateView):
    model_form = QuestionForm

# forms;py
from django.forms import ModelForm
from .models import Question

class QuestionForm(ModelForm):
    class Meta:
         model = Question
         fields = ['title', 'text']

I still have to figure out how to raise an error message in this last situation, it's somewhere in the docs.

Which is the best practice? Or is this all acceptable code?


texts:
I've written a simple app that draws with a kaleidoscope effect in javascript, could someone please review the code? I'm especially interested in functional practices and design patterns.

const game = {
  pi2: Math.PI*2,
  sides: 12,
  background: '125,125,125',
  load: function () {
    game.canvas = document.createElement('canvas');
    game.ctx = game.canvas.getContext('2d');
    document.body.appendChild(game.canvas);
    document.body.style.overflow = 'hidden';
    document.body.style.background = 'rgba('+game.background+',1)';
    game.resize();
    game.input = document.querySelector('input');
    game.input.addEventListener('change', game.change);
    game.change();
    game.button = document.querySelector('button');
    game.button.addEventListener('click', game.clear);
    game.clear();
  },
  getPoint: function (event) {
    return {
      x: event.clientX - game.hw,
      y: event.clientY - game.hh
    };
  },
  mousedown: function (event) {
    game.clicking = true;
  },
  mouseup: function (event) {
    game.clicking = false;
  },
  draw: function (event) {
    game.point = game.getPoint(event);
    if (game.last) {
      if (game.clicking) {
        game.ctx.fillStyle = 'rgba('+game.background+',0.01)';
        game.ctx.fillRect(0,0,innerWidth, innerHeight);
      }
      var angle1 = Math.atan2(game.last.y,game.last.x);
      var angle2 = Math.atan2(game.point.y,game.point.x);
      for (var i=0; i<game.sides; i++) {
        angle1 += game.slice;
        angle2 += game.slice;
        var p1 = game.rotate(angle1, game.last);
        var p2 = game.rotate(angle2, game.point);
        var h = Math.round((angle1*360)/game.pi2);
        var color = 'hsl('+h+',5%,50%)';
        game.ctx.lineWidth = 1;
        if (game.clicking || game.clicking !== game.release) {
          color = 'hsl('+h+',100%,75%)';
          game.ctx.lineWidth = 3;
        }
        if (game.clicking !== game.release) {
          game.circle(p2,color);
        }
        game.line(p1,p2,color);
      }
    }
    game.last = game.point;
    game.release = game.clicking;
  },
  rotate: function (a,p) {
    var d = Math.sqrt(Math.pow(p.x,2)+Math.pow(p.y,2));
    return {
      x: d * Math.cos(a),
      y: d * Math.sin(a)
    }
  },
  line: function (a,b,c) {
    game.ctx.beginPath();
    game.ctx.strokeStyle = c;
    game.ctx.moveTo(a.x + game.hw, a.y + game.hh);
    game.ctx.lineTo(b.x + game.hw, b.y + game.hh);
    game.ctx.stroke();
  },
  circle: function (p,c) {
    game.ctx.beginPath();
    game.ctx.strokeStyle = c;
    game.ctx.arc(p.x + game.hw, p.y + game.hh, 3, 0, game.pi2);
    game.ctx.stroke();
  },
  resize: function () {
    game.canvas.width = innerWidth;
    game.canvas.height = innerHeight;
    game.hw = innerWidth/2;
    game.hh = innerHeight/2;
  },
  change: function () {
    game.sides = game.input.value;
    game.slice = game.pi2 / game.sides;
  },
  clear: function () {
    game.ctx.fillStyle = 'rgba('+game.background+',1)';
    game.ctx.fillRect(0,0,innerWidth, innerHeight);
  }
};
addEventListener('load', game.load);
addEventListener('mousedown', game.mousedown);
addEventListener('mouseup', game.mouseup);
addEventListener('resize', game.resize);
addEventListener('mousemove', game.draw);
body {
  overflow: hidden;
  cursor: crosshair;
}
div {
  position: absolute;
  margin: 0.2em;
  margin-left: calc(50% - 3em);
  background: rgba(255,255,255,0.8);
  padding: 0 0.3em;
  border-radius: 0.3em;
}
input {
  width: 3em;
  padding: 0.2em;
  margin: 0.3em;
}
button {
  padding: 0.2em 0.5em;
}

  Sides:
  <input type="number" value="7" min="1">
  <button>X</button>


texts: K&R exercise 1-19: reversing each line of input

texts:
This is my solution for exercise 1-19 of K&R:

  Write a function reverse(s) that reverses the character string s. Use it to write a program that reverses its input a line at a time.1

It works, but I'm trying to write good programs. I think the fact that I can't use the length of the vector when already got the line in function getlinea makes me think I could do better. The function reverse(s) uses 3 for sentences, which might be a little ugly. I know it doesn't mean it's not good but having to "read" the line 4 times is kind of a little stupid to me. I still can't think of a different solution.

/*
 * main.c
 *
 *  Created on: 19/3/2015
 *      Author: utnso
 */

#include <stdio.h>

#define MAXLINE 1000

void reverse (char s [] );
int getlinea (char s [] , int lim);

int main ()
{
    int len;
    char palabra [MAXLINE];
    while ( ( len = getlinea ( palabra, MAXLINE ) )  >= 0 )
        if (len > 0)
            printf ("%s\n", palabra);
    return 0;

}

int getlinea ( char s [], int lim )
{
    int i, c;
    i = 0;
    while ( ( c = getchar() ) != EOF && c != '\n' && i < lim-1 )
    {
        s [i] = c ;
        ++ i;
    }
    s [i] = '\0';
    if ( i > 0 )
        reverse ( s ) ;
    else
        if ( c == EOF )
            return -1;
    return i ;
}

void reverse ( char turnaround [] )
{
    int i, j;
    int h = 0;
    char aux [MAXLINE];
    for ( i = 0; turnaround [i] != '\0' ; ++i )
        ;
    for ( j = i-1 ; j >= 0 ; --j)
    {
        aux [h] = turnaround [j];
        ++h;
    }
    for ( i = 0 ; turnaround [i] != '\0' ; ++i )
        turnaround [i] = aux [i];
}

This is the output for

$ ./1-19 < main.c

(it also deletes white lines)

*/
c.niam *
*
5102/3/91 :no detaerC  *
osntu :rohtuA      *
/*
>h.oidts< edulcni#
0001 ENILXAM enifed#
;) ][ s rahc( esrever diov
;)mil tni , ][ s rahc( aenilteg tni
)( niam tni
{
;nel tni
;]ENILXAM[ arbalap rahc
) 0 =>  ) ) ENILXAM ,arbalap ( aenilteg = nel ( ( elihw
)0 > nel( fi
;)arbalap ,"n\s%"( ftnirp
;0 nruter
}
) mil tni ,][ s rahc ( aenilteg tni
{
;c ,i tni
;0 = i
) 1-mil < i && 'n\' =! c && FOE =! ) )(rahcteg = c ( ( elihw
{
; c = ]i[ s
;i ++
}
) 0 > i ( fi
{
;'0\' = ]i[ s
; ) s ( esrever
}
esle
) FOE == c ( fi
;1- nruter
; i nruter
}
) ][ dnuoranrut rahc ( esrever diov
{
;j ,i tni
;0 = h tni
;]ENILXAM[ xua rahc
) i++ ; '0\' =! ]i[ dnuoranrut ;0 = i ( rof
;
)j-- ; 0 => j ; 1-i = j ( rof
{
;]j[ dnuoranrut = ]h[ xua
;h++
}
) i++ ; '0\' =! ]i[ dnuoranrut ; 0 = i ( rof
;]i[ xua = ]i[ dnuoranrut
}

1http://cs.indstate.edu/~cbasavaraj/cs559/the_c_programming_language_2.pdf -
 Page 31


texts:
I'm designing a table cell based map design for a little game I'm building, and I was hoping I could get some cleanup pointers or design tips to "perfect" my engine's design. Basically, in the end result, you'll walk around the map one tile at a time. On any visible tile you can walk to it, but only the tile you're on will have "actions" (randomly generated).

Here is my prototype design:

function Map() {
    this.x;
    this.y;
}

Map.prototype = {
    move:function() {
        var new_x = this.x - 1;
        var new_y = this.y - 1;
        Map.prototype.render(new_x, new_y);
    },
    render:function(p_x,p_y) {
        //check for map boundaries
        var max_divs = 2;
        if(!p_x) p_x = 1;
        if(!p_y) p_y = 1;
        if(p_x >= 99) p_x--;
        if(p_y >= 99) p_y--;

        divs_x = max_divs + p_x;
        divs_y = max_divs + p_y;
        //create new table
        var root = document.createElement("table");
        root.id = 'root_table';
        //loop coordinates and generate surrounding cells
        for (var x = p_x; x <= divs_x; x++) {
            var row = document.createElement("tr");
            for (var y = p_y; y <= divs_y; y++) {
                var cell = document.createElement("td");
                if (x <= 0 || y <= 0 || x >= 101 || y >= 101) {
                    cell.textContent = "";
                }
                else {
                    this.x = x; this.y = y;
                    cell.textContent = "("+this.x+","+this.y+")";
                    //add event handler for the click event (move)
                    cell.addEventListener("click", this.move, false);
                    cell.x = x; cell.y = y;
                    cell.className = 'map';
                }
                //add cell to row
                row.appendChild(cell);
            }
            //add row to table
            root.appendChild(row);
        }
        var main = document.getElementById("container");
        var old_table = document.getElementById('root_table')
        if(old_table) main.removeChild(old_table);
        //remove old table, add new one
        main.appendChild(root);
    }
}

var map = new Map();
map.render();

And here is a current working link to my map: zombiesss ahhhh


texts:
I'm relatively new at programming in general including Python. But I've tried to create a program in Python that alerts users through a pop up window to perform an action every 2 hours.

import time
import ctypes

count = 0

print "This break message was sent on "+time.ctime()
messageBox = ctypes.windll.user32.MessageBoxA
returnValue = messageBox(None, "TextAskingToDoSomething", "WindowTitle", 0x40 | 0x4)
if returnValue == 6:
    messageBox = ctypes.windll.user32.MessageBoxA
    returnValue = messageBox(None, "TextRespondingToAnswerYes", "SWindowTitle", 0x40 | 0x0)
elif returnValue == 7:
    messageBox = ctypes.windll.user32.MessageBoxA
    returnValue = messageBox(None, "TextRespondingToAnswerNo", "WindowTitle", 0x40 | 0x0)

while (count < 4):
    time.sleep(60*60*2)
    print "This break message was sent on"+time.ctime()
    messageBox = ctypes.windll.user32.MessageBoxA
    returnValue = messageBox(None, "TextAskingToDoSomething", "WindowTitle", 0x40 | 0x4)
    if returnValue == 6:
        messageBox = ctypes.windll.user32.MessageBoxA
        returnValue = messageBox(None, "TextRespondingToAnswerYes", "WindowTitle", 0x40 | 0x0)
    elif returnValue == 7:
        messageBox = ctypes.windll.user32.MessageBoxA
        returnValue = messageBox(None, "TextRespondingToAnswerNo", "WindowTitle", 0x40 | 0x0)
    count = count + 1

time.localtime()

It essentially calls a message box with a title and a text in it and if the user clicks one button then another one follow up message box appears. If the user clicks on the other button, then another follow up message appears. This process is repeated every 2 hours for 5 times.

How could I improve this code to be shortened? Could I use a function somehow? Or what would be a way to shorten it and avoid me repeating myself too much (if that is the case)?


texts: MCMC Metropolis Hastings for German Tank Puzzle

texts:
I have implemented the following MCMC algorithm for the german tank puzzle
found here

I just want to make sure everything is legit and that I am not getting the right answer by chance.

from scipy.stats import norm
import numpy as np
import math
import scipy as sp
import matplotlib.pyplot as plt

from scipy.stats import uniform

# Tank serial numbers collected in the field
data = np.array([10,20,50])

posterior = []
theta_current = 10
num_samples = 10000
for i in range(num_samples):
    theta_proposal = uniform(max(data), 10000).rvs()

    likelihood_current = uniform(0, theta_current).pdf(data).prod()
    likelihood_proposal = uniform(0, theta_proposal).pdf(data).prod()

    p_accept = likelihood_proposal/likelihood_current

    accept = np.random.rand() < p_accept
    if accept:
                # Update position
        theta_current = theta_proposal
    posterior.append(theta_current)

#BURN IN
posterior = posterior[5000:]
import matplotlib.pyplot as plt
# define window size, output and axes
fig, ax = plt.subplots(figsize=[8,6])

# create histogram within output
N, bins, patches = ax.hist(posterior, bins=50, color="#777777")
for bin_size, bin, patch in zip(N, bins, patches):
     if bin_size == 40:
         patch.set_facecolor("<some color like #FF000>")

plt.show()


texts: How can this async url response checker be cleaner/faster?

texts:
with open('things.txt') as things:
    urls = [url.strip().lower() for url in things]

async def is_site_404(s, url):
    async with s.head(f"https://example.com/{url}") as r1:
        if r1.status == 404:
            print('hello i am working')

async def create_tasks(urls):
    tasks = []
    async with aiohttp.ClientSession() as s:
        for url in urls:
            if len(url) >= 5 and len(url) < 16 and url.isalnum():
                task = asyncio.create_task(is_site_404(s, url))
                tasks.append(task)
        return await asyncio.gather(*tasks)

while True:
    asyncio.get_event_loop().run_until_complete(create_tasks(urls))

Hi, this is a basic asynchronous url response checker that I created and it's pretty fast, but I'm wondering if there is any way to get more requests per second with the base of this code. I have it designed so that it runs forever and just prints whenever there is a 404 in this example basically. I'm pretty new to python and coding in general and I would like some guidance/advice from anyone who has more experience with this kind of thing.. maybe there is an aiohttp alternative I should use that's faster? ANY advice is greatly appreciated.


texts:
I have written this program to deal 7 cards to one player.

#include <iostream>
#include <string>
#include <cstdlib> //for rand and srand
#include <cstdio>
#include <vector>
using namespace std;

string suit[] = {"Diamonds", "Hearts", "Spades", "Clubs"};
string facevalue[] = {"Two", "Three", "Four", "Five", "Six", "Seven",         "Eight", "Nine", "Ten", "Jack", "Queen", "King", "Ace"};
int numberOfCardsDrawn = 0;
string drawnCards[52];

string drawCard () {
    string card;
    int cardvalue = rand()%13;
    int cardsuit = rand()%4;
    card += facevalue[cardvalue];
    card += " of ";
    card += suit[cardsuit];
    return card;
}

bool isMyCardAlreadyDrawn (string card) {
    for(int i = 0; i < 52; i++) {
        if(card.compare(drawnCards[i]) == 0) {
            // if this is true, then both strings are the same
            return true;
        }
    }
    return false;
    // if the code reaches this point, then the card has not   been drawn yet
}

string getCard () {
    srand(time(0));
    string card = drawCard();
    while (isMyCardAlreadyDrawn(card) == true) {
        // keep drawing until an    undrawn card is found
        card = drawCard(); // draw a new card
    }
    drawnCards[numberOfCardsDrawn] = card;
    numberOfCardsDrawn++;
    return card;
}

int main () {
    cout << "Your Cards:\n";
    vector<string> p0; //player 0's card
    const int DEAL_CARDS = 7; //number of cards we can deal to each player
    string choices[] = { "a", "b","c","d","e","f","g" };

    for (int i = 0; i < DEAL_CARDS; i++){
        string p0_getCard = getCard();
        cout <<" " << choices[i] << ")"<< p0_getCard << " ";
        p0.push_back(p0_getCard);
    }
}

However, I will eventually want to have a five-player game (dealing cards to four more vectors), and I feel that extending this code to accomplish that would result in excessive code duplication.  How do I go about improving the code to support that?


texts: NodeJS ReadableStream _read implementation, ArticleReader with changing dates

texts:
I have a NodeJS stream.Readable, ArticleReader. Its job is to read articles, Meantime I have to give it a date to signify the date of the articles, say the default date is today, now I start reading with .on('data') event, and the stream ends. Later I want to change the date and start reading yesterday's articles. In what way should I implement this stream.Readable so this is possible?

One way to think about this is to construct a new ArticleReader for each date. Is this a good approach or is there a better way?

Here's a sample implementation for reference:

var async = require('async'),
    util = require('util'),
    ReadableStream = require('readable-stream').Readable;

function ArticleReader(date) {
    ReadableStream.call(this, { objectMode: true });
    this.strategy = new BasicStrategy();
    this.date = date;
}

util.inherits(ArticleReader, ReadableStream);

ArticleReader.prototype._read = function() {
    var strategy = this.strategy, date = this.date;
    var articles = strategy.getArticleList(date);
    var self = this;
    async.each(articles, function(link, callback) {
        strategy.parseLink(link, function(article) {
            self.push(article);
            callback();
        });
    }, function(err) {
        if (err) {
            self.emit('error', err);
        } else {
            self.push(null);
        }
    });
};


texts:
I am writing a simple count down timer in React:

index.js

import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import bootstrap from "bootstrap/dist/css/bootstrap.css";
import App from "./App";

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById("root")
);

App.js:

import React, { useEffect, useState } from "react";

const App = () => {
  const oneSec = 1000;
  const [secCount, setSecCount] = useState(60);
  const [minCount, setMinCount] = useState(60);
  const [hrCount, setHrCount] = useState(24);

  useEffect(() => {
    const timer;    //<= here is my problem.
    if (secCount > 0) {
      timer = setInterval(() => {
        setSecCount(secCount - 1);
      }, oneSec);
    }
    if (secCount === 0 && minCount > 0) {
      timer = setInterval(() => {
        setSecCount(60);
      }, oneSec);
    }
    return () => clearInterval(timer);
  }, [secCount]);

  useEffect(() => {
    const timer =
      minCount > 0 &&
      setInterval(() => {
        setMinCount(minCount - 1);
      }, 60 * oneSec);
    return () => clearInterval(timer);
  }, [minCount]);

  return (
    <div>
      {minCount}:{secCount}
    </div>
  );
};

export default App;

I am having a hard time with my useEffect hooks. The first useEffect hook is supposed to update the second field, the logic is simply:

if secCount is bigger than 0, continue to countdown every second
if secCount is zero and minCount is bigger than 0, reset secCount to 60 and continue to countdown.

But since there are two branches in my first useEffect hook, I need to declare the timer variable and reassign it later. Can I get away with declaring it as let timer? A const variable does not allow me to change its value.


texts:
In the picture below, I want to open a modal when a user clicks anywhere within in the yellow block, including if they click on the white ‘+’ sign. The problem is, the click event happens on a different target depending on whether the user clicks on the yellow portion, or on the white ‘+’ sign.

In my JavaScript code, I have been handing it like this so far, but I wonder if there is a better, shorter way of doing this that doesn’t require the II operator:

function openModal(e) {
  if (e.target.classList.contains('project-box__picture-box') || e.target.classList.contains('project-box__icon')) {
    modalEl.classList.add('open');
  }
}


texts:
This asks the user for the file name and the number of lines they want to remove. It then stores each line into a vector. A dynamic array is used to hold the random line numbers (generated by random generator) and the corresponding element in the vector is deleted. This vector is then copied to a new file named "temp.txt" where each element is its own line.

Questions:

What can I improve to make this code for efficient? i.e. Better methods to perform this task?
What should I not use and should change (for example any bad habits)?
What did I use that is good and should keep it as a habit?
Are there any exceptions I can use to ensure code?

Warnings I received:

  Warning    C26495  Variable 'LineEditor::array' is uninitialized. Always initialize a member variable (type.6). for LineEditor().
  Avoid unnamed objects with custom construction and destruction (es.84).    for getFileName() in void removeLines().

#include <iostream>
#include <string>
#include <fstream>
#include <random>
#include <ctime>
#include <cstring>
#include <vector>
#include <algorithm>
#include <iterator>

template<typename T>
void writeTo(const std::string& filename, std::vector<T>& v)
{
    std::ofstream fstream(filename);
    if (!fstream)
        exit(1);
    std::copy(v.begin(), v.end(), std::ostream_iterator<T>(fstream, "\n"));
    fstream.close();
}

class LineEditor
{
    std::vector<std::string> buf;
    std::string fileName;
    int noOfLines{ 0 };
    int* array;
public:
    LineEditor()
    {
    }

    ~LineEditor()
    {
        std::cout << "\"" << fileName << "\"" << " " << noOfLines << " lines removed.\n";
        delete[] array;
    }

    void removeLines()
    {
        getFileName();
        TotalLinesToRemove();

        std::ifstream fileIn;
        std::string line;
        int lineCounter{ 0 };
        int* array = new int[noOfLines];

        fileIn.open(fileName);
        if (!fileIn)
        {
            std::cerr << fileName << " can not be opened." << std::endl;
            exit(1);
        }
        while (fileIn.is_open())
        {
            while (std::getline(fileIn, line))
            {
                lineCounter++;
                buf.push_back(line);
            }
            for (int i{ 0 }; i < noOfLines; ++i)
            {
                array[i] = getRandomNumber(0, lineCounter - 1);
                buf.erase(buf.begin() + (array[i]));
                --lineCounter;
            }
            writeTo("temp.txt", buf);
            fileIn.close();
        }
    }
private:
    std::string getFileName()
    {
        std::cout << "Enter name of text file: ";
        std::cin >> fileName;

        return fileName;
    }
    int TotalLinesToRemove()
    {
        std::cout << "Enter the number of lines to remove: ";
        std::cin >> noOfLines;

        return noOfLines;
    }
    int getRandomNumber(int min, int max)
    {
        std::mt19937 seed{ static_cast<std::mt19937::result_type>(std::time(nullptr)) };
        std::uniform_int_distribution<> rand(min, max);
        return rand(seed);
    }
};

int main()
{
    LineEditor file;
    file.removeLines();
    return 0;
}

I am fairly beginner to intermediate at C++ and want to improve.


texts:
This code takes a list of EBITDA amounts (for a hypothetical business), and computes a loan that would fund that business with working capital in periods of loss. When the business has positive EBITDA again, the loan is paid off. The loan also charges interest.
Some specific questions I have

I am not sure the way wcLoanCalc calls wcLoanR is the most beautiful solution. Is there something more elegant I could do?
It feels awkward to have such huge statements to update the LoanPeriod type, but I like having a single type name and hold all this data. Is there a better way?
Is there a more general way I could implement printing out the table? Presumably there is some nice library for doing this

I'm grateful for any and all feedback!
-- Compute Working Capital Loan using Haskell

import Data.List
import Text.Printf

-- | Hold all information about a single period of loan amortization
data LoanPeriod = LoanPeriod
  { cashAvail :: Double
  , draw      :: Double
  , ds        :: Double
  , principal :: Double
  , interest  :: Double
  , balance   :: Double
  }

instance Show LoanPeriod
  where
    show lp = printf "%-10.2f %-10.2f %-10.2f %-10.2f %-10.2f %-10.2f"
                (cashAvail lp)
                (draw lp)
                (ds lp)
                (principal lp)
                (interest lp)
                (balance lp)

type WCLoanAmort = [LoanPeriod]

-- | Test the wcLoanCalc function
wcLoanTest :: WCLoanAmort
wcLoanTest = wcLoanCalc testEbitda testInterestRate
  where
    testEbitda = [100.0, 30.0, -50.0, -10.0, 20.0, 40.0, 60.0, -100.0, 120.0, 30.0]
    testInterestRate = 0.12

-- | Print the result of the wcLoanTest
wcLoanTestPrint :: IO ()
wcLoanTestPrint = loanTable wcLoanTest

-- | Print out a WCLoanAmort as a table
loanTable :: WCLoanAmort -> IO ()
loanTable lpList =
    putStrLn $
    printf "%-10s %-10s %-10s %-10s %-10s %-10s\n"
              "Cash" "Draw" "DS" "Prin" "Int" "Bal" ++
    concat ["---------- " | x <- [1..6]] ++ "\n" ++
    concat [show lp ++ "\n" | lp <- lpList]

-- | Calculate a working capital loan
wcLoanCalc :: [Double] -> Double -> WCLoanAmort
wcLoanCalc ebitda interestRate =
    wcLoanR ebitda interestRate []

-- | Recursively compute each period of working-capital loan
wcLoanR :: [Double] -> Double -> WCLoanAmort -> WCLoanAmort
wcLoanR (ebitda:es) interestRate loanData
    | es == [] = newLoanData
    | otherwise = wcLoanR es interestRate newLoanData
  where
    startBalance  = case length loanData of
                        0 -> 0.0
                        _ -> balance (last loanData)
    newInterest   = startBalance * interestRate / 12.0
    newDraw       = - min ebitda 0.00
    newDS         = max 0.0 $ min ebitda (startBalance + newInterest)
    newPrincipal  = newDS - newInterest
    newBalance    = startBalance + newDraw - newPrincipal
    newLoanData   = loanData ++ [newLoanPeriod]
    newLoanPeriod = LoanPeriod
                      { cashAvail = ebitda
                      , draw      = newDraw
                      , ds        = newDS
                      , principal = newPrincipal
                      , interest  = newInterest
                      , balance   = newBalance}


texts:
As a result of my previous post, I have implemented / refactored my code and have started making successful use of my class. However I have come across a couple of new questions:

The observer must call PopObjects() to consume the data in the vector. PopObjects() returns a bool so I don not have to check the vector count. However, this allows me put the call in a while loop which could never break if the data producer(s) are producing faster than I can consume. I think this concern out of the scope of this class or can it be solved easily within?
I like to assign values to my class members (simulating c++ initializer lists). Is this overkill?
I noticed I cannot instantiate my class unless I provide a null value or method to the constructor. Is making a private default constructor redundant in this case?

using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace fAloha.Core
{
  public class NotifyVector<T>
  {
    public delegate void NotifyCBR();
    private Action notifyCbr_ = () => { }; // Noop;
    private System.Collections.Generic.List<T> vector_;
    private readonly Object dataSyncObject_ = new object();
    private readonly object notifySyncObject_ = new object();
    private volatile bool asyncNotfyInProgress_ = false;

    // Class Instantiation requires a Callback routine
    public NotifyVector(Action cbr)
    {
      if (cbr != null)
        notifyCbr_ = cbr;
      vector_ = new System.Collections.Generic.List<T>();
    }

    // Notify the Observer by asynchronous invocation of cbr
    // Lock is used to reduce notifications. A producer could
    // looping and adding many items adding one at a time.
    public void Notify()
    {
      if (asyncNotfyInProgress_ == false)
      {
        lock (notifySyncObject_)
        {
          asyncNotfyInProgress_ = true;
          Task.Run(async () =>
          {
            await Task.Delay(TimeSpan.FromTicks(1));
            notifyCbr_();
          }).ContinueWith(AsyncResult =>
          {
            asyncNotfyInProgress_ = false;
          });
        }
      }
    }

    // Threadsafe add for vector
    public void AddObject(T obj)
    {
      lock (dataSyncObject_)
      {
        vector_.Add(obj);
      }
    }

    // Threadsafe pop Objects from vector (swap all objects to Observer)
    public bool PopObjects(ref System.Collections.Generic.List<T> inlist)
    {
      bool retval = false;
      lock (dataSyncObject_)
      {
        if (vector_.Count > 0)
        {
          inlist = vector_;
          vector_ = new System.Collections.Generic.List<T>();
          retval = true;
        }
      }
      return retval;
     }
  }
}


texts: Gallery of employees with dynamic filtering

texts:
I'm trying to learn how to write better, more efficient JavaScript code and wanted to run this function I'd written by you and see if people can suggest an improved method.

It's basically a people filter based upon two variables.

Demo.

It works fine, but if additional categories come in (so far there are three) then the code would become redundant.

var family = 'director';
var expertise = 'asset';

function showConsultant(){
   $('.profile').stop(true,true).fadeOut(100);
   $('.profile[data-family="'+family+'"][data-expertise="'+expertise+'"]').delay(101).fadeIn();
}

showConsultant();

$('.top-level li').on('click', function() {

  $('.top-level li').removeClass('selected');
  $(this).addClass('selected');

  if( $(this).index() === 0 ){
     family = 'director';
     showConsultant();
  } else if( $(this).index() === 1 ){
      family = 'consultant';
      showConsultant();
  } else if( $(this).index() === 2 ){
      family = 'support';
      showConsultant();
  }

});

$('.second-level li').on('click', function() {

  $('.second-level li').removeClass('selected');
  $(this).addClass('selected');

  if( $(this).index() === 0 ){
     expertise = 'asset';
     showConsultant();
  } else if( $(this).index() === 1 ){
      expertise = 'insurance';
     showConsultant();
  } else if( $(this).index() === 2 ){
      expertise = 'wealth';
     showConsultant();
  }

});


texts: Find the sum of all digits that match the following digit in a circular list

texts:
The challenge

  The captcha requires you to review a sequence of digits (your puzzle input) and find the sum of all digits that match the next digit in the list. The list is circular, so the digit after the last digit is the first digit in the list.

  For example:

  1122 produces a sum of 3 (1 + 2) because the first digit (1) matches the second digit and the third digit (2) matches the fourth digit.
  1111 produces 4 because each digit (all 1) matches the next.
  1234 produces 0 because no digit matches the next.
  91212129 produces 9 because the only digit that matches the next one is the last digit, 9.

My Logic

I keep track of the first item, the last seen item and the total.
I pass over the list, adding the items that match the last seen item.
I handle the first digit by adding the first to the total if it matches the last of the list.

import kotlinx.cinterop.*
import platform.posix.*

const val FILEPATH = "data.dat"
const val ZERO_CODEPOINT = '0'.toInt()

fun main(args: Array<String>) {
    withFile(FILEPATH) { fd ->
        val (first, last, total) = generateSequence {
            val value = fgetc(fd)
            when (value) {
                -1 -> null
                else -> value
            }
        }
            .map { it - ZERO_CODEPOINT }
            .foldIndexed(listOf(-1, -1, 0)) { index, (first, last, total), value ->
                val newTotal = if (last == value) total + value else total
                val newFirst = if (first == -1) value else first
                listOf(newFirst, value, newTotal)
            }

        val result = if (first == last) total + first else total
        println(result)
    }
}
fun <T> withFile(filename: String, block: (CPointer<FILE>) -> T): T {
    val fd = fopen(filename, "r")
    if (fd != null) {
        val ret = block(fd)
        fclose(fd)
        return ret
    } else {
        throw AssertionError("File not found: $filename")
    }
}


texts: How to merge two descending singly linkedlist into one ascending linkedlist using Recursion without any helper method?

texts:
Here is my solution:
I want to know if my solution fits the requirement 100%? Or if there is any better solution?
Constraint of the question:

must be singly linkedlist
must use recursion, and no helper methods allowed.
The method must return the head node of the merged list.

class Solution{
    Node dummy=new Node(0,null);// the dummy node to store the merged result

    public   Node mergeAscend(Node a,Node b){
        if(a==null&&b==null){//base case
            return null;
        }

        else{
            if((a!=null&&b==null)||a.value>=b.value){// insert "b" after dummy
                //store the next node of current a, before pointing a.next to dummy.next;
                Node store_a_next_node=a.next;
                //insert Node "a" between dummy and dummy.next
                a.next=dummy.next;
                dummy.next=a;
                mergeAscend(store_a_next_node,b);
            }
            else if((a==null&&b!=null)||a.value<b.value){//insert "a" after dummy
                Node store_b_next_node=b.next;
                b.next=dummy.next;
                dummy.next=b;
                mergeAscend(a,store_b_next_node);
            }
        }
        return  dummy.next;
    }
}

class Node {
    public int value;
    public Node next;

    public Node(int value, Node next) {
        this.value = value;
        this.next = next;
    }
}


texts:
First post.
Can you please review my code and help me improve my coding. Please also suggest improvements if there is a miss in this post.

Problem Statement
Given two sorted arrays X[] and Y[] of size m and n each, merge elements of X[] with elements of array Y[] by maintaining the sorted order.
i.e. fill X[] with first m smallest elements and fill Y[] with remaining elements.
Input:
X[] = {1, 4, 7, 8, 10}
, Y[] = {2, 3, 9}
Output:
X[] = {1, 2, 3, 4, 7}
, Y[] = {8, 9, 10}

public static void main(String[] args) {
    int[] X = {11, 14, 17, 18, 110};
    int[] Y = {112, 113, 114};

    mergeRunner(X, Y);

    System.out.println("X: " + Arrays.toString(X));
    System.out.println("Y: " + Arrays.toString(Y));

}

private static void mergeRunner(int[] x, int[] y) {

    if (x[x.length - 1] > y[y.length - 1]) {
        merge(x, y);
    } else {
        merge(y, x);
    }

}

private static void merge(int[] x, int[] y) {
    final int m = x.length;
    final int n = y.length;

    int last = x[m - 1];
    int i = m - 2;
    for (int j = n - 1; j >= 0; j--) {

        while (i >= 0 && x[i] > y[j]) {
            i--;
        }

        //Insertion
        insertValue(x, i + 1, y[j]);

        y[j] = last;
        last = x[m - 1];

        //System.out.println("X: " + Arrays.toString(x));
        //System.out.println("Y: " + Arrays.toString(y));
    }

}

private static void insertValue(int[] x, int index, int valueToInsert) {

    int i = x.length - 1;
    while (i > index) {
        x[i] = x[i - 1];
        i--;
    }
    x[i] = valueToInsert;
}


texts: Function that divides money with regard to the smallest denomination

texts:
I'm writing a function divideMoney that takes the value of a sum of money and divides it according to some percentages, then rounds each division to the nearest denomination.

For example:

//divideMoney(sum, percentages, denomination);

divideMoney(102, [0.5, 0.30, 0.20], 0.25);

This should divide the sum of $102 to 3 divisions, first is 50% ($51), second is 30% ($30.6) and the third is 20% ($20.4).

But because the smallest accepted denomination is the quarter ( 0.25 ), so $30.6 should be $30.50 instead, and $20.40 should be $20.50 as well. So the expected result is [51, 30.5, 20.5].

Here is what I tried

Original Code

function divideMoney(sum, percentages, denomination) {
    var result, diff, resultSum;
    result = [];
    diff = 0;
    percentages.forEach(function (percent) {
        var div, fraction, mod;
        div = (percent * sum) + diff;
        fraction = div - Math.trunc(div);
        if (fraction > 0) {
            mod = fraction % denomination;
            diff += mod;
            div -= mod;
        }
        result.push(div);
    });
    resultSum = result.reduce(function(a, b){ return a + b; }, 0);
    if (resultSum < sum) {
        result.push(sum - resultSum);
    }
    return result;
}

Update (fix rounding)

function divideMoney(sum, percentages, denomination) {
    var result = [], remainder = sum, part, i;
    for(i = 0; i < percentages.length - 1; i++) {
        part = percentages[i] * sum;
        if (part % 1) {
            part = Math.round(part/denomination)*denomination;
        }
        remainder -= part;
        result.push(part);
    }
    result.push(remainder);
    return result;
}


texts:
Any tips on how to improve my code and make it cleaner to read for other programmers? Formatting, spacing, etc.

#include <iostream>
#include <stdlib.h>
#include <time.h>
#include <cstdlib>
#include <windows.h>

using namespace std;

int main()
{
    int userInput;
    int number;
    int min = 1;
    int max = 10;
    float playerTimesToPlay = 0;
    int playAgain;
    float tries = 3;

    do
    {
        system("CLS");
        cout << "Welcome to my number guessing game!" << endl;
        cout << "====================================================" << endl;
        cout << "The computer is generating a number between 1 and 10." << endl;
        cout << "====================================================" << endl;
        srand(time(0));
        number = rand()% (max - min + 1)+min;
        playerTimesToPlay = 0;
        tries = 3;

        do
        {

            cout << "Please take a guess: ";
            if (!(cin >> userInput))
            {
            cout << endl;
            cout << "Please enter numbers only." << endl;
            cin.clear();
            cin.ignore(10000,'\n');
            }

            while(userInput > 10 || userInput < 0)
            {
                cout << "Pick a number BETWEEN 1 TO 10." << endl;
                cout << endl;
                userInput = NULL;
                playerTimesToPlay=0;
            }

            tries--;
            cout << endl;
            cout << "You picked: " << userInput << endl;
            cout << "======================" << endl;
            playerTimesToPlay++;

            if(userInput != number && tries > 0 && userInput <= 10)
            {
                cout << "Sorry! Invalid choice. Please try again. You have " << tries << " guess(es) remaining." << endl;
                cout << endl;
            }

            else if(userInput != number && tries == 0)
            {
                cout << "Sorry! Invalid choice." << endl;
                cout << "You have " << tries << " guesses remaining. You lose." << endl;
                cout << endl;
                cout << "Play again? " << endl;
                cout << "1. Yes" << endl;
                cout << "2. No" << endl;
                cout << ": " ;
                cin >> playAgain;
            }

            if(userInput == number)
            {
                cout << "Congratulations! You guessed the correct number!" << endl;
                cout << "Thanks for playing!" << endl;
                Sleep(2500);
            }

        }
        while (playerTimesToPlay < 3 && userInput != number);
    }
    while (playAgain == 1);

    system("Pause(0)");
    return 0;
}


texts: DB2 statement to update a header file if no corresponding record exists

texts:
I have written below SQL in an RPGLE program. Intent is to update the header file (TC400F) if no corresponding records exist in detail file (TC401F). Are there better ways of doing this?

Exec SQL UPDATE  TC400F
            SET  T40STS = '05',
                 T40OFL = '1'
          WHERE  T40SID = :K#T41SID AND
                 T40PID = :K#T41PID AND
     NOT EXISTS  (SELECT * FROM TC401F WHERE
                 T41SID = :K#T41SID AND
                 T41PID = :K#T41PID );


texts: Iterate through slicer settings and print to PDF

texts:
I have a spreadsheet with seven tables (tbl_1, tbl_2, ..., tbl_7) each controlled by its own slicer. Each slicer has six buttons (10, 20, 30, 40, 50, 60) referring to Team Codes. I use the code below to select one team on every slicer, then create a PDF for each team / slicer setting.

As of now, the code takes anywhere from 5-7min to run.

Sub SlicerTeam()
Dim wb As Workbook
Dim sc As SlicerCache
Dim si As SlicerItem

On Error GoTo errHandler
Application.ScreenUpdating = False
Application.EnableEvents = False

Set wb = ThisWorkbook

For x = 1 To 6
    For i = 1 To 7
    Set sc = wb.SlicerCaches("tbl_" & i)
        sc.ClearAllFilters
        For Each si In sc.VisibleSlicerItems
            Set si = sc.SlicerItems(si.Name)
                If Not si Is Nothing Then
                    If si.Name = x * 10 Then
                        si.Selected = True
                    Else
                        si.Selected = False
                    End If
                Else
                    si.Selected = False
                End If
        Next si

    Next i
Call PDFCreate
Next x

exitHandler:
Application.ScreenUpdating = True
Application.EnableEvents = True
Exit Sub

errHandler:
MsgBox ("Error in updating slicer filters.")
Resume exitHandler

End Sub

Sub PDFCreate()
Dim Fname As String
Dim path As String

path = "S:\MyFilePath\"
Fname = path & Sheets("Detail").Range("T1").Value & " - " & [TEXT('Population Detail'!B1,"mmm, yyyy")] & ".pdf"

    Sheets("Detail").ExportAsFixedFormat Type:=xlTypePDF, _
        FileName:=Fname, Quality:=xlQualityStandard, IncludeDocProperties:=True, _
        IgnorePrintAreas:=False, OpenAfterPublish:=False

End Sub


texts:
I aim to convert the TOC of The Python Language Reference — Python 3.6.3 documentation to a structured data with the following steps:

Copy contents to a plr.md file:

In [1]: with open('plr.md') as file:
   ...:     content = file.read()
In [2]: content
Out[2]: '\n\n- \\1. Introduction\n  - [1.1. Alternate Implementations]
(https://docs.python.org/3.6/reference/introduction.html#alternate-implementations)\n  - [1.2. Notation](https://docs.python.org/3.6/reference/introduction.html#notation)\n- \\2. Lexical analysis\n  - [2.1. Line structure]
(https://docs.python.org/3.6/reference/lexical_analysis.html#line-structure)\n  - [2.2. Other tokens](https://docs.python.org/3.6/reference/lexical_analysis.html#other-tokens)\n

Get chapters:

In [47]: chapters = content.split('\n- \\')
    ...: #subtract the unqualified part
    ...: chapters = chapters[1:]
In [50]: chapters[0]
Out[50]: '1. Introduction\n  - [1.1. Alternate Implementations](https://docs.python.org/3.6/reference/introduction.html#alternate-implementations)
\n  - [1.2. Notation](https://docs.python.org/3.6/reference/introduction.html#notation)'

Separate chapter name and section name in each chapters:

chapter_details = chapters[0].split('\n  -')
sections = chapter_details[1:]
chapter = chapter_details[0]
In [54]: chapter
Out[54]: '1. Introduction'
In [55]: sections
Out[55]:
[' [1.1. Alternate Implementations](https://docs.python.org/3.6/reference/introduction.html#alternate-implementations)',
 ' [1.2. Notation](https://docs.python.org/3.6/reference/introduction.html#notation)']

Convert section:

def convert_section(s):
    start = s.index('[') + 1
    end = s.index(']')
    return s[start:end]
In [57]: print(convert_section(' [1.1. Alternate Implementations](https://docs.python.org/3.6/reference/i
    ...: ntroduction.html#alternate-implementations)'))
1.1. Alternate Implementations

sections = map(convert_section, sections)
sections = list(sections)

Create a dict:

key = chapter
{key:sections}
 {'1. Introduction':['1.1. Alternate Implementations', '1.2. Notation']}

Encapsulate code in a class and get the result:

class TOC:
    def __init__(self, filename):
        self.filename = filename

    def read(self, filename):
        with open (filename) as file:
            content = file.read()
        return content

    def convert_section(self, s):
        start = s.index('[') + 1
        end = s.index(']')
        return s[start:end]

    def get_chapters(self, filename):
        content = self.read(filename)
        chapters = content.split('\n- \\')
        #subtract the unqualified part
        chapters = chapters[1:]
        return chapters

    def create_chapter_dict(self, chapter):
        chapter_details = chapter.split('\n  -')
        sections = chapter_details[1:]
        key = chapter_details[0]
        value = map(self.convert_section, sections)
        return {key: list(value)}

    def get_chapters_dict(self):
        chapters = self.get_chapters(self.filename)
        chapters_dict = {}
        for chapter in chapters:
            chapter_dict = self.create_chapter_dict(chapter)
            chapters_dict.update(chapter_dict)
        return chapters_dict

Run and get the result:

In [89]: TOC('plr.md').get_chapters_dict()
Out[89]:
{'1. Introduction': ['1.1. Alternate Implementations', '1.2. Notation'],
 '2. Lexical analysis': ['2.1. Line structure',
  '2.2. Other tokens',
  '2.3. Identifiers and keywords',
  '2.4. Literals',
  '2.5. Operators',
  '2.6. Delimiters'],
 '3. Data model': ['3.1. Objects, values and types',
  '3.2. The standard type hierarchy',
  '3.3. Special method names',
  '3.4. Coroutines'],

This solution is a bit too much for a daily common operation. Is there a standard or easy method for such a task?


texts:
This is a simple interpreter for the esoteric brainfuck programming language, written in C. It is one of my personal projects and I would love to receive expert advice.
Behavior

All characters except the eight commands ><+-.,[] are ignored and
treated as comments.

The array has 30,000 cells and each cell in the array contains a byte
(most commonly 8 bits).

Moving the pointer outside the bounds of the array will result in
undefined behavior.

Running
After successfully installing the interpreter, you can run it:
brain <file>

This is an example of running brain:
brain example.bf

You can visit the Git Repository at gitlab.com/andy-sb/brain for building/compiling instructions and further information.
Code
In brain.c I have:
#include <stdio.h>
#include <stdlib.h>

void goto_open(char **codep)
{
    int search = 1;
    while (search > 0) {
        --*codep;
        switch (**codep) {
        case '[':
            --search;
            break;
        case ']':
            ++search;
            break;
        default:
            break;
        }
    }
}

void goto_close(char **codep)
{
    int search = 1;
    while (search > 0) {
        ++*codep;
        switch (**codep) {
        case '[':
            ++search;
            break;
        case ']':
            --search;
            break;
        default:
            break;
        }
    }
}

void exec_command(char **codep, char **memp)
{
    switch (**codep) {
    case '>':
        ++*memp;
        break;
    case '<':
        --*memp;
        break;
    case '+':
        ++**memp;
        break;
    case '-':
        --**memp;
        break;
    case '.':
        fputc(**memp, stdout);
        break;
    case ',':
        **memp = fgetc(stdin);
        break;
    case '[':
        if (!**memp)
            goto_close(codep);
        break;
    case ']':
        if (**memp)
            goto_open(codep);
        break;
    default:
        break;
    }
}

void interpret(FILE *fp)
{
    fseek(fp, 0, SEEK_END);
    long fsize = ftell(fp);
    fseek(fp, 0, SEEK_SET);

    char code[fsize];
    char *codep = code;
    fread(code, 1, fsize, fp);

    char mem[30000] = {0};
    char *memp = mem;

    while (*codep != '\0') {
        exec_command(&codep, &memp);
        ++codep;
    }
}

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

    FILE *fp = fopen(argv[1], "r");
    if (!fp) {
        fprintf(stderr, "Error: failed to open file '%s'\n", argv[1]);
        exit(EXIT_FAILURE);
    }

    interpret(fp);

    fclose(fp);
    return EXIT_SUCCESS;
}


texts:
The following code is complete and works perfectly. What I want to do to is  make it more modular in a way where I can use the code again - similar to an api. I also hardly ever code in javascript, and I think my code looks disgusting, I feel like there are cleaner ways to write what I've written but I just don't have enough knowledge yet. If anyone has some advice/suggestion that would be appreciated.

The purpose of the module is to give the effect of a sentence being typed, then being backspaced out one character at a time. Here is a demo on my site: meneliktucker.me.

There are four main values to set:

sentences() - which is an array of sentences to be written out.
pause_sentence_time - the amount of time the sentence will pause after be written out - so the user can read the sentence before the sentence is deleted.
write_time - the time in ms to print a character
delete_time - the time in ms to delete a character

var delete_characters, delete_time, loop_characters,
loop_sentences, pause_sentence_time, print_char, sentences,
str_distance, write_time;

pause_sentence_time = 750;
write_time = 60;
delete_time = 40;

sentences = function() {
  var all_sentences;
  return all_sentences = ['is a student at the uOttawa.',
                       'loves to build things.'];
};

window.automatic_typing = function() {
  var char_array;
  char_array = sentences()[0].split('');
  loop_characters(char_array, 0, 0);
};

loop_sentences = function(prev_index) {
  var char_array, char_index, current_index;
  current_index = (prev_index + 1) % sentences().length;
  char_index = str_distance(prev_index);
  char_array = sentences()[current_index].split('');
  loop_characters(char_array, char_index, current_index);
};

loop_characters = function(char_array, char_index, index) {
  var timer;
  timer = 60;
  if (char_index === char_array.length) {
    timer = 750;
  }
  setTimeout((function() {
    if (char_index === char_array.length) {
      return delete_characters(index, str_distance(index));
    }
  print_char(char_array[char_index++]);
  loop_characters(char_array, char_index, index);
  }), timer);
};

print_char = function(c) {
  $('.automatic-typing').append(c);
};

delete_characters = function(index, dist) {
  setTimeout((function() {
    var temp;
    temp = $('.automatic-typing').text();
    if (temp.length === dist) {
      return loop_sentences(index);
    }
    $('.automatic-typing').text(temp.slice(0, temp.length - 1));
    delete_characters(index, dist);
  }), 40);
};

//The purpose of this function is to count the number of letters that
//the current and next sentence share from the start of both sentences.
//ex. the distance between 'this is cool' and 'this is not cool' is 7.

str_distance = function(index) {
  var counter, i, next_index, next_str_array, str_array, _i, _ref;
  str_array = sentences()[index].split('');
  next_index = index + 1;
  next_str_array = sentences()[next_index % sentences().length].split('');
  counter = 0;
  for (i = _i = 0, _ref = str_array.length; _i <= _ref; i = _i += 1) {
    if (str_array[i] === next_str_array[i]) {
      counter++;
    } else {
      break;
    }
  }
  if (str_array[counter] !== " " && counter !== 0) {
    while (true) {
      if (str_array[--counter] === " ") {
        break;
      }
    }
  }
  return counter;
};


texts: Set state in life cycle events from props

texts:
This is a ReactJS component that accepts a date and displays how long ago this date was (5 seconds ago, 3 minutes ago, 5 hours ago, ...) + it uses a setTimeout to automatically update itself when the state.displayDate changes.

What's going on:

On ComponentWillMount: set state.date from props
Update the state.displayDate with a setTimeout

Is this a good pattern or what are the alternatives?

var MomentAgo = React.createClass({
  propTypes: {
    date: React.PropTypes.string.isRequired
  },
  getInitialState: function() {
    return {
      date: null,
      displayDate: null
    };
  },
  componentWillMount: function (){
    this.setState({ date: this.props.date });
  },
  componentDidMount: function() {
    //with a setTimeout:
    this.setState({ displayDate: date.format('DD MMMM YYYY') });
  },
  render: function() {
    return(<span>{this.state.displayDate}</span>);
  }

According to Facebook, setting initial state from props is an anti-pattern.
What happens here is that state is set from props in ComponentWillMount. It would seem that this is thus also the same anti-pattern. Or is this the correct way to do it?


texts:
I finished CS50's bleep.py from pset6. I was hoping to get some feedback on my code (e.g., redundant code, bad practice, etc...).

Program function

load in a dictionary of banned words
accept a message from the user
if words in the message appear in the banned list, censor the word with *

from cs50 import get_string
from sys import argv, exit

def main():
    # ensure correct usage
    if len(argv) != 2:
        print("Usage: python bleep.py dictionary")
        exit(1)

    # open dictionary of bad words
    name = argv[1]
    text = open(name, "r", encoding="latin_1")
    if not text:
        print("Could not open {}.".format(name))
        exit(1)

    # store banned words in list
    bannedList = []
    for ban in text:
        ban = ban.replace('\n', '')
        bannedList.append(ban)

    # get user input to censor and split into words
    toCensor = input("What message would you like to censor? ")
    toCensor = toCensor.split()

    # for censored phrase
    final = []

    # check if word needs to be censored
    for word in toCensor:
        if word.lower() in bannedList:
            censored = word.replace(word, "*"*len(word))
            final.append(censored)
        else:
            final.append(word)

    print(' '.join(final))

if __name__ == "__main__":
    main()

EDIT

I implemented the suggestions, and I like it a lot better now. It even handles commas, periods, and other punctuation now. Thanks again!

from cs50 import get_string
from sys import argv, exit
import re

def censor(text, banned_words):
    # for censored phrase
    final = []

    # check if word needs to be censored
    for word in text:
        if (word.lower()).strip(",.!?") in banned_words:
            censored = re.sub('[a-zA-Z]', '*', word)
            final.append(censored)
        else:
            final.append(word)

    #return censored phrase
    return ' '.join(final)

def main():
    # ensure correct usage
    if len(argv) != 2:
        print("Usage: python bleep.py dictionary")
        exit(1)

    # open dictionary of bad words
    name = argv[1]
    with open(name, 'r', encoding="UTF-8") as f:
        lines = [line.rstrip() for line in f]

    # get user input to censor and split into words
    to_censor = input("What message would you like to censor? ")
    to_censor = to_censor.split()

    #censor and obtain new phrase
    censored = censor(to_censor, lines)
    print(censored)

if __name__ == "__main__":
    main()


texts: Improving function that replaces all instances of x with y in string

texts:
I have the following:

#include <string>
#include <string_view>
#include <vector>
#include <unordered_map>

#include <iostream>

namespace utils
{
    void replace_all(std::string& string, const std::string_view from, const std::string_view to)
    {
        std::size_t start_pos{ 0 };
        while ((start_pos = string.find(from)) != std::string::npos)
        {
            string.replace(start_pos, from.length(), to);
            start_pos += to.length();
        }
    }

    void replace_all(std::string& string, const std::unordered_map<std::string_view, std::string_view>& map) // Warning 2 here
    {
        for (const auto [from, to] : map) // Warning 1 here
        {
            replace_all(string, from, to);
        }
    }
}

int main()
{
    std::unordered_map<std::string_view, std::string_view> my_map{ {"this", "that"}, {"hes", "her"}, {"my", "yours"} };
    std::string my_string{ "This is hes chocolate and my aswell" };
    utils::replace_all(my_string, my_map);
    std::cout << my_string << std::endl;

    return 0;
}

It works and outputs: This is her chocolate and yours aswell as expected.

Analysing this in MSVC 2019 with C++ Core guidelines turned on I do get the following warnings though:

C:\dev\MyVSProjects\AE\AE\include\AE\Main.cpp(23): warning C26486: Don't pass a pointer that may be invalid to a function. Parameter 0 '$S1' in call to '<move><std::pair<std::basic_string_view<char,std::char_traits<char> > const ,std::basic_string_view<char,std::char_traits<char> > > const & __ptr64>' may be invalid (lifetime.3).

C:\dev\MyVSProjects\AE\AE\include\AE\Main.cpp(21): warning C26487: Don't return a pointer '(*(*map))' that may be invalid (lifetime.4).

I'd like to remove these warnings and make the code as clean as possible.


texts: Simple DRY Rails - check if a model belongs to a user

texts:
I can clearly see I'm repeating myself, but I don't know how to refractor this without making it really ugly. What I have:

class ChildModelController < ApplicationController

    def new
        @model = ParentModel.find(params[:id])
        # Does the current user have permissions on the parent model
        if signed_in?
          unless current_user.admin? or current_user.id == @model.user_id
            flash[:error] = t('errors.messages.not_authorized')
            flash.keep
            redirect_to root_path
          end
        else
          unless session and session[:session_id] == @model.author_session_token
            flash[:error] = t('errors.messages.not_authorized')
            flash.keep
            redirect_to root_path
          end
        end
        #do stuff to the model
    end

end

The only way I can think to make it smaller is to make it ugly:

class ChildModelController < ApplicationController

    def new
        @model = ParentModel.find(params[:id])
        # Does the current user have permissions on the parent model
        if (!signed_in? and session and session[:session_id] == @model.author_session_token ) || (signed_in and current_user.admin? or current_user.id == @model.user_id)
            flash[:error] = t('errors.messages.not_authorized')
            flash.keep
            redirect_to root_path
          end

        #do stuff to the model
    end

end

Am I missing an even easier way?


texts: Go version of Advent of Code, day 5 - Dealing with runes

texts:
I tried to solve the Advent of Code quiz for day 5 in Go, since my brute force algorithm wasn't efficient in Ruby. I solved the first part of the quiz with the  following Go code.

package main

import (
        "crypto/md5"
        "encoding/hex"
        "fmt"
        "strings"
)

func main() {
        fmt.Println("Password:", extractPassword("abc"))
}

func extractPassword(roomId string) string {
        position := 0
        i := 0
        password := make([]rune, 8)

        for position < 8 {
                letter := evaluateIndex(roomId, i)
                if 0 != letter {
                        fmt.Printf("Found %c for index %d\n", letter, i)
                        password[position] = letter
                        position++
                }
                i++
        }
        return string(password)
}

func evaluateIndex(roomId string, index int) rune {
        text := fmt.Sprintf("%s%d", roomId, index)
        hash := md5Hash(text)
        if strings.HasPrefix(hash, "00000") {
                return []rune(hash)[5]
        } else {
                return 0
        }
}

func md5Hash(text string) string {
        hash := md5.Sum([]byte(text))
        return hex.EncodeToString(hash[:])
}

My biggest issue was the string vs rune conflict. I'm interested in following points.

Idiomatic Go style
Usage of the Go standard library
Performance improvments, while it's fast enough yet


texts:
I have code to calculate STM CRC32 in python. It works well but I'm shocked from time when I see how much it takes. Namely calculating for 5120 bytes takes about 20ms (or even more)! Now I'm thinking this code is weak or it is just python ?

Code :

custom_crc_table = {}
poly = 0x04C11DB7

def generate_crc32_table(_poly):

    global custom_crc_table

    for i in range(256):
        c = i << 24

        for j in range(8):
            c = (c << 1) ^ _poly if (c & 0x80000000) else c << 1

        custom_crc_table[i] = c & 0xffffffff

def crc32_stm(bytes_arr):

    length = len(bytes_arr)
    crc = 0xffffffff

    k = 0
    while length >= 4:

        v = ((bytes_arr[k] << 24) & 0xFF000000) | ((bytes_arr[k+1] << 16) & 0xFF0000) | \
        ((bytes_arr[k+2] << 8) & 0xFF00) | (bytes_arr[k+3] & 0xFF)

        crc = ((crc << 8) & 0xffffffff) ^ custom_crc_table[0xFF & ((crc >> 24) ^ v)]
        crc = ((crc << 8) & 0xffffffff) ^ custom_crc_table[0xFF & ((crc >> 24) ^ (v >> 8))]
        crc = ((crc << 8) & 0xffffffff) ^ custom_crc_table[0xFF & ((crc >> 24) ^ (v >> 16))]
        crc = ((crc << 8) & 0xffffffff) ^ custom_crc_table[0xFF & ((crc >> 24) ^ (v >> 24))]

        k += 4
        length -= 4

    if length > 0:
        v = 0

        for i in range(length):
            v |= (bytes_arr[k+i] << 24-i*8)

        if length == 1:
            v &= 0xFF000000

        elif length == 2:
            v &= 0xFFFF0000

        elif length == 3:
            v &= 0xFFFFFF00

        crc = (( crc << 8 ) & 0xffffffff) ^ custom_crc_table[0xFF & ( (crc >> 24) ^ (v ) )]
        crc = (( crc << 8 ) & 0xffffffff) ^ custom_crc_table[0xFF & ( (crc >> 24) ^ (v >> 8) )]
        crc = (( crc << 8 ) & 0xffffffff) ^ custom_crc_table[0xFF & ( (crc >> 24) ^ (v >> 16) )]
        crc = (( crc << 8 ) & 0xffffffff) ^ custom_crc_table[0xFF & ( (crc >> 24) ^ (v >> 24) )]

    return crc


texts: How can I refactor this method so I don't use it in multiple places?

texts:
I have the following method which I use in multiple places, but it only differs by a few different things, so I was wondering how I can refactor it so I can have it in a common class and call it from there everywhere.

public override DataTable GetRecords(QueryContext queryContext, out int totalRecords)
{
    // Build Query
    //Different
    StringBuilder query = new StringBuilder("SELECT * FROM TABLE");
    Dictionary<string, string> parameters = new Dictionary<string, string>();

    if (queryContext.OrderByColumns.Count == 0)
    {
        //Can very in length or number of parameters
        queryContext.OrderByColumns.Add("param_1"); //different
        queryContext.OrderByColumns.Add("param_2"); //different
    }

    if (queryContext.Parameters.Count > 0)
    {
        foreach (QueryParameter p in queryContext.Parameters)
        {
            dataAccess.paramAdd(parameters, query, p.ColumnName, p.Value.ToString());
        }
    }

    // Order By Clause
    query.Append(queryContext.OrderByColumns.GetSqlClause());

    // Apply Limit
    if (queryContext.ApplyLimit)
    {
        query.AppendFormat(" LIMIT {0},{1}", queryContext.Offset, queryContext.Limit);
    }

    //Execute the query.
    DataSet results = dataAccess.ExecuteQuery(query.ToString(), parameters);
    totalRecords = Convert.ToInt32(results.Tables[1].Rows[0][0]);
    return results.Tables[0];
}

The only differences in other places are the value of the query variable and the paramters added by queryContext.OrdByColumn.Add(...).  Other than that, everything is the same.

My first shot was going to be doing something like:

public override DataTable GetRecords(StringBuilder query, string[] orderByParams, QueryContext queryContext, out int totalRecords)
{

    Dictionary<string, string> parameters = new Dictionary<string, string>();

    if (queryContext.OrderByColumns.Count == 0)
    {
        foreach(var param in orderByParams)
        {
            queryContext.OrderByColumns.Add(param);
        }
    }

    if (queryContext.Parameters.Count > 0)
    {
        foreach (QueryParameter p in queryContext.Parameters)
        {
            dataAccess.paramAdd(parameters, query, p.ColumnName, p.Value.ToString());
        }
    }

    // Order By Clause
    query.Append(queryContext.OrderByColumns.GetSqlClause());

    // Apply Limit
    if (queryContext.ApplyLimit)
    {
        query.AppendFormat(" LIMIT {0},{1}", queryContext.Offset, queryContext.Limit);
    }

    //Execute the query.
    DataSet results = dataAccess.ExecuteQuery(query.ToString(), parameters);
    totalRecords = Convert.ToInt32(results.Tables[1].Rows[0][0]);
    return results.Tables[0];
}

LINQ is available to me, so if that can improve it, I am welcome to ideas using that too.


texts:
So I'm using the acts_as_taggable_on gem to tag 3 different models: Question, Blog, and Video

Each one has a site_id to distinguish which site they show up on (SaaS-ish).

I wanted to get all tags for a specific site without saving site_id right on a Tag or Tagging.

I came up with the following, but I feel like there might be something more efficient I could do.

ActsAsTaggableOn::Tag.class_eval do
  extend FriendlyId
  friendly_id :name, use: :slugged

  def self.find_by_site site, limit=0
    klasses = [Blog, Question, Video]
    sql = []
    site_ids = []
    klasses.each do |k|
      sql << "
        SELECT tags.*, (SELECT COUNT(*) FROM taggings t WHERE t.tag_id = tags.id) AS `count`
              FROM tags
              LEFT JOIN taggings
              ON (taggings.tag_id = tags.id)
              LEFT JOIN #{k.table_name}
              ON (#{k.table_name}.id = taggings.taggable_id)
              WHERE taggings.taggable_type = '#{k.name}'
              AND #{k.table_name}.site_id = ?
      "
    end
    sql = sql.join(" UNION ")
    sql += " GROUP BY id "
    sql += " ORDER BY COUNT DESC "
    sql += "LIMIT #{limit}" if limit > 0
    klasses.count.times { site_ids << site.id }
    find_by_sql([sql, *site_ids])
  end
end

Here is the current functionality with timing:

irb(main):011:0> ActsAsTaggableOn::Tag.find_by_site Site.find(3); nil
  Site Load (0.4ms)  SELECT `sites`.* FROM `sites` WHERE `sites`.`id` = 3 LIMIT 1
  ActsAsTaggableOn::Tag Load (0.5ms)
 SELECT tags.*, (SELECT COUNT(*) FROM taggings t WHERE t.tag_id = tags.id) AS `count`
 FROM tags
 LEFT JOIN taggings
 ON (taggings.tag_id = tags.id)
 LEFT JOIN blogs
 ON (blogs.id = taggings.taggable_id)
 WHERE taggings.taggable_type = 'Blog'
 AND blogs.site_id = 3
 UNION
 SELECT tags.*, (SELECT COUNT(*) FROM taggings t WHERE t.tag_id = tags.id) AS `count`
 FROM tags
 LEFT JOIN taggings
 ON (taggings.tag_id = tags.id)
 LEFT JOIN questions
 ON (questions.id = taggings.taggable_id)
 WHERE taggings.taggable_type = 'Question'
 AND questions.site_id = 3
 UNION
 SELECT tags.*, (SELECT COUNT(*) FROM taggings t WHERE t.tag_id = tags.id) AS `count`
 FROM tags
 LEFT JOIN taggings
 ON (taggings.tag_id = tags.id)
 LEFT JOIN videos
 ON (videos.id = taggings.taggable_id)
 WHERE taggings.taggable_type = 'Video'
 AND videos.site_id = 3
 GROUP BY id ORDER BY COUNT DESC


texts:
Uncaught TypeError: document.getElementById(...) is null
I have a single JavaScript file that is connected to multiple pages. The below snippet is a function that is used for a single page. The above error appears when the user navigates to one of the pages that does not use the below function, and it references the document.getElementById('button01').addEventListener('click', newThing); line at the bottom. I've gathered that the error comes up due to the fact that button01 does not exist on these pages.
function newThing() {
const output = document.getElementsByTagName('output')[0];
if (!(document.forms.thingSelection2.type.value in options)) {
    return false;
}
const list = options[document.forms.thingSelection2.type.value];
const method = document.forms.thingSelection1.mode.value + 'Item';
const item = list[method]();
output.innerHTML = item;

}
document.getElementById('button01').addEventListener('click', newThing);

Solution
My solution for this is simple; place the line in an if statement like so:
if(document.getElementById('button01')) {
    document.getElementById('button01').addEventListener('click', newThing);
}

This removes the error from the pages that don't use it.
Questions
Does this open up the possibility for any buggy behavior that I don't know about? Is there a better way to achieve the same results?
HTML
I'm thankful for the feedback this post has received thus far. Since some of the answers contain recommendations based on assumptions of my HTML, I've decided to add the respective HTML in the below snippet. One thing to note is that I use two forms. This is required for the functionality of the code. I'm unaware of any unintended bugs this may cause. If it does, please let me know below.

<output></output>

<button id="button01">New Thing</button>

   <form name="thingSelection1">
      <input type="radio" name="mode" value="random" id="mode1">&nbsp;Random

<input type="radio" name="mode" value="forward" id="mode2">&nbsp;Old&nbsp;-&nbsp;New

<input type="radio" name="mode" value="reverse" id="mode3">&nbsp;New&nbsp;-&nbsp;Old
   </form>

   <form name="thingSelection2">
       Doodle&nbsp;<input type="radio" name="type" value="doodle" id="doodleCheck">

       Video&nbsp;<input type="radio" name="type" value="video" id="videoCheck">

       Audio&nbsp;<input type="radio" name="type" value="audio" id="audioCheck">

       Photo&nbsp;<input type="radio" name="type" value="photo" id="photoCheck">

       Text&nbsp;<input type="radio" name="type" value="text" id="textCheck">
   </form>

Furthermore, I'd like to point out that the original snippet is only part of my full JavaScript. Based on the information provided by this post, I've concluded that adding the remaining JavaScript, while possibly beneficial and relevant to some of the answers below, could possibly be out of the scope of the original topic of this post. Please note your thoughts on this in the comments below.


texts:
On several occasions I had to use a fixed set of keys (constants in the sense of static final String) with some additional logic (grouping in different keySets). After some more or less lefthanded approaches with static final String constants, I learned the advantages of enum. Since everything is known from the start I tend to use enum. But I don't see how to make this approach reusable for different sets of keys (avoid copy paste). Here is the pattern I found unseful so far. Hope you have some ideas how to improve.

import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;

public class TestKeys
{
    public enum Groups
    {
        BASIC,
        BROAD(BASIC), // Keys defined in group BASIC are also part of group BROAD
        SEPARATE;

        private Collection<Groups> m_subGroups = new HashSet<Groups>();
        private Collection<String> m_keySet = new HashSet<String>();

        private Groups()
        {
            m_subGroups.add(this);
        }

        private Groups(Groups... groups)
        {
            this();
            for (Groups group : groups)
            {
                m_subGroups.add(group);
            }
        }

        public boolean contains(String keyString)
        {
            return m_keySet.contains(keyString);
        }

        public boolean contains(Keys key)
        {
            return m_keySet.contains(key.toString());
        }

        public boolean containsIgnoreCase(String keyString)
        {
            for (String key : m_keySet)
            {
                if (key.equalsIgnoreCase(keyString)) return true;
            }
            return false;
        }
    }

    public enum Keys {
        KEY_BASE1("Base 1", Groups.BASIC),
        KEY_BASE2("Base 2", Groups.BASIC),
        KEY_BROAD1("Broad 1", Groups.BROAD),
        KEY_BROAD2("Broad 2", Groups.BROAD),
        KEY_DIFF1("Different 1", Groups.SEPARATE)
        ;

        private String m_str;
        private Groups m_group;

        Keys(String str, Groups group)
        {
            m_str = str;
            m_group = group;
            if (group == null)
            {
                throw new AssertionError("group mustn't be null");
            }
        }

        public Groups getGroup()
        {
            return m_group;
        }

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

        public boolean equals(String string)
        {
            if (toString().equals(string)) return true;
            return false;
        }

        public Keys getKeyIgnoreCase(String keyString)
        {
            for (Keys key : Keys.values())
            {
                if (key.toString().equalsIgnoreCase(keyString)) return key;
            }
            return null;
        }
    }

    static
    {
        fillKeySets();
        integrityCheck();
    }

    public static void integrityCheck() throws AssertionError
    {
        for (Groups bereich : Groups.values())
        {
            checkMultipleKeys(bereich);
        }
    }

    public static void checkMultipleKeys(Groups bereich)
            throws AssertionError
    {
        HashSet<String> set = new HashSet<String>();
        for (Keys key : Keys.values())
        {
            if (set.contains(key.toString()))
            {
                throw new AssertionError("Multiple Key \"" + key + "\".");
            }
            set.add(key.toString());
        }
    }

    public static void fillKeySets()
    {
        for (Groups bereich : Groups.values())
        {
            for (Keys key : Keys.values())
            {
                if (bereich.m_subGroups.contains(key.m_group))
                {
                    bereich.m_keySet.add(key.toString());
                }
            }
            bereich.m_keySet = Collections.unmodifiableCollection(bereich.m_keySet);
        }
    }

    public static Collection<String> keySet(Groups group)
    {
        return group.m_keySet;
    }
}


texts: Using Task.Wait() for waiting while task is finished (even if it already finished)

texts:
Can I use task.Wait(); like that? Note that when I call task.Wait the task is probably already finished.

And probably you can suggest better pattern.

class A {
    private Task task1;
    private Task task2;

    ...
    public void Connect() {
        stayConnected = true;
        task1 = Task.Factory.StartNew(....,
            while (stayConnected) {
                ....
            }
            LongRunning);
        task2 = Task.Factory.StartNew(....,
            while (stayConnected) {
                ....
            }
            LongRunning);
    }

    private volatile bool stayConnected;

    // should be synchronous. when return everything should be disconected
    public void Disconnect() {
        stayConnected = false;
        task1.Wait();
        task1 = null;
        task2.Wait();
        task2 = null;
    }

}


texts: Optimising sum of 2 from an array - leetcode challenge

texts:
I was for the first time doing a challenge on the leetcode, and I have come up with the JS code for finding the indexes of 2 numbers that add up to a target value that looks like this:

let nums = [-3, 0, 3, 2, 4, 0];
let target = 0;

var twoSum = function(nums, target) {
    let checkedNums = [];
    let result = [];
    nums.forEach((num, i) => {
        if (result.length === 0) {
            if (checkedNums.includes(target - num)) {
                result = [nums.indexOf(target - num), i];
            } else {
                    checkedNums.push(num);
            }
        }
    })
    return result;
};

twoSum(mums, target) // outputs [0, 2]

But, when I saw that the runtime of this code it 72ms, and that there are far better runtimes I wonder how can I optimise this code to get a better runtime?
Here is the fiddle.
I have also came up with solution, which I thought would be faster since we stop the for loop immediately when the solution is found, but I didn't see any decrease in the runtime:

var twoSum = function(nums, target) {
    let checkedNums = [];
    for (let i = 0; i < nums.length; i++) {
        if (checkedNums.includes(target - nums[i])) {
          return [nums.indexOf(target - nums[i]), i];
        } else {
          checkedNums.push(nums[i]);
        }
    }
};


texts:
Is it possible to rewrite this piece of code any better when it comes to efficiency and/or readability?

public function dispatch()
{
    $key = array_search($this->reqUri, $this->routes);

    if ($key !== false) {
        if (isset($this->methods[$key])) {
            if ($this->methods[$key] === $this->reqMethod) {
                call_user_func($this->callables[$key]);

                return;
            } else {
                $this->defaultCallable();

                return;
            }
        }

        call_user_func($this->callables[$key]);

        return;
    }

    $this->defaultCallable();
}


texts:
I'm pretty new, but I'm always looking for different/better ways to solve these problems as it helps me understand it better and hopefully will make me better programmer. Feel free to point out any mistakes or industry "dont's" as well.

#include <cstdio>
using namespace std;

//Function Prototypes
void deleteDupes(char message[], int msg_length);
int length(char message[]);

int main()
{
    //Declaring vars
    int msg_length = 0;
    char message[500] = "The dog jumped up and down and ate chocolate, then he bit the cat";

    //Display the original message and it's length
    msg_length = length(message);
    puts(message);
    printf("The message length before deleting the dupes is: %d\n\n", msg_length);

    //Deletes the duplicates and displays the new message and length
    deleteDupes(message, msg_length);
    msg_length = length(message);
    puts(message);
    printf("The message length after deleting the dupes is: %d\n", msg_length);

    return 0;
}//end main

//Function to determine the message length
int length(char array[])
{
    int i = 0;
    for(i; '\0' != array[i]; i++){}
    return i;
}

//Function to delete the duplicate char(s) from the array message
void deleteDupes(char message[], int msg_length)
{
    for(int i = 0; i < msg_length; ++i)
    {
       for(int j = i + 1; j < msg_length; ++j)
       {
           if(message[j] == message[i])
           {
               for(int k = j; k < msg_length; ++k)
               {
                   message[k] = message[k + 1];
               }
            msg_length -= 1;
            --i;
           }
       }
    }
}


texts: Adding punctuation to US and European patent numbers

texts:
I want to add custom punctuations in a given string.

eg:

US 8012999 B2 --> US 8,012,999 B2
US 20170107206 A1 --> US 20170107206 A1
EP 2795605 B1 --> EP 2 795 605 B1
US 09700674 --> US 09/700,674

This is what I wrote

def punctuate(text, punctuations):
    """Given text and list of tuple(index, puncuation)
    returns punctuated text"""

    char_list = list(text)
    k = 0
    for i, char in punctuations:
        char_list.insert(i + k, char)
        k += 1
    return "".join(char_list)

In [53]: punctuate('US 8012999 B2', [(4, ','), (7, ',')])
Out[53]: 'US 8,012,999 B2'

In [54]: punctuate('US 20170107206 A1', [(7, '/')])
Out[54]: 'US 2017/0107206 A1'

In [55]: punctuate('US 09700674', [(5, '/'), (8, ',')])
Out[55]: 'US 09/700,674'

In [56]: punctuate('EP 2795605 B1', [(4, ' '), (7, ' ')])
Out[56]: 'EP 2 795 605 B1'

This works fine. Is this the best way to do it?
The punctuations list will always be sorted one starting from lower to higher index.


texts: Pandas DataFrame.sort_values() new method to exclude by row name

texts:
I was working on new function with Pandas DataFrame. It's meant to sort values by column name but exclude specific rows from sorting and return sorted dataframe with that has rows with preserved positions.
E.g. I have a DataFrame
       Name     marks
rank1   Tom     10
rank2   Jack    30
rank3   nick    50
rank4   juli    5

So I created a function (not finalized, but the idea)
def sort_df_values(df, column_names, ascending=False, fixed_categories=None):
    if fixed_categories is not None and fixed_categories:
        original_positions = {name: position for position, name in enumerate(df.index.values) if name in fixed_categories}
        original_positions = dict(sorted(original_positions.items(), key=operator.itemgetter(1), reverse=True))

        excluded = df.loc[fixed_categories]
        included = [name for name in list(df.index) if name not in fixed_categories]
        new_df = df.loc[included].sort_values(column_names, ascending=ascending)
        result = pd.concat([new_df, excluded])

        new_index_values = list(result.index.values)

        while original_positions:
            val, old_position = original_positions.popitem()
            print(val, old_position)
            for current_position, name in enumerate(new_index_values):
                if name == val:
                    new_index_values.insert(old_position, new_index_values.pop(current_position))
                    break
        result = result.reindex(new_index_values)
    else:
        result = df.sort_values(column_names, ascending=ascending)

    return result

And then I call it like this:
sort_df_values(df, ['marks'], fixed_categories=['rank3'])

The result is correct, I sort all data, but I preserve the excluded rows positions:
       Name     marks
rank2   Jack    30
rank1   Tom     10
rank3   nick    50
rank4   juli    5

Is there any better option on how to do this? Maybe there is already some feature in pandas that could help me out on this one?
DataFrame example:
{'Name': {'rank1': 'Tom', 'rank2': 'Jack', 'rank3': 'nick', 'rank4': 'juli'},
 'marks': {'rank1': 10, 'rank2': 30, 'rank3': 50, 'rank4': 5}}


texts:
Spent some time implementing a graph as an adjacency list. Looking for suggestions on how to improve this implementation.

#include<vector>
#include<iostream>

class Graph{

public:
     //n is the number of vertices in graph
     Graph(int n)
     {
          N=n;
          E=0;
          //for(int i=0;i < n; ++i)
          for(;n > 0; n--)
          {
              std::vector<int> row;
              adjList.push_back(row);
          }
     }
     //# of vertices
     int Vertices()
     {
         return N;
     }
     //# of Edges
     int Edges()
     {
          return E;
     }
     void addEdge(int v, int w)
     {
          adjList[v].push_back(w);
          adjList[w].push_back(v);
          ++E;
     }

     void  adjVertices(int v)
     {
        std::cout<<"Adjacent vertices of"<< v <<std::endl;
        for(auto &x : adjList[v])
           std::cout<< x << std::endl;
     }

private:
    int N;
    int E;
    std::vector< std::vector<int> > adjList;
};

int main()
{
     Graph G(10);
     G.addEdge(3, 4);
     G.addEdge(0, 2);
     G.addEdge(0, 4);
     G.addEdge(0, 9);
     G.adjVertices(0);
     G.adjVertices(4);
}


texts:
I'm doing Python programming challenges and have come across one where the object of the challenge was to create a script to change passwords. The script must validate that the password contains, one upper, one lowercase, and one number. After everything has been validated the script should save the password to a text file. I added special characters and some basic encryption to the program to make it a little more interesting.

Source:

# -*- encoding: UTF-8 -*-

import re
import getpass
from random import randint

class PasswordValidator(object):
    """ A password validator, used to validate a password for
        specific characters, numbers, and special characters """

    validated = False

    def __init__(self, password):
        self.password = password

    def validate_length(self):  # Check the length, gotta be over 8
        if len(self.password) > 8:
            return True
        else:
            return False

    def validate_upper_case(self):  # Check for upper case characters
        return re.search("[A-Z]", self.password) is not None

    def validate_lower_case(self):  # Check for lower case characters
        return re.search("[a-z]", self.password) is not None

    def validate_integers(self):  # Check for integers
        return re.search("[0-9]", self.password) is not None

    def validate_spec_chars(self):  # Check for special characters
        return re.search("[!$&*]", self.password) is not None

    def validate_all(self):
        """ Validate everything. """
        length = self.validate_length()
        upper = self.validate_upper_case()
        lower = self.validate_lower_case()
        digits = self.validate_integers()
        specs = self.validate_spec_chars()

        if specs is False:
            return "Failed special characters validation. Allowed special chars: (! $ & *)"
        elif digits is False:
            return "Failed integer validation. Allowed integers: (0 - 9)"
        elif lower is False:
            return "Failed lower case validation. (a - z)"
        elif upper is False:
            return "Failed uppercase validation. (A - Z)"
        elif length is False:
            return "Failed length validation. Allowed length: (> 8)"
        else:
            self.validated = True
            return "Password validated successfully."

def encrypt(password):
    """ Encrypt the password simply example: bÃFuo <- says Test!23456
    :type password: String """
    arr = list(password)
    new_arr = []

    for i in arr:
        num = ord(i) + randint(0, 100)
        new_arr.append(chr(num))

    return ''.join(new_arr)

def obtain_password():
    """ Get the password, simple and easy with getpass library """
    return getpass.getpass('Change your password: ')

def second_authentication(password_to_verify):
    """ Verify that the password is what the user wants it to be,
        by asking for it a second time.
        :type password_to_verify: String """
    password = getpass.getpass('Enter password a second time: ')
    if password == password_to_verify:
        with open('passwords.txt', 'w') as f:
            f.write(encrypt(password_to_verify))
        return "Password changed."
    else:
        return "Password not changed."

if __name__ == '__main__':
    pass_verify = obtain_password()
    val = PasswordValidator(pass_verify)
    print val.validate_all()
    if val.validated is False:
        print "Password not validated."
    else:
        print second_authentication(pass_verify)

My question is, what can I do better to make this more efficient and more accurate?


texts:
Here's my solution for the Leet Code's Two Sum problem -- would love feedback on (1) code efficiency and (2) style/formatting.

Problem:

  Given an array of integers, return indices of the two numbers such
  that they add up to a specific target.

  You may assume that each input would have exactly one solution, and
  you may not use the same element twice.

  Example:

  Given nums = [2, 7, 11, 15], target = 9,

  Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].

My solution:

def twoSum(nums, target):
    """
    :type nums: List[int]
    :type target: int
    :rtype: List[int]
    """

    num_lst = list(range(len(nums)))

    for indx, num in enumerate(num_lst):
        for num_other in num_lst[indx+1:]:
            if nums[num] + nums[num_other] == target:
                return [num, num_other]
            else:
                continue
    return None