Complete Singly Link List C++ #include <iostream>
using std::cout;
using std::endl;

class SinglyLinkedList
{
    struct SLL
    {
        int data;
        SLL* next;
    };

    SLL *head;

public:
    SinglyLinkedList()
    {
        head = NULL;
    }

    SLL* createNewNode()
    {
        SLL *newNode = new SLL;
        newNode->next = NULL;
        newNode->data = -1;

        return newNode;
    }

    void printLL()
    {
        SLL *temp = head;

        while(temp)
        {
            cout << temp->data << " ";
            temp = temp->next;
        }

        cout<<endl;
    }

    void insertAtBeginning(int n)
    {
        insertAtPos(n,0);
    }

    void insertAtEnd(int n)
    {
        insertAtPos(n,0xFF);//max position so that it will add to end
    }

    void insertAtPos(int n, int pos)
    {

        if(pos < 0)
            return;

        SLL *newNode = createNewNode();
        newNode->data = n;

        if(head == NULL)
        {
            head = newNode;
            return;
        }

        int i = 0;
        SLL* temp = head;
        SLL* prev = temp;
        while(temp->next && i<pos)
        {
            i++;
            prev = temp;
            temp = temp->next;
        }

        if(temp->next == NULL)
        {
            temp->next = newNode;
        }

        else
        {
            newNode->next = temp;

            if(pos == 0)
                head = newNode;
            else
                prev->next = newNode;
        }
    }

    void deleteAtPos(int pos)
    {
        if(head == NULL)
            return;

        int i = 0;
        SLL* temp = head;
        SLL* prev = temp;

        SLL* nodeToDelete = NULL;

        if(pos == 0) //delete head node
        {
            nodeToDelete = head;
            head = head->next;

            delete nodeToDelete;
        }

        else
        {
            while(i<pos)
            {
                i++;
                prev = temp;
                temp = temp->next;
            }

            nodeToDelete = temp;
            prev->next = temp->next;

            delete nodeToDelete;
        }
    }

    void deleteLL()
    {
        SLL *temp = head;

        while(temp)
        {
            temp = head;
            head = temp->next;

            delete temp;

            temp = head;
        }

        cout<<endl;
    }

};

int main(int argc, char* argv[])
{
    SinglyLinkedList ll;

    //test cases
    ll.insertAtEnd(1);
    ll.insertAtEnd(2);
    ll.insertAtEnd(3);
    ll.insertAtEnd(4);
    ll.insertAtEnd(5);
    ll.insertAtEnd(6);

    ll.printLL();

    ll.insertAtBeginning(11);
    ll.insertAtBeginning(22);
    ll.insertAtBeginning(33);
    ll.insertAtBeginning(44);
    ll.insertAtBeginning(55);
    ll.insertAtBeginning(66);
    ll.insertAtBeginning(77);

    ll.printLL();

    ll.insertAtPos(0,1);
    ll.insertAtPos(4,1);
    ll.insertAtPos(2,1);
    ll.insertAtPos(5,1);
    ll.insertAtPos(1,1);

    ll.printLL();

    ll.deleteAtPos(0);
    ll.deleteAtPos(4);
    ll.deleteAtPos(2);
    ll.deleteAtPos(5);
    ll.deleteAtPos(1);

    ll.printLL();

    ll.deleteLL();

    ll.printLL();

    return 0;
}

Main Flaw
You have committed the biggest C++ sin. You have a class that contains an owned pointer SLL *head; but you have not done any of the resource management.
Please look up the rule of three.
Currently your code is just broken because you forgot this. Currently any copy of the object (through the compiler generated copy constructor or assignment operator) will mean both objects are using the same underlying list. Thus updates to one will update the other.
You don't have a destructor so your objects just leak memory when they go out of scope.
Interface
Why are you exposing the SSL internal object via a public API?
SLL* createNewNode()

This is just a bad idea. Your container contains int objects the user of your object does not need to know about SSL objects. This leakage of scope is a massive problem in terms of maintainability.
Code Review
Don't do this in header files.
using std::cout;
using std::endl;

If I include your header in my code you change the behavior for me. cout and endl may seem benign but it general it is a bad habit. If you want to do confine it to the closest scope you can.
Sure have a print method.
    void printLL()

But why not pass the stream you want to print on as a parameter (you can even default to std::cout).  But the main way to print in C++ is to use operator<<() so you should define this (and just make it call printLL).
Prefer "\n" over std::endl. The only difference is the extra flush. There is no need to flush any buffers. The default built in automatic flushing will flush ehenever you need. Any extra flushes that you do will just make the code less effecient.
        cout<<endl;

Your list seriously has a limit of 255 elements!
        insertAtPos(n,0xFF);//max position so that it will add to end

also 0xFF is not the maximum value that an int can hold. You may want to look up a better value.
Wht does SSL not have a constructor that takes the data value?
        SLL *newNode = createNewNode();
        newNode->data = n;

This could have been written much easier with:
        SSL* newNode = new SSL(n); // SSL constructor does the rest of the work.


Can I simplify my Restaurant MenuCard program? Here is my task: Create classes for a menu plan. With the help of the classes it should be possible to create a menu card for a restaurant in a hotel.
There should be a 'MenuCard' class for this purpose. This should include a date for the card and one or more course menus. Use an appropriate data type in Python for the date. It should be possible to add the courses to a menu card one after the other with a method add_course. There should be a class 'Course' for the course menu. This has a name (e.g. starter or first course). Furthermore, each course has one or more dishes, which can be added with the 'add_dish' method. For this purpose, the 'Dish' class is to be assembled, which is the name of the food administration and whether it is vegetarian. Use the str function in all classes to display the menu card on the screen.
Additional task: Create a class for a three-course menu ThreeCourseMenuCard, which the existing class sequences. With this class you have to make sure that there are no more than (or exactly) three courses.
Create your own personal map by controlling instances from the classes.
I already programmed this, but its to complicated for some users i know. Can someone give me any ideas on how to simplify this program. Thank you in advance.
Here is my code:
#! /usr/bin/python3
import datetime, locale

class Dish():
    def __init__(self, name, veggy):
        self.__name = name
        self.__veggy = veggy
    def __str__(self):
        if self.__veggy == bool(1):
            return "{} (vegetarisch)".format(self.__name)
        else:
            return "{}".format(self.__name)

class Course():
    def __init__(self, name):
        self.__name = name
    def add_dish(self):
        for i in range(len(self.__name[1])):
            print(Dish(self.__name[1][i][0], self.__name[1][i][1]))
            if i < len(self.__name[1])-1:
                print("oder")
    def __str__(self):
        return "\n\n{}\n".format(self.__name[0][0])

class MenuCard():
    def __init__(self, date):
        self.__date = date.strftime('%A, %d.%m.%Y')
    def add_course(self, new_course):
        print(Course(new_course))
        Course(new_course).add_dish()
    def __str__(self):
        return "\n\nMenukarte fuer {}".format(self.__date)

vorspeise =     [["Vorspeise"],[
                ["Carpaggio vom Rind auf knackigem Blattsalat", 0],
                ["Honigmelone mit hausgemachtem Speck vom Hängebauchschwein", 0]
                ]]

suppe =         [["Suppe"],[
                ["Kräftige Rindssuppe mit Eiertörtchen", 1]
                ]]

erster_gang =   [["1. Gang"],[
                ["Salat vom Buffet", 0]
                ]]

zweiter_gang =  [["2. Gang"],[
                ["Wiener Schnitzel mit Kartoffelsalat", 0],
                ["Wildsaibling an Herbstgemüse auf Safranrisotto", 0],
                ["Saftiges Hirschgulasch mit Kastanienrotkraut und Semmelknödel", 0],
                ["Spinatlasagne mit frischen Tomaten", 1]
                ]]

nachspeise =    [["Nachspeise"],[
                ["Vanilleparfait auf Himbeerspiegel", 1],
                ["Luftige Topfenknödel mit roter Grütze", 0]
                ]]

locale.setlocale(locale.LC_ALL, 'de_DE.utf8')
menu = MenuCard(datetime.datetime(2020, 11, 9))
print(menu)

gaenge = [vorspeise, suppe, erster_gang, zweiter_gang, nachspeise]

for gang in gaenge:
    menu.add_course(gang)
