texts: Is this the way to use HibernateCompositeUser type for handling localized contents?

texts:
I am trying to use HibernateCompositeUser type to handle i18n specific data in my application. I am trying to use the below approach.

I have a table named master table which contains all locale independent data, while I have created another table master_translation which contains all locale sensitive information. Master table contains a reference to the master_translation.

Here is the detailed table structure:

master
 ---ID
 ---master_translation
 ---Other locale independent fields.

master_translation
 ---ID
 ---language_id
 ---Other locale sensitive fields

Now I am using HibernateCompositeUser type to handle this internal process.  Here is the mapping for master class:

<hibernate-mapping>
    <class name="Master"
        table="MASTER">
        <id name="uuid" type="java.lang.String">
            <column name="UUID" />
            <generator class="uuid" />
        </id>

        <property name="master_i18n" type="masteri18n">
           <column name="NAME"/>
           <column name="SHORTDESCRIPTION"/>
           <column name="LONGDESCRIPTION"/>
    </class>
</hibernate-mapping>

where type="masteri18n" is hibernate CompositeUserType.now.

When I am fetching the master content, it is correctly fetching the data based on the language and my Master class contains a reference to the Master_translation which holds locale specific data.

I am handling this case:

public Object nullSafeGet(ResultSet rs, String[] arg1,
        SessionImplementor arg2, Object arg3) throws HibernateException,
        SQLException {

    Master_i18n master_i18n=Master_i18n.getInstance();
    master_i18n=dao.getMaster_i18n(rs.getString(arg1[0]), "nl_NL");;

    //return Master_i18n.getName();
    return Master_i18n;
}

@Override
public void nullSafeSet(PreparedStatement ps, Object arg1, int index,
            SessionImplementor arg3) throws HibernateException, SQLException {

    if(arg1==null){
        ps.setNull(index, Hibernate.STRING.sqlType());
        //ps.setNull(index+1, Hibernate.STRING.sqlType());
        //ps.setNull(index+2, Hibernate.STRING.sqlType());set
    }
    else{
         Master_i18n des=(Master_i18n)arg1;
         des=dao.saveMaster_i18n(des);
         ps.setString(index, des.getUuid());
         ps.setString(index+1, des.getUuid());
         ps.setString(index+2, des.getUuid());
         ps.setString(index+3, des.getUuid());
    }
}

Somehow I am not feeling confident about my approach.  Am I implementing it correctly or not?


texts: Handle data received by Ajax request and update database (prepared statement)

texts:
I have an Ajax request from a page where the user is being asked to enter their date of birth. The request URL file has the code below and works all good. However, I'll be rewriting all MySQL/MySQLi functions used on the same website and this is generally how I use prepared statements. Should I avoid using die();? Is the code below acceptable and secure at some level?

// If received the birthday of logged in user
if(isset($_REQUEST['new_dob']) && isset($_REQUEST['userId'])) {
  $newdob = $_REQUEST['new_dob'];
  $userid = $_REQUEST['userId'];

  $check_info = "SELECT date_of_birth FROM users WHERE id = ? ";
  $check_mate = $conn -> prepare($check_info);
  if ( false === $check_mate ) {
    die('prepare() failed: ' . htmlspecialchars($conn->error));
  }
  $check_mate -> bind_param("i", $userid);
  $check_exe = $check_mate -> execute();
  if ( false === $check_exe ) {
    //No dob record at all for this userid
    die('execute() failed: ' . htmlspecialchars($conn->error));

  } else {
    $check_mate -> bind_result($date_of_birth);
    $check_mate -> fetch();
    if ($newdob != $date_of_birth) {
        $update_flag = 1;
        $check_mate -> close();
    } else if ($newdob == $date_of_birth || $newdob == '--' || $newdob == '0000-00-00' || $newdob == false || $newdob == NULL) {
        exit;
    }
  }
  if($update_flag == 1) {
    $update_dob = "UPDATE users SET date_of_birth = ? WHERE id = ? ";
    $update_exe = $conn -> prepare($update_dob);
    if ( false === $update_exe ) {
      die('prepare() failed: ' . htmlspecialchars($conn->error));
    }
    $update_exe -> bind_param("si", $newdob, $userid);
    $update_result = $update_exe -> execute();
    if ( false === $update_result ) {
      //No record at all for this userid
      die('execute() failed: ' . htmlspecialchars($conn->error));
    } else {
        $updated = 1;
        $update_exe -> close();
    }
  } else {
    // set dialog as completed
  }
}


texts: Align text (left, center, right) without additional packages

texts:
I wrote this short subroutine to left, center, right-align a multiline string.

How can I make it better (shorter, prettier, optimized)?  Can you offer some suggestions?

#!/usr/bin/env perl
use strict;

# A bit of text
$_ = <<END;
     Lorem ipsum dolor sit amet consectetur adipiscing elit
          Curabitur pretium odio dictum nisl posuere, vitae mollis nibh facilisis
   Curabitur tempus tincidunt ante eget facilisis
     Pellentesque ut accumsan dui, nec semper odio
        Ut libero lacus, fermentum quis ultricies quis, tempus nec augue
                   Mauris tincidunt hendrerit accumsan
END

# Test each alignment case
for my $align ('left', 'center', 'right') {
    print align($_, $align)."\n";
}

# Alignment subroutine
sub align {
    local $_ = shift;
    my ($align) = @_;    # Text to align, Alignment type
    my $re = qr/^(.*)/m;
    s/^[ \t]+|[ \t]+$//gm;   # Remove trailing/leading spaces

    # Get longest line
    my $max = 0;
    length($1) > $max and $max = length($1) while /$re/g;

    if    ($align eq 'left')   { s|$re|$1 . " " x ($max-length($1))|ge }
    elsif ($align eq 'center') { s|$re|" " x (($max-length($1))/2) . $1|ge }
    elsif ($align eq 'right')  { s|$re|" " x ($max-length($1)) . $1|ge }

    return $_;
}


texts: 100DaysofSwiftUI - Project 1 - Challenge 1: Convert temperature units: Celsius, Fahrenheit and Kelvin

texts:
This is my code to solve the challenge in 100 Days of SwiftUI by Paul Hudson. This is the first challenge in the series and I chose to convert the temperature units from C° -> F°, F° -> C°, C° -> K° and K°-> C°

I need to ask, is this code readable by you and if anything needs to be changed/modified in order to make more efficient?

import SwiftUI

struct ContentView: View {
    @State private var inputTemp = ""
    @State private var inputUnit = 0
    @State private var outputUnit = 0

    let inputUnits = ["C", "F", "K"]
    let outputUnits = ["C", "F", "K"]

    var convertedDegreeC2F: Int {
        guard let inputDegree = Int(inputTemp) else { return 0 }
        let convertC2F = Int(inputDegree/5*9+32)
        let convertF2C = Int((inputDegree-32)*5/9)
        let convertC2K = Double(inputDegree) + 273.15
        let convertK2C = Double(inputDegree) - 273.15

        if inputUnit == 0 && outputUnit == 1 {
           return convertC2F
        } else if inputUnit == 1 && outputUnit == 0 {
            return convertF2C
        } else if inputUnit == 0 && outputUnit == 2 {
            return Int(convertC2K)
        } else if inputUnit == 2 && outputUnit == 0 {
            return Int(convertK2C)
        }

        return 0
    }

    var body: some View {
        NavigationView {
            Form {
                Section {
                    TextField("Input Temperature", text: $inputTemp)
                        .keyboardType(.decimalPad)
                }
                Section(header: Text("Select input unit:" )) {
                    Picker("Input Unit", selection: $inputUnit) {
                        ForEach(0..<inputUnits.count) {
                            Text("\(self.inputUnits[$0])°")
                        }
                    }
                    .pickerStyle(SegmentedPickerStyle())
                }
                Section(header: Text("Select output unit:" )) {
                    Picker("Output Unit", selection: $outputUnit){
                        ForEach(0..<outputUnits.count) {
                            Text("\(self.outputUnits[$0])°")
                        }
                    }
                        .pickerStyle(SegmentedPickerStyle())
                }
                Section(header: Text("Temperature after conversion is:")) {
                    Text("\(convertedDegreeC2F)°")
                }
            }
        .navigationBarTitle("UConvert")
        }
    }
}


texts: Updating the icon of every JLabel in a JLabel ArrayList

texts:
I want to update every icon of a JLabel ArrayList, to its own individual icon based off of an outside ArrayList. The outside ArrayList is called _board_, and the JLabel ArrayList is called _tiles_. I want to update every icon to its corresponding item in _board_. How can I do that efficiently? I need it to update every icon of a huge list, we're talking like 100 - 200 items long. Right now, at a hundred items long, it takes about 4 seconds before displaying all of the icons at the same time:

for (int i = 0; i < board.size(); i++) {
    //this is all one line:
    tiles.get(i).setIcon(resizeIcon(displayTile(board.get(i),
    tiles.get(i).getHeight(), tiles.get(i).getHeight()));
}
//this resizes the ImageIcon and returns the risized icon:
public static ImageIcon resizeIcon(ImageIcon i, int x, int y) {
    Image image = i.getImage();
    Image newimg = image.getScaledInstance(x, y, java.awt.Image.SCALE_SMOOTH);
    i = new ImageIcon(newimg);
    return i;
}
//this returns an ImageIcon based off of the number that is put in:
public static ImageIcon displayTile(int num) {
    if (num != 0) {
        ImageIcon i = new ImageIcon("src/resources/" + num + ".png");
        return i;
    }
    ImageIcon i = new ImageIcon("src/resources/0.png");
    return i;
}


texts:
Given an iterator of iterators, return all of the elements from the iterators in order. Looking for code review, optimizations, and best practices. Verifying complexity to be \$O(n)\$, where \$n\$ is the total number of elements from all iterators.

public class IteratorOfIterator implements Iterator<Integer>{

    private final Iterator<Iterator<Integer>> iteratorOfIterator;
    private Iterator<Integer> currentIterator;

    public IteratorOfIterator(Iterator<Iterator<Integer>> iterator)  {
        this.iteratorOfIterator = iterator;
    }

    @Override
    public boolean hasNext() {
        while (currentIterator == null || !currentIterator.hasNext()) {
            if (!iteratorOfIterator.hasNext()) return false;
            currentIterator = iteratorOfIterator.next();
        }
        return true;
    }

    @Override
    public Integer next() {
        if (!hasNext()) {
            throw new NoSuchElementException("the stuff cannot be null.");
        }
        return currentIterator.next();
    }

    @Override
    public void remove() {
        throw new UnsupportedOperationException("The remove operation is not supported.");
    }
}

public class IteratorOfIteratorTest {

    @Test
    public void testIterator() {
        List<Integer> list1 = new ArrayList<>(Arrays.asList(1, 2, 3, 4));
        List<Integer> list2 = new ArrayList<>(Arrays.asList(5, 6, 7, 8));
        List<Iterator<Integer>> combined = new ArrayList<>(Arrays.asList(list1.iterator(), null, list2.iterator()));

        IteratorOfIterator ioi = new IteratorOfIterator(combined.iterator());
        int[] expected = {1, 2, 3, 4, 5, 6, 7, 8};
        int[] actual = new int[8];
        int i = 0;
        while (ioi.hasNext()) {
             actual[i] = ioi.next();
             i++;
        }
        assertArrayEquals(expected, actual);
    }
}


texts:
This morning I decided to write this question: https://stackoverflow.com/questions/11727571/are-there-problems-if-i-have-a-verbose-datatype/11727723#11727723

I don't really explain my scenario about how am I accesing through the nested dictionaries. I decided to have the default alias (IDictionary<string, IDictionary<Levels, IList<Problem>>>) but I'm thinking that's not a good option right now.

I'm gonna show some parts of my code:

ProblemBaseFactory

public abstract class ProblemBaseFactory : IProblemFactory
{
    private IDictionary<string, IDictionary<Levels, IList<Problem>>> problemDictionaryPackages;

    protected ProblemBaseFactory()
    {
        problemDictionaryPackages = new Dictionary<string, IDictionary<Levels, IList<Problem>>>();
    }

    protected IDictionary<string, IDictionary<Levels, IList<Problem>>> ProblemDictionaryPackages
    {
        get { return problemDictionaryPackages; }
    }

    public abstract IEnumerable<Levels> AvailableLevels(string packageName);
    public abstract IEnumerable<Problem> LoadProblems(ProblemFactoryProperties properties);
}

RuleProblemFactory

public abstract class RuleProblemFactory : ProblemBaseFactory
{
    private IDictionary<string, IDictionary<Levels, IList<ProblemRule>>> ruleDictionaryPackages;
    private IRuleAlgorithmSelector ruleAlgorithmSelector;
    private IList<Problem> temp;

    protected RuleProblemFactory()
        : this(new Dictionary<string, IDictionary<Levels, IList<ProblemRule>>>(), new SequentialRuleSelector())
    {
    }

    protected RuleProblemFactory(IRuleAlgorithmSelector ruleAlgorithmSelector)
        : this(new Dictionary<string, IDictionary<Levels, IList<ProblemRule>>>(), ruleAlgorithmSelector)
    {
    }

    protected RuleProblemFactory(IDictionary<string, IDictionary<Levels, IList<ProblemRule>>> ruleDictionary,
        IRuleAlgorithmSelector ruleAlgorithmSelector)
    {
        this.ruleDictionaryPackages = ruleDictionary;
        this.ruleAlgorithmSelector = ruleAlgorithmSelector;

        LoadBankOfRules();
    }

    protected IDictionary<string, IDictionary<Levels, IList<ProblemRule>>> RuleDictionaryPackages
    {
        get { return ruleDictionaryPackages; }
    }

    public override IEnumerable<Problem> LoadProblems(ProblemFactoryProperties properties)
    {
        // does exist the package name?
        if (!ProblemDictionaryPackages.ContainsKey(properties.NamePackage))
            throw new InvalidOperationException("namePackage");

        IDictionary<Levels, IList<Problem>> problemPackage = this.ProblemDictionaryPackages[properties.NamePackage];

        // does exist the list
        if (!problemPackage.ContainsKey(properties.Difficulty))
            problemPackage.Add(properties.Difficulty, new List<Problem>());

        temp = problemPackage[properties.Difficulty];

        if (temp.Count >= properties.Quantity)
            return temp;
        else
            return GenerateProblems(properties);
    }

    private IEnumerable<Problem> GenerateProblems(ProblemFactoryProperties properties)
    {

        ruleAlgorithmSelector.Rules = ruleDictionaryPackages[properties.NamePackage][properties.Difficulty];

        ...
    }

    public override IEnumerable<Levels> AvailableLevels(string name)
    {
        return ruleDictionaryPackages[name].Keys;
    }
}

Sometimes I guess is difficult to readability. What do you recomend me to to mantain a better readability?


texts: Converting a boolean list to string, and vice versa

texts:
I am currently using this to convert a List of booleans to a string

    var tempbllist = new List<int>();
        foreach (var t in blenabled)
            switch (t)
            {
                case true:
                    tempbllist.Add(1);
                    break;
                case false:
                    tempbllist.Add(0);
                    break;
            }

        Settings.Default.blEnabled = String.Join(",",
            tempbllist.Select(i => i.ToString(CultureInfo.InvariantCulture)).ToList());

(converts them to 1s and 0s to save space)

and this to convert them back

if (Settings.Default.blEnabled.Contains(","))
            blenabled =
                new List<bool>(
                    Settings.Default.blEnabled.Split(',').Select(Int32.Parse).Select(i => i == 1).ToList());

What is a better way of doing this?


texts:
I'm using data from a database from the IMDB website. The database consists of five relevant tables.

Actor (id, fname, lname, gender)
Movie (id, name, year, rank)
Director (id, fname, lname)
Cast (pid, mid, role)
Movie_Director (did, mid)

It's worth noting that the id column in Actor, Movie & Director tables is a key for the respective table.

Cast.pid refers to Actor.id, and Cast.mid refers to Movie.id.

Here's the prompt and my initial attempt at solving it.  Any help in improving/speeding up the query would be greatly appreciated.

/* For every pair of male and female actors that appear together in some film,
   find the total number of films in which they appear together.
   Sort the answers in decreasing order of the total number of films. */

SELECT a1.fname, a1.lname, a2.fname, a2.lname, count(*) AS num_films
FROM Actor AS a1, Actor AS a2, Cast AS c1, Cast AS c2
WHERE c1.mid = c2.mid AND
      a1.id = c1.pid    AND
      a2.id = c2.pid    AND
      a1.gender = 'M' AND
      a2.gender = 'F'
GROUP BY a1.id, a2.id, a1.fname, a1.lname, a2.fname, a2.lname
HAVING COUNT(*) > 0
ORDER BY COUNT(*) DESC;


texts: Including file based on user input: Efficiency and Security

texts:
Currently I'm using this code:

<?php
/*
Clean, Simple, Minimal.
*/
$pages = array('home', 'login', 'register', 'logout', 'test');
if (isset($_GET['p']))
{
    $page = $_GET['p'];
    if (in_array($page, $pages))
    {
       include('pages/' . $page . '.php');
    }
}
 else {
    echo 'Hi';
}
?>

I want this to be as secure and efficient as possible, I've seen multiple versions of this. I wasn't sure how to do what i really wanted, I wanted it so that if the requested file .php exists in /pages/ it'll show it, and else throw an error. But last time i did that I was vulnerable to LFI.


texts: Restucture code to wrap optional resources in a using block

texts:
I have some C# I/O code that can take one or two input files.  I would like to wrap the Stream objects in a using block, but cannot find a way to succinctly express this in code.

Currently, I have two large files (>1GB), that contain concatenated TIFF files and PDF files respectively that need to be extracted into individual files.  The metadata of the individual files (TIFF Tags and PDF Keywords) cross-reference one another, so the processing rules are different if I receive both files at once, i.e. there is more information and verification logic.

I have a FileProcessor class than implements an IEnumerable<Range> to return the byte ranges of each individual file within the archive. My current implementation just wraps the main processing loop in a try/finally block and calls Dispose manually.

// Struct to represent the byte range of a file in the archive
struct Range
{
   public long start;
   public long end;
}

// Custom class that takes a Stream object in the constructor and implements IEnumerable<Range> to return the individual files in sequence
public class FileProcessor : IDisposable, IEnumerable, IEnumerable<Range>
{
    private Stream _stream;
    public FileProcessor(Stream stream) { this._stream = stream; }
    public virtual void Dispose()
    {
       if (_stream != null) { _stream.Dispose(); _stream = null; }
    }
}

public class TiffProcessor : FileProcessor { ... }
public class PdfProcessor : FileProcessor { ... }

// Snippet of the dispatching/processing logic
TiffProcessor infile1 = null,
PdfProcessor  infile2 = null;
try
{
    if (HasFirstInputFile)
    {
       infile1 = new TiffProcessor(File.OpenRead(FirstInputFileName));
    }

    if (HasSecondInputFile)
    {
       infile2 = new PdfProcessor(File.OpenRead(SecondInputFileName));
    }

    if (infile1 != null && infile2 == null)
    {
        foreach (var range in infile1) { ... }
    }

    if (infile1 == null && infile2 != null)
    {
        foreach (var range in infile2) { ... }
    }

    if (infile1 != null && infile2 != null)
    {
        foreach (var ranges in infile1.Zip(infile2, (tiff, pdf) => new Range[] { tiff, pdf })) { ... }
    }
}
finally
{
    if (infile1 != null) { infile1.Dispose(); }
    if (infile2 != null) { infile2.Dispose(); }
}

Is there any construct that can help clean up and organize this code structure.  It's not too bad now, but could become exponentially more complex if additional input streams are required in the future.

Edit

Based on the comments received, perhaps creating an intermediate Strategy object that managed resources would work?

using (var strategy = StrategyFactory.Create(CommandLineArgs))
{
    strategy.Process();
}

public static class StrategyFactory
{
    public static IStrategy Create(CommandLineArguments args)
    {
        if (args.FirstInputFile != null && args.SecondInputFile == null)
        {
            return new FirstStrategy(args.FirstInputFile);
        }

        if (args.FirstInputFile == null && args.SecondInputFile != null)
        {
            return new SecondStrategy(args.SecondInputFile);
        }

        if (args.FirstInputFile != null && args.SecondInputFile != null)
        {
            return new ThirdStrategy(args.FirstInputFile, args.SecondInputFile);
        }
    }
}


texts:
I'm writing GUI controls and there are many places where there are many nested ifs checking for some result.

function TMyObject.GetCursor: TCursor;
begin
  if CanDragX then
  begin
    if CanDragY then
      Result := crSizeAll
    else
      Result := crSizeWE;
  end
  else if CanDragY then
    Result := crSizeNS
  else
  if CanClick then
    Result := crHandPoint
  else
    Result := crArrow;
end;

How would you format/rewrite this code?


texts: Parse a list of people to determine who likes someone

texts:
I have a data file that looks like this:

Friend Name                     Joe
Likes                           Jill
Age                             30
Gender                          Male

Friend Name
Likes                           Mark
Age                             30
Gender                          Male

Friend Name                     Bob
Likes                           Ralph
Age                             30
Gender                          Male

Note: the data file has leading spaces before the first column.

I want to parse this file and see who likes a given person (likes). In this example, at most only one person likes the given person. So, say I am finding who likes 'Ralph', only Bob does. It is possible that the likes is not even in the data. It is also possible that the Friend Name might be blank (see the second Friend).

Here is my code to parse this data and return the friend who likes 'likes':

def parse_friends_list(friends_list, likes):
    output = friends_list.strip().splitlines()
    for line in output:
        try:
            if line.startswith('Friend Name'):
                friend = line.split()[2]
            elif line.startswith('Likes'):
                found_likes = line.split()[1]
                if found_likes == likes and friend:
                    return friend
                friend = ''
        except IndexError:
            pass
    raise NoFriendParse('Unable to find a friend for {}'.format(likes))


texts: "Digit Queries" CSES Solution giving TLE

texts:
I really need a more accurate way to size inf_string. This code works but gets exponentially more inefficient the bigger max(queries) is, and therefore just can't hold up to the gargantuan numbers that CSES throws into it.
Problem:
Consider an infinite string that consists of all positive integers in increasing order:
12345678910111213141516171819202122232425...
Your task is to process q queries of the form: what is the digit at position k in the string?
The first input line has an integer q: the number of queries.
After this, there are q lines that describe the queries. Each line has an integer k: a 1-indexed position in the string. For each query, print the corresponding digit.
queries = []
for i in range(int(input())):
    queries.append(int(input()))
# TODO FIND A BETTER WAY TO LIMIT inf_string LENGTH
inf_string = [str(x) for x in range(1, max(queries)+1)]
inf_string = "".join(inf_string)
for k in queries:
    print(inf_string[k-1])


texts:
def truthy(v):
    if issubclass(v.__class__, numbers.Number):
        return bool(int(v))
    if isinstance(v, basestring):
        vl = v.lower()[0]
        if vl == 'y' or vl == 't':
            return True
    return False

Is there some type/class I missed that can be evaluated by Python as True/False that I missed here?
Drawbacks? Better ways?


texts: A traits class for (compound) pointers - beyond what std::pointer_traits offers

texts:
This is a percolation of ideas which originated this SO question:

Compound pointer traits class with method generalizing make_shared and make_unique?

The std::pointer_traits class offers the following traits, basically:

Types: pointer, element_type, difference_type, and rebind (given a pointer-like type for pointing to T, get a pointer-like type for pointing to U)

Static methods:

to_address - get the plain vanilla T* from some fancy pointer-to-T-like class, if possible
pointer_to - opposite of to_address. This is a fishy method, since it's not clear what it means with respect to resource ownership.

I think it's useful to add at least two methods - for creating a pointer to a new object / array of objects, a-la std::make_shared and std::make_unique, and one for releasing ownership + getting the raw address. Here's my implementation:

#pragma once
#ifndef EXTRA_POINTER_TRAITS_HPP_
#define EXTRA_POINTER_TRAITS_HPP_

#include <memory>

template <typename Ptr>
struct extra_pointer_traits;

template <typename T>
struct extra_pointer_traits<T*>
{
    using ptr_type = T*;
    using element_type = T;

    static ptr_type make(size_t count) { return new T[count]; }
    static ptr_type make()             { return new T;        }
};

template <typename T>
struct extra_pointer_traits<T[]>
{
    using ptr_type = T[];
    using element_type = T;

    static T* make(size_t count) { return new T[count]; }
    static T* make()             { return new T;        }
};

template <typename T, class Deleter>
struct extra_pointer_traits<std::unique_ptr<T[], Deleter>>
{
    using ptr_type = std::unique_ptr<T[], Deleter>;
    using element_type = T;

    static T* release(ptr_type& ptr) { return ptr.release(); }
    static std::unique_ptr<T[], Deleter> make(size_t count)
    {
        return std::make_unique<T[]>(count);
    }
};

template <typename T, class Deleter>
struct extra_pointer_traits<std::unique_ptr<T, Deleter>>
{
    using ptr_type = std::unique_ptr<T, Deleter>;
    using element_type = T;

    static T* release(ptr_type& ptr) { return ptr.release(); }
    static std::unique_ptr<T, Deleter> make()
    {
        return std::make_unique<T>();
    }
};

template <typename T>
struct extra_pointer_traits<std::shared_ptr<T>>
{
    using ptr_type = std::shared_ptr<T>;
    using element_type = typename std::pointer_traits<ptr_type>::element_type;

    // No release()
    static std::shared_ptr<element_type[]> make(size_t count)
    {
        return std::make_shared<element_type[]>(count);
    }
    static std::shared_ptr<element_type> make()
    {
        return std::make_shared<element_type>();
    }
};

#endif // EXTRA_POINTER_TRAITS_HPP_

I'm considering suggesting something like this as an addition to the existing traits class the standards committe, but for now I've implemented it as a separate class.

Note: To clarify - these are not all possible template specializations for pointer-like classes in the standard library, there would be a few more.


texts:
I am trying to learn me some Haskell because I found it to be an interesting language. Right now, I am trying to implement a function in Haskell to get acquainted with the language. The function just gets user input and adds the input numbers to a list of floats.

get_budget_values _values _index _length = do
    tmp_value <- getLine

    let new_value = read tmp_value :: Float
    let new_values = new_value : _values
    let new_index = _index + 1

    if new_index < _length
        then get_budget_values new_values new_index _length
        else return new_values

So, is this a proper way to implement a function like that in Haskell? What beginner mistakes am I making? Are there any standard ways of doing something like this?


texts:
Used to use Laravel's easy to use form validation class, decided to mimic it in JS. I've been learning JS for 4 days now and decided to write my first piece of real code.

I'm pretty sure its full of bad practices, and a lot of it can be improved. I'm looking for some constructive criticism on what I can do better next time, thanks in advance.

Class:

class Validator {
    make(rules) {
        this.rules = rules;
    }

    valid() {
        if (!this.hasOwnProperty('rules')) {
            return true;
        }

        let errors = [];
        let checkFunction = this.checkRuleForElement; // Storing this here because it doesn't seem to work in its invoked scope.

        Object.keys(rules).forEach(function(key) {
            let formElement = document.getElementsByName(key)[0];

            if (formElement == undefined) {
                return;
            }

            let ruleSet = rules[key].split('|');

            ruleSet.forEach((rule) => {
                let result = checkFunction(rule, formElement)

                if (!result.valid && result.message != undefined) {
                    errors.push(result.message);
                }
            });
        });

        return {
            valid: errors.length == 0,
            errors: errors
        }
    }

    checkRuleForElement(rule, formElement) {
        let isValid = true;
        let error = "no error";

        switch (rule) {
            case "required":
                if (formElement.value.length <= 0) {
                    isValid = false;
                    error = `Form element ${formElement.getAttribute("name")} is required.`;
                }
                break;
             // todo: alpha => only alpha characters
             // todo: alphanum => Alphanumeric characters
             // todo: num => Numbers only
        }

        return {
            valid: isValid,
            message: error
        };
    }
}

Setup (usage):

let validator = new Validator();

function checkValidation() {
    validator.make({
        "username": "required",
        "password": "required",
    });

    let result = validator.valid();

    if (!result.valid) {
        alert('Something went wrong.');
        alert('Errors are: ' + result.errors[0]);
    }
    else {
        alert('Validation was a success.');
    }
}


texts:
The main objective of this code is that you must accept an input from the user and loop and remove the consonants and vice versa and display the new word.

I know there is a easier way of doing it, but I have no idea how.

String test = "john doe", check;
    for(int ktr = 0; ktr < test.length(); ktr++){
       // System.out.println(test.substring(ktr, ktr+1));
        check = test.substring(ktr, ktr+1);
        if(!"b".equals(check) && !"c".equals(check)){
            if(!"d".equals(check) && !"f".equals(check)){
                if(!"g".equals(check) && !"h".equals(check)){
                    if(!"j".equals(check) && !"k".equals(check)){
                        if(!"l".equals(check) && !"m".equals(check)){
                            if(!"n".equals(check) && !"p".equals(check)){
                                if(!"q".equals(check) && !"r".equals(check)){
                                    if(!"s".equals(check) && !"t".equals(check)){
                                        if(!"v".equals(check) && !"w".equals(check)){
                                            if(!"x".equals(check) && !"y".equals(check)){
                                                if(!"z".equals(check)){
                                                     System.out.print(check);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }


texts:
I recently started to learn more about OOP in PHP and I created a website for testing. I have 4 classes: database, user, posts, comments.
This is a simple database.class.php:

class DB {

    protected $pdo;
    protected $engine    = 'mysql';
    protected $host      = 'localhost';
    protected $db_name   = 'test';
    protected $db_user   = 'root';
    protected $db_passwd = '';

    public function connect() {
        try {
            $this->pdo = new PDO($this->engine.':host='.$this->host.';dbname='.$this->db_name,$this->db_user,$this->db_passwd);
            $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            return $this->pdo;
        }   catch(PDOException $e) {
            die($e->getMessage());
        }
    }
}

Then, every other class starts like this:

class user {

    public $link;

    public function __construct() {
        $pdoObj = new DB();
        $this->link = $pdoObj->connect();
        return $this->link;
    }

}

I use $link as a reference to the pdo object so I can use all the methods associated with PDO.  My question is: is this wrong?

I saw a lot of source codes and most of them used 'static' and didn't instantiated the class with new Class(); but just ClassName::foo(); Is it wrong to instantiate every class and work with instances? I always do:

$obj = new user();
$obj->SelectAll();

// and so on..

If my way is wrong, how can I move my code to static?

Here is an example of a method:

public function register($username, $email, $passwd, $re_passwd) {
    # fix email and passwd regex
    $reg_error = array();
    $regex_username = '/[a-zA-Z0-9-._]{6,20}$/';
    $regex_email = '/[a-zA-Z0-9._-]{3,}@[a-zA-Z0-9]{3,}.[a-zA-Z.]{2,}$/';
    if (empty($username) || empty($email) || empty($passwd) || empty($re_passwd)) {
        $reg_error['fields'] = 'All fields are required';
    }   else {
        if (!preg_match($regex_username, $username)) {
                $reg_error['username'] = 'Username must be at least 6 characters';
        }   if (!preg_match($regex_email, $email)) {
                $reg_error['email'] = 'Invalid email';
        }   if(strlen($passwd) <= 6) {
                $reg_error['passwd'] = 'Password must be at least 6 characters long and must contain at least 1 uppercase, 1 lowercase and 1 digit value';
        }   if ($re_passwd !== $passwd) {
                $reg_error['match'] = 'Passwords do not match';
        }   if($this->usernameExists($username)) {
                $reg_error['username_exists'] = 'Username: ' .$username. ' already exists';
        }   if($this->emailExists($email)) {
                $reg_error['email_exists'] = 'Email: ' .$email. ' already exists in our database';
        }
    }
    if (!empty($reg_error)) {
        foreach($reg_error as $error => $er) {
            echo 'Error: '.$er.'<br />';
        }
    }   else {
        try {

            $query = $this->link->prepare("INSERT INTO users(username, email, password, ip_address, activation_code)
                                            VALUES(:username, :email, :passwd, :ip_addr, :code)");
            $passwd = hash('sha512', $passwd);
            $ip_addr = $_SERVER['REMOTE_ADDR'];
            $code = substr( hash('sha512', md5(rand(999, 9999))) , 15, 40);
            $params = array(':username' => $username,
                            ':email'    => $email,
                            ':passwd'   => $passwd,
                            ':ip_addr'  => $ip_addr,
                            ':code'     => $code);
            $query->execute($params);
            if ($query->rowCount() != 0) {
                redirect('index.php?lastid='.$this->lastId());
            }   else {
                    return 'There\'s been a tehnical problem during the registration process, please try again later.';
            }
        }   catch (PDOException $e) {
                die($e->getMessage());
        }
    }
}


texts:
I have built a Caesar Cipher in Ruby that utilizes ASCII for the encryption. I am not sure whether or not this was the best way to go about the task but this way made the most sense to me. Please give me any feedback that comes to mind.

puts 'Please enter your string to be coded'
    string = gets.chomp.split("")

puts 'Please enter your number key'
    key = gets.chomp.to_i

    if (key > 26)
        key = key % 26
    end

    string.map! do |i|
        i.ord
    end

    string.map! {|i| i = i + key}.map! {|i|
        if (i > 122)
            then i = i - 26
        elsif (90 < i && i < 97)
            then i = i - 26
        elsif (i > 96 && (i - key) < 91 && (i - key) > 64)
            then i = i - 26
        elsif (i < 65 )
            then i = 32
        else
            i
        end
    }

    string.map! do |i|
        i.chr
    end

    puts "Your coded word is #{string.join("")}"

puts 'Return back to original string? (Yes or No)'
    response = gets.chomp.downcase

    if response == 'yes'
        string.to_s.split("")
        string.map! do |i|
            i.ord
        end

        string.map! {|i| i - key}.map! {|i|
            if (90 < i && i < 97)
                then i = i + 26
            elsif ((i+key) > 96 && i < 91 && i > 64)
                then i = i + 26
            elsif (i < 65 && (i+key) < 91 && (i + key) > 64)
                then i = i + 26
            elsif (i < 65)
                then i = 32
            else
                i
            end
        }

        string.map! do |i|
            i.chr
        end

        puts string.join("")

    end


texts:
I am using asp.net core entitiy framework.  The page displays the customers.  The user can add new customers or delete existing ones.  I am looking for ways to improve my code.

Here is my cshtml page

@Html.Partial("Index")
@model ecommerce.Models.Users

Add a new customer

<form asp-controller="Customer" asp-action="AddCustomer" method="post" role="form">

        Name
        <input asp-for="name"/>
        <button type="submit">Add</button>
        <input asp-for="created_at" value="@DateTime.Now" class="time"/>
        <input asp-for="updated_at" value="@DateTime.Now" class="time"/>
</form>
@{
        if(ViewBag.NotUnique!=null)
        {

Name is alread in DB

        }

        if(ViewBag.Empty!=null)
        {

Name is empty

        }

                        Customer Name
                        Created Date
                        Actions

        @if(ViewBag.Users != null)
        {
                foreach(var user in ViewBag.Users)
                {

                                @user.name
                                @user.created_at.ToString("MMM")  @user.created_at.ToString("dd") @user.created_at.ToString("yyyy")

                                  <form action="/DeleteCustomer/@user.id" method="post">
                                        <input type="submit" name="submit" value="Delete"/>
                                  </form>

                }
        }

}

Here is my cs file

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using ecommerce.Models;
using ecommerce.Controllers;
using System.Linq;

namespace ecommerce.Controllers
{
    public class CustomerController : Controller
    {
        // GET: /Home/

        private YourContext _context;

        public CustomerController(YourContext context)
        {
            _context = context;//connection for my db
        }

        [HttpGet]
        [Route("customers")]
        public IActionResult Customers()
        {
            ViewBag.Users = _context.Users.AsEnumerable();
            return View();
        }

        [HttpPost]
        [Route("deleteCustomer/{id}")]
        public IActionResult DeleteCustomer(int id)
        {
            var temp = _context.Users.Where(x => x.id == id).SingleOrDefault();
            _context.Users.Remove(temp);
            _context.SaveChanges();
            return RedirectToAction("Customers");
        }

        [HttpPost]
        [Route("addCustomer")]
         public IActionResult AddCustomer(String name, DateTime created_at)
        {
            Users user = new Users();
            user.name = name;
            user.created_at = created_at;
            user.updated_at = created_at;

            var temp = _context.Users.AsEnumerable().ToList();
            if(temp.Any(x => x.name == name))
            {
                ViewBag.NotUnique = true;
                return RedirectToAction("Customers");
            }
            if (user.name != null)
            {
                // Success

                _context.Users.Add(user);
                _context.SaveChanges();
                return RedirectToAction("Customers");
            }

            ViewBag.Empty = true;
            // If there were errors, re-render the view but bind the model that was submitted.
            return RedirectToAction("Customers");
        }
    }
}


texts:
My project uses at least 100 helper classes like the below:

.pa5 {padding:5px} .pa10 {padding:10px} /* ... */
.pt5 {padding-top:5px} .pt10 {padding-top:10px} /* ... */
.pr5 {padding-right:5px} .pr10 {padding-right:10px} /* ... */
 /* ... */

It comes handy in some cases like
...
 but I think we overused it or, even worse, misused it.

For example, the below  tag contains 8 classes to define how it display (background, background hover, padding, border radius, diplay inline block, margin and float left). It looks like the way you use style="..." to inline style it:

In other case, even when we had the class profileInfo, we still use it with a lot of helper classes:

I think this is a worse practice and could cause significant performance overhead on page rendering. Since I haven't worked a lot with CSS, I could not explain it clearly to make us change the way of using it. What do you think? Does your project have an explicit rule to limit the number of CSS classes for one element?


texts:
Recently I've been doing some experimenting with RPN and the shunting-yard algorithm, in order to test these systems more appropriately I planned on writing a tokenizer and then using these tokens to check validity and eventually get some output. I also think that I could use this to work with some primitive programming language, such as making a CHIP-8 assembler.
Function
The intention is for my tokenizer to separate the input string into a list of the following:

Individual Symbols ('(', ')', '*', etc...)
Sequences of digits ('1', '384', etc...)
Sequences of characters ('log', 'sin', 'x', etc...)

Note that because of this sequences such as:

'3.14' (parsed as '3', '.', '14')
'6.02E23' (parsed as '6', '.', '02', 'E', '23')

Will not come out as the numbers they represent but can be reconstructed later on.
But sequences such as '3x' will come out as '3', 'x' making it easier to account for multiplication of variables.
Questions
For the most part I'm quite happy with this code, a couple things that I'm interested in (alongside general review) are:

How can I make the line if l.isalpha() and buf.isdigit() or l.isdigit() and buf.isalpha(): more concise?
What about the if buf: out += [buf]; buf = '' lines? Would there be anything wrong with putting this inside a nested function in tokenize? Or would out, buf = out + [buf], '' be more pythonic?
This technique makes it easier later on to identify function calls such as min, max or sin, but how would I differentiate the meanings of 'xy'? (x*y vs a variable actually called xy, also this question is less relevant in the context of programming languages which would parse 'xy' as a single token over the multiplication of 2)(This question is possibly out of scope for CR, if so this question can be removed)

The reasons for these questions specifically is that I like concise code, writing it on few lines without having any too long.
Code
def tokenize(s):
    out = []
    buf = ''
    for l in s:
        if not l.isalnum():
            if buf:
                out += [buf]
                buf = ''
            out += [l]
        else:
            if l.isalpha() and buf.isdigit() or l.isdigit() and buf.isalpha():
                out += [buf]
                buf = ''
            buf += l
    if buf:
        out += [buf]
    return out


texts: Removal of subtrees in tree on condition optimally

texts:
I have a small program that removes subtrees of a tree based on following condition: If a subtree consists only of nodes with "rank" 1, remove it.  I am using recursive DFS approach.  Trees or subtrees does not have any further special properties. I want to ask about your opinions.  Is it possible to make this more elegant/more optimal?

public class Main {

    public static void main(String[] args) {
        List<Node> tree1 = Arrays.asList(
            new Node(1, null, 1),
            new Node(2, 1, 1),
            new Node(3, 1, 1),
            new Node(4, 2, 0),
            new Node(5, 3, 1),
            new Node(6, 5, 0),
            new Node(7, 5, 1),
            new Node(8, 7, 0),
            new Node(9, 5, 1),
            new Node(10, 3, 1)
        );

        List<Node> newTree = new ArrayList<>();
        traverse(tree1.get(0), tree1, newTree);
        if(tree1.get(0).rank != 1 || tree1.get(0).getNumberOfValidSubtrees() != 0) {
            newTree.add(tree1.get(0));
        }

        System.out.println(tree1);
        newTree.sort(Comparator.comparing(Node::getId));
        System.out.println(newTree);
    }

    private static void traverse(Node parent, List<Node> allNodes, List<Node> newTree){
        List<Node> children = allNodes.stream().filter(e -> e.parentId != null && e.parentId == parent.id).collect(Collectors.toList());

        for(Node child : children) {
            traverse(child, allNodes, newTree);

            if(child.rank != 1 || child.getNumberOfValidSubtrees() != 0) {
                parent.incrementValidSubtree();
                newTree.add(child);
            }
        }
    }
}

Node class

class Node{
    int id;
    Integer parentId;

    int rank;
    private int numberOfValidSubtrees;

    Node(int id, Integer parentId, int rank){
        this.id = id;
        this.parentId = parentId;
        this.rank = rank;
        this.numberOfValidSubtrees = 0;
    }

    public int getNumberOfValidSubtrees(){
        return this.numberOfValidSubtrees;
    }

    public void incrementValidSubtree() {
        this.numberOfValidSubtrees++;
    }

    public int getId() {
        return id;
    }

    public String toString() {
        return String.valueOf(id);
    }
}


texts: OpenMP parallelization of a for loop with function calls

texts:
Using OpenMP, is it correct to parallelize a for loop inside a function "func" as follows?

void func(REAL coeff, DATAMPOT *dmp, int a, int la, int b, int lb, REAL L)
{
    int i,j,k;
    REAL dx,dy,dz;
    REAL dx2,dy2,dz2;
    REAL r;

    #pragma omp parallel for default(shared) private(k,i,j,dx,dy,dz,dx2,dy2,dz2,r) reduction(+:deltaE)
    for(k=0; k<la*lb; ++k){
        j=k/la+b;
        i=k%la+a;

        dx=fabs(part[i].x-part[j].x);
        dy=fabs(part[i].y-part[j].y);
        dz=fabs(part[i].z-part[j].z);
        dx2=(dx<0.5?dx*dx:(1-dx)*(1-dx));
        dy2=(dy<0.5?dy*dy:(1-dy)*(1-dy));
        dz2=(dz<0.5?dz*dz:(1-dz)*(1-dz));
        r=L*sqrt(dx2+dy2+dz2);

        deltaE += coeff*((dmp+NSPES*part[i].s+part[j].s)->npot>1?
mpot(r,dmp+NSPES*part[i].s+part[j].s,((REAL)rand())/RAND_MAX):
(dmp+NSPES*part[i].s+part[j].s)->pot[0](r,(dmp+NSPES*part[i].s+part[j].s)->dp ) );

    }

}

Where:

REAL is double (#define REAL double)
DATAMPOT *dmp is a pointer to a struct containing (among others) some pointers to functions, such as pot[0]
part is a global array of struct
deltaE (variable for summation-reduction) is a REAL global variable

I know that, for a correctness, a special treatment of function rand() is also required;
but apart from that, are there some other important (conceptual) correction to do on the above parallelization? Which is limited at only one directive row?


texts: Find an order with the minimum total price

texts:
We want to create an application for the analysis of the order history at an online store. Each order is made by a customer and concerns the purchase of one or more items. Orders are stored in OR, an array of integers having 4 columns. The generic line OR[i] = [o, a, q, p] denotes the fact that in the order with code "o" a quantity "q" of the article with code "a" is required, sold at a unit price equal to "p" (for which obviously the total price paid for the item a in the order "o" is equal to "p * q"). An order has as many rows in OR as there are different items contained in the order.

I must write a function "ordine_min(OR)" which returns the order code with the minimum total price. In case of a tie, any of the orders with the minimum total price must be returned.

def ordine_min(OR):
    ret = []
    for i in range(len(OR)):
        if prezzo(OR,i):
            ret.append((prezzo(OR, i),i))
    return min(ret)

def prezzo(OR, i):
    prezzo_tot = 0
    for k in range(len(OR)):
        if OR[k][0] == i:
            prezzo_tot += OR[k][2] * OR[k][3]
    return prezzo_tot

The matrix is here:

OR = [[1,1,2,2],
      [1,2,3,2],
      [2,1,1,2],
      [2,4,1,3],
      [3,3,2,1],
      [3,4,2,1],
      [4,4,1,7],
      [4,5,2,1],
      [5,1,2,4],
      [5,5,1,4],
      [6,1,2,1],
      [6,2,1,3]]


texts: Code to sort based on quantities of a data member occuring

texts:
The setup is that I have a vector of a class, and I need to sort it by the quantity of a data member value, not the value itself. The below code exhibits the correct behavior, and part of that behavior is "stable" sorting where the order of elements should be preserved when possible.
Between the /*** Starting here ***/ and /*** Ending here ***/ comments, are there some Standard Library functions and/or classes that can be substituted? Per the tag, the code needs to exist in C++14. Yes, I realize that the MRE is written with C++17 (maybe some 20, but I compiled it as C++17), but the code in question [hopefully] isn't.
#include <algorithm>
#include <iostream>
#include <iterator>
#include <random>
#include <utility>
#include <vector>

struct Foo {
  int fizz = 0;
  int buzz = 0;
};

std::ostream &operator<<(std::ostream &sout, const Foo &obj) {
  return sout << "(" << obj.fizz << ", " << obj.buzz << ")";
}

template <typename Container>
void print(const Container &container, std::ostream &sout = std::cout) {
  std::copy(container.begin(), container.end(),
            std::ostream_iterator<typename Container::value_type>(sout, " "));
  sout << '\n';
}

int main() {
  std::mt19937 prng(std::random_device{}());
  std::uniform_int_distribution<int> dist(0, 9);
  std::uniform_int_distribution<int> large(500, 999);

  std::vector<Foo> devices;
  for (int i = 0; i < 100; ++i) {
    devices.push_back(Foo{.fizz = dist(prng), .buzz = large(prng)});
  }

  print(devices);
  std::cout << '\n';

  /*** Starting here ***/
  // Counting occurrences
  std::vector<std::pair<int, int>> counts;
  int index = 0;
  for (int i = 0; i < 10; ++index, ++i) {
    counts.emplace_back(index, 0);
  }
  for (auto i : devices) {
    ++counts[i.fizz].second;
  }

  // Descending sort using counts of occurrence of a fizz value
  std::stable_sort(counts.begin(), counts.end(),
                   [](auto a, auto b) { return a.second > b.second; });

  std::vector<int> sort_by(10);
  for (int i = 0; i < 10; ++i) {
    sort_by[i] = counts[i].first;
  }
  print(sort_by);  // Prints fizz values in order of descending count
  std::cout << '\n';

  // Sort devices according to highest quantity of fizz
  auto walker = devices.begin();
  for (auto i : sort_by) {
    for (auto it = devices.begin(); it != devices.end(); ++it) {
      if (it->fizz == i) {
        std::iter_swap(walker, it);
        ++walker;
      }
    }
  }
  /*** Ending here ***/

  print(devices);
}


texts: Very simple RESTful API dispatching in PHP

texts:
This code is meant to be a very simple RESTful API.

The simple router takes the URI request and maps it to a function with a matching name. E.g. www.domain.com/bill maps to function bill(). Then bill will provide functions that will be REST endpoints - DELETE bill/id, GET bill (which gets all bills for a user), PUT bill/id, POST bill, etc.

I would like to make the code more object oriented. At the moment I only have one class, Token.

Any suggestions on where to add more classes in this small application would be helpful.

index.php

include token.php; // not included here
include bill.php;

// Parse URI
$actions = explode("/", $_SERVER['REQUEST_URI']);

// JWT Secret
$secret = "rvMuQ1MJ002IeWcl09TT4grwUxz41sSR";

// 'Router'
if(function_exists($actions[1])) {
    call_user_func_array($actions[1], array($secret));
}

bill.php

function bill($secret) {

    // Get all bills for user
    if($_SERVER['REQUEST_METHOD'] === 'GET') {

        // Make sure token is valid
        $id = checkToken($secret);
        if($id != 0) {

            $refreshed_token = new Token($id, $secret, null);

            // Retrieve the bills
            $db = new PDO("sqlite:../database/database.sqlite");
            $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

            $query = "SELECT bills.id, bills.user_id, billers.name, billers.category, bills.amount, bills.due, bills.status FROM bills INNER JOIN billers ON bills.biller_id = billers.id WHERE bills.user_id = :user_id";

            $stmt = $db->prepare($query);

            //if(!$stmt) { print_r($db->errorInfo()); }

            $stmt->bindParam(':user_id', $id);

            if($stmt->execute()) {

                $bills = $stmt->fetchAll();
                echo json_encode([
                    'code' => 200,
                    'message' => 'OK',
                    'bills' => $bills,
                    'token' => $refreshed_token->getTokenString()]);

            } else {

                echo json_encode([
                    'code' => 404,
                    'message' => 'Not found',
                    'bills' => '',
                    'token' => $refreshed_token->getTokenString()]);

            }

        } else {

            echo json_encode(["code" => 401, "message" => "Unauthorized"]);

        }

    }

    ..... other similar methods DELETE, PUT, etc.

}


texts: Returns an array of all inputs with specified name

texts:
I've made a nice little function to return a NodeList array containing all the inputs that have a specified name attribute:

function GiveElementsByName(name) {
var finalOutput = [], times = document.getElementsByTagName('input').length, inOutput = 0, inAll = 0; //For use later.
while(times--)
{
if (document.getElementsByTagName('input')[inAll].name == name) //Apply to all inputs with specified name.
 {
 finalOutput[inOutput] = document.getElementsByTagName('input')[inAll]; //Array with all the matching inputs.
 inOutput++;
 }
inAll++;
}
return finalOutput;
}
function MyFunc() {
  GiveElementsByName("Lol1")[1].value = "I don't like potatos anymore";
}
<input type="text" name="Lol1" value="I like potatos">
<input type="text" name="Lol1" value="I like potatos">
<input type="text" name="Lol1" value="I like potatos">
<input type="text" name="Lol1" value="I like potatos">

<input type="text" name="Lol2" value="I like potatos more">
<input type="text" name="Lol2" value="I like potatos more">
<input type="text" name="Lol2" value="I like potatos more">
<input type="text" name="Lol2" value="I like potatos more">

<input type="button" value="Click me!" onClick="MyFunc()">

Could you help me shrink down the function and make it quicker?


texts: Minimum router Peripherality Breadth First Search (BFS) Algorithm performance

texts:
I have solved the MinRouterPeripherality task in codility using javascript using Breadth First Search(BFS) approach.

However time complexity is O(N^2). I am really struggling to make performance improvement necessary so I can get the time complexity to possibly O(N) or close to it

Task: https://app.codility.com/programmers/task/min_router_peripherality/
Solved Report: https://app.codility.com/demo/results/trainingQ87TKA-9R2/

I am not 100% sure what improvements I could do to achieve this in Javascript.

    // you can write to stdout for debugging purposes, e.g.
    // console.log('this is a debug message');

    function solution(T) {
    // console.log(T);

    const treeMap = {}
    if(T.length < 3) {
          let min = Math.min(...T);

          return T.indexOf(min);
    }

    T.forEach((q, i)=>{
        if (q === i) {
            return;
        }

        if(!treeMap[q]) {
            treeMap[q] = [];
        }

        if(!treeMap[i]) {
            treeMap[i] = [];
        }

        treeMap[q].push(i);
        treeMap[i].push(q)
    });

    // Calculate distances
    const calcs = (n) => {
        let distanceMap = {};
        let queue = [n];
        let visited = [];
        let distance = 0;
        masterMap[n][n] = 0;
        const calculateDistances = (p) => {
            let start = p;
            visited.push(p)
    //        masterMap[n][p] = 0;
            let children = treeMap[p];

            if(!distanceMap[p]){
                distanceMap[p] = 0;
            }

            children.forEach((c) => {
                if(visited.indexOf(c) > -1) {
                    return;
                }

                distanceMap[c] = distanceMap[p] + 1;
             //   distance += distanceMap[c];

                if(!masterMap[c]) {
                    masterMap[c] = []
                }
                masterMap[n][c] = distanceMap[c];
                masterMap[c][n] = distanceMap[c];
             //   runs++;
            //    console.log('====', c, p, n)
            //    console.log(masterMap)
            //    console.log('====')
                queue.push(c)
            });

        };

        for(let i = 0; i < routerNodes.length; i++ ) {
            calculateDistances(queue.shift());
        }

      //  console.log(distanceMap)

        return distance;
    }

    const routerNodes = Object.keys(treeMap);

    let pdCalculations = [];
    let masterMap = [];
   // let runs = 0;
    for(let i = 0; i < routerNodes.length; i++ ) {
        if(masterMap[i] && Object.keys(masterMap[i]).length === (routerNodes.length - 1)) {
          break;
        }
        if(!masterMap[i]) {
            masterMap[i] = [];
            masterMap[i][i] = 0
        }
       // console.log(masterMap[i])
        calcs(i);
    }

   for(let k = 0; k < masterMap.length; k++ ) {
         pdCalculations.push(masterMap[k].reduce((a, b)=> a + b, 0))
   }

  // let value = Object.keys(pdCalculations).sort((a, b) => pdCalculations[a] - pdCalculations[b])[0];
   let min = Math.min.apply(null, pdCalculations);
  // console.log(min);

    return pdCalculations.indexOf(min);
  // return parseInt(value);

}


texts: two or more render/redirect in the same method

texts:
I often have method like this one with two or more render to do due to catching the error for example.
I currently do something like this:

def update
  @user = current_user
  if params[:user][:camera_type].present? && params[:user][:lens_type].present? && params[:user][:photo].present?
    r = Photo.instance.Upload(camera_type: @user.id,
                              album: @user.default_album,
                              photo: params[:user][:photo],
                              lens_type: params[:user][:lens_type],
                              camera_type: params[:user][:camera_type])
    @user.camera_type = params[:user][:camera_type]
    @user.lens_type = params[:user][:lens_type]
    @user.photo = params[:user][:photo]
    @user.save!
    render action: 'edit'
    return
  end
rescue Photo => e
  redirect_to photo_path, :flash => { :alert => t(:text_photo_edit_failed) }
end

But may be there is a better way to do it ?


texts: Count occurrences of an element in a list

texts:
I've been learning Haskell from LYAH for quite some time, and as a first practice for Chapter 7: Modules, I decided to make a simple numTimesFound function: it returns the number of times an element is found in a list.

Here's my working code:

numTimesFound :: Ord a => a -> [a] -> Integer
numTimesFound _ [] = 0
numTimesFound x list
  | x `notElem` list = 0
  | otherwise =
      let
        appearencesTable = map (\full@(first:_) -> (first, length full + 1)) . group . sort $ list
        appearencesOfX = snd $ head $ filter (\(elem, _) -> elem == x) appearencesTable
      in
        toInteger appearencesOfX

Personally, I think I take the cake for using Haskell features, but I also think that the intent of this code is hard to understand. One of my major gripes with it is that it's hard to tell what the appearencesTable actually is from the code - it's a list of tuples that gives you the number of times each element was found. For example, for the list [1, 1, 1, 2, 2, 3, 3, 3, 3, 4, 4, 5] the appearencesTable is [(1, 3), (2, 2), (3, 4), (4, 2), (5, 1)]. If you know that it's pretty easy to get what the rest of the code is trying to do, but it still does require quite a bit of study for such a trivial function.

I would greatly appreciate any help in improving the readability of this code.


texts: LW, MTD, STD, YTD Sales... all in line and looking pretty

texts:
That's Last Week, Month-to-Date, Season-to-Date, and Year-to-Date sales.

I have a table-valued function for each one, that takes a date and returns all CalendarDate values for the interesting time span:

dbo.CalendarDatesLW
dbo.CalendarDatesMTD
dbo.CalendarDatesSTD
dbo.CalendarDatesYTD

So I have a CTE for selecting YTD sales (where "year" runs from December to November):

with
    cteYTD (SalesRep, Category, Units, Amount) as (
        select
            sales.RepCode,
            sales.Category,
            sum(sales.TotalUnits),
            sum(sales.TotalNetAmount)
        from dbo.Sales sales
            inner join dbo.CalendarDatesYTD(getdate()) calendar on sales.InvoiceDate = calendar.CalendarDate
        group by
            sales.RepCode,
            sales.Category),

..then another for LW sales:

    cteLW (SalesRep, Category, Units, Amount) as (
        select
            sales.RepCode,
            sales.Category,
            sum(sales.TotalUnits),
            sum(sales.TotalNetAmount)
        from dbo.Sales sales
            inner join dbo.CalendarDatesLW(getdate()) lw on sales.InvoiceDate = lw.CalendarDate
        group by
            sales.RepCode,
            sales.Category),

...another for MTD sales:

    cteMTD (SalesRep, Category, Units, Amount) as (
        select
            sales.RepCode,
            sales.Category,
            sum(sales.TotalUnits),
            sum(sales.TotalNetAmount)
        from dbo.Sales sales
            inner join dbo.CalendarDatesMTD(getdate()) mtd on sales.InvoiceDate = mtd.CalendarDate
        group by
            sales.RepCode,
            sales.Category),

...and another for STD sales:

    cteSTD (SalesRep, Category, Units, Amount) as (
        select
            sales.RepCode,
            sales.Category,
            sum(sales.TotalUnits),
            sum(sales.TotalNetAmount)
        from dbo.Sales sales
            inner join dbo.CalendarDatesSTD(getdate()) std on sales.InvoiceDate = std.CalendarDate
        group by
            sales.RepCode,
            sales.Category)

..and they all individually run pretty much instantly (0-1 seconds each, execution plan isn't complaining about any would-be-missing index). Then I join them:

select
    ytd.SalesRep,
    ytd.Category,
    isnull(lw.Units,0) UnitsLW,
    isnull(lw.Amount,0) AmountLW,
    isnull(mtd.Units,0) UnitsMTD,
    isnull(mtd.Amount,0) AmountMTD,
    isnull(std.Units,0) UnitsSTD,
    isnull(std.Amount,0) AmountSTD,
    ytd.Units UnitsYTD,
    ytd.Amount AmountYTD
from cteYTD ytd
    left join cteSTD std on ytd.SalesRep = std.SalesRep
                        and ytd.Category = std.Category
    left join cteMTD mtd on ytd.SalesRep = mtd.SalesRep
                        and ytd.Category = mtd.Category
    left join cteLW lw on ytd.SalesRep = lw.SalesRep
                        and ytd.Category = lw.Category

That's 17 seconds, for 35 rows - and it gets exponentially worse if I start adding more columns in the group by ...and the execution plan looks very, very weird (although not surprising, given the script):

I'm querying dbo.Sales 4 times, grabbing a different time span each time, and then aggregating the same fields over and over. There has to be a better way of doing this... right?

dbo.Sales is a view, joining multiple FK's and implementing some business rules (e.g. such or such customer sales under category X should be reported under category Y).

My gut-feeling is that I'm abusing CTE's and should be using something else to do this. But what?


texts:
Going through a book, I encountered the following assignment:

  Write an application that asks for the user’s first, middle, and last names and
  replies with the user’s initials.

Are there any flaws you notice immediately? Is there any way this code can be improved? I'm not really interested in coding style (I guess someone is going to say that I should put those braces on the next line, but I like it this way).

import javax.swing.JOptionPane;

public class Program
{

private static String fullName;
private static String firstName;
private static String middleName;
private static String lastName;

private static char firstInitial;
private static char middleInitial;
private static char lastInitial;

public static void main(String[] args)
{
    start();
}

public static void start()
{
    greet();
    askInput();
    seperateFullName(fullName);
    getInitials(firstName, middleName, lastName);
    showResult();
}

// @formatter:off
private static void greet()
{
    int dialogResult = JOptionPane.showConfirmDialog(null,  "This program asks you for you first, middle and last name"
                            + " and gives back your initials.\nDo you want to continue?");

    if (dialogResult == JOptionPane.NO_OPTION)
    {
        JOptionPane.showMessageDialog(null, "Shutting down...", null, JOptionPane.WARNING_MESSAGE);
        System.exit(0);
    }

}

private static void askInput()
{
    fullName = JOptionPane.showInputDialog("Please enter your first, middle and last name.");
}

private static void seperateFullName(String fullName)
{
    try
    {
        int firstSpace = fullName.indexOf(" ");
        firstName = fullName.substring(0, firstSpace);
        int lastSpace = fullName.lastIndexOf(" ");
        middleName = fullName.substring(firstSpace + 1 , lastSpace);
        lastName = fullName.substring(lastSpace + 1, fullName.length());
    }
    catch (StringIndexOutOfBoundsException e)
    {
        JOptionPane.showMessageDialog(null, "Invalid input!", null,
                JOptionPane.WARNING_MESSAGE, null);
        start();
    }
}

private static void getInitials(String firstName, String middleName, String lastName)
{
    firstInitial = firstName.charAt(0);
    middleInitial = middleName.charAt(0);
    lastInitial = lastName.charAt(0);
}
// @formatter:on

private static void showResult()
{
    JOptionPane.showMessageDialog(null, "Your initials are: "
            + firstInitial + "." + middleInitial + "." + lastInitial + ".");
}
}


texts:
I have a very simple app which removes buttons and re-adds buttons to certain layouts when a button is clicked. The problem is this process is taking a very long time. How do I speed this process up?

red.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(final View v) {

                // Remove the clicked button from it's frame layout parent.
                    ViewManager p = (ViewManager) v.getParent();
                    p.removeView(v);
                    // Find another button randomly.
                    Random rng = new Random();
                    View v2;
                    do
                    {
                        int i = rng.nextInt(4);
                        v2 = buttons.get(i);
                    }
                    while (v2 == v); // Loop until you get a different button to swap with.
                    // Remove the other button from it's frame layout parent.
                    ViewManager p2 = (ViewManager) v2.getParent();
                    p2.removeView(v2);
                    // Now simply insert each button into the other buttons frame layout.
                    p.addView(v2, v2.getLayoutParams()); //Adding v2, the random button, into where v, the button clicked, was before(p)!
                    p2.addView(v, v.getLayoutParams()); //Adding v, the button clicked, into where v2, the random button, was before(p2)
                }
   }
       });

This code just gets another button from the other three (there are 4 buttons in total) randomly, and swaps the red button (the button clicked) with the random button.

The problem is this process is taking 3-4 seconds after being clicked How can I speed it up? I want it to appear as if the buttons have been swapped as soon as the red button is clicked.

Should I keep my approach but make it immediate after button click to make it faster?
Somehow change the properties of the buttons by swapping click listeners and images AND somehow being able to keep track of the NEW red button so that I can swap again.


texts:
I am writing a book database, and ultimately a library system, in Django. When a book is created without a title set, the ISBN will be used to automatically fetch book data from WorldCat I have just created a form to add new books to the database, but it has no real error-handling. Also, as I am new to Django, I suspect I have put a lot of my code in the wrong place.

Improving error-handling is my main incentive, but any other improvements would be welcome.

The form, in forms.py:

class AddBookForm(ModelForm):

    """docstring for AddBookForm"""

    class Meta:
        model = Book
        fields = ['isbn']

The form view, in views.py:

# This defines the navbar
pages = [['Search', '/'], ['Add Book', '/add']]

def add_book(request):
    if request.method == 'POST':
        # create a form instance and populate it with data from the request:
        form = AddBookForm(request.POST)
        # check whether it's valid:
        if form.is_valid():
            # process the data in form.cleaned_data as required
            addedBook = form.save()
    # if a GET (or any other method) we'll create a blank form
    else:
        form = AddBookForm()

    # Highlights navbar entry
    pages[1].append(True)
    context = {'pages': pages, 'form': form,}
    if 'addedBook' in locals():
        context['added'] = addedBook
    else:
        context['added'] = None
    return render(request, 'library/add.html', context)

The form template (add.html):

{% extends "library/base_site.html" %}
{% block title %}Add book{% endblock %}
{% block content %}
    {% if added %}

            <button type="button" class="close" data-dismiss="alert">
                &times;
                Close
            </button>
            Succesfully added book "{{ added.title }}" by {{ added.author }} - ISBN {{ added.isbn }}

    {% endif %}
    <form role="form" method="post" action=".">
        {% csrf_token %}

            Isbn
            <input id="id_isbn" class="form-control" maxlength="13" name="isbn" type="text" placeholder="Enter ISBN or scan barcode">

        <button type="submit" class="btn btn-default">Submit</button>
    </form>
{% endblock %}

The entire project is available on GitHub.


texts:
Does this adequately sanitize untrusted input for client side frontend templating where templates are otherwise trusted? What details remain to address or need reconsidering?
Please note the character substitutions are replacing less-than, greater-than, single and double quote, back-slash and the ampersand characters with look-alike characters of the same type which I do not expect in any circumstance to parse (or become parsable) as tag or attribute or encoding circumvention in any context of an HTML5 document. This follows, or more accurately attempts to follow, the OWASP replacement recommendations.
function sanitizer(str, i, list){
        return str + (this[i] ?? '').toString()
        .replace(/</g, '﹤')
        .replace(/>/g, '﹥')
        .replace(/'/g, '’')
        .replace(/"/g, '”')
        .replace(/&/g, '＆')
        .replace(/\//g, '／')
        ;
}
function sanitize(str, ...input){
        return str.map(sanitizer, input).join('');
}
function template(data){
        return sanitize`<div>${ data }</div>`;
}

Calling template('1<23') should render a HTMLDivElement with Text '1﹤23'.


texts:
I have finished a really short and small import / export script using Python 2.7, and now I would like to structure it using classes and methods where possible.

Could anybody give me some advice on what would be the best approach for this?

I haven't used any OOP because I would also like somebody to give me some best practices on how this should be done/structured.

from similarweb import ContentClient
import csv

FILE_OUT = 'similarweb/new_domains.csv'
FILE_IN = 'similarweb/domains.csv'

content_client = ContentClient("some_key")
final_result = ""

with open(FILE_IN, 'r') as csv_read_file:
    reader = csv.reader(csv_read_file)
    for i, line in enumerate(reader):
        url = ', '.join(str(e) for e in line)
        final_result += url + " " + (content_client.category(url)['Category']) + "\n"

with open(FILE_OUT, 'w') as csv_write_file:
    csv_write_file.write(final_result)


texts: dynamic programming solution for a string ending with 0, 1 or 2

texts:
A string that contains only 0s, 1s, and 2s is called a ternary string. Find a total ternary strings of length n that do not contain two consecutive 0s or two consecutive 1s.

I have defined a recurrence relation as dp[i][j] means the total number os trings ending with j where i is the length of the string and j is either 0, 1 or 2.

dp[i][0] = dp[i-1][1] + dp[i-1][2]

dp[i][1] = dp[i-1][0] + dp[i-1][2]

dp[i][2] = dp[i-1][1] + dp[i-1][2] + dp[i-1][1]

from collections import defaultdict

def end_with_x(n):
  dp = defaultdict(int)
  dp[1] = defaultdict(int)
  dp[1][0] = 1
  dp[1][1] = 1
  dp[1][2] = 1
  for i in range(2, n+1):
    dp[i] = defaultdict(int)
    dp[i][0] = dp[i-1][1] + dp[i-1][2]
    dp[i][1] = dp[i-1][0] + dp[i-1][2]
    dp[i][2] = dp[i-1][2] + dp[i-1][0] + dp[i-1][1]
  return dp[n][0] + dp[n][1] + dp[n][2]
print(end_with_x(2))


texts: Project Euler #12 in C++ - highly divisible triangular number

texts:
Project Euler Problem 12 asks (paraphrased):

  The nth triangular number Tn = 1 + 2 + … + n.  T7 = 28 has 6 divisors (1, 2, 4, 7, 14, 28).  What is the first Tn to have over 500 divisors?

After asking for some help on Stack Overflow, I've managed to write this code to solve it:

#include "stdafx.h"
#include <iostream>
#include <map>
//#include <algorithm>
#include <numeric>

int divisors (unsigned int num, std::map<int, int>& map)
{
    int orig_num = num;
    for(unsigned int i = 2; i <= num; ++i)
    {
        while (num % i == 0)
        {
            num /= i;
            ++map[i];
            //std::cout << map[i] << "\t";
        }
    }
    std::cout << orig_num << " = ";
    for(auto& iter:map)
        std::cout << iter.first <<  "^" << iter.second << " * ";
    return 0;
}

int overall_factors(unsigned int n)
{
    std::map <int, int> primefactors1, primefactors2;
    int no_of_divisors = 1;
    divisors(n,primefactors1);
    std::cout << std::endl;
    divisors(n+1,primefactors2);
    std::cout << std::endl;
    std::map<int, int> primefactors_triangle = std::accumulate( primefactors1.begin(), primefactors1.end(), std::map<int, int>(),
        []( std::map<int, int> &m, const std::pair<const int, int> &p )
    {
        return ( m[p.first] +=p.second, m );
    } );

    primefactors_triangle = std::accumulate( primefactors2.begin(), primefactors2.end(), primefactors_triangle,
        []( std::map<int, int> &m, const std::pair<const int, int> &p )
    {
        return ( m[p.first] +=p.second, m );
    } );

    for ( const auto &p : primefactors_triangle )
    {
        std::cout << "{ " << p.first << ", " << p.second << " } ";
        if (p.first == 2)
            no_of_divisors *= p.second;
        else
        no_of_divisors *= p.second+1;
    }

    std::cout << std::endl;
    return no_of_divisors;
}

int main()
{
    int i = 2;
    while (overall_factors(i) < 500)
    {
        std::cout << overall_factors(i) << std::endl;
        ++i;
    }
    return 0;
}

There're some pieces left that output debugging info to see that everything is working as intended. But overall, it doesn't work as fast as I want it to - or as fast as I expect a proper solution to a Project Euler problem to work.

How can this code be improved?  Clearly the program, as it is, now calculates primefactors for a given number twice.  What else is wrong and could be improved?

UPD: After I changed the while loop condition, the problem was solved rather quickly. Still, I believe my code is improvable.


texts: A One-Pass Hash Table Solution to twoSum

texts:
I read the guiding solution to twoSum in leetcodes ;

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

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

  Example:

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

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

  Approach 3: One-pass Hash Table
  It turns out we can do it in one-pass. While we iterate and inserting elements into the table, we also look back to check if current element's complement already exists in the table. If it exists, we have found a solution and return immediately.

and mimic a python solution

class Solution:
    def twoSum(self, nums, target) -> List[int]:
        """
        :type nums: List[int]
        :type target: int
        """
        nums_d = {}

        for i in range(len(nums)):
            complement = target - nums[i]

            if nums_d.get(complement) != None: #Check None not True Value
                return [i, nums_d.get(complement)]
            nums_d[nums[i]] = i    #produce a map
        return []

Unfortunately, my solution is only faster than 81%, which I thought was a best solution.

  Runtime: 40 ms, faster than 81.00% of Python3 online submissions for Two Sum.
  Memory Usage: 14.3 MB, less than 5.08% of Python3 online submissions for Two Sum.
  Next challenges:

How could continue to improve the code, and I am curious about the approaches of the top 20%.


texts: Lock free MPMC Ring buffer implementation in C

texts:
I have written a lock free MPMC FIFO in C based on a ring buffer. It uses gcc's atomic built-ins to achieve thread safety. The queue is designed to return -1 if it's full on enqueue or empty on dequeue.

After some feedback, I've changed by design. I have tested this code to work, but testing multithreaded code is hardly enough to prove it's correct.

struct queue
{
    void** buf;
    size_t num;
    uint64_t writePos;
    uint64_t readPos;
};

queue_t* createQueue(size_t num)
{
    struct queue* new = xmalloc(sizeof(*new));
    new->buf = xmalloc(sizeof(void*) * num);
    memset(new->buf, 0, sizeof(void*)*num);
    new->readPos = 0;
    new->writePos = 0;
    new->num = num;
    return new;
}

void destroyQueue(queue_t* queue)
{
    if(queue)
    {
        xfree(queue->buf);
        xfree(queue);
    }
}

int enqueue(queue_t* queue, void* item)
{
    for(int i = 0; i < kNumTries; i++)
    {
        if(__sync_bool_compare_and_swap(&queue->buf[queue->writePos % queue->num], NULL, item))
        {
            __sync_fetch_and_add(&queue->writePos, 1);
            return 0;
        }
    }
    return -1;
}

void* dequeue(queue_t* queue)
{
    for(int i = 0; i < kNumTries; i++)
    {
        void* value = queue->buf[queue->readPos % queue->num];
        if(value && __sync_bool_compare_and_swap(&queue->buf[queue->readPos % queue->num], value, NULL))
        {
            __sync_fetch_and_add(&queue->readPos, 1);
            return value;
        }
    }
    return NULL;
}

(link to the previous iteration)


texts: Minimum sum of elements, taken 2 at a time

texts:
Update:
I had not recalled the question correctly and ended up with the wrong question. I have now updated the question and the solution:

The question is:
Given an array of integers say [8,4,6,12,10]
You can pop any two elements at a time and place the sum (chosen sum) back into the array.
Repeating until a single element (final sum) is remaining.
The task is to minimize the sum of these chosen sums in the end.

My approach is:

Pop the two elements with lowest value in the array, push the sum back.
Repeat this until a single element is remaining.
Maintain a sums, which maintains the running sum

My solution is as follows:

  Sort the array
  Pop first two elements, add them, get the sum
  Place the sum in the array in such a way that it remains sorted (to avoid sorting again)
  Repeat steps 2 and 3 until we have less than two elements in the array

JavaScript Code:

  function join(parts, sums) {
  if(parts.length < 2) {
    return sums
  }
  sum = parts[0] + parts[1]
  sliced = parts.slice(2)
  placed = place(sliced, sum)
  sums = sums + sum
  return join(placed, sums)
}

function place(arr, x) {
  index = 0
  for(i=0;i<arr.length;i++) {
    if(arr[i]>x) {
     index = i
     break
    }
  }
  first = arr.slice(0,i)
  second = arr.slice(i)
  return [...first,x,...second]
}
function process(parts) {
  parts.sort((a,b)=>a>b)
  return join(parts, 0)
}
process([8,4,6,12,10])

Is this best possible approach? Can you think of any better optimized approach?

Update:
The complexity is O(nlog n) (sort - best case) + O(n)

As pointed out in the comments, the ideal solution would be to use a priority queue:
https://www.geeksforgeeks.org/minimize-the-sum-calculated-by-repeatedly-removing-any-two-elements-and-inserting-their-sum-to-the-array/


texts: Iterator-like interface for extracting records from a blob

texts:
I have a blob whose format is something like:

(id1,key1,value1)(id2,key2,value2)....

where id is a uint32_t, and key and value are null-terminated strings. I am looking for an iterator-like interface that will extract records from the blob.

This is what I have come up with:

typedef struct blob_ {
    uint32_t size;  // length of the buffer
    char buf[];
}blob;

typedef struct record_ {
    uint32_t id;    // id
    char *key;      // pointer to key in the blob
    char *value;    // pointer to value in the blob
    char *next;    // pointer to where the next record starts
} record;

static record
get_next_obj(const char* begin, const char* end)
{
    record obj;
    if (begin == end) {
        obj.id = 0;
        obj.key = NULL;
        obj.value = NULL;
        obj._next = NULL;
    } else {

        memcpy(&obj.id, begin, sizeof(uint32_t));
        begin += sizeof(uint32_t);

        obj.key = begin;
        while(begin < end && *begin != '\0')
            ++begin;

        ++begin;

        obj.value = begin;
        while(begin < end && *begin != '\0')
            ++begin;
        ++begin;

        obj.next = begin;
    }
    return obj;
}

record
blob_list_next(const blob *data, const record *prev)
{
    const char *begin, *end;

    begin = prev->next;
    end = data->buf + data->size;

    return get_next_obj(begin, end);
}

record
blob_list_begin(const blob *data)
{
    const char *begin, *end;

    begin = data->buf;
    end = data->buf + data->size;
    return get_next_obj(begin, end);
}

record
blob_list_end(const blob *data)
{
    record obj;
    obj.id = 0;
    obj.key = NULL;
    obj.value = NULL;
    obj.next = NULL;
    return obj;
}

Then the API will be accessed with something like this:

record obj;
record obj_end;
// comp is a comparison operator of two record objects
for (obj = blob_list_begin(data), obj_end = blob_list_end(data);
    comp(obj, obj_end) == false; obj = blob_list_next(data, &obj))  {
   // access the obj
}

I used return-by-value semantics because I wanted to avoid calling malloc(). There will be a maximum of 4096 records in a tuple.


texts:
I'm implementing a Mediator and I'd like to simplify the callback notation a bit.

My mediator has Register and Notify methods :

public class Mediator {
    private Dictionary<Messages, Action<object>> registeredCallback;

    public void Register(Messages message, Action callback) {
        registeredCallback[message] = callback;
    }

    public void Notify(Messages message, object parameter) {
        callback(parameter);
    }

    public Mediator() {
        registeredCallback = new Dictionary<Messages, Action<object>>();
    }
}

It uses a Messages enumerator to sanitize events between registered objects, for example :

public enum Messages {
    UserCreated,
    UserDeleted,
    UserChangedPassword
};

So far, so good. However, when I use this mediator I'm making ugly callback definitions :

mediator.Register(Messages.UserCreated, (object user) => GreetUser(((User)user).name));

with the following User:

public class User {
    public string name;
}

Type casting? Lambda expressions? This looks obviously filthy. How can I clean this up? Is my architecture at fault?


texts: Handling with the 'error' parameter inside a callback function in node.js

texts:
I have multiple controllers and every controller has this error handler:

if (error) {
  res.render('error', {
     error: error
  });
}

Sometimes I have more than one:

exports.update = function(req, res, next) {
    MyModel.findById(req.params.id, function(error, event) {
        if (error) {
            res.render('error', {
                error: error
            });
        }
        else {
            event['active'] === false ? event['active'] = true : event['active'] = false;

            event.update({
                'active': event['active']
            }, function(error) {
                if (error) {
                    res.render('error', {
                        error: error
                    });
                }
                else {
                    res.end('Success!');
                }
            });
        }
    });
};

I have more than 30 controllers and this seems like an inefficient way of handling.


texts: Console calculator, takes a string as input (like: 2+3*4-1+3) and outputs the result

texts:
I am a beginner programmer(solo learning). I know the basics of c/c++, but I would not consider myself too experienced. Recently I decided to make this calculator which takes an array of characters as input and then decodes the operations. I would like to know if I can improve it in any way and an overall review.

#include <iostream>
#include <string.h>
#include <stdio.h>
using namespace std;

int main()
{
    char v[20];
    int sign, n, i;
    float result, nr, aux, c;
    while (1)
    {
        cout << "insert the expression:" << endl;
        scanf("%s", v);
        n = strlen(v);
        result = 0, nr = 0, aux = 0, c = 0;
        sign = 1, n, i = 0;
        while (i<n)//loops only once through the array
        {
            while (v[i] >= '0'&&v[i] <= '9')//builds the number
            {
                nr = nr * 10 + (v[i] - '0');
                i++;
            }
            switch (v[i])//identifies the operations
            {
            case '+': {

                if (!(v[i - 1] == '*') && !(v[i - 1] == '/'))//if a*-b or a/-b occurs it does nothing
                {
                    if (c == 1)// * was found before: 2*2+1
                    {
                        result += aux*nr*sign;// updates the end result
                        aux = 0;//aux is reseted
                    }
                    else if (c == 2)// / was found before: 2/2+1
                    {
                        result += aux / nr*sign;
                        aux = 0;
                    }
                    else
                    {
                        result += nr*sign;
                    }
                    nr = 0;
                    c = 0;
                }

                sign = 1;

                break;
            }
            case '-': {
                if (!(v[i - 1] == '*') && !(v[i - 1] == '/'))
                {
                    if (c == 1)
                    {
                        result += aux*nr*sign;
                        aux = 0;
                    }
                    else if (c == 2)
                    {
                        result += aux / nr*sign;
                        aux = 0;
                    }
                    else
                    {
                        result += nr*sign;
                    }
                    c = 0;
                    nr = 0;
                }
                sign = -1;
                break;
            }
            case '*': {
                if (!aux)
                {
                    aux = nr*sign; // aux hold the result from * and / operations
                }
                else if (c == 2)
                {
                    aux /= nr*sign;
                }
                else
                {
                    aux *= nr*sign;
                }
                c = 1;
                nr = 0;
                sign = 1;
                break;
            }
            case '/': {
                if (!aux)
                {
                    aux = nr * sign;
                }
                else if (c == 1)
                {
                    aux *= nr*sign;
                }
                else
                {
                    aux /= nr*sign;
                }
                c = 2;
                nr = 0;
                sign = 1;
                break;
            }
            default:;
            }
            if (i >= (n - 1))// updates the result because there is no + or - at the end of the string.
            {
                if (c == 1)
                {
                    result += aux*nr*sign;
                }
                else if (c == 2)
                {
                    result += aux / nr*sign;
                }
                else
                {
                    result += nr*sign;
                }
            }
            i++;
        }
        cout << "=" << result << endl;
        system("pause");
        system("cls");

    }

}


texts: Save handler without a nested "deferred antipattern"

texts:
I have an application in which a user makes a change, and when they click Save they will be prompted to confirm, and the appropriate REST call will be made if they agree. The intial call to Save() returns a promise that is fulfilled if the call returned successfully, or rejected if there was an error or the user canceled the confirmation.

I've boiled my actual implementation down to an equivalent example in order to highlight the (anti)pattern:

//assume confirm() and commit() are functions that return a promise:
//confirm() will be fulfilled or rejected based on a user choice
//commit() will be fulfilled or rejected based on the response from a RESTful web call

function save() {
    var deferred = $q.defer();

    confirm().then(function(response) {
        commit().then(function(response) {
            deferred.resolve();
        }).catch(function(rejection) {
            deferred.reject(rejection);
        });
    }, function(rejection) {
        deferred.reject(rejection);
    });

    return deferred.promise;
};

This stuck out to me rather clearly as the deferred antipattern, and so I refactored it to this:

function save() {
    var deferred = $q.defer();

    confirm().then(function(response) {
        deferred.resolve(commit());
    }, function(rejection) {
        deferred.reject(rejection);
    });

    return deferred.promise;
};

Subsequently, it still looked like the deferred antipattern, and after a little while of thinking and Googling, I reduced it to this:

function save() {
    return confirm().then(function(response) {
        return commit();
    }, function(rejection) {
        return $q.reject(rejection);
    });
};

Now, that looks pretty good to me, but I'm not sure if it's as good as it can be. All three versions above are functional, but is there perhaps a fourth iteration that would reduce it even further, or is this the simplest form for this depth of promises?

I've created a fiddle here for anyone who may want to see it in action.


texts: Parsing notes saved in text file to a dictionary

texts:
I have a script that allows me to open and view the general notes I save at work and studies. I have this particular function, and I am afraid it will become overwhelming. How should I approach this?

The purpose of the function is to parse summary information into a JSON and record stats like last modified, times viewed, date created, etc. So I can organise the notes with this information and ignore the file contents.

def note_component(note_lines):
    """ Creates the new note data structure.
        Here is where one would add more note information.

    :param list[str] note: containing a single note.
    :return: the dict note element.
    """
    sections = get_sections(note_lines)
    contents = get_contents(note_lines)

    # This loops through multiple notes
    note_component = {}
    for heading, content in zip(sections, contents):
        heading = save_text(heading, content)

        note_component[heading] = {
            'timestamp': None,
        }

        note_component[heading]['timestamp'] = 'now'

        description = note_description(content)
        if description:
            note_component[heading]['description'] = description

        tags = note_tags(content)
        if tags:
            note_component[heading]['tags'] = tags

    return note_component

A typical note contains markup that allows the rest of the script to identify which parts belong where. Here is a typical note:

# the_title
==============
:Describe the note to me

Contents.
 - further point

On a final note!

{tag} {code} {review}
==============

So this note will be passed into the note_component function in the form of a list of strings:

note_lines = [
    '# the_title',
    '==============',
    ':Describe the note to me',
    '',
    'Contents.',
    ' - further point',
    '',
    '',
    'On a final note!',
    '',
    '{tag} {code} {review}',
    '=============='
]

Here are the functions used in note_component:

def get_sections(note):
    # Section parsing needs improvement (regex)
    _sections = [line[2:] for line in note if line[:2] == '# ']
    return _sections

def note_description(content):
    # Needs to return multiple descriptions (sectioning)
    description = content[1]
    if description and description[0] == ':':
        return description
    return None

def save_text(heading, content):
    """ This saves the note as a text file.
    :param heading: (string) the heading of the note used as filename.
    :param content: (list) containing the lines of the note.
    """
    heading = unique_note(heading)

    text_string = '\n# {heading}\n'.format(heading=heading)
    text_string += '\n'.join(content)

    name_note = NOTES.format(
        note_name=heading
    )

    with open(name_note, 'w') as save_txt:
        save_txt.write(text_string)

    return heading

def unique_note(heading):
    saved_notes = [filename for filename in os.listdir(NOTE_DIR)]

    suffix = 0
    if '{heading}.txt'.format(heading=heading) in saved_notes:
        while '{}_{}.txt'.format(heading, str(suffix)) in saved_notes:
            suffix += 1

        new_name = '{}_{}'.format(heading, str(suffix))
        heading = new_name

    return heading

def note_tags(contents):
    tag_line = contents[-2]

    if tag_line and '{' in tag_line:
        tags = [tag[1:-1] for tag in tag_line.split(' ') if tag]
        return tags
    return None

def pairwise(iterable):
    a = iter(iterable)
    return zip(a, a)

def get_contents(note):
    content_index = [
        index
        for index, line
        in enumerate(note)
        if line[:2] == '=='
    ]

    content_list = []
    indexes = pairwise(content_index)

    for start, end in indexes:
        content = note[start:end+1]
        content_list.append(content)

    return content_list

Please excuse the missing doc-strings.

My biggest concerns are, how should I approach this function to make it easy to test, and easy to expand information stored note_component with out losing readability?

I think I also need to improve my distinctions in variable names.


texts: hand optimising javascript selector function

texts:
I personally want a small selector function that covers the three common cases

getElementById
getElementsByClassName
getElementsByTagName

It should support contexts and should not support querySelectorAll since <opinionated> QSA is slow as hell and should be avoided </opinionated>

I have an implementation of such a function

function select(selector, context) {
    var c = selector.charAt(0),
        method;

    if (c === "#") {
        method = "getElementById";
        selector = selector.substring(1);
    } else if (c === ".") {
        method = "getElementsByClassName";
        selector = selector.substring(1);
    } else {
        method = "getElementsByTagName";
    }

    return (context || document)[method](selector);
}

And I have a benchmark.

As can be seen it's still a factor of 4 away from native support.

Can I hand optimise this further? And if so, how?