texts: Utilizing std::map and std::array for displaying a modulus grid

texts:
I've written a modulus-type program (using std::vector).  The user inputs a number, and the program displays a modulus grid pertaining to that number.

This is what it looks like (example program output with 12):

(0)  12 24  36  48  60  72  84  96  108  120
(1)  13  25  37  49  61  73  85  97  109  121
(2)  14  26  38  50  62  74  86  98  110  122
(3)  15  27  39  51  63  75  87  99  111  123
(4)  16  28  40  52  64  76  88  100  112  124
(5)  17  29  41  53  65  77  89  101  113  125
(6)  18  30  42  54  66  78  90  102  114  126
(7)  19  31  43  55  67  79  91  103  115  127
(8)  20  32  44  56  68  80  92  104  116  128
(9)  21  33  45  57  69  81  93  105  117  129
(10)  22  34  46  58  70  82  94  106  118  130
(11)  23  35  47  59  71  83  95  107  119  131
(12)  24  36  48  60  72  84  96  108  120  132

Now, I've decided to make it nicer by using std::map and std::array.  I get the same output as before, but with the same alignment issues (fixing those could complicate my display function).

Is this an effective use of these containers (and am I using them correctly)?  If not, what other containers could be used instead?  I'm using std::array instead of std::vector here because I'm keeping the number of columns (array size) at 10.

#include <iostream>
#include <map>
#include <array>

const unsigned NUM_ARR_ELEMS = 10;

std::map<unsigned, std::array<unsigned, NUM_ARR_ELEMS>> getModGrid(unsigned);
void displayModGrid(const std::map<unsigned, std::array<unsigned, NUM_ARR_ELEMS>>&);

int main()
{
    std::map<unsigned, std::array<unsigned, NUM_ARR_ELEMS>> modGrid;
    unsigned mod;

    std::cout << "\n\n> Mod: ";
    std::cin >> mod;

    std::cout << std::endl << std::endl;
    modGrid = getModGrid(mod);
    displayModGrid(modGrid);

    std::cout << std::endl << std::endl;
    std::cin.ignore();
    std::cin.get();
}

std::map<unsigned, std::array<unsigned, NUM_ARR_ELEMS>> getModGrid(unsigned mod)
{
    std::map<unsigned, std::array<unsigned, NUM_ARR_ELEMS>> modRow;
    std::array<unsigned, NUM_ARR_ELEMS> modValues;

    for (unsigned modIter = 0; modIter <= mod; ++modIter)
    {
        for (unsigned arrIter = 0; arrIter < NUM_ARR_ELEMS; ++arrIter)
            modValues[arrIter] = modIter + (mod * (arrIter+1));

        modRow[modIter] = modValues;
    }

    return modRow;
}

void displayModGrid(const std::map<unsigned, std::array<unsigned, NUM_ARR_ELEMS>> &modGrid)
{
    for (auto rowIter = modGrid.cbegin(); rowIter != modGrid.cend(); ++rowIter)
    {
        std::cout << "  (" << rowIter->first << ")  ";

        for (auto colIter = rowIter->second.cbegin(); colIter != rowIter->second.cend(); ++colIter)
        {
            std::cout << *colIter << "  ";
        }

        std::cout << std::endl;
    }
}


texts:
I'm trying to create a component that receives an array, this component is going to show a list with props data
const Mesas = [{
      id: 1,
      valor: 500,
      produtos:['COCA COLA', 'FANTA']
    },{
      id: 2,
      valor: 100,
      produtos:['PRATO1', 'PRATO2']
    }]
const App = () => {
    return (<ListaMesas mesas = {{...Mesas}} />)
}

The component:
class mesas extends Component {
    render(){
        const mesas = [this.props.mesas]
        mesas.map(function(item){
           return(
               <div key ={item.id}>
                   <text>{item.id}</text>
               </div>
           )
        })
        return(
            <div>
                {mesas}
            </div>
        )
    }
}

What is the best way to do this list?


texts: Parsing a string containing arithmetic operations in prefix notation

texts:
This is a piece from the complete program.
What it does is parses mathematical expressions of the form (+(*3,x),5) to 3*x + 5 and store it in an object of class Formula. Add,Mul, Div, Exp, X, Integer and Symbols are derived from Formula class. Recursive strategy has been used to parse formulae with greater complexity.

Please request for any other piece of code if required.

Does this code have redundancy? How can it be improved?

void parse(Formula*& f, string s, int &k)
{
    if(s[k] == '(')
    {
        k++;
        if(s[k] == '+')
        {
            f = new Add();
        }
        else if(s[k] == '/')
        {
            f = new Div();
        }
        else if(s[k] == '-')
        {
            f = new Sub();
        }
        else if(s[k] == '*')
        {
            f = new Mul();
        }
        else
        {
            f = new Exp();
        }

        k++;
        parse(f->left, s, k);
        k = k + 2;
        parse(f->right, s, k);
        k++;
    }
    else
    {
        if(s[k] == 'x')
        {
            X* a = new X();
            f = a;
        }
        else if(48 <= s[k] <= 57)
        {
            Integer* a = new Integer();
            a->i = s[k] - 48;
            f = a;
        }
    }
}


texts: Extracting an XML config file from ZIP file and parsing it

texts:
I am currently working with an app that should load various info on a very specific zip file which contains the XML config file, using the DotNetZip library on C#, here's the code:

        public static void InitializeData(string configFilePath)
    {
        if (File.Exists(configFilePath))
        {
            using (ZipFile zip1 = ZipFile.Read(configFilePath))
            {
                zipEntriesCount = zip1.Count;
                if (zip1.ContainsEntry(installConfigFileName))
                {
                    var entries = zip1.SelectEntries(installConfigFileName);
                    ZipEntry[] entriesArray = new ZipEntry[entries.Count];
                    entries.CopyTo(entriesArray, 0);
                    entriesArray[0].Extract(installConfigStream);
                    installConfigData = StreamToString(installConfigStream);
                    XmlDocument xmlDoc = new XmlDocument(); // Create an XML document object
                    xmlDoc.Load(installConfigStream); // Load the XML document from the specified file

                    // Get elements
                    XmlNodeList XmlAppTitle = xmlDoc.GetElementsByTagName("appTitle");
                    XmlNodeList XmlAppCompany = xmlDoc.GetElementsByTagName("appCompany");
                    XmlNodeList XmlAppIconPath = xmlDoc.GetElementsByTagName("appIconPath");
                    XmlNodeList XmlAppLargeIconPath = xmlDoc.GetElementsByTagName("appLargeIconPath");

                    // Store app config data globally
                    // eg: globalVar = XmlVar[0].InnerText;
                    appTitle = XmlAppTitle[0].InnerText;
                    appCompany = XmlAppCompany[0].InnerText;
                    appIconPath = XmlAppIconPath[0].InnerText;
                    appLargeIconPath = XmlAppLargeIconPath[0].InnerText;
                }
            }
        }
    }

My question is, is there any better/more compact way of reaching same functionality?


texts: JQuery UI Datepicker with beforeShowDay function

texts:
I am relatively new to JavaScript and JQuery. I wanted a Datepicker that has the following functionality:

Weekends are not selectable
Non working days (bank holidays etc.) are not selectable
The first selectable day must be x number of full working days in the future, taking into account bank holidays and weekends

I looked at few examples and came up with this (the date format is dd/mm):

$(function() {

  var holidays= [[3,1], [22,4], [25,4], [29,4], [2,5], [30,5], [29,8], [26,12], [27,12]];

  var workingDayOffset = 10, selectedDate = new Date();

  function nonWorkingDays(date) {
    for (var j = 0; j < holidays.length; j++) {
      if (date.getMonth() == holidays[j][1] - 1 && date.getDate() == holidays[j][0]) {
        return [false, ''];
      }
    }
  return [true, ''];
  }

  function beforeCurrentDate(date) {
   if(date.getDate() === selectedDate.getDate() && date.getMonth() === selectedDate.getMonth() && date.getFullYear() === selectedDate.getFullYear())
   {
    return [true, ''];
   }
   return [date < selectedDate,''];
  }

  function nonAvailableDays(date) {
    var noWeekend = $.datepicker.noWeekends(date), before = beforeCurrentDate(date), holiday = nonWorkingDays(date);
    return [noWeekend[0] && before[0] && holiday[0], ''];
  }

  for(var i = 0; i < workingDayOffset; i++) {
    selectedDate.setDate(selectedDate.getDate() + 1);
    if(!nonAvailableDays(selectedDate)[0])
    {
      i--;
    }
  }

  Date.prototype.formatDDMMYY=function(){
    var dd = this.getDate(), mm = this.getMonth()+1, yyyy = this.getFullYear();
    if(dd<10){
      dd = '0' + dd;
    }
    if(mm<10){
      mm = '0'+ mm;
    }
  return String(dd + "\/" + mm + "\/" + yyyy);
  };

  $( "#datepicker" ).val(selectedDate.formatDDMMYY());

  $( "#datepicker" ).datepicker({ beforeShowDay: nonAvailableDays, dateFormat: 'dd/mm/yy', showOn: 'button', buttonText: "select", defaultDate: selectedDate,gotoCurrent: true}) ;
});

I am looking for a general critique of the code, but also there are a couple of things that I thought would be easier / cleaner:

In beforeCurrentDate I wanted to do a check that the date was less than selectedDate, in terms of the whole date, not including the time component. Using date > selectedDate would return false even if the date component was the same, due to the time part.  I thought about setting the time on the selected date, but then GMT offset came into play. It seemed to me that it should be easier, in the end I added a fudge that check just the date components for a match.
I am not sure adding Date.prototype.formatDDMMYY is the right way to go.  Again, this felt like it should be more straight forward.

I am interested to hear your thoughts on this.