```

MenuCard should have two variables, courses_list and menu_date. In my opinion, the method add_course should take in a Course object as parameter instead of taking in the name of the course.
def add_course(self, new_course: Course):
    self.__courses_list.append(new_course)

Course should have two variables, name and dishes_list. The add_dish method should take in a Dish object as parameter and append it to the dishes_list.
Dish seems alright. You should probably change if self.__veggy == bool(1): to if self.__veggy is True:.


Find the missing letter in sequence The challenge was to find the missing letter in an array in alphabetical order.

  Find the missing letter in the passed letter range and return it.

  If all letters are present in the range, return undefined.

My solution was this:

function fearNotLetter(str) {
  var letters = str.split('');
  var codes = [];
  var missing = 0;
  var start = 0 , next = 0 , c = 0;
  for(var i= 0; i < letters.length; i++){
    var charcode = letters[i].toString();
    codes.push(charcode.charCodeAt());
  }
  for(var j = 1; j < codes.length; j++){
    start = codes[j] -1;
    if(codes.indexOf(start) === -1){
      missing += start;
    }

  }
  if(missing === 0){
    return undefined
  }else {
    return String.fromCharCode(missing);
  }
}

I am wondering whether I have followed some bad practices or used dry code which might cause problems in a later use. Thanks in advance.

In general, you don't need to split the string and then process the array. Simply you must start from the first letter and store its charcode and then process the next later and check with the incremented charcode. If there is a difference than just break.

function f(str) {
    if (str && 0 < str.length) {
        var desCharCode = str.charCodeAt(0);
        for (var i = 1; i < str.length; ++i) {
            ++desCharCode;
            if (str.charCodeAt(i) != desCharCode) {
                return String.fromCharCode(desCharCode);
            }
        }
    }

    return undefined;
}


BTC price checker with web scraping, regex and Tkinter GUI The purpose of this was to practice web scraping, regex and GUI. I use a popular bitcoin website to scrape the names and prices of the top 16 cryptocurrencies. I then create a data frame and make a GUI to display the information based on the user's selection. I am looking for any and all input on how to improve this code.

import bs4
from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup
import pandas as pd

my_url = 'https://coinmarketcap.com/'
uClient = uReq(my_url)
page_html = uClient.read()
uClient.close()
page_soup = soup(page_html, "html.parser")

containers = page_soup.find("div", {"class": "container main-section"})
tabes = containers.find("table", {"id": "currencies"})
table_names= tabes.find("tbody")

btc = table_names.find_all("tr")

#Get the names and prices of the first 16 crypto coins
prices = []
names = []

for i in range(16):
    x = btc[i]

    #find the price
    x.find("a", {"class": "price"}).text
    current_price = x.find("a", {"class": "price"}).text.strip()
    prices.append(current_price)

    #find the name of the crypto
    name = x.find("td", {"class": "no-wrap currency-name"})
    q = name.text.strip()
    coin_name = " ".join(q.split("\n"))
    names.append(coin_name)

#Make a dataframe with the information we have gathered
df = pd.DataFrame({'Name': names,
                   'Price': prices,
                   })

#Use regular expressions to create a column with just the symbol
import re

symbols = []

for i in df['Name']:
    symbols.append(re.search(r"[A-Z]{3,5}\s\s", i).group().split()[0])

df['Symbol'] = symbols

#GUI
from tkinter import *

root = Tk()
root.title('BTC Price Check')
root.geometry('{}x{}'.format(950, 550))

frame = Frame(root,relief= GROOVE)
frame.pack(side = BOTTOM)

class CheckBox(Checkbutton):
    boxes = []  # Storage for all buttons
    def __init__(self, master=None, **options):
        Checkbutton.__init__(self, frame, options)
        self.boxes.append(self)
        self.var = IntVar()
        self.configure(variable=self.var)

header = Label(height=1, width=100, text = "Welcome to BTC Price Check")
header.config(font=("Courier", 20))
header.pack(side = TOP, pady = 0)

text = Text(frame)
text.pack(padx = 20, pady = 0, side = RIGHT)

#fucntions for our buttons
def display_price():
    for c, box in enumerate(CheckBox.boxes):
        if box.var.get():
            text.insert(INSERT, "The price of " + names[c] + " is: " + prices[c])
            text.insert(INSERT, "\n")
    text.config(state=DISABLED)

def clearBox():
    text.config(state=NORMAL)
    text.delete("1.0", "end")

#Use the class we created to iterate through the 16 cryptos and create a checkbox for each
a=0
while a<len(df['Name']):
   bouton=CheckBox(text = names[a],bg = 'yellow')
   a=a+1
   bouton.pack(fill = Y, pady = 2, side = TOP)

#Buttons
pricefind = Button(frame, text = 'Search',width= 20, command = display_price)
pricefind.pack()
clearprice = Button(frame, text = 'Clear', width= 20, command = clearBox)
clearprice.pack()

mainloop()

Group your imports

You should put all of your imports at the top of the file instead of sprinkling them throughout the code. This is both a best practice and a recommendation from PEP8

Don't use wildcard imports

You import Tkinter with from tkinter import *, but the PEP8 guidelines (and best practices) say you should not. For me, the best way to import Tkinter is with import tkinter as tk because it avoids polluting the global namespace and gives you a short prefix for using Tkinter classes and objects.  The prefix helps to make your code a bit more self-documenting.

Use more functions and classes

Most of your code exists in the global namespace. While that's fine for short programs, it becomes difficult to manage as the program grows. Its good to get in the habit of always using functions or classes for nearly all of your code.

For example, I recommend putting all of the GUI code into a class. That will make the code a bit easier to read, and gives you the flexibility of moving the code to a separate file.

clearBox should restore the state of the text widget

Your clearBox function resets the state of the text widget to be editable so that it can clear the contents, but it doesn't set it back. That means that after clicking the clear button, the user could be able to type anything they want in that window. It's somewhat harmless, but is a bit sloppy.


How can I optimize this mergesort? In main:

for(int i = 1; i < upto; i *= 2)
    {  for(int j = 0; j < (upto - i); j += (2*i))
       {  int end2 = (2*i < (upto - j)) ? 2*i : upto - j;
          mymerge(&(array[j]), i, end2); }  }

Merge:

void mymerge(people  *arr, int end1, int end2){
  int i = 0;
  int j = end1;
  int k = 0;
  people * temp = new people[end2];

  while(i < end1 && j < end2){
    if(arr[i].lname < arr[j].lname){
        temp[k] = arr[i];
        i += 1;
    }else if(arr[i].lname > arr[j].lname){
        temp[k] = arr[j];
        j += 1;
    }else if(arr[i].fname < arr[j].fname){
        temp[k] = arr[i];
        i += 1;
    }else if(arr[i].fname > arr[j].fname){
        temp[k] = arr[j];
        j += 1;
    }else if(arr[i].dob < arr[j].dob){
        temp[k] = arr[i];
        i += 1;
    }else if(arr[i].dob >= arr[j].dob){
        temp[k] = arr[j];
        j += 1; }

   k += 1;
 }

  while( i < end1){
    temp[k] = arr[i];
    i +=1; k +=1; }

  while(j < end2){
    temp[k] = arr[j];
    j += 1; k += 1; }

  for(int c = 0; c < end2; c += 1)
    arr[c] = temp[c];

  delete [] temp;
}

Would a recursive or iterative approach improve run time? Is there a better way to use pointers? This would be for an array that is not likely to be in any partially sorted order.

First you should define your ordering separately from your merge:

bool operator<(people const& lhs, people const& rhs)
{
    if (lhs.lname < rhs.lname)  {return true;}
    if (lhs.lname > rhs.lname)  {return false;}

    // lhs.lname == rhs.lname
    if (lhs.fname < rhs.fname)  {return true;}
    if (lhs.fname > rhs.fname)  {return false;}

    // lhs.lname == rhs.lname  && lhs.fname == rhs.fname
    if (lhs.dob < rhs.dob)      {return true;}

    // Optimize away the last test.
    //if (lhs.dob > rhs.dob)      {return false;}

    return false;
}

Incrementing by one can be done with the operator++

j += 1;
// Easier to write as:
++j;

Or you can do it in-place with:

temp[k] = arr[i];
i += 1;
// Easier to write as
temp[k] = arr[i++];

Using new/delete is a bad idea. It makes you do all the memory management. It is better to use classes that do it all for you. In your case std::vector is a better choice for memory management of arrays

people * temp = new people[end2];
....
delete [] temp;
// Better to use std::vector
std::vector<people>  temp(end2);
....

Prefer to use standard algorithms rather than manual loops.

  for(int c = 0; c < end2; c += 1) {
    arr[c] = temp[c];
  }
  // Use std::copy
  std::copy(temp.begin(), temp.end(), arr);

If you are copying something and not going to use the original again. Then try and move the object to the destination rather than copying it.

  temp[k] = arr[i];
  // Prefer to move rather than copy
  // if you are not going to use the value at arr[i] again.
  temp[k] = std::move(arr[i]);

  // Note this assumes you have defined move constructor and move assignment operator
  // for the class people. If you have not defined these operations then it will
  // default to use the normal copy versions.

Now your merge becomes more readable:

void mymerge(people  *arr, int end1, int end2)
{
  int i = 0;
  int j = end1;
  std::vector<people>  temp;
  temp.reserve(end2);

  while(i < end1 && j < end2)
  {
      people&  src =  (arr[i] < arr[j])
                         ? arr[i++]
                         : arr[j++];
      temp.emplace_back(std::move(src));
  }

  std::move(&arr[i], &arr[end1], std::back_inserter(temp));
  std::move(&arr[j], &arr[end2], std::back_inserter(temp));

  std::move(temp.begin(), temp.end(), arr);
}

Now that I have cleaned up the mymerge() function I can understand what you are doing and it looks like it should work. But it requires the input sections to be already pre-sorted. I am not sure how your double loop in main() achieves this.


build a string based on user's input python I need to write a function to build a string based on user input.
when user provide one type group of input: "tab" and link variable the string should be tab_link: xxxx.
when user provide one type group of input: "subtab" and link variable the string should be subtab_link: subtabxxxxx.

the logic is pretty much like following function. but do I have better way to do it then using if, else? because lets say if I have multiple group, does it mean I need to have more if, elif, elif to identify different group input and match the string?

subtab = {'subtab1': 1, 'subtab2': 2, 'subtab3': 3}
_dir = {'tab': 'tab_link:{}', 'subtab': 'subtab_link:{}'}

def func(**kwargs):
    if kwargs['_type'] == 'tab':
        print(_dir[kwargs['_type']].format(kwargs['_link']))
    else:
        print(_dir[kwargs['_type']].format(subtab[kwargs['_link']]))

func(_type='tab', _link='a')
func(_type='tab', _link='b')
func(_type='subtab', _link='subtab1')
func(_type='subtab', _link='subtab2')

#expect
tab_link:a
tab_link:b
subtab_link:1
subtab_link:2

You can take _type and _link as keyword arguments, and so would simply your code. This can be as simple as func(_type=None, _link=None). However you may want to only take them if they are keyword arguments, and that method would allow them to be passed as normal positional arguments. To do this you can use prepend * to the function to do this. And so you can use func(*, _type=None, _link=None).


Deque implemented using a circular array I found a tutorial on implementing a deque using a circular array. I changed the implementation but I am not sure if it is correct or not.

So I have one question:

I wrote code that uses an addCount field to record whether there are any additions, but I'm not sure if it's correct? If not, please tell me where I made an error.

class Deque {
    static final int MAX = 100;
    int arr[];
    int front;
    int rear;
    int size;
    int addCount;

    public Deque(int size) {
        arr = new int[size];
        front = 0;
        rear = 0;
        this.size = size;
        addCount = 0;
    }

    // Checks whether Deque is full or not.
    boolean isFull() {

        return front == rear && !isEmpty();
    }

    // Checks whether Deque is empty or not.
    boolean isEmpty() {
        return front == rear && addCount == 0;
    }

    // Inserts an element at front
    void insertfront(int key) {
        if (isFull())
            return;

        addCount++;
        arr[front] = key;
        front = front + 1;
        front %= this.size;
    }

    // function to inset element at rear end
    // of Deque.
    void insertrear(int key) {
        if (isFull())
            return;
        addCount++;
        rear = (rear - 1) % this.size;
        arr[rear + this.size] = key;

    }

    // Deletes element at front end of Deque
    void deletefront() {
        if (isEmpty())
            return;
        addCount--;
        front = (front - 1) % this.size;
    }

    // Delete element at rear end of Deque
    void deleterear() {
        if (isEmpty())
            return;
        addCount--;
        rear = (rear + 1) % this.size;
    }

    // Returns front element of Deque
    int getFront() {
        int getFront = front-1;

        if (getFront < 0)
            getFront += this.size;
        return arr[getFront % this.size];
    }

    // function return rear element of Deque
    int getRear() {
        int getRearIndex = rear + this.size;
        return arr[getRearIndex % this.size];
    }

    // Driver program to test above function
    public static void main(String[] args) {
        Deque dq = new Deque(5);
        System.out.println("Insert element at rear end : 5 ");
        dq.insertrear(5);

        System.out.println("insert element at rear end : 10 ");
        dq.insertrear(10);

        System.out.println("get rear element : " + dq.getRear());

        dq.deleterear();
        System.out.println("After delete rear element new rear become : " + dq.getRear());

        System.out.println("inserting element at front end");
        dq.insertfront(15);

        System.out.println("get front element: " + dq.getFront());

        dq.deletefront();

        System.out.println("After delete front element new front become : " + +dq.getFront());

    }
}

I do not see any problems with addCount as long as we add a disclaimer that this solution is not thread safe.

The presented solution is a collection that can only accept int items. You can expand this if you add generic parameter to the class. Note that in this case, the internal array is of Object[] type and you let the compiler enforce type safety and also do auto-boxing to support primitive data items, just like in Java collections library. And while we mentioned that, you might want to consider making your solution implement the Deque interface from Java collections so that clients will work with a familiar API (of course you will want to change the name of the class to reflect that it is a concrete implementation of a Deque)


Simple Scala money library for some fun, I decided to start working on something that let me work with Money calculations. I realise there are libraries out there like Joda Money, but I'm doing this mainly for fun.

I was hoping to get a review on the way I've started to construct the library.

GitHub

private def calculate(that: Money)(f: (BigDecimal, BigDecimal) => BigDecimal): Either[String, Money] = (this.currency, that.currency) match {
case (c, c1) if c == c1 => new Right(this.copy(this.currency, f(this.amount, that.amount)))
case _ => new Left(Money.COMPARE_ERROR_MESSAGE)
}

private def compare(that: Money)(f: (BigDecimal, BigDecimal) => Boolean): Either[String, Boolean] = (this.currency, that.currency) match {
    case (c, c1) if c == c1 => new Right(this.amount > that.amount)
    case _ => new Left(Money.COMPARE_ERROR_MESSAGE)
}

These two methods are incredibly similar except for the return type. Could someone suggest a way to improve this?

First thoughts:

If an operation can fail, it is generally good practise to make this explicit in the API by returning a Try instead of an Either.
The duplicate code seems to stem from the fact that Money operations are only valid on Currencies of the same type. Scala gives you the power to have this check at compile time.

Example Code:

object Money {
  sealed trait Currency
  case object GBP extends Currency
}
case class Money[T <: Money.Currency](amount: BigDecimal) {
  private def calculate(that: Money[T])(f: (BigDecimal, BigDecimal) => BigDecimal): Money[T] = {
    copy(amount = f(this.amount, that.amount))
  }
  private def compare(that: Money[T])(f: (BigDecimal, BigDecimal) => Boolean): Boolean = {
    this.amount > that.amount
  }
}


null/undefined checking for checking seats This looks pretty messy (need to reduce nesting I feel).  I need a check an input for a seat, but I can't guarantee it has a value (one may not be chosen for example). If the seats aren't in a certain color it goes to seat basic (1), otherwise seat premium (2).

 var seat = $("input[id*=" + seatPrefix + "]");
    if (seat != 'undefined') {
        seat = seat[0].value;
        if (seat != "") {
            if (seat != "red" && seat != "blue" && seat != "silver" && seat != "gold") {
                chooseSeat(seat, "2");
            }
            else {
                chooseSeat(seat, "1");
            }
        }
    }

var seat = $("input[id*=" + seatPrefix + "]");
    if (seat != 'undefined') {

First off, an extra level of indentation has crept in here. Let me assume this is just a copy/paste error.

Any chance you could be using classes here instead of prefixed IDs? Best case: a single ID you know in advance. It seems that you assume there's only one match anyways.

jQuery, when it doesn't find anything, returns an empty collection, not undefined (or 'undefined'; did you get confused by typeof x !== 'undefined'?). To test if a jQuery collection is empty, you can use seat.length === 0 or even ! seat.length.

I don't normally use hungarian notation, but I do use it for jQuery objects, especially when I'm dealing with native elements as well: $seat. On a side note, shouldn't the variable name be $seatInput or something, rather than just $seat?

I recommend against the coercing equality operator (==). Use === instead. == can be a bit... unpredictable at times. There are some special cases or case where I find == acceptable (== null for null or undefined) but this is not one of them (if only because undefined != 'undefined')

seat = seat[0].value;

You can use seat.val() here. This has a positive side-effect that val returns undefined if the jQuery object holds no elements. Your code will attempt to dereference undefined in that case.

Also, you are reusing the same variable to mean a jQuery object at one point, then to mean a string in the next line. You should use two separate variables (or inline the first one) here.

if (seat != "") {

If you use val, you can move it outside its condition block, and merge the condition with this one:

if(seat !== undefined && seat !== "")

Since both undefined and the empty string are falsy and all other strings are truthy, this will work as well:

if(seat)

Of course, @retailcoder's suggestion to invert the condition and return early still applies.

if (seat != "red" && seat != "blue" && seat != "silver" && seat != "gold") {

You can use indexOf to shorten that code and make it more readable:

if (["red", "blue", "silver", "gold"].indexOf(seat) == -1)

if you like shortcuts,

if (!~["red", "blue", "silver", "gold"].indexOf(seat))

At this point, the array definition can (and should) be moved outside the condition. It is marginally nicer to the memory, but more importantly it's easier to find the array in case you want to ever change it if you put it at the beginning of the file.

if(...){
    chooseSeat(seat, "2");
} else {
    chooseSeat(seat, "1");
}

Shouldn't this logic be part of the chooseSeat function?

Also, 1 and 2 are non-obvious. Since you're passing a string anyways (why?), perhaps chooseSeat should accept "basic" and "premium" as its arguments?

If I couldn't modify the chooseSeat function or your HTML, I would probably refactor your code like this:

var basicColors = ["red", "blue", "silver", "gold"];
var seat = $("input[id*=" + seatPrefix + "]").val();
if (!seat) return;

if (~basicColors.indexOf(seat)) {
    chooseSeat(seat, "1");
} else {
    chooseSeat(seat, "2");
}

or, if return cannot be used (this is not the whole body of the function it is in),

var basicColors = ["red", "blue", "silver", "gold"];
var seat = $("input[id*=" + seatPrefix + "]").val();

if (seat) {
    if (~basicColors.indexOf(seat)) {
        chooseSeat(seat, "1");
    } else {
        chooseSeat(seat, "2");
    }
}


Array decomposing recursive function in JavaScript What I need is to remove first word from the string again and again until only one word is left, and put it all into array.

For example, I have this string as an input:

Chicago IL 12345 United States

What I need to achieve is this array:

[ 'Chicago IL 12345 United States',
'IL 12345 United States',
'12345 United States',
'United States',
'States' ]

My code works but I wanted to get rid of the second param, and maybe make the code shorter and look more beautiful.

Here is what I currently have:

const stringToArray = (str, arr) => {
  const result = arr || [];
  const wordArray = str.split(' ');
  const len = wordArray.length;
  result.push(str);

  if (len === 1) {
    return arr;
  }

  return stringToArray(wordArray.slice((-1 * len) + 1).join(' '), result);
};

const partsArray = stringToArray('Chicago IL 12345 United States');

console.log(partsArray);

If you don't need using recursion, this is an alternative where you can get rid of the second param of the function.

const stringToArray = (str) => {
  const result = [];
  let wordArray = str.split(' ');

  while(wordArray.length > 0) {
    result.push(wordArray.join(' '));
    wordArray = wordArray.slice(1);
  }

  return result;
};

const partsArray = stringToArray('Chicago IL 12345 United States');

console.log(partsArray);


Reviewing password hashing functions I'm currently reviewing some standard pieces of code I use a lot in projects.

Currently I'm using the following functions for password hashing.

function generate_salt($length = 20){
  $chars =  'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.
            '0123456789``-=~!@#$%^&*()_+,./<>?;:[]{}\|';

  $str = '';
  $max = strlen($chars) - 1;

  for ($i=0; $i < $length; $i++)
    $str .= $chars[rand(0, $max)];

  return $str;
}

function hash_password($password, $salt, $iter=5) {
  $hash = sha1(sha1($password.$salt).sha1(strrev($password).strrev($salt)));

  for($i=0;$i<=$iter;++$i) {
     $hash = sha1(sha1($hash).sha1(strrev($hash)));
  }

  return $hash;
}

I will replace sha1() with hash('sha512', ).

Any other suggestions to make this more secure / to improve it?

What is the motivation behind hashing and reversing the string multiple times? If you have a secure hash function, then hashing a single time (combined with a sufficient amount of salt data) is perfectly sufficient. If you have an insecure hash function, then hashing multiple times is extraordinarily unlikely to be enough to make it secure.

The only slight security issue I can see in the code you've posted is the possibility that the random number generator will not be properly seeded, or is not a sufficiently secure random number generator. This is extremely unlikely to be a problem, however, since the purpose of salting is not typically undermined by having an insecure random number generator. Provided hashes get salt values that are reasonably well-distributed it won't help an attacker. If your attacker can interfere with the timing of password creation somehow, to ensure that the majority of users ended up with exactly the same salt, then this would render a dictionary attack easier at a later date, provided they could obtain the hashed passwords. In reality, any user who has this level of control over your system has probably got lots of other ways to obtain the passwords.

Which is of course the real point. Don't spend a lot of time trying to make your hash function cleverer or more secure, just make sure that it does its job. Spend the rest of your time looking over the rest of the system for any chinks in the armour. The system is only as strong as the weakest link in the chain, and that's unlikely to be the hash function. For example, maybe you store the unhashed function in the PHP session, and your server is misconfigured so that the session data is readable by other users on the same box. Maybe you forgot to configure HTTPS so the site is vulnerable to packet sniffers. Maybe your box got rooted and the attacker changed your PHP, so even though the code in your repository is flawless, all your users are compromised.


Reducing memory footprint in anagram-finding program for text public static bool IsAnagramOf(this string word1, string word2)
{
    return word1.OrderBy(x => x).SequenceEqual(word2.OrderBy(x => x));
}

public static void Main()
  {
    Console.SetIn(new StreamReader(Console.OpenStandardInput(8192)));
    string test = Console.ReadLine();
    string[] split = test.Split(new Char[] { ',', '.', ' ' },
                         StringSplitOptions.RemoveEmptyEntries);
    for (int i = 0; i < split.Length; i++)
    {
        foreach (string s in split)
        {
            if (split[i] != s)
                if (split[i].IsAnagramOf(s))
                {
                    Console.WriteLine(s);

                }
        }

    }
    Console.ReadLine();
}

and just shortening it up Jesse's answer...

private static bool IsAnagramOf(this string word1, string word2)
{
    return word1
        .OrderBy(x => x)
        .SequenceEqual(word2.OrderBy(x => x));
}

static void Main(string[] args)
{
    using (var si = new StreamReader(Console.OpenStandardInput(8192)))
    {
        Console.SetIn(si);
        var split = (Console.ReadLine() ?? "").Split(new[] {',', '.', ' '}, StringSplitOptions.RemoveEmptyEntries);
        split.SelectMany(t => split.Where(s => (t != s) && t.IsAnagramOf(s))).ToList().ForEach(Console.WriteLine);
        Console.ReadLine();
    }
}


Selecting minimal sum of two distinct entries of two dicts with common keys Can this function simplified?
The goal is return one key from each dictionary (both contain the identical keys), so that the sum of the values that belong to the selected keys are minimal (and also the two keys cannot be identical).

a = {1:50, 2:60, 3:30}
b = {1:50, 2:70, 3:40}
def get_double_min(a, b):
        a_sorted = sorted(a, key=a.get)
        a1, a2 = a_sorted[0], a_sorted[1]
        b_sorted = sorted(b, key=b.get)
        b1, b2 = b_sorted[0], b_sorted[1]
        if a1 != b1:
            return a1, b1
        if a1 == b1:
            sum1 = a[a1] + b[b2]
            sum2 = a[a2] + b[b1]
            if sum1 < sum2:
                return a1, b2
            else:
                return a2, b1
        else:
            raise ValueError("error incorrect value")
print get_double_min(a, b)

Simplified: Lines-of-Code

Sorting & Extracting

You are sorting lists of values, storing these in variables, and then extracting only the first entries from these lists.  You can use an array slice to keep only the first two entries from the sorted lists, and extract these:

    a1, a2 = sorted(a, key=a.get)[:2]
    b1, b2 = sorted(b, key=b.get)[:2]

If / Else

You test a1 != b1, and if that is True, you return a value.  If not, you again test these values with a1 == b1, and based that, you return different values, or raise an error.

What are the possibilities for a1 != b1 and a1 == b1?  Can the first and the second conditions ever both be False?  Either they are equal, or they are not equal.  Or something very strange is going on.  Since the values are keys to a dictionary, tests for equality must be possible and consistent, so this raising of an error looks like it can never be reached.

So you are left with an if and and else case.  In the else case, you again have two possibilities, so we can make the whole thing into one if/elif/else statement:

    if a1 != b1:
        return a1, b1
    elif a[a1] + b[b2] < a[a2] + b[b1]:
        return a1, b2
    else:
        return a2, b1

Simplified: Time Complexity

Python's sorting is an \$O(N \log N)\$ time-complexity operation.  This is done twice, once for the a dictionary and once for the b dictionary, but that doesn't change the complexity.

After sorting, the two smallest entries are retrieved.  You are taking a \$O(N \log N)\$ time complexity hit to extract the smallest and the second smallest entries.

Finding the minimum is a \$O(N)\$ operation:

    a1 = min(a, key=a.get)
    b1 = min(b, key=b.get)

Finding the second smallest can also be done in \$O(N)\$ time:

    a2 = min((k for k in a if k != a1), key=a.get)
    b2 = min((k for k in b if k != b1), key=b.get)

The above is doing two \$O(N)\$ passes over each list.  You can also find the lowest two values in a list using only a single pass by iterating over the list and maintaining the smallest and second smallest values (and their keys).  Implementation left to student.

Finally, you can use the Python heapq.nsmallest function.

  a1, a2 = heapq.nsmallest(2, a, key=a.get)
  b1, b2 = heapq.nsmallest(2, b, key=b.get)


Codewars "Find the Parity Outlier" code I completed this Codewars exercise. Here are the instructions:

  You are given an array (which will have a length of at least 3, but
  could be very large) containing integers. The integers in the array
  are either entirely odd or entirely even except for a single integer
  N. Write a method that takes the array as an argument and returns N.

  For example:

  [2, 4, 0, 100, 4, 11, 2602, 36]

  Should return: 11

  [160, 3, 1719, 19, 11, 13, -21]

  Should return: 160

Any comments on the following code appreciated. (I used Python 2.7)

def ifeven(list):
     #Determine if we are dealing with list of evens or odds
    sum = 0
    for ran in (0,1,2):
        sum += abs(list[ran])%2
    avg = float(sum)/3
    r_avg = round(avg)
    return r_avg == 0

def find_outlier(integers):
    even =  ifeven(integers)
    new = []
    for num in integers:
        new.append(num%2)
    if even:
        loc = new.index(1)
    else:
        loc = new.index(0)
    return integers[loc]

The code in the post, and the code in the answers by Joe Wallis and 200_success, traverses the whole of the input to collect the parities of all the items. But it is easy to return the result as soon as the outlier has been identified, avoiding a wasted traversal of the remainder of the input.

def outlier(it):
    """Given an iterable with at least 3 items, all of which have the
    same parity except for a single outlier, return the outlier.

    """
    count, item = [0, 0], [None, None]
    for n in it:
        parity = n % 2
        if count[parity] == 0 and count[1 - parity] >= 2:
            return n
        elif count[1 - parity] == 1 and count[parity] >= 1:
            return item[1 - parity]
        count[parity] += 1
        item[parity] = n
    else:
        raise ValueError("bad iterable")


Extracting a conversation from a Skype sqlite database I've made this code to extract a conversation from a Skype database file with a certain user ID, all this being specified as a command line argument.

Since Skype uses SQLite to store the messages I can use the sqlite3 Python module to retrieve the messages.

The code first checks for the database file, opens it if it exists, parses it and finally outputs the chat either to stdout or a specified output file (it uses the partner's ID by default if nothing is provided). The output looks somewhat like what you would expect from an IRC conversation.

I'm quite satisfied with the script in general however  I had several issues with unicode characters which made me have to use some "cheats". I'm not satisfied with all these unicode() conversions, and the fact I have to specify once more at the end via encode('utf-8') that I am indeed going to output other things than ASCII. I also think this code could be made more elegant, especially with the SQL query. If I ever want to add more options, such as sorting, I feel like putting everything in the SQL query looks ugly.

#!/usr/bin/env python2
# charset=utf-8

from __future__ import print_function

import sys
import sqlite3
import os.path
import datetime
import HTMLParser

def eprint(*args, **kwargs):
    print(*args, file=sys.stderr, **kwargs)

def eprint_use():
    eprint("usage : " + sys.argv[0] + " <file.db> <partner's skype ID> [output file]")

# actual code here
# first of all check argv and print the help message if it's wrong

if not len(sys.argv) in [3, 4]:
    eprint_use()

else:
    database_path = sys.argv[1]
    partner_id = sys.argv[2]
    output_path = sys.argv[3] if len(sys.argv) == 4 else partner_id + '.txt'

    if not os.path.isfile(database_path):
        sys.exit('the file %s does not exist' % (database_path))

    output_file = sys.stdout if output_path == '-' else open(output_path, 'w')

    connection = sqlite3.connect(database_path)
    cursor = connection.cursor()

    parser = HTMLParser.HTMLParser()

    cursor.execute("""
    SELECT timestamp,from_dispname,body_xml
    FROM Messages
    WHERE dialog_partner='""" + partner_id + """'
    ORDER BY timestamp
    """)

    for row in cursor.fetchall():
        timestamp = unicode(datetime.datetime.utcfromtimestamp(int(row[0])).strftime('%Y-%m-%d %H:%M:%S'))
        name_tag = unicode(row[1])
        message_body = unicode(parser.unescape(unicode(row[2])))

        output = "[%s] <%s> %s\n" % (timestamp, name_tag, message_body)

        output_file.write(output.encode('utf-8'))

Please keep in mind that I've barely been actively programming in Python for about a year and a half. I try to make my code as pythonic as possible, but as primarily being a C programmer I tend to neglect some of the aspects of the python language in favour of "C-tricks". If you see any such thing, please tell me as well.

First off, you should be using argparse for any argument parsing more complicated than python script.py arg1. It has automatic parsing of sys.argv, allow default values, custom help messages, custom argument types, prints a help message if any arguments mismatch and exits, ...

import argparse
import os.path
import sys

def is_file(f):
    if os.path.isfile(f):
        return f
    raise OSError("{} does not exist".format(f))

parser = argparse.ArgumentParser(descr="Skype history reader")
parser.add_argument('db_path', type=is_file, help="Database path")
parser.add_argument('partner_id', help="Partner to show history of")
parser.add_argument('output_path', help="Location to save output to", default="-")
args = parser.parse_args()

args.output_path = args.output_path or "{.partner_id}.txt".format(args)
output = sys.stdout if args.output == "-" else open(args.output_path, "w")

For your SQL, you should be using Prepared Statements (or the Python implementation of it)

cursor.execute("""
    SELECT timestamp, from_dispname, body_xml
    FROM Messages
    WHERE dialog_partner = ?
    ORDER BY timestamp
    """, partner_id)

This needs paramstyle='qmark'. Otherwise use %s instead of ?. It ensures that partner_id is correctly escaped, so you can't do SQL injection with something like

partner_id = "'; DROP TABLE Messages; SELECT * FROM USERS '"

(Not sure this exact string would work, but something similar to it would be able to delete your whole database. Or print all your chat partners. Or add swearwords to all your messages.)

You should always close your files, otherwise you could get file corruption. Normally I would advise using with open(file_name, "w") as output:, but here we need to also use sys.stdout. Therefore you need to add an explicit output_file.close() at the end, ideally by wrapping your code in a try...finally to ensure it is also closed if some code in between raises an exception.

Likewise, you should close your connection to the db at the end:
connection.close().


Populate database of web articles What I have here is a relatively simple endpoint for a small site I'm making. Idea is to take:

title
content
tags

and create an entry in the database. It works properly.
I threw this together as something that should work and tried to make it clean (like with the error list that gets returned) but clearly I'm doing this all by hand. Are there best practices for writing these API-style endpoints that I'm not following?
I looked under the hood at a few sites (such as SO) and noticed they are using JSON as encoding for the response. That's why I used it too.
On the input validation front, is my system decently robust or is it too flimsy?
I also tried to make the code safe by catching any exceptions that might pop up. If there's something I've overlooked please let me know.
@main.route('/createpost', methods=['POST'])
@login_required
def createpost():
resp = {
    'success': False
}

err = []

u = current_user.id  # 2458017363
title = request.values.get('title')
_tags = request.values.get('tags')  # JSON btw
content = request.values.get('content')
# _attachments = request.files.getlist('file')
# attachments = []

# for f in _attachments:
#     if f.filename.rsplit('.', 1)[1].lower() not in ALLOWED_EXTENSIONS:
#         filepath = os.path.join(UPLOAD_DIR, secure_filename(f.filename))
#         f.save(filepath)
#         attachments.append(filepath)
#     else:
#         err.append('File ' + f.filename + "is not permitted!")

if not title or len(title) > 100:
    err.append('Your title must exist and be less than 100 characters.')

try:
    tags = json.loads(_tags)
    if not tags or len(tags) > 3:
        err.append('Choose between 1-3 tags so people know what your post is about!')
except Exception:
    err.append('Choose between 1-3 tags so people know what your post is about!')

if not content or len(content) < 50:
    err.append('Your content must be at least 50 characters.')

if err:
    resp['error'] = err
    print('err')
    return Response(json.dumps(resp), mimetype='text/json')

# PROVIDED EVERYTHING IS CORRECT

while True:
    try:
        dbentry = Post(id=snowflake(),
                       author_id=u,
                       title=bleach.clean(str(title)),
                       tags=bleach.clean(str(_tags)),
                       content=bleach.clean(str(content)).encode(),
                       )

        db.session.add(dbentry)
        db.session.commit()
    except IntegrityError:
        continue
    break

resp['success'] = True
return Response(json.dumps(resp), mimetype='text/json')

imports are as follows:
# main.py
import json
import os

import bleach
from sqlalchemy.exc import IntegrityError

from .models import Post # sqlalchemy model for posts
from flask import Blueprint, render_template, request, Response
from flask_login import login_required, current_user
from werkzeug.utils import secure_filename

from . import db
from .utils import snowflake  # random number generator
# (hence why i have a while loop around the db entry creation since there is a
# miniscule chance it will give the same number again)

Some quicky remarks:

a well-behaved API should return specific HTTP codes depending on the outcome, that is:
200 for success, or 201 for resource created. 204 is a possibility for an empty but successful response too but I would not advise using the full panoply available. Just be aware of what codes exist and when to use them.
likewise, use 401/403 for permission issues or authentication errors but here you have the @login_required that should take care of that
accordingly, an error should return a meaningful status code to the client - 400 would be a good candidate for an invalid request
the bottom line, always return an appropriate status code, never return HTTP/200 if the request failed. API calls are routinely automated, and the client will rely on the status code returned by the server to determine if the call was successful or not.
useless variable: u = current_user.id  # 2458017363. You could just write: author_id=current_user.id, instead of author_id=u. u is not an intuitive variable name anyway
I don't understand the logic of generating a random ID in your code, the database backend should generate an incremented record ID for you (simply update your data model). I don't see why you need a random value here...
When you decide to handle certain exceptions like except IntegrityError, you can indeed decide to ignore them or hide them to the client but you should still log them for later review. IntegrityError suggests there is something wrong with your handling of incoming data. It should not happen if data is inspected and sanitized properly.
except Exception is too broad when all you're doing is json.loads. The error that you can expect here should be ValueError. Try submitting empty JSON and malformed JSON to verify.
to sum I don't think you should have resp['error'] and resp['success'], just use the same name in all cases eg: 'response'. It is the status code that will make the difference between success and failure. Whatever you do, the API should respond in a way that is consistent and predictable.


Java Apache Commons Net SMTP Wrapper Attachment Can the below code be improved? Are there any major issues with it?
Thanks

Writer w = client.sendMessageData();
for (File file : myAttachments) {
    w.append("\r\n").append("--").append(bound).append("\r\n");
    w.append("Content-Type: application/octet-stream\r\n");
    w.append("Content-Transfer-Encoding: base64\r\n");
    w.append("Content-Disposition: attachment; filename=\"" + Tools.getNameForAttach(file.getName()) + "\"\r\n\r\n");
    FileInputStream fileInputStream = new FileInputStream(file);
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();

    int nRead;
    byte[] data = new byte[1024];

    while ((nRead = fileInputStream.read(data, 0, data.length)) != -1) {
        buffer.write(data, 0, nRead);
    }

    buffer.flush();

    fileInputStream.close();

    w.append(Base64.encodeBase64String(buffer.toByteArray()));
    w.append("\r\n");

}
w.close();

SRP - single responsibility principle

The code is violating the SRP, as it does to many things.

It is

adding/composing headers for the attachments
reading files from disc

I would extract the composition of the headers to a separate method.

private String getHeaders() {
    StringBuilder sb = new StringBuilder();

    sb.append("\r\n").append("--").append(bound).append("\r\n");
    sb.append("Content-Type: application/octet-stream\r\n");
    sb.append("Content-Transfer-Encoding: base64\r\n");
    sb.append("Content-Disposition: attachment; filename=\"");

    return sb.toString();
}

and would assign the result before the for loop to a String variable.

Next we extract the file reading to a separate method. I don't know if Android supports Try with resources so I don't use it here. We also rename the int nRead to bytesRead.

private byte[] readFile(File file) throws FileNotFoundException, IOException {
    FileInputStream fileInputStream = new FileInputStream(file);
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    int bytesRead;
    byte[] data = new byte[1024];

    while ((bytesRead= fileInputStream.read(data, 0, data.length)) != -1) {
        buffer.write(data, 0, bytesRead);
    }

    buffer.flush();
    fileInputStream.close();

    return buffer.toByteArray();
}

next, we add a method which takes a file and returns the content as base64 encoded string

private String getContentAsBase64(File file) throws FileNotFoundException, IOException {

    byte[] fileContent = readFile(file);

    return Base64.encodeBase64String(fileContent);
}

After using the fluent append() method instead of the string adding using +, this leads to the former code beeing refactored to

Writer w = client.sendMessageData();
String attachmentHeader = getAttachmentHeader();
for (File file : myAttachments) {
    w.append(attachmentHeader);
    w.append(Tools.getNameForAttach(file.getName()));
    w.append("\"\r\n\r\n");
    w.append(getContentAsBase64(file));
    w.append("\r\n");
}
w.close();


Find majority element in an array given constant external space Given constant external space (yes no HashMap), how would you improve the following code (code-wise or complexity-wise with stress on the latter) to find the majority element in an array?

/**
 * Created by mona on 5/27/16.
 */

import java.util.Arrays;

public class FinaMajority {
    public static int findMajority(int[] a) {
        Arrays.sort(a);
        int maxCount = Integer.MIN_VALUE;
        int maxIdx = Integer.MIN_VALUE;
        for (int i=0; i<a.length; i++) {
            int count = 0;
            while ( (i+count) < a.length && a[i] == a[i+count]) {
                count++;
                if (count == a.length/2) {
                    return a[i];
                }
                if (count > maxCount) {
                    maxCount = count;
                    maxIdx = i;
                }
            }
        }
        return a[maxIdx];
    }

    public static void main(String[] args) {
        int[] a = {3,1,2,2,3,2,2,4,4,3,5,2,3,1,3,4,3,3,3};
        System.out.println(findMajority(a));
    }

}

What is a "majority element" ?

It would be good to define this, as there could be multiple interpretations:

It could be the element that occurs more than any other in the array. This seems the most natural, intuitive interpretation
It could be the element that occurs more than n / 2 times, as in this online challenge. I think they made a mistake, the common name for this is leader element instead of "majority".

Off-by-one error

The program gives incorrect result for the input [3, 2, 3].
The culprit is here:

int count = 0;
while ( (i+count) < a.length && a[i] == a[i+count]) {
    count++;
    if (count == a.length/2) {
        return a[i];
    }

The sorted array contains [2, 3, 3].
At i=0, since (i+0) < a.length and a[i] == a[i+0],
count is incremented to 1 on the next line,
and since a.length/2 is 1, the method prematurely returns 2.

The fix is to move count++ to the end of the while loop.

Notice that starting from count = 0 is pointless.
It would be better to start from count = 1.

Index out of bounds for singleton array

The program will crash for the input [1].
In this case maxIdx will never change,
its value remains at Integer.MIN_VALUE,
and so it will crash on the line return a[maxIdx].

Slowness

The program is too slow for large arrays, because after counting the consecutive numbers,
it does not skip those,
and continues checking from the next value of i.
Due to this, the time complexity of the loop degenerates to \$O(n^2)\$.

You can improve by adding to i the number of elements that can be skipped.

int count = 1;
while ((i + count) < a.length && a[i] == a[i + count]) {
    if (count == a.length / 2) {
        return a[i];
    }
    if (count > maxCount) {
        maxCount = count;
        maxIdx = i;
    }
    count++;
}
i += count - 1;

Alternative implementation

If you're really looking for the majority element and not the leader element, then your implementation can be written slightly simpler without a nested loop:

public int findMajority(int[] nums) {
    Arrays.sort(nums);

    int maxCount = 0;
    int maxIndex = 0;

    int count = 1;

    for (int i = 1; i < nums.length; i++) {
        if (nums[i - 1] == nums[i]) {
            count++;
            if (count > maxCount) {
                maxIndex = i;
                maxCount = count;
            }
        } else {
            count = 1;
        }
    }
    return nums[maxIndex];
}

Finding the leader element

If you're actually looking for the leader element,
the element that occurs more than n / 2 times,
then an \$O(n)\$ solution is possible:

track a candidate and its count
increment the count when the same candidate is seen
decrement the count when a different value is seen
replace the candidate when the count is 0

Like this:

public int majorityElement(int[] nums) {
    int candidate = 0;
    int count = 0;
    for (int num : nums) {
        if (count == 0) {
            count = 1;
            candidate = num;
        } else if (candidate == num) {
            count++;
            // as a further optimization, you can add a condition here to return early if the required count is reached
        } else {
            count--;
        }
    }
    return candidate;
}

This works when the leader element is guaranteed to exist.
If it's not guaranteed to exist,
then you need another \$O(n)\$ pass to verify the count of the candidate is indeed greater than half of the number of all elements.


Adding action id to a history repository In my system I have a history repository.
My history class is big and with a lot of information regarding operations.
My warehouse needs, for some actions to know which histories are caused by the same action.

My first idea was to create an overloaded version of each method requiring to write histories and make all the clients using that services create and supply a guid if they want to specify an action.

As my system has a lot of services that some use other services and a lot of clients that may need to specify an action that solution sounds bad. Complicated, error prone and would pollute code that is not interested in knowing anything about this.

My solution:
I created a ActionIdContext class that my clients can use to specify a group action and then my HistoryBuilder uses a static property to get the current ActionId if any. This way no services or overloads have to be created or changed.

Do you like this design or maybe you have another idea?

public class ActionIdContext : IDisposable
{
    private static Guid? actionId;
    private readonly bool isActionIdSet;

    public ActionIdContext()
    {
        if (actionId == null)
        {
            actionId = Guid.NewGuid();
            isActionIdSet = true;
        }
    }

    public static Guid? ActionId
    {
        get { return actionId; }
        set { actionId = value; }
    }

    public void Dispose()
    {
        if (isActionIdSet)
        {
            actionId = null;
        }
    }
}

public class HistoryBuilder
{
    private string text;

    public HistoryBuilder SetText(string value)
    {
        this.text = value;
        return this;
    }

    public History Build()
    {
        return new History()
        {
            Text = text,
            ActionId = ActionIdContext.ActionId
        };
    }
}

public class Client
{
    private readonly ISomeService someService;

    public Client(ISomeService someService)
    {
        this.someService = someService;
    }

    public void DoSomeAction()
    {
        someService.DoSomething("Flying in the sky");
    }

    public void DoSomeGroupAction()
    {
        using (new ActionIdContext())
        {
            someService.DoSomething("Driving in the corner");
            someService.DoSomething("Reading Hulk!");
            someService.DoSomething("Doing math");
        }
    }
}

The problem is that the action id is static so it will be shared with all instances of the ActionIdContext class. That means that 2 separate pieces of work excuting at the same time could log everything with the same action id.

var client1 = new Client(someService);
var client2 = new Client(someService);
var client3 = new Client(someService);

Task.Run(() => client1.DoSomeGroupAction());
Task.Run(() => client2.DoSomeGroupAction());
Task.Run(() => client3.DoSomeGroupAction());

You have no idea how this code will log the actions - it could log them all with the same action id, it could log some with no action id and some with a common action id. It could also log some with one action id and others with another.

The point I'm trying to make is, although a nice idea in theory, you can't locally instantiate state then share it via a static property and expect it to work.

Can't you add a LogHistories(Guid actionId, param History[] histories) method or something?

You should implement the full IDisposable.Dispose pattern;

public static Guid? ActionId
{
    get { return actionId; }
    set { actionId = value; }
}

would be better as an auto property.

HistoryBuilder is a bit weird - Builders are generally used with immutables or objects with very complex constructors (in my experience).


Angular directive to disable a button when clicked, allowing re-enabling as needed I have written an Angular Directive that disables a button after it has been clicked, to prevent double posting / saving of data. This works fine in most of our use cases. However, in some situation we want to re-enable the button. For example: the button-click triggers a form submit, but the server-side validation fails. We want to allow the user to submit again, so we need to re-enable the button.

My solution uses an EventEmitter that is owned by the 'host' Component. This EventEmitter is passed on to the button's Directive. This Directive then subscribes to it. Whenever the host wants to instruct the button to re-enable, is emits an event. The Directive will take care of enabling the button.

As an alternative, one could use the disabled property of the button to control its state. However, I would like to reserve that property for other logic that is part of the host Component (e.g. are all required fields correctly filled, etc.). I would like to keep the code for the double posting safeguard contained to the Directive as much as possible.

I'd like to learn if there might be a cleaner way to accomplish what I'm after. Here's what I do now:

The button as used in the host Component template

<button [appDisableAfterClick]="reenableButton"
        (click)="doStuff()">My button</button>

Inside the host Component

private reenableButton = new EventEmitter<boolean>();

doStuff() {
  // Make some external call.
  // In case of an error, re-enable the button:

  this.reenableButton.emit();
}

The DisableAfterClick Directive

Several null checks and unsubscribe calls omitted for brevity.

@Directive({
  selector: '[appDisableAfterClick]'
})
export class DisableAfterClickDirective implements OnChanges, OnDestroy {
  @Input('appDisableAfterClick') reenableButton: EventEmitter<boolean>;

  ngOnChanges(changes: SimpleChanges) {
    this.reenableButton = changes.reenableButton.currentValue;

    this.reenableButton.subscribe(_ => {
      (<HTMLButtonElement>this.el.nativeElement).disabled = false;
    });
  }

  @HostListener('click')
  onClick() {
    (<HTMLButtonElement>this.el.nativeElement).disabled = true;
  }
}

One of the main ways in which you can improve this is by using Renderer2 in the directive instead of directly accessing this.el.nativeElement and making changes to it. This might work in most of the cases. But remember, the Angular code might run at other places as well(like in case of Service Workers and in case of Server Side Rendering). In these cases, you might not have direct access to the this.el.nativeElement.

So it's always recommended to use Renderer2 instead. Once you start using the renderer, your directive logic would significantly reduce. Here's how:

import { Directive, OnDestroy, Input, EventEmitter, HostListener, Renderer2, ElementRef } from '@angular/core';
import { Subscription } from 'rxjs';

@Directive({
  selector: '[appDisableAfterClick]'
})
export class DisableAfterClickDirective {

  @Input('appDisableAfterClick') reenableButton: EventEmitter<boolean>;
  subscription: Subscription;

  constructor(
    private renderer: Renderer2,
    private el: ElementRef
  ) {}

  @HostListener('click')
  onClick() {
    this.renderer.setAttribute(this.el.nativeElement, 'disabled', 'true');
  }

  ngOnInit() {
    this.subscription = this.reenableButton.subscribe(value => {
      if(!value)  this.renderer.removeAttribute(this.el.nativeElement, 'disabled');
    });
  }

  ngOnDestroy() {
    this.subscription && this.subscription.unsubscribe();
  }

}

Another thing would be to not have this directive itself in the first place unless you are going to reuse it in several other places in your App.

I've created this StackBlitz for your reference. Just in case.


Lightweight shorthand JS library Long story short: I wanted some of the time-saving functionality of jQuery without the bulk of the entire library. So, I wrote a lightweight shorthand library inspired by jQuery I'm calling Mozart JS, and I'd like to see how I can further enhance it without major impact on load times.

Thoughts? Full library on GitHub.

Mozart JS

Element Retrieval

Fairly straightforward.

function $get(e, t) {
    if (void 0 === t) t = document;
    if (e.startsWith('#')) return t.getElementById(e.substring(1));
    if (e.startsWith('.')) return t.getElementsByClassName(e.substring(1));
    if (e.startsWith('-')) return t.getElementsByName(e.substring(1));
    return t.getElementsByTagName(e);
}

Example:

var foo = $get('#bar'); //returns element with the Id of "bar"
var zed = $get('.cop'); //returns collection with the classname "cop"

Element Creation

Slightly more complicated; allows the assignment of common properties and all attributes.

function $make(t, p) {
    var o = document.createElement(t);
    if (p.style) o.style.cssText = p.style;
    if (p.class) o.className = p.class;
    if (p.text) o.textContent = p.text;
    if (p.value) o.value = p.value;
    Object.keys(p).forEach((e) => {
        if(e.startsWith("@")) {
            o.setAttribute(e.substring(1), p[e]);
        }
    });
    return o;
}

Example:

var h = $make('a', {
    'class': 'myClass',
    'text': 'Google',
    '@id': 'googleLink',
    '@href': 'https://google.com',
    '@target': '_blank'
});

//Equivalent to:

var h = document.createElement('a');
h.className = 'myClass';
h.textContent = 'Google';
h.setAttribute('id','googleLink');
h.setAttribute('href', 'https://google.com');
h.setAttribute('target', '_blank');

Element Sibling Insertion

Designed to mimic most of jQuery's insertBefore() method. Equivalent function exists for insertAfter(); omitted here in order to save space.

function $addBefore(e, t) {
    if (typeof t === 'string' || t instanceof String) {
        if (t.startsWith('#')) {
            $get(t).parentNode.insertBefore(e, $get(t));
        } else {
            var arr = $get(t);
            for (var i in arr) {
                var f = e.cloneNode(true);
                arr[i].parentNode.insertBefore(f, arr[i]);
            }
        }
    } else {
        t.parentNode.insertBefore(e, t);
    }
}

Example:

var foo = $make('div', {'text': 'This is a test'});
$addBefore(foo, '.myClass'); //adds an instance of foo before each myClass

Element Removal

Removes an element. Still uses basic jQuery syntax.

function $remove(e) {
    if (typeof e === 'string' || e instanceof String) {
        $remove($get(e));
    } else if (e.nodeType === 1 || e.nodeType === 3) {
        e.parentNode.removeChild(e);
    } else {
        for (var i in e) {
            e[i].parentNode.removeChild(e[i]);
        }
    }
}

Example:

$remove('#myId');
$remove('.myClass');

//Equivalent to:

var rem = document.getElementById('myId');
rem.parentNode.remove(rem);
for (var i in document.getElementsByClassName(myClass)) {
    var elm = document.getElementsByClassName(myClass)[i];
    elm.parentNode.remove(elm);
}

I wanted some of the time-saving functionality of jQuery without the bulk of the entire library.

If you don't look back at older browsers, use version 2.x of jQuery. It's smaller than the 1.x as it has less cross-browser compatibility code (See How 2.0 Changed section). You can also custom-build jQuery to your own spec to include what you need. An even smaller yet jQuery-compatible library is Zepto, just ~9k compressed.

  Element Retrieval

Pretty straightforward. However, there is querySelectorAll which pretty much acts like jQuery's $. A singular version of it is querySelector. It's native, and has been there for quite a while.

One neat thing about jQuery and jQuery-like libraries is that they encapsulate results, single or multiple, into a set. Methods operate by looping through and applying to each item in the set. No items, no loop, thus no throw.

$('#foo').children().eq().next().remove();

The following example will not throw an error even when there's no #foo in the page.

  Element Creation

var h = $make('a', {
    'class': 'myClass',
    'text': 'Google',
    '@id': 'googleLink',
    '@href': 'https://google.com',
    '@target': '_blank'
});

Not entirely sure what's the difference between class and the other attributes when it's also an attribute. What should be different is text since it doesn't actually describe the element. Also, text nodes can be created separately via createTextNode.

  Element Sibling Insertion

if (t.startsWith('#')) {
  $get(t).parentNode.insertBefore(e, $get(t));
} else {
  var arr = $get(t);
  for (var i in arr) {
    var f = e.cloneNode(true);
    arr[i].parentNode.insertBefore(f, arr[i]);
  }
}

This is one case where your code will start to become unmaintainable. This function is making a special case for singular results. If you go with the set-like behavior of jQuery, singular results are still a set. Your code will always assume a set and be more consistent in operation.

  Element Removal

function $remove(e) {
    if (typeof e === 'string' || e instanceof String) {
        $remove($get(e));
    } else if (e.nodeType === 1 || e.nodeType === 3) {
        e.parentNode.removeChild(e);
    } else {
        for (var i in e) {
            e[i].parentNode.removeChild(e[i]);
        }
    }
}

Again, your code is doing special cases for different things. This could have been easier if you operated with a set of things.

function $remove(input){

  // Building the set
  var set = inputIsAString ? lookForElements(input)
          : inputIsAnElement ? createASet(input)
          : inputIsAlreadyASet ? input
          : [];

  // The actual operation
  set.forEach(function(){
    // element removal code
  });
}


Simple way to show popup After some research I found the following information: In this closed question I found a solution which does not work well when pop-up has height bigger than screen (and some jquery solution). Here is a question about showing outside page in popup. And here are some theoretical and angularJS solutions. However, those answers do not satisfy me.
I want to show a pop-up to user which contains my content (not loaded from URL) e.g. an editor. I am interested in only pure JS/HTML/CSS solutions (no jQuery or other libs). This is the code which I regularly use, and which was tested on Chrome, Safari, Firefox and Edge:

toggle = q => document.querySelector(q).classList.toggle('hide');
body { margin: 0; padding: 0; }
.btn { padding: 10px; background: #BADA55; border-radius: 5px; cursor: pointer}

.popupBg {
  position: absolute;
  top: 0;
  left: 0;
  display: flex;
  min-height: 100vh;
  width: 100vw;
  justify-content: center;
  align-items:center;
  background: rgba(255,0,0,0.5)
}

.popup {
  width: 100px;
  min-height: 200px;
  border: 1px solid black;
  background: #88f;
  margin: 40px;
}

.hide {
  display: none;
}

Some content

PopUP

      My popup

Here is a JSfiddle version.
Question1: Is there simpler way to show popup (similar to this in snipped and easy to modify) to user?
Question2: Does approach have any drawbacks?

General notes:

I will focus mainly on your second question as I cannot imagine simpler solution. I would even suggest to do it a little bit more complex in order to make CSS more scalable (in the terms of resolution and content size).

For instance you can consider using width: auto; for your .popup class in order to make it scale itself depending on internal content.

Another approach would be to set width and height fixed and use overflow:auto; in order to use some scrollbars as internal content grows bigger.

If you would like to make it simpler for the user (if you mean an user of your code) you can wrap it inside some API like:

function showPopup(message) {
      const popupContainerClass = '.popupBg';
      document.querySelector(popupContainerClass).classList.toggle('hide');
      const popupContentClass = '.popup';
      const popupElement = document.querySelector(popupContentClass);
      popupElement.innerHTML = message;
      //... but please be aware of potential Cross Site Request Forgery vulnerability here!
      popupElement.focus();
}

Question2:

Your approach is about hiding an element that in fact is always present in DOM. It usually has advantages because displaying popup will not consume any processing power.

But in some cases (for instance when your popup presence would solely cause complex computations, or require lot of memory -like some videos or animations) it would be considerable to completely remove it from DOM instead.


Fetch an array from API endpoint in async function I've been studying javascript for the love of it, I'm currently learning how to use async functions and my code actually works, but I know there is always room for improving.

I'm open to any help regarding my use of async functions and how I use the return of sizeJokesArray() in fetchJokes().

const jokeContainer = document.querySelector('.joke-container');

async function sizeJokesArray() {
  let url = 'https://api.icndb.com/jokes/count';
  let data = await (await fetch(url)).json();
  return data.value;
}

async function fetchJokes() {
  let url = `https://api.icndb.com/jokes/random/${length}`;
  let jokesData = [];
  let data = await (await fetch(url)).json();
  for (jokePosition in data.value) {
    jokesData.push(data.value[jokePosition].joke);
  }
  return jokesData;
}

