texts: LaTeX table generator - file in argument list

texts:
My code generates a LaTeX table from a plain text file which uses whitespace as delimiters. It asks you the title of the columns one-by-one (mind the formatting!). Then it outputs a latex.txt file with a nicely formatted table inside.

How can I improve it?

Here's the code:

#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>

int main(int argc, char* argv[])
{
    if(argc!=2){
        std::cerr << "Error loading file." << std::endl;
        return 1;
    }
    int col = 0, row = 0;
    // First of all. Provide an input file split by whitespaces.
    std::ifstream fin(argv[1],std::ios::in);
    std::vector< std::vector<double> > matrix;
    while(!fin.eof()){
        std::vector<double> v;
        std::string line;
        getline(fin, line);
        std::istringstream nums(line);
        double x;
        while(nums >> x){
            v.push_back(x);
        }
        matrix.push_back(v);
        row++;
    }
    // Basic.
    row--;
    col = matrix[0].size();
    std::ofstream fout("latex.txt",std::ios::out);
    fout << "\\begin{center}\n\\begin{tabular}{";
    for(int i=0;i<col;i++){
        fout << "|c";
    }
    fout << "|}\n";
    fout << "\\hline\n";
    // Ask for col titles:
    for(int i=0;i<col;i++){
        std::cout << "What is the title of the " << i+1 <<  ". column?(Please mind the formatting!)" << std::endl;
        std::string title;
        getline(std::cin,title);
        fout << title;
        if(i!=col-1){
            fout << " & ";
        }else{
            fout << " \\\\\n\\hline\n";
        }
    }
    for(int i=0;i<row;i++){
        for(int j=0;j<col;j++){
            fout << matrix[i][j];
            if(j!=col-1){
                fout << " & ";
            }else{
                fout << " \\\\\n\\hline\n";
            }
        }
    }
    fout << "\\end{tabular}\n";
    fout << "\\end{center}";
    return 0;
}


texts:
Last night I made a object oriented pattern that I find very useful. With this pattern, one can quickly assign a new class, add to an existing class, and chain methods together.

Its pretty short, I was wondering if anyone could suggest some improvements or point out any error before I end up using this pattern over an over.

Thanks everyone!

 /**
 * Creates a new namespaced global prototype
 * @constructor ClassCreate
 * @param {string} ns - Classname / method namespace
 * @param {object} newMethods - Object containing methods
 * to be merged with built in ones prior to instantiation
 * @return {function} [ns]() - New dynamically named prototype function
 */

function ClassCreate(ns, newMethods) {
    "use strict";
    var Constructor = function() { /* Base constructor Class */ };

    Constructor.prototype.methods = { /* Hashtable for containing all methods for all things */ };

    // Directly merge in any new methods provided before constructing a new instance of the Class
    var validMethodTypes = 0,
        totalPropsInObj = 0;

    if (typeof newMethods === 'object') {
        for (var method in newMethods) {
            totalPropsInObj++;
            if (typeof newMethods[method] === 'function' && newMethods.hasOwnProperty(method)) validMethodTypes++;
        }
        if (validMethodTypes === totalPropsInObj) {
            Constructor.prototype.methods = newMethods;
        } else {
            alert('invalid');
        }
    }

    (function loadInheritedMethods() {
        // Some built in methods
        Constructor.prototype.methods['alert'] = function(msg) {
            alert(msg);
            return this;
        };

        Constructor.prototype.methods['ready'] = function(rdFn) {
            window.onload = function() {
                rdFn();
            };
            return this;
        };
    })();

    // No more can be done with the prototype after this!
    window[ns] = new Constructor(); // Initialize app, set the global namespace
    return window[ns]; // return the new function to the global context
};

// Usage:
ClassCreate('Calculator', {

    "add": function(a, b) {
        return a + b;
    },

    "subtract": function(a, b) {
        return a - b;
    },

    "multiply": function(a, b) {
        return a * b;
    },

    "divide": function(a, b) {
        return a / b;
    }

}).methods.alert('This method was even chained to the constructor!');

var x = Calculator.methods.add(1, 2),
    y = Calculator.methods.divide(4, 1),
    result = Calculator.methods.multiply(x, y);

Calculator.methods.ready(function() {
    alert(result);
});

// Define
ClassCreate('Test', {"test1": function(msg){ return alert(msg);} });

// Use
Test.methods.test1('test2!');

View the live demo here


texts: PHP function to evaluate comparisons between two values, with debug logging

texts:
The following method works fine but it is rather verbose:

private function performComparison($element, $operator, $value_allowed, $value_entered)
{
    switch($operator):
        case '>':
            $result = ($value_entered >  $value_allowed) ? true : false;
            break;
        case '>=':
            $result = ($value_entered >= $value_allowed) ? true : false;
            break;
        case '<':
            $result = ($value_entered <  $value_allowed) ? true : false;
            break;
        case '<=':
            $result = ($value_entered <= $value_allowed) ? true : false;
            break;
        case '=':
            $result = ($value_entered == $value_allowed) ? true : false;
            break;
    endswitch;
        $dateformat = 'n/j/Y';
        $debug = ['element' => $element, 'operator' => $operator, 'value allowed' => is_a($value_allowed, 'DateTime') ? $value_allowed->format($dateformat) : $value_allowed, 'value entered' => is_a($value_entered, 'DateTime') ? $value_entered->format($dateformat) : $value_entered, 'result' => ($result === false) ? 'false' : 'true'];
        echo '
'.print_r($debug,1).'
';
    return $result;
}

Note that the 3 lines of code just before the return $result; line are very helpful for debugging in the Development phase so I'd like to keep those.

In an attempt to make a more concise version of this method I came up with the following:

private function performComparison($element, $operator, $value_allowed, $value_entered)
{
    $comparisonFunctions = [
        '>' => function($value_allowed, $value_entered) { return ($value_entered >  $value_allowed) ? true : false; },
        '>='    => function($value_allowed, $value_entered) { return ($value_entered >= $value_allowed) ? true : false; },
        '<' => function($value_allowed, $value_entered) { return ($value_entered <  $value_allowed) ? true : false; },
        '<='    => function($value_allowed, $value_entered) { return ($value_entered <= $value_allowed) ? true : false; },
        '=' => function($value_allowed, $value_entered) { return ($value_entered == $value_allowed) ? true : false; }
    ];

    $result = array_key_exists($operator, $comparisonFunctions) ? $comparisonFunctions[$operator]($value_allowed, $value_entered) : null;
        $dateformat = 'n/j/Y';
        $debug = ['element' => $element, 'operator' => $operator, 'value allowed' => is_a($value_allowed, 'DateTime') ? $value_allowed->format($dateformat) : $value_allowed, 'value entered' => is_a($value_entered, 'DateTime') ? $value_entered->format($dateformat) : $value_entered, 'result' => ($result === false) ? 'false' : 'true'];
        echo '
'.print_r($debug,1).'
';
    return $result;
}

This version also works fine but I'm wondering if there are any ways it could be condensed further.


texts: Function to split either a string array or string into a string array

texts:
I am programming a language interpreter in C# and have recently created a set of functions that receive either a string or a string[] and split it by a received string.

For example, with a string:

"Hey:123:hello:456"
":"

It will return this array:

{"hey","123","hello","456"}

And with a string[]:

{"a:b","c","d:e:f"}
":"

It will return this array:

{"a","b","c","d","e","f"}

How can I improve efficiency and maybe make it tidier?

public string[] SplitRows(object thevar, string delimiter) {

            if (delimiter == "<newline>") delimiter = "\n";

            if (thevar.GetType() == typeof(string)) {
                string temp = (string) thevar;
                return temp.Split(new string[] {
                    delimiter
                }, System.StringSplitOptions.None);
            }
            if (thevar.GetType() == typeof(string[])) {
                return stringarraysplitter((string[]) thevar, delimiter);
            }
            return null;
        }

        public string[] stringarraysplitter(string[] arr, string delimiter) {
            string[][] tempr = new string[arr.Length][];
            for (int i = 0; i < arr.Length; i++) {
                tempr[i] = arr[i].Split(new string[] {
                    delimiter
                }, System.StringSplitOptions.None);
            }
            System.Collections.Generic.List < string > templist = new System.Collections.Generic.List < string > ();
            for (int i = 0; i < tempr.Length; i++) {
                for (int j = 0; j < tempr[i].Length; j++) {
                    templist.Add(tempr[i][j]);
                }
            }

            return templist.ToArray();
        }

Side notes:

SplitRows() is the only main function allowed to receive either a string array or string. Even though I use 2 functions, I cannot create 2 for the 2 variable types.
<newline> is a replacement string for \n in my language and can be ignored.


texts: JavaScript function for logging the members of an object (with horizontal alignment)

texts:
When iterating over the members of an object for logging the keys / values one gets a "stair case" effect.
Therefore I wrote myself this function which takes care for a left-alignment of the values.

Any hints concerning flaws and improvement-recommendations welcome.

// #### START TEST #######################
var person = {
  yourMobilPhoneNumber : 01234171819,
  firstName : 'theFirstName',
  lastName : 'theLastName',
  mail : 'myEmail@abc.com',
  zip : '12345',
  street : 'theNameOfMyStreet',
  city : 'someCitySomewhere',
  yourVeryPersonalWebpage : 'http://that-is-me.com',
  id : 12345,
  calculate: function() { return 3 + 4; }
};

displayMembers(person);
// #### END TEST #######################

// Displays the members of an assigned
//   object on the console.

// -- Parameter -------------
// Object - An object which members
//   shall be displayed.

function displayMembers(obj) {
  var i;
  var max = (function() {
    var ret = 0;
    var keys = Object.keys(obj);

    for (i = 0; i < keys.length; i++) {
      if (keys[i].length > ret)
        ret = keys[i].length;
    }

    return ret;
  })();

  var getSpacer = function(len, state) {

    if (state.length < len) {
      return getSpacer(len, state += ' ');
    } else {
      return state;
    }
  }

  for (i in obj) {
    console.log('%s: %s%s',
                i,
                getSpacer(max - i.length, ''),
                obj[i]);
  }
}


texts: fixed size memory allocator interface without fragmentation on freeing the memory

texts:
I was trying to write a memory pool interface which:

Grants memory of fixed size chunks in linked list style fashion.

On returning the memory there is no risk of memory fragmentation.
//mem_struct.h
#ifndef MEM_STRUCT_H
#define MEM_STRUCT_H

struct mem_struct
{
   char arr[4];
   struct mem_struct *next;
};

#endif

Now using above structure the interface will grant memory to the user (the function which demands memory):
//mem_allocator.c
#include<stdlib.h>
#include<string.h>
#include"mem_struct.h"
#define total 10     //max no. of fixed size memory blocks initialized at once in a pool

unsigned int total_pool_size=0;   //total bytes of memory in pool available
struct mem_struct *head=NULL;     //first node of memory pool

/* function to initialize memory pool of max total no. of memory blocks or less if memory not
   available and add newly allocated blocks to existing memory pool blocks */
int mem_pool_init()
{
   struct mem_struct *temp;
   unsigned short count = 0; //no. of memory blocks/chunks successfully allocated and added to existing memory pool

   while(count < total)
   {
      temp = calloc(1,sizeof(*temp));
      if(temp)
      {
         temp->next = head;
         head = temp;
         total_pool_size += sizeof(temp->arr);
         count++;
      }
      else
         return 1;
   }
   return 0;
}

