texts:
This question was recently asked: Determining if three numbers are consecutive

It intrigued me, even though it was broken. I have the following implementation I thought would be interesting, and I am looking for reviews on readability, usability, and for any edge cases it may miss, etc.

/**
 * Determine whether three int values can be arranged in to an incrementing sequence.
 *
 * @param a the first value
 * @param b the second value
 * @param c the third value
 * @return true if there is an order of the three inputs which makes them sequential
 */
public static final boolean isSequential(int a, int b, int c) {
    final int x = Math.abs(a - b);
    final int y = Math.abs(b - c);
    final int z = Math.abs(a - c);
    return x + y + z == 4 && x * y * z == 2;
}

I put this together in a unit test. Here's the full file:

import org.junit.Assert;
import org.junit.Test;

public class ThreeInARow {

    /**
     * Determine whether three int values can be arranged in to an incrementing sequence.
     *
     * @param a the first value
     * @param b the second value
     * @param c the third value
     * @return true if there is an order of the three inputs which makes them sequential
     */
    public static final boolean isSequential(int a, int b, int c) {
        final int x = Math.abs(a - b);
        final int y = Math.abs(b - c);
        final int z = Math.abs(a - c);
        return x + y + z == 4 && x * y * z == 2;
    }

    private static final int[] FROM = {Integer.MIN_VALUE, Integer.MIN_VALUE + 3, -5, -4, -3, -2, -1,
            0, 1, 2, 3, 100, Integer.MAX_VALUE - 2, Integer.MAX_VALUE};

    @Test
    public void testGoodBlocks() {

        for (int f : FROM) {
            int a = f;
            int b = a + 1;
            int c = b + 1;
            Assert.assertTrue(isSequential(a, b, c));
            Assert.assertTrue(isSequential(b, c, a));
            Assert.assertTrue(isSequential(c, a, b));
            Assert.assertTrue(isSequential(b, a, c));
            Assert.assertTrue(isSequential(a, c, b));
            Assert.assertTrue(isSequential(c, b, a));
        }

    }

    @Test
    public void testBadBlocks() {

        for (int f : FROM) {
            int a = f;
            int b = a + 1;
            int c = b + 2;
            Assert.assertFalse(isSequential(a, b, c));
            Assert.assertFalse(isSequential(b, c, a));
            Assert.assertFalse(isSequential(c, a, b));
            Assert.assertFalse(isSequential(b, a, c));
            Assert.assertFalse(isSequential(a, c, b));
            Assert.assertFalse(isSequential(c, b, a));
        }

    }

    @Test
    public void testSpecials() {
        int[][] specials = {
                {0,0,0},
                {1,0,1},
                {0,0,1}
        };
        for (int[] attempt : specials) {
            Assert.assertFalse(isSequential(attempt[0], attempt[1], attempt[2]));
        }
    }

}


texts:
After looking through PHP.net documentation for hours, is this the best way to offset an array from start to finish by using array_slice() with array_merge()?

For example: $array = array(1,2,3,4) to offset by 2 to get return $array = array(3,4,1,2).

Here's the code I'm using it in:

    $team = 2;
    $course = array(
    array('title'=>1,  'hole'=> 'h01', 'shot1'=>'value="-3"', 'shot2'=>'value="-2"', 'shot3'=>'value="-1"', 'shot4'=>'value="0"', 'shot5'=>'disabled="disabled"'),
    array('title'=>2,  'hole'=> 'h02', 'shot1'=>'value="-4"', 'shot2'=>'value="-3"', 'shot3'=>'value="-2"', 'shot4'=>'value="-1"', 'shot5'=>'value="0"'),
    array('title'=>3,  'hole'=> 'h03', 'shot1'=>'value="-3"', 'shot2'=>'value="-2"', 'shot3'=>'value="-1"', 'shot4'=>'value="0"', 'shot5'=>'disabled="disabled"'),
    array('title'=>4,  'hole'=> 'h04', 'shot1'=>'value="-2"', 'shot2'=>'value="-1"', 'shot3'=>'value="0"', 'shot4'=>'disabled="disabled"', 'shot5'=>'disabled="disabled"'),
    array('title'=>5,  'hole'=> 'h05', 'shot1'=>'value="-4"', 'shot2'=>'value="-3"', 'shot3'=>'value="-2"', 'shot4'=>'value="-1"', 'shot5'=>'value="0"')
    );

    $array1 = array_slice($course, $team);
   $array2 = array_slice($course, 0, $team);
   $merged = array_merge($array1, $array2);

}


texts: JavaScript function for computing the checksum of a given number

texts:
I've got to made a function which returns the checksum of an given integer.

Source code of my implementation so far:

function computeChecksum(num) {
  if (typeof num !== 'number' || isNaN(num)) {
    throw new Error('Number, which is not NaN, expected as Parameter.');
  }

  num = Math.floor(Math.abs(num)); // Make sure the computation is done based upon an positive Integer.

  if (num < 10) {
    return num;
  }

  let divisor = Math.pow(10, num.toString().length);
  let checksum = 0;

  while (divisor >= 10) {
    let quotient = Math.floor(num / divisor);
    let divisorAsString = divisor.toString(); // For avoiding calling .toString() two times later. Appropriated or exaggeration?

    checksum += quotient;
    num -= quotient * divisor;

    // Should I pass the return-value of .slice() through parseInt()?
    //  Or just keep the implicit casting which is done when using it as an arithmetic operand?
    divisor = divisorAsString.slice(0, divisorAsString.length - 1);
  }

  return checksum + num;
}

// -------- Just testing & demo-usage------------------
// -- Not important concerning question ! -------------
let testNumbers = [11, 111, 1111,
  1111, 11111, 111111,
  123, 468, 2510,
  2501, 123456789, 1
];
let biggestSize = Math.max.apply(null, testNumbers);
let pad = new Array(biggestSize.toString().length);

pad = pad.join(' ');

testNumbers.forEach((num) => {
  console.log('%s > %s',
    (pad + num).slice(-pad.length),
    computeChecksum(num));
});
// ----------------------------------------------------

Because not in a special hurry I've avoided to search the internet for other (already available) solutions.

So the code above is the solution which came to my mind.
It seems to work as expected. Please see the added testing.

Nevertheless I like to ask:

Are there a better algorithm for computing a checksum in JavaScript?
Could parts of my implementation been improved by using other patterns?
For example the pattern I used for creating an integer with a defined size. Perhaps there's a better way?

Two further questions I've put right into my code as comments. I think that way it is better understandable what I mean.

All comments, recommendations and hints concerning my question (and my code in general) appreciated.


texts: Replacing all keys found in a dictionary for its value in a list

texts:
I have a file that is written DOS format and I need to replace some characters into others. I created a dictionary for that purposes, and now I have to read everyline from my stream and replace my values as I go.

I created this piece of code in C#, however, I highly doubt that this is the way to go, since I figure that C# dictionary class must have a simpler way to this probably common operation. Any feedback is greatly appreciated !

public Dictionary<char, string> Chars { get; set; } = new Dictionary<char, string>();

    // Called in my constructor
    public void CreateDictionnary()
    {
        Chars.Add('\u001b', " ");
        Chars.Add('\u0000', " ");
        // Multiple other characters that I have to replace
    }

public List<string> ReplaceSpecialCharacters(List<string> lines)
    {
        var result = new List<string>();

        foreach (var line in lines)
        {
            string newLine = string.Empty;

            foreach (var @char in line)
            {
                string replacedChar = @char.ToString();
                bool keyFound = false;

                foreach (var entry in Chars)
                {
                    if (keyFound)
                        continue;

                    if (@char == entry.Key)
                    {
                        replacedChar = entry.Value;
                        keyFound = true;
                    }
                }

                newLine += replacedChar;
            }

            result.Add(newLine);
        }

        return result;
    }


texts:
Trying something out of my comfort zone here, and attempting to implement a D-style range around std::string_view.

Looking for any and all suggestions or improvements.

One of the things I'm not exactly happy about is having to declare difference_type, pointer and reference just to fullfill the forward_iterator concept properly, yet not being able to actually use them.

I feel that this allowing me to initialize a vector straight from the iterator pair is worth the clunkiness, but I welcome any opinion on the subject, or suggestions on how to make it better.

Thanks!

#include <iterator>
#include <string_view>

template <typename CharT>
struct SplitStringIterator {
  using difference_type = std::ptrdiff_t;
  using value_type = std::basic_string_view<CharT>;
  using pointer = std::basic_string_view<CharT>*;
  using reference = std::basic_string_view<CharT>&;
  using iterator_category = std::forward_iterator_tag;

  SplitStringIterator(value_type str, CharT delim)
      : remainder_(str), delim_(delim) {
    advance_();
  }

  SplitStringIterator& operator++() {
    advance_();
    return *this;
  }

  SplitStringIterator operator++(int) {
    SplitStringIterator other = *this;
    advance_();
    return other;
  }

  value_type operator*() const { return sub_str_; }

  bool operator==(SplitStringIterator const& rhs) const {
    return sub_str_.data() == rhs.sub_str_.data() &&
           remainder_.data() == rhs.remainder_.data() && delim_ == delim_;
  }

  bool operator!=(SplitStringIterator const& rhs) const {
    return !(*this == rhs);
  }

 private:
  value_type sub_str_;
  value_type remainder_;
  const CharT delim_;

  void advance_() {
    auto delim_pos = remainder_.find(delim_);

    if (delim_pos == value_type::npos) {
      sub_str_ = remainder_;
      remainder_ = value_type();
    } else {
      sub_str_ = value_type(&*remainder_.begin(), delim_pos);
      remainder_.remove_prefix(delim_pos + 1);
    }
  }
};

template <typename CharT>
struct SplitString {
  SplitString(std::basic_string_view<CharT> src, CharT d)
      : source(src), delim(d) {}

  std::basic_string_view<CharT> source;
  CharT delim;

  SplitStringIterator<CharT> begin() const {
    return SplitStringIterator<CharT>(source, delim);
  }

  SplitStringIterator<CharT> end() const {
    return SplitStringIterator<CharT>(std::basic_string_view<CharT>(), delim);
  }
};

// Returns a lazy string splitter.
template <typename CharT>
SplitString<CharT> split(std::basic_string_view<CharT> str, CharT delim) {
  return SplitString<CharT>(str, delim);
}

Usage example:

#include <vector>
#include <iostream>

void foo() {
  std::string data = "aa:bb:cccc";
  auto parts = split(std::string_view(data), ':');

  for(auto p : parts) {
    std::cout << p << std::endl;
  }

  //if we need random access:
  std::vector<std::string_view> parts_indexable(parts.begin(), parts.end());
}


texts: Sql Server: Getting the highest value based on two uniqueidentifiers - possible to avoid union?

texts:
I have two riscProfileTypeIds (both of type uniqueidentifier) of which I need the one with the highest sequence number
(the highest of the two risc profiles, at business level).
The below query does the job, but I'm not very happy with the union, I wonder if there's a way to do the same without it.

SELECT [ID]
FROM [RiscProfileType]
WHERE 1 = 1
AND [Active] = 1
AND [Sequence] = (
    SELECT MAX([Sequence])
    FROM (
        SELECT [Sequence]
        FROM [RiscProfileType]
        WHERE 1 = 1
        AND [Active] = 1
        AND [ID] = @riscProfileTypeId1
        UNION
        SELECT [Sequence]
        FROM [RiscProfileType]
        WHERE 1 = 1
        AND [Active] = 1
        AND [ID] = @riscProfileTypeId2
    ) src
)