sizeJokesArray().then(size => (length = size)); // return of sizeJokesArray

jokeContainer.addEventListener('click', event => {
  if (event.target.value === 'Fetch') {
    fetchJokes(length).then(jokesData => (jokesArray = jokesData)).then(jokesData => (console.log(jokesData)));
  }
});

Fetch some jokes bro!!

        <button type="button" value="Fetch">Fetch Jokes</button>

the existing console.log() it's not actually used in my code just used it here to log my results for the question purpose.

I've improved a few things to your script, making it more consistent over all:

;(function () {
  const jokeContainer = document.querySelector('.joke-container')

  async function fetchCount() {
    const url = 'https://api.icndb.com/jokes/count'
    const { value } = await (await fetch(url)).json()

    return value
  }

  async function fetchJokes(length = fetchCount()) {
    const url = `https://api.icndb.com/jokes/random/${await length}`
    const { value } = await (await fetch(url)).json()

    return value.map(({ joke }) => joke)
  }

  jokeContainer.addEventListener('click', async event => {
    if (event.target.value === 'Fetch') {
      const jokes = await fetchJokes()

      console.log(jokes)
    }
  })
}())

Fetch some jokes bro!!

    <button type="button" value="Fetch">Fetch Jokes</button>

Wrapped your script in an IIFE to avoid polluting the global scope.
Removed your bizarre usage of the global length variable, which you defined without using var, let, or const, and is considered bad practice.
Used object destructuring to improve the readability of your code in some places.
Declared your event listener as async in order to take advantage of await instead of using a then() chain to improve consistency and readability.
Converted your imperative initialization of jokesData into a functional idiomatic approach using Array#map() in order to further improve readability.