//function which grants memory in bytes to the user request
void* mem_grant(unsigned int siz)
{
    struct mem_struct *temp_head = NULL;  //pointer to first block of memory to be returned to the requesting function
    if(siz > 0)
    {
       //This loop will go on till there is sufficient memory in the memory pool to allocate memory of size - siz or the CPU is left with no memory
       while(total_pool_size < siz)
           if(mem_pool_init())
              return NULL;

       struct mem_struct *temp = head;
       unsigned int total_nodes = 0;   //total no of nodes of memory to be returned to the requesting function

       if(total_pool_size >= siz)
       {
          temp_head = head;

          if(siz%sizeof(temp_head->arr) > 0) //to determine no. of memory blocks to be returned to the user request
             total_nodes = siz/sizeof(temp_head->arr) + 1;
          else
             total_nodes = siz/sizeof(temp_head->arr);

          while(total_nodes)
          {
              temp = temp->next;
              --total_nodes;
              total_pool_size = total_pool_size - sizeof(temp->arr);
          }
          head = temp->next;
          temp->next = NULL;
       }
   }
   return (void *)temp_head;
}

//function to add the memory earlier allocated back to the memory block
void free_mem(void *temp_head) //temp_head points to the first byte of the memory allocated to the user using mem_grant
{
    if(temp_head)
    {
        struct mem_struct *temp = *temp_head;

        while(temp)
        {
           memset(temp,0,sizeof(temp->arr));

           if(!temp->next)
           {
               temp->next = head;
               break;
           }
           total_pool_size += sizeof(temp->arr);
        }
        head = temp_head;
    }
}

Here is the main function:
//main.c
#include<stdio.h>

extern void* mem_grant(unsigned int);
extern void  free_mem(void*);
extern unsigned int total_pool_size;

int main()
{
    void* ptr = mem_grant(42);
    if(ptr)
        printf("total_pool_size after grant %u\n", total_pool_size);
    free_mem(ptr);
    printf("total_pool_size after free %u\n", total_pool_size);
    return 0;
}

I am new to this part of programming and I want to know how can I improve as I don't have any reference material to lookup. Could someone please review this and tell me how this design is?


texts:
I am wondering if I can make these classes a bit more efficient.

Test Results

Single Run

Method 1: 5 Columns - Text Query - 81178 Records = 00:00:00.6390366
secs
Method 2: 5 Columns - Text Query - 81178 Records = 00:00:00.5360307
secs

10 Run Loop

Method 1: 5 Columns - Text Query - 81178 Records = 00:00:05.3253045
secs
Method 2: 5 Columns - Text Query - 81178 Records = 00:00:05.0912912
secs

100 Run Loop

Method 1: 5 Columns - Text Query - 81178 Records = 00:00:54.1270959
secs
Method 2: 5 Columns - Text Query - 81178 Records = 00:00:53.8710813
secs

All 3 attempts for both methods never peak over 25% CPU usage.

As you can see there really is no significant improvement over either method, and method 2 (judging by CPU usage) does not seem to multi-thread.

I am thinking that if I can get rid of my usage of reflection to map the columns to strongly-typed classes that it would make a significant boost to both methods performance, and I am sure that I can make improvements to the asyncronicity of method 2 as well... I just don't know how.

WrapperTest.cs

    private static IList<T> Map<T>(DbDataReader dr) where T : new()
    {
        try
        {
            // initialize our returnable list
            List<T> list = new List<T>();
            // fire up the lamda mapping
            var converter = new Converter<T>();
            // read in each row, and properly map it to our T object
            var obj = converter.CreateItemFromRow(dr);

            // reutrn it
            return list;
        }
        catch (Exception ex)
        {
            // Catch an exception if any, an write it out to our logging mechanism, in addition to adding it our returnable message property
            _Msg += "Wrapper.Map Exception: " + ex.Message;
            ErrorReporting.WriteEm.WriteItem(ex, "o7th.Class.Library.Data.Wrapper.Map", _Msg);
            // make sure this method returns a default List
            return default(List<T>);
        }
    }

This is a continuation of this question.

The code above definitely runs more efficiently now.  Is there any way to make it better?


texts: Finding the maximum pairwise difference in a collection of colors

texts:
Note that this problem is equivalent to finding the longest line segment defined by any two points in a collection of 3D coordinates, which may be an easier way to visualize the problem, and is almost certainly a version that has received more research.

Essentially, given a List<Color> and this method...

public static int ColorDiff(Color a, Color b)
{
    int rDiff = a.R - b.R;
    int gDiff = a.G - b.G;
    int bDiff = a.B - b.B;
    return (int)Math.Sqrt(rDiff * rDiff + gDiff * gDiff + bDiff * bDiff);
}

... I'd like to get the highest ColorDiff value for any pair of points in the list.

Informed Sequential Approach

int max = 0;
for (int i = 0; i < colors.Count - 1; i++)
{
    for (int j = i + 1; j < colors.Count; j++)
    {
        int temp = ColorDiff(colors[i], colors[j]);
        if (temp > max)
            max = temp;
    }
}

Naive LINQ Parallel Approach

int max = colors.AsParallel().Max(a => colors.Max(b => ColorDiff(a, b)));

Informed Parallel Approach

int max = 0;
Object locker = new Object();
System.Threading.Tasks.Parallel.For(0, colors.Count - 1, () => 0,
    (i, unused, localMax) =>
    {
        int temp = 0;
        for (int j = i + 1; j < colors.Count; j++)
            temp = Math.Max(temp, ColorDiff(colors[i], colors[j]));
        return Math.Max(localMax, temp);
    }, localMax =>
    {
        lock (locker)
        {
            if (localMax > max)
                max = localMax;
        }
    });

My testing indicates the naive LINQ approach takes about 60-70% of the time the sequential approach takes. However, I'm pretty sure it's naively doing the comparisons twice (ColorDiff(colors[i], colors[j]) and ColorDiff(colors[j], colors[i])), and that the speedup is entirely due to the parallelization across 4 cores. The performance of the informed parallel approach supports that; it takes approximately 30-40% of the time the LINQ approach takes, making it about 5 times faster than the informed sequential approach.

The LINQ approach is taking approximately 1 minute on my trial datasets (about 60 thousand elements in the list), and a little over 15 minutes on a larger dataset (230 thousand elements). I don't even want to know how long it will take on a full size dataset (about 1.1 million elements in the list).

Can I improve the brute force approach any further? Or better yet, is there an algorithm I can easily implement in C# that's better than O(n2)? A good approximation of the max value (within 5% of the true max) would probably be acceptable.

Extra information:

Because these are colors rather than points, their R, G, and B values are guaranteed to be in the range 0 to 255. I don't know if knowing the area the points will be inside helps, though; the way the colors are generated results in them often being clustered in a small sub-space of the total range.
Because of the way the colors are generated, every color will have N exact duplicates in the list (N >= 0, usually < 4). The value of N will be known at this point, but the ordering of the list must be preserved and is not guaranteed to keep duplicates near each other. A shallow copy of the list can be made and ordered if that helps (and is worth the extra CPU time & memory).


texts: Combining immutable lists of strings with each other

texts:
The Problem

Create a javascript method which combines each string of two immutable lists with each other:

const a1 = new List(['a', 'b', 'c']);
const a2 = new List(['x', 'y', 'z']);

const combinedArray = combineArrays(a1,a2);
=> combinedArray: ['a-x', 'a-y', 'a-z', 'b-x', 'b-y', 'b-z', 'c-x', 'c-y', 'c-z']

My Solution

import { List } from 'immutable';

const combineArray = (arrayA = new List([]), arrayB = new List([])) => {
  if (arrayA.count() === 0) {
  return arrayB;
}

if (arrayB.count() === 0) {
  return arrayA;
}

let combinations = new List([]);

combinations = arrayA.reduce((accum, value) => {
  if (value) {
    return accum.push(arrayB.reduce((accum2, value2) => {
      if (value2) {
        return accum2.push(`${value}-${value2}`);
      }
      return value;
    }, new List([])));
  }

  return accum;
}, new List([]));

  return combinations.flatten(true);
};

export default combineArray;

Updated Solution

based on @bergis response I updated the implementation

import { List } from 'immutable';

const combineArray = (arrayA = new List([]), arrayB = new List([])) => {
  if (arrayA.isEmpty()) { return arrayB; }
  if (arrayB.isEmpty()) { return arrayA; }

  return arrayA.flatMap(valueA => (
    arrayB.map(valueB => (
      `${valueA}-${valueB}`
    ))
  ));
};

export default combineArray;

My Question

Would you have concerns regarding performance? (We are talking about a maximum of 10 items per list)
How would you improve the implementation?


texts: Scraping data from json response using twofold request

texts:
I've written a script which is able to get javascript encrypted links from a webpage and then using those newly produced links by making another request It can reach the target page and going there it is capable of scraping necessary data from json response. It's working like magic. I tried to make the whole thing flawlessly. Here is what I did:

Sub Json_Twofold()
Const link = "https://www.aopa.org/learntofly/school/wsSearch.cfm?method=schoolDetail&businessId="
Dim http As New XMLHTTP60, str As Variant, exstr As Variant

With http
    .Open "GET", "https://www.aopa.org/learntofly/school/wsSearch.cfm?method=findSchools&searchTerm=All&radius=25", False
    .send
    str = Split(.responseText, "city"":""")
End With