The [RiscProfileType] table is very small (4 records), so performance isn't much of an issue but still I prefer to write the best query possible.

Put simply it contains:

[Risc]          [Sequence]
Unacceptable    4
High            3
Normal          2
Low             1

I don't think a join is possible, because there's no real link between the entities.

Any suggestions on improving this query, or is this fine?


texts: Updating a chart from Yahoo Finance CSV files

texts:
I want to load some CSV columns or contents in my Ajax code. Please help me or improve my code. This will be live API code for me.

Data will be downloaded from Yahoo Finance in CSV format on an interval, and updated into this chart code. The values will be updated and chart will continue to be updated.

<?php $row = 1; if(($handle = fopen("table.csv", "r")) !== FALSE)  {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE){
$row++;
for ($c=0; $c<1; $c++)
{
echo $data[$c];
}
for ($c1=5; $c1<6; $c1++)
{
$data[$c];
}
for ($c2=4; $c2<5; $c2++)
{
$data[$c];
}
fclose($handle);
}
?>

var chart;
var chartData = [

{   year: '(here is the data from csv "col 1 row 1")',  income: '(here is the data from csv "col 5 row 1")',     expenses: '(here is the data from csv "col 4 row 1")'},{ year: '(here is the data from csv "col 1 row 2")',    income: '(here is the data from csv "col 5 row 2")',     expenses: '(here is the data from csv "col 4 row 2")'},{year: '(here is the data from csv "col 1 row 3")',    income: '(here is the data from csv "col 5 row 3")',expenses: '(here is the data from csv "col 3 row 3")'}];

AmCharts.ready(function () {
        // SERIAL CHART
        chart = new AmCharts.AmSerialChart();
        chart.pathToImages = "../amcharts/images/";
        chart.dataProvider = chartData;
        chart.categoryField = "year";
        chart.startDuration = 1;

        // AXES
        // category
        var categoryAxis = chart.categoryAxis;
        categoryAxis.gridPosition = "start";

        // value
        // in case you don't want to change default settings of value axis,
        // you don't need to create it, as one value axis is created automatically.

        // GRAPHS
        // column graph
        var graph1 = new AmCharts.AmGraph();
        graph1.type = "column";
        graph1.title = "Income";
        graph1.valueField = "income";
        graph1.lineAlpha = 0;
        graph1.fillAlphas = 1;
        chart.addGraph(graph1);

        // line
        var graph2 = new AmCharts.AmGraph();
        graph2.type = "line";
        graph2.title = "Expenses";
        graph2.valueField = "expenses";
        graph2.lineThickness = 2;

        chart.addGraph(graph2);

        // LEGEND

        // WRITE
        chart.write("chartdiv");
    });
</script>


texts: Read hex from file and convert to decimal

texts:
I made a small script to read text file that contain hexadecimal and convert to another file in decimal by using command-line as a filename input.

#this is content from hex.txt
0x5B03FA01
0x42018360
0x9FF943B3

and this is what I expected my python to deliver output

#this is content from hex_1.txt
1526987265
1107395424
2683913139

After 3 hour of trial and error. I can see a result in the way I want. The code is follow;

#this was copied from Learn Python the Hard way exercise.
from sys import argv
from os.path import exists

#this is the main function to convert hexadecimal to decimal
def hex2dec (hex):
    result_dec = int(hex, 0)
    return result_dec

#this to accept parameter from command-line
script, from_file = argv

#this to make sure the output generate as a new file with _1
to_file = from_file[:-4] + "_1.txt"
out_file = open(to_file, 'w').close()

#this took me a few hour to figure out a bug. Thanks to stackoverflow
with open(from_file) as in_file:
    lines = in_file.read().splitlines()

for i in lines:
    converted = str(hex2dec (i))
    out_file = open(to_file, 'a+')
    out_file.write(converted + "\n")
    out_file.close()

    #this to print the result for reference on-screen.
    print "converted =" + str(converted)

print "done."

Even though this is done but I feel there are plenty area I could improve to this script e.g. bugs handling in hex2dec function.

However, may I ask you what would you do to enhance this further? and if you could suggest, could anyone suggest me which topic or area I can study further to improve this code or any other about Python?


texts: Better way to apply class based on multiple conditions

texts:
I am using Angular 8.x. I have a table with two columns that can be sorted. You can only sort one column at a time. I have conditions that display an up and down sort icon if neither column is being sorted, or a up or down sort icon depending on the sort direction. Is there a better way to write this condition?

html

   Issue Opened At

   Issue Updated At

component

sortCol = '';

onSort = (col) => {
  this.sortCol = col;
  this.isDescSort = !this.isDescSort;
}


texts:
Write the program expr, which evaluates a reverse Polish expression from the command line, where each operator or operand is a separate argument.

  For example:

expr 2 3 4 + *

There are 4 files:

calc.c

#include <stdio.h>
#include <stdlib.h>
#include "calc.h"

int main(int argc, char *argv[]) {
    double tmpOp;
    char c;

    if(argc > 3) {

        while(--argc) {
            c = getOp(*++argv);
            switch(c) {
                case NUMBER:
                    push(atof(*argv));
                    break;
                case '+':
                    push(pop() + pop());
                    break;
                case '-':
                    tmpOp = pop();
                    push(pop() - tmpOp);
                    break;
                case '*':
                    push(pop() * pop());
                    break;
                case '\\':
                    tmpOp = pop();

                    if(!tmpOp) {
                        printf("error: can't divide by 0\n");
                    }
                    else {
                        push(pop()/tmpOp);
                    }
                    break;
                default:
                    printf("error: invalid expression %s\n", *argv);
            }
        }
        printf("%g\n", pop());
    }
    else {
        printf("invalid call\n");
    }

    return 0;
}

This file consist in a while loop that runs argc-1 times. At each iteration an argument is analized. If it is a number, it is pushed to the stack. If it is an operator, 2 numbers are popped from the stack and the operator is applied to these operands. If the argument is not valid, an error is printed.

argc should allways be bigger than 3 because, at this moment, the calculator needs at least 2 operands and 1 operator for an valid call.

The file getop.c:

#include <ctype.h>
#include "calc.h"

static int isNumber(const char *s) {
    int i = 0;

    if(isdigit(s[i])) {
        for(; isdigit(s[i]); i++)
            ;
    }

    if(s[i] == '.') {
        i++;
        for(; isdigit(s[i]); i++)
            ;
    }

    if(s[i] == 'e' || s[i] == 'E') {
        i++;
        for(; isdigit(s[i]); i++)
            ;
    }

    if(s[i] != '\0') {
        return 0;
    }
    return 1;
}

char getOp(const char *op) {
    int i;

    if(!isdigit(op[0]) && op[0] != '.') {
        return op[0];
    }

    i = 0;

    /* support for negative number */
    if(op[0] == '-' && !isdigit(op[1])) {
        return op[0];
    }
    else {
        i++;
    }
    if(isNumber(op + i)) {
        return NUMBER;
    }

    return op[0];
}

The function getOp returns 'n' if op contains an valid number or the first charachter of op if it is not a number - for example when we are dealing with operators.
The function getOp uses a helper to check if the the value of op is a valid number. Also, the call getOp(op + i) is intended to validate checks for negative number.

The file stack.c:

#include <stdio.h>
#define STACKVALUE 100

static double stack[STACKVALUE];
static double *pStack = stack; /* next free position in stack */

void push(double value) {
    if(pStack - stack > STACKVALUE) {
        printf("error: there is not enough psace in stack");
    }
    else {
       *(pStack++) = value;
    }
}

double pop(void) {
    if((pStack - stack) > 0) {
        return *--pStack;
    }

    printf("warning: the stack is free");
    return 0.0;
}

And the file calc.h:

#define NUMBER 'n'

int getOp(const char *s);
void push(double value);
double pop(void);


texts: Open encrypted PDF file by trying passwords from a word list

texts:
As an exercise, I wrote a program to decrypt a PDF file.  The only thing that is known about the encryption password is that it is a single English word (all capital or lowercase).

The program uses a dictionary file containing over 45000 words to unlock the file. It looks like this:

dictionary.txt

AARHUS
AARON
ABABA
ABACK
ABAFT
ABANDON
ABANDONED
ABANDONING
ABANDONMENT
ABANDONS
ABASE
ABASED
ABASEMENT
ABASEMENTS
ABASES
ABASH
ABASHED
ABASHES
⋮
ZEROTH
ZEST
ZEUS
ZIEGFELD
ZIEGFELDS
ZIEGLER
ZIGGY
ZIGZAG
ZILLIONS
ZIMMERMAN
ZINC
ZION
ZIONISM
ZIONIST
ZIONISTS
ZIONS
ZODIAC
ZOE
ZOMBA
ZONAL
ZONALLY
ZONE
ZONED
ZONES
ZONING
ZOO
ZOOLOGICAL
ZOOLOGICALLY
ZOOM
ZOOMS
ZOOS
ZORN
ZOROASTER
ZOROASTRIAN
ZULU
ZULUS
ZURICH

pdf_password_breaker

"""
Brute force password breaker using a dictionary containing
English words.
"""

import sys
import PyPDF2
from pathlib import Path

def get_filename_from_user() -> Path:
    """Asks for a path from the User"""
    while True:
        filename: str = input("Enter filename in folder of script:")
        path: Path = Path(sys.path[0], filename)

        if path.is_file():
            return path.as_posix()
        print("File doesn't exist\n")

def decrypt(pdf_filename: Path, password: str) -> bool:
    """
    Try to decrypt a file. If not successful a false is returned.
    If the file passed is not encrypted also a false is passed
    """
    with open(pdf_filename, 'rb') as pdf_file:
        pdf_reader = PyPDF2.PdfFileReader(pdf_file)
        pdf_reader.decrypt(password)
        pdf_writer = PyPDF2.PdfFileWriter()

        try:
            for page_number in range(pdf_reader.numPages):
                pdf_writer.addPage(pdf_reader.getPage(page_number))
        except PyPDF2.utils.PdfReadError:
            return False

        new_name: str = pdf_filename.stem + "_decrypted.pdf"
        filename_decrypted = pdf_filename.parent / new_name

        with open(filename_decrypted, 'wb') as pdf_file_decrypted:
            pdf_writer.write(pdf_file_decrypted)
    return True

def break_encryption(pdf_filename: Path, dictionary_filename: str) -> bool:
    """Try's out words from a dictionary to break encryption"""
    with open(dictionary_filename, 'r') as dictionary_file:
        keyword: str = dictionary_file.readline().strip()

        if decrypt(pdf_filename, keyword):
            return keyword
        if decrypt(pdf_filename, keyword.lower()):
            return keyword.lower()

        while keyword:
            keyword = dictionary_file.readline().strip()

            if decrypt(pdf_filename, keyword):
                return keyword
            if decrypt(pdf_filename, keyword.lower()):
                return keyword.lower()
    return None

def pdf_password_breaker():
    """main loop"""
    filename: Path = get_filename_from_user()
    password: str = break_encryption(filename, "dictionary.txt")

    if password:
        print("File unlocked. Password was:" + password)
        return
    print("File could not be unlocked")