MySQL proliferation of subqueries and left joins I have the following query:

 $sql = "SELECT p.id, p.fname, p.mname, p.surname, p.consultant_id,
                e.address,
                ph.number,
                a.street, a.street_more, a.city, a.country,
                co.label as 'nationality',
                msap.label as 'module'
        FROM per_person AS p
        LEFT JOIN (
            SELECT person_id, number
            FROM per_phone
            WHERE is_primary = 1
        ) AS ph ON p.id = ph.person_id
        LEFT JOIN (
            SELECT person_id, address
            FROM per_email
            WHERE is_primary = 1
        ) AS e ON p.id = e.person_id
        LEFT JOIN (
            SELECT person_id, street, street_more, city, country
            FROM per_address
            WHERE is_primary = 1
        ) AS a ON p.id = a.person_id
        LEFT JOIN (
            SELECT person_id, module
            FROM per_sap
        ) AS sap ON p.id = sap.person_id
        LEFT JOIN (
            SELECT id as 'country_id', iso_code, label
            FROM meta_country
        ) AS co ON p.nationality = co.country_id
        LEFT JOIN (
            SELECT id as 'sap_id', short_code, label
            FROM meta_sap
        ) AS msap ON sap.module = msap.sap_id
        WHERE is_deleted IS NULL
        ORDER BY fname ASC
        LIMIT ".$index.", ".$per_page.";";