y = UBound(str)
For i = 1 To y
    req = link & Split(Split(str(i), "businessId"":")(1), ",")(0)

    With http
        .Open "GET", req, False
        .send
        exstr = Split(.responseText, "mgrLast"":""")
    End With

    Z = UBound(exstr)
    For L = 1 To Z
        x = x + 1
        Cells(x, 1) = Split(Split(exstr(L), "city"":""")(1), """")(0)
        Cells(x, 2) = Split(Split(exstr(L), "businessName"":""")(1), """")(0)
        Cells(x, 3) = Split(Split(exstr(L), "email"":""")(1), """")(0)
        Cells(x, 4) = Split(Split(exstr(L), "web"":""")(1), """")(0)
        Cells(x, 5) = Split(Split(exstr(L), "phone"":")(1), ",")(0)
    Next L
Next i
End Sub


texts:
I am a C#/.Net developer and have decided it is time to branch out and really learn Python. I started with a simple implementation of a Mastermind-esque game. Any comments about the code would be greatly appreciated. I already know the gameplay isn't perfect, but it was just a quick attempt. I also am aware that there isn't much user input checking, but again, quick attempt.

import random

class Game(object):
    def run(self):
        guesses = []
        game_states = []
        length = int(input("Choose length of code to break: "))
        code = [random.randint(0, 9) for i in range(length)]

        def take_guess():
            correct_guess_length = False
            while not correct_guess_length:
                guess = input("Guess a number of length {0}: ".format(length))
                if len(guess) != length:
                    print("Guesses must be a number of length {0}.".format(length))
                else:
                    correct_guess_length = True
            return guess

        def check_guess(guess):
            return all([x == y for x, y in zip(guess, code)])

        def evaluate_guess(guess):
            new_state = []
            for pos, number in enumerate(guess):
                if code[pos] == number:
                    new_state.append(str(number))
                elif number in code:
                    new_state.append("O")
                else:
                    new_state.append("X")
            game_states.append(''.join([c for c in new_state]))

        def print_game_state():
            print()
            for guess, state in zip(guesses, game_states):
                print("{0}\t{1}".format(guess, state))

        correct = False
        while not correct:
            guess = take_guess()
            guesses.append(guess)
            guess_as_ints = [int(c) for c in guess]
            if not check_guess(guess_as_ints):
                evaluate_guess(guess_as_ints)
                print_game_state()
            else:
                print("You guessed the code was {0}! Congratulations!".format(''.join([str(i) for i in code])))
                correct = True

if __name__ == '__main__':
    game = Game()
    game.run()


texts:
Let's say I have this array.
items = [
  {
    amount: 100,
    add: true
  },
  {
    amount: 50,
    add: false
  },
  {
    amount: 100,
    add: true
  }
]

What I want to do is add the amount if add is true and subtract it if add is false.
This code uses an extra total variable.
total = 0
items.each do |item|
  if item[:add]
    total += item[:amount]
  else
    total -= item[:amount]
  end
end

A one-liner code.
items.sum { |item| item[:add] ? item[:amount] : -item[:amount] }

I wonder if there is a better implementation for this problem. Is the one-liner readable enough?


texts:
Here is my code for quick select in Python 2.7. I am trying to optimize code for fewer comparisons. And my specific question is marked in code, 3 lines marked with more safe way. Wondering if my code is safe enough to handle all corner cases (in more details, I think more safe way definitely can handle all corner cases, and wondering if my current code which has less comparison is also good to handle all corner cases)? I have tested (see main function) and also tested using median as an example.

Any performance improvement in terms of algorithm time complexity, code bugs or code style are appreciated.

Source code in Python 2.7,

import random
def quick_select(numbers, start, end, k):
    if start == end:
        if k == 0:
            return numbers[start]
        else:
            raise Exception('invalid input!')
    pivot = numbers[end]
    i = start
    j = end - 1
    while i < j: # more safe way: i<=j
        while i < j and numbers[i] <= pivot: # more safe way: while i <= j and numbers[i] <= pivot:
            i += 1
        while numbers[j] > pivot: # more safe way: while i<= j and numbers[j] > pivot
            j -= 1
        if i < j:
            numbers[i], numbers[j] = numbers[j], numbers[i]
    numbers[i], numbers[end] = numbers[end], numbers[i]
    if i - start== k:
        return numbers[i]
    elif i - start > k:
        return quick_select(numbers, start, i-1, k)
    else:
        return quick_select(numbers, i+1, end, k-i+start-1)

def median(numbers):
    if len(numbers) % 2 == 1:
        quick_select(numbers, 0, len(numbers)-1, len(numbers) / 2)
    else:
        x = quick_select(numbers, 0, len(numbers)-1, len(numbers)/2 - 1)
        y = quick_select(numbers, 0, len(numbers) - 1, len(numbers) / 2)
        return (x+y)/2.0

if __name__ == "__main__":
    numbers = []
    for i in range(10):
        numbers.append(random.randint(0,10))
    k = random.randint(0, 9)
    numbers = [7, 5, 2, 3, 7, 2, 8, 7, 4, 9]
    k = 2
    print 'original ', numbers
    print 'k ', k
    print quick_select(numbers, 0, len(numbers)-1, k)
    print 'median', median(numbers)
    print 'sorted ', sorted(numbers)


texts:
I was working on a program that simulates the Buffon's Needle experiment. If anyone is not familiar with it, a Wiki link is provided -  Buffons's Needle

The point of Buffon's experiment is to find the value of pi, or at least approximate it. Usually you draw a couple of lines and then you scatter pins around the board in which you drew the lines in, the more pins the better. Then you take the number of pins crossing the lines and divide that by the number of pins you first had and multiply that by 4.

Below, I have provided the code for my program which is written in Java. Right now, it seems as if there are too many variables/methods. Could someone help refine it so it functions and looks better?

import java.util.Random;
import java.util.Scanner;
public class buffonNeedle {
    public static void main(String[] args) {
        Scanner in = new Scanner (System.in);
        System.out.println("How many darts do you want in each trial?");
        int darts = in.nextInt();
        System.out.println("How many trials do you want conducted?");
        int trials = in.nextInt();
        for(int i = 0; i<trials; i++) {
            xVal(darts);
            yVal(darts);
            hits(darts);
            System.out.println(piCalc(darts));
        }
    }
    public static double [] xVal (int darts){
        double [] xVal = new double[darts];
        Random random = new Random();
        for (int i = 0; i<darts; i++){
            xVal[i] = -1+random.nextDouble()*2;
        }
        return xVal;
    }
    public static double [] yVal (int darts){
        double [] yVal = new double[darts];
        Random random = new Random();
        for (int i = 0; i<darts; i++){
            yVal[i] = -1+random.nextDouble()*2;
        }
        return yVal;
    }
    public static int hits (int darts){
        int hits = 0;
        double [] xVal = xVal(darts);
        double [] yVal = yVal(darts);
        for(int i = 0; i<darts; i++){
            if((Math.pow(xVal[i],2)+Math.pow(yVal[i],2))<=1){
                hits++;
            }
        }
        return hits;
    }
    public static double piCalc(int darts){
        double hits = hits(darts);
        double pi = (hits/darts)* 4;
        return pi;
    }
}


texts:
I am new to Java and had some difficulty creating this simple Publisher Subscriber class. It finally seems to be working and I wanted to check if I have been following best practices and see if there are any improvements I can make.

The following Java class accepts any topics as a string (e.g. "rand_int") and forwards any messages to that topic to any subscribers.

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;

public class PubSub {
  private Map<String, ArrayList<Consumer<?>>> topicsSubscribers =
      new HashMap<String, ArrayList<Consumer<?>>>();
  private static PubSub pubSubSingleton = null;

  public static PubSub getInstance() {
    if (pubSubSingleton == null)
      pubSubSingleton = new PubSub();

    return pubSubSingleton;
  }

  public <T> void publish(String topic, T message) {
    ArrayList<Consumer<?>> subscribers = this.topicsSubscribers.get(topic);
    if (subscribers == null)
      return;

    for (Consumer subscriberConsumer : subscribers) {
      subscriberConsumer.accept(message);
    }
  }

  public synchronized <T> void subscribe(String topicName, Consumer<T> subscriberCallback) {
    ArrayList<Consumer<?>> subscribers = this.topicsSubscribers.get(topicName);
    if (subscribers == null) {
      subscribers = new ArrayList<Consumer<?>>();
      subscribers.add(subscriberCallback);
      this.topicsSubscribers.put(topicName, subscribers);
    } else {
      subscribers.add(subscriberCallback);
    }
  }
}

Example usage:

public class SomeClass {
  public SomeClass() {
    PubSub.getInstance().subscribe("rand_int", this::randIntCallback);
    PubSub.getInstance().publish("rand_int", 46);
  }

  public randIntCallback(int number) {
    System.out.println(number);
  }
}

The above code should output "46".

As I said, I am very new to Java and would like some feedback on my code to help improve. So any help on this is very appreciated.


texts:
As the title says, simple quicksort to help myself get used to C++ templates and iterators.  Main concern is whether there's a better way to template so that you can have a simple function (e.g. quicksort) that accepts any container type (specifically should I have some kind of assert or more complicated template to make sure the arguments are in fact iterators?)  Also note that it is inclusive of the end value, so to sort a whole container the call is qsort(c.begin(), c.end()-1).

template <typename Iter> Iter partition(Iter start, Iter end){
    Iter pivot = start;
    Iter cur = start;
    while (cur < end) {
        if(*cur <= *end){
            std::swap(*cur,*pivot);
            pivot++;
        }
        cur++;
    }
    std::swap(*pivot, *end);
    return pivot;
}

template <typename Iter> void qsort(Iter start, Iter end){
    if(end > start) {
        Iter p = partition(start, end);
        qsort(start, p - 1);
        qsort(p + 1, end);
    }
}


texts:
I'm working my way through The Java Programming Language, Fourth Edition - The Java Series.  This is Exercise 13.3:

  As shown, the delimitedString method assumes only one such string per input string. Write a version that will pull out the delimited strings and retun an array.

The provided delimitedString method:

public static String delimitedString(String from, char start, char end) {
    int startPos = from.indexOf(start);
    int endPos = from.lastIndexOf(end);

    if (startPos == -1)
        return null;
    else if (endPos == -1)
        return null;
    else if (startPos > endPos)
        return null;
    else
        return from.substring(startPos, endPos + 1);
}

My solution. Note that regular expressions are covered in the next section of the book, so I chose not to use a split for this particular exercise:

public static String[] delimitedStrings(String from, char startDelim, char endDelim) {
    int index;
    int startPos = 0;
    ArrayList<String> list = new ArrayList<String>();

    while ((index = from.indexOf(startDelim, startPos)) != -1) {
        int endPos;
        if ((endPos = from.indexOf(endDelim, index)) != -1) {
            list.add(from.substring(index, endPos + 1));
            startPos = endPos;
        } else {
            break;
        }
    }
    return list.toArray(new String[list.size()]);
}

Supporting tests:

@Test
public void testDelimitedStringsSimple() throws Exception {
    String[] strArray = {"<Bonjour!>"};
    assertEquals(strArray, StringUtil.delimitedStrings("I say <Bonjour!>", '<', '>'));
}

@Test
public void testDelimitedStringsComplex() throws Exception {
    String[] strArray = {"<Bonjour!>","<Bonjour!>","<B<onjour!>", "<Bonjour!>"};
    assertEquals(strArray, StringUtil.delimitedStrings("I say <Bonjour!> I say <Bonjour!> and a tricky <B<onjour!> and ><Bonjour!>", '<', '>'));
}

@Test
public void testDelimitedStringsNoStart() throws Exception {
    String[] strArray = {};
    assertEquals(strArray, StringUtil.delimitedStrings("Bonjour!>", '<', '>'));
}

@Test
public void testDelimitedStringsNoEnd() throws Exception {
    String[] strArray = {};
    assertEquals(strArray, StringUtil.delimitedStrings("<Bonjour!", '<', '>'));
}

@Test
public void testDelimitedStringsReversed() throws Exception {
    String[] strArray = {};
    assertEquals(strArray, StringUtil.delimitedStrings(">Bonjour!<", '<', '>'));
}

@Test
public void testDelimitedStringsEmpty() throws Exception {
    String[] strArray = {};
    assertEquals(strArray, StringUtil.delimitedStrings("", '<', '>'));
}


texts: Giveth me thy easier user input in C++ - follow up

texts:
I've decided to take some of the many suggestions for improvement on my previous question, Easier user input in C++, and actually get it to work as expected. This time around, a few things are different, namely:

The function will now accept string input with spaces, like "Ethan Bierlein", and not just spit back the first "word" in the input.
The function now also accepts a different input stream rather than just std::cin, if, for some reason you do something like that.
The function now allows for a "no-prompt" option, as well, which just means that the argument prompt has a default value of "".
There is an optional way to specify the type of the prompt as well now. It's default type is std::string.
The function, now named get_input, has it's own namespace, easy_input, rather than being patched into std.

I do have a few concerns about my code though, and I'd like to hear your opinions on them:

Is it a good idea to declare a static variable, just so I can have a default value for prompt? Is it a good idea to have a default value for prompt?
How necessary is it to provide an option to get input from a different input stream?
Am I writing good C++, or am I doing certain things horribly wrong?
Is there anything else that stands out for improvment?

easy_input.h

#if HAVE_PRAGMA_ONCE
#pragma once
#endif

#ifndef EASY_INPUT_H_
#define EASY_INPUT_H_

#include <iostream>
#include <string>
#include <boost/lexical_cast.hpp>

namespace easy_input
{
    const std::string input_error_message = "an I/O error was encountered.";
    static std::string default_prompt = "";

    template <typename TInput, typename TPrompt = std::string>
    TInput get_input(
        const TPrompt& prompt = default_prompt,
        std::istream& input_stream = std::cin
    );
}

/**
 * This function serves as a useful wrapper for getting user input.
 * Rather than forcing the user to type out multiple lines every
 * time they want to get input, they only have to type one line.
 * @tparam          TInput  - The type of the input to obtain.
 * @tparam          TPrompt - The type of the prompt to be used. The default type is std::string.
 * @param {TPrompt} prompt  - The prompt to be used.
 */
template <typename TInput, typename TPrompt = std::string>
TInput easy_input::get_input(
    const TPrompt& prompt = easy_input::default_prompt,
    std::istream& input_stream = std::cin)
{
    std::cout << prompt;
    std::string user_input_value { };

    if(!std::getline(input_stream, user_input_value)) {
        throw std::istream::failure { easy_input::input_error_message };
    }
    return boost::lexical_cast<TInput>(user_input_value);
}

#endif

main.cpp (tests)

#include <iostream>
#include "easy_input.h"

int main()
{
    std::string a = easy_input::get_input<std::string>("Enter your name please! ");
    std::cout << a << "\n";

    int b = easy_input::get_input<int>("Enter an integer please! ");
    int c = easy_input::get_input<int>("Enter an integer please! ");
    std::cout << b + c << "\n";

    std::string d = easy_input::get_input<std::string>();
    std::cout << d << "\n";

    int e = easy_input::get_input<int>();
    int f = easy_input::get_input<int>();
    std::cout << e + f << "\n";
}


texts: Fetching objects and adding a calculated field in Doctrine 2

texts:
I'm making a section that shows a list of blogs and how many comments it has without loading any comment data. My Blog entity is as follows:

/**
 * @ORM\Entity
 * @ORM\Table(name="blogs")
 */
class Blog
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

   // This field is aggregated. Not in DB table
    protected $totalComments = 0;

    /**
     * @ORM\Column(type="string")
     */
    protected $title;

     /**
     * @ORM\OneToMany(targetEntity="Comment", mappedBy="blog")
     */
    protected $comments;

    // More attributes

    public function __construct(){
        $this->comments = new ArrayCollection();
    }

    // Setters and Getters
}

and my Comment Entity:

class Comment
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\ManyToOne(targetEntity="Blog", inversedBy="comments")
     * @ORM\JoinColumn(name="blog_id", referencedColumnName="id")
     */
    protected $blog;

   // more attributes

    public function __construct(){     }

    // Setter and Getters
}

They have a oneToMany relationship. 1 Blog has N comments.

My next step is convert this query to the Doctrine2 World:

'SELECT b.*, COUNT( b.id ) AS totalComments FROM  `blogs` b LEFT JOIN comments c ON b.id = c.blog_id GROUP BY b.id'

That was an easy task:

function getLatestBlogs(){
        $qb = $this->createQueryBuilder('b')
        ->select('b, c')
        ->addSelect('count(b.id) as totalComments')
        ->leftJoin('b.comments', 'c')
        ->groupBy('b.id');

        $result = $qb->getQuery()->getResult();

        foreach($qResult as $row){ //tweaking original result
            $row[0]->setTotalComments($row['totalComments']);
            $list[] = $row[0];
        }
        return $list;
    }

In the foreach loop is where I fix my fetched result because doctrine's getResult was returning an array of arrays like this:

// var_dump($result)
array (size=8)
  0 =>
    array(2) =>
      0 =>
          object Blog
          'id' => int 330
          'title' => string 'title blog'
          // ... more attributes

      "totalComments" => int 5

  1 => ...
  );

Is there any fashion way that I'm missing ? I've really dig in to depth and couldn't find anything that fix this situation.


texts: Program to solve variations of the seven thieves & diamonds riddle

texts:
I answered a question yesterday on SO based on this riddle, but the code was so hard to read/follow to actually understand what was going on it was easier to write my own code to test the scenario and debug the program.

I wrote it pretty fast, but I want to make sure the program I wrote is easy to follow and adheres to basic C practices to avoid someone else have the same problem reading and following my code as I did in the original question. The program itself was a variation of the following riddle:

  There are seven thieves who steal diamonds from a diamond merchant and run away in the jungle. While running, night sets in and they decide to rest in the jungle. When everybody is sleeping, two of the best friends get up and decide to distribute the diamonds among themselves and run away. So they start distributing but find that one diamond was extra. So they decide to wake up 3rd one and divide the diamonds again...only to their surprise they still find one diamond extra. So they decide to wake up the fourth one. Again one diamond is spare. 5th woken up...still one extra. 6th still one extra. Now they wake up 7th and diamonds are distributed equally.

The solution is as follows:

  Lets say there are x diamonds, now these diamonds are exactly
  divisible by 7 and:

  x = 1 + N1*2;

  x = 1 + N2*3;

  x = 1 + N3*4;

  x = 1 + N4*5;

  x = 1 + N5*6;
  x = N6*7;

  Where N1, N2, N3, N4 and N5 are
  integers. From above we can also say:
  N1*2 = N2*3 = N3*4= N4*5 = N5*6 =y

  Now y should be divisible by 2, 3, 4, 5 and 6, its nothing but
  common multiple of all.

  LCM of 2, 3, 2*2, 5, 2*3 => 2*3*2*5 => 60

  At the same time common multiple + 1 should be divisible by 7 as well.

  60 + 1 is not divisible by 7 120(60*2) + 1 is not divisible by 7
  180(60*3) + 1 is not divisible by 7 240(60*4) + 1 is not divisible by
  7 300(60*5) + 1 is divisible by 7

  Thus they must have stolen minimum 301 diamonds.

The generalization is the program takes any number of thieves and returns a number of diamonds the thieves stole if it is a valid input (prime number).

#include<stdio.h>

int isPrime(int tmp)
{
    int i;
    for(i = 2; i <= tmp/2; i++)
    {
        if(tmp % i == 0)
            return 0;
    }
    return 1;
}

long gcd(long a, long b) {
  if (b == 0) {
    return a;
  }
  else {
    return gcd(b, a % b);
  }
}

int main()
{
    int thieves, i;
    long diamonds, lcm = 1;
    printf("Enter the number of thieves that is prime and greater than 1:\n");
    scanf("%d",&thieves);

    if(isPrime(thieves) && thieves > 1)
    {
        for(i = 2;i < thieves;i++)
        {
                lcm = (lcm*i)/gcd(i,lcm);
        }

        i = 1;
        diamonds = lcm*i + 1;
        while(diamonds % thieves != 0)
        {
            diamonds = lcm*++i + 1;
        }
        printf("The minimum number of diamonds is: %d\n",diamonds);
    }
    else
    {
        printf("Input invalid.\n");

    }
}


texts: Usage of Interlocked.CompareExchange for deciding whether a property has been changed by another thread

texts:
I'm developing a Windows Service that receives data from somewhere and saves it to DB one time per 5 minutes. The Service is multithreaded and I actually got problems when several threads saved data at same minute (no thread sync was implemented).

Now I've implemented it and am looking for code-review and optimizations.

class DataProccessor
{
    private int _lastMinutesUpdate;
    private readonly Timer _saveTimer = new Timer(TimerTick, null, _settingsProvider.SaveInterval, Timeout.Infinite);

    private void TimerTick(object state)
    {
        var watch = new Stopwatch();
        watch.Start();
        var initialLastMinutesUpdate = _lastMinutesUpdate;
        var currentDate = DateTime.UtcNow;
        var currentDateMinutes = currentDate.Minute;
        var fiveMinUpdate = currentDateMinutes % 5 == 0 &&
                            currentDateMinutes != initialLastMinutesUpdate &&
                            initialLastMinutesUpdate == Interlocked.CompareExchange(ref _lastMinutesUpdate, currentDateMinutes, initialLastMinutesUpdate);
        if(fiveMinUpdate)
        {
            // Insert values to DataBase
        }
        // TimerTick will be called in interval from settings minus time spent to TimerTick execution.
        _saveTimer.Change(Math.Max(0, _settingsProvider.SaveInterval- watch.ElapsedMilliseconds), Timeout.Infinite);
    }
}


texts: Haskell: Implementing the data type LExpR as an instance of show

texts:
I am trying to implement the data type LExpr as an instance of show.
data LExpr = Var String
                | App LExpr LExpr
                | Lam String LExpr

This is my code:
 instance Show LExpr where
      showsPrec d (Var str)   = showString' str
      showsPrec d (App e1 e2) = showParen (d>=6) $ showsPrec 6 e1  . showString " " . showsPrec 5  e2
      showsPrec d (Lam str e) = showParen (d>=5) $ showString ("\\"++str++" -> ") . showsPrec 5 e

I am looking for some advice on how to further improve my code.


texts: Delegate that selects a writable property on a generic

texts:
In the following contrived example, I have a collection of PropertyManagers that each contains selector and assigner delegates to read from and write to a property on the generic type. It feels clunky for lots of reasons, not least of which is that both delegates are basically there to serve the same purpose: To identify the property on the generic that I want to read from then write back into.

using System;
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;

namespace Tests
{
    [TestFixture]
    public class ReadWritePropertySelectorTests
    {
        public void Round<T>(IEnumerable<T> collection,
            params PropertyManager<T>[] propertyManagers)
        {
            foreach (var item in collection)
            {
                foreach (var propertyManager in propertyManagers)
                {
                    var valueToRound = propertyManager.Selector(item);
                    propertyManager.Assigner(item, Math.Round(valueToRound, 1));
                }
            }
        }
        public class PropertyManager<T>
        {
            public Func<T, decimal> Selector { get; set; }
            public Action<T, decimal> Assigner { get; set; }
        }
        public class Combatant
        {
            public decimal Attack { get; set; }
            public decimal Defense { get; set; }
            public decimal Health { get; set; }
        }
        [Test]
        public void Test()
        {
            // Arrange
            var combatants = new[]
            {
                new Combatant { Attack = 33.12M, Defense = 12.771M, Health = 60.1181M }
            };

            // Act
            Round(combatants,
                new PropertyManager<Combatant>
                {
                    Selector = c => c.Attack, Assigner = (c, v) => c.Attack = v
                },
                new PropertyManager<Combatant>
                {
                    Selector = c => c.Defense, Assigner = (c, v) => c.Defense = v
                },
                new PropertyManager<Combatant>
                {
                    Selector = c => c.Health, Assigner = (c, v) => c.Health = v
                });

            // Assert
            var array = combatants.ToArray();
            Assert.AreEqual(33.1M, array[0].Attack);
            Assert.AreEqual(12.8M, array[0].Defense);
            Assert.AreEqual(60.1M, array[0].Health);
        }
    }
}

Is there any way to redo this to make the call to Round() more concise, preferably removing the need for a strongly typed PropertyManager? I think ultimately calling it as follows would be awesome, but I can't figure out the language constructs to use to get there:

Round(combatants, c => c.Attack, c => c.Defense, c => c.Health);


texts: Find length of non-repeated numbers in array

texts:
How can I optimize this code which can get the length of non-repeated numbers in an array?
package com.sujay.practice;

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

/**
 * Find the length of non-repeated numbers in an array
 * @author Sujay
 * 08-May-2018
 */
public class DuplicateValuesInArray {

    public static void main(String[] args) {
        int[] array = { 1, 2, 2, 3, 4, 5, 6, 2, 4, 5, 3 };
        usingMap(array);
        usingString(array);
    }

    private static void usingString(int[] array) {
        String str = "";
        for (int i = 0; i < array.length; i++) {
            String temp = String.valueOf(array[i]);
            if (!str.contains(temp)) {
                str = str + temp;
            }
        }
        System.out.println(str.length());
    }

    private static void usingMap(int[] array) {
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        for (int i = 0; i < array.length; i++) {
            map.putIfAbsent(array[i], i);
        }
        System.out.println(map.size());
    }
}


texts:
I've implemented a polling function with a timer in C, that every 10s checks a given condition (I've just replaced it for a log to stdout for testing purposes only) but I would like to know your opinion on this code, namely if there is a simpler way to achieve the same result, what issues may arise concerning performance, thread-safety, memory footprint. I'm interested in writing the most simple, correct and fast code for this. Suggestions are, as always, welcome.

/* includes removed for clarity */

void signalAlarmHandler(int signum) {
  switch(signum) {
  case SIGINT:
    fprintf(stdout, "received interrupt. going to exit.\n");
    exit(0);
    break;
  case SIGALRM:
    fprintf(stdout, "received signal alarm.\n");
    /* checking for condition here */
    break;
  default:
    break;
  }
}

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

  if(initializeEnvironment(argc, argv) == -1) {
    return -1;
  }
  else {

    signal(SIGINT, signalAlarmHandler); /* for testing purposes */
    signal(SIGALRM, signalAlarmHandler);

    fprintf(stdout, "starting the signal alarm stuff\n");
    while(1) {
      alarm(10);
      sleep(20);
    }
  }
}


texts: Given an array, find all its elements that can become a leader

texts:
I was successful in solving a challenge in codility, but my solution failed performance tests. How can I improve my solution?

  Challenge:

  Integers K, M and a non-empty array A consisting of N integers, not
  bigger than M, are given.

  The leader of the array is a value that occurs in more than half of
  the elements of the array, and the segment of the array is a sequence
  of consecutive elements of the array.

  You can modify A by choosing exactly one segment of length K and
  increasing by 1 every element within that segment.

  The goal is to find all of the numbers that may become a leader after
  performing exactly one array modification as described above.

  Write a function:

def solution(K, M, A)

  that, given integers K and M and an array A consisting of N integers,
  returns an array of all numbers that can become a leader, after
  increasing by 1 every element of exactly one segment of A of length K.
  The returned array should be sorted in ascending order, and if there
  is no number that can become a leader, you should return an empty
  array. Moreover, if there are multiple ways of choosing a segment to
  turn some number into a leader, then this particular number should
  appear in an output array only once.

  For example, given integers K = 3, M = 5 and the following array A:

A[0] = 2
A[1] = 1
A[2] = 3
A[3] = 1
A[4] = 2
A[5] = 2
A[6] = 3

  the function should return [2, 3]. If we choose segment A[1], A[2],
  A[3] then we get the following array A:

A[0] = 2
A[1] = 2
A[2] = 4
A[3] = 2
A[4] = 2
A[5] = 2
A[6] = 3

  and 2 is the leader of this array. If we choose A[3], A[4], A[5] then
  A will appear as follows:

A[0] = 2
A[1] = 1
A[2] = 3
A[3] = 2
A[4] = 3
A[5] = 3
A[6] = 3

  and 3 will be the leader.

  And, for example, given integers K = 4, M = 2 and the following array:

A[0] = 1
A[1] = 2
A[2] = 2
A[3] = 1
A[4] = 2

  the function should return [2, 3], because choosing a segment A[0],
  A[1], A[2], A[3] and A[1], A[2], A[3], A[4] turns 2 and 3 into the
  leaders, respectively.

  Write an efficient algorithm for the following assumptions:

  N and M are integers within the range [1..100,000];
  K is an integer within the range [1..N];
  Each element of array A is an integer within the range [1..M].

My Solution

def modify(segment):
   return [e+1 for e in segment]

def dominant(A):
   d = dict()
   lenOfHalfA = int(len(A)/2)
   domList = []

   for i in A:
       if not i in d:
           d[i] = 1
       else:
           d[i] = d[i]+1

   for key, value in d.items():
       if value > lenOfHalfA:
           domList.append(key)

   return domList

def solution(K, M, A):
   # write your code in Python 3.6
   dominantList = []

   x = 0
   while x <= len(A) - K:
       modifiedA = A[:]
       modifiedA[x:K+x] = modify(A[x:K+x])
       dominantList += dominant(modifiedA)
       x += 1

   return list(set(dominantList))


texts: Using numpy polynomial module - is there a better way?

texts:
I'm working on a project where I need to solve for one of the roots of a quartic polymonial many, many times.  Is there a better, i.e., faster way to do this?  Should I write my own C-library?  The example code is below.

# this code calculates the pH of a solution as it is
# titrated with base and then plots it.

import numpy.polynomial.polynomial as poly
import numpy as np
import matplotlib.pyplot as plt

# my pH calculation function
# assume two distinct pKa's  solution is a quartic equation
def pH(base, Facid1, Facid2):
    ka1 = 2.479496e-6
    ka2 = 1.87438e-9
    kw = 1.019230e-14
    a = 1
    b = ka1+ka2+base
    c = base*(ka1+ka2)-(ka1*Facid1+ka2*Facid2)+ka1*ka2-kw
    d = ka1*ka2*(base-Facid1-Facid2)-kw*(ka1+ka2)
    e = -kw*ka1*ka2
    p = poly.Polynomial((e,d,c,b,a))
    return -np.log10(p.roots()[3]) #only need the 4th root here

# Define the concentration parameters
Facid1 = 0.002
Facid2 = 0.001
Fbase = 0.005    #the maximum base addition

# Generate my vectors
x = np.linspace(0., Fbase, 200)
y = [pH(base, Facid1, Facid2) for base in x]

# Make the plot frame
fig = plt.figure()
ax = fig.add_subplot(111)

# Set the limits
ax.set_ylim(1, 14)
ax.set_xlim(np.min(x), np.max(x))

# Add my data
ax.plot(x, y, "r-") # Plot of the data use lines

#add title, axis titles, and legend
ax.set_title("Acid titration")
ax.set_xlabel("Moles NaOH")
ax.set_ylabel("pH")
#ax.legend(("y data"), loc='upper left')

plt.show()

Based on the answer, here is what I came up with.  Any other suggestions?

# my pH calculation class
# assume two distinct pKa's  solution is a quartic equation
class pH:
    #things that don't change
    ka1 = 2.479496e-6
    ka2 = 1.87438e-9
    kw = 1.019230e-14
    kSum = ka1+ka2
    kProd = ka1*ka2
    e = -kw*kProd

    #things that only depend on Facid1 and Facid2
    def __init__(self, Facid1, Facid2):
        self.c = -(self.ka1*Facid1+self.ka2*Facid2)+self.kProd-self.kw
        self.d = self.kProd*(Facid1+Facid2)+self.kw*(self.kSum)

    #only calculate things that depend on base
    def pHCalc(self, base):
        pMatrix = [[0, 0, 0, -self.e],  #construct the companion matrix
                   [1, 0, 0, self.d-base*self.kProd],
                   [0, 1, 0, -(self.c+self.kSum*base)],
                   [0, 0, 1, -(self.kSum+base)]]
        myVals = la.eigvals(pMatrix)
        return -np.log10(np.max(myVals)) #need the one positive root


texts: Make repeating numbers 0 and putting them at the beginning of array

texts:
I am new to programming and I have made a program to make all repeating numbers in an array 0 and put those all 0s in left side:

import java.util.*;
class ArrayWork
{
    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);
        int arr[],n,i,j,nr[]= new int[5];
        System.out.println("Enter the value for n: ");
        n = sc.nextInt();
        if(n>25)
            System.out.println("Invalid input");
        else
        {
            arr = new int[n];
            System.out.println("Enter the array elements: ");
            for(i=0;i<n;i++)
            {
                arr[i] = sc.nextInt();
            }
            int count =0;
            for( i=0; i< arr.length-1;i++)
            { for (j=i+1;j<arr.length;j++)
                {if(arr[i]==arr[j])
                   nr[i]=arr[i];
                    System.out.println(nr[i]);
                }}
            for(int v=0;v<n;v++){  for(i=0;i<n;i++)
            {
                if(arr[i]==nr[v])
                {
                    for(j=i-1;j>=0&&arr[j]>0;j--)
                    {
                        arr[j+1]=arr[j];
                    }
                    arr[j+1]=0;
                }
            }}

            System.out.println("The array is: ");
            for(i=0;i<n;i++)
            {
                System.out.print(arr[i] + " ");
            }
        }
    }

}

Can I do anything to make this program smaller although the output is coming right and the program is ok
but I have made many loop,
Hope you know any better way?

INPUT:

10,20,20,4,4,6

OUTPUT:

0,0,0,0,10,6


texts: Multiplying an array by a number in C and how can achive vectorize the principal loop in this function?

texts:
I have code in C that multiplies each element of an array by a number (0-9), resulting in a series of base 10 digits.

I compile with

gcc -xc -Ofast -msse2 -flax-vector-conversions -ffast-math -funroll-all-loops --param max-unroll-times=50 -ftree-vectorize -fopt-info-vec-missed

My processor is core i7 950.
My problem is that this function takes longer to run that I expected (8 seconds in my faster version). I need it to be faster.

I know that my problem is that
can't vectorize the principal loop for because of this error: not vectorized: not suitable for gather load x_60 = table[_59]. How can this code be modified to solve this problem and make the code faster? It's fine for the solution to use intrinsics or other specialized techniques.

Compilable code with different tests here.

My fastest version so far is this:

  uint8_t ConstMul(uint8_t *V, size_t N, uint8_t digit){
        #define TABLE_SIZE ((9*256 + 9)*9 + 9 + 1)
        static uint32_t table[TABLE_SIZE];
        if(!table[1]){
                #pragma simd
                for(uint32_t i = 0; i < TABLE_SIZE; ++i){
                        uint32_t u = i % 256 % 10;
                        uint32_t d = (i / 256 + i % 256 / 10) % 10;
                        uint32_t c = (i / 256 + i % 256 / 10) / 10;
                        table[i] = c | (u << 8)|(d << 16);
                }
        }
        if(N == 0 || digit <= 1){
                if(digit == 0) memset(V,0,N);
                return 0;
        }else{
                size_t CARRY = 0;
                if((uintptr_t)V & 1){
                        int R = V[0] * digit + (uint8_t)CARRY;
                        CARRY = (uint8_t)(R / 10);
                        V[0] = (uint8_t)(R - CARRY * 10);
                        V++;
                        N--;
                }
                {
                        uint16_t *V2 = (uint16_t *)(void *)V;
                        size_t N2 = N / 2;
                        for(size_t i = 0; i < N2; ++i){
                                uint32_t x = table[V2[i] * digit + CARRY];
                                V2[i] = (uint16_t)(x >> 8);
                                CARRY = (uint8_t)x;
                        }
                }
                if(N & 1){
                        int R = V[N-1]*digit + (uint8_t)CARRY;
                        CARRY = (uint8_t)(R/10);
                        V[N-1] = (uint8_t)(R - CARRY * 10);
                }
                return (uint8_t)CARRY;
        }
        #undef TABLE_SIZE
}

But I also tried these approaches which were slower:

void ConstMult( uint8_t *V, size_t N, uint8_t digit )
    {
      uint8_t CARRY = 0;
      for ( size_t i=0; i< N; ++i )
      {
        V[i] = V[i] * digit + CARRY;
        CARRY = ((uint32_t)V[i] * (uint32_t)0xCCCD) >> 19;
        V[i] -= (CARRY << 3) + (CARRY << 1);
      }
    }
uint8_t ConstMult( uint8_t *V, size_t N, uint8_t digit )
{
  uint8_t CARRY = 0;
  for ( int i=0; i< N; i++ )
  {
    char R = V[i] * digit + CARRY;
    CARRY = R / 10;
    R = R - CARRY*10;
    V[i] = R;
  }
  return CARRY; // may be from 0 to 9
}
uint8_t ConstMult(uint8_t *V, size_t N, uint8_t digit)
{
  uint8_t CARRY = 0;
  uint8_t ja = 0;
  for (size_t i = 0; i < N; ++i) {
    uint8_t aux = V[i] * digit;
    uint8_t R = aux + CARRY;
    CARRY = ((u_int32_t)R*(u_int32_t)0xCCCD) >> 19;
    ja = (CARRY << 3) + 2*CARRY;
    R -= ja;
    V[i] = R;
  }
  return CARRY;
}


texts:
I have written a selection sort code in java. I know its very elementary algorithm, but since i am learning, so wanted your input about the quality of the code. Please have a look at the code:
package selection_sort;
import java.util.Scanner;

public class SelectionSort {

int [] arrayToBeSorted;
Scanner scan=new Scanner(System.in);

SelectionSort(){
    System.out.println("Enter the number of elements");
    int total=scan.nextInt();
    this.arrayToBeSorted=new int[total];
    for(int i=0;i<total;i++) {
        System.out.println("Enter the "+i+" number of elements");
        this.arrayToBeSorted[i]=scan.nextInt();
    }

}

public void Sort() {
    int minIndex,min;
    boolean swapRequired=false;
    for(int i=0;i<arrayToBeSorted.length;i++) {
        minIndex=i;
        min=this.arrayToBeSorted[i];
        for(int j=i+1;j<this.arrayToBeSorted.length;j++) {
            if(this.arrayToBeSorted[j]<min) {
                min=this.arrayToBeSorted[j];
                minIndex=j;
                swapRequired=true;
            }
        }
        if(swapRequired) {
            swap(i,minIndex);
        }

    }

    for(int x:this.arrayToBeSorted) {
        System.out.print(x+" ");
    }

    }

public void swap(int i,int j) {

    //System.out.println("swap called, pos="+i+"and minindex="+j);
    int temp=this.arrayToBeSorted[i];
    this.arrayToBeSorted[i]=this.arrayToBeSorted[j];
    this.arrayToBeSorted[j]=temp;

    //System.out.println("------------");

}
public static void main(String[] args) {
    SelectionSort s=new SelectionSort();
    s.Sort();
}

}

Also about Analysis, as selection is O(n2), is it because I am using nested for loop. Is there any tool which tells us about complexity of code .Thanks in advance and please be patient if its very naive


texts: Trying to implement cross-class functionality that needs a field to operate in C#

texts:
Crosspost from here, it was suggested that this is better place to pose my question.

I'm implementing a series of classes in a game that all derive from one base class that references the scripting of the object that it pertains. Most of these are objects that are generated by certain spells/abilities, and very frequently there is a lot of overlap between functionality each script needs.

Unfortunately, the functionality requires the use of some kind of field to use, whether it be a Dictionary or a couple of primitives. Normally I'd just apply an interface to each one, but because each "piece of functionality" requires a field to operate correctly that doesn't seem optimal. And adding every kind of multi-use functionality into the base class seems like it would make each object unnecessarily bloated.

Here's an example:

BlazingAura_Server

...
public BlazingAuraC_Server conditionInstance;
public Queue<KeyValuePair<int, float>> reapplyDelay = new Queue<KeyValuePair<int, float>>();

...
void Update()
{
    KeyValuePair<int, float> id;
    while (reapplyDelay.Count > 0)
    {
        if (reapplyDelay.Peek().Value - BlazingAuraC_Server.BURNING_REAPPLY_DELAY > conditionInstance.duration)
        {
            id = reapplyDelay.Dequeue();
        }
        else
        {
            break;
        }
    }
}

void OnTriggerEnter(Collider collider)
{
    if (collider.tag != "Spell")
    {
        EntityInfoServer collidedInfo = collider.transform.GetComponentInChildren<EntityInfoServer>();
        collidedInfo.QueueDamageRaw(conditionInstance, BlazingAuraC_Server.TICK_FREQ * BlazingAuraC_Server.BASE_DPS, ValueModDamageSubtype.Elemental);

        if (!reapplyDelay.Any(id => id.Key == collidedInfo.entityId))
        {
            reapplyDelay.Enqueue(new KeyValuePair<int, float>(collidedInfo.entityId, conditionInstance.duration));
            collider.transform.GetComponentInChildren<EntityInfoServer>().AddConditionServer(Condition.Burning, conditionInstance);
        }
    }
}

And here's another example:

Storm_Server

...
public float duration;
public Queue<KeyValuePair<int, float>> reapplyDelay = new Queue<KeyValuePair<int, float>>();

...
void Update()
{
    duration += Time.deltaTime;

    if (Mathf.CeilToInt((duration + Time.deltaTime) / TICK_FREQ) > Mathf.CeilToInt(duration / TICK_FREQ))
    {
        Activate(stormCollider);
    }

    KeyValuePair<int, float> id;
    while (reapplyDelay.Count > 0)
    {
        if (reapplyDelay.Peek().Value - STORM_DRENCH_DELAY > duration)
        {
            id = reapplyDelay.Dequeue();
        }
        else
        {
            break;
        }
    }
}

public void OnTriggerEnter(Collider collider)
{
    if (collider.tag == "Player")
    {
        //Debug.Log("IN STORM");
        EntityInfoServer collidedInfo = collider.transform.GetComponentInChildren<EntityInfoServer>();

        if (!reapplyDelay.Any(id => id.Key == collidedInfo.entityId))
        {
            reapplyDelay.Enqueue(new KeyValuePair<int, float>(collidedInfo.entityId, duration));
            collider.transform.GetComponentInChildren<EntityInfoServer>().AddConditionServer(Condition.Drenched, stormInfo);
        }
    }
}

Basically, each class keeps track of entities that have collided with it and store it in a queue, and make sure that a condition doesn't get reapplied unless the entity has been dequeued after a certain duration. However, it requires the Queue to work correctly, but declaring a Queue and utilizing an interface in each class doesn't seem like very good abstraction and feels sloppy in general.

What are my best options for including functionality like this (i.e. having a reapply delay) across multiple classes?


texts: Google Code Jam: Store Credit Java Solution

texts:
It would be great if I could get this code reviewed.
I would love tips on how I could improve my code.

Problem
You receive a credit C at a local store and would like to buy two items. You first walk through the store and create a list L of all available items. From this list you would like to buy two items that add up to the entire value of the credit. The solution you provide will consist of the two integers indicating the positions of the items in your list (smaller number first).
Input
The first line of input gives the number of cases, N. N test cases follow. For each test case there will be:
One line containing the value C, the amount of credit you have at the store.
One line containing the value I, the number of items in the store.
One line containing a space separated list of I integers. Each integer P
indicates the price of an item in the store.
Each test case will have exactly one solution.
Output
For each test case, output one line containing "Case #x: " followed by the indices of the two items whose price adds up to the store credit. The lower index should be output first.

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.stream.IntStream;

public class StoreCredit {

    private static int case_num = 0;
    private static int num_cases, credit_value, item_cnt;
    private static ArrayList<Integer> prices;
    private static Scanner reader;
    private static ArrayList<String> output;

    public static void main(String... args) throws FileNotFoundException{
        output = new ArrayList<String>();
        reader = new Scanner(new File("src/store_credit/input.txt"));

        num_cases = reader.nextInt();
        for(int i = 0; i < num_cases; ++i){
            prices = new ArrayList<Integer>();
            credit_value = reader.nextInt();
            item_cnt = reader.nextInt();
            IntStream.range(0, item_cnt).forEach((j) ->  prices.add(j, reader.nextInt()));
            solution();

        }
        for(String s : output)
            System.out.println(s);
    }

    public static void solution(){
        for(int i = 0; i < item_cnt; ++i){
            if(prices.contains(credit_value - prices.get(i))){
                output.add("Case #" + ++case_num + ": " + (i + 1) + " " + (prices.lastIndexOf(credit_value-prices.get(i)) + 1));
                return;
            }
        }
    }
}

Input Information


texts:
I have written simple code to construct a graph, but I think there are too many different types for such a simple task.

In this code I need to store Node structs in the Graph instead of pure values because it encapsulates some logic. The user should not know about Key. The user will be working with references to nodes.

How can I do this code simpler and clearer?

use std::collections::HashMap;
use std::rc::Rc;
use std::borrow::Borrow;

fn main() {
    let mut graph = Graph::<i32>::new();
    let n1 = graph.create_node(1);
    let n2 = graph.create_node(2);
    let n3 = graph.create_node(3);
    graph.add_edge(n1.clone(),n2.clone(), 6, false);
    graph.add_edge(n1.clone(),n3.clone(), 7, false);
    graph.get_rel_nodes(n1);
}

type Key = usize;
type Weight = usize;

#[derive(Debug, Clone)]
struct Node<T: Clone> {
    key: Key,
    value: T
}
impl<T: Clone> Node<T> {
    fn new(value: T, key: Key) -> Self {
        Node{
            key: key,
            value: value
        }
    }
}

#[derive(Debug)]
struct Graph<T: Clone> {
    map: HashMap<Key, HashMap<Key, Weight>>, // Contains edges
    list: HashMap<Key, Rc<Node<T>>>, // Contains nodes
    next_key: Key,
}

impl<T: Clone> Graph<T> {
    fn new() -> Self {
        Graph {
            map: HashMap::new(),
            list: HashMap::new(),
            next_key: 1,
        }
    }

    // Creates new node with value and return rel for it.
    fn create_node(&mut self, value: T) -> Rc<Node<T>>  {
        let key = self.get_next_key();
        let node = Node::new(value,key);
        let node = Rc::new(node);
        self.list.insert(key, node.clone());
        self.map.insert(key, HashMap::new());
        node
    }

    // Creates new adge between two nodes.
    fn add_edge<N: Borrow<Node<T>>>(&mut self, n1: N, n2: N, weight: Weight, bidirected: bool){
        let key1 = n1.borrow().key;
        let key2 = n2.borrow().key;
        if let Some(map) = self.map.get_mut(&key1) {
            map.insert(key2, weight);
        } else {
            return;
        }
        if bidirected {
            if let Some(map) = self.map.get_mut(&key2) {
                map.insert(key1, weight);
            }
        }
    }

    // Get relative nodes.
    fn get_rel_nodes<N: Borrow<Node<T>>>(&self, node: N) -> Vec<&Rc<Node<T>>> {
        let key = node.borrow().key;
        let rel_keys = self.map.get(&key).unwrap();
        let mut result = vec![];
        for(k,_) in rel_keys {
            result.push(self.list.get(k).unwrap());
        }
        result
    }

    fn get_next_key(&mut self) -> Key {
        let key = self.next_key;
        self.next_key += 1;
        key
    }
}


texts:
I am writing a program which automatically crawls codes from this site!

Would you please review my code?

The required .jars: jsoup, org.apache.commons.io.

Main.java:

public class Main {
    public static void main(String[] args) throws Exception {
        final String site1 = "http://codereview.stackexchange.com/questions/";
        String site2[] = {"69", "109", "131"};
        String site3[] = {"is-this-implementation-of-shamos-hoey-algorithm-ok",
                "are-there-any-ways-to-improve-my-http-request-path-parser",
                "law-of-demeter-and-data-models"};
        HtmlGetter htmlGetter = new HtmlGetter();

        for(int i = 0 ; i < site2.length ; ++i) {
            htmlGetter.setUrl(site1, site2[i], site3[i]);
            htmlGetter.download();
            htmlGetter.parse(i+1);
        }
    }
}

HtmlGetter.java:

import java.io.*;
import java.net.URL;
import java.util.Scanner;

import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.io.IOUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class HtmlGetter {
    private URL url;
    private String fileName;

    public void setUrl(String site1, String site2, String site3) throws Exception {
        this.url = new URL(site1 + site2 + "/" + site3);
        this.fileName = "[" + site2 + "]" + site3 + ".html";
    }

    public void download() throws Exception {
        final InputStream in = url.openStream();
        final OutputStream out = new FileOutputStream(fileName);
        IOUtils.copy(in, out);
        in.close();
        out.close();
        divideFile();
    }

    private void divideFile() throws Exception {
        Scanner scanner = new Scanner(new File(fileName));
        String oneLine;
        final BufferedWriter out1 = new BufferedWriter(new FileWriter("question.html"));
        final BufferedWriter out2 = new BufferedWriter(new FileWriter("answer.html"));

        while(scanner.hasNextLine()) {
            oneLine = scanner.nextLine();
            if(oneLine.matches(".*
.*")) {
                while(scanner.hasNextLine()&&(!oneLine.matches(".*
.*"))) {
                    out1.write(oneLine);
                    out1.newLine();
                    oneLine = scanner.nextLine();
                }
            }
            if(oneLine.matches("")) {
                while(scanner.hasNextLine()&&(!oneLine.matches(".*
.*"))) {
                    out2.write(oneLine);
                    out2.newLine();
                    oneLine = scanner.nextLine();
                }
                break;
            }
        }
        out1.close();
        out2.close();
     }

    public void parse(int articleNumber) throws Exception {
        parse2("question.html", articleNumber);
        parse2("answer.html", articleNumber);
    }

    public void parse2(String strFileName, int articleNumber) throws Exception {
        File input = new File(strFileName);
        Document doc = Jsoup.parse(input, "UTF-8");
        Elements codes = doc.select("code");
        BufferedWriter out;
        int subNumber = 0;
        String qa = "x";

        for(Element code: codes)
        {
            if(strFileName.equals("question.html")) { qa = "q"; }
            else if(strFileName.equals("answer.html")) { qa = "a"; }
            else { System.out.println("Error!"); }
            out = new BufferedWriter(new FileWriter(qa + articleNumber + "-" + (++subNumber) + ".txt"));
            out.write(code.text().replaceAll("[\r\n]", "\r\n"));
            out.close();
        }
    }
}


texts:
The below code takes an incoming sequence of objects, checks each object's type and then yields the object in a specific order.  This is all taking place in an active pattern.  As I am still new to F#, I would like to know if there is a better or more efficient way of accomplishing this task.

    type ArticleObj =
    | Submission
    | Photos
    | ReviewRating
    | BusinessReviewRating
    | ArticleTag

let (|OrderArticleObj|_|) (objSeq : seq<obj>) =

    // Create DU array
    let articleParts = [|
                        Submission; Photos; ReviewRating;
                        BusinessReviewRating; ArticleTag
                    |]

    // create ordered array of objects
    let orderedSeq = seq{
                for row in articleParts do
                    for row2 in objSeq do
                        match row with
                        | Submission ->
                                        let isValid =
                                            match row2 with
                                            | :? ArticleSubmission as Sub -> true
                                            | _ -> false

                                        if isValid
                                        then
                                            yield row2
                        | Photos ->
                                    let isValid =
                                            match row2 with
                                            | :? seq<Photos> as Photo -> true
                                            | _ -> false

                                    if isValid
                                    then
                                        yield row2
                        | ReviewRating ->
                                            let isValid =
                                                match row2 with
                                                | :? ArticleReviewRating as RevRating -> true
                                                | _ -> false

                                            if isValid
                                            then
                                                yield row2
                        | BusinessReviewRating ->
                                                    let isValid =
                                                        match row2 with
                                                        | :? BusinessReviewRating as BizRev -> true
                                                        | _ -> false

                                                    if isValid
                                                    then
                                                        yield row2
                        | ArticleTag ->
                                        let isValid =
                                            match row2 with
                                            | :? seq<ArticleTags> as ArtTag -> true
                                            | _ -> false

                                        if isValid
                                        then
                                            yield row2
            }

    if not (Seq.isEmpty orderedSeq)
    then Some(orderedSeq) else None


texts: "Between time s and time t, how many new calls were made to the call centre?"

texts:
Input: The ﬁrst line of input consists of two integers n and q. Here, 1 ≤ n ≤ 86,400 is the number of seconds your call center is open for each day and 1 ≤ q ≤ 50,000 is the number of queries you want to make.

The next line contains n integers, each between 0 and 100. Consecutive integers will be separated by a single space. The ith integer on this line indicates how many new calls were received by your call center yesterday in the ith second of operation.
Finally, q lines follow. Each consists of two integers 1 ≤ s ≤ t ≤ n separated by a single space.

Output: consists of q lines, one for each query. For each query with integers s, t, you should output the total number of calls your call center received yesterday between the sth and tth second of operation (including the calls received exactly at second s and at second t).

Sample Input 1
13 7
5 3 13 0 0 1 4 3 12 1 0 0 17
1 3
1 4
1 13
3 3
4 4
2 7
8 11

Sample Output 1
21
21
59
13
0
21
16

The code I made is not fast enough. What can I do to make it faster? Any suggestions would help, and any explanation as to why this is not fast and anything that would make it faster.

Here is a GitHub repository with the test center.

# read the first line
n , q = list(map(int, input().split()))
# read the calls
calls = [int(i) for i in input().split()]
s_array , t_array = [], []
# read and process each query
for i in (range(0,q)):
    s , t = list(map(int, input().split()))
    s_array.append(s)
    t_array.append(t)

#print  the answer
sorting = {} #empty dictionary
#how many quaries between eacth s and t array
for i in range(0, q):
    sorting[i] = sum(calls[s_array[i] - 1:t_array[i]])

for k, v in sorting.items():
   print(v)

Edit: answer figured out:

# read the first line
n, q = list(map(int, input().split()))

# read the calls
calls = [int(i) for i in input().split()]

s_array, t_array = [], []
# read and process each query
for i in (range(0, q)):
    s, t = list(map(int, input().split()))
    s_array.append(s)
    t_array.append(t)

aux = [i for i in range(0, n)]  # initializing theauxiliary array
aux[0] = calls[0]

for i in range(1, n):
    # O(n) time to find the sum till that index and store in auxiliary array
    aux[i] = aux[i-1] + calls[i]

# print the answer
sorting = {}  # empty dictionary
# how many quaries between eacth s and t array
for i in range(0, q):
    sorting[i] = aux[t_array[i]-1]-aux[s_array[i]-1]+calls[s_array[i]-1]
    # sum(i,j) = aux[j] - aux[i-1]; =>Constant time

for k, v in sorting.items():
    print(v)


texts: Which is a better style to write default return case in if-else

texts:
private String GetFacilityName(String facilityHexID) {
    if (facilityHexID.equals(FACILITY_AIRCON_HEX_ID)) {
       return FACILITY_AIRCON_NAME;
    }
    else if (facilityHexID.equals(FACILITY_FAN_HEX_ID)) {
       return FACILITY_FAN_NAME;
    }

    return facilityHexID;
}

Or

private String GetFacilityName(String facilityHexID) {
    if (facilityHexID.equals(FACILITY_AIRCON_HEX_ID)) {
       return FACILITY_AIRCON_NAME;
    }
    else if (facilityHexID.equals(FACILITY_FAN_HEX_ID)) {
       return FACILITY_FAN_NAME;
    }
    else {
       return facilityHexID;
    }
}

They essentially do the same thing. I'm thinking first one is better from the standpoint of "Write more code only if you have to" and the second one is better from readability aspect.

I'd use a switch statement with default case but I'm using a old version of JDK.. so I can't use it on Strings.

Which one is better?


texts: Do you think this design pattern is good for game portal content management system

texts:
I am developing game portal content management system using java and j2ee technology. However i am stuck in my design implementation.

Here is the scenario:

Each Game object has attributes like id, name, developer, price, platformType, platformName and so on...

However the release date may be different for each platform - PC, Mobile, Console and so on.
Of course it is the same with the price.

The other problem is that for example if the game is for PC platform it has requirements like RAM, Video card and so on. So I decided to make another class for the platformType.

Do you think that the following design is good?

Here is the main Game object class:

public class Game
{
   private long systemId;
   private String name;
   private String developer;
   private Date registerDate;
   private ArrayList<GamePlatform> gamePlatforms;
   private GameScore gameScore;
   private GameRank gameRank;
   private ArrayList<String> genre;
}

Here is the GamePlatform class and its subclasses

public abstract class GamePlatform
{
   private Date releaseDate;
   private int price;
   private String name;
   private PlatformType platformType;

   public GamePlatform(Date releaseDate, int price, String name, PlatformType  platformType) {

       this.releaseDate = releaseDate;
       this.price = price;
       this.name = name;
       this.platformType = platformType;
   }

   public abstract PlatformType getType();
}

child class 1

public class ConsolePlatform extends GamePlatform
{

   public ConsolePlatform(Date releaseDate, int price, String name, PlatformType platformType) {
       super(releaseDate, price, name, platformType);
   }

   @Override
   public PlatformType getType()
   {
       return PlatformType.CONSOLE;
   }

}

child class 2

public class MobilePlatform extends GamePlatform
{

public MobilePlatform(Date releaseDate, int price, String name, PlatformType platformType)
   {
       super(releaseDate, price, name, platformType);
   }

   @Override
   public PlatformType getType()
   {
       return PlatformType.MOBILE;
   }

child class 3

public class PCPlatform extends GamePlatform
{

   private PCRequirements pcRequirements;

   public PCPlatform(Date releaseDate, int price, String name, PlatformType platformType, PCRequirements pcRequirements)
   {
       super(releaseDate, price, name,platformType);
       this.pcRequirements = pcRequirements;
   }

   public PCRequirements getPcRequirements() {
       return pcRequirements;
   }

   public void setPcRequirements(PCRequirements pcRequirements) {
       this.pcRequirements = pcRequirements;
   }

   @Override
   public PlatformType getType()
   {
       return PlatformType.PC;
   }

}

And finally i have Enum class for the platform types. Here it is:

public enum PlatformType
{
   MOBILE
   {
       @Override
       public String toString(){ return "Mobile";}
   },
   CONSOLE
   {
       @Override
       public String toString(){ return "Console";}
   },
   PC
   {
       @Override
       public String toString(){ return "PC";}
   };
}


texts:
I followed a video on YouTube to create a custom user model, this is my attempt:

# Django Imports
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
from django.db import models

# The Custom (UserManager) Class
class UserManager(BaseUserManager):
    # Defining A Function That Will Be Used To Create New Users
    def create_user(self, email, username, f_name, l_name, password = None):
        if not email:
            raise ValueError('Users Must Have An E-Mail Address')
        if not username:
            raise ValueError('Users Must Have A Username')

        # Creating An Object Of The Type (User)
        user                    = self.model(
            user_email          = self.normalize_email(email),
            user_name           = username,
            first_name          = f_name,
            last_name           = l_name
        )

        # Setting The Password For The User Object We Created Above
        user.set_password(password)

        # Saving The User To The Database
        user.save(using = self._db)

        # Returning The (user) Instance To Where The Function Was Called
        return user

    # Defining A Function That Will Be Used To Create Superusers (Admins)
    def create_superuser(self, email, username, f_name, l_name, password):
        # Creating An Instance Of Type (User)
        user                    = self.create_user(
            user_email          = self.normalize_email(email),
            user_name           = username,
            password            = password,
            first_name          = f_name,
            last_name           = l_name
        )

        # Setting The User We Created Above As An Administrator
        user.is_admin           = True
        user.is_staff           = True
        user.is_superuser       = True

        # Saving The User To The Database
        user.save(using = self._db)

        # Returning The (user) Instance To Where The Function Was Called
        return user

# The Custom (User) Class
class User(AbstractBaseUser):
    # The Data (Columns) For Each User
    user_email                  = models.EmailField(max_length = 120, unique = True)
    user_name                   = models.CharField(max_length = 40, unique = True)
    first_name                  = models.CharField(max_length = 60)
    last_name                   = models.CharField(max_length = 60)
    date_joined                 = models.DateTimeField(auto_now_add = True)
    last_login                  = models.DateTimeField(auto_now = True)
    is_admin                    = models.BooleanField(default = False)
    is_active                   = models.BooleanField(default = True)
    is_staff                    = models.BooleanField(default = False)
    is_superuser                = models.BooleanField(default = False)

    # The Data (Column) That Is Going To Be Used As A Login Identifier
    USERNAME_FIELD              = 'user_email'
    REQUIRED_FIELDS             = ['user_name', 'first_name', 'last_name']

    # Defining How The Output Of An Object Of The (User) Class Will Look Like
    def __str__(self):
        return f'{self.user_email} - ({self.user_name})'

    # Defining A Function That Will Check Whether A User Is Admin Or Not
    def has_perm(self, perm, obj = None):
        return self.is_admin

    # Defining A Function That Will Check Whether A User Is Admin In The Current App Or Not
    def has_module_perms(self, app_label):
        return True

I know the way I comment stuff is incorrect, I am going to leave this habit as I don't need to write comments everywhere, instead focus on code clarity, so other than my bad commenting style, is this approach to creating custom users in Django correct?

P.S: I use PostgreSQL as my Database


texts: First Dockerfile, I would appreciate critique

texts:
As the title says, this is my first Dockerfile. It won't be published on any registry, just for my internal use at home. I'd appreciate any critique of what I could do better. I'm currently working on a way to not hard-code the password into the docker-compose file...

This image is to run Postfix on Alpine as a SMTP relay for my devices to alert me (e.g., NAS, security cameras, etc...).

Dockerfile

FROM alpine:3.10

ARG BUILD_DATE

LABEL maintainer="MyNameGoesHere" \
      org.label-schema.schema-version="1.0" \
      org.label-schema.name="postfixrelay" \
      org.label-schema.build-date=$BUILD_DATE

RUN apk add --no-cache --update \
    bash ca-certificates cyrus-sasl-login postfix rsyslog tzdata && \
    rm -rf /var/cache/apk/*

EXPOSE 25

VOLUME [ "/var/spool/postfix" ]

COPY ./entrypoint.sh /

RUN chmod +x /entrypoint.sh

ENTRYPOINT ["/entrypoint.sh"]

entrypoint.sh

#!/bin/sh -e

#Set timezone
if [ ! -f /etc/timezone ] && [ ! -z "$TZ" ]; then
  cp /usr/share/zoneinfo/$TZ /etc/localtime
  echo $TZ >/etc/timezone
fi

# Set Postfix options
postconf -e "inet_interfaces = all" && \
postconf -e "mynetworks = 0.0.0.0/0" && \
postconf -e "relayhost = [$RELAY_IP]:$RELAY_PORT" && \
postconf -e "smtp_use_tls = yes" && \
postconf -e "smtp_sasl_auth_enable = yes" && \
postconf -e "smtp_sasl_security_options = noanonymous" && \
postconf -e "smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd"&& \
postconf -e "smtp_tls_CAfile = /etc/ssl/certs/ca-certificates.crt" && \

# Create password file
echo "[$RELAY_IP]:$RELAY_PORT   $EMAIL:$PASS" > /etc/postfix/sasl_passwd && \
chown root:root /etc/postfix/sasl_passwd && \
chmod 600 /etc/postfix/sasl_passwd && \
postmap /etc/postfix/sasl_passwd

# Start postfix
postfix start-fg

docker-compose.yml

version: '3'
services:
  postfixrelay:
    container_name: postfixrelay
    restart: unless-stopped
    environment:
      - TZ=America/New_York
      - RELAY_IP=smtp.gmail.com
      - RELAY_PORT=587
      - EMAIL=my_email_address@gmail.com
      - PASS=password
    networks:
      - postfixrelay
    ports:
      - '25:25'
    volumes:
      - 'postfixrelay_data:/var/spool/postfix'
    image: postfixrelay

networks:
  postfixrelay:

volumes:
  postfixrelay_data:
    driver: local


texts: Simplest way to write "FizzBuzz" in Rust

texts:
Can you write an a simpler Rust fizzbuzz program than I have? Use my output or the spec:

  Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”.

to write your program. I want to see if it's possible to write an even simpler program.

fn main() {
    for i in 1..102 {
        match i {
            i if (i % 15 == 0) => { println!("{:?}", "FizzBuzz") },
            i if (i % 3 == 0) => { println!("{:?}", "Fizz") },
            i if (i % 5 == 0) => { println!("{:?}", "Buzz") },
            _ => { println!("{:?}", i) },
        }
    }
}


texts: Project Euler #1 - Multiples of 3 and 5 - First Program

texts:
Taking a problem from the website, "Project Euler #1", I have created my first C# program. The problem I have used is as follows:

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.

The program I have made:
using System;

namespace _5_multiples
{
    public class MainClass
    {
        public static void Main()
        {
            int currentNumber = 1000;
            int allSum = 0;

            currentNumber = currentNumber - 1;
            while (currentNumber > 0)
            {
                if (currentNumber % 3 == 0)
                {
                    allSum = allSum + currentNumber;
                }
                else
                {
                    if (currentNumber % 5 == 0)
                    {
                        allSum = allSum + currentNumber;
                    }
                }
                currentNumber = currentNumber - 1;
            }
            Console.WriteLine(allSum);
        }
    }
}

I understand there is probably a lot to improve - this is my first C# program after all. I did run into a few problems such as referencing non static members from a static context and no suitable entry method. Rather than finding a definitive fix, the solution I implemented was more of a workaround; hence why I feel there may be a lot to improve.
namespace _5_multiples - this doesn't look right? Name of the program is actually 3_5_multiples - perhaps a badly chosen name?
Anyway, please let me know on anything that could be improved.


texts: JS deep merging of objects- removing empty keys

texts:
I've written a helper for combining objects (deep merge).

It works, and is flexible to add options (like uniq and replace).

Replace should replaces the any matching properties on the object (but spread in any existing properties).

The code below works, but I believe it could be optimized particularly as I could NOT find a way to remove empty keys without the use of JSON.parse(JSON.stringify - it feels wrong to have to crawl back over the entire array to do so.

Using Lodash is not an option.

Examples

DATA = {foo:{i:{z:[1]},x:[1]}}

getDeepMerge(DATA, {add:{foo:{q:[1]}}}
// {foo:{i:{},x:[1], q:[1]}}
getDeepMerge(DATA, {add:{foo:{}}, replace:true}
// {foo:{}}
getDeepMerge(DATA, {add:{foo:{i:{}}} }, replace:true, removeEmpty:true}
// {add:{foo:{i:{}}, x[1]} }

Code

const removeKey = (key, {[key]: _, ...rest}) => rest;

const getNewObj = toAdd => Array.isArray(toAdd) ? getObj(toAdd) : toAdd

const DE_DUPE = (e, i, arr) => arr.indexOf(e) === i

const removeEmptyObj = (o) => {
  let ignores = [null, undefined, ""],
  isNonEmpty = d => !ignores.includes(d) && (typeof(d) !== "object" || Object.keys(d).length)
  return JSON.parse(JSON.stringify(o), function(k, v) {
    if (isNonEmpty(v))
      return v;
  });
}
const getDeepMerge = (ogObj, opts={})=> {
  const { add, uniq=true, replace=false, removeEmpty=false } = opts

  const isObject = obj => obj && typeof obj === 'object';
    return [ogObj, add].reduce((prev, obj) => {
      let _add = {...prev}
      Object.keys(obj).forEach(key => {

        const pVal = _add[key];
        const oVal = obj[key];

        if (Array.isArray(pVal) && Array.isArray(oVal)) {
          _add[key] = pVal.concat(...oVal).filter(uniq ? DE_DUPE : null)
          if(replace){
_add[key] = oVal }
          _add = removeEmpty ? removeKey(key, _add) : _add

        }
        else if (isObject(pVal) && isObject(oVal)) {
            _add[key] = getDeepMerge(pVal, {...opts, add:oVal})
            if(replace){
              _add[key] = oVal
            }
        }
        else {
          _add[key] = oVal
        }
      });
      return removeEmptyObj(_add)
    }, {});
}

Live working demo: https://jsbin.com/yuduvukiqe/1/edit?js,console