if __name__ == "__main__":
    pdf_password_breaker()

I tried a file with a simple password like "hello". It works but it takes a lot of time until it reaches the "hello" in the file.

I wonder if theres a way to improve the speed, or any other aspect of the code.


texts:
I implemented this method and wanted to get suggestions and or improvements.
The objective of the method is to print the even and odd indexes of Strings contained within an array. Each set of indexes(even and odd) should be seperated by a space.

public static void printEvenOddIndexes(String[] strings){

    for(int i = 0; i < strings.length;i++){
        String word = strings[i];
        ArrayList<Integer> oddIndexes  = new ArrayList<>();
        for(int j= 0; j < word.length();j++){
            if(j % 2 == 0){
                System.out.print(word.charAt(j));
            }else{
                oddIndexes.add(j);
            }
        }
        System.out.print(" ");
        for(Integer index : oddIndexes){
            System.out.print(word.charAt(index));
        }
        System.out.println();
    }
 }


texts: Check that an image is available to be served

texts:
I have a couple of images in my database and I need to check if the images are still good or if they're deleted or corrupted. I came up with a solution but it's very slow. I was wondering if there was a way to make this faster.

img = 'http://some_image_cdn.com/images/image.jpg'
begin
  Nokogiri::HTML(open(img))
rescue
  # do something
end


texts:
I have asked a previous question but at the last moment I realized that the code does not work as intended as it has some small bugs.

I got some ideas for improvement though, but they didn't seem to work as well, so I decided to re-write it. This time, I was following the logic all the time.

char *tbl_getline (char *source, size_t line)
{
    size_t current_line = 1, columns;
    size_t iter;

    for(iter = 0; source[iter] != '\0' && current_line != line; iter++)
        if(source[iter] == '\n') current_line++;
    for(columns = 0; source[iter + columns] != '\n' && source[iter + columns] != '\0'; columns++);

    char *buff = malloc(columns + 1);
    memcpy(buff, source + iter * sizeof(char), columns);
    buff[columns] = '\0';
    return(buff);
}

And that was the code able to return a line from a string in a relatively good speed.


texts: Python: OOP design for event pricing updates

texts:
This was an interview question, I was supposed to refactor the EventPricingUpdate class to reduce the amount of nested ifs.
Here are the basic rules:

EventPricingUpdate() is responsible for updating the price of a list of events after each day.
Each event's price will be reduced by 10 for each day.
The price of each event must be in the range of 50 <= price <= 500.
The field days_from_start represents how many days before the event begins. If days_from_start < 7, then the effect of pricing change will be doubled. For example, a regular event's price will be reduced by 10 * 2 each day in the last 6 days.
There are special event_types that behavors differently.

"music" events' price will always go up by 10 each day, and up by 10 * 2 each day in the last 6 days.
"construction" events' price will never change.
"sports" events' price will drop by double the regular amount(20 instead of 10).

The class should support easily adding new conditions for a new event_type.

As you can see below, I had trouble refactoring the nested ifs in the update() method, what are some good approach to refactor it?

class Event(object):
    def __init__(self, price, days_from_start, event_type):
        self.price = price
        self.days_from_start = days_from_start
        self.event_type = event_type

class EventPricingUpdate(object):
    def __init__(self, events):
        self.events = events

    def update(self):
      for event in self.events:
        if event.event_type == 'construction':
          continue
        elif event.event_type == 'music':
          if event.days_from_start < 7 and event.price <= 480:
            event.price += 20
          elif event.price <= 490:
            event.price += 10
        elif event.event_type == 'sports':
          if event.days_from_start < 7 and event.price >= 90:
            event.price -= 40
          elif event.price >= 70:
            event.price -= 20
        elif event.days_from_start < 7 and event.price >= 70:
            event.price -= 20
          elif event.price >= 60:
            event.price -= 10
        event.days_from_start -= 1
      return self.events


texts: Running validation procedures on a table

texts:
I am working on a project that has to parse through a text file and perform validations on certain fields in the file. Some of the validations are basic (i.e. data types), and other's are a little more complex (i.e. field 1 must be x if field 2 is y).

There is a requirement that this be done in SQL Server. I have a C# background and find myself frustrated by T-SQL's difficulty in manipulating data. It is awesome for Set based operations and CRUD. However, if I need to perform row operations, I find myself writing ugly code. For example, if I need to loop through a table and step through row by row, and pull out 10 columns etc. it generates hard to read code.

Here is the code I have created and with some more information. I have a file with a predetermined format. This file needs to be validated against a list of validations stored in a table. For example, the first character of a line must be either 1, 3 or 5. I need to group the lines together based on a key and then loop through these and run all the validations against them. All this logic must be done in SQL Server.

declare @activeValidations table
(
    validationId int,
    processed bit
)

insert into @activeValidations
select Validation_ID, 0 from Validations_List where [ENABLED] = 'Y'

-- UDT
declare @keyData KeyData

insert into @keyData
select distinct Field1, Field2, Field3, Field4, Field5, Field6, 0 as 'Processed'
from [FILE]
where Field2 is not null

WHILE (select COUNT(*) from @keyData where processed = 0) > 0
BEGIN
    declare @recordId bigint
    select top 1 @recordId = KeyDataRecordId from @keyData where processed = 0

    update @activeValidations
    set Processed = 0

    WHILE (select COUNT(*) from @activeValidations where processed = 0) > 0
    BEGIN
        declare @validationId int

        select top 1 @validationId = validationId from @activeValidations where processed = 0

        declare @keyDataRow KeyData
        insert into @keyDataRow
        select top 1 Field1, Field2, Field3, Field4, Field5, Field6, [Processed] from @keyData where KeyDataRecordId = @recordId

        declare @storedProcIndicator char(1)
        select @storedProcIndicator = PROC_INDICATOR from Validations_List where Validation_ID = @validationId

        IF @storedProcIndicator = 'Y'
        BEGIN
            declare @procName nvarchar(40)
            select @procName = PROC_NAME from Validations_List where Validation_ID = @validationId

            EXECUTE sp_executesql @procName, N'@keyDataRow KeyData READONLY', @keyDataRow

        END

        update @activeValidations
        set Processed = 1
        where validationId = @validationId
    END

    update @keyData
    set Processed = 1
    where KeyDataRecordId = @recordId
END

Validation Proc

ALTER PROCEDURE [dbo].[sp110_v1]
(@keyData KeyData READONLY)
AS
BEGIN

    declare @validationMessage varchar(500)
    select @validationMessage = Message from Validations_List where Validation_ID = 110

    -- Field must be numeric in Position 108-117 10 bytes
    insert into FailedValidations
    select Field1, Field2, Field3, Field4, Field5, Field6, @validationMessage
    from [FILE] wf
    where wf.Field1= (select Field1 from @keyData) and
          wf.Field2 = (select Field2 from @keyData) and
          wf.Field3 = (select Field3 from @keyData) and
          wf.Field4 = (select Field4 from @keyData) and
          wf.Field5 = (select Field5 from @keyData) and
          wf.Field6 = (select Field6 from @keyData) and
          wf.RecordType = '04' and
          --Note the row column is varchar(500) and represents 1 row in a text file
          ISNUMERIC(SUBSTRING(Row, 108, 10)) <> 1

END


texts: Sort numbers in ascending order using Python