At the moment it takes about 0.078 sec / 0.000 sec for the query to complete (it is limited to take 10 records for each query call).

How would you recommend me to better structure my query so that the execution time can be shortened. Each of those table have (on average) ~ 2000 rows. And all of them are indexed based on the primary_key (id of the table) and FK of the referenced table.

Quick look at this and you have a lot of sub queries that seem unnecessary and could just be rewritten as normal joins. If the is_primary field is added to the foreign keys then this would enable the individual records to be accessed with an index.

Something like this:-

$sql = "SELECT p.id, p.fname, p.mname, p.surname, p.consultant_id,
                e.address,
                ph.number,
                a.street, a.street_more, a.city, a.country,
                co.label as 'nationality',
                msap.label as 'module'
        FROM per_person AS p
        LEFT JOIN per_phone ph ON p.id = ph.person_id AND ph.is_primary = 1
        LEFT JOIN per_email e ON p.id = e.person_id AND e.is_primary = 1
        LEFT JOIN per_address a ON p.id = a.person_id AND a.is_primary = 1
        LEFT JOIN per_sap sap ON p.id = sap.person_id
        LEFT JOIN meta_country co ON p.nationality = co.country_id
        LEFT JOIN meta_sap msap ON sap.module = msap.sap_id
        WHERE p.is_deleted IS NULL
        ORDER BY p.fname ASC
        LIMIT ".$index.", ".$per_page.";";

