texts:
I made a page to generate a random color with JavaScript and set that color to the background of the page.

//Global Variables
const hexChars = '0123456789ABCDEF';
const container = document.getElementById('container');
const hexText = document.getElementById('hex-text');

//Function to generate random hex code

function randomColor() {
 let hexCode = '#';
 for(i=0; i<=5; i++) {
   let randomNum = Math.floor(Math.random() * 16);
    hexCode += hexChars[randomNum];
  }
  return hexCode;
}

//Function to change page color & text

function applyColor() {
  let hexCode = randomColor();
 container.style.backgroundColor = hexCode;
  hexText.innerHTML = hexCode;
}

//Make random color on page load, click, and spacebar press.
window.onload = applyColor();
container.onclick = () => applyColor();
document.body.onkeyup = e => {
  if(e.keyCode == 32) {
    applyColor();
  }
}
* {
  margin: 0;
  padding: 0;
  user-select: none;
}

#container {
  position: absolute;
  height: 100%;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: background-color .4s;
}

#hex-text {
  font-family: sans-serif;
  font-size: 2em;
  color: white;
  background-color: rgba(150, 150, 150, .6);
  padding: .4em;
  border-radius: 6px;
}

    #000000

How can I improve the efficiency or functionality of the JavaScript?

Edit: I'd also like to know if this is a fair generator, or if it's more likely to get one shade than another. I don't see why it would, but you never know.


texts: Coloured bash prompt including git status and previous exit code

texts:
I wanted to create a short, informational and colourful prompt.

My prompt includes:

Exit status of last command (if not 0)
Distinctive changes when root
rsync-style user@host:pathname for copy-paste goodness
Git branch, index, modified, untracked and upstream information
Pretty colours

Example:

Is there a way to achieve a similar result with less lines of code?

In ~/.bashrc:

#
# Set the prompt #
#

# Select git info displayed, see /usr/lib/git-core/git-sh-prompt for more
export GIT_PS1_SHOWDIRTYSTATE=1           # '*'=unstaged, '+'=staged
export GIT_PS1_SHOWSTASHSTATE=1           # '$'=stashed
export GIT_PS1_SHOWUNTRACKEDFILES=1       # '%'=untracked
export GIT_PS1_SHOWUPSTREAM="verbose"     # 'u='=no difference, 'u+1'=ahead by 1 commit
export GIT_PS1_STATESEPARATOR=''          # No space between branch and index status
export GIT_PS1_DESCRIBE_STYLE="describe"  # detached HEAD style:
#  contains      relative to newer annotated tag (v1.6.3.2~35)
#  branch        relative to newer tag or branch (master~4)
#  describe      relative to older annotated tag (v1.6.3.1-13-gdd42c2f)
#  default       exactly eatching tag

# Check if we support colours
__colour_enabled() {
    local -i colors=$(tput colors 2>/dev/null)
    [[ $? -eq 0 ]] && [[ $colors -gt 2 ]]
}
unset __colourise_prompt && __colour_enabled && __colourise_prompt=1

__set_bash_prompt()
{
    local exit="$?" # Save the exit status of the last command

    # PS1 is made from $PreGitPS1 + <git-status> + $PostGitPS1
    local PreGitPS1="${debian_chroot:+($debian_chroot)}"
    local PostGitPS1=""

    if [[ $__colourise_prompt ]]; then
        export GIT_PS1_SHOWCOLORHINTS=1

        # Wrap the colour codes between \[ and \], so that
        # bash counts the correct number of characters for line wrapping:
        local Red='\[\e[0;31m\]'; local BRed='\[\e[1;31m\]'
        local Gre='\[\e[0;32m\]'; local BGre='\[\e[1;32m\]'
        local Yel='\[\e[0;33m\]'; local BYel='\[\e[1;33m\]'
        local Blu='\[\e[0;34m\]'; local BBlu='\[\e[1;34m\]'
        local Mag='\[\e[0;35m\]'; local BMag='\[\e[1;35m\]'
        local Cya='\[\e[0;36m\]'; local BCya='\[\e[1;36m\]'
        local Whi='\[\e[0;37m\]'; local BWhi='\[\e[1;37m\]'
        local None='\[\e[0m\]' # Return to default colour

        # No username and bright colour if root
        if [[ ${EUID} == 0 ]]; then
            PreGitPS1+="$BRed\h "
        else
            PreGitPS1+="$Red\u@\h$None:"
        fi

        PreGitPS1+="$Blu\w$None"
    else # No colour
        # Sets prompt like: ravi@boxy:~/prj/sample_app
        unset GIT_PS1_SHOWCOLORHINTS
        PreGitPS1="${debian_chroot:+($debian_chroot)}\u@\h:\w"
    fi

    # Now build the part after git's status

    # Highlight non-standard exit codes
    if [[ $exit != 0 ]]; then
        PostGitPS1="$Red[$exit]"
    fi

    # Change colour of prompt if root
    if [[ ${EUID} == 0 ]]; then
        PostGitPS1+="$BRed"'\$ '"$None"
    else
        PostGitPS1+="$Mag"'\$ '"$None"
    fi

    # Set PS1 from $PreGitPS1 + <git-status> + $PostGitPS1
    __git_ps1 "$PreGitPS1" "$PostGitPS1" '(%s)'

    # echo '$PS1='"$PS1" # debug
    # defaut Linux Mint 17.2 user prompt:
    # PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[01;34m\] \w\[\033[00m\] $(__git_ps1 "(%s)") \$ '
}

# This tells bash to reinterpret PS1 after every command, which we
# need because __git_ps1 will return different text and colors
PROMPT_COMMAND=__set_bash_prompt

[Note: the current code based upon feedback received is here]


texts: "EnumSpace" - enum inheritance attempt using namespace macro

texts:
EnumSpace

This file enables the use of a utility I like to call "EnumSpace". This utility is enums and namespaces combined together in order to create an entity that acts like an enum that is able to inherit and extend an already existing one.

It provides three macros for that purpose:

ENUMSPACE_CREATE
ENUMSPACE_EXTEND
ENUMSPACE_END

ENUMSPACE_CREATE should be used to create a new, independent EnumSpace. It receives the name you would like to give your EnumSpace as an argument.

ENUMSPACE_EXTEND should be used to extend an already existing EnumSpace. It receives two arguments:

The name of the EnumSpace you would like to inherit.
The name of the new EnumSpace.

ENUMSPACE_END should be used like a closing bracket to each of the above.

Usage example:

#include ".../enumspace.hpp"

ENUMSPACE_CREATE( First )         ONE                 ENUMSPACE_END
ENUMSPACE_EXTEND( First, Second ) TWO,   THREE, FOUR  ENUMSPACE_END
ENUMSPACE_EXTEND( Second, Third ) FIVE,  SIX,   SEVEN ENUMSPACE_END
ENUMSPACE_EXTEND( Third, Fourth ) EIGHT, NINE,  TEN   ENUMSPACE_END

int main()
{
std::cout
<< Fourth::ONE
<< Fourth::TWO
<< Fourth::THREE
<< Fourth::FOUR
<< Fourth::FIVE
<< Fourth::SIX
<< Fourth::SEVEN
<< Fourth::EIGHT
<< Fourth::NINE
<< Fourth::TEN;
}

Output:

0 2 3 4 6 7 8 10 11 12

You probably noticed the inconsistency. The ability to stitch EnumSpaces comes with a price: it is impossible to retain a straight streak of numbers automatically.

[ONE = 0, _last( = 1)]
[_first = _last = 1, 2, 3, 4, _last( = 5)]
[_first = _last = 5, 6, 7, 8, _last( = 9)]
[_first = _last = 9, 10, 11, 12, _last( = 13)]