texts:
This is Python code to sort the numbers in ascending order (It's my school task). How does it look?

It works, but I think that this can be improved.

# How many number we have to sort
num = int(input("How many figures : "))
storage = []
result = []

# Creating an array of users numbers
for i in range(1,num+1):
    a = int(input("Enter value" + str(i) + " : "))
    storage.append(a) # user enter

# Sorting the array
for m in range(len(storage)):
    b = min(storage)
    storage.remove(b)
    result.append(b) # user get
j = ' '.join(str(i) for i in result)
print(j)


texts: Finding the most frequent character in a string

texts:
This is in C/C++ (using a c-string as input). I'm curious if my solution could be more efficient than it currently is.

char mostFrequent(char *bytes, int length) {
  char holder[26];
  for (int i = 0; i < 26; i++) {
    holder[i] = 0;
  }

  for (int i = 0; i < length; i++) {
    holder[bytes[i]-97] += 1;
  }

  char b = 97; // a
  int count = holder[0];
  for (int i = 1; i < 26; i++) {
    if (holder[i] > count) {
      count = holder[i];
      b = i+97;
    }
  }

  return b;
}


texts: Fetch data from database either with a stored procedure or a query

texts:
I have this method, GetDataAsync(), that grabs data from the database using a stored procedure if sqlToRun Dictionary contains the table name. If not, then there is no stored procedure to run and just grab the table from the db directly (no SP) and convert it to a C# object to use.

Here's the code:

private async Task<Response> GetDataAsync(string table, int? start, int? end)
{
    if (_sqlToRun.ContainsKey(table))
    {
        var sql = _sqlToRun[table];
        var data = new List<Dictionary<string, object>>();
        var resp = new Response();

        using (var conn = new SqlConnection(_ConnectionString))
        {
            var cmd = new SqlCommand(sql, conn) { CommandType = CommandType.StoredProcedure };

            var startParam = new SqlParameter
            {
                ParameterName = "@startRowNum",
                Value = start,
                SqlDbType = SqlDbType.Int
            };

            cmd.Parameters.Add(startParam);

            var endParam = new SqlParameter
            {
                ParameterName = "@endRowNum",
                Value = end,
                SqlDbType = SqlDbType.Int
            };

            cmd.Parameters.Add(endParam);
            var outputParam = cmd.Parameters.Add("@recordCount", SqlDbType.Int);
            outputParam.Direction = ParameterDirection.Output;

            await conn.OpenAsync();
            using (var rdr = await cmd.ExecuteReaderAsync())
            {
                while (await rdr.ReadAsync())
                {
                    var dictionary = new Dictionary<string, object>();
                    foreach (var i in Enumerable.Range(0, rdr.FieldCount))
                    {
                        var dbValue = string.IsNullOrWhiteSpace(rdr.GetValue(i).ToString()) == true
                            ? string.Empty
                            : rdr.GetValue(i);

                        dictionary.Add(rdr.GetName(i), dbValue);
                    }

                    data.Add(dictionary);
                }
            }

            Int32.TryParse(cmd.Parameters["@recordCount"].Value.ToString(), out var recordCount);
            resp.Data = data;
            resp.RecordCount = recordCount;
        }

        return resp;
    }
    else
    {
        var data = new List<Dictionary<string, object>>();
        var resp = new Response();

        using (var conn = new SqlConnection(_ConnectionString))
        {
            string sql = "Select * from " + table;
            SqlCommand cmd = new SqlCommand(sql, conn);

            await conn.OpenAsync();
            using (var rdr = await cmd.ExecuteReaderAsync())
            {
                while (await rdr.ReadAsync())
                {
                    var dictionary = new Dictionary<string, object>();
                    foreach (var i in Enumerable.Range(0, rdr.FieldCount))
                    {
                        var dbValue = string.IsNullOrWhiteSpace(rdr.GetValue(i).ToString()) == true
                            ? string.Empty
                            : rdr.GetValue(i);

                        dictionary.Add(rdr.GetName(i), dbValue);
                    }

                    data.Add(dictionary);
                }
            }

            Int32.TryParse(cmd.Parameters["@recordCount"].Value.ToString(), out var recordCount);
            resp.Data = data;
            resp.RecordCount = recordCount;
        }

        return resp;
    }
}

Where Response is below:

public class Response
{
    public int RecordCount { get; set; }
    public List<Dictionary<string, object>> Data { get; set; }
}

How can I improve this code and refactor it?


texts: Simplify simple object clear function with Javascript

texts:
I have a clear function that accepts an array, string, or no arguments. If no arguments, it should clear the entire data object. It works fine, but looking for a code review.

The possibilities should be:

clear('one');
clear(); //clear all
clear(['one', 'three']);

var data = {
  one: 'test1',
  two: 'test2',
  three: 'test3'
};

var clear = function(fields) {
  if (fields !== undefined) {
    if (typeof fields === 'string') {
      data[fields] = '';
    } else {
      _.each(fields, function(field) {
        if(data.hasOwnProperty(field)) {
          data[field] = '';
        }
      });
    }
  } else {
    // clear all
    _.each(data, function(value, key) {
      data[key] = '';
    });
  }
};

clear(['one', 'two']);
clear();
clear(['one']);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>


texts: Are these list-comprehensions written the fastest possible way?

texts:
This is a simple repeatable question regarding the usage of Python3's comprehensions:

Could the Python3 syntax be used in another way to speed up the process, further so the gap between Python3 and numpy would be reduced? (see chart below).

The results & code:

Above: Runtime test of Python3's list comprehension, dict comprehension, python for loop and numpy

Update 1 Above: Runtime test without power-functions including Janne Karila suggestion to break down the power function to x * x * x

Update2 Above: Runtime test without powerfunctions and with Justin Peels recommendation to use return list(a.values())

#/usr/bin/python3 -

import sys
from datetime import datetime
import numpy
import matplotlib.pyplot as pyplot

def doingnothing(n):
    for i in range(n):
        pass
    return []

def numpysum(n): #NPY
    a = numpy.arange(n) ** 2.
    b = numpy.arange(n) ** 3.
    c = a + b
    return c

def listexpression(n):  #LE
    #return [x**2+x**3 for x in range(n)]
    return [x*x+x*x*x for x in range(n)]

def dictcomprehension(n):  #DC
    # a = {x:x**2+x**3 for x in range(n)}
    a = {x:x*x+x*x*x for x in range(n)}
    # return [a[key] for key in a]
    return list(a.values())

def pythonsum(n): #PS
    a = list(range(n))
    b = list(range(n))
    c = []

    for i in range(len(a)):
            # a[i] = i ** 2.
            a[i] = i * i
            # b[i] = i ** 3.
            b[i] = i * i * i
            c.append(a[i] + b[i])
    return c

def runtimetest(size,verbose=True):
    v = verbose
    d = {'DoingNothing':None,
         'NPY':None,
         'LE':None,
         'DC':None,
         'PS':None}

    start = datetime.now()
    c = doingnothing(size)
    d['DoingNothing'] = datetime.now() - start

    start = datetime.now()
    c = numpysum(size)
    d['NPY'] = datetime.now() - start

    start = datetime.now()
    c = listexpression(size)
    d['LE'] = datetime.now() - start

    start = datetime.now()
    c = dictcomprehension(size)
    d['DC'] = datetime.now() - start

    start = datetime.now()
    c = pythonsum(size)
    d['PS'] = datetime.now() - start

    if v:
        for key in sorted(d):
            print(key, "took", round(d[key].seconds + d[key].microseconds/10**6,6), " sec.")
    else:
        return d

def view(results):
    """
    result['header']=['DoingNothing','NPY','LE','DC','PS']
    result[3000]=[0.0, 0.0, 0.002, 0.003, 0.003001]
    """
    if 'header' in results.keys():
        results.pop('header')

    steps,DN,NPY,LE,DC,PS=[],[],[],[],[],[] #I love multiple assignment!

    for step in sorted(results):
        steps.append(step)
        DN.append(results[step][0])
        NPY.append(results[step][4])
        LE.append(results[step][5])
        DC.append(results[step][6])
        PS.append(results[step][4])

    pyplot.plot(steps,DN)
    pyplot.plot(steps,NPY)
    pyplot.plot(steps,LE)
    pyplot.plot(steps,DC)
    pyplot.plot(steps,PS)
    pyplot.legend(['Empty Loop', 'Numpy.Arange', 'List Comprehension', 'Dict Comprehension', 'Python for Loop'], loc='upper left')
    scale = 'linear'
    pyplot.xscale(scale)
    pyplot.yscale(scale)
    pyplot.title('runtime test')
    pyplot.xlabel('length of list')
    pyplot.ylabel('runtime in seconds')

    pyplot.show()

def longruntimetest(length):
    if length<10**4:
        length=10**4

    result = {}
    result['header']=['DoingNothing','NPY','LE','DC','PS']
    for step in range(10**3, length+1,10**3):
        t=runtimetest(step,verbose=False)
        result[step]=[t['DoingNothing'],t['NPY'],t['LE'],t['DC'],t['PS']]
        for i in range(len(result[step])):
            result[step][i]=round(result[step][i].seconds
                                  +result[step][i].microseconds/10**6,6)

    view(result)

def main():
    if sys.version_info <= (3, 2):
        sys.stdout.write("Sorry, requires Python 3.2.x, not Python 2.x\n")
        sys.exit(1)

    testsize=10**5
    runtimetest(testsize)
    longruntimetest(testsize)

if __name__=='__main__':
    main()


texts:
I just finished this exercise where i should reverse a string with a recursive function. First of all, i created a separate function called swap to swap the chars, should i write it as function pointer?. After i call the function recursively untill i reach the base case, the if check if the variable "lenght" is 1 or 0, bacause the string can be even or odd. Any tips to improve this code? i don't know it's seems pretty ugly.

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

void swap(char arr[], int pos, int pos_2){
  char sent = arr[pos_2];
  arr[pos_2] = arr[pos];
  arr[pos] = sent;

}

void recursive_mirror(char arr[], int lenght){

  if(lenght == 0 || lenght == 1){
    return;
  }

  swap(arr, 0, lenght - 1);
  lenght--;
  recursive_mirror(arr + 1, lenght - 1);

}

int main(void) {

  char arr[] = "mirror";
  recursive_mirror(arr,strlen(arr));
  printf("%s\n", arr);
  return 0;
}


texts: Sequence generator with custom step size, start value and operation

texts:
I have created a little generator class to generate number sequences.The intended purpose of this class is to be used with generate_n to populate containers. I would like to know whether there is something which i can do to improve performance or usability or to make the code more generic. It should be possible to compile the code with a c++14 conformant compiler at the moment, but i am open to use any number of c++17 features.
My generator class:

#include <functional>

template<typename Number,
         typename AdvanceOperation = std::plus<Number>>
class sequence_generator
{
  public:
    constexpr sequence_generator(Number start_value = Number{},
                                 Number step_size = Number{1},
                                 AdvanceOperation advancer = AdvanceOperation{})
                                 : current_value{start_value},
                                   step_size{step_size},
                                   advancer{advancer}
    {}
    constexpr auto operator()() -> Number
    {
      return next();
    }
    constexpr auto next() -> Number
    {
      auto tmp = current_value;
      current_value = advancer(current_value, step_size);
      return tmp;
    }
  private:
    Number current_value;
    Number step_size;
    AdvanceOperation advancer;
};

template<typename Number, typename AdvanceOperation=std::plus<Number>>
auto make_sequence_generator(Number start_value, Number step_size,
                             AdvanceOperation advancer)
{
    return sequence_generator<Number, AdvanceOperation>{start_value, step_size,
                                                        advancer};
}

Some use cases:

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

#include "generator.hpp"

int main()
{
  std::vector<int> vector(10);
  std::generate(std::begin(vector), std::end(vector),
                sequence_generator<int>{});
  assert(vector == std::vector<int>({0,1,2,3,4,5,6,7,8,9}));
  std::generate(std::begin(vector), std::end(vector),
                make_sequence_generator(1,2,std::multiplies<>{}));
  assert(vector == std::vector<int>({1,2,4,8,16,32,64,128,256,512}));
}


texts:
I'm basically trying to build a function that searches all nodes on the DOM to check for data attributes, then swap them out with whatever is stored with the "data-intl-" attribute. For example, if someone had data-intl-attr, whatever attr is on, that node would get replaced by what's in data-intl-attr.

The code works; I just want to know if I could have approached it differently.

var all = $('*');

$.map(all,function(el) {

    filter($(el).data(), function(clean){
      var originalAttrVal = $(el).attr(clean);
      var intlAttr = $(el).attr("data-intl-" + clean);

      $(el).attr(clean, intlAttr);

    });

});

function filter(foo, cb){
        var capture;
    for(var i in foo) {
      if (foo.hasOwnProperty(i)) {
        i = i.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
        i = i.replace(/intl-/g, '');
        capture= i;
     }
     cb(capture);
  }

}

Input HTML:

test href

Output HTML:

test href


texts:
I'm quite new to C, and I'm looking for feedback on this (doubly) linked list code.

Once I get to the add and remove methods, I feel like the code goes downhill. I'm looking for any potential errors I haven't spotted, and improvements that could be made for efficiency/tidiness.

struct node {
    int data;
    struct node *next;
    struct node *previous;
};

struct listset {
    struct node *head;
    struct node *tail;
    int current_elements;
};

struct listset * new_listset(){
    struct listset *new_list = malloc(sizeof(struct listset));
    new_list ->head = NULL;
    new_list ->tail = NULL;

    return new_list;
};

struct node *listset_lookup(struct listset *this, int item){
    struct node *curr_elem = this->head;
    if(!curr_elem) return NULL;
    while(item != curr_elem->data){
        if(curr_elem->next==NULL)return NULL;
        curr_elem = curr_elem->next;
    }
    return curr_elem;
}

void listset_add(struct listset *this, int item){
    struct node *new_node = malloc(sizeof(struct node));
    new_node -> data = item;
    new_node ->next = NULL;
    if(!this->head) {
        new_node->previous = NULL;
        this->head = this->tail = new_node;
    }
    else{
        this->tail->next = new_node;
    }
    this->current_elements++;
}
void listset_remove(struct listset *this, int item){
    struct node *elem_remove = listset_lookup(this, item);
    if(!elem_remove) return;
    if(elem_remove->next && elem_remove->previous) elem_remove->previous->next = elem_remove->next;
    else if (elem_remove->previous && !elem_remove->previous){
        elem_remove->previous->next=NULL;
        this->tail = elem_remove->previous;
    }
    else{
        this->tail = NULL;
        this->head = NULL;
    }
    free(elem_remove);
}


texts:
In a service I'm developing I'm using three cloud services (five if you count additional two streaming services I have to create that are used by those cloud services in turn) and to orchestrate bits and pieces incoming I need a cache for objects relating data from all those services. That cache has to be is safe to access from various Tornado handlers in an atomic manner.

Now, since Tornado is based on I/O loop, theoretically I do not need to use locks or some other synchronization primitives... but that's obviously relying on implementation detail (GIL) and it can reportedly cause problems under some circumstances anyway, so to be rather safe than sorry I try to develop the cache that is all:

Singleton
Thread-safe
Creates a default object available under a key

I'm approaching the subject with some trepidation as so far I have not done such stuff much. This is what I've come up with so far:

UPDATE

I've realized I had a stupid mistake in the previous implementation: the setdefault method called default_factory every time. Updated version works but it's kinda ugly:

class ThreadSafeSingletonCache(object):
    __me = None
    __cache = None
    __lock = threading.Lock()

    def __new__(cls, _):
        if cls.__me is None:
            cls.__cache = {}
            cls.__me = super(ThreadSafeSingletonCache, cls).__new__(cls)
        return cls.__me

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

    def obj_setattr(self, cache_key, obj_attr, value):
        with self.__lock:
            item = self.__like_setdefault(cache_key)
            setattr(item, obj_attr, value)

    def __like_setdefault(self, cache_key):
        ''' Unfortunately I cannot use .setdefault as default_factory function gets called on each setdefault use'''
        item = self.__cache.get(cache_key)
        if not item:
            item = self.default_factory()
            self.__cache[cache_key] = item
        return item

    def get(self, cache_key):
        with self.__lock:
            return self.__like_setdefault(cache_key)

    def set(self, cache_key, obj):
        with self.__lock:
            self.__cache[cache_key] = obj

Please point out problems and potential improvements.


texts: Reading columns of a delimited text file

texts:
This class reads a delimited text file into String arrays on demand. Delimiter can be any regex.

Features include:

Read a single column
Read a range of columns
Read arbitrary columns by providing an array of indices, e.g. for columns 1, 3, 5, use new int[]{1, 3, 5}

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.function.Supplier;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * Created by IDEA on 17/11/14.
 */
public class Txt {
    final private String sep;
    final private Pattern pattern;
    final private String filename;
    private Supplier<Stream<String>> fileStream;
    Txt(String _filename, String _sep) throws IOException {
        sep = _sep;
        filename = _filename;
        pattern = Pattern.compile(sep);
        fileStream = () -> {
            try {
                return Files.lines(Paths.get(filename), Charset.defaultCharset());
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
        };
    }
    Txt(String _filename) throws IOException {
        this(_filename, "\\s+");
    }

    public String[] nthCol(int n) throws IOException {
        if(n < 1) n = 1;
        final int finalN = n;
        List<String> colList =  fileStream.get()
                .map(line -> pattern.split(line, finalN + 1)[finalN - 1])
                .collect(Collectors.toList());
        return colList.toArray(new String[colList.size()]);
    }

    public String[][] cols() throws IOException {
        List<String[]> colsList =  fileStream.get()
                .map(line -> pattern.split(line))
                .collect(Collectors.toList());
        return colsList.toArray(new String[colsList.size()][]);
    }

    public String[][] cols(final int start, final int end) {
        if(start > end || start < 1) throw new IllegalArgumentException("Starting index must <= ending index AND >= 1");
        List<String[]> colsList =  fileStream.get()
                .map(line -> {
                    String[] fields = pattern.split(line, end + 1);
                    // indices of col 2-4          2 3 4
                    // fields after splitting    0 1 2 3 4
                    // range of array              1     4
                    // java ending index is              exclusive
                    String[] demandedFields = Arrays.copyOfRange(fields, start-1, end);
                    return demandedFields;
                })
                .collect(Collectors.toList());
        return colsList.toArray(new String[colsList.size()][]);
    }

    public String[][] cols(int[] index) {
        Arrays.sort(index);
        final int[] finalIndex = index;
        final int start = finalIndex[0];
        final int end = finalIndex[finalIndex.length - 1];
        if(start > end || start < 1) throw new IllegalArgumentException("Starting index must <= ending index AND >= 1");
        List<String[]> colsList =  fileStream.get()
                .map(line -> {
                    String[] fields = pattern.split(line, end + 1);
                    String[] demandedFields = new String[finalIndex.length];
                    for(int i=0; i<finalIndex.length; i++) {
                        demandedFields[i] = fields[finalIndex[i]-1];
                    }
                    return demandedFields;
                })
                .collect(Collectors.toList());

        return colsList.toArray(new String[colsList.size()][]);
    }
}


texts:
I want to compare two unordered list and currently I am doing it in the following way. Is there a better way to do this as I am repeating my code twice (for null check & then converting to a Set). Maybe there exists a library in Guava which does this?

public class CompareUnorderedList implements BiPredicate<Object, Object> {
    private Function<Object, Object> mapping;
    public CompareUnorderedList(Function<Object, Object> mapping) {
       this.mapping = mapping;
    }
    @Override
    public boolean test(Object o1, Object o2) {
        o1 = o1 != null ? o1 : Collections.EMPTY_LIST;
        o2 = o2 != null ? o2 : Collections.EMPTY_LIST;

        Set<Object> firstSet = (List<Object>o1).stream().map(mapping).collect(Collectors.toSet());
        Set<Object> secondSet = (List<Object>o2).stream().map(mapping).collect(Collectors.toSet());
        return firstSet.equals(secondSet);
    }
}


texts:
Please review the following code. Methods getFirsts and getSeconds, both of which are private, return a list of objects which implement CommonInterface. Is this a good or bad design?

@Override
public final List<? extends CommonInterface> getObjects(final CommonEnum type) {
    if (type == null) {
        return new ArrayList<CommonInterface>();
    }
    switch (type) {
        case FIRST:
            return getFirsts();
        case SECOND:
            return getSeconds();
        default:
            return null;
    }
}


texts:
Here is my simple implementation on XML parser for XML which I received from a server response. Also I've tried to use XmlPathDocument but failed to get child elements for a node in XmlPathIterator.

    public OutboxResponse CheckSendResponseForOutboxPacket(Outbox outbox)
    {
        var responseContent = outbox.Outbox_content.FirstOrDefault().response_content;

        OutboxResponse outboxResponse = new OutboxResponse();
        outboxResponse.Violations = new List<OutboxResponseViolation>();

        XmlDocument responseDocument = new XmlDocument();
        responseDocument.LoadXml(responseContent);
        var rootElement = responseDocument.DocumentElement;

        //XPath templates
        string responseResult = "r:body/r:result/text()";
        string violationCode = "g:body/g:code/text()";
        string violationLevel = "g:body/g:level/text()";
        string violationName = "g:body/g:name/text()";
        string violationDescription = "g:body/g:violations/g:violation";
        string itemResultResult = "g:body/g:itemResults/g:itemResult/g:result/text()";
        string itemResultViolations = "g:body/g:itemResults/g:itemResult/g:violations/g:violation";

        XmlNamespaceManager nsmanager = new XmlNamespaceManager(responseDocument.NameTable);
        nsmanager.AddNamespace("g", "http://google.com");

        switch (rootElement.SelectSingleNode(responseResult, nsmanager).Value)
        {
            case "success":
                outboxResponse.Result = "Packet received without errors";

                foreach (XmlNode violation in rootElement.SelectNodes(itemResultViolations, nsmanager))
                {
                    outboxResponse.Violations.Add(new OutboxResponseViolation
                    {
                        Level = violation.SelectSingleNode("g:level/text()", nsmanager).Value,
                        Name = violation.SelectSingleNode("g:name/text()", nsmanager).Value,
                        Description = violation.SelectSingleNode("g:description/text()", nsmanager).Value

                    });

                }

                break;
            case "failure":
                outboxResponse.Result = "Errors was found in packet";

                foreach (XmlNode violation in rootElement.SelectNodes(violationDescription, nsmanager))
                {
                    outboxResponse.Violations.Add(new OutboxResponseViolation
                    {
                        Level = violation.SelectSingleNode("r:level/text()", nsmanager).Value,
                        Name = violation.SelectSingleNode("r:name/text()", nsmanager).Value,
                        Description = violation.SelectSingleNode("r:description/text()", nsmanager).Value

                    });

                }

                break;
        }

        return outboxResponse;

    }


texts: Iterating through a collection of objects

texts:
Subject

I have to iterate through a collection of objects (in this case IGrouping<string, SupplyDemand>). So I could do this easyly using a query with LINQ.

Code

    public IEnumerable<string> getParentPegs(IGrouping<string, SupplyDemand> data)
    {
        IEnumerable<string> query =
            from d in data
            where d.Source.ToLower() == "make"
            select d.Part;

        return query;
    }

Problem

I'm using this function inside a loop in a VSTO Excel project and it's pretty slow, besides it stops running (memory leak). So I came up with the following code:

Improved Code

    public List<string> getParentPegs(IGrouping<string, SupplyDemand> data)
    {
        List<string> result = new List<string>();

        var enumerator = data.GetEnumerator();
        while (enumerator.MoveNext())
        {
            SupplyDemand obj = enumerator.Current;
            if (obj.Source.ToLower() == "make")
            {
                result.Add(obj.Peg);
            }
        }

        return result;
    }

Question

Is there any other way to improve this?


texts: Algorithm to replace this duplicated code

texts:
I've got a simple thing that I inherited from another developer and think it could be replaced with something a bit more elegant. What this is doing is comparing the length of a string to a set value, and setting the font size accordingly:

if(maxLen<50){$('.fc-cards').css('font-size',40);}
if(maxLen<100){$('.fc-cards').css('font-size',25);}
if(maxLen<150){$('.fc-cards').css('font-size',22);}
if(maxLen<200){$('.fc-cards').css('font-size',20);}

If the min font size is 18, and the max 40, what a nice way to dynamically figure a font size with a range of <50 chars being 40px to >200 being 18px... it doesn't have to match the exact values mentioned above, a sliding scale would be perfect.


texts: Accumulate ids to make a single ajax request

texts:
I have multiple places where I need to make ajax requests to fetch the items corresponding to some ids. However, I only want to make a single request by accumulating these ids and debouncing the actual method that makes the ajax request...So far I've come up with this code, but it just feels ugly/non-reusable.

Is there any simpler/recommended method to achieve similar results without sharing resolve/promise variables like I did here?

Here's a fiddle

const fakeData = [{
    id: 1,
    name: 'foo'
  },
  {
    id: 2,
    name: 'bar'
  },
  {
    id: 3,
    name: 'baz'
  }
];

let idsToFetch = [];

let getItemsPromise, resolve, reject;

const fetchItems = _.debounce(() => {
  console.log('fetching items...');
  const currentResolve = resolve;
  const currentReject = reject;

  // simulating ajax request
  setTimeout(function() {
    const result = idsToFetch.map((id) => fakeData.find(item => item.id == id));
    currentResolve(result);
  }, 400);

  getItemsPromise = resolve = reject = null;
}, 500);

function getItems(ids) {
  idsToFetch = ids.filter((id) => !idsToFetch.includes(id)).concat(idsToFetch);
  if (!getItemsPromise) {
    getItemsPromise = new Promise((_resolve, _reject) => {
      resolve = _resolve;
      reject = _reject;
    });
  }

  fetchItems();

  return getItemsPromise
    .then((res) => {
      return res.filter((item) => ids.includes(item.id));
    })
}

setTimeout(() => {
  console.log('first request start');
  getItems([1]).then(res => console.log('first result:', res));
}, 100);
setTimeout(() => {
  console.log('second request start');
  getItems([1, 2]).then(res => console.log('second result:', res));
}, 200)
setTimeout(() => {
  console.log('third request start');
  getItems([1, 3]).then(res => console.log('third result:', res));
}, 300)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>


texts: Converting Shell input into Windows DOS compliant input

texts:
I have a shell and batch script to make specific calls to a MBean on a JMX server. The shell input args are not working in windows because windows handles " differently than linux.

Assuming this is a bean name : bean = "hostName=\"localhost\",name=\"foobar\"\""; and the whole input args on linux is something like this:

String[] params = new String[]{"-srv", "localhost:1234", "-usr", "foo", "-pwd", "bar", "-b", bean};

This works perfectly fine on a shell but not for windows.

I wrote one method to convert the bean name to be windows dos compliant. This is essentially accomplished by adding 2 double quotes to a single double quote and adding only 2 double quotes to two double quotes:

" -> """ and "" -> """"

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

    String bean = "hostName=\"localhost\",name=\"foobar\"\"";
    String[] params = new String[]{"-srv", "localhost:1234", "-usr", "foo", "-pwd", "bar", "-b", bean};

    for ( int i = 0; i < params.length; i++)
    {
      if (params[i].equals("-b"))
      {
        // this is most likely the bean name
        String beanName = params[i + 1];
        StringBuilder dosCompliantName = new StringBuilder();
        // commence magic to make double quotes (") correct for windows
        for (int j = 0; j < beanName.length(); j++)
        {
          char c = beanName.charAt(j);
          if (c == '"')
          {
            try
            {
              if (beanName.charAt(j + 1) != '"')
              {
                // this is only one double quote so we add 2 additional double quotes to it
                dosCompliantName.append(c);
                dosCompliantName.append(c);
                dosCompliantName.append(c);
              }
              else if (beanName.charAt(j + 1) == '"')
              {
                // we have 2 double quotes here so we add only one because the next loop run will then also add only
                // one and in the end we have 4 double quotes:
                // "" -> """ -> """"
                dosCompliantName.append(c);
                dosCompliantName.append(c);
              }
            }
            catch (StringIndexOutOfBoundsException e)
            {
              // we have reached the end and the last char was a double quote so we add 2
              dosCompliantName.append(c);
              dosCompliantName.append(c);
            }
          }
          else
          {
            dosCompliantName.append(c);
          }
        }

        System.out.println(dosCompliantName);
        params[i + 1] = dosCompliantName.toString();
      }
    }
  }

The input/output for Linux and Windows on the console should look like this:

Linux : hostName="localhost",name="foobar""

Windows:hostName="""localhost""",name="""foobar""""

This looks like to work but to me it looks terribly inefficient, ugly and the readability is also not really great. How can I improve this?

Note: of course this whole stuff is extracted into its own method but for the sack of demonstration I put it into the main method


texts:
At the moment I am using this to check a boolean property in sharepoint 2007 using C# and .Net Framework 3.5

if (bool.Parse(listItem.Properties["Boolean Property"].ToString()) == false)

is there any better way of doing it ?

Edit

when my code try to convert property into string it gives me exception even when am validating if property is empty or not.

This Worked For me

using method "Contains Key" instead of "Properties.Containsfield"

object abc = "bool property";

foreach (SPListItem item in list.Items)
{
     if (item.Properties.ContainsKey(abc)


texts:
I need to get some ids from contacts and contactgroups to be able to collect the data. My example works but i dont know if this is the way to go.

getIdArray() {
let contactIds = [];
let groupIds = [];
let contacts = this.http.get('Contacts/').map(res => res.json());
let contactGroup = this.http.get('ContactGroups/').map(res =>res.json());
Observable.forkJoin([contacts, contactGroup]).subscribe(res => {

  for (let b of res[0].contacts) {
    console.log(b.contactId);
    contactIds.push(b.contactId)
  }

  for (let b of res[1].contactgroups) {
    console.log(b.contactgroupId)
    groupIds.push(b.contactgroupId)
  }
  this.loadContacts(contactIds);
  this.loadGroups(groupIds);

 });
}

loadContacts(contactId) {
console.log("ids" + JSON.stringify(contactId));
Observable.forkJoin(
  contactId.map(
    i => this.http.get('Contacts/' + i)
      .map(res => res.json())
  )
 ).subscribe(data => {
  for (let b of data) {
    console.log(b);
  }
});
}

loadGroups(groupIds){
console.log("ids" + JSON.stringify(groupIds));
Observable.forkJoin(
  groupIds.map(
    i => this.http.get('ContactGroups/' + i)
      .map(res => res.json())
  )
).subscribe(data => {
  for (let b of data) {
    console.log(b);
  }
});
}


texts: Multi-threading with TPL - Access Internal Class Properties

texts:
I am using the TPL library to parallelize a 2D grid operation. I have extracted a simple example from my actual code to illustrate what I am doing. I am getting the desired results I want and my computation times are sped up by the number of processors on my laptop (12).

I would love to get some advice or opinions on my code as far as how my properties are declared. Again, it works as expected, but wonder if the design could be better. Thank you in advance.

My simplified code:

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

namespace Gridding
{

    public abstract class Base
    {
        /// <summary>
        /// Values representing the mesh values where each node in the gridis assigned som value.
        /// </summary>
        public float[,] Values { get; set; }
        public abstract void Compute();
    }

    public class Derived : Base
    {

        /// <summary>
        /// Make the mesh readonly.  Is this necessary?
        /// </summary>
        readonly Mesh MyMesh;

        Derived(Mesh mesh)
        {
            MyMesh = mesh;
        }

        public override void Compute()
        {
            Values = new float[MyMesh.NX, MyMesh.NY];

            double[] xn = MyMesh.GetXNodes();
            double[] yn = MyMesh.GetYNodes();

            /// Paralellize the threads along the columns of the grid using the Task Paralllel Library (TPL).
            Parallel.For(0, MyMesh.NX, i =>
            {
                Run(i, xn, yn);
            });
        }

        private void Run(int i, double[] xn, double[] yn)
        {
            /// Some long operation that parallelizes along the columns of a mesh/grid
            double x = xn[i];
            for (int j = 0; j < MyMesh.NY; j++)
            {

                /// Again, longer operation here
                double y = yn[j];

                double someValue = Math.Sqrt(x * y);
                Values[i, j] = (float)someValue;
            }
        }

        static void Main(string[] args)
        {
            int nx = 100;
            int ny = 120;
            double x0 = 0.0;
            double y0 = 0.0;
            double width = 100;
            double height = 120;

            Mesh mesh = new Mesh(nx, ny, x0, y0, width, height);

            Base tplTest = new Derived(mesh);
            tplTest.Compute();

            float[,] values = tplTest.Values;

            Console.Read();

        }

        /// <summary>
        /// A simple North-South oriented grid.
        /// </summary>
        class Mesh
        {
            public int NX { get; } = 100;
            public int NY { get; set; } = 150;
            public double XOrigin { get; set; } = 0.0;
            public double YOrigin { get; set; } = 0.0;
            public double Width { get; set; } = 100.0;
            public double Height { get; set; } = 150.0;
            public double DX { get; }
            public double DY { get; }

            public Mesh(int nx, int ny, double xOrigin, double yOrigin, double width, double height)
            {
                NX = nx;
                NY = ny;
                XOrigin = xOrigin;
                YOrigin = yOrigin;
                Width = width;
                Height = height;
                DX = Width / (NX - 1);
                DY = Height / (NY - 1);
            }

            public double[] GetYNodes()
            {
                double[] yNodeLocs = new double[NY];
                for (int i = 0; i < NY; i++)
                {
                    yNodeLocs[i] = YOrigin + i * DY;
                }
                return yNodeLocs;
            }

            public double[] GetXNodes()
            {
                double[] xNodeLocs = new double[NX];
                for (int i = 0; i < NX; i++)
                {
                    xNodeLocs[i] = XOrigin + i * DX;
                }
                return xNodeLocs;
            }
        }
    }
}


texts:
Basically, I'm performing an if statement on an array based on the returned value

<?php
if($array[1]>10000 AND $array[1]<50000){
        $selling = $array[1] - 250;
    }
    elseif($array[1]>50000 AND $array[1]<100000){
        $selling = $array[1] - 500;
    }
    else{
        $selling = $array[1] - 100;
    }
    $buying = $array[1] - 1000;

    if($array[1]>=10000){
        $buying = $buying-1000;
        if($array[1]>=20000){
            $buying = $buying-1000;
            if($array[1]>=30000){
                $buying = $buying-1000;
            }
                if($array[1]>=40000){
                    $buying = $buying-1000;
                }
                    if($array[1]>=50000){
                        $buying = $buying-750;
                    }
                        if($array[1]>=60000){
                            $buying = $buying-500;
                        }
                            if($array[1]>=70000){
                                $buying = $buying-500;
                            }
        }
    }
?>

As you can see it's VERY messy, would anyone be able to point me in the correct direction for cleaning this up please?


texts: Python, given a word, generate a list with one letter changing for each letter in alphabet

texts:
Here is my problem:

  Return the number of times that the string code appears anywhere in the given string, except we'll accept any letter for the d, so cope and cooe count.

I solved it by creating a list with all 26 possible co_e combinations and then used two for loops to iterate through the list and search for matches in the given string.

Is there another way I could have created that list? or is there a way to ignore the third character in word and only search for matching characters 1, 2 and 4?

Here is my solution:

if len(inputstring)<4:
    return 0
wordlist=['coae','cobe','coce','code'...etc]
count=0

for i in wordlist:
    for j in range(len(inputstring)):
        if inputstring[j:j+4] == i:
            count+=1
return count


texts:
I've written concurrent queue based on std::queue.

#include <queue>
#include <shared_mutex>
#include <condition_variable>

template <typename T, typename S = typename std::queue<T>::container_type>
class concurrent_queue {
    // no std::shared_mutex yet
    using mutex_type = std::shared_timed_mutex;

public:
    explicit concurrent_queue(const S &sequence)
            : queue_(sequence) { }

    explicit concurrent_queue(S &&sequence = S())
            : queue_(std::move(sequence)) { }

    concurrent_queue(const concurrent_queue &other)
    {
        std::shared_lock<mutex_type> other_lock(other.mutex_);
        queue_ = other.queue_;
    }

    concurrent_queue(concurrent_queue &&other)
    {
        std::unique_lock<mutex_type> lock(mutex_, std::defer_lock);
        std::shared_lock<mutex_type> other_lock(other.mutex_, std::defer_lock);
        std::lock(lock, other_lock);
        queue_ = std::move(other.queue_);
    }

    concurrent_queue &operator=(const concurrent_queue &other)
    {
        if (this != &other) {
            std::unique_lock<mutex_type> lock(mutex_, std::defer_lock);
            std::shared_lock<mutex_type> other_lock(other.mutex_, std::defer_lock);
            std::lock(lock, other_lock);
            queue_ = other.queue_;
        }
        return *this;
    }

    concurrent_queue &operator=(concurrent_queue &&other)
    {
        if (this != &other) { // not needed?
            std::unique_lock<mutex_type> lock(mutex_, std::defer_lock);
            std::shared_lock<mutex_type> other_lock(other.mutex_, std::defer_lock);
            std::lock(lock, other_lock);
            queue_ = std::move(other.queue_);
        }
        return *this;
    }

    ~concurrent_queue() = default;

    T pop()
    {
        std::unique_lock<mutex_type> lock(mutex_);
        condition_variable_.wait(lock, [this] { return !queue_.empty(); });
        T item = queue_.front(); // use auto?
        queue_.pop();
        return item;
    }

    bool pop(T &item)
    {
        std::unique_lock<mutex_type> lock(mutex_);
        if (queue_.empty()) {
            return false;
        } else {
            item = queue_.front();
            queue_.pop();
            return true;
        }
    }

    void push(const T &item)
    {
        std::unique_lock<mutex_type> lock(mutex_);
        queue_.push(item);
        lock.unlock();
        condition_variable_.notify_one();
    }

    void push(T &&item)
    {
        std::unique_lock<mutex_type> lock(mutex_);
        queue_.push(std::move(item));
        lock.unlock();
        condition_variable_.notify_one();
    }

    template <typename ...Args>
    void emplace(Args &&... args)
    {
        std::unique_lock<mutex_type> lock(mutex_);
        queue_.emplace(std::forward<Args>(args)...);
        lock.unlock();
        condition_variable_.notify_one();
    }

private:
    mutable mutex_type mutex_;
    std::condition_variable_any condition_variable_;
    std::queue<T, S> queue_;
};

Things I'd like to know about this code:

Possible deadlocks - it seems to be working fine in my program, but I'm only using one producer and one consumer. (see #3)
Exception safety - I guess pop methods can throw, but I don't see how this could be avoided without hacks like external locking (lock-front-pop-unlock)
Testing - I've done some really basic tests, things like multiple readers and writers. It has never crashed but I don't really know how to test it.
Anything that comes to your mind.


texts: HarckerRank 2D Arrays Hourglass challenge

texts:
About this 2D Arrays HackerRank problem.

The task is to find the maximum sum of a region in a 2D array. Specifically, it is to find the maximum sum of an "hourglass" region, defined as a 3x3 square without the middle entries on the left and right sides, as shown by this mask.

1 1 1
0 1 0
1 1 1

Here's my solution.

I'd appreciate some review about code quality.

# Begin of HackerRank code: data entries for testing the user code
# ----------------------------------------------------------------
arr = []

for _ in range(6):
    arr.append(list(map(int, input().rstrip().split())))
# ----------------------------------------------------------------
# End of HackerRank code

my_hourglasses = list()

for i in range(0,4):
    for j in range(0,4):
        hourglass = list()
        hourglass += arr[i][j:j+3]
        hourglass.append(arr[i+1][j+1])
        hourglass += arr[i+2][j:j+3]
        my_hourglasses.append(hourglass)

hourglasses_sums = [sum(item) for item in my_hourglasses]

print(max(hourglasses_sums))


texts:
I had seen a YouTube video making actual Lissajous patterns with sand falling from a pendulum with 2 different periods and looking in the Wikipedia page the looked very easy to simulate.

I made a Processing sketch simulating such a pattern. Here is an example output with a = 3, b = 4 (the same as the third Wikipedia example).

// Lissajous patterns simulator
// https://en.wikipedia.org/wiki/Lissajous_curve

void setup() {
  size(600, 600);
  background(255);
}

int A = 300; // X stretching factor
int B = 300; // Y stretching factor
float a = 3; // x "relative importance"
float b = 4; // y "relative importance"
float time = 0;
int offset = 0;
final float TIMESTEP = 0.001;

void draw() {
  int x = (int) ( A * sin(a*time + offset) );
  int y = (int) ( B * sin(b*time) );

  point(x + A, y + B);
  time += TIMESTEP;
}

I have two main questions:

I kept the names short to match closely the Wikipedia specification, and added a short comment near them. Is this best practice?
I have quite a few related variables. Should I encapsulate them into a class (maybe LissajousSimulator, with a single function updateState)? Or would that just be over-engineering?


texts: Counting dropped frames while converting uncompressed video data

texts:
I am writing a class for converting uncompressed video data which processes data in its incoming queue and stores them in its outgoing queue. Every time it tries to process a frame of a format it doesn't know, it drops this frame and increases its internal m_dropCnt. The calling component is keeping track of all droped frames (from this class or other classes) and therefore needs to add this counter to its own counter.

This process is performed regularly which is why I need to reset m_dropCnt every time the calling component calls getDropCount(). I was wondering whether there is a shorter way of doing so than this:

class FormatConverter
{

public:
  FormatConverter() :
    m_dropCnt(0),
    m_running(false)
     /* other members */
    {
    }

  int getDropCount()
  {
    in ret = m_dropCnt;
    m_dropCnt = 0;
    return ret;
  }

  void convert()
  {
    while (m_running)
    {
      if (!validConversion())
      {
        m_dropCnt++;
        m_inQueue.pop();
      }
      else
      {
        /* perform conversion */
      }
    }
  }

private:
  int  m_dropCnt;
  bool m_running
  /* other members */
}

convert is actually running in its own thread, however I left everything regarding thread synchronization out.

To summarize: Is there a way to shorten the method getDropCount()?


texts:
In code I'm currently maintaining, there is a need to do very many repeated XOR operations of blocks of memory.  The block size in my case is always 16 bytes.  Because the code is executed very frequently, and because it's speed critical, I would like it to be as fast as possible.  Ordinarily I'd write this in assembly language for that reason, but I'd prefer that the code stay in C++ to maximize portability.  This is what I'm currently using, but I would like a review to address particularly the following questions:

Can this code be made faster?
Can the portability be improved?  In particular, I'm interested in avoiding problems on architectures for which there is a penalty for misaligned memory access.

memxor.c
const size_t BLKSIZE = 16;
typedef unsigned bigsize_t;
inline void memxor(uint8_t dst[BLKSIZE], const uint8_t *a, const uint8_t *b)
{
    bigsize_t *s=reinterpret_cast<bigsize_t *>(dst);
    const bigsize_t *au = reinterpret_cast<const bigsize_t *>(a);
    const bigsize_t *bu = reinterpret_cast<const bigsize_t *>(b);
    for (size_t i=BLKSIZE/sizeof(*s); i; --i)
        *s++ = *au++ ^ *bu++;
}


texts: Node module using promises and the revealing module pattern

texts:
Can someone give me some feedback on this pattern?

I am writing a node.js module that connects to a remote API, caches JSON, returns it as output. I have a cli wrapper script that uses the module, and then returns the output to a non-node app for a completely different purpose.

Am I using promises correctly here? Does anyone have any good module pattern + promises examples to look at? Is it proper to promisify a non-promise library and then wrap that library inside of a new promise when creating a function?

In this example saveJSON, cachedJSON, and refreshJSON all use fs or request so I am returning promises for those.

The lib is similar to this:

foo.js:

var Promise = require('bluebird')
var fs = Promise.promisifyAll(require("fs"))
var request = Promise.promisifyAll(require("request"));

function Foo() {
    var json = {}

    var emptyJSON = function() {
        return {
            "entries": {
                "vars": {}
            }
        }
    }

    var saveJSON = function(json) {
        return new Promise(function(resolve, reject) {
            fs.writeFileAsync('foo.json', JSON.stringify(json))
              .then(function() {
                  resolve(cachedJSON())
              })
              .catch (function(e) {
                  reject(e)
              })
        })
    }

    var cachedJSON = function() {
        return new Promise(function(resolve, reject) {
            fs.readFileAsync('./foo.json')
              .then(JSON.parse)
              .then(function(json) {
                  resolve(json)
              })
              .catch(SyntaxError, function(e){
                  // File exists, but has a syntax issue
                  reject("Invalid json")
              })
              .catch (function(e) {
                  // Return empty json on error
                  resolve(emptyJSON())
              })
        });
    }

    var refreshJSON = function() {
        return new Promise(function(resolve, reject) {
            request.getAsync('http://berkeleymapper.googlecode.com/svn-history/r101/trunk/web/foo.json').get(1)
                   .then(JSON.parse)
                   .then(saveJSON)
                   .then(function(json) {
                        resolve(json)
                   })
                   .catch (function(e) {
                       // Return empty json on error
                       resolve(emptyJSON())
                   })
             })
    }

    return {
        cachedJSON: cachedJSON,
        refreshJSON: refreshJSON
    }

}

module.exports = new Foo()

Where this could be utilized in a situation like this:

runFoo.js:

var foo = require("./foo")

// Refresh and return the latest json from remote
foo.refreshJSON()
   .then(function(json) {
       console.log('### Refresh cached json with remote and return ###')
       console.log(json)
   });

// Return only the cached json
foo.cachedJSON()
   .then(function(json) {
       console.log('### Return cached json only ###')
       console.log(json)
   });


texts: Python webscrape Amazon Music, generate tracklist

texts:
So I've been working on a tracklist generator that scrapes from Amazon Music using a url using Python for albums with one artist. I've made uhhh this, I'm really new to this requests and beautifulsoup4 thing. I wonder if I can improve it to make it more efficient.

import requests
from bs4 import BeautifulSoup

Amazon=str(input("Please enter an Amazon music url:"))
r=requests.get(Amazon)
soup = BeautifulSoup(r.text,'html.parser')
name=soup.find_all('a', attrs={'class':'a-link-normal a-color-base TitleLink a-text-bold'}) #find out the names of the track title
time=soup.find_all('td',attrs={'class':'a-text-right a-align-center'}) #find the duration of the track
artist= soup.find('a', attrs={'id':'ProductInfoArtistLink'}) #find the creator of the track, which for now can only take one

for i in range(1,len(name),2):
    print(str(int(i/2+1))+'. '+name[int(i)].text+' - '+ artist.text + ' (' + time[int((i-1)/2)].text[12:16] + ')')

#first int produces a placeholder number for the track e.g 1., 2.
#second int produces track name, which len shows twice of number of tracks
#artist text gives artist name
#time gives time and puts it in brackets


texts:
I need to change the page title based on the current state of my store. Right now I came up with
const useTitle = () => {
  const { foo, bar } = useSelector(selectFoorBar);
  const baz = useSelector(selectBaz);

  const fooBarDisplayString = format(foo, bar);
  const barDisplayString = (bar ?? 0).toFixed(0);

  useEffect(() => {
    document.title = `${fooBarString} | ${bazDisplayString}`;
  }, [fooBarDisplayString, bazDisplayString]);
};

export default useTitle;

Is the name useTitle appropriate? It's technically a hook, because it's using other hooks, so it must start with use keyword. That feels weird to somebody coming outside of the React world like me. Furthermore, it doesn't return any title, so it's more of a keepTitleUpToDate(), which should become useKeepTitleUpToDate() which is even weirder. How would you name it?
Is it appropriate to keep this functionality in a hook like I did or is there some other convention in React for stuff that depends on hooks?


texts:
VBA has built-in functions for repeating a single character:

  Function String$(Number As Long, Character) As String

  Function Space$(Number As Long) As String

But neither are of any use when you need to repeat a string that has more than one character.

You could repeat a string "abcde" 5 times by doing something crafty like:

?Join(Split(String$(5,"."),"."),"abcde")

But that is neither intuitive nor performant.

In Excel, there is also WorksheetFunction.Rept, but it is painfully slow, and only available in Excel.

So I made a custom function that builds the string, while minimizing the concatenations. In fact, it doesn't use any concatenation, but instead uses a buffer and CopyMemory to fill the buffer. And rather than filling the buffer one instance at a time, the code fills the buffer using a lookback that reduces the number of buffer writes exponentially:

Given a string "abcde" that repeats 5 times:

Create a buffer of 25 spaces

"                         "

1st buffer write - assign the string to the first buffer position

"abcde                    "
 [NEW]

2nd buffer write - copy the existing populated buffer (5 characters) into the next buffer position

"abcdeabcde               "
      [NEW]

3rd buffer write - copy the existing populated buffer (10 characters) into the next buffer position

"abcdeabcdeabcdeabcde     "
           [  NEW   ]`

4th buffer write - copy the lesser of the existing populated buffer (20 characters) and the remaining buffer (5 characters) into the next buffer position.

"abcdeabcdeabcdeabcdeabcde"
                     [NEW]

StringRepeat

Private Declare Sub CopyMemory Lib "kernel32.dll" Alias "RtlMoveMemory" (ByVal Destination As Long, ByVal source As Long, ByVal Length As Long)

Public Function StringRepeat(number As Long, expression As String) As String

  Dim copyBufferLength As Long
  copyBufferLength = LenB(expression)

  'Create a buffer
  StringRepeat = Space$(number * Len(expression))

  Dim bufferLengthBytes As Long
  bufferLengthBytes = LenB(StringRepeat)

  Dim bufferPointer As Long
  bufferPointer = StrPtr(StringRepeat)

  'Copy the original expression to the start of the buffer
  CopyMemory bufferPointer, StrPtr(expression), copyBufferLength

  Do While copyBufferLength < bufferLengthBytes
    Dim remainingByteCount As Long
    'Check we're not going to overflow the buffer
    remainingByteCount = bufferLengthBytes - copyBufferLength
    If copyBufferLength > remainingByteCount Then
      CopyMemory bufferPointer + copyBufferLength, bufferPointer, remainingByteCount
    Else
      CopyMemory bufferPointer + copyBufferLength, bufferPointer, copyBufferLength
    End If
    copyBufferLength = copyBufferLength * 2
  Loop

End Function

The performance varies by the number of repeats, and the number of characters in the string to be repeated. I tried handling special cases like repeating a string 1 time (just return the string), and/or repeating a single character (return the result of String$ instead), but while that speeds up the special cases, it slows down all other cases.

I'm not checking whether the number input is positive, and I'm not checking that the string to repeat is at least 1 character long, as for now, I'm focusing on performance.

In some instances (small values of number, short expression lengths), avoiding the Exponential lookback approach is not as fast as a straight-up loop and copy:

RepeatString Simple

Function StringRepeatSimple(number As Long, expression As String) As String

  Dim expressionLengthBytes As Long
  expressionLengthBytes = LenB(expression)

  'Create a buffer
  StringRepeatSimple= Space$(number * Len(expression))

  Dim bufferPointer As Long
  bufferPointer = StrPtr(StringRepeatSimple)

  Dim expressionPointer As Long
  expressionPointer = StrPtr(expression)

  Dim copyCounter As Long
  For copyCounter = 0 To number - 1
    CopyMemory bufferPointer + copyCounter * expressionLengthBytes, expressionPointer, expressionLengthBytes
  Next copyCounter

End Function


texts:
I'm trying to refactor the following code and could use some suggestions.  Basically, three functions generating random numbers in different ways are called:

import java.util.Random;
public final class JP_RandomNumbers {

    /**
     * @param aArgs
     */

    public static void main(String[] aArgs) {
        genRandomNumbers1();
        genRandomNumbers2();
        genRandomNumbers3();
    }

    private static void genRandomNumbers1() {
        log("Generating 10 random integers in range 0..99.");

        //note that a single Random object is reused here
        Random randomGenerator = new Random();
        for (int idx = 0; idx < RANGE ; ++idx) {
            int randomInt = randomGenerator.nextInt(100);
            log("Generated :" + randomInt);
        }
        log("Done.");

    }

    private static void genRandomNumbers2() {
        //Generating random numbers in a specific range
        int START = 1;
        int END = 10;

        Random random = new Random();
        for (int idx = 1 ; idx <= 10 ; ++idx) {
            showRandomInteger(START, END, random);
        }
        log ("Done");

    }

    private static void showRandomInteger(int aStart, int aEnd, Random aRandom) {
        if(aStart > aEnd) throw new IllegalArgumentException("Start cannot exceed End.");

        //get the range, casting to avoid overflow problems
        long range = (long)aEnd - (long) aStart + 1;
        //compute a fraction of the range , 0 <= frac <= range
        long fraction = (long) (range * aRandom.nextDouble());
        int randomNumber = (int)(fraction + aStart);
        log("Generated : " + randomNumber);
    }

    private  void genRandomNumbers3() {
        double MEAN = 100.0f;
        double VARIANCE = 5.0f;
        for(int idx = 1; idx <= 10; ++idx){
            log("Generated : " + String.valueOf(getGaussean(MEAN,VARIANCE)));
        }
        log ("Done");

    }

    private double getGaussean(double aMean, double aVariance){
        return aMean + fRandom.nextGaussian() * aVariance;
    }

    //Private
    private static final int RANGE = 10;
    private Random fRandom = new Random();
    private static void log( String aString) {
        System.out.println(aString);
    }

}

Output:

Generating 10 random integers in range 0..99.
Generated :74
Generated :99
Generated :75
Generated :15
Generated :32
Generated :31
Generated :96
Generated :61
Generated :80
Generated :89
Done.
Generated : 2
Generated : 4
Generated : 1
Generated : 9
Generated : 9
Generated : 5
Generated : 9
Generated : 4
Generated : 3
Generated : 7
Done
Generated : 96.16324820042756
Generated : 97.4298343909747
Generated : 105.18654272922421
Generated : 90.56523225378042
Generated : 100.26474837892167
Generated : 99.13288502577953
Generated : 105.99193834986883
Generated : 101.21081536019025
Generated : 99.48291677422242
Generated : 100.55524156214658
Done


texts:
Given the following recursive definition of sum:

(define (sum term a next b)
  (if (> a b)
      0
      (+ (term a)
         (sum term (next a) next b))))

And the task:

  Exercise 1.30

  The sum procedure
  above generates a linear recursion.
  The procedure can be rewritten so that
  the sum is performed iteratively. Show
  how to do this by filling in the
  missing expressions in the following
  definition:

(define (sum term a next b)
  (define (iter a result)
    (if <??>
        <??>
        (iter <??> <??>)))
  (iter <??> <??>))

I wrote the following code.  What do you think?

(define (i-sum term a next b)
  (define (iter a result)
    (if (> a b)
        result
        (iter (next a) (+ result (term a)))))
  (iter a 0))

(define (identity x) x)
(define (inc x) (+ 1 x))
(define (sum-integers a b) (i-sum identity a inc b))


texts:
In general, I'd love some comments on this basic queue using dynamic allocation.
In particular, I want comments about whether this queue is good in embedded systems, for example say a a sensor network gateway, which has to queue up packets to be forwarded on say a UART.
I hear normally that mallocs are a bad idea for embedded, so what are the pitfalls in such a scenario?
One thing is, that malloc could return that it was unable to allocate the required memory. But what I thought was that if I did the calculation and I was reasonably certain that I definitely have MAX_QSIZE amount of memory available for the MAX_DATSIZE then realistically I shouldn't be able to see malloc fail. Is that a correct assumption?
I am rewriting the same code for a version with static array and no mallocs as well, so I'll try to analyze how both behave.
Thank you for your time.
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdlib.h>

#define MAX_QSIZE   100
#define MAX_DATSIZE     128

struct node{
    void *data;
    struct node *next;
};
typedef struct node node_t;

typedef struct queue_t {
    node_t *head;
    node_t *tail;
    int size;
} queue_t;

queue_t *q_init(void)
{
    queue_t *q = malloc(sizeof (*q));
    q->size = 0;
    q->head = q->tail = NULL;
}

int q_push(queue_t *q, const void *pdata, int bsize)
{
    if (q == NULL)
        return -1;
    if (q->size == MAX_QSIZE)
        return -2;
    if (bsize > MAX_DATSIZE)
        return -3;

    node_t *new = malloc(sizeof (*new));
    new->next = NULL;
    new->data = malloc(bsize);
    bzero(new->data, bsize);
    memcpy(new->data, pdata, bsize);

    if (q->size == 0) {
        q->head = new;
    } else {
        q->tail->next = new;
    }
    q->tail = new;
    q->size++;

    return 0;
}

node_t *q_peek(queue_t *q)
{
    return q->head;
}

void q_pop(queue_t *q)
{
    if (q->size == 0)
        return;
    node_t *this = q->head;
    q->head = this->next;
    free(this);
    q->size--;
    if (q->size == 0)
        q->tail = NULL;
}

void freeq(queue_t *q)
{
    while (q->head != NULL) {
        node_t *t = q->head;
        q->head = t->next;
        free(t);
    }
    free(q);
}

void printq(queue_t *q)
{
    int i = 0;
    for (node_t *h = q->head; h != NULL; h = h->next) {
        printf("[%d] %s\n", i++, (char*)h->data);
    }
}

int main()
{
    char *test[] =
    {
        "January",
        "February",
        "Random"
    };
    int numtest = sizeof test / sizeof test[0];
    queue_t *nameq = q_init();
    for (int i = 0; i < numtest; i++) {
        q_push(nameq, test[i], strlen(test[i]));
    }
    printq(nameq);

    q_pop(nameq);
    printq(nameq);

    char *hname = (char*)(q_peek(nameq)->data);
    printf("head name = %s\n", hname);

    freeq(nameq);
    return 0;
}


texts: Testing if the binary representation of an integer has an odd number of ones

texts:
The fn odd_ones(x: u32) -> bool function should return true when x contains a odd number of 1s.

Assumption:

x is 32 bit unsigned.

Restriction:

The code should contain a total of at most 12 arithmetic, bitwise and logical operations.

Forbidden:

Conditionals, loops, function calls and macros.
Division, modulus and multiplication.
Relative comparison operators (<, >, <= and >=).

Allowed operations:

All bit level and logic operations.
Left and right shifts, but only with shift amounts between 0 and w - 1
Addition and subtraction.
Equality (==) and inequality (!=) tests.
Casting between u32 and i32.

My code: (Rust playground)

fn odd_ones(x: u32) -> bool {
   let mid = (x >> 16) ^ x;
   let mid2 = (mid >> 8) ^ mid;
   let mid3 = (mid2 >> 4) ^ mid2;
   let mid4 = (mid3 >> 2) ^ mid3;

   (((mid4 >> 1) ^ mid4) & 1) == 1
}

fn odd_ones_test(x: u32) -> bool {
    let sum = (0..32).map(|y| x >> y )
                     .fold(0, |sum ,y| sum + (y & 1));
    sum % 2 != 0
}

fn test (from: u32, to: u32) -> bool {
    (from..to).all(|x| odd_ones_test(x) == odd_ones(x))
}

fn main() {
    println!("{}", test(!0 - 45345, !0));
}

Any better way of doing this?


texts: Checking the validation of a field through the Property mutator method `set`

texts:
I'm newish to C#, being mainly Java oriented. I have a field _config which needs to be a value from 1 to 8, and I have this code which checks to make sure I can only set _config to 1-8. If the value given for set is "invalid", _config becomes -1.

public int Config {
    get
    {
        return _config;
    }

    set
    {
        if (value > 8 || value < 1)
        {
            _config = -1;
        }
        else
        {
            _config = value;
        }
    }
}
private int _config; // the actual field that the property 'Config' refers to.

This feels really weird to me, but it does what I need it to do. I'm also thinking about having the setter throw an exception instead of setting _config to -1 when given an invalid value. Am I using Properties correctly, or have I completely misunderstood the point of them?