Note an index on fname might well help to order the results.


Detecting the end of a method chaining I've been through a lot of posts over the web(and in SO) saying that it is not possible. However, I did the following code:

var a = {
 _sum: 0,
 _timer: null,
 _resetTimer: function() {
  if (this._timer) {
   window.clearTimeout(this._timer);
  }

  this._timer = window.setTimeout(this._endChain.bind(this), 0);
 },
 _endChain: function() {
  console.log(this._sum);
 },

 A: function() {
  this._resetTimer();
  this._sum+= 1;
  return this;
 },
 B: function() {
  this._resetTimer();
  this._sum+= 2;
  return this;
 }
};

a.A().B().B().A();

Demo in JsFiddle

I want to know how problematic this can be, if this is not encouraged to be used.

Edit:

A negative point is: if you need anything that would be processed by _endChain you could not use return, only with a promise or another timeout outside the whole chain. Example.

It's not problematic in the sense that _endChain will always be called after the whole chain. In fact you could simplify the code by only creating the timer once:

var a = {
  _timer: null,
  _resetTimer: function() {
    if (!this._timer)
     this._timer = window.setTimeout(this._endChain.bind(this), 0);
  },

But the problem will come with code that follows for example:

a.A().B().B().A();
DoMoreStuff();

Most developers would be surprised to find that the first call has not completed. I think the better solution would be to implement an end method which is what many libraries do:

let result = a.A().B().B().A().end();
DoMoreStuff();

Or a promise like method:

a.A().B().B().A().then( function(result) {
  DoMoreStuff();
});


Indentation and formatting for chained jQuery methods Below I have some jQuery code that handles footnotes. My question is actually about the formatting and indentation of the code, so I won't bother trying to explain what the code does beyond that.

I'd like to know what patterns of indentation are considered the most maintainable and readable when chaining jQuery function calls of the form: $(foo).foo(bar).foo(function(){ bar; }).foo(function(){ bar; });

Here is my specific code and the formatting/indentation that I've come up with:

$('.footnote[id^="ret_"]')
  .removeAttr('title')
  .removeAttr('alt')
  .mouseenter(function(e) {
    var footnote = $('#footnote_cont_' + this.id.substring(4)).html();

    $footnoteTooltip.stop(true, false);
    //only completely hide and change text/position if we are hovering over a different footnote
    if($footnoteTooltip.html() != footnote)
      $footnoteTooltip.hide().html(footnote).css({ left: e.pageX + 10, top: e.pageY + 15});

    $footnoteTooltip.fadeTo(fadeTime, opacity);
  })
  .mouseleave(function() {
    $footnoteTooltip.delay(fadeTime).fadeOut(fadeTime);
  })
;

Is there a more readable way of indenting this?

My suggestion:

$('.footnote[id^="ret_"]')
   .removeAttr('title')
   .removeAttr('alt')
   .mouseenter(function(e) {
      var footnote = $('#footnote_cont_' + this.id.substring(4)).html();
      $footnoteTooltip.stop(true, false);

      //only completely hide and change text/position if we are hovering over a different footnote
      if($footnoteTooltip.html() != footnote)
         $footnoteTooltip.hide().html(footnote).css({ left: e.pageX + 10, top: e.pageY + 15});

      $footnoteTooltip.fadeTo(fadeTime, opacity);
   }).mouseleave(function() {
      $footnoteTooltip.delay(fadeTime).fadeOut(fadeTime);
   });

Three or four spaces indentation - your preference. My opinion is that two spaces is more difficult to read (although Lisp uses it).
Semicolon on same line as last method call. The only time I approve of having it on it's own line is an empty while.
}).mouseLeave() I put the call on the same line as the end of the block to make it clear that you're calling the method of the object returned.