You CAN manually declare the first element you add to be "first" (-> the previous inherited namespace`s "last"):

ENUMSPACE_CREATE( First )         ONE                          ENUMSPACE_END
ENUMSPACE_EXTEND( First, Second ) TWO   = _first, THREE, FOUR  ENUMSPACE_END
ENUMSPACE_EXTEND( Second, Third ) FIVE  = _first, SIX,   SEVEN ENUMSPACE_END
ENUMSPACE_EXTEND( Third, Fourth ) EIGHT = _first, NINE,  TEN   ENUMSPACE_END

Which will result in:

[ONE = 0, _last( = 1)] V  V  V
[_first = _last = 1,  |1, 2, 3,| _last( = 4)]
[_first = _last = 4,  |4, 5, 6,| _last( = 7)]
[_first = _last = 7,  |7, 8, 9,| _last( = 10)]

Or in clear output:

0 1 2 3 4 5 6 7 8 9

Please note that, even though the macro seems to work OK, it relies on behavior I'm not quite sure is defined.

The macro adds a _first and _last elements to any EnumSpace created to facilitate the "stitch" between them.

Now, what would happen when you extend the EnumSpace more than once? There would be more than one _last for the new _first to pick from...

The macro seems to work just fine, and my guess is this happens because whenever the macro asks for the previous EnumSpace's _last, it receives the one in the closest scope, which is the latest inherited EnumSpace's. It`s rather ambiguous, however, and your compiler might scream at you. Consider yourself warned.

One last note: You'll probably want to prefix your values with something when using this macro so that you can filter the namespaces names that get inherited along out of auto completion.

#define ENUMSPACE_CREATE(EnumSpaceName) \
    namespace EnumSpaceName {\
        enum {

#define ENUMSPACE_EXTEND(EnumSpace, NewEnumSpaceName) \
    namespace NewEnumSpaceName {\
        using namespace EnumSpace;\
        enum { _first = EnumSpace::_last,

#define ENUMSPACE_END \
    , _last }; }

Will this work? I mean, I tested this. As you can tell by the output provided. But, if something is fundamentally wrong with this, please let me know.


texts:
How can the normalize() method below be improved? I've extracted the functionality from a project I'm working on into a simple class for the purposes of this question.

The method takes a string input and compares it to a set of 'truthy' and 'falsey' strings, returning true or false respectively if a case insensitive match is found. The truthy and falsey strings are mutable so cannot be hard coded into the method.

If the $nullable property is set to true and no match is found, null is returned. Otherwise false is returned.

I feel as though I may be missing a trick by looping through the array and calling strcasecmp twice for each iteration.

<?php

class BooleanNormalizer
{
    /** @var array */
    public $binaries = [
        'yes'     => 'no',
        '1'       => '0',
        'on'      => 'off',
        'enabled' => 'disabled',
    ];

    /** @var bool */
    public $nullable = false;

    /**
     * @param string $value
     *
     * @return bool|null
     */
    public function normalize($value)
    {
        foreach ($this->binaries as $truthy => $falsey) {
            if (strcasecmp($value, $truthy) === 0) {
                return true;
            }

            if (strcasecmp($value, $falsey) === 0) {
                return false;
            }
        }

        return ($this->nullable) ? null : false;
    }
}

Usage:

$normalizer = new BooleanNormalizer();

$normalizer->nullable = true;
$normalizer->binaries = ['enabled' => 'disabled'];

$normalizer->normalize('enabled'); // returns true
$normalizer->normalize('disabled'); // returns false
$normalizer->normalize('blah'); // returns null


texts: Read from SQL database table, store in list of objects

texts:
IList<WebSite> wsl = new List<WebSite>();
 login1 l = new login1();

 string q = "select Id, DomainUrl, IsApproved, Date from website where UserId = @UserId";

 using (MySqlConnection con = new MySqlConnection(WebConfigurationManager.ConnectionStrings["MySqlConnectionString"].ToString()))
 {
      using (MySqlCommand cmd = new MySqlCommand(q, con))
      {
           cmd.Parameters.Add("@UserId", MySqlDbType.Int32).Value = userId;
           con.Open();

           var reader = cmd.ExecuteReader();
           while (reader.Read())
           {
                var ws = new WebSite();
                ws.Id = reader.GetInt32("Id");
                ws.DomainUrl = reader.GetString("DomainUrl");
                ws.IsApproved = reader.GetBoolean("IsApproved");
                ws.User.Id = reader.GetInt32("UserId");
                ws.Date = reader.GetDateTime("Date");
                wsl.Add(ws);
           }
           reader.Close();
           return wsl;
      }
 }

I want to make this code as elegant as possible.

For this particular project I cannot use NHibernate as I have been instructed.


texts: Reading from file and storing as Linked List

texts:
This is the code I have:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct island{
    char *name;
    struct island *nextIsland;
} island;

void printIslands(island *i){
    printf("%s\n",i->name);
    if(i->nextIsland != NULL){
        printIslands(i->nextIsland);
    }
}

island* fileReader(FILE *file){
    island *i = malloc(sizeof(island));
    char islandName[20];
    int fileRead = fscanf(file,"%s",islandName);
    if(fileRead != EOF){
        i->name = strdup(islandName);
        i->nextIsland = fileReader(file);
    }
    if(fileRead == EOF) {
        return NULL;
    }
    return i;
}

int main(){
    FILE *x = fopen("islands.txt","r");
    island *i = fileReader(x);
    printIslands(i);
    fclose(x);
}

Input file:

 islandone
 islandtwo
 islandthree
 islandfour
 islandfive

The output of the program will be exactly same with the input file, which is desired.

My question is, do you think fileReader is too complicated and fragile? How would you implement fileReader? Would you create a createIsland method and somehow use it in the fileReader?

Any comments welcome on the code.


texts:
Please review for performance and C# style.

I already solved this question in 1 way.
LeetCode: trapping rain water C#

I tried also the dynamic programming approch

https://leetcode.com/problems/trapping-rain-water/

using System;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace ArrayQuestions
{
    /// <summary>
    /// https://leetcode.com/problems/trapping-rain-water/
    /// </summary>
    [TestClass]
    public class TrappingRainWater
    {
        [TestMethod]
        public void TestMethod1()
        {
            int[] height = { 0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1 };
            Assert.AreEqual(6, TrapDynamicProgramming(height));
        }

        public int TrapDynamicProgramming(int[] height)
        {
            if (height == null || height.Length == 0)
            {
                return 0;
            }

            int ans = 0;
            int size = height.Length;
            var leftMax = Enumerable.Repeat(0, size).ToList();
            var rightMax = Enumerable.Repeat(0, size).ToList();

            //compute the max height from the left for each cell
            //starting from the left
            leftMax[0] = height[0];
            for (int i = 1; i < size; i++)
            {
                leftMax[i] = Math.Max(height[i], leftMax[i - 1]);
            }

            //compute the max height from the right for each cell
            //starting from the right..
            rightMax[size - 1] = height[size - 1];
            for (int i = size - 2; i >= 0; i--)
            {
                rightMax[i] = Math.Max(height[i], rightMax[i + 1]);
            }

            //the amount of water is the minimal between left and right height.
            // and we need to remove the height of the cell, think of this
            // like where the ground starts
            for (int i = 1; i < size - 1; i++)
            {
                ans += Math.Min(leftMax[i], rightMax[i]) - height[i];
            }

            return ans;
        }
}


texts: The use of database "sets" rather than "functions"

texts:
I've currently got a MSSQL stored procedure that uses multiple SQL functions to achieve a number of returns. Now I've been told about using sets rather than functions as it creates " bad code smell of a DBA who is not yet thinking in sets" Original Link
I'd like to better my code and love to know what sets are. So below are two of my functions from a long list of functions. Thanks to any that attempt the answer.
Function that returns a long list of values
CREATE FUNCTION dbo.funcGetPropertyEnviListFR
(
    @PropertyId AS INT
)
RETURNS VARCHAR(200)
AS
BEGIN
    DECLARE @ENVIFR VARCHAR(200)
    SET @ENVIFR = ''

        SELECT
            @ENVIFR = COALESCE(@ENVIFR + ', ', '') + ENVIRONMENT.FR
        FROM
            ENVIRONMENT
        INNER JOIN
            MATRIXPROPENVIRONMENT
        ON
            MATRIXPROPENVIRONMENT.EnvironmentId = ENVIRONMENT.id
        WHERE
            MATRIXPROPENVIRONMENT.PropertyId = @PropertyId
        ORDER BY
            Weight

        SET @ENVIFR = SUBSTRING(@ENVIFR, 3, 200)
        RETURN @ENVIFR
END

Result may look like - Coastal, Village, Habitat
Function that returns a seller's ID
CREATE FUNCTION dbo.funcSellIdByPropId
(
@PropertyId AS INT
)
RETURNS INT
AS
    BEGIN
        DECLARE @ID AS INT
        SET @ID = 0
            SELECT
        @ID = MATRIXAGENCYPROPERTY.AgencyId
    FROM
        MATRIXAGENCYPROPERTY
    WHERE
        MATRIXAGENCYPROPERTY.PropertyId = @PropertyId

    IF @ID = 0
        BEGIN
            SELECT
                @ID = PRIVATESELLERS.id
            FROM
                PRIVATESELLERS
            WHERE
                PRIVATESELLERS.PropertyId = @PropertyId
END

RETURN @ID
END

Result may look like - 43
Function that returns an image value from database
CREATE FUNCTION dbo.funcDefaultImage
(
    @PropertyId INT,
    @Position INT
)

RETURNS VARCHAR(50)

AS
BEGIN
    DECLARE @IMAGE VARCHAR(50)

    SELECT @IMAGE = T.image
    FROM (
        SELECT
            ROW_NUMBER() OVER (ORDER BY weight DESC) AS [rownum],
            PROPERTYGALLERY.image
        FROM
            PROPERTYGALLERY
        WHERE
            PROPERTYGALLERY.PropertyId = @PropertyId
    ) T
    WHERE
        rownum = @Position

    RETURN @IMAGE
END

Result may look like - property_0001.png


texts:
I've got this working JavaScript (example is [here][1]), which should work the same as on the Stack Exchange network.

How can I simplify it a bit?

function yellow() {
    return 'rgb(255, 255, 0)';
}

$(function() {
    $(".post-upvote").click(function() {
      //  ajax(url + "upvote/" + $(this).attr('data-postid'), false, false);

        if ($(this).parent().children('.post-downvote').css('background-color') == yellow()) { // user upvoted so let's delete upvote
            $(this).parent().children('.post-votes').text(parseInt($(this).parent().children('.post-votes').text()) + parseInt(1));
        }
        $(this).parent().children('.post-downvote').css('background-color', 'white');

        if ($(this).css('background-color') == yellow()) { // if it's yellow, user is canceling his downvote
            $(this).css('background-color', 'white');
            $(this).parent().children('.post-votes').text(parseInt($(this).parent().children('.post-votes').text()) - parseInt(1));
        }
        else {
            $(this).css('background-color', 'yellow');
            $(this).parent().children('.post-votes').text(parseInt($(this).parent().children('.post-votes').text()) + parseInt(1));
        }
    });
    $(".post-downvote").click(function() {
       // ajax(url + "downvote/" + $(this).attr('data-postid'), false, false);

        if ($(this).parent().children('.post-upvote').css('background-color') == yellow()) { // user upvoted so let's delete upvote
            $(this).parent().children('.post-votes').text(parseInt($(this).parent().children('.post-votes').text()) - parseInt(1));
        }

        $(this).parent().children('.post-upvote').css('background-color', 'white');

        if ($(this).css('background-color') == yellow()) { // if it's yellow, user is canceling his downvote
            $(this).css('background-color', 'white');
            $(this).parent().children('.post-votes').text(parseInt($(this).parent().children('.post-votes').text()) + parseInt(1));
        }
        else {
            $(this).css('background-color', 'yellow');
            $(this).parent().children('.post-votes').text(parseInt($(this).parent().children('.post-votes').text()) - parseInt(1));
        }
    });
});


texts:
I was watching a C++ Talk and he showed some code for a basic for_each_adjacent.
I took the base concept and improved it a little bit, I am wondering if i could have any feedback. It automatically deduces the amount of parameters.

My main concern is the remainder. I am not sure to pass in a epilogue function for the remaining variables, or a pointer to remaining variables. If i use an epilogue function, I can foresee some issues with a vectors, because its size can change a run time. Ultimately that would force the epilogue to have the same parameter count as the lambda, and which some of the values would be null, but I would have to set them to 0 and it could be a headache to tell if they are really 0 or supposed to be null? Hopefully that makes sense. Anyways, here is the video which started the whole thing if your curious.

#include <iostream>
#include <numeric>
#include <array>
#include <cstring>
#include <optional>

namespace detail
{
    template<class Function, class Iterator, unsigned... IntegerSequence>
    auto apply(Function f, Iterator first, std::integer_sequence<unsigned, IntegerSequence...>)
    {
        return f(*std::next(first, IntegerSequence)...);
    }
    template<typename F>
    struct arg_count : arg_count<decltype(&F::operator())> {};

    template<typename F,typename Return,typename... Args>
    struct arg_count<Return(F::*)(Args...)const>
    {
        static const unsigned value = sizeof...(Args);
    };

    template<typename F>
    constexpr const unsigned arg_count_v = arg_count<F>::value;
}

//Returns a pointer to the remainder values or the end or nullptr
template<class Iterator,class Function>
auto for_each_adjacent(Iterator begin,Iterator end,Function func)
    -> std::optional<typename std::iterator_traits<Iterator>::pointer>
{
    using value_type = typename std::iterator_traits<Iterator>::value_type;
    const value_type length = std::distance(begin,end);
    const std::ptrdiff_t remainder = length % detail::arg_count_v<Function>;

    for (auto d = length; d >= detail::arg_count_v<Function>; d -= detail::arg_count_v<Function>)
        detail::apply(func,(end - d),std::make_integer_sequence<unsigned,detail::arg_count_v<Function>>());

    return (remainder) ? std::make_optional(end - remainder) : std::nullopt;
}

int main()
{
    std::array<int,256> test_array{};
    std::iota(test_array.begin(),test_array.end(),0);

    std::optional<int*> leftover_values = for_each_adjacent(test_array.begin(),test_array.end(),[](int a,int b,int c) {
        std::cout << a << "," << b << "," << c << "\n";
    });

    std::cout << leftover_values.value()[0]; // 255;
}


texts: Count the number of ways to obtain a sum, with consecutivity restriction

texts:
A cricketer can score 1, 2, 4 or 6 in a ball. Find in how many ways the player can score a total of "n" runs without hitting 3 consecutive boundaries. Note: Scoring 4 or 6 is considered as a boundary.

My solution is:

int *arr; //global array to save calculated ways
int waysUtil(int n, int boundaries){

     if(n==0)
        return 1;
     if(n<1)
        return 0;

    if(arr[n]>0)
        return arr[n];//if already calculated return the value
    int hit_one = waysUtil(n-1, 0);
    if(n-1 >=0) arr[n-1]= hit_one;
    int hit_two = waysUtil(n-2, 0);
    if(n-2 >=0) arr[n-2] = hit_two;
    int hit_four=0, hit_six=0;
    // for 4 and 6 check number of consecutive boundaries hit.
    //if less than two then calculate
    if(boundaries<2 ){

        hit_four = waysUtil(n-4, boundaries + 1);
        if(n-4 >=0) arr[n-4] = hit_four;
        hit_six = waysUtil(n-6, boundaries + 1);
        if(n-6 >=0) arr[n-6] = hit_six;

    }
    return hit_one + hit_two + hit_four + hit_six;
}

int ways(int score){
    arr =(int*)malloc(sizeof(int)*score);
    memset(arr, -1, sizeof(arr));
    int noOfWays = waysUtil(score, 0);
    free(arr);
    return noOfWays;
}

Is better solution possible?


texts:
I wonder if the code below is a good (quality and correctness) implementation of a single linked list in C++, in regard of data structure (not the exposed interface).

class List
{
  class Node
  {
    friend class List;
    int value;
    Node *next;
  };
  Node *head, *last;

  public:
  int size;
  List()
  {
    head = new Node;
    head->next = 0;
    last = head;
    size = 0;
  }
  ~List()
  {
    Node *it = head, *next;
    while (it)
    {
      next = it->next;
      delete it;
      it = next;
    }
  }
};


texts: Coherent usage of Hibernate's session and DAO

texts:
public void something()
{
    Session session = HibernateUtil.newSession();
    AModelDAO amd = new AModelDAO(session);
    BModelDAO bmd = new BModelDAO(session);

    Transaction tx = session.beginTransaction();
    amd.savesomething(object);
    bmd.savesomething(object2);
    tx.commit();
    session.close();
}

I would like to know if my coding here is good enough or if there is a better method to produce the same result.


texts:
Given a string, return the sum of all the numbers in the string, 0 if none are present.

Below is my solution for the problem above. I feel like this can be turned into one line. I would really only like suggestions on the actual algorithm, but anything else is appreciated.

def sum_numbers(string: str) -> int:
    """
    Returns the sum of all the numbers in the string
    """
    num_sum = 0
    for char in string:
        if char.isnumeric():
            num_sum += int(char)
    return num_sum

if __name__ == '__main__':

    # Test Cases #

    assert sum_numbers("123") == 6
    assert sum_numbers("abc") == 0
    assert sum_numbers("4x7") == 11
    assert sum_numbers("wefbyug87iqu") == 15
    assert sum_numbers("123456789") == 45


texts: Group by lastName and variable firstName

texts:
I'm trying to solve a problem of how to group name objects. A name has firstName and lastName properties. Need to group the name objects that have identical lastnames and a similar firstName(aka Tom Smith and Thomas Smith should be grouped together). Case doesn't matter. The firstName equivalency is provided by a string separated by ";"'s.
example:
input:
const FIRST_NAME_DICTIONARY =
  "Robert, Bob, Bobby; Liz, Elizabeth, Beth; Tom, Thomas";

const people = [
  { firstName: "robert", lastName: "smith" },
  { firstName: "Liz", lastName: "thomas" },
  { firstName: "robert", lastName: "smith" },
  { firstName: "Thomas", lastName: "hardin" },
  { firstName: "Elizabeth", lastName: "thomas" },
  { firstName: "bob", lastName: "smith" },
  { firstName: "Bobby", lastName: "smith" },
  { firstName: "ryan", lastName: "roberts" },
  { firstName: "bob", lastName: "wallace" },
  { firstName: "bobby", lastName: "smith" },
  { firstName: "beth", lastName: "roberts" },
  { firstName: "beth", lastName: "thomas" },
  { firstName: "Tom", lastName: "hardin" },
];

output:
[
    [
      { firstName: 'robert', lastName: 'smith' },
      { firstName: 'robert', lastName: 'smith' },
      { firstName: 'bob', lastName: 'smith' },
      { firstName: 'Bobby', lastName: 'smith' },
      { firstName: 'bobby', lastName: 'smith' }
    ],
    [
      { firstName: 'Liz', lastName: 'thomas' },
      { firstName: 'Elizabeth', lastName: 'thomas' },
      { firstName: 'beth', lastName: 'thomas' }
    ],
    [
      { firstName: 'Thomas', lastName: 'hardin' },
      { firstName: 'Tom', lastName: 'hardin' }
    ],
    [ { firstName: 'ryan', lastName: 'roberts' } ],
    [ { firstName: 'bob', lastName: 'wallace' } ],
    [ { firstName: 'beth', lastName: 'roberts' } ]
]

Here's what I have now:
const groupDuplicates = (list, dictionary) => {
  const mappedNames = mapDictionary(dictionary);
  const groupByNames = {};
  people.forEach((person) => {
    // gets the id equivalent for firstName or use the firstName it the id DNE
    const firstNameId =
      mappedNames[person?.firstName?.toLowerCase()] ||
      person?.firstName.toLowerCase(); // example 1 or ryan since ryan dne in the dictionary
    const stringifyKey = JSON.stringify([
      firstNameId,
      person.lastName.toLowerCase(),
    ]); // example "[1, smith]"

    // if key exists push to that array, otherwise create the key and then push
    if (groupByNames[stringifyKey]) {
      groupByNames[stringifyKey].push(person);
    } else {
      groupByNames[stringifyKey] = [person];
    }
  });

  // essentially convert object into array
  const keys = Object.keys(groupByNames);
  const groupByNamesArray = [];
  keys.forEach((key) => {
    groupByNamesArray.push(groupByNames[key]);
  });

  return groupByNamesArray;
};

// {
//     robert: 1,
//     bob: 1,
//     bobby: 1,
//     liz: 2,
//     elizabeth: 2,
//     beth: 2,
//     tom: 3,
//     thomas: 3
// }
const mapDictionary = (dictionary) => {
  const nameGroups = dictionary.split(";");
  let nameKey = 1;
  const mapNameToKey = {};
  nameGroups.forEach((nameGroup) => {
    const names = nameGroup.split(",");
    names.forEach((name) => {
      const noSpacesAndLowercase = name.trim().toLowerCase();
      mapNameToKey[noSpacesAndLowercase] = nameKey;
    });
    nameKey += 1;
  });
  return mapNameToKey;
};

Seems to work but is there a better way to accomplish this? I think the JSON.stringify seems a little hacky.


texts: Prime numbers less than a given number N

texts:
So, I began this challenge on CodeEval, which asks to print out the number of prime numbers less than any given integer N, where 0 < N < 4,294,967,295, ideally in O(N log N) time.  I came up with this solution:

import java.io.*;
public class Main {
    public static void main (String[] args) throws IOException {
        File file = new File(args[0]);
        BufferedReader buffer = new BufferedReader(new FileReader(file));
        String line;
        int limit;
        while ((line = buffer.readLine()) != null) {
            StringBuilder sb = new StringBuilder();
            line = line.trim();
            limit = Integer.valueOf(line);
            for (int i = 2; i <= limit; i++)
                if (isPrime(i) || i == 2)
                    sb.append(i + ",");
            sb.deleteCharAt(sb.length() - 1);
            System.out.println(sb);
        }
    }

    private static boolean isPrime(int n) {
        if (n % 2 == 0)
            return false;
        for (int i = 3; i*i <= n; i += 2)
            if (n % i == 0)
                return false;
        return true;
    }
}

Basically, I'm building up a string where I append all prime numbers less than N (which is passed by argument). Testing it, it works perfectly (or so it seems); submitting it, I get a "partially" status and score of 85. Don't know really what I'm messing up here...


texts: Inserting JSON array data into a MySQL database using PHP

texts:
Here I am parsing a JSON array and inserting it into a MySQL database. The JSON Array comes from my android code.

This is how my JSON array looks like:

["{custInfo=Ujwal  9975022560, rate=24000, weight=21.00000, desc=GENTS ANGTHI 22k NO STONE, makingAmt=200, vat=RS.3064.38, itemTotal=51073, sum_total=RS.156283.38, barcode=BQSP78BB, net_rate=24200, date=2015-11-30, invoiceNo=1, bill_type=Invoice}",
"{custInfo=Ujwal  9975022560, rate=24000, weight=21.00000, desc=GENTS ANGTHI 22k NO STONE, makingAmt=200, vat=RS.3064.38, itemTotal=51073, sum_total=RS.156283.38, barcode=BQSP78BB, net_rate=24200, date=2015-11-30, invoiceNo=1, bill_type=Invoice}",
"{custInfo=Ujwal  9975022560, rate=24000, weight=21.00000, desc=GENTS ANGTHI 22k NO STONE, makingAmt=200, vat=RS.3064.38, itemTotal=51073, sum_total=RS.156283.38, barcode=BQSP78BB, net_rate=24200, date=2015-11-30, invoiceNo=1, bill_type=Invoice}"]

This is my php code to parse and insert the data.

<?php
require "init.php";
$json = file_get_contents('php://input');
//$data = json_decode($json,true);
// remove the ,true so the data is not all converted to arrays
$data = json_decode($json);
// Now process the array of objects
foreach ( $data as $inv ) {
    $custInfo = $inv->custInfo;
    $rate =     $inv->rate;
    $weight=    $inv->weight;
    $desc=      $inv->desc;
    $makingAmt= $inv->makingAmt;
    $vat=       $inv->vat;
    $itemTotal= $inv->itemTotal;
    $sum_total= $inv->sum_total;
    $barcode=   $inv->barcode;
    $net_rate=  $inv->net_rate;
    $date=      $inv->date;
    $invoiceNo= $inv->invoiceNo;
    $bill_type= $inv->bill_type;
    $sql = "INSERT INTO selected_items
             (custInfo, invoiceNo, barcode, desc,
              weight, rate, makingAmt,net_rate,
              itemTotal,vat,sum_total,bill_type,date)
            VALUES
             ('$custInfo','$invoiceNo','$barcode','$desc',
              '$weight','$rate','$makingAmt','$net_rate',
              '$itemTotal','$vat','$sum_total','$bill_type','$date')";
    $res = mysqli_query($sql,$con);
echo $res;
    if(!$res){
        $result = new stdClass();
        $result->status = false;
        $result->msg = mysql_error();
        echo json_encode($result);
        exit;
    }
}
?>


texts: Read JSON as a dictionary of country codes and names

texts:
For a small system I need the Country Code mapped to the country name
(e.g. "GB"-> "United Kingdom"). To accomplish that I read a JSON file and save it to a dictionary using swiftyJSON. Is there a cleaner and better way than I did:

fileprivate func loadNames() {
    if let filePath = Bundle.main.path(forResource: "countryNames", ofType: "json") {
        if let jsonData = NSData(contentsOfFile: filePath) {
            let json = JSON(jsonData)
            countryNames = json.dictionaryObject! as NSDictionary
        }
    }
}

The JSON looks like this:

{
"BD": "Bangladesh",
"BE": "Belgium",
...
}


texts:
My goal is to save space occupied by 2D array (sea) that has 3 different values.

Ocean sea; //Ocean class has member 'private int[][] oceanMatrix;'

public final static int EMPTY = 1;
public final static int SHARK = 2;
public final static int FISH = 3;

by compressing it and place in two one dimensional array.

int[] runType = new int[10]; // each cell stores 1 or 2 or 3

int[] runLength = new int[10]; // corresponding index cell stores its number of occurence of that respective runType.

I am using Runlength encoding idea and wrote below code, which is yet to be fit into a Java class.

I need feedback/critiques on this logic of the below code and coding style, so that I can optimize and make it better. Constraint is to not use any existing Java library class except (array's length member).

private static int[] doubleTheSize(int[] arg){
        int[] temp = new int[2*arg.length];
        for(int c = 0; c < arg.length; c++){
            temp[c] = arg[c];
        }
        return temp;
    }

public static void main(String[] args) {
            Ocean sea;
            int[] runType = new int[10];
        int[] runLength = new int[10];
        int index = 0;
        boolean firstCell = true;
 //i&j are width & height of a 2d array read from commandline
        for(int row = 0; row < j ; row++){
            for(int col = 0; col < i ; col++){
                if(firstCell){
                    firstCell=false;
                    runType[index] = sea.cellContents(0, 0);
                    runLength[index]++;
                    continue;
                }
                switch(sea.cellContents(row, col)){
                case Ocean.EMPTY:
                    if(runType[index] == Ocean.EMPTY){
                        runLength[index]++;
                    }else{
                        index++;
                        if(index==runType.length){
                            runType = doubleTheSize(runType);
                            runLength = doubleTheSize(runLength);
                        }
                        runType[index]=Ocean.SHARK;
                        runLength[index]++;
                    }
                    break;
                case Ocean.SHARK:
                    if(runType[index] == Ocean.SHARK){
                        runLength[index]++;
                    }else{
                        index++;
                        if(index==runType.length){
                            runType = doubleTheSize(runType);
                            runLength = doubleTheSize(runLength);
                        }
                        runType[index]=Ocean.SHARK;
                        runLength[index]++;
                    }
                    break;
                case Ocean.FISH:
                    if(runType[index] == Ocean.FISH){
                        runLength[index]++;
                    }else{
                        index++;
                        if(index==runType.length){
                            runType = doubleTheSize(runType);
                            runLength = doubleTheSize(runLength);
                        }
                        runType[index]=Ocean.FISH;
                        runLength[index]++;
                    }
                    break;
                }// end switch
            }//end inner for loop
        }//end outer for loop
}//end main()

I wrote the above code for that.  Please help me review this code for optimization. One point that I recognized is, firstCell check that I did for every cell doesn't make sense. I need suggestion to better this logic because I need to enter in firstCell i{} block for only (0,0) cell.


texts: Dependency injection in constructor vs Supplying argument in utility functions

texts:
I have the following:

public class Person{
    public string FirstName {get; set;} = "";
    public string MiddleName {get; set;} = "";
    public string LastName {get; set;} = "";
    public string Title {get; set;} = "";
}

public class Program
{
    public static void Main()
    {
        var person = new Person {FirstName = "Daniel", MiddleName = "W", LastName = "Craig", Title = "Mr"};
    }
}

I am writing a service class that reports back a user's

Full name (First + Middle + Last names)
Title + Full name
First name and last name

Using dependency injection, I have the following:

(1)

public class NameService{

    private readonly Person _person;
    public NameService(Person person){
        _person = person;
    }

    public string GetFullName(){
        var fullName = $"{_person.FirstName} {_person.MiddleName} {_person.LastName}";

        return fullName;
    }

    public string GetFullNameWithTitle(){
        var fullNameWithTitle = $"{_person.Title} {_person.FirstName} {_person.MiddleName} {_person.LastName}";

        return fullNameWithTitle;
    }

    public string GetFirstLastName(){
        var fullName = $"{_person.FirstName} {_person.LastName}";

        return fullName;
    }
}

Which I can use like this:

var person = new Person {FirstName = "Daniel", MiddleName = "W", LastName = "Craig", Title = "Mr"};
var service = new NameService(person);

var fullName = service.GetFullName();

However, I can also define the service like this:

(2)

public class NameService
{
    public NameService(){}

    public string GetFullName(Person person)
    {
        var fullName = $"{person.FirstName} {person.MiddleName} {person.LastName}";
        return fullName;
    }

    public string GetFullNameWithTitle(Person person)
    {
        var fullNameWithTitle = $"{person.Title} {person.FirstName} {person.MiddleName} {person.LastName}";
        return fullNameWithTitle;
    }

    public string GetFirstLastName(Person person)
    {
        var fullName = $"{person.FirstName} {person.LastName}";
        return fullName;
    }
}

And then get a person's full name like so:

    var person = new Person {FirstName = "Daniel", MiddleName = "W", LastName = "Craig", Title = "Mr"};
    var service = new NameService();

    var fullName = service.GetFullName(person);

Which is the better approach? My thoughts:

(1)

Looks like the service is designed on a "per Person" basis. This means calling another person's full name will require instantiating a new service with a new Person argument (and that's okay).

(2)

This is a lightweight constructor that allows different Person object to be supplied into GetFullName(person) to allow different rendition of full name.

What other pros and cons can you think of?


texts: Proper separation of behaviour and data structure when the data structure is complex

texts:
The code in its full glory, complete with unit tests is here (and some discussion of the issue).

I am struggling with how the principle of separating data structures and behaviour applies here.

This would be the data structure, only with public fields:

package org.rulez.demokracia.pdengine;

import java.util.HashMap;
import java.util.Map;

import javax.persistence.ElementCollection;

public class BeatTableEntity {

    @ElementCollection
    public Map<Choice, HashMap<Choice, Integer>> table;

    public BeatTableEntity() {
        super();
    }

}

And this would be the behaviour, no data fields:

package org.rulez.demokracia.pdengine;

import java.util.HashMap;

import org.rulez.demokracia.pdengine.exception.IsNullException;

public class BeatTable extends BeatTableEntity {
    public enum Direction {
        DIRECTION_FORWARD, DIRECTION_BACKWARD
    }

    public BeatTable() {
        table = new HashMap<>();
    }

    public int beatInformation(Choice choice1, Choice choice2, Direction direction) throws IsNullException {
        if(direction == null)
            throw new IllegalArgumentException("Null direction");

        int result = 0;

        if(direction.equals(Direction.DIRECTION_FORWARD))
            result = getBeatValue(choice1, choice2);
        else
            result = getBeatValue(choice2, choice1);

        return result;
    }

    private HashMap<Choice, Integer> getBeatRow(Choice choice) {
        if (table.get(choice) == null)
            throw new IllegalArgumentException("Not existing row key");
        return table.get(choice);
    }

    private int getBeatValue(Choice choiceF, Choice choiceS) throws IsNullException {
        if (choiceF == null || choiceS == null)
            throw new IsNullException("Choice");
        HashMap<Choice, Integer> row = getBeatRow(choiceF);
        if (row.get(choiceS) == null)
            throw new IllegalArgumentException("Not existing column key");
        return row.get(choiceS);
    }

}

This is obviously badly encapsulated; an example is the test which changes a whole row to an empty one, and calls beatInformation() to throw an exception. That test fiddles around with the internals of the data representation (which should have no internals in the first place), and results in an error which is not exactly making sense in the business logic level.

My question is: what would be the right data structure to back this behaviour.

We came up with two possible solutions, none of them could really convince me:

have table as a simple map , where key is effectively the (Choice choice1, Choice choice2) tuple (e.g. choice1.id + choice2.id, as those are strings). This way the data structure have no internals to hide, but it is slow for a non-sparse matrix, and I do believe that good design is not slow.
come up with a Matrix class which we think of as a "primitive type". Matrix would itself use an internal data structure fully encapsulated, and implement its own serialization. The reasoning of this would be that this complexity of data cannot work without internals, and as the compiler can hide the internals of e.g. a HashMap, we just do the same, and thus we can use Matrix as a building block in properly separated code.

What are the points to consider here, and what would be the right solution?


texts:
In order to better understand functional programming in Javascript, I thought I'd try to recreate (as well as extend) some of the higher order functions on the Array object. These methods don't intend to be identical but to have the basic functionality. Any tips/suggestions/feedback would be greatly appreciated!

// Array.prototype.map()
Array.prototype.newMap = function(fn) {
    var returnedArray = [];

    for (var i = 0; i < this.length; i++) {
        returnedArray[i] = fn(this[i]);
    }
    return returnedArray;
};

// newMap for multi-dimensional arrays
Array.prototype.newMapMulti = function(fn) {
    var mainArray = [];

    for (var i = 0; i < this.length; i ++) {
        var result = this[i].newMap(fn);
        mainArray.push(result);
    }
    return mainArray;
};

// Array.prototype.filter()
Array.prototype.newFilter = function(fn) {
    var returnedArray = [];

    for (var i = 0; i < this.length; i++) {
        var c = this[i];

        if (fn(c)) {
            returnedArray.push(c);
        }
    }
    return returnedArray;
};
// newFilter for multi-dimensional arrays
Array.prototype.newFilterMulti = function(fn) {
    var mainArray = [];

    for (var i = 0; i < this.length; i++) {
        var result = this[i].newFilter(fn);
        if (result.length === 0) { continue }
        mainArray.push(result);
    }
    return mainArray;
};

// Array.prototype.find()
Array.prototype.newFind = function(fn) {

    for (var i = 0; i < this.length; i++) {
        var c = this[i];

        if (fn(c)) {
            return c;
        }
    }
};

// Array.prototype.reduce()
Array.prototype.newReduce = function(fn) {
    var total = 0;

    for (var i = 0; i < this.length; i++) {
        total += fn(this[i]);
    }
    return total;

};

// newReduce for multi-dimensional arrays
Array.prototype.newReduceMulti = function(fn) {
    var total = 0;

    for (var i = 0; i < this.length; i++) {
        total += this[i].newReduce(fn);
    }
    return total;
};

// returns a reduce value. if fn1 returns a value < x, then apply fn2 and return that value
Array.prototype.newReduceIf = function(fn1, fn2, x) {
    var reduceResult = this.newReduce(fn1);

    if (reduceResult < x) {
        var secondResult = this.newReduce(fn2);
        return secondResult;
    }
    return reduceResult;
};


texts: Does using a lambda make this code more DRY?

texts:
I started out with a function having code duplication like this:

    private static void GetAndSaveResources(string url)
    {
            ...

            if (url.Contains("[" + "access_id" + "]"))
            {
                RestCall.UriVariables.Add("access_id", 1);
            }

            if (url.Contains("[" + "affiliate_status" + "]"))
            {
                RestCall.UriVariables.Add("affiliate_status", "approved");
            }

            ...
    }

Then, because I had copy/pasted to make that code, I started trying to eliminate that duplication.

First I extracted a method:

    private static void ConfigureUriVariable(string url, string variable, object value)
    {
        if (url.Contains("[" + variable + "]"))
        {
            RestCall.UriVariables.Add(variable, value);
        }
    }

However, while that eliminated the duplication it also created a duplication of string url accross two functions so I futher reduced it to:

        Action<string,object> setUriVariable = (variable, value) =>
        {
            if (url.Contains("[" + variable + "]"))
            {
                RestCall.UriVariables.Add(variable, value);
            }
        };
        setUriVariable("access_id", 1);
        setUriVariable("affiliate_status", "approved");

However, I would have been confused by that code before I learned about lamdas so I wonder, was the last step a step in the wrong direction?


texts:
File manipulation code, I've noticed, has two salient properties:

  It's everywhere, and vitally important to functional software
  It has lots of exceptions.

Please give me some pointers on how I can better improve the usability of this rough draft I wrote yesterday. It assumes some very basic things, and was scrapped together after browsing Google as I stumbled through the concepts.

makeproject.py

'''create a simple setup folder for a new project

Follows the guide posted at:
http://guide.python-distribute.org/quickstart.html#lay-out-your-project

The structure built will match the following:

| ProjectName/
|---> LICENSE.txt
    | README.txt
    | setup.py
    | projectname/
    | ---> __init__.py

#For the sake of best practices, __init__.py is left empty.
'''
#! usr/bin/env python

import sys, os, errno

class NewProject(object):
    '''interface for building a directory with a new project in it'''

    def __init__(self, projectname, directory):
        self.project = projectname
        self.base = check_path(directory)
        #project defaults: I don't want them here as class attributes!
        self.SETUP = {

'README.txt' :
'''This is an unmodified README text file.
It contains a list of changes to the program.
It also contains help for dealing with the application.
''',

'LISCENSE.txt' :
'''Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License
'''
}

    def newproject(self):
        '''creates a file structure for a new project at `directory`
        '''
        self.name = self.project.replace(' ', '')
        self.path = os.sep.join([self.base, self.name])

        sub = self.name.lower()
        subpath = os.sep.join([self.path, sub])

        check_build_path(subpath)
        for filename, content in self.SETUP.items():
            self.buildfile(filename, content, directory=self.path)
        #setup takes arguments, it has its own method
        setup = self.buildsetup()
        self.buildfile('setup.py', setup)
        self.buildfile('__init__.py', directory=subpath)

    def buildfile(self, name, content="", directory = ""):
        '''opens and creates a new file at `directory` with `contents`'''
        #assumes bad directories have been purified
        if directory == "":
            loc = os.sep.join([self.path, name])
            w = open(loc, 'w')
        else:
            directory = os.sep.join([directory, name])
            w = open(directory, 'w')
        w.write(content)
        w.close()

    def buildsetup(self):
        return '''from distutils.core import setup

setup(
    name='{0}',
    version='0.1dev',
    packages=['{1}',],
    license=open('LISCENSE.txt').read(),
    long_description=open('README.txt').read(),
)
'''.format(self.project, self.name.lower())

def check_path(loc):
    '''recursively check if last character in `loc` is like os.sep character.
    If so, remove.'''
    if loc[-1] == os.sep:
        return check_path(loc[:-1])
    return loc

def check_build_path(loc):
    d = os.path.normpath(loc)
    if not os.path.exists(d):
        os.makedirs(d)
    else:
        try:
            os.rmdir(d)
        except OSError as ex:
            if ex.errno == errno.ENOTEMPTY:
                print "Directory specified must be new or empty"
                sys.exit(1)
        #if delete was successful, build the directory
        check_build_path(loc)

if __name__ == '__main__':
    if len(sys.argv) != 3:
        print "Usage: string 'Project Name', string '/abs/path'"
        sys.exit(1)
    project = NewProject(sys.argv[1], sys.argv[2])
    project.newproject()


texts: Polymorphic STL foreach without passing the container type

texts:
I was trying to figure out how to make a breakable foreach macro for STL containers and I came up with this method that uses templates to recognize the container type automatically. Are there any performance / code-wise improvements you can think of?

// polymorphic break-able foreach test that works with nested calls on the same type of container

#include <vector>
#include <list>
#include <iostream>
#include <unordered_map>

std::unordered_map<void *, bool> _advance_iterator__instances_done;

template <class Tc, class Ti>
bool advance_iterator(Tc &container, Ti &iterator)
{
   static typename Tc::iterator it;

   if (_advance_iterator__instances_done[&container])
   {
      it = container.begin();
      _advance_iterator__instances_done[&container] = false;
   }

   if (it == container.end())
   {
      _advance_iterator__instances_done[&container] = true;
      return false;
   }

   iterator = *it;
   it++;

   return true;
}

#define foreach(value_type, iterator, container) \
_advance_iterator__instances_done[&container] = true; \
for (value_type iterator; advance_iterator(container, iterator); )

int main(int argc, char *argv[])
{
   std::vector<int> vec;
   std::list<int> lis;
   std::list<std::list<int>> matrix;

   // populate containers
   for (int i = 0; i < 10; i++)
   {
      static std::list<int> row;

      vec.push_back(i);
      lis.push_back(i + 10);

      for (int j = 1; j <= 10; j++)
         row.push_back(j * i);

      matrix.push_back(row);
      row.clear();
   }

   // regular foreach test
   std::cout << "vec:" << std::endl;

   foreach(int, value, vec)
      std::cout << value << std::endl;

   std::cout << std::endl << "half of lis:" << std::endl;

   // breaking test
   foreach(int, value, lis)
   {
      std::cout << value << std::endl;

      if (value == 14)
         break;
   }

   // regular again
   std::cout << std::endl << "full lis:" << std::endl;

   foreach(int, value, lis)
      std::cout << value << std::endl;

   // nested test
   std::cout << std::endl << "matrix:" << std::endl;

   foreach(std::list<int>, row, matrix)
   {
      foreach(int, value, row)
         std::cout << value << " ";

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

   return 0;
}


texts:
Problem:

  Monk goes to graph city to learn about graphs, and meets an
  undirected graph having  \$ N \$ nodes, where each node has a value \$ i \$ such that  \$ 1 \le i \le N \$. Each node of the graph is very
  curious and wants to know something about the nodes which are directly
  connected to it.

  For each node, if we sort the nodes directly connected to it, according to their values in descending order, what is the value of the node at the \$ k \$ th position? The graph is 1-based.

  Note: If two nodes have the same value, they are sorted according to their indices in ascending order.

My accepted solution:

import sys
from collections import defaultdict

node_value_dict = defaultdict(int)
connected_graph_component = defaultdict(list)

def connect_graph():
    n, m, k = list(map(int, sys.stdin.readline().split()))
    node_values = list(map(int, sys.stdin.readline().split()))
    for i in range(1, len(node_values) + 1):
        node_value_dict[i] = node_values[i - 1]

    for m_i in range(m):
        n1, n2 = list(map(int, input().split()))
        connected_graph_component[n1].append(n2)
        connected_graph_component[n2].append(n1)

    for i in range(1, n + 1):
        if i in connected_graph_component:
            curr_co = connected_graph_component[i]
            sort_list = sorted(curr_co, key=lambda value: node_value_dict[
                               value], reverse=True)
            for i in range(len(sort_list) - 1):
                if node_value_dict[sort_list[i]] == node_value_dict[sort_list[i + 1]] and sort_list[i] < sort_list[i + 1]:
                    sort_list[i], sort_list[
                        i + 1] = sort_list[i + 1], sort_list[i]

            print(sort_list[k - 1])
        else:
            print(-1)

connect_graph()

With a runtime of 9.14092 sec.

How can I improve the code quality and further optimize runtime duration?

In case of equal values, I need to sort the nodes according to their indices in ascending order. Currently I'm doing it by looping over the sorted list and then comparing values again side by side maintaining two pointers.

Can you please suggest some elegant way of doing this.

Question Link


texts:
I have created this prime number generator. I want it to be as fast as possible, but I am wondering if there is a faster way (there must be).

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

bool is_prime(const unsigned long long);

int
main(
    void)
{
    puts("2\n3");

    for (unsigned long long n = 5; n < ULLONG_MAX; n+=2) {
        if (is_prime(n)) {
            printf("%llu\n", n);
        }
    }
}

bool
is_prime(
    const unsigned long long n)
{
    if (n < 4) {
        return n > 1;
    } else if (n % 2 == 0 || n % 3 == 0) {
        return false;
    } else {
        for (unsigned long i = 5; i * i <= n; i += 6) {
            if (n % i == 0 || n % (i + 2) == 0) {
                return false;
            }
        }

        return true;
    }
}

Possible slow areas:

usage of printf
usage of bool instead of int (not sure)

Compilation command:

clang -O3 -Weverything -pipe -march=native -o png png.c


texts: Generic Linked List Implementation in Java

texts:
I am looking for feedback on my doubly linked list implementation that I have written in Java. I am looking for specific feedback on the efficiency of my code, as well as my usage of generics. I am pretty new to using generics in Java, and I'm not quite sure that I am using them correctly yet.

My node class is pretty basic, but I'd like to revisit my Equals and Hashcode. Am I implementing these correctly? See snippet below:

My node class's equals/hashcode:

@Override
public boolean equals(Object that){
    if(this == that)
        return true;
    if(!(that instanceof LLNode))
        return false;

    return this.data.equals(((LLNode)that).getData());
}

@Override
public int hashCode(){
    return (this.data == null ? 0 : this.data.hashCode());
}

The DoublyLinkedList class, where the linked list is actually implemented can be found here, as there is too much to post here I think. Am I missing any major functionality? Are generics used properly?

If possible I'd also like to have my test cases reviewed to see if they are strong enough, and at least somewhat well designed. Those are here.

I was unsure of how to test certain things - specifically cases where I am expecting exceptions to be thrown.


texts:
I am building a tool that interacts with a batched stream of incoming data. This data needs to be processed and the result returned. To split up the work I have created a class that has inbound (_in) and outbound (out) queues and workers that are getting, processing, and depositing the work.
This example takes an iterable of numbers (in pass_data) and multiplies them by f.
import queue, random, time
from multiprocessing import Process, Queue

def _worker(_in, out, f):
    """Get work from _in and output processed data to out"""
    while True:
        try:
            work = _in.get()
        except queue.Empty:
            continue
        # simulate blocking for some time
        time.sleep(random.uniform(0.01, 0.5))
        out.put(work * f)

class C:
    def __init__(self, f, threads=2):
        self.f = f
        self.threads = threads
        self._in, self.out = Queue(), Queue()
        self.args = (self._in, self.out, self.f)
        self.workers = [
            Process(target=_worker, args=self.args) for _ in range(self.threads)
        ]

    def __repr__(self):
        return f"{self.__class__.__name__}(threads={self.threads})"

    def start(self):
        """Start all workers"""
        for worker in self.workers:
            worker.start()

    def terminate(self):
        """Terminate all workers"""
        for worker in self.workers:
            worker.terminate()

    def pass_data(self, data):
        """Pass data to the queue to be processed"""
        for rec in data:
            self._in.put(rec)

    def get_completed(self):
        """Return a list of processed data"""
        items = []
        while True:
            try:
                items.append(self.out.get_nowait())
            except queue.Empty:
                break
        return items

if __name__ == "__main__":
    c = C(f=12, threads=2)
    c.start()

    for i in range(5):
        s = 0
        n = random.randint(1, 20)
        c.pass_data(list(range(n)))
        print(f"sent: {n}")
        while s < n:
            r = c.get_completed()
            s += len(r)
            if r:
                print(len(r), end=", ")
            time.sleep(random.uniform(0.01, 0.4))
        print()
    c.terminate()

This is, at the moment, a proof of concept. Are there any pitfalls to this method? Is there a better way to do this already?!
Aspects that I intend to address:

queue size limits
thread number limits


texts:
(See the next iteration.)

From time to time, while working with a command line in *nix family of operating systems, we have to write those scripts doing a rather specific task. Usually we use bash + utility programs to do the job. However, I had to ask myself: how to implement such a script in C? After an invocation of such a script, it should perform the following:

Create a temporary source file \$S\$,
Dump the C code to \$S\$,
Compile \$S\$ to the program \$P\$,
Run \$P\$ passing the arguments to it and caching its exit status,
Remove \$S\$ and \$P\$,
Return the cached exit status of \$P\$.

Code

#! /bin/bash

# Below, XXXX asks for random characters in order to make a unique file name.
# Mac OSX seems to ignore XXXX, yet Ubuntu requires them.

# Create a temporary file name for the source code:
TMP_SOURCE_FILE="$(mktemp -t sourceXXXX).c"
# Create a temporary file name for the executable file:
TMP_PROGRAM_FILE="$(mktemp -t programXXXX)"

# Write the source code into the temporary source file:
cat > $TMP_SOURCE_FILE <<- END_OF_SOURCE
#include <stdio.h>

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

    puts("Hello, world! I am a pseudoportable C program.");
    for (i = 1; i < argc; ++i)
    {
        printf("Argument %d: %s\n", i, argv[i]);
    }

    return argc - 1;
}
END_OF_SOURCE

# Compile and run:
gcc $TMP_SOURCE_FILE -o $TMP_PROGRAM_FILE
$TMP_PROGRAM_FILE $@
EXIT_STATUS=$?

# Clean the source and the binary:
rm $TMP_SOURCE_FILE
rm $TMP_PROGRAM_FILE

# Delegate the exit status of the C program to calling bash:
exit $EXIT_STATUS

So, what do you think? How can I improve anything? Also, can you come with an example of the situation where this "C script" pattern is more preferable than bash + command line utilities, Python, etc.?


texts:
I'm learning C++ and also about data structures, so I am trying to implement some. This is my linked list. I've included two different ways of getting the length of the list, with a length variable and also a function (getLength2) that goes through the list until it finds a NULL pointer. I suspect that there could be memory leaks in it, though I'm not sure.

    #include "stdafx.h"
    #include <iostream>
    using namespace std;

    template <class val>
    class linked_list{
        struct node{
            val value;
            node *next;
        };
        node *start;
        unsigned int length;
    public:
        linked_list() { length = 0; start = NULL; }
        unsigned int getLength() { return length; }
        val getFirst() { return (*start).value; }
        unsigned int getLength2();
        void add(val value);
        val getVal(unsigned int pos);
        val pop();
    };

    int _tmain(int argc, _TCHAR* argv[])
    {
        linked_list<int> gary;
        for (int i = 0; i < 10; ++i){
            gary.add(pow(2, i));
        }
        for (int k = 0; gary.getLength() > 0; ++k){
            cout << gary.pop() << ' ' << gary.getLength() << endl;
        }
        return 0;
    }

    template <class val>
    void linked_list<val>::add(val value){
        node *second = start;
        start = new node;
        (*start).value = value;
        (*start).next = second;
        length += 1;
    }

    template <class val>
    val linked_list<val>::getVal(unsigned int pos){
        node current = *start;
        for (unsigned int depth = 0; depth < pos; ++depth){
            current = *(current.next);
        }
        return current.value;
    }

    template <class val>
    val linked_list<val>::pop(){
        val ret = start->value;
        node *new_address = start->next;
        delete start;
        start = new_address;
        length -= 1;
        return ret;
    }

    template <class val>
    unsigned int linked_list<val>::getLength2() {
        if (start == NULL){
            return 0;
        }
        node current = *start;
        unsigned int len = 1;
        while (current.next != NULL){
            current = *(current.next);
            len += 1;
        }
        // should this have a 'delete current'?
        return len;
    }


texts: Min function accepting varying number of arguments in C++17

texts:
Come across this problem once again in the book The Modern C++ Challenge.

18. Minimum function with any number of arguments
Write a function template that can take any number of arguments and returns the minimum value of them all, using operator < for comparison. Write a variant of this function template that can be parameterized with a binary comparison function to use instead of operator <.

I wonder how simple and elegant the implementation could be using c++17. The following is the parameterized version. Ideas?
#include <algorithm>

template <typename Less, typename T, typename... Ts>
constexpr const T& min(Less less, const T& a, const T& b, const Ts&... rems) {
  if constexpr (sizeof...(rems)) {
    return min(less, std::min(a, b, less), rems...);
  }
  else {
    return std::min(a, b, less);
  }
}


texts: Sum up all odd numbers between 1 and 2n + 1

texts:
Assignment:

  Write a program which reads a number n from the console. Then
  calculates the sum of all odd numbers between 1 and 2n + 1 (incl.).

Assignment also on GitHub, Exercise 0.0.

The functions read_hex and print_eax as well as the header and tail of the script are provided by the tutor.

format PE console
entry start

include 'win32a.inc'

; ===============================================
section '.text' code readable executable

start:
    call    read_hex

    mov     esi, 1 ; esi becomes the counting variable.

    mov     ebx, 2
    mul     ebx
    add     eax, 2
    mov     edi, eax ; edi becomes the limit.

    mov     eax, esi
    mov     ebx, 2 ; Will be the divisor.
    mov     ecx, 0 ; ecx will store the sum.
operationSet:
    mov edx, 0 ; Make sure that the register is empty.
    div ebx

    cmp edx, 0
    JE manageOperationSet ; If 0 then skip next operation.
    add ecx, esi
manageOperationSet:
    inc esi
    mov eax, esi
    cmp esi, edi
    jne operationSet

    mov eax, ecx
    call print_eax

    push    0
    call    [ExitProcess]
include 'training.inc'

I've tested my program with the numbers from 1 to 6 and get correct results. I think it works correctly, but I'm not sure concerning my register usage.

Moreover: What could be improved? Are there weak points in my code?


texts: Calculating (\$a^2\$ + \$b(2c-d)^2)/(3e)\$ in assembly

texts:
I made a simple assembly program to evaluate the function

$$f =\frac{a^2 + b(2c-d)^2}{3e}$$

Since this is basically my first ever, I would like to hear what I can improve and know how to use registers better.

.model small
.stack 100h
.data
a dw 4
b dw 15
c dw 86
d dw 155
e dw 8
res dw 0;
.code
mov ax,@data
mov ds,ax
mov dx,0
mov bx,0
mov cx,0
mov ax,c
shl ax,1
mov bx,d
sub ax,bx
mul ax
mul b
mov dx,ax
push dx
mov dx,0
mov ax,a
mul ax
pop cx
add ax,cx
mov dx,ax
push dx
mov dx,0
mov ax,e
mov bx,3
mul bx
mov bx,ax
pop cx
mov ax,cx
mov cx,bx
div cx
mov ax,4c00h
int 21h
end


texts: UIGraphicsImageContext Memory Spike - Reducing Footprint

texts:
I have a UIImage Category for iOS Objective-C which tints an image based on a given UIColor value. You can take a look at the method below:

- (UIImage *)tintImageWithTint:(UIColor *)color withIntensity:(float)alpha {
    CGSize size = self.size;

    UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale); // MEMORY SPIKE
    CGContextRef context = UIGraphicsGetCurrentContext();

    [self drawAtPoint:CGPointZero blendMode:kCGBlendModeNormal alpha:1.0]; // MEMORY SPIKE

    CGContextSetFillColorWithColor(context, color.CGColor);
    CGContextSetBlendMode(context, kCGBlendModeOverlay);
    CGContextSetAlpha(context, alpha);

    CGContextFillRect(UIGraphicsGetCurrentContext(), CGRectMake(CGPointZero.x, CGPointZero.y, self.size.width, self.size.height));

    // Get the resized image from the context and a UIImage
    CGImageRef newImageRef = CGBitmapContextCreateImage(context); // MEMORY SPIKE
    UIImage *tintedImage = [UIImage imageWithCGImage:newImageRef];

    CGImageRelease(newImageRef);
    UIGraphicsEndImageContext();

    return tintedImage;
}

I've been testing this method with Xcode's Instruments app and found that it takes up more than 96.0 % of all bytes used during the life cycle of the app. That's crazy! It allocates more than 5 MB very quickly, which causes a level one memory warning and begins to terminate other running processes.

The image that I'm tinting is only a 111 KB, so I can't see how this code could possibly allocate more than 5 MB so quickly.

How can I improve the performance of this code and reduce its memory impact? I'm not very familiar with CoreGraphics, so any help would be appreciated.


texts: Fastest Windows script to move files from one did to a network dir

texts:
I wrote a script that moves files older than two days over to a network share (via scheduled task). Windows Task Scheduler doesn't seem to like the script so much, but it works well by itself.

Is there a faster way than what I have?
Is there a way to programmatically make it a scheduled task or service of some type?

Backup.ps1

$today = get-date
$tda= $today.addDays(-2) #two days ago

$files = get-childitem d:\source_path | select fullname, lastwritetime | where-object{$_.lastwritetime -lt $tda}

foreach ($file in $files) {
  Echo "moving " $file.fullname #just so I know it's still running, get rid of this?
  mv $file.fullname 'n:\dest_folder'
  Echo 'done'
}


texts: Care to review my immutable singly linked list?

texts:
public sealed class SinglyLinkedList<T> : IEnumerable<T>
{
    readonly static SinglyLinkedList<T> _empty = new SinglyLinkedList<T>();
    readonly bool _isEmpty;
    readonly T _head;
    readonly SinglyLinkedList<T> _tail;

    private SinglyLinkedList()
    {
        _isEmpty = true;
    }

    private SinglyLinkedList(T head)
    {
        _isEmpty = false;
        _head = head;
    }

    private SinglyLinkedList(T head, SinglyLinkedList<T> tail)
    {
        _isEmpty = false;
        _head = head;
        _tail = tail;
    }

    public static SinglyLinkedList<T> Empty
    {
        get { return _empty; }
    }

    public int Count
    {
        get
        {
            var list = this;
            var count = 0;
            while (!list._isEmpty)
            {
                count++;
                list = list._tail;
            }
            return count;
        }
    }

    public bool IsEmpty
    {
        get { return _isEmpty; }
    }

    public T Head
    {
        get
        {
            if (_isEmpty)
                throw new InvalidOperationException("The list is empty.");
            return _head;
        }
    }

    public SinglyLinkedList<T> Tail
    {
        get
        {
            if (_tail == null)
                throw new InvalidOperationException("This list has no tail.");
            return _tail;
        }
    }

    public static SinglyLinkedList<T> FromEnumerable(IEnumerable<T> e)
    {
        if (e == null)
            throw new ArgumentNullException("e");
        return FromArrayInternal(e.ToArray());
    }

    public static SinglyLinkedList<T> FromArray(params T[] a)
    {
        if (a == null)
            throw new ArgumentNullException("a");
        return FromArrayInternal(a);
    }

    public SinglyLinkedList<T> Append(T value)
    {
        var array = new T[Count + 1];
        var list = this;
        var index = 0;
        while (!list._isEmpty)
        {
            array[index++] = list._head;
            list = list._tail;
        }
        array[index] = value;
        return FromArrayInternal(array);
    }

    public SinglyLinkedList<T> Prepend(T value)
    {
        return new SinglyLinkedList<T>(value, this);
    }

    public SinglyLinkedList<T> Insert(int index, T value)
    {
        if (index < 0)
            throw new ArgumentOutOfRangeException("index", "Cannot be less than zero.");
        var count = Count;
        if (index >= count)
            throw new ArgumentOutOfRangeException("index", "Cannot be greater than count.");
        var array = new T[Count + 1];
        var list = this;
        var arrayIndex = 0;
        while (!list._isEmpty)
        {
            if (arrayIndex == index)
            {
                array[arrayIndex++] = value;
            }
            array[arrayIndex++] = list._head;
            list = list._tail;
        }
        return FromArrayInternal(array);
    }

    public IEnumerator<T> GetEnumerator()
    {
        var list = this;
        while (!list._isEmpty)
        {
            yield return list._head;
            list = list._tail;
        }
    }

    public override string ToString()
    {
        if (_isEmpty)
            return "[]";
        return string.Format("[{0}...]", _head);
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }

    static SinglyLinkedList<T> FromArrayInternal(T[] a)
    {
        var result = Empty;
        for (var i = a.Length - 1; i >= 0; i--)
        {
            result = result.Prepend(a[i]);
        }
        return result;
    }
}


texts: Mark positions attacked by a queen on a chess board

texts:
Problem - Given a chess board and the position of only one queen piece in it, mark all the position where the queen can move with X.

Kindly review this Scala code and suggest improvements.

import scala.collection.mutable._

object ChessQueenAttack {
  val board = Array.fill(8)(Array.fill(8)('0'))
  def printBoard = {
    println
    println
    board foreach { row => println(row.mkString(" "))}
  }

  def main(args: Array[String]): Unit = {
    printBoard
    val qR = args(0).toInt
    val qC = args(1).toInt
    board(qR)(qC) = 'Q'
    printBoard

    var (r,c) = (qR, qC)

    // horizontal
    for ( i <- 0 until 8 ) {
      if (i != qC) board(qR)(i) = 'X'
      if (i != qR) board(i)(qC) = 'X'
    }

    // top left
    r = qR -1
    c = qC -1
    while (r >= 0 && c >= 0) {
      board(r)(c) ='X'
      r -= 1
      c -= 1
    }
    // top right
    r = qR - 1
    c = qC + 1
    while (r >= 0 && c  < 8) {
      board(r)(c) = 'X'
      r -= 1
      c += 1
    }
    // bottom right
    r = qR + 1
    c = qC + 1
    while (r < 8 && c < 8 ) {
      board(r)(c) = 'X'
      r += 1
      c += 1
    }
    // bottom left
    r = qR + 1
    c = qC - 1
    while (r<8 && c>=0) {
      board(r)(c) = 'X'
      r += 1
      c -= 1
    }
    printBoard
  }
}

Output -

scalac ChessQueenAttack.scala
scala ChessQueenAttack 3 3

0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0

0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 Q 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0

X 0 0 X 0 0 X 0
0 X 0 X 0 X 0 0
0 0 X X X 0 0 0
X X X Q X X X X
0 0 X X X 0 0 0
0 X 0 X 0 X 0 0
X 0 0 X 0 0 X 0
0 0 0 X 0 0 0 X


texts:
While doing a little project involving sniffing packets, I found myself programming a cross platform network to host byte order and host to network byte order, this is my first time developing a project using networking.

ntboc.h

#ifndef NTBOC_H_INCLUDED
#define NTBOC_H_INCLUDED

#define LITTLE_EDIAN    1
#define BIG_EDIAN       2

// convert from host to network byte order
void ntboc_tont(void *data, size_t len);
//convert from network to host byte order
#define ntboc_toht(data, len)   (ntboc_tont(data,len))
#endif

ntboc.c

#include <stdlib.h>
#include "ntboc.h"

static unsigned int ntbo = 0;

static void ntboc_init()
{
    int t = 1;
    if(*((char *)&t))
        ntbo = LITTLE_EDIAN;
    else
        ntbo = BIG_EDIAN;
}

static void ntboc_swap(void *data, size_t len)
{
    size_t off = len-1;

    unsigned char *ddata = data;
    unsigned char *sdata = data + off;
    unsigned char tmp;

    while((void *)sdata > (data + (off)/2)) {
        tmp = *ddata;
        *ddata = *sdata;
        *sdata = tmp;

        sdata--, ddata++;
    }

}

void ntboc_tont(void *data, size_t len)
{
    if(ntbo == 0)
        ntboc_init();

    if(ntbo == BIG_EDIAN)
        return;

    ntboc_swap(data, len);
}

main()
{
    short len = 0x3e;
    ntboc_toht(&len, 2);
    printf("len : %x", len);
}


texts: Lazy Load for multiple entities at a time

texts:
We have a system with a non standard database solution. All trips to the DB are rather expensive. We cannot use entity framework.

Currently our lazy loading is on an entity by entity basis. So if I have a Customer and access their Orders object it only loads the Orders for that customer.

Something like so

//DAL
public List<Entities.Customer> GetCustomersByIds(IEnumerable<int> ids)
{
    var customers = db.GetCustomersByIds(ids);
    foreach(var customer in customers)
    {
        customer.Orders = new ResetLazy<List<Entities.Order>>(() =>
            db.GetOrdersByCustomerId(c.Id));
    }
    return customers;
}

ResetLazy taken from here https://stackoverflow.com/a/6255398/102526

Ideally if we had a collection of Customers and accessed an Orders collection on one of the customers it would load all the Orders for all the Customers. (If not in a collection it would just load it's own orders)

//DAL
public List<Entities.Customer> GetCustomersByIds(IEnumerable<int> ids)
{
    var customers = db.GetCustomersByIds(ids);
    foreach(var customer in customers)
    {
        customer.Orders = new ResetLazy<List<Entities.Order>>(() =>
            GetOrdersByCustomersLazy(customers, customer.Id));
    }
    return customers;
}

protected List<Entities.Order> GetOrdersByCustomersLazy(
    List<Entities.Customer> customers,
    int customerId)
{
    var orders = db.GetOrdersByCustomerIds(
        customers.Select(customer => customer.Id).AsEnumerable());
    foreach(var customer in customers)
    {
        customer.Orders = new ResetLazy<List<Entities.Order>>(() => {
            customer.Orders = new ResetLazy<List<Entities.Order>>(() =>
                GetOrdersByCustomersLazy(customers, customer.Id));
            return orders.Where(order => order.CustomerId == customer.Id).ToList();
        });
    }
    return customers.FirstOrDefault(customer => customer.Id == customerId).Orders.Value;
}

This seems to work well, but it is too complex and not generic.


texts: Take a list of ascii strings from a file and hash them using python threading

texts:
How can I do this in a more performant way? I'm concerned that throwing the data in a queue like this is defeating the purpose of yield from the open() and also how about handling the shared reference to file handle?

import hashlib
import sys
from threading import Thread
import queue

class HashWorker(Thread):

    def __init__(self, queue, fp_out):
        Thread.__init__(self)
        self.queue = queue
        self.fp_out = fp_out

    def run(self):
        while True:
            password = self.queue.get()
            try:
                hash_threaded(password, self.fp_out)
            finally:
                self.queue.task_done()

def main(argv):

    if sanitize(argv) is False:
        return -1

    # fp = open(argv[1], "r")
    fp_out = open("sha256hashes.txt", "a+")

    myqueue = queue.Queue()

    for x in range(8):
        worker = HashWorker(myqueue, fp_out)
        worker.daemon = True
        worker.start()

    for l in open(argv[1], "r"):
        myqueue.put(l)

    myqueue.join()
    print("Done.")
    fp_out.close()

def sanitize(argv):
    if len(argv) != 2:
        print("USAGE: {} filename.txt".format(argv[0]))
        return False
    return True

def hash_threaded(password, fp_out):
    line_bytes = bytes(password, "ascii")
    output_line = hashlib.sha256(line_bytes).hexdigest()
    fp_out.write("{}\n".format(output_line))
    #  print(".", end='')

if __name__ == '__main__':
    main(sys.argv)


texts: Split a file into multiple files if it reaches a particular limit?

texts:
For each clientId, I have a Collection<Task> object. I am making file for each clientId and for each clientId file, I have all their tasks in it separated by new line in it.

Below is my original code:-

public class FileProcessor {
  private final String clientId;
  private final Collection<Task> tasks;

  public FileProcessor(String clientId, Collection<Task> tasks) {
    this.clientId = clientId;
    this.tasks = tasks;
  }

  public void generateFile() {
    String fileName = "tasks_info_" + clientId + ".txt";
    StringBuilder sb = new StringBuilder();
    for (Task task : tasks) {
      sb.append(task).append(System.getProperty("line.separator"));
    }
    try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileName))) {
      writer.write(sb.toString());
    } catch (IOException ex) {
      ex.printStackTrace();
    }
  }
}

Let' say if clientId is 123, then it will create a file called "tasks_info_123.txt" with all the tasks in it. Now I have a requirement that file size of each clientId file cannot go more than 50000 bytes. So now what I have to do is:

I have to split each clientId file into multiple files like this: "tasks_info_123_0.txt", "tasks_info_123_1.txt", "tasks_info_123_2.txt"
As you can see, I have added "_0", "_1", "_2" in it.
So I will keep creating multiple files for each clientId until I can fit all the data in it and also making sure each file size is not more than 50000 bytes.
If we can fit all the data in one file, then I will have only one clientId file like this: "tasks_info_123_0.txt"
Also we should not create a file if collection of task object is empty.

So I got below code but it is not efficient as well seems like so opting for code review to see if there is any better and efficient way?

  public void generateFile() {
    int size = 0;
    int index = 0;
    StringBuilder sb = new StringBuilder();
    for (Task task : tasks) {
      sb.append(task).append(System.getProperty("line.separator"));
      size += sb.toString().getBytes(StandardCharsets.UTF_8).length;
      if (size > 50000) {
        String fileName = "tasks_info_" + clientId + "_" + index + ".txt";
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileName))) {
          writer.write(sb.toString());
        } catch (IOException ex) {
          ex.printStackTrace();
        }
        index++;
        sb = new StringBuilder();
        size = 0;
      }
    }
    // for cases where we don't reach the limit
    String fileName = "tasks_info_" + clientId + "_" + index + ".txt";
    try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileName))) {
      writer.write(sb.toString());
    } catch (IOException ex) {
      ex.printStackTrace();
    }
  }