texts:
What improvements can I make to the following Pig Latin translator? So far, I've been wondering about the FlexibleInstances declaration, but I can't think of how to remove it (since it's required for PigLatin String in instances, which is required for me to use " " in the Monoid instance; I need the extra type argument for Functor).

{-# LANGUAGE FlexibleInstances #-}

import Control.Monad(when)
import Data.Char (toLower, toUpper)
import System.IO (hFlush, stdout)

data PigLatin a = PigLatin a

instance Monoid (PigLatin String) where
  mempty = PigLatin ""
  mappend (PigLatin a) (PigLatin b) = PigLatin $ a ++ " " ++ b

instance Functor PigLatin where
  fmap f (PigLatin x) = PigLatin $ f x

instance Show (PigLatin String) where
  show (PigLatin s) = s

data English a = English a
  deriving (Eq)

safeTail :: [a] -> [a]
safeTail (_:xs) = xs
safeTail [] = []

quitCommand :: English String
quitCommand = English "\\q"

wordToPig :: English String -> PigLatin String
wordToPig (English word@(x:_)) = PigLatin $ if isVowel x
                                              then word ++ "yay"
                                              else rearrangedWord ++ "ay"
    where rearrangedWord = drop (length initialConsonants) word ++ initialConsonants
          initialConsonants = takeWhile isConsonant word
          isConsonant = not . isVowel
wordToPig (English "") = PigLatin ""

isVowel :: Char -> Bool
isVowel letter = letter `elem` ['a', 'e', 'i', 'o', 'u']

englishWords :: English String -> [English String]
englishWords (English input) = map English $ words input

sentenceToPig :: English String -> PigLatin String
sentenceToPig = fmap (capitalize . safeTail . map toLower) . foldl mappend mempty . map wordToPig . englishWords

capitalize :: String -> String
capitalize (x:xs) = toUpper x : map toLower xs
capitalize [] = ""

prompt :: String -> IO (English String)
prompt promptInput = do
  putStr promptInput
  hFlush stdout
  input <- getLine
  return $ English input

main :: IO ()
main = do
    input <- prompt "> "
    when (input /= quitCommand) $ do
      print $ sentenceToPig input
      main


texts: Measure durations using a calendar table

texts:
For a report, I have, among other things, to count the amount of days between two dates on the same entry and group them by month.

select year(calendar.db_date), month(calendar.db_date), count(calendar.db_date)
FROM hospitalizacion
JOIN calendar
  ON calendar.db_date >= fecha_ingreso
     AND calendar.db_date <= case when fecha_alta is null then now() else fecha_alta end
where (habitacion regexp "[0-9]{3}" or habitacion like "UCI%")
group by year(calendar.db_date), month(calendar.db_date);

This will create a row for each day between the check-in and check-out. Now the join is a performance killer. I've removed everything but the join and can't seem to improve the query times using MariaDB. Using equal instead of less/more than makes the query much faster, since it doesn't do comparisons.

This is the create query for the table

CREATE TABLE `hospitalizacion` (
  `IdEncuentro` int(10) unsigned NOT NULL,
  `habitacion` varchar(5) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
  `fecha_ingreso` date NOT NULL,
  `fecha_alta` date DEFAULT NULL,
  PRIMARY KEY (`IdEncuentro`),
  KEY `fecha_alta_idx` (`fecha_alta`),
  KEY `fecha_ingreso_idx` (`fecha_ingreso`),
  KEY `hosp_fecha_ingresoidx` (`fecha_ingreso`),
  KEY `hosp_fecha_altaidx` (`fecha_alta`),
  KEY `hosp_habitacionidx` (`habitacion`),
  KEY `habitacion_idx` (`habitacion`),
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci

The calendar table:

CREATE TABLE `calendar` (
  `id` int(11) NOT NULL,
  `db_date` date NOT NULL,
  `year` int(11) NOT NULL,
  `month` int(11) NOT NULL,
  `day` int(11) NOT NULL,
  `quarter` int(11) NOT NULL,
  `week` int(11) NOT NULL,
  `day_name` varchar(9) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
  `month_name` varchar(9) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
  `holiday_flag` char(1) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT 'f',
  `weekend_flag` char(1) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT 'f',
  `event` varchar(50) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `td_ymd_idx` (`year`,`month`,`day`),
  UNIQUE KEY `td_dbdate_idx` (`db_date`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4

This is the explain:

id  select_type table   type    possible_keys   key key_len ref rows    Extra
1   SIMPLE  hospitalizacion ALL fecha_ingreso_idx,hosp_fecha_ingresoidx,hosp_habitacionidx,habitacion_idx   [NULL]  [NULL]  [NULL]  28,218  Using where; Using temporary; Using filesort
1   SIMPLE  calendar    index   td_dbdate_idx   td_dbdate_idx   3   [NULL]  736,625 Using where; Using index; Using join buffer (flat, BNL join)


texts: Assigning default values to function arguments which may be "empty"

texts:
In perl, is there a canonical practice or idiom for assigning value to an argument which, if "empty", is assigned a default value?

Here, "empty" is defined as an argument value which is either undef or the null string (''). Notably, 0 (or perl false) is a valid, non-"empty" value, which rules out the construction $min_perl_version = (shift ||= '5.008009').

This is my current construction (note the use of the v5.10+ logical-or operator, //):

my $min_perl_version = do {$_ = shift // q{}; (length) ? $_ : '5.008009'};

as in the example function:

sub is_CORE { # ( $:MIN_PERL_VERSION , $:MODULE )
    use 5.008009; # perl v5.8.9; required for Module::CoreList to be available in CORE
    my $min_perl_version = do {$_ = shift // q{}; (length) ? $_ : '5.008009'}; # "empty" => default to version 5.008009
    my $module = shift;
    return ($Module::CoreList::VERSION >= 2.99) && Module::CoreList::is_core($module, undef, $min_perl_version);
}

I don't want warnings or to duplicate the use of the default value.

Is there a simpler / more elegant solution, say... without a named temporary variable?

A succinct solution which is functional back to earlier perl versions (5.6 or 5.8) would be a plus as well.

edit: for clarity

For clarification, the function interface and definition of argument validity (eg, what "empty" means) are set constants. While I appreciate any critique, a conversation about the line:

my $min_perl_version = do {$_ = shift // q{}; (length) ? $_ : '5.008009'};

and how it might be better coded is the real point of the question.


texts: BigInteger class, supporting addition only

texts:
Here is just addition, no multiplication or subtraction, but I will implement them later. Before going on, I'm here to ask for advice about the design.

#pragma once
#include <stdlib.h>
#include <crtdbg.h>
#include "stdafx.h"
#include <string>
#include <iostream>
#include <vector>
#include <cassert>
#include <algorithm>
#define to_int(x) (x - '0')
#define to_char(x) (char)(x + '0')
struct InvalidBigInt {};
class BigInteger
{
private:
    std::vector<char> vnum;
    std::string snum;
public:
    static bool flag;
    BigInteger() = default;
    BigInteger(const std::vector<char>& v) : vnum(v) {}
    BigInteger(std::string&& str) : snum(str)
    {
        vnum.clear();
        vnum = { str.crbegin(), str.crend() };
        try
        {
            if (std::find_if(str.begin(), str.end(),
                [](char c) { return !(isdigit(c)); }) != str.end())
            {
                throw InvalidBigInt();
            }
        }
        catch (InvalidBigInt)
        {
            std::cout << "*****************      Input invalid integer      *****************" << std::endl << \
                "*****************      Please input again         *****************" << std::endl;
        }
        flag = true;
    }
    friend std::ostream& operator<<(std::ostream& out, BigInteger bi)
    {
        std::for_each(bi.vnum.rbegin(), bi.vnum.rend(), [&](char c) {out << c; });
        return out;
    }
    BigInteger operator+(BigInteger b)
    {
        std::string result;
        auto more = b.vnum.size() >= this->vnum.size() ? b.vnum : this->vnum, less = b.vnum.size() < this->vnum.size() ? b.vnum : this->vnum;
        int temp = 0, digit = 0, diff = more.size() - less.size();
        for (size_t i = 0; i < diff; i++) { less.push_back('0'); }
        for (auto IteratorMore = more.begin(), IteratorLess = less.begin();
            IteratorMore < more.end() && IteratorLess < less.end();
            IteratorMore++, IteratorLess++)
        {
            digit = to_int(*IteratorMore) + to_int(*IteratorLess) + temp;
            if (digit > 9) { temp = 1; digit -= 10; }
            else { temp = 0; }
            result = to_char(digit) + result;
        }
        if (temp) { result = to_char(temp) + result; }
        return BigInteger(std::move(result));
    }
    bool operator==(BigInteger b)
    {
        return this->vnum == b.vnum;
    }
    ~BigInteger() noexcept {}
};
bool BigInteger::flag{ false };

int main()
{
    /*********************************PLUS*******************************/
    {
        assert(BigInteger("0") + BigInteger("0") == BigInteger("0"));
        assert(BigInteger("0") + BigInteger("1") == BigInteger("1"));
        assert(BigInteger("1023") + BigInteger("1") == BigInteger("1024"));
        assert(BigInteger("987") + BigInteger("34") == BigInteger("1021"));
        assert(BigInteger("98765") + BigInteger("23456") == BigInteger("122221"));
        assert(BigInteger("9230842083418927893758317489127418924781923748912") + BigInteger("81923743214617823686412783461237846178463")
            == BigInteger("9230842165342671108376141175540202386019769927375"));
    }
}


texts:
C++17 have <charconv>. However this header does not work on MacOS - It compiles, but can not link. Same header is not present in MSVS. The header also missing from my Arm Linux, even my gcc compiler there supports C++17 as well.

Following is a take to convert non terminated char array (e.g. buffer, string_view etc) into signed or unsigned integer.

I probably will use the code in production, once I do some more tests.

#include <limits>
#include <type_traits>
#include <string_view>
#include <utility>

namespace impl{
    template<typename T>
    T x10(T a){
        return a * 10;
    }

    inline char digit(char c){
        return c - '0';
    }

    inline bool is_space(char c){
        return c == ' ' || c == '\t' || c == '\r' || c == '\n';
    }

    inline bool is_sign(char c){
        return c == '+' || c == '-';
    }

    inline bool is_digit(char c){
        return c >= '0' && c <= '9';
    }

    template<typename T>
    std::pair<bool,T> convert_unsigned(const char *c, const char *e){
        T num = 0;

        while(c != e && is_digit(*c)){
            T tmp = x10(num) + digit(*c);

            if (tmp < num)
                return { false, num };

            num = tmp;

            ++c;
        }

        return { true, num };
    }

    template<typename T>
    std::pair<bool,T> convert(const char *c, const char *e, std::true_type /* unsigned */){
        if (c != e && *c == '+')
            ++c;

        return convert_unsigned<T>(c, e);
    }

    template<typename T>
    std::pair<bool,T> convert(const char *c, const char *e, std::false_type /* unsigned */){
        using U = std::make_unsigned_t<T>;

        T sign = +1;
        U max  = std::numeric_limits<T>::max();

        if (c != e && is_sign(*c)){
            if (*c == '-'){
                sign = -1;
                max  = - (U) std::numeric_limits<T>::min();
            }

            ++c;
        }

        // std::cout << ">>> " << sign << ' ' << max << ' ' << '\n';

        auto [ ok, result ] = convert_unsigned<U>(c, e);

        if (result > max)
            return { false, (T) result };

        if (result == max)
            return { true, (T) result };

        return { ok, sign * (T) result };
    }
}

template<typename T>
std::pair<bool,T> convert(std::string_view const s){
    static_assert(std::is_integral_v<T>);

    return impl::convert<T>(std::begin(s), std::end(s), std::is_unsigned<T>{});
}

#include <cstdint>
#include <iostream>

template<typename T>
void test(const char *s, T correct){
    auto [ok, i] = convert<T>(s);

    if (!ok)
        std::cout << "Err" << '\n';

    std::cout << ( i == correct ? "OK" : "NO") << ' ' << i << '\n';
}

int main(){
    test<uint16_t>  ("-0",              std::numeric_limits<uint16_t>::min()    );
    test<uint16_t>  ("65535",           std::numeric_limits<uint16_t>::max()    );
    test<int16_t>   ("+32767",          std::numeric_limits<int16_t>::max() );
    test<int16_t>   ("-32768",          std::numeric_limits<int16_t>::min() );
    test<int16_t>   ("+0",              0                   );
    test<int16_t>   ("-0",              0                   );
    test<int16_t>   ("+10",             +10                 );
    test<int16_t>   ("-10",             -10                 );

    test<uint64_t>  ("+0",                      std::numeric_limits<uint64_t>::min()    );
    test<uint64_t>  ("+18446744073709551615",   std::numeric_limits<uint64_t>::max()    );
    test<int64_t>   ("+9223372036854775807",    std::numeric_limits<int64_t>::max() );
    test<int64_t>   ("-9223372036854775808",    std::numeric_limits<int64_t>::min() );
}


texts:
I'm seeking a review of my Flask-SQLAlchemy model structure, particularly adherence to DB best practices, such as avoiding duplication, etc.

The models represent the relations between Departments, Teams, and Roles. A more detailed explanation of these has been included.

Model Specification:

Department: A Department represents a collection of Teams. A Department without Teams should be considered valid. On deletion, all Teams associated with the Department should also be deleted.
Team: A Team represents a collection of Roles. A Team without Roles should be considered valid. On deletion, all Roles associated with the Team should also be deleted. A Team may only belong to one department.
Role: A Role may only belong to one Team.

Models:

class Department(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), nullable=False)

    teams = db.relationship(
        'Team',
        backref='department',
        cascade='all, delete-orphan',
        lazy='dynamic'
    )

    def __repr__(self):
        return '<Department {} >'.format(self.name)

class Team(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), nullable=False)

    roles = db.relationship(
        'Role',
        backref="team",
        cascade="all, delete-orphan",
        lazy='dynamic'
    )

    department_id = db.Column(
        db.Integer,
        db.ForeignKey('department.id'),
        nullable=False
    )

    def __repr__(self):
        return '<Team {} >'.format(self.name)

class Role(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), nullable=False)

    team_id = db.Column(db.Integer, db.ForeignKey('team.id'), nullable=False)

    def __repr__(self):
        return '<Role {} : ID {} >'.format(self.name, self.id)

Questions:

Had I written this as SQL, I would have expected Role to contain both the Department_id and Team_id. Can the same structure be achieved using SQL-Alchemy? Is the current (sub-optimal?) structure symptomatic of an ORM?

Update

The tables this produces are as follows:

Department: ID, Name
Team: ID, Name, department_id
Role: ID, Name, role_id


texts: Find biggest palindrome which is the product of two 3-digit numbers

texts:
isPalindrome :: Integer -> Bool
isPalindrome n = reverse x == x
    where x = show n

is3x3 :: Integer -> Bool
is3x3 n = any (\x -> cond1 x && cond2 x) [101..999]
    where
        cond1 x = n `mod` x == 0
        cond2 x = length (show $ n `div` x) == 3

main = print $ head [p | p <- [999^2,999^2-1..], isPalindrome p, is3x3 p]

I have some doubts about the code I wrote:

isPalindrome: is it ok or is it better to keep dividing by 10, storing the remainder in a list and check if list is equal to the reversed self?
is3x3: is it a good practice to declare functions inside functions? Is there a better way to write the function?
how to delete the parentheses in cond2? $ doesn't work because of ==
[999^2,999^2-1..]:

is Haskell smart and calculates 999^2 only once, subtracting 1 every time? Or does it compute 999^2-x for each xth+1 element of the list?
is there a better way to write this list?
is it  better to put the end of the list (in this case 10001) or it doesn't matter in terms of performance? I know lists are lazy but ...


texts:
The program sorts the array from lowest to highest and outputs the index of the searched value:

public static void main(String[] args) {

    Integer[] random = {6, -4, 12, 0, -10};
    List<Integer> list = new ArrayList<Integer>(Arrays.asList(random));
    Collections.sort(list);
    Integer[] array = list.toArray(new Integer[list.size()]);

    int y = Arrays.binarySearch(array, 6);
    System.out.println(y);

}

This works as expected, but you can see that I had to use 3 lines just to sort the array, before being able to do a binarySearch on it.

Can this code be improved?


texts:
I am working on a haskell exercise where I have to compute the amount of people riding a rollercoaster in a day. I have the following data: the number of rides  in a day, the number of seats, and the composition of the queue.

The queue is a list of groups. During each ride, the first few groups of the list enter the ride. A group always rides together. The total number of people cannot exceed the number of seat during one ride.

After the ride, the groups go to the end of the queue (in the same order).

So the exercise is not really hard. But when numbers get big, my haskell implementation becomes quite slow. I have used the profiler to improve some parts, but I wasn't able to spot a bottleneck.

The first time I ran the profiler, the part that was parsing the groups was slow. Here is my second version (1st one was replicateM n $ read <$> getLine):

getGroups :: IO [Int]
getGroups = do
    c <- TIO.getContents
    return $ readInts c

readInts :: T.Text -> [Int]
readInts s
    | T.null s = []
    | otherwise = val : rest where
        (Right (val, s')) = TR.decimal s
        rest = if T.null s'
            then []
            else (readInts $ T.tail s')

Another cost center is the actual computing function:

type Queue = Seq.Seq Int
data Roller = Roller Int Int Queue

compEarn :: Roller -> Int
compEarn (Roller placeNbr rideNbr groups) = go rideNbr groups 0
  where
    go turnsLeft queue accum
        | turnsLeft == 0 = accum
        | otherwise = let
            (riding, waiting) = breakQueue placeNbr queue
            newQueue = waiting Seq.>< riding
            newAccum = accum + (F.sum riding)
            in go (turnsLeft - 1) newQueue newAccum

breakQueue :: Int -> Queue -> (Queue, Queue)
breakQueue placeNbr queue = go Seq.empty queue placeNbr where
    go riding waiting spaceLeft = case Seq.viewl waiting of
            Seq.EmptyL -> (riding, waiting)
            group Seq.:< rest -> if spaceLeft' < 0
                then (riding, waiting)
                else go (riding Seq.|> group) rest spaceLeft'
              where
                spaceLeft' = spaceLeft - group

Am I missing something obvious regarding performances with this program?


texts:
I have created a nice little image gallery for the web. I set out wanting 3 things. 1. The whole gallery had a basic level responsiveness to it. 2. The gallery would take images of any size, and display them without cropping. 3. The gallery would run automatically. If you look here(JSFiddle) I have done just that. The automatic slide show is just a small bit of jQuery.

setInterval(function () {
  $(".image_background").last().animate({
        left: '-=1000'
        }, 1000, 'swing', function() {
          var top_element= $(this).detach();
          top_element.css({"left": 0});
          $(".image_gallery").prepend(top_element);
    })}, 2000);

I am quite happy with it. It's the css bit that I am not so sure about.

.main_image_gallery{
  display: inline-block;
  position: absolute;
  height: 50%;
  width: 30%;
  z-index: 2;
  top: 30%;
  left: 3%;
  background-color: #4e9ba1;
  box-sizing: border-box;
  overflow: hidden;
}
.image_background{
  background-color: #4e9ba1;
  display: inline-block;
  position: absolute;
  height: 100%;
  width: 100%;
}
.gallery_image{
  margin: auto;
  position: absolute;
  top: 0; left: 0; bottom: 0; right: 0;
  max-width: 100%;
  max-height: 100%;
}

For reference, here's the HTML

I feel like there is a simpler way to do it. Any thoughts on how I can clean it up, maybe improve the responsive aspects?


texts:
I've been doing a lot of Project Euler lately and just wanted to make sure my implementation was as good as it could be. Does anyone have any suggestions to speed this up?

def sieve(upperlimit):
    # mark off all multiples of 2 so we can use 2*p as the step for the inner loop
    l = [2] + [x if x % 2 != 0 else 0 for x in range(3, upperlimit + 1)]

    for p in l:
        if p ** 2 > upperlimit:
            break
        elif p:
            for i in range(p * p, upperlimit + 1, 2 * p):
                l[i - 2] = 0
    # filter out non primes from the list, not really that important i could work with a list full of zeros as well
    return [x for x in l if x]


texts: Phone number to words based on the dictionary

texts:
This is the problem:

  Given a 10 digit phone number, you must return all possible words or combination of words from the provided dictionary, that can be mapped back as a whole to the number.

  With this we can generate numbers like 1-800-motortruck which is easier to remember then 1-800-6686787825

  The phone number mapping to letters is as follows:

2 = a b c
3 = d e f
4 = g h i
5 = j k l
6 = m n o
7 = p q r s
8 = t u v
9 = w x y z

  The phone numbers will never contain a 0 or 1.  Words have to be at least 3 characters.

  To get give you an initial verifiation, the following must be true:

  6686787825 should return the following list [["motor", "usual"], ["noun", "struck"], ["nouns", "truck"], ["nouns", "usual"], ["onto", "struck"], "motortruck"] # These words exist in a dictionary file.
  The conversion of a 10 digit phone number should be performed within 1000ms.

My solution works but takes longer than 1 sec.
How can I improve my code so execution time will be less than 1 sec?

class NumberToWord

  def letter_combinations(digits)
    #return if number not valid
    return [] if digits.nil? || digits.length != 10 || digits.split('').select{|a|(a.to_i == 0 || a.to_i == 1)}.length > 0
    #number to letters mapping
    letters = {"2" => ["a", "b", "c"],"3" => ["d", "e", "f"],"4" => ["g", "h", "i"],"5" => ["j", "k", "l"],"6" => ["m", "n", "o"],"7" => ["p", "q", "r", "s"],"8" => ["t", "u", "v"],"9" => ["w", "x", "y", "z"]}

    # Read dictionary file and hold all values in a array
    dictionary = []
    file_path = "dictionary.txt"
    File.foreach( file_path ) do |word|
      dictionary.push word.chop.to_s.downcase
    end
    # get all letters for numbers in form of array
    keys = digits.chars.map{|digit|letters[digit]}

    results = {}
    total_number = keys.length - 1 # total numbers
    #Loo through all letters and get matching records with dictionary
    for i in (2..total_number)
      first_array = keys[0..i]
      second_array = keys[i + 1..total_number]
      next if first_array.length < 3 || second_array.length < 3
      first_combination = first_array.shift.product(*first_array).map(&:join) # Get product of arrays
      next if first_combination.nil?
      second_combination = second_array.shift.product(*second_array).map(&:join)
      next if second_combination.nil?
      results[i] = [(first_combination & dictionary), (second_combination & dictionary)] # get common values from arrays
    end
    #arrange words like we need as a output
    final_words = []
    results.each do |key, combinataions|
      next if combinataions.first.nil? || combinataions.last.nil?
      combinataions.first.product(combinataions.last).each do |combo_words|
        final_words << combo_words
      end
    end
    # for all numbers
    final_words << (keys.shift.product(*keys).map(&:join) & dictionary).join(", ") # matche with all character
    final_words
  end

end

final_words = NumberToWord.new().letter_combinations("6686787825")
print final_words


texts: Trim trailing lines and remove blank lines in C

texts:
This simple program, that I call trim(1), trims trailing lines and, if the flag -l is passed as an argument, it also removes empty lines and lines containing only blanks.

I did this as an exercise for learning C and good practices of C programming in UNIX.

It reads from standard input if no argument is passed or read from the files passed as arguments.

I am a bit suspicious of that realloc idiom for reallocing the buffer if it gets full. Is it right?

#include <err.h>
#include <errno.h>
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#define MID 0   /* in middle of line */
#define BEG 1   /* at beginning of line */

static int blankline = 0;
static int exitval = EXIT_SUCCESS;

static void trim(FILE *fp);
static void usage(void);

/* remove trailing blanks and delete blank lines */
int
main(int argc, char *argv[])
{
    int ch;
    FILE *fp;

    while ((ch = getopt(argc, argv, "l")) != -1) {
        switch (ch) {
        case 'l':
            blankline = 1;
            break;
        default:
            usage();
            break;
        }
    }
    argc -= optind;
    argv += optind;

    if (argc == 0) {
        trim(stdin);
    } else {
        while (*argv) {
            if ((fp = fopen(*argv, "r")) == NULL) {
                warn("%s", *argv);
                exitval = EXIT_FAILURE;
            } else {
                trim(fp);
                fclose(fp);
            }
            argv++;
        }
    }
}

/* trim trailing blanks from fp; if blankline is set also remove blank lines */
static void
trim(FILE *fp)
{
    char *buf = NULL;
    size_t i, size, newsize;
    int status;
    int c;

    size = BUFSIZ;

    if (buf == NULL)
        if ((buf = malloc(size)) == NULL)
            err(EXIT_FAILURE, "malloc");

    i = 0;
    status = BEG;
    while ((c = getc(fp)) != EOF) {

        if (isblank(c)) {               /* collect blanks in buf */
            if (i >= size) {            /* realloc */
                newsize = size + BUFSIZ;
                if (newsize <= size)    /* check for overflow */
                    errc(EXIT_FAILURE, EOVERFLOW, "realloc");
                size = newsize;
                if ((buf = realloc(buf, size)) == NULL)
                    err(EXIT_FAILURE, "realloc");
            }
            buf[i++] = c;
        } else if (c == '\n') {
            if (status == MID || (!blankline))
                putchar('\n');
            status = BEG;
            i = 0;
        } else {
            fwrite(buf, 1, i, stdout);
            putchar(c);
            status = MID;
            i = 0;
        }
    }

    if (ferror(fp)) {
        warn("getc");
        exitval = EXIT_FAILURE;
    }
}

/* show usage */
static void
usage(void)
{
    (void)fprintf(stderr, "usage: trim [-l] [file...]\n");
    exit(EXIT_FAILURE);
}


texts: Refactoring custom validator using lots of if's

texts:
I have a custom validator that checks the min and max score of different sporting leagues -- e.g., MLB, NBA, NFL, NCAAB, etc.

Here's short version of what it looks like:

class ScoreValidator < ActiveModel::Validator

  def validate(event)

    if event.league_is_mlb?
      if event.total_score < 1
        event.errors.add :base, 'min total score for an MLB event is 1'
      elsif event.total_score > 49
        event.errors.add :base, 'max total score for an MLB event is 49'
      end
    elsif event.league_is_nba?
      if event.total_score < 119
        event.errors.add :base, 'min total score for an NBA event is 119'
      elsif event.total_score > 370
        event.errors.add :base, 'max total score for an NBA event is 370'
      end
    end

  end

end

Seems like this code could be much cleaner by making smarter use of ruby data structures and methods.  Any creative suggestions you could make would be educational and much appreciated.


texts:
This is my implementation for this hacker rank problem. (And a follow-up.)

Problem

  You are given a list(1-indexed) of size n, initialized with zeroes.
  You have to perform m operations on the list and output the maximum of
  final values of all the  elements in the list. For every operation,
  you are given three integers a, b and  and you have to add value k to
  all the elements ranging from index  to (both inclusive).

Example input

5 3
1 2 100
2 5 100
3 4 100

Expected output

200

Explanation

After first update list will be:

100 100 0 0 0

After second update list will be:

100 200 100 100 100

After third update list will be:

100 200 200 200 100

So the required answer will be: 200

First solution

My first attempt I think is quite readable (ignoring the way input and output is handle in hacker rank)

#include <bits/stdc++.h>
#include <algorithm>

using namespace std;

int main() {
    int n, m;
    cin >> n >> m;
    vector<long long> v(n);
    for(int a0 = 0; a0 < m; a0++){
        int start, end, val;
        cin >> start >> end >> val;
        auto it_start = v.begin()+(start-1);
        auto it_end = v.begin()+(end);
        transform(it_start, it_end , it_start, [k](long long &x){return x+=k;});
    }
    cout << *max_element(v.begin(),v.end());
    return 0;
}

Final solution

But this approach, although readable, is too slow for what it is actually being ask, which is the maximum value that it would be achieved. So I wrote this, which passed the tests, but which is more difficult to understand in my opinion.

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

int main() {
    int n; int m;
    std::cin >> n >> m;
    using val_type = long long;
    std::vector<val_type> v(n);
    while(m--){
        val_type start, end, val;
        std::cin >> start >> end >> val;
        auto it_start = v.begin()+(start-1);
        auto it_end   = v.begin()+ end;
        *it_start     += val;
        *it_end       -= val;
    }
    val_type max{0};
    auto accumulate_max_val = [x=val_type(0),&max](val_type y) mutable{x+=y; if (x>max) max=x;};
    std::for_each(v.begin(),v.end(),accumulate_max_val);
    std::cout << max;
    return 0;
}

What would you do to improve it? Am I using lambdas and the for_each appropriately, or is there a clearer way to express what I want to do?


texts: Python Hash Table implemented using lists

texts:
I implemented a Python Hash Table using only lists.
Here is my implementation:

class HashTable:
    # Initialize the table with a fixed size of 54 slots
    def __init__(self):
        self.Table = [None] * 54

    def _get_value(self, key): #This is my hash function.
        # It finds the hash of every string. total % 54
        total = hash(key)
        return total % 54

    def insert(self, key):
        val = self._get_value(key)
        col = False #Collision bool
        index = 0

        if self.Table[val] == None: #Empty slot - turn into list of keys to avoid extra cases
            self.Table[val] = [key]

        else: #Collision - append
            self.Table[val].append(key)
            col = True
            index = len(self.Table[val]) - 1

        return val, col, index

    def delete(self, key):
        val = self._get_value(key)

        if self.Table[val] == None: #Deleting an unexisting element
            return -1, 0

        elif key in self.Table[val]: #This is the O(n) part of the hashtable
            index = self.Table[val].index(key)
            self.Table[val].remove(key)
            return val, index

        else: # No match was found in list, element does not exist
            return -1, 0

    def lookup(self, key):
        val = self._get_value(key)

        if self.Table[val] == None:
            return -1, 0
        else:
            if key in self.Table[val]:
                index = self.Table[val].index(key)
                return val, index

            # No match was found in list, element does not exist
            return -1, 0

    def clear(self):
        self.__init__()

I am using and returning some variables to keep track of collision, values, and indexes to print to the user.

I want to understand how I could improve this implementation - still using only lists (no sets for checking).
From a time complexity perspective or even code design, how can I make this more efficient? What design choices were poorly made in my code? What can I improve in this to make it better?


texts: Feedback on a programming practice problem in C

texts:
This is a programming practice that our teacher gave us, and I would appreciate if someone can look over my program and tell me if I did a good job.

Basically, the context is I joined a company and am supposed to write a program in C that takes three inputs (ft of steel, number of ball bearings, and lbs of bronze), and returns how many bells and whistles can be made the next day.

Making a whistle requires 0.5 ft of steel and 1 ball bearing. Making a bell requires 1.10 lbs of bronze (.75 lbs of bronze and 1 clapper (.35 lbs of bronze)).

This is the program I have written.  I apologize if it seems messy.

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

void PrintLine();
int CalculateWhistles(int steel, int bearings);
int CalculateBells(int bronze);

int main() {
    bool runProgram = true;
    int runAgain = 0;

    while (runProgram == true) {
        int ftSteelIn = 0;
        int numBallBearingIn = 0;
        int ibsBronzeIn = 0;

        printf("\n\n"); // Formatting...
        PrintLine();

        printf("    How many feet of steel was received today:               "); // Steel received
        scanf("%d", &ftSteelIn);
        printf("    How many ball bearings were received today:              "); // Ball bearings received
        scanf("%d", &numBallBearingIn);
        printf("    How many pounds of bronze was received today:            "); // Bronze received
        scanf("%d", &ibsBronzeIn);

        PrintLine(); // Print line

        PrintLine(); // Print line

        // Print company logo and program title
        printf("                                Acme Corporation\n");
        printf("                                Product Report\n");

        PrintLine();// Print line

        // Print number of bells and whistles
        printf("    Number of Bells                                                      %d\n", CalculateBells(ibsBronzeIn));
        printf("    Number of Whistles                                                   %d\n", CalculateWhistles(ftSteelIn, numBallBearingIn));

        PrintLine(); // Print line
        PrintLine();

        printf("\n\n");
        PrintLine();

        // Ask the user if they would like to run the program again
        printf("    Would you like to run the program again? ('1' for yes, '2' for no): ");
        scanf("%d", &runAgain);
        PrintLine();

        // If user does not say 'yes', end the program and say goodbye
        if (runAgain != 1) {
            printf("\n    Exitting the program. Have a good day.\n\n");
            PrintLine();
            runProgram = false;
        }
    }

    return 0;
}

void PrintLine() {
    int i = 0;
    printf("    ");
    while (i <= 70) {
        printf("-");
        i++;
    }
    printf("\n");
}

int CalculateWhistles(int steel, int bearings) {
    steel = steel / 0.5;
    if (steel < bearings) {
        return steel;
    }
    else if (bearings < steel) {
        return bearings;
    }
}

int CalculateBells(int bronze) {
    int bells = bronze / 1.1;
    return bells;
}

It runs fine with no errors. There is a second part where I calculate the remainder, but I want some feedback before I go on to that part.

Any advice would be appreciated, how to make it more efficient or anything like that (I'm just learning C).


texts: Merging results of product searches by category, price, and manufacturer

texts:
Following is code which takes three arguments as

String
Map
String

now I already have some predefined methods which return the requirement of both String as List and since my map contains only two keys (for now) and all I get is their output in form of List which is then converted to set and added to set.

Now what I want to achieve is to reduce the number of declarations as they all merge in the same set.Now the question is there any way to reduce the noisy declarations of set or I should keep it the way these are

 @Override
        public Set<Product> getProductByCategoryPriceManfacturer(String category, Map<String, String> priceParms,
                String manufacturer) {
            Set<String> priceFilter = priceParms.keySet();
            Set<Product> lowPrice = new TreeSet<>();
            Set<Product> highPrice = new TreeSet<>();
            Set<Product> productByCategory = new TreeSet<>(this.getProductByCategory(category));
            Set<Product> productByManfacturer = new TreeSet<>(this.getProductsByManufacturer(manufacturer));
            productByCategory.addAll(productByManfacturer);

            if (priceFilter.contains("low")) {
                for (String low : priceParms.get("low")) {
                    lowPrice.addAll(this.getProductByMinimumPrice(low));
                }
            }
            if (priceFilter.contains("high")) {
                for (String high : priceParms.get("high")) {
                    highPrice.addAll(this.getProductByMaximumPrice(high));
                }
            }
            productByCategory.addAll(highPrice);
            productByCategory.addAll(lowPrice);
            return productByCategory;
        }

Note where all arguments in constructors of Set are List.

Now, is there any way to reduce the code I mean if I can reduce the number of declarations.

Edit In order to reduce the noise I ended up using Map<String,String> and now the method is as follow, can It be reduced more?

@Override
    public Set<Product> getProductByCategoryPriceManfacturer(String category, Map<String, String> priceParms,
            String manufacturer) {
        BigDecimal minPrice = new BigDecimal(priceParms.get("low".trim()));
        BigDecimal maxPrice = new BigDecimal(priceParms.get("high".trim()));

        return listAllProducts.stream().filter(product -> product.getCategory().equalsIgnoreCase(category))
                .filter(productMinPrice -> productMinPrice.getUnitPrice().compareTo(maxPrice) < 0)
                .filter(minPriceProduct -> minPriceProduct.getUnitPrice().compareTo(minPrice) > 0)
                .collect(Collectors.toSet());

    }

Edit I have one more question as this is repository class in springMVC the only one liner suggestion i want that, is that good to perform all operations of databases in Repository class given the fact that running query for every  single call will make it slow to load products or i just load all products at once and perform all operations after that?


texts: Checking screen sizes for responsive site

texts:
I wrote this piece of code to make any breakpoint to the users choice:

@mixin breakpoint($media) {
  $max-width: 0;
  @if($media == 'phones') {
    $max-width: $phone-medium;

  } @else if ($media == 'monitors') {
    $max-width: $screen-medium;

  //etc etc etc

  } @else if($media > 0) {
    $max-width: $media;
  }

  @media only screen and  (max-width: $max-width) {
    @content;
  }
}

This function comes with these variables:

//Phone width sizes
$phone-small: 480px;
$phone-medium: 768px;

//Screen widths
$screen-small: 1024px;
$screen-medium: 1280px;
$screen-big: 1920px;

This can be used by typing:

@include breakpoint('phones') {
   ....
}

or

@include breakpoint(450px) {
   ....
}

Is there any better way to do this?


texts:
I'm using Rails 4.2.5, and I'd like to update existing records with a csv file with two fields: id,category. Where if the category field is blank, it defaults to misc.

Here's an example csv file:

id,category
123-123-123,0
123-123-124,1
123-123-125,
123-123-126,2

So, I've created some tasks, update_item_categories, and set_item_categories:

# lib/tasks/update_item_categories.rake
require 'csv'

namespace :db do
  task :update_item_categories => :environment do
  categories = ['misc', 'food', 'drink']
  CSV.foreach('public/update/item_categories.csv', headers: true) do |row|
    row_hash = row.to_hash
    category = categories[row_hash['category'].to_i]
    unless Item.where(id: row_hash['id']).empty?
      item = Item.find(row_hash['id'])
      item.update_attributes(
        :category => category
      )
      item.save!
    end
  end

  task :set_item_categories => :environment do
    Item.where(category: nil).each do |item|
      item.update_attributes(category: 'misc')
      item.save!
    end
  end
end

I will definitely appreciate any advice on how this could be better written, and also whether this is even a good way to go about solving this problem.


texts:
I'm making a news aggregator using newsAPI, and have everything working - to begin with. But was wondering if the code I use to filter through an object can be made more efficient - meaning fewer lines of code.

So far, it only returns what I need from the raw JSON file, then filters it using a for loop to ignore objects with blank values.

Any help would be great.

   if (!error && response.statusCode == 200) {

        let data = JSON.parse(body);

        let articles = data.articles.map(article => {
            return {
                "title": article.title,
                "date": article.publishedAt,
                "image": article.urlToImage,
                "description": article.description,
                "link": article.url
            }
        });

        let filtered = []
        for (let i = 0; i < articles.length; i++) {
            if (articles[i].title !== null &&
                articles[i].date !== null &&
                articles[i].image !== null &&
                articles[i].description !== null &&
                articles[i].link !== null) {
                filtered.push(articles[i])
            }
        }

        console.log(filtered)

        res.render("index", { filtered: filtered });

   }


texts: Find no of swaps needed to club identical elements of array together

texts:
I have created a solution for the problem as below:

  Given a string S consisting of letters 'O' and 'Z'. Calculate the
  minimum number of changes required such that all O's are adjacent to
  each other and all Z's are adjacent to each other. One change is
  equivalent to swapping two neighbouring letters

  for e.g for a given array: oozozo  desired array is : oooozz so,min no
  of swap would be 3,which should be the desired output.

Let me know if the solution has any bad practices.

My Code:

package com.test.practice;

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class TestClass {

    public static void main(String args[]) throws Exception {

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String numberOfInputs = br.readLine();

        for (int i = 0; i < numberOfInputs.length(); i++) {
            String inputString = br.readLine();

            findNumberOfTurns(inputString);
        }

    }

    private static void findNumberOfTurns(String inputString) {

        int count = 0;
        char[] input = inputString.toCharArray();
        char firstCharacter = input[0];
        char secondCharacter;
        boolean secondCharEncountered = false;
        int countSecondChar = 0;
        for (int i = 1; i < input.length; i++) {
            if (firstCharacter == input[i]) {
                if (!secondCharEncountered) {
                    countSecondChar=0;
                } else {
                    count+=countSecondChar;
                    secondCharEncountered=false;
                }
            } else {
                secondCharEncountered=true;
                countSecondChar+=1;
            }
        }

        System.out.println(count);
    }

}


texts:
This is a basic implementation of a stack. Can anyone please review it and let me know how I can improve this code and overall coding practice?

 #include"iostream"
    #define MAX_SIZE 5
    using namespace std;
    class Mystack
    {
    private:
        int A[MAX_SIZE];
        int top;
    public:
        Mystack();
        void push(int x);
        void pop();
        void topElement();
        void print();
        void isEmpty();
    };
        Mystack::Mystack()
        {
            top = -1;
        }
        void Mystack::push(int x)
        {
            if(top == MAX_SIZE-1)
            {
                cout << "Stack Overflow"<< endl;
                return;
            }
            else
            {
                top++;
                A[top] = x;
            }
        }
        void Mystack::pop()
        {
            if (top != -1)
            {
                top--;
            }
            else
            {
                cout << "Stack Underflow" << endl;
                return;
            }
        }
        void Mystack::isEmpty()
        {
            if (top == -1)
            {
                cout << "Is Empty"<< endl;
            }
            else
            {
                cout << "Not Empty" << endl;
            }
        }
        void Mystack::topElement()
        {
            cout<<"The top element is : "<< A[top];
        }
        void Mystack::print()
        {
            for (int i = 0; i <=top; i++)
            {
                cout << "top:  " << A[i]<< endl;
            }
        }
    void main()
    {
        Mystack s1;
        int num,ch = 1;
        while (ch >0)
        {
            cout << "\n1. PUSH" << endl;
            cout << "2. TOP" << endl;
            cout << "3. IsEmpty" << endl;
            cout << "4. POP" << endl;
            cout << "5. EXIT" << endl;
            cout << "6. Print" << endl;
            cout << "Enter the choice"<<endl;
            cin >> ch;
            switch (ch)
            {
            case 1:
                cout << "Enter the number to be pushed" << endl;
                cin >> num;
                s1.push(num);
                break;
            case 2:
                cout << "Get the TOP Element" << endl;
                s1.topElement();
                break;
            case 3:
                cout << "Check Empty" << endl;
                s1.isEmpty();
                break;
            case 4:
                cout << "POP the element" << endl;
                s1.pop();
                break;
            case 5: exit(0);
            case 6:
                s1.print();
                break;
            }
        }
        system("pause");
    }


texts: Implementation of ApplySort method from IBindingList

texts:
I am currently developing a family of keyed collections, and I wanted to have one which would implement the IBindingList interface.

My BindingKeyedCollection is derived from a KeyedCollection which owns a look-up dictionary, used to make the researches by key.

However, I have suspicions about my implementation of the ApplySort method (a method used to sort the collection relatively to one of the items property). It seems to be working as it is now, but I am not sure that all items are synchronized properly.

protected virtual void ApplySortCore(PropertyDescriptor property, ListSortDirection direction)
    {
        this.SortProperty = property;
        this.SortDirection = direction;
        if (direction == ListSortDirection.Ascending)
        {
            ResetItems(this.OrderBy(item => property.GetValue(item)).ToList());
            IsSorted = true;
            OnListChanged(new ListChangedEventArgs(ListChangedType.Reset, property));
        }
        else if (direction == ListSortDirection.Descending)
        {
            ResetItems(this.OrderByDescending(item => property.GetValue(item)).ToList());
            IsSorted = true;
            OnListChanged(new ListChangedEventArgs(ListChangedType.Reset, property));
        }
    }

Basically I am using LINQ to order another collection and change its Items list with the main one.

private void ResetItems(List<TItem> items)
    {
        base.ClearItems();

        foreach (var item in items)
        {
            base.InsertItem(IndexOf(item), item);
        }
    }

I would like to have an external opinion on this way of sorting my collection, if they are any flaws that I would have missed, and if so, is there a way to avoid them?


texts: Checking if string characters can be arranged to form another string

texts:
I am working on a code project that checks if all the characters in str1 can be arranged to form another string (str2).  If all the characters in str2 are present in str1 (including any repeated characters in str2, i.e. if str2 has two 'a' characters, str1 must correspondingly have two as well), then the function returns true.

For example, here are some test cases below and the intended return:

str1 = 'rkqodlw'
str2 = 'world'
Expected: true

str1 = 'cedewaraaossoqqyt'
str2 = 'codewars'
Expected: true

str1 = 'katas'
str2 = 'steak'
Expected: false

str1 = 'scriptjava'
str2 = 'javascript'
Expected: true

I have a working code solution, but I'd like to refactor for optimal performance as there are a quite a number of random tests (of unknown length) that the code must test against and my code isn't completing the tests in the recommended timeframe.

function stringscrambling(str1, str2) {
  var arr1 = str1.split('');
  var arr2 = str2.split('');
  var index;
  var l = arr2.length;

  while (l--) {
    index = arr1.indexOf(arr2[l]);
    if (index > -1) {
      arr1.splice(index, 1);
    } else {
    return false;
    };
  }
  return true;
}

I originally used a basic for loop (with the array length cached as a variable and not in the for statement) as follows:

for (var i = 0, l = arr2.length; i < l ; i++) {
    index = arr1.indexOf(arr2[i]);
    if (index > -1) {
      arr1.splice(index, 1);
    } else {
      return false;
    };
  }
  return true;
 }

but tried the while-loop in reverse as I read that specific looping would offer a bit better in terms of benchmarked performance. The change in loop offered a negligible performance upgrade.

Are there any other specific tricks I can implement on my code that can speed it up and still retain the original functionality?


texts: Exporting HTML table data to Excel using C#

texts:
I have JSON data that I bind to a table:

Now I would like to export this data to Excel, so I have written this code that involves data formatting of an Excel spreadsheet.

private static MemoryStream JsonToStream<T>(string data, string html, string movieReportName)
{
    IEnumerable<T> serializedData = data.JsonDeserialize<T>().AsEnumerable<T>();
    List<SelectListItem> colOrder = ParseColumnsToList(html);
    DataTable dataTable = serializedData.ToDataTable<T>(colOrder);
    ExcelPackage epackage = new ExcelPackage();
    ExcelWorksheet excel = epackage.Workbook.Worksheets.Add(movieReportName);
    excel.Cells["A1"].LoadFromDataTable(dataTable, true);

    int rowCount = dataTable.Rows.Count;
    int columnCount = dataTable.Columns.Count;
    for (int i = 2; i < rowCount + 2; i++)
    {
        for (int j = 1; j <= columnCount; j++)
        {
           if (value.Contains("%"))
            {
                if ((dataTable.Columns[j - 1].ColumnName != "Movie Code") {

                    value = value.Replace("%", "");
                    if (value.Contains("."))
                    {
                        double number = 0.0;
                        double.TryParse(value, out number);
                        excel.Cells[i, j].Value = number / 100;
                        excel.Cells[i, j].Style.Numberformat.Format = "0.00##%";
                    }
                }
            }
         }
      }
      MemoryStream ms = new MemoryStream(epackage.GetAsByteArray());
      epackage.Dispose();
      return ms;
  }

This works fine but it runs very slowly. Do you think I have to move data formatting to a database?

Update
What are different better option to export large data from HTML to excel?


texts:
I am looking to improve and simplify the way I code. What is the best way to represent this:

let names = [];
let name;

while(true) {
 name = prompt('Enter a name:');
  names.push(name);

  if(name === ''){
   names.pop();
   break;
  }
}

let winner = function(){
 return names[Math.floor(Math.random() * names.length)];
}

console.log(winner());


texts:
Please review the following code and list all the coding errors and poor coding practices that you can see in this code.

function output()
{
    // Check authorization
    if(is_authorized())
    {
        $authorized = true;
        include('/path/to/' . $_REQUEST['module'] . '.php');
    }
    echo "
"
    $conn = mysql_connect( "dbserver.com:6789", "dbyuser", "dbpassWd" );
    mysql_select_db( "kum", $conn ); // selects a database
    $q = " SELECT * FROM main WHERE id > " . $_GET["id"]. ";";
    $res = mysql_query( $q, $conn);
    while( $row = mysql_fetch_assoc( $res ) )
    {
        echo "
".$row['description']."
";
    }
    echo "

";
    $q = " SELECT * FROM main WHERE id < " . $_GET["id"]. ";";
    $res = mysql_query( $q, $conn);
    while( $row = mysql_fetch_assoc( $res ) )
    {
        // Display the status if it is authorized, otherwise display N/A
        echo "
".$row['description']. "(" .
        $authorized ? $row['status'] : "N/A" . ")
";
    }
    echo "
";
}


texts: Splitting an array in 2 parts such that one part sums to a multiple of 10 and other sums to an odd number

texts:
Given an array of ints, is it possible to divide the ints into two
  groups, so that the sum of one group is a multiple of 10, and the sum
  of the other group is odd. Every int must be in one group or the
  other. Write a recursive helper method that takes whatever arguments
  you like, and make the initial call to your recursive helper from
  splitOdd10(). (No loops needed.)

splitOdd10({5, 5, 5}) → true

splitOdd10({5, 5, 6}) → false

splitOdd10({5, 5, 6, 1}) → true

public boolean splitOdd10(int[] nums) {
        int total=findSum(0, nums, 0);
        if((total%10)%2==0||total==0)
        {
             return false;
        }
        return ifGroupExistsThatSumsToValue(0, nums, total%10);
    }
    public int findSum(int n, int[] nums, int sum)
    {
        if(nums.length==0)
            return 0;
        if(n==nums.length-1)
        {
            return sum+nums[n];
        }
        return findSum(n+1, nums, sum+nums[n]);
    }

    public boolean ifGroupExistsThatSumsToValue(int start, int[]nums, int target)
    {
       if(start==nums.length-1)
       {
           return target-nums[start]==0;
       }
       if(target==0)
       {
           return true;
       }
       if(ifGroupExistsThatSumsToValue(start+1, nums, target-nums[start]))
          return ifGroupExistsThatSumsToValue(start+1, nums, target-nums[start]);

       return ifGroupExistsThatSumsToValue(start+1, nums, target+nums[start]);
       }


texts:
package main

import (
    "fmt"
)

type LinkedList struct {
    first, last *node

}

type node struct {
    item int
    next *node

}

func (l *LinkedList) add (val int) {
    n := node {
        item: val,
        next: nil,
    }
    if l.first == nil {
        l.last = &n
        l.first = &n
    } else {
        l.last.next = &n
        l.last = &n
    }

}

func (l *LinkedList) traverse () {
    for n := l.first; n != nil; n = n.next {
        fmt.Printf("%v ", n.item)

    }

    fmt.Println()

}

func (l *LinkedList) swapLL () {
    if l.first == nil {
        panic("First element cannot be null")
        }

    if l.first.next == nil {
        return
    }

    ptr1 := l.first
    var ptr2 *node
    var ptr3 *node
    var prev *node

    for ; ptr1 != nil && ptr1.next != nil; {
        //Allocate resources
        ptr2 = ptr1.next
        ptr3 = ptr2.next

        //swap
        ptr2.next = ptr1
        ptr1.next = ptr3

        //hook to the previous pair
        if prev == nil {
            l.first = ptr2
        } else {
            prev.next = ptr2
        }

        //advance
        prev = ptr1
        ptr1 = ptr3
    }

}

func main () {
    l := LinkedList {
        first: nil,
        last: nil,
    }

    l.add(10)
    l.add(20)
    l.add(30)
    l.add(40)

    l.traverse()

    l.swapLL()

    l.traverse()
}

Input:

Linkedlist:  10 -> 20 -> 30 -> 40 -> null

Output:

Linkedlist: 20 -> 10 -> 40 -> 30 -> null

Question:

Here 10 and 20 are adjacent thus they were swapped. Likewise, 30 and 40 are adjacent thus they were swapped.

I am looking for suggestions for improving my code, any optimizations, or anything to make my code more readable and elegant.


texts:
I've implemented InsertionSort and SelectionSort in PHP and tested it with an array of 20.000 unique integers.

It took many seconds to complete the insertion selection sorts.  For comparison, I saw a Java implementation that only took 3 seconds for both combined. I wanted to ask if my implementations are just bad or if this is a hardware/language based problem.

Here are my methods:

$rand = randomArray(20000);
insertionSort($rand);
selectionSort($rand);

function insertionSort($sort_array){
    $time_start = microtime(true);
    for ($i = 0; $i < count($sort_array)-1; $i++){
      for ($j = $i + 1; $j > 0; $j--)
        {
          if($sort_array[$j-1] > $sort_array[$j]){
            $temp = $sort_array[$j-1];
            $sort_array[$j-1] = $sort_array[$j];
            $sort_array[$j] = $temp;
          }
        }
    }
    $time_end = microtime(true);
    $time = $time_end - $time_start;
    echo $time;
    return $sort_array;
}

function selectionSort($sort_array)
{
    $time_start = microtime(true);
    for ($i = 0; $i < count($sort_array) - 1; $i++)
    {
        $min = $i;
        for ($j = $i + 1; $j < count($sort_array); $j++)
        {
            if ($sort_array[$j] < $sort_array[$min]){
              $min = $j;
        }
      $temp = $sort_array[$i];
      $sort_array[$i] = $sort_array[$min];
      $sort_array[$min] = $temp;
    }
    $time_end = microtime(true);
    $time = $time_end - $time_start;
    echo $time;
    return $sort_array;
    }
}

function randomArray($max){
    $random = range(0, $max-1);
    shuffle($random );
    return  $random;
}


texts: string manipulation, which version of those 2 functions is better?

texts:
I wrote my own version of endswith just like in high-level programming languages in C which I would like reviews on.

There are 2 versions. One is my own and the other is from ccan. For some reason, I feel that ccan's version is better than mine until proven wrong.

ccan/str's version:

static inline bool strends(const char *str, const char *postfix)
{
    if (strlen(str) < strlen(postfix))
        return false;

    return strcmp(str + strlen(str) - strlen(postfix), postfix) == 0;
}

My version:

bool strends(const char *str, const char *postfix)
{
    register const char *end = str + strlen(str) - 1;
    register const char *epostfix = postfix + strlen(postfix) - 1;

    while (end > str && epostfix > postfix)
        if (*end-- != *epostfix--)
            return false;
    return true;
}

Update
This is the newer version of mine:

bool strends(const char *str, const char *postfix)
{
        register const char *end = str + strlen(str) - strlen(postfix);
        if (strlen(str) < strlen(postfix))
                return false;

        while (*end)
                if (*end++ != *postfix++)
                        return false;
        return true;
}

I wonder which one is better and why (in terms of readability, performance and so on).  Please be specific and provide your research if possible.

Thanks in advance.


texts:
Every time I go to write an MVVM application (say every 4-6 months) I rewrite my ViewModelBase class. This is for a range of reasons but let's say either I don't have access to prior code, the previous code was built for a client and isn't my code, or I'm working on someone else's machine and still don't have the code.

So I rewrite the basic INotifyPropertyChanged implementation, and I think it's a little different each time. Here's what I've come up with today:

public class ViewModelBase : INotifyPropertyChanged
{
    protected void OnPropertyChanged<T>(Expression<Func<T>> expression)
    {
        var property = (MemberExpression)expression.Body;
        this.OnPropertyChanged(property.Member.Name);
    }

    protected void OnPropertyChanged(string name)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(name));
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
}

I would like to get a nice implementation that is simple and small, and any improvements to this (what other functionality is required in a ViewModelBase?) would be great.


texts:
I found a code on my computer that i wrote a while ago. It is based on an exercise from O'Reilly book Programming the Semantic Web. There is a class, that stores RDF triples, that is data in the form subject-predicate-object:

class SimpleGraph:
    def __init__(self):
        self._spo = {}
        self._pos = {}
        self._osp = {}

    def add(self, (s, p, o)):
        # implementation details
        pass

    def remove(self, (s, p, o)):
        # implementation details
        pass

Variables _spo, _pos, _osp are different permutations of subject, predicate, object for performance reasons, and the underlying data structure is dictionary of dictionaries of sets like {'subject': {'predicate': set([object])}} or {'object': {'subject': set([predicate])}}. The class also has a method to yield triples that match the query in a form of a tuple. If one element of a tuple is None, it acts as a wildcard.

def triples(self, (s, p, o)):
    # check which terms are present
    try:
        if s != None:
            if p != None:
                # s p o
                if o != None:
                    if o in self._spo[s][p]:
                        yield (s, p, o)
                # s p _
                else:
                    for ro in self._spo[s][p]:
                        yield (s, p, ro)
            else:
                # s _ o
                if o != None:
                    for rp in self._osp[o][s]:
                        yield (s, rp, o)
                # s _ _
                else:
                    for rp, oset in self._spo[s].items():
                        for ro in oset:
                            yield (s, rp, ro)
        else:
            if p != None:
                # _ p o
                if o != None:
                    for rs in self._pos[p][o]:
                        yield (rs, p, o)
                # _ p _
                else:
                    for ro, sset in self._pos[p].items():
                        for rs in sset:
                            yield (rs, p, ro)
            else:
                # _ _ o
                if o != None:
                    for rs, pset in self._osp[o].items():
                        for rp in pset:
                            yield (rs, rp, o)
                # _ _ _
                else:
                    for rs, pset in self._spo.items():
                        for rp, oset in pset.items():
                            for ro in oset:
                                yield (rs, rp, ro)
    except KeyError:
        pass

You see, this code is huge, and i feel it could be more terse and elegant. I suspect the possible use of dicts here, where tuple (s, p, o) is matched with a certain key in this dict, and then the yield is done. But i have no idea how to implement it.

How can i simplify this huge if-else structure?


texts: Calculating the number of candy bars and gumballs that can be redeemed using coupons

texts:
The following question was taken from Absolute Java 5th ed. by Walter Savitch:

  The video game machines at your local arcade output coupons according to how well you play the game. You can redeem 10 coupons for a candy bar or 3 coupons for a gumball. You prefer candy bars to gumballs. Write a program that defines a variable initially assigned to the number of coupons you win. Next, the program should output how many candy bars and gumballs you can get if you spend all of your coupons on candy bars first, and any remaining coupons on gumballs.

This is the code that I have written:

public class Question2 {

    private static final int NUMBER_OF_COUPONS_FOR_A_CANDYBAR = 10;
    private static final int NUMBER_OF_COUPONS_FOR_A_GUMBALL = 3;

    private static int numberOfCoupons = 13;

    public static void main(String[] args) {

        System.out.println(numberOfCandybars(numberOfCoupons)
                + " candybar(s) and " + numberOfGumballs(numberOfCoupons)
                + " gumball(s).");

    }

    private static int numberOfCandybars(int initialCoupons) {
        return initialCoupons / NUMBER_OF_COUPONS_FOR_A_CANDYBAR;
    }

    private static int numberOfGumballs(int remainingCoupons) {
        remainingCoupons = numberOfCoupons % NUMBER_OF_COUPONS_FOR_A_CANDYBAR;
        return remainingCoupons / NUMBER_OF_COUPONS_FOR_A_GUMBALL;
    }
}


texts: How can this  be set up to maximize inheritance if additional classes will be passed in from a JSON file?

texts:
Objective

Currently I have the flags hardcoded. But want to optimize my code for production. So I am wondering if I have this code done clean enough to leverage CSS inheritance while maintaining support for older browsers.

I have this menu on my CodePen

whose size will vary per device (media queries not shown yet). I restructured my code from
's to this

HTML

North America

On the div with the flag, I want to be able to pass its CSS rules without giving it the class of intlFlag and for the intlButton I want to also pass rule without giving it the class. I hesitated to use the :last-of-type selector because it is not supported below IE8, and many users of the site will unfortunately use IE8.

Image from w3schools.com

As far as the first
 I want the class to be passed in based on what country they are detected to be coming from. So the script would for example detect that you are in North America. And then pass in that class which then sets your flag. In production I will be using MustacheJS templates. So I plan to do something like this

{{region}}

my JSON values might be something like

"flag":"usFlag",
"region":"North America"

That usFlag class would add this class to display the respective flag

.usFlag { background-position: 0px 0px; }

the other rules passed into that
 are currently passed in with

.intlFlag {
  background-color: #fff;
  background-image: url('https://s3-us-west-2.amazonaws.com/s.cdpn.io/101702/flag-sprite.png');
  height: 28px;
  width: 44px;
}

Here are the complete set of my CSS rules for this element

.international {
  background-color: rgba(96, 80, 80, 0.3);
  font-size: 18px;
  line-height: 42px;
  list-style-type: none;
  margin: auto;
  padding-left: 0;
  position: absolute;
  bottom: 0; left: 0; right: 0;
  width: 100%;
}
/* only on tablet */
.international { max-width: 240px; }

.international > li {
  display: inline-block;
  line-height: 42px;
  margin-left: 6px;
  vertical-align: middle;
}

.intlFlag {
  background-color: #fff;
  background-image: url('https://s3-us-west-2.amazonaws.com/s.cdpn.io/101702/flag-sprite.png');
  height: 28px;
  width: 44px;
}

.usFlag { background-position: 0px 0px; }

.intlButton {
  float: right;
  font-size: 24px;
  margin-right: 6px;
}
.intlButton a { color: #444; }
.intlButton i {
  background-color: rgba(225, 225, 225, .7);
  border-radius: 3px;
  padding: 4px;
}


texts: Handling rejected HTTP responses with status 401

texts:
I'm kinda new to javascript and have question about it. Now my practical project is growing a bit bigger. I got the following if else statement. Is it possible to refactor this ? Should i use an use case or are there other options or will this decrease the loading speed of the application.

(function () {
    'use strict';

    angular
        .module('app')
        .factory('HttpResponseInterceptor', HttpResponseInterceptor);

    HttpResponseInterceptor.$inject = ['$q','$location'];
    function HttpResponseInterceptor($q,$location) {

        return {
            response: function(response){
                if (response.status === 401) {

                }
                return response || $q.when(response);
            },
            responseError: function(rejection) {

                if(rejection.status ===401 && rejection.config.url === "user") {
                    console.log("Check")
                }
                else if (rejection.status ===401 &&  rejection.config.url == "l18n/fr_FR.json")
                {
                    console.log("Check2")
                }
                else if (rejection.status ===401 &&  rejection.config.url == "l18n/nl_NL.json")
                {
                    console.log("Check2")
                }
                else if (rejection.status ===401 &&  rejection.config.url == "l18n/de_DE.json")
                {
                    console.log("Check2")
                }
                else if (rejection.status ===401 &&  rejection.config.url == "l18n/es_ES.json")
                {
                    console.log("Check2")
                }
                else if (rejection.status ===401 &&  rejection.config.url == "l18n/en_US.json")
                {
                    console.log("Check2")
                }
                else
                {
                    $location.path('/login');
                }

               /* if (rejection.status === 401 && rejection.config.url !== "user") {

                    $location.path('/login');
                }*/
                return $q.reject(rejection);
            }
        };

    }

})();


texts:
I am just wondering if this is a correct way to execute multiple query from a text file.

Connection conn = Utility.getConnection();
Statement stmt = null;
try{
    JFileChooser chooser = new JFileChooser();
    int returnVal = chooser.showOpenDialog(chooser);
    if(returnVal == JFileChooser.APPROVE_OPTION) {
       String fileName=chooser.getCurrentDirectory().toString()+File.separator+chooser.getSelectedFile().getName();
       FileInputStream fstream = new FileInputStream(fileName);
       DataInputStream in = new DataInputStream(fstream);
       BufferedReader br = new BufferedReader(new InputStreamReader(in));
       String strLine;
       if(conn != null)
           stmt = conn.createStatement();
       while ((strLine = br.readLine()) != null)   {
           if(stmt !=null){
               int rc=stmt.executeUpdate(strLine);
               if(rc == 0)
                   System.out.println("executing:  "+strLine);
           }
       }
       stmt.close();
       conn.close();
       in.close();
    }
}catch (Exception e){
    e.printStackTrace();
}


texts:
Solving the merge intervals problem in golang(link: https://leetcode.com/problems/merge-intervals/).
The Problem
Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input.

Example 1:

Input: intervals = [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].
Example 2:

Input: intervals = [[1,4],[4,5]]
Output: [[1,5]]
Explanation: Intervals [1,4] and [4,5] are considered overlapping.

Code
package main

import (
    "fmt"
    "sort"
)

func main() {

    var intervals [][]int
    intervals = append(intervals, []int{7, 10})
    intervals = append(intervals, []int{3, 4})
    intervals = append(intervals, []int{2, 5})

    mergeIntervals(intervals)

}

func mergeIntervals(intervals [][]int) [][]int {

    if len(intervals) < 2{
        return intervals
    }
    var mergedIntervals [][]int
    fmt.Println("intervals :", intervals)
    sort.Slice(intervals, func(i, j int) bool {
        return intervals[i][0] < intervals[j][0]
    })

    previousEndTime := intervals[0][1]
    for index, _ := range intervals {

        if index >= len(intervals)-1 {

            if index == len(intervals)-1 {
                mergedIntervals = append(mergedIntervals, []int{intervals[index][0], intervals[index][1]})
            }
            break
        }
        if index != 0 {
            //skip current interval if previous interval end time is higher
            if previousEndTime > intervals[index][1] {
                continue
            }
        }
        fmt.Println("comparing intervals ", intervals[index], "and ", intervals[index+1])
        if intervals[index][1] > intervals[index+1][1] {
            //check if current end time greater than end time of next interval
            mergedIntervals = append(mergedIntervals, []int{intervals[index][0], intervals[index][1]})
            previousEndTime = intervals[index][1]
        } else if intervals[index][1] >= intervals[index+1][0] {
            //the actual merge for overlapping  values
            mergedIntervals = append(mergedIntervals, []int{intervals[index][0], intervals[index+1][1]})
            previousEndTime = intervals[index+1][1]
        } else {
            //just include current interval with no overlap
            mergedIntervals = append(mergedIntervals, []int{intervals[index][0], intervals[index][1]})
            previousEndTime = intervals[index][1]
        }
    }

    fmt.Println("merged intervals ", mergedIntervals)
    return mergedIntervals
}

Looking for

Code Bugs.
Feel this code is too verbose.Any suggestions on how to    optimize
the code further.


texts: Click the center of an image if that image appears on the screen

texts:
To be clear, this code is built to be used with the Snipping Tool and Robot Framework. Use the snipping tool to snip an image of something on the screen. A strange button with weird locators, something outside of the DOM... anything as long as it consistently repeats visually during your test. Then, send that image to the keyword, and the code will locate the center of that image on the screen and execute a click command at that location.

I'm currently looking for consistency suggestions, but if you also have optimization suggestions, I'd gladly accept those as well. It's very, very fast, but I'm running into a problem where the code doesn't find the image unless it's a relatively large image with some detail (larger than a tab on Google Chrome, I haven't found the exact "x pixels by y pixels" size). I'd like to be able to tell Robot Framework to click the "X" button to close the browser window without worrying about the exact pixel-based coordinates of the browser.

EDIT: That's an example of how small I'd like the image to be, not the ultimate goal of this code.

from robot.libraries.BuiltIn import BuiltIn
import pyautogui as pag

class click_by_image(object):
    def __init__(self):
        self.selenium_lib = None

    def click_by_image(self, image_name):
        """
        Click the center of a rectangle on the screen given the
        image_name of the image rectangle to search for
        :param image_name: Path to image
        """
        #   If ExtendedSelenium2Library instance is undefined
        if self.selenium_lib is None:
            # Instantiate ExtendedSelenium2Library
            self.selenium_lib = BuiltIn().get_library_instance('ExtendedSelenium2Library')
        pag.click(pag.locateCenterOnScreen(str(image_name)))

Here's an example of the use of the Robot Framework keyword, assuming the image of what you're trying to click is called button.png and is located in the same folder as the resource file it's being used in. I believe it will take most common formats of picture.

Click By Image  button.png


texts:
I am saving (image) files to PostgreSQL database in my Node.js and Express server application. The code is used to upload user images to server (at the moment it is not restricted to image files in any way though, but that's not the point). The files are sent as multipart requests and they are parsed using Busboy. These are then converted to hex strings which are put to database.

My main concern with this code is the stream handler that reads data from buffer and then concatenates it into a string. Is there a better way to do this and put the file to database?

app.post('/upload', function(req, res, next) {
  //Set busboy to parse file-inputs
  req.busboy.on('file', function(fieldName, file, filename) {
    //File data will be added to this string
    var fileData = '';

    //Add stream handler function for type data.
    //Function concatenates buffered data to fileData string in hex format.
    file.on('data', function(buffer) {
      fileData += buffer.toString('hex');
    });

    //Add stream handler for stream end.
    //Add \x to the beginning of the data to mark that it is hex formatted data.
    //Data string is then put to database.
    file.on('end', function() {
      fileData = '\\x' + fileData;

      //Get database client from pool and make query adding our data to the database.
      pg.connect(process.env.DATABASE_URL, function(err, client, done) {
        if (err) {
          return console.error('error fetching client from pool', err);
        }

        var query = 'INSERT INTO Files(data) VALUES ($1) RETURNING id';
        client.query(query, [fileData], function(err, writeResult) {
          //call `done()` to release the client back to the pool
          done();
          if (err) {
            return console.error('error running query', err);
          }
          client.end();

          var responseObject = {
            status: 'success',
            id: writeResult.rows[0].id,
            url: req.get('host') + '/files/' + writeResult.rows[0].id
          };
          res.json(responseObject);
        });
      });
    });
  });
  req.pipe(req.busboy);
});


texts:
I haven't written any Java in years and I wanted to catch up a little, especially on newer features. I started looking at streams and aggregate operations and came up with the following solution to Project Euler #7 (find the 10001st prime).

package com.example;
import java.util.stream.IntStream;
import org.apache.commons.lang3.time.StopWatch;

public class Main {
    static boolean isPrime(int i) {
        int limit = (int)Math.sqrt(i)+1;
        return !IntStream.range(2, limit)
                .anyMatch(n -> i % n == 0);
    }

    public static void main(String[] args) {
        StopWatch stopWatch = new StopWatch();
        int n = 10001;
        stopWatch.start();
        int nthPrime = IntStream.iterate(2, i -> i+1)
                .filter(Main::isPrime)
                .skip(n-1)
                .findFirst().getAsInt();
        stopWatch.stop();
        System.out.printf("The %dth prime is %d\n", n, nthPrime);
        System.out.printf("Execution time: %.2fs\n", (float)stopWatch.getTime()/1000);
    }
}

Is there any obvious way to speed it up? Am I overcomplicating something? My way of getting an infinite sequence of integers, for example. Any other feedback?


texts: Prints out all ways to multiply smaller integers that equal the original number

texts:
Write a program in Java that takes a positive integer and prints out all ways to multiply smaller integers that equal the original number, without repeating sets of factors.  In other words, if your output contains 4 * 3, you should not print out 3 * 4 again as that would be a repeating set.  Note that this is not asking for prime factorization only.

Here is the sample from one solution:

Example:

$ java -cp . PrintFactors 32

  32 * 1

  16 * 2

  8 * 4

  8 * 2 * 2

  4 * 4 * 2

  4 * 2 * 2 * 2

  2 * 2 * 2 * 2 * 2

I'm looking for code review, best practices, optimizations etc.

Verifying Complexity: \$O(n!)\$ - time, where \$n\$ is the input number.

public final class PrintFactors {

    private PrintFactors() {}

    public static void printFactors(int number) {
        if (number <= 0) throw new IllegalArgumentException("The number should be greater than 0.");
        printFactorsList(number, number + "*" + 1 + "\n", number);
    }

    private static void printFactorsList(int dividend, String factorString, int prevDivisor) {
        /*
         * This function contains factorString as an argument to facilitate the recursive call for subsequent
         * factors until it reaches prime values. For example, let's say input number = 32 and when i = 8 it prints
         * 8*(32/8) ==> 8 * 4 but the subsequent reduction of 4 is needed and this is done by recursively passing in 4
         * as number. But we also want to maintain the chain "8 * ". So this makes the carry over string as an input
         * argument for the helper function printFactorsList
         */
        for (int divisor = dividend - 1; divisor >= 2; divisor--) {

            if (dividend % divisor != 0)
                continue;

            if (divisor > prevDivisor)
                continue;

            int quotient = dividend / divisor;

            /*
             * 32*1 16*2 8*4 8*2*2 4*4*2 4*2*2*2 2*2*2*2*2
             *
             * Note: as we go right, the values keeps descending.
             */
            if (quotient <= divisor) {
                if (quotient <= prevDivisor) {
                    System.out.println(factorString + divisor + "*" + quotient);
                }
            }
            printFactorsList(quotient, factorString + divisor + "*", divisor);
        }
    }

    public static void main(String[] args) {
        printFactors(12);
        System.out.println();
        printFactors(32);
    }
}


texts: Function "between" for "Everything in One Line" library

texts:
This is a function to determine if a number is between x and y. It is part of a library of mine called EOL or "Everything in One Line".

#include <stdbool.h>

#ifndef _WINDOWS_H
    #include <windows.h>
#endif

bool between (WORD n, WORD x, WORD y) { return (n >= x && n <= y) ? (true) : (false); }


texts:
Defines a simple module for timeoutable computations, with the ability to return
arbitrary intermediary results on timeout or the final value otherwise. It also
allows default return values.

The implementation uses Unix.sigalrm to define timeout intervals with second resolution.
There is a small overhead on starting the computation, because we have to set up
signal handlers and only then call the Functor's 'call' method. Similarily, there is a
small overhead on returning the computation result (partial or final), as we have
to restore the original SIGALRM signal handler. Those should amortize if the actual
computation takes some time (seconds) - and this is the context in which you would want
to use the Timeout module anyway.

For using this, define your own module respecting the Timeoutable interface.
Implement functionality in the call function. If you need to return intermediary
results on timeout, catch the CallTimeout exception and return an appropiate value.
If the code you write raises and does not catch an exception, the call function
will return with the default value. The same thing happens if you don't catch the
CallTimeout exception in your code and it timeouts.

exception CallTimeout;;

type ('p,'f) result =
    [ `Timeout of 'p (* partial result *)
    | `Done of 'f    (* final result   *)
    | `Error of string
    ]

module type Timeoutable =
sig
  type ('p,'f) t
  type arg

  val default: ('p,'f) t
  val call: arg -> ('p,'f) t

end

module Timeout (U:Timeoutable) =
struct
    let sigalrm_handler = Sys.Signal_handle (fun _ -> raise CallTimeout);;

    let tcall arg timeout =
        let old_behaviour = Sys.signal Sys.sigalrm sigalrm_handler in
        let reset_sigalrm () = Sys.set_signal Sys.sigalrm old_behaviour in
          ignore (Unix.alarm timeout);
      try
            let res = U.call arg in reset_sigalrm(); res;
      with exn -> reset_sigalrm(); U.default;
end

Using it:

module AddTwo = struct
  type ('p,'f) t = (int,int) Timeout.result
  type arg = int

  let default = `Error "could not complete AddTwo"

  let call a =
    try
      ignore(Unix.sleep 2);
      `Done (a+2)
    with
      | Timeout.CallTimeout-> `Timeout (a+1)
end

module Test = Timeout.Timeout(AddTwo);;

let r = Test.tcall 7 10 in
  match r with
    | `Done x    -> print_int x
    | `Timeout b -> print_string "Function timeout, partial result: "; print_int b
    | `Error s   -> print_string s

Any ideas on how to improve this? What other features would you require for timeoutable computations?


texts: The code duplication reducing in the linked list implementation

texts:
I am writing the linked list data structure, using this question's requirements (the method set).

I have written two working methods, which do the similar thing and differs by only few lines. So, I tried to refactor them and although I move the duplicate part to the separate function, the code became more verbose. Also, it added two function calls overhead, that is not good for data structure implementations.

The question:

Do you see another way to duplication elimination?
I understand, that in this particular case, it will be better to leave everything as it is, without refactoring. But from the point of best production practices and "pythonic" way, which variant will be better?

Before refactoring

def insert_before_key(self, key, value):
        new_node = Node(value)
        prev, curr = self._find_key(key)

        if curr:
            if prev:
                new_node.next = curr            # differs
                prev.next = new_node            # differs
            else:
                new_node.next = self.head       # differs
                self.head = new_node            # differs

def insert_after_key(self, key, value):
        new_node = Node(value)
        prev, curr = self._find_key(key)

        if curr:
            if prev:
                new_node.next = curr.next       # differs
                curr.next = new_node            # differs
            else:
                new_node.next = self.head.next  # differs
                self.head.next = new_node       # differs

After refactoring

# Common part was moved to this function
def insert(self, key, value, with_prev, non_prev):
    new_node = Node(value)
    prev, curr = self._find_key(key)

    if curr:
        if prev:
            with_prev(prev, curr, new_node)
        else:
            non_prev(prev, curr, new_node)

# put two little chunks of code to the nested functions
# and pass them to the "insert" function, that implement the logic
def insert_before_key(self, key, value):
    def with_prev(prev, curr, new_node):
        new_node.next = curr
        prev.next = new_node

    def non_prev(prev, curr, new_node):
        new_node.next = self.head
        self.head = new_node

    self.insert(key, value, with_prev, non_prev)

def insert_after_key(self, key, value):
    def with_prev(prev, curr, new_node):
        new_node.next = curr.next
        curr.next = new_node

    def non_prev(prev, curr, new_node):
        new_node.next = self.head.next
        self.head.next = new_node

    self.insert(key, value, with_prev, non_prev)