Functional Implementation of Co-prime pairs in array Program finds the number of pairs of co-primes in an array using
functional concepts in Node.js

const assert = require('assert')

const gcd = (a, b) => (b != 0) ? gcd(b, a % b) : a

const co_prime = (a, b) => gcd(a, b) == 1

const co_prime_pairs = (_list) => {
    co_primes = []
    _list.map(
        (x, i) => _list.slice(i + 1)
                        .filter(y => co_prime(x, y))
                        .forEach(y => co_primes.push([x, y]))
        )
    return co_primes.length
}

const main = () => {
    assert.equal(co_prime_pairs([1, 2, 3]), 3)
    assert.equal(co_prime_pairs([4, 8, 3, 9]), 4)
}

main()

Is the time complexity similar to that of the simple for-loop implementation?

Is there any scope for improving the time-complexity by using map and filter functions?

How is my choice of variable names?

How is code formatting?

How is my choice of variable names?

In general you used snake case for the function names which is more a ruby-style.

Additionally the function co_prime_pairs let me acept that it return pairs of co-primes. However it returns a number of co-pairs inside an array.

The variable co_primes is declared globally.

co_prime_pairs

This function is not a pure function internally because .forEach(y => co_primes.push([x, y])) modifies co_primes.
I rewrite the function and spit the logic into:

build pairs
filter the co primes
return the length

The functions:

const filterCoPrimes = xss =>
    xss.filter(xs => isCoPrime(xs[0], xs[1]))

const buildPair = x => y =>
    [x, y]

const buildPairs = (xs, pairs) =>
    xs.length === 0 || xs.length === 1
        ? pairs
        : buildPairs(
            xs.slice(1),
            pairs.concat(xs.map(buildPair(xs[0])))
        )

The chain:

const co_prime_pairs = xs =>
    filterCoPrimes(buildPairs(xs, [])).length

If we use pipe as a kind of function composition it can be rewritten to:

const co_prime_pairs = pipe(
    buildPairs([]),
    filterCoPrimes,
    length
)

Full working Example

function calls:

const gcd = (a, b) =>
  (b != 0) ? gcd(b, a % b) : a

const isCoPrime = (a, b) =>
  gcd(a, b) === 1

const filterCoPrimes = xss =>
  xss.filter(xs => isCoPrime(xs[0], xs[1]))

const buildPair = x => y =>
  [x, y]

const buildPairs = (xs, pairs) =>
  xs.length === 0 || xs.length === 1
      ? pairs
      : buildPairs(
          xs.slice(1),
          pairs.concat(xs.map(buildPair(xs[0])))
      )

const co_prime_pairs = xs =>
  filterCoPrimes(buildPairs(xs, [])).length

console.log(co_prime_pairs([4, 8, 3, 9]))

with pipe:

const pipe = (...fns) => fns.reduce((f, g) => (...args) => g(f(...args)))

const filter = fn => xs =>
    xs.filter(fn)

const map = fn => xs =>
    xs.map(fn)

const length = xs =>
    xs.length

const gcd = (a, b) =>
    (b != 0) ? gcd(b, a % b) : a

const isCoPrime = (a, b) =>
    gcd(a, b) === 1

const filterCoPrimes = xss =>
    xss.filter(xs => isCoPrime(xs[0], xs[1]))

const buildPair = x => y =>
    [x, y]

const buildPairs = pairs => xs =>
    xs.length === 0 || xs.length === 1
        ? pairs
        : buildPairs
            ( pairs.concat(xs.map(buildPair(xs[0]))) )
            ( xs.slice(1) )