Note: I don't want to use logger for this, just that I want to try it out on my own.


texts:
Below I have some code written in prolog as a brief example. The goal of the program is to take a Computer and Information Science (CISC) course number and return any CISC prerequisites (prereqs).

I would like to know if this code followed common practices in prolog.

%CISC Courses
cisc(100).
cisc(101).
cisc(103).
cisc(106).
cisc(120).
cisc(160).
cisc(201).
cisc(211).
cisc(225).
cisc(233).
cisc(298).
cisc(300).
cisc(301).
cisc(311).
cisc(320).
cisc(330).
cisc(333).
cisc(340).
cisc(349).
cisc(365).
cisc(370).
cisc(380).
cisc(390).
cisc(397).
cisc(399).
cisc(400).
cisc(431).
cisc(432).
cisc(433).
cisc(440).
cisc(444).
cisc(460).
cisc(491).
cisc(498).
cisc(499).

Define Prereqs
prereqs(160,120).
prereqs(211,120).
prereqs(225,120).
prereqs(300,120).
prereqs(233,160).

prereqs(301,211).
prereqs(301,233).
prereqs(311,160).
prereqs(311,225).
prereqs(320,211).

prereqs(320,233).
prereqs(330,211).
prereqs(333,233).
prereqs(340,233).
prereqs(349,233).

prereqs(370,333).
prereqs(390,120).
prereqs(397,225).
prereqs(397,301).
prereqs(399,233).

prereqs(400,233).
prereqs(400,301).
prereqs(431,233).
prereqs(431,399).
prereqs(432,233).

prereqs(433,301).
prereqs(433,399).
prereqs(440,370).
prereqs(444,433).
prereqs(460,225).

prereqs(460,233).
prereqs(491,225).
prereqs(491,301).
prereqs(498,298).

%Return prereqs to a given class with prereqs of prereqs
prereq(X,Y) :- prereqs(X,Y),format("CISC ~w is a prereq of CISC ~w~n",[Y,X]).

prereq(X,Y) :- prereqs(X,Z),
    prereq(Z, Y).


texts:
I have this short function, it converts a human selected name like "Accelerometer" to "Acc" which a sensor can use:
private final String[] sensorNames = {"Acc", "Gyro", "Magn", "IMU9", "Temp"};

/**
 * Converts human representation of sensor names to movesense names. TODO: better code
 * @param sensorType Human representation of sensor name.
 * @return Short name of the sensor.
 */
private String findShortSensorName(String sensorType) {
    for (int i = 0; i < sensorNames.length; i++) {
        if (sensorType.substring(0,1).equals(sensorNames[i].substring(0,1))) {
            return sensorNames[i];
        }
    }
    return "";
}