const co_prime_pairs = pipe(
    buildPairs([]),
    filterCoPrimes,
    length
)

console.log(co_prime_pairs ([4, 8, 3, 9]))


Longest palindrome in an array I am new to programming, and think this code could be improved upon.  Any suggestions?

  #include <stdio.h>
  #define size 10
  void main()
  {

    int  i,j,ii,jj,arr[size]={1,2,4,2,1,1,2,1,1,2};
    int count=0, max_count=0, start_index=0, temp_start_index=0;

    for(i=0;i<size;++i)
    {
       for (j=size-1;j>=0;--j)
       {
          for (ii=i,jj=j;;++ii,--jj)
          {
             if (arr[ii]==arr[jj])
             {
                if (count==0)
                {
                   temp_start_index=ii;
                }
                ++count;
                if (ii==jj)    //odd number of elements in palindrome
                {
                    count=count*2-1;
                    break;
                }else{
                       if (ii>jj)   //even number of elements in palindrome
                       {
                          --count;
                          count=count*2;
                          break;
                       }
               }

           }

           else
           {
               count=0;
               break;
           }
       }

       if (count>max_count)
       {
           max_count=count;
           start_index=temp_start_index;
           count=0;
           temp_start_index=0;

       }
   }
 }

  for (i=start_index;i<start_index+max_count;++i)
  {
    printf("%d ",arr[i]);
  }
  printf("\n");
  printf("%d\n",max_count);
 }

Syntax & Styling

Instead of #defineing size to be 10, you should declare a static const.

static const size = 10;

This answer explains nicely as to why.  Good job on having this declared though, it's better than having magic numbers in your code.
You should never declare main() to return void.  There is no good reason to not declare it as int main().  See this answer for more explanation.
You should declare your main with void parameters, as such:

int main(void)

Your main() is doing too much within it.  You should abstract your code into different functions and then call it from within main().
Put the variable declarations to separate lines and initialize them to some value. From Code Complete, 2d Edition, p. 759:

  With statements on their own lines, the code reads from top to bottom,
  instead of top to bottom and left to right. When you’re looking for a
  specific line of code, your eye should be able to follow the left
  margin of the code. It shouldn’t have to dip into each and every line
  just because a single line might contain two statements.

You should declare your for loops as such:

for(int i=0; i < size; ++i)

Note that this was introduced in the C99 standard.  There is no reason you should not be using this standard in your code.

Algorithm

Why do you limit yourself to finding palindromes within an int array?  It's more typical to find palindromes within a string.
Right now the time complexity for your algorithm is \$ O(n^3) \$, which is expensive.  Let's use Manacher's algorithm which can do it in \$ O(n) \$.  Here is a C implementation of the algorithm, but recognize that this has some bad practices within the code and should only be looked at to get an idea for implementing the algorithm yourself.


Select grand child in array knockout I'm trying to select a grand child from an array in an array.

If it was C# I would have wrote something like below

SubSteps.Select(item => item.First(subitem => subitem == 1)).First();

I have code that works, but I'm not sure it is the best way to do it:

ko.utils.arrayFirst(ko.utils.arrayFirst(self.SubSteps(),
        function (item) {
            return ko.utils.arrayFirst(item.SubSteps(),
                function (subItem) { return subItem.InternalName == localStorage.getItem('lastWizardPage'); });
        }).SubSteps(), function (item) {
            return item.InternalName == localStorage.getItem('lastWizardPage');
        })

Is there a method I can use that I've never heard of perhaps?

Interesting question.

First off, your indentation is terrible, your code is far more readable like this:

ko.utils.arrayFirst(ko.utils.arrayFirst(self.SubSteps(),
  function(item) {
    return ko.utils.arrayFirst(item.SubSteps(),
      function(subItem) {
        return subItem.InternalName == localStorage.getItem('lastWizardPage');
      });
  }).SubSteps(), function(item) {
  return item.InternalName == localStorage.getItem('lastWizardPage');
})

Second, you are retrieving your subitem twice, because you loose track of it, simply use a 'local global' and assign your subitem to it.

var needle, found;
ko.utils.arrayFirst(self.SubSteps(),
  function(item) {
    return ko.utils.arrayFirst(item.SubSteps(),
      function(subItem) {
        found = subItem.InternalName == localStorage.getItem('lastWizardPage');
        if(found) {
          needle = subItem;
        }
        return found;
      });
  });

or, if you dont mind some sorcery (don't do this at work!)

var needle, found;
ko.utils.arrayFirst(self.SubSteps(),
  function(item) {
    return ko.utils.arrayFirst(item.SubSteps(),
      function(subItem) {
        found = subItem.InternalName == localStorage.getItem('lastWizardPage');
        return found && (needle = subItem), found;
      });
  });

Furthemore, you should consider caching localStorage.getItem('lastWizardPage') and you should consider implementing old skool loops so that you can exit immediately.


Comparison application I'm making a comparing section, which I've just started typing, trying to get something working. It's working now, but as you can see its pretty messy.  I feel this could be done in one or two less queries, or I should break it apart into smaller methods.

foreach (XMLObject source in Sources)
{
    var matchedElement =
        destList.FirstOrDefault(s.ElementName == source.ElementName);
        // checks to see if it exists in one list but not the other

    if (matchedElement == null) // element is in one list and not the other
    {
        var alter =
            lstAlteration.FirstOrDefault(
                a => a.ElementName == source.ElementName && a.ChangeInfo.ChangeFrom == source.ElementName);
            // check to see if the the element is a Removal (Changed From would not be blank)

        if (alter == null) // Removal has not been triggered
        {
            alter = new Alteration
                        {
                            ElementName = source.ElementName,
                            ChangeInfo = new ChangeDetail( {ChangeTo = source.ElementName}
                        };
        }
        else
        {
            alter.ChangeInfo.ChangeTo = source.ElementName;
        }

        lstAlteration.Add(alter);
    }
}

foreach (var source in Sources.Where(x => !destList.Exists(s => s.ElementName == x.ElementName))
{
    var alter = lstAlteration.FirstOrDefault(a => a.ElementName == source.ElementName
                                 && a.ChangeInfo.ChangeFrom == source.ElementName);

    if (alter == null) {
        alter = new Alteration
                    {
                        ElementName = source.ElementName,
                        ChangeInfo = new ChangeDetail()
                    };

        lstAlteration.Add(alter);
    }

    alter.ChangeInfo.ChangeTo = source.ElementName;
}

Sorter
Only one .ChangeInfo.ChangeTo = source.ElementName; execution


Validate IP address and create a registration attempt I'm a C++/Python developer attempting to learn JavaScript, but I'm struggling to write clean code.  I've read that async.waterfall and Promises are two ways to flatten the code a bit, but my implementation seems far more inflated than what I've grown accustomed to using Python.  Is there anything that I can do to refactor the below code sample to compact it without failing to handle errors?

nodejs Implementation:

Authenticator.prototype.register = function(opts) {
  var self = this;
  return new Promise(function(resolve, reject) {
    self.__validateIpAddress(opts.ip)
    .then(function() {
      self.__createRegisterAttempt(opts)
      .then(function(attempt) {
         // ...
      }, function(err) {
        reject(err);
      }
    }, function(err) {
      reject(err);
    });
  });
};

Python Implementation: (for comparison)

class Authenticator(object):
    # caller must handle exceptions
    def register(self, opts):
        self.__validateIpAddress(opts['ip'])
        attempt = self.__createRegisterAttempt(opts)
        # ...

Creating a new promise when you already have a promise is considered a Promise anti-pattern.  Instead, you can just use the promise that is already available to you.  This then saves you all the reject handlers because if anywhere in the promise chain, there is a rejection that will propagate back.  So, I think you can just do this:

Authenticator.prototype.register = function(opts) {
  var self = this;
  return  self.__validateIpAddress(opts.ip).then(function() {
      self.__createRegisterAttempt(opts).then(function(attempt) {
         // ...
      });
  });
};


Excel VBA optimizing for large data base I am new to coding and need help with a code that won't complete. I suspect it is due to the size of the data set. I tested the code using a reduced data set and it processes fine. However, my actual data set is over 210,000 rows and is expected to grow.
Is there a way to speed this up? Thank you for your assistance

Sub DupValidation()
    Dim wb As Workbook
    Dim ws1 As Worksheet

    Dim i As Long
    Dim lastrow As Long
    Dim lastrow2 As Long

    Set wb = ActiveWorkbook
    Set ws1 = wb.Worksheets("Tickets")

    lastrow = ws1.Cells(Rows.Count, 1).End(xlUp).Row

    ws1.Range("g2:g" & lastrow).ClearContents

    i = 2
    Do While i <= lastrow
        If Application.CountIf(ws1.Range(ws1.Cells(2, 2), ws1.Cells(lastrow, 2)), ws1.Cells(i, 2)) > 1 Then
            ws1.Cells(i, 7).Value = True
        End If
        i = i + 1
    Loop
End Sub

Finding (and removing) duplicates is already a built-in functionality; this code is kind of reinventing the wheel. Making VBA code faster than native functionality, from what I've seen, requires thinking outside the box and manipulating memory locations.

But let's review the code we're looking at.

Sub DupValidation()

Kudos for using a meaningful name! This one reads like a noun though; since Sub procedures typically do something, it's common practice to make their names start with a verb, so ValidateDuplicates would be a better name. The procedure is also implicitly Public; consider always using explicit modifiers.

Next we have a handful of declarations, for each of the variables used in the procedure. Again, kudos for explicitly declaring all variables (is Option Explicit specified?) - but consider declaring them when they're needed, as they're needed. That way it's much harder to accidentally leave unused variables behind, like what happened to lastrow2.

Rule of thumb, if there's a digit at the end of a name, it's usually a bad name. ws1 could be sheet, or ticketsSheet.

But you're not here to hear about variable naming are you.

I'm curious why Range("g2:g" & lastrow) is good enough to get a range encompassing all cells in column G, but once inside the loop we switch to a very long-winded Range(Cells, Cells) call instead of just doing Range("B2:B" & lastrow) like we just did.

Do we really need to COUNTIF to identify a 2nd or 3rd (or 250th) duplicate for one value?

If we had a data structure we could quickly lookup a value from, we could put the known-dupe value in it, and then only perform the expensive COUNTIF when we already know we're not looking at a known duplicate value. Dictionary and its O(1) keyed retrieval sounds like a good tool for this.

So instead of just writing True into column G, we can store the value of column B into our dictionary, and then the loop can now conditionally evaluate the countif when the dictionary doesn't already contain the value in column B.

Actually, with a dictionary you could make the whole loop much more efficient than that.

Start at row 2, end at lastrow: the number of iterations is known before we even start looping - the loop should be a For loop, not Do While. So we loop i from 2 to N, and at each row we try to add the value of column B into the dictionary. If the value already exists in there (that's O(1); CountIf is O(n)), then we know we have a dupe at that row so we write True to column G. After the loop, column G identifies all dupes, and the dictionary contains all the unique values. Iterating a variant array of values in-memory instead of worksheet cells would be even faster. You'll find the Dictionary class in the Scripting library if you want it early-bound.

But then again, I doubt it would be faster than the native highlight duplicates functionality.