Is there a way to make this more efficient or use less code? The return ""; is also bugging me. Thanks for your input!


texts: Project Euler #35 - Circular primes solution is slow

texts:
This is my code for project euler #35 (in Python):

The number, 197, is called a circular prime because all rotations of the digits: 197, 971, and 719, are themselves prime.
There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97.
How many circular primes are there below one million?

The program takes about 2 minutes to run, and I don't really know how to improve the efficiency of it. I'm using a sieve to generate the primes, and I'm only checking rotations until the rotation isn't prime.
def primes_sieve(limit):
    limitn = limit+1
    not_prime = [False] * limitn
    primes = []

    for i in range(2, limitn):
        if not_prime[i]:
            continue
        for f in range(i*2, limitn, i):
            not_prime[f] = True

        primes.append(i)

    return primes

primes = set(primes_sieve(1000000));
exclude = ['2','4','5','6','8','0']
def circularPrime(n):
    ss = str(n);
    for i in range(n):
        if ss[-1] in exclude:
            return 0;
        if int(ss) not in primes:
            return 0;
        ss = ss[-1] + ss[:-1];
    return 1;

gg = 0;
for num in primes:
    gg += circularPrime(num);
print gg;

Any help is greatly appreciated.


texts:
I'm looking to define the Rebol date format in EBNF notation. I'd like as best as possible to only define valid dates—at least those that are valid in Rebol at the moment:

Date ::= DateDate ('/' Time DateZone?)?

DateDate ::=
      DateDay31 ('-' DateMonth31 '-' | '/' DateMonth31 '/') DateYear
    | DateDay30 ('-' DateMonth30 '-' | '/' DateMonth30 '/') DateYear
    | DateDay28 ('-' DateMonthFebruary '-' | '/' DateMonthFebruary '/') DateYear
    | "29" ('-' DateMonthFebruary '-' | '/' DateMonthFebruary '/') DateYearLeap
    | DateYear ('-' DateMonth31 '-' | '/' DateMonth31 '/') DateDay31
    | DateYear ('-' DateMonth30 '-' | '/' DateMonth30 '/') DateDay30
    | DateYearLeap ('-' DateMonthFebruary '-' | '/' DateMonthFebruary '/') DateDay29
    | DateYear ('-' DateMonthFebruary '-' | '/' DateMonthFebruary '/') DateDay28

/*
    Currently years cannot be negative and have a maximum value of 16383
    So the following two values are shortcuts.
*/
DateYear ::= Digit (Digit (Digit (Digit Digit?)?)?)?

DateYearLeap ::=
      '1' Digit Digit DateYearLeapEnd
    | Digit Digit DateYearLeapEnd
    | Digit DateYearLeapEnd
    | DateYearLeapEnd
    | [048]

DateYearLeapEnd ::= [02468] [048] | [13579] [26]

DateMonth ::= DateMonth31 | DateMonth30 | DateMonthFebruary

DateDay31 ::= '3' [01] | DateDay29

DateDay30 ::= '30' | DateDay29

DateDay29 ::= [12] Digit | '0'? [1-9]

DateDay28 ::= '2' [0-8] | '1' Digit | '0'? [1-9]

DateMonth31 ::=
    DateMonthJanuary |
    DateMonthMarch |
    DateMonthMay |
    DateMonthJuly |
    DateMonthAugust |
    DateMonthOctober |
    DateMonthDecember

DateMonth30 ::=
    DateMonthApril |
    DateMonthJune |
    DateMonthSeptember |
    DateMonthNovember

/* Currently only English month names are valid */
DateMonthJanuary ::= 'Jan' ('u' ('a' ('r' 'y'?)?)?)? | '0'? '1'

DateMonthFebruary ::= 'Feb' ('r' ('u' ('a' ('r' 'y'?)?)?)?)? | '0'? '2'

DateMonthMarch ::= 'Mar' ('c' 'h'?)? | '0'? '3'

DateMonthApril ::= 'Apr' ('i' 'l'?)? | '0'? '4'

DateMonthMay ::= 'May' | '0'? '5'

DateMonthJune ::= 'Jun' 'e'? | '0'? '6'

DateMonthJuly ::= 'Jul' 'y'? | '0'? '7'

DateMonthAugust ::= 'Aug' ('u' ('s' 't'?)?)? | '0'? '8'

DateMonthSeptember ::= 'Sep' ('t' ('e' ('m' ('b' ('e' 'r'?)?)?)?)?)? | '0'? '9'

DateMonthOctober ::= 'Oct' ('o' ('b' ('e' 'r'?)?)?)? | '10'

DateMonthNovember ::= 'Nov' ('e' ('m' ('b' ('e' 'r'?)?)?)?)? | '11'

DateMonthDecember ::= 'Dec' ('e' ('m' ('b' ('e' 'r'?)?)?)?)? | '12'

/* Zone Hours are currently -15 - 15, the following is a shortcut: */
DateZone ::= Sign Digit Digit? ':' ([03] '0' | [14] '5')

Time ::= TimeHour ':' TimeMinute (':' TimeSecond)?

/* Need to constrain to valid hours */
TimeHour ::= Sign Digit* | Sign? Digit+

/* Need to constrain to 0-59 */
TimeMinute ::= Sign? Digit Digit?

/* Need to constrain to 0-59.999999 */
TimeSecond ::= Sign? ((Digit Digit?)? '.' Digit+ | Digit Digit? '.'?)

Digit ::= [0-9]

Sign ::= [+-]

Notes:

Partial matches are bad: this rule should match a whole string—a partial match is failure, e.g. the following would only partially match 22 and would thus fail.
'2' | '22'
I've taken shortcuts on some values (see source comments), I would expect to flesh these out.
Although Rebol will interpret 12-010-2014 as a date (12-Oct-2014), I don't see any reason to support this.

To test this code in Rebol, save as a file and load as a parse rule to use against samples:

Rebol []
do http://reb4.me/x/ebnf.r
date-grammar: get in context load-ebnf %date.ebnf 'date

foreach test [
    "28-Feb-2016"
    "29-Feb-2000"
    "29-Feb-2011"
    "29-Feb-2010"
    "29-Feb-2016"
    "1-April-2015/12:00"
    "1-4-2015/12:00+5:00"
    "01-Apr-2015"
    "31-Apr-2015"
    "29-Feb-1900"
    "00-Feb-20"
    "15-Apr-16"
    "2015-04-01/12:15:10"
    "2015-04-01/12:15:10."
    "2015-04-01/12:15:."
    "2015-04-01/12:15:10.1234"
    "2015-04-01/12:15:10.1234-05:00"
    "2015-04-01/12:15:10.1234-0:00"
][
    print [either parse test date-grammar ["*"][" "] mold test date? try [load test]]
]


texts: Wrap array operation result string inside another string

texts:
I'm trying to loop through an array, add " before, ", after each member but ommit the , at the very last member in order to generate a JSON string:

const generate_list_data_attribute = (attribute_name, from_array) => {
    let string = '';

    from_array.forEach((element, key, array) => {
        if(Object.is(array.length - 1, key)) {
            string += `"${element}"`
        } else {
            string += `"${element}",`
        }
    });

    return `data-${attribute_name}="[${string}]"`;
}

I don't like the fact that I need to Object.is(array.length-1, key) in order to dictate what the code should do with the last member. It should be automatically handled.

To note: I understand that I can just return to skip the usage of else but I'm looking for a way to automatize that "last member" check more or less.

Input (array): my_array = ["food", "gourmet", "foodie"]

Operation: generate_list_data_attribute('random', my_array);

Output (string): data-random="["food", "gourmet", "foodie"]"


texts:
Just the beginning of graphs API in Python:

# Simple graph API in Python, implementation uses adjacent lists.
# Classes: Graph, Depth_first_search, Depth_first_paths
# Usage:
# Creating new graph: gr1 = Graph(v) - creates new graph with no edges and v vertices;

# Search object: gr2 = Depth_first_search(graph, vertex) - creates search object,
# gr2.marked_vertex(vertex) - returns true if given vertex is reachable from source(above)

# Path object: gr3 = Depth_first_paths(graph, vertex)- creates a new path object,
# gr3.has_path(vertex) - thee same as above
# gr3.path_to(vertex) - returns path from source vertex (to the given)

class Graph:
    """class graph"""
    def __init__(self, v_in):
        """constructor -  takes number of vertices and creates a graph
         with no edges (E = 0) and an empty adjacent lists of vertices"""
        self.V = v_in
        self.E = 0
        self.adj = []
        for i in range(v_in):
            self.adj.append([])

    def V(self):
        """returns number of vertices"""
        return self.V

    def E(self):
        """returns number of edges"""
        return self.E

    def add_edge(self, v, w):
        """void, adds an edge to the graph"""
        self.adj[v].append(w)
        self.adj[w].append(v)
        self.E += 1

    def adj_list(self, v):
        """returns the adjacency lists of the vertex v"""
        return self.adj[v]

    def __str__(self):
        """to string method, prints the graph"""
        s = str(self.V) + " vertices, " + str(self.E) + " edges\n"
        for v in range(self.V):
            s += str(v) + ": "
            for w in self.adj[v]:
                s += str(w) + " "
            s += "\n"
        return s

class Depth_first_search:
    """class depth forst search, creates an object,
    constructor takes graph and a vertex"""
    def __init__(self, gr_obj, v_obj):
        self.marked = [False] * gr_obj.V
    self.cnt = 0
    self.__dfs(gr_obj, v_obj)

    def __dfs(self, gr, v):
        """void depth first search, proceed recursively,
        mutates marked - marks the all possible to reach
         from given (v) vertices; also mutates cnt - number of visited vert"""
        self.marked[v] = True
        self.cnt += 1
        for w in gr.adj_list(v):
            if self.marked[w] == False:
                self.__dfs(gr, w)

    def marked_vertex(self, w):
        """returns True if given vertex (w) is reachable
        from vertex v"""
        return self.marked[w]

    def count(self):
        """returns number of visited verticles
        (from given in the constructor vertex)"""
        return self.cnt

class Depth_first_paths:
    """class depth first paths, solves
    single paths problem: given graph and a vertex (source vertex), find
    a path to another vertex."""

    def __init__(self, gr_obj, v_obj):
        self.marked = [False] * gr_obj.V
        self.edge_to = [0] * gr_obj.V
        self.s = v_obj
        self.__dfs(gr_obj, v_obj)

    def __dfs(self, gr, v):
        """void recursive depth first search, mutates array marked,
        mutates counter (cnt), and creates a path (filling an array     edge_to)"""
        self.marked[v] = True
        for w in gr.adj_list(v):
            if self.marked[w] == False:
                self.edge_to[w] = v
                self.__dfs(gr, w)

    def has_path(self, v):
    """returns true if there is a path from the source
    vertex to the given, else false"""
    return self.marked[v]

    def path_to(self, v):
        """returns path from source to the given vertex"""
        if self.has_path(v) == False:
            return None
        path = []
        x = v
        while x != self.s:
            path.insert(0, x)
            x = self.edge_to[x]
        path.insert(0, self.s)
        return path

I've used classes not function because there is no need for global variables. How do you think build the rest graph algorithms on it?


texts: Converting Array of Floats to UINT8 (`char`) or UINT16 (`unsigned short`) Using SSE4

texts:
The problem is given image in 32 Bit Floating Point Format (float) how to convert it to UINT8 (char) or UNIT16 (unsigned short) in the most efficient way.

Assumptions:

Image is very long, namely don't be troubled with edge cases.
One can not assume the image is in any given range.
Output data must be clipped into the proper range ([0, 255], [0, 2 ^ 16 - 1]). I think the term is to be saturated.
Data should be rounded to nearest integer.
One could use SSE4 operations (Namely, everything but AVX).

I'd rather have a code in C style.
But C++ is also OK (I will translate it on my own).

I tried this simple code for the UINT8 case:

void ConvertToUint8(char* mO, float* mF, float* mB, int numRows, int numCols, int numColsPad, float scalingFctr)
{
    // mB - Background, mF - Foreground

    int ii, jj;

    __m128  floatPx;
    __m128  scalingFactor;
    __m128i uint8Px;

    scalingFactor = _mm_set1_ps(scalingFctr);

#pragma omp parallel for private(jj, floatPx, scalingFactor, uint8Px)
    for (ii = 0; ii < numRows; ii++) {
        for (jj = 0; jj < numCols; jj += SSE_STRIDE) {

            floatPx = _mm_loadu_ps(&mB[(ii * numColsPad) + jj]);
            uint8Px = _mm_cvtps_epi32(_mm_mul_ps(floatPx, scalingFactor));

            uint8Px = _mm_packus_epi32(uint8Px, uint8Px);
            uint8Px = _mm_packus_epi16(uint8Px, uint8Px);

            *(int *) (mO[(ii * numColsPad) + jj]) = _mm_cvtsi128_si32(uint8Px);

        }
    }

}

The code above is based on StackOverflow Q29856006 - SSE intrinsics: Convert 32-bit floats to UNSIGNED 8-bit integers.

But I'm sure there are better ways (For instance, why not load 4 packed __m128 and then store 32 Pixels at once)?


texts: SQL prepared statement to search songs by various text fields

texts:
As we know, using PDO and prepared statements, binding a table or column using bindParam is not possible. So for this, I've figured out to use function parameters to do it by replacing the column names with the parameters, as shown in the example bellow.

function search($filter,$input,$type,$order,$sort,$limit){
    $st=$this->conn->prepare("SELECT Title,Type,Youtube,Score,Ratings,Singer,ID
    FROM song WHERE $filter LIKE CONCAT('%',?,'%')
    AND Type=? ORDER BY $order $sort LIMIT $limit");
    $st->bindparam(1,$input);
    $st->bindparam(2,$type);
    $st->execute();
    return $st->fetchall();
}

And I call this function here:

$result=$search->search($_POST['filter'],$_POST['input'],$_POST['type'],$_POST['order'],$_POST['sort'],$_POST['limit']);

Where the values come from:

$filter----select
$input----input
$type----radio
$order----select
$sort----radio
$limit----input

As you see the table I'm selecting from is fix, that's not optional, but I have the option to choose which column I want the result to be ordered by($order), which column I'd like to search($filter), I want it to be ascending or descending($sort), and how many I'd like to see($limit).

And this code works fine, but I'm not sure if it's a safe way to do this. Are there some kind of risks of this solution, or it's safe to leave it like this?