texts:
I've written a script with the Google Maps JavaScript API v3.

I've ran it through JSHint and everything seems to be valid.

I'm wondering if my script has room for improvement.

Any suggestions are very much welcome!

(function () {
    'use strict';

    var map,
        markers = [];

    function initMap() {
        var paris = new google.maps.LatLng(48.856614, 2.3522219000000177),
            options = {
                // required
                center: paris,
                zoom: 10,
                // disable all user interaction
                disableDefaultUI: true,
                navigationControl: false,
                mapTypeControl: false,
                scaleControl: false,
                scrollwheel: false,
                draggable: false,
                zoomControl: false,
                disableDoubleClickZoom: true
            };

        map = new google.maps.Map(document.getElementById('map'), options);

        addMarker(paris, false);

        // center map responsively
        google.maps.event.addDomListener(window, 'resize', function () {
            var center = map.getCenter();

            google.maps.event.trigger(map, 'resize');

            map.setCenter(center);
        });
    }

    function geocodeAddress() {
        var geocoder = new google.maps.Geocoder(),
            addressInp = document.getElementById('address-inp');

        geocoder.geocode({ 'address': addressInp.value }, function (results, status) {
            if (status !== google.maps.GeocoderStatus.OK) {
                alert('Geocode was not successful for the following reason: ' + status);

                return;
            }

            map.fitBounds(results[0].geometry.viewport);
            map.setCenter(results[0].geometry.location);

            deleteAllMarkers();
            addMarker(results[0].geometry.location, true);

            addressInp.value = results[0].formatted_address;
        });
    }

    function addMarker(location, animateDrop) {
        var marker = new google.maps.Marker({
            map: map,
            position: location
        });

        if (animateDrop) {
            marker.setAnimation(google.maps.Animation.DROP);
        }

        google.maps.event.addListener(marker, 'click', function () {
            if (marker.getAnimation() !== null) {
                marker.setAnimation(null);
            } else {
                marker.setAnimation(google.maps.Animation.BOUNCE);
            }
        });

        markers.push(marker);
    }

    function deleteAllMarkers() {
        for (var i = 0; i < markers.length; i++) {
            markers[i].setMap(null);
        }
    }

    google.maps.event.addDomListener(window, 'load', initMap);

    window.onload = function () {
        var addressInp = document.getElementById('address-inp'),
            searchBtn =  document.getElementById('search-btn');

        addressInp.onkeydown = function (e) {
            if (e.keyCode === 13) {
                searchBtn.click();
                addressInp.blur();
            }
        };

        searchBtn.onclick = function () {
            geocodeAddress();
        };
    };
})();


texts:
Looking for optimizations and cleaner, more pythonic ways of implementing the following code.

#Given an array find any three numbers which sum to zero.

import unittest

def sum_to_zero(a):
    a.sort(reverse=True)
    len_a = len(a)
    if  len_a < 3:
        return []
    for i in xrange(0, len_a):
        j = i + 1
        for k in xrange(j + 1, len_a):
            if a[j] + a[k] == -1 * a[i]:
                return [a[i], a[j], a[k]]
    return []

class SumToZeroTest(unittest.TestCase):

    def test_sum_to_zero_basic(self):
        a = [1, 2, 3, -1, -2, -3, -5, 1, 10, 100, -200]
        res = sum_to_zero(a)
        self.assertEqual([3, 2, -5], res, str(res))

    def test_sum_to_zero_no_res(self):
        a = [1, 1, 1, 1]
        res = sum_to_zero(a)
        self.assertEqual(res, [], str(res))

    def test_small_array(self):
        a = [1, 2, -3]
        res = sum_to_zero(a)
        self.assertEqual(res, [2, 1, -3], str(res))

    def test_invalid_array(self):
        a = [1, 2]
        res = sum_to_zero(a)
        self.assertEqual(res, [], str(res))

#nosetests sum_to_zero.py


texts: Compare 2 arrays and preserve the row number

texts:
Background:

You have an eCommerce order of 10 products but you want to refund only 5 of them. The stock managing system needs to preserve the order of row number (orderline) when you do the returns, but don't send the items that are not refunded.

The order looks like this:

"Poduct1" Orderline ="1"
"Poduct2" Orderline ="2"
"Poduct3" Orderline ="3"
"Poduct4" Orderline ="4"

Refund all except Product2 and Product3 becomes:

"Poduct1" Orderline ="1"
"Poduct4" Orderline ="4"

But the creditmemo object returns it like this:

"Poduct1" Orderline ="1"
"Poduct4" Orderline ="2"

Because there is nothing in the refunded object about non-refunded items, my strategy is to compare the refund object with the order one and spot the difference (empty place).

Get order items and build and array of all SKUs:

$items = $products->getAllVisibleItems();
$all_skus = array();

    foreach ($items as $key => $item) {

        $all_sku = $item->getData("sku");
        $all_skus[] = $all_sku;

    }

Get refunded items and build an array of all SKUs:

    $all_memo_skus = array();
    foreach ($creditmemo->getAllItems() as $key => $item) {

        $memo_sku = $item->getData('sku');
        $all_memo_skus[] = $memo_sku;

    }

Check the difference between them:

$memo_diff = array_diff($all_skus, $all_memo_skus);

returns keys and SKUs. But I'm interested only in the key, the position where there is an empty place:

$memo_diff = array_keys($memo_diff);

because the array starts at 0, but the Orderline rows have to begin with 1, add 1 to each item of the array:

        $memo_increase = array();
        foreach($memo_diff as $val){
            $memo_increase[] = $val + 1;
        }

If there are consecutive numbers group them, for example if rows 2,3,4,5 are not refunded, you want the Orderline to jump to 6.

Here I am grouping the consecutive rows:

$result  = array();
        $temp = array();
        foreach($memo_increase as $val) {
            if(next($memo_increase) == ($val + 1)){
                $temp[] = $val;
            }
            else{
                if(count($temp) > 0) {
                    $temp[] = $val;
                    $result[]  = $temp[0].'-'.end($temp);
                    $temp   = array();
                }
                else{
                    $result[] = $val;
                }
            }
        }

This will return something like array("1", "4-9", "12") if rows 1,4,5,6,7,8,9,12 are missing.

//start array key from 1 instead of 0

array_unshift($result,"");
        unset($result[0]);

Then loop through each refunded item and assign it the right Orderline:

    $i = 1;

    foreach ($creditmemo->getAllItems() as $key => $item) {

            //if item is inside a grouped element, i.e 2-7 put the orderline at 2 then the next one at 8
            foreach($result as $val){
                if(strpos($val,"-")){
                    $piece = explode("-", $val);
                    if(($piece[0]) == $i){
                        $orderline = $piece[0];
                        $i = $piece[1] + 1;

                    }
                }
            }
//if item is single
            if(in_array($i, $result)){
                $orderline = $i+1;
                $i++;
            }
            else{
                $orderline = $i;
            }

It is overly complex for such a simple task. Is there a better way?


texts: Holding shift to check multiple items in JS

texts:
I did another challenge by from Wes Bos JS course. This is my version, and I'll also post his version. Please let me know which one you think is better, thanks.

const inbox = document.querySelector('.inbox');
let firstIndex = -1;
let shiftPressed = false;

function getIndex(parent, child) {
  return Array.from(parent.children).indexOf(child);
}

inbox.addEventListener('change', e => {
  const checkbox = e.target.closest('input[type="checkbox"]');
  if (!checkbox) return;

  const parent = checkbox.parentNode;
  const grandParent = parent.parentNode;
  if (!shiftPressed) {
    firstIndex = getIndex(grandParent, parent);
  } else {
    const secondIndex = getIndex(grandParent, parent);

    const grandChildren = grandParent.children;
    const [minIdx, maxIdx] = [Math.min(firstIndex, secondIndex), Math.max(firstIndex, secondIndex)];
    for (let idx = minIdx + 1; idx < maxIdx; idx++) {
      const itemDiv = grandChildren.item(idx);
      const itemCheckbox = itemDiv.querySelector('input[type="checkbox"]');
      itemCheckbox.checked = true;
    }

    firstIndex = -1;
    shiftPressed = false;
  }
});

window.addEventListener('keydown', e => {
  if (e.shiftKey && firstIndex !== -1) {
    shiftPressed = true;
  }
});
html {
  font-family: sans-serif;
  background: #ffc600;
}

.inbox {
  max-width: 400px;
  margin: 50px auto;
  background: white;
  border-radius: 5px;
  box-shadow: 10px 10px 0 rgba(0, 0, 0, 0.1);
}

.item {
  display: flex;
  align-items: center;
  border-bottom: 1px solid #F1F1F1;
}

.item:last-child {
  border-bottom: 0;
}

input:checked+p {
  background: #F9F9F9;
  text-decoration: line-through;
}

input[type="checkbox"] {
  margin: 20px;
}

p {
  margin: 0;
  padding: 20px;
  transition: background 0.2s;
  flex: 1;
  font-family: 'helvetica neue';
  font-size: 20px;
  font-weight: 200;
  border-left: 1px solid #D1E2FF;
}

    <input type="checkbox">

This is an inbox layout.

    <input type="checkbox">

Check one item

    <input type="checkbox">

Hold down your Shift key

    <input type="checkbox">

Check a lower item

    <input type="checkbox">

Everything in between should also be set to checked

    <input type="checkbox">

Try to do it without any libraries

    <input type="checkbox">

Just regular JavaScript

    <input type="checkbox">

Good Luck!

    <input type="checkbox">

Don't forget to tweet your result!

And this is his JS code:

const checkboxes = document.querySelectorAll('.inbox input[type="checkbox"]');

let lastChecked;

function handleCheck(e) {
  // Check if they had the shift key down
  // AND check that they are checking it
  let inBetween = false;
  if (e.shiftKey && this.checked) {
    // go ahead and do what we please
    // loop over every single checkbox
    checkboxes.forEach(checkbox => {
      console.log(checkbox);
      if (checkbox === this || checkbox === lastChecked) {
        inBetween = !inBetween;
        console.log('Starting to check them in between!');
      }

      if (inBetween) {
        checkbox.checked = true;
      }
    });
  }

  lastChecked = this;
}

checkboxes.forEach(checkbox => checkbox.addEventListener('click', handleCheck));


texts: "Can a given array be made strictly increasing by removing one number?"

texts:
The premise of the problem is that given an array of numbers, can you remove only one to make it a strictly increasing sequence?

[1, 1, 1, 2, 3] would be false because if you remove one of the 1s the array would still start off non-increasing because of the other two remaining 1s before it increased.
[1, 2, 3, 4, 99, 5, 10] would be true because you can remove the 99 and the remaining array [1, 2, 3, 4, 5, 10] would be strictly increasing.
[1, 88, 2, 3, 4, 99, 5, 6] would be false because removing any number would still leave an array that would not strictly increase.

For [1, 1] it would return true because even though removing one of the 1s would only leave one 1 which by definition can't increase sequentially because it is only one thing, I did not write the problem and this is the response they wanted.

and so on....

My questions

I've clearly made this code too complex, but it does work. Below my code is the tests that I used to check it with the expected returns commented out next to each.

How can I refactor this code to simplify it? Is there a way to do this without using chunk_while?

def almost_increasing_sequence(sequence)
  array_of_arrays = sequence.chunk_while {|i, j| i < j}.to_a
  if array_of_arrays.length == 1
    puts true
  elsif array_of_arrays.length > 2
    puts false
  else
    if (array_of_arrays[0].last <=> array_of_arrays[1].first) == 1
      if (array_of_arrays[0][-2] <=> array_of_arrays[1][0]) == -1
        puts true
      elsif (array_of_arrays[0].last <=> array_of_arrays[1][1]) == -1
        puts true
      elsif (array_of_arrays[0][-2]) == nil
        puts true
      else
        puts false
      end
    else
      puts true
    end
  end
end

almost_increasing_sequence([1, 2, 3, 4, 99, 5, 6]) #true
almost_increasing_sequence([1, 3, 2]) #true
almost_increasing_sequence([10, 1, 2, 3, 4, 5]) #true
almost_increasing_sequence([0, -2, 5, 6]) #true
almost_increasing_sequence([1, 2, 3, 4, 3, 6]) #true
almost_increasing_sequence([1, 1]) #true
almost_increasing_sequence([100, 200, 300, 400, 99, 500, 600]) #true
almost_increasing_sequence([1, 2, 1, 2]) #false
almost_increasing_sequence([1, 2, 3, 4, 5, 3, 5, 6]) #false
almost_increasing_sequence([40, 50, 60, 10, 20, 30]) #false
almost_increasing_sequence([1, 3, 2, 1]) #false
almost_increasing_sequence([1, 4, 10, 4, 2] ) #false
almost_increasing_sequence( [1, 1, 1, 2, 3]) #false
almost_increasing_sequence([10, 1, 2, 3, 4, 5, 6]) #true
almost_increasing_sequence([5, 7, 8, 90, 91, 92, 93]) #true


texts: Speed problems with SetValue, ToType and Reflection

texts:
I have a 'speed problem' with a program I'm currently developing. I already have encountered the methods which costs some time.

public void ConvertDataFrameToValueFields()
    {
        List<byte[]> items = new List<byte[]>() { new byte[2], new byte[2], new byte[2], new byte[2] };

        items[0][0] = this.DataBytes[0];
        items[0][1] = this.DataBytes[1];
        items[1][0] = this.DataBytes[2];
        items[1][1] = this.DataBytes[3];
        items[2][0] = this.DataBytes[4];
        items[2][1] = this.DataBytes[5];
        items[3][0] = this.DataBytes[6];
        items[3][1] = this.DataBytes[7];

        int i = 0;
        IEnumerable<PropertyInfo> result = this.determineCanMessageValueFields();

        foreach (var prop in result)
        {
            if (prop.PropertyType == typeof(MessageStatusValueField))
            {
                prop.SetValue(this, new MessageStatusValueField(BitConverter.ToUInt16(items[i], 0), prop.Name, this.UnitType), null);
            }
            else if (prop.PropertyType == typeof(MessageValueField))
            {
                prop.SetValue(this, new MessageValueField(BitConverter.ToUInt16(items[i], 0), prop.Name), null);
            }
            else if (prop.PropertyType == typeof(MessageValueFieldInt32))
            {
                prop.SetValue(this, new MessageValueFieldInt32(BitConverter.ToUInt16(items[i], 0), prop.Name), null);
            }
            else if (prop.PropertyType.GetCustomAttributes(false).Count(x => x.GetType() == typeof(BitmaskValueFieldClass)) > 0)
            {
                var tempField = new MessageValueField(BitConverter.ToUInt16(items[i], 0), prop.Name);
                prop.SetValue(this, Convert.ChangeType(tempField, prop.PropertyType), null);
            }
            i++;
        }
    }

     private IEnumerable<PropertyInfo> determineCanMessageValueFields()
            {
                //Get all properties with the
                //custom attribute [IsValueField]
                return this.GetType().GetProperties()
                                     .Where(p => p.GetCustomAttributes(false)
                                     .Count(x => x.GetType() == typeof(IsValueField)) > 0)
                                     .OrderBy(x => ((IsValueField)x.GetCustomAttributes(false)[0]).ValueFieldIndex);
            }

 public object ToType(Type conversionType, IFormatProvider provider)
        {
            //...only convert if the conversion type is a BitmaskValueFieldClass
            if (conversionType.GetCustomAttributes(false).Count(x => x.GetType() == typeof(BitmaskValueFieldClass)) == 0)
            {
                throw new NotImplementedException("The conversion is only available for conversion types with the BitmaskValueFieldClass attribute");
            }

            //...create an instance of the conversion type
            var instance = Activator.CreateInstance(conversionType);

            //...go thru each property and set the value
            foreach (var item in instance.GetType().BaseType.GetProperties())
            {
                item.SetValue(instance, this.GetType().GetProperty(item.Name).GetValue(this, null), null);
            }

            return instance;
        }

The method ConvertDataFrameToValueFields() is the sticking point. I know it is because of the prop.SetValue() and the ToType() IConvertible method calls. When I am removing the ConvertDataFrameToValueFields() method I gain the missing time I need to fulfill the project.

Is there a way to improve the whole thing? Problem is that the idea has to be as it is. In the ConvertDataFrameToValueFields() method I have to map the returning DataFrame, the DataBytes array, to the MessageValueField properties of the specific class. I'm getting all containing messagevaluefields by calling the ConvertDataFrameToValueFields().


texts: Python decorator for retrying w/exponential backoff

texts:
This is my first decorator in Python! I found some of it on the internet but have tweaked it to our needs.

Here is the couple concerns of mine:

Multiple python version compatibility
Is grabbing the self or arg[0] the best way to get the instance of the class?
Any other general improvements!

Here is the decorator.

import logging
import time

def retry_and_catch(exceptions, tries=5, logger=None, level=logging.ERROR, logger_attr=None, delay=0, backoff=0):
    """
    Retries function up to amount of tries.

    Backoff disabled by default.

    :param exceptions: List of exceptions to catch
    :param tries: Number of attempts before raising any exceptions
    :param logger: Logger to print out to.
    :param level: Log level.
    :param logger_attr: Attribute on decorated class to get the logger ie self._logger you would give "_logger"
    :param delay: initial delay seconds
    :param backoff: backoff multiplier
    """
    def deco_retry(f):
        def f_retry(*args, **kwargs):
            max_tries = tries
            d = delay
            exs = tuple(exceptions)
            log = logger
            while max_tries > 1:
                try:
                    return f(*args, **kwargs)
                except exs as e:
                    message = "Exception {} caught, retrying {} more times.".format(e.message, max_tries)

                    # Get logger from cls instance of function
                    # Grabbing 'self'
                    instance = args[0]
                    if not log and logger_attr and hasattr(instance, logger_attr):
                        log = getattr(instance, logger_attr, None)

                    if log:
                        log.log(level, message)
                    else:
                        print(message)

                    # Sleep current delay
                    if d:
                        time.sleep(d)

                        # Increment delay
                        if backoff:
                            d *= backoff
                    max_tries -= 1

            return f(*args, **kwargs)  # Final attempt will not catch any errors.
        return f_retry
    return deco_retry

Here is an example usage

class MyClass(object):
    _logger = logging.getLogger()

    @retry_and_catch([ValueError], logger_attr='_logger', delay=1, backoff=2)
    def my_func(self):
        raise ValueError('Unable to run my_func')

c = MyClass()
print(c.my_func())


texts:
I was just getting some products using entity framework and was wondering which would be better to do when getting the results, or if there is no difference.

Option 1 - Query the context directly

return dbContext
                    .PPCProducts
                    .Include(p => p.Attributes)
                    .Include(p => p.ChildProducts)
                    .Where(p => p.Attributes.FirstOrDefault(a => a.AttributeName.IndexOf(attributeName, StringComparison.InvariantCultureIgnoreCase) > -1) != null)
                    .OrderBy(p => p.ProductName)
                    .ToList();

Option 2 - Query the cache

// cache the products
var products = dbContext
   .PPCProducts
   .Include(p => p.Attributes)
   .Include(p => p.ChildProducts);
CacheHelper.Add("products", products, CacheDuration.Hours3);

// query the cache
return ((List<Product>)HttpContext.Current.Cache["products"]).Where(p => p.Attributes.FirstOrDefault(a => a.AttributeName.IndexOf(attributeName, StringComparison.InvariantCultureIgnoreCase) > -1) != null)
                    .OrderBy(p => p.ProductName)
                    .ToList();


texts:
I'm creating my own little toolbox for pinging IP interfaces (for the test, only in localhost). In the future I'm thinking of piping the output to a text file. But I'd like to focus on improving the performance for now.

For now, scanning a class A IP range is pretty fast, but for a B range (65025 addresses) it's very long. Taking in excess of 5 minutes.
Here is my code:

#!/usr/bin/python3

import threading
import os

# Define a function for the thread
def pingBox( threadName, host):
    response = os.system("ping -c 1 "+host)
    print('response for pinging %s is %s' %(threadName, response))
    if response == 0:
        print ('%s : is up' %host)
    else:
        print ('%s : is down' %host)
# Create one thread by ping
def createThread(host):
    try:
        tlist = []
        tlist.append(
            threading.Thread(
                target=pingBox,
                kwargs={
                    "threadName": "Thread:{0}".format(host),
                    "host":host
                }
        ))

        for t in tlist:
            t.start()

        for t in tlist:
            t.join()
    except Exception as e:
        print(e)

def rangeSelector(ipRange):
    if ipRange== 'A' or ipRange== 'a':
        for i in range (0,255):
            createThread('127.0.0.'+str(i))
    elif ipRange== 'B' or ipRange== 'b':
        for i in range (0,255):
            for j in range(0,255):
                createThread('127.0.'+str(i)+'.'+str(j))
    else:
        pass

if __name__ == "__main__":
    ipRange=input('Choose range A|B :')
    rangeSelector(ipRange)


texts:
Trying to improve my HTML and CSS.
Creating a Basic Table using CSS grid, to match as closely to this image:

Please ignore the color red and green in the rows and Some rows are missing since it was used with data inside a react application and since I only care about the HTML and CSS I copied only what was relevant.
Having trouble with expanding the last row.
I know it's a mess and a lot to improve.

.App {
  display: flex;
  justify-content: center;
  align-items: center;
}

.wrapper {
  background-color: rgb(243, 241, 241);
  border: 1px solid rgb(170, 167, 167);
  padding: 5px;
}

.table-border {
  background-color: rgb(170, 167, 167);
  border: 1px solid rgb(170, 167, 167);
  border-radius: 6px;
}

.table {
  display: grid;
  /* background-color:rgb(243, 241, 241); */
  border: 1px solid rgb(170, 167, 167);
  border-radius: 6px;
  font-size: 12px;
  grid-template-columns: auto auto auto auto;
  gap: 1px 0px;
  color: #444;
}

.table-footer {
  padding: 5px;
  background-color: rgb(243, 241, 241);
}

.th {
  margin-bottom: 3px;
}

.last {
  border-right: none;
}

.cell {
  padding: 5px;
  background-color: white;
}

.cell.th {
  background-color: rgb(243, 241, 241);
}

.top-left-corner {
  border-radius: 6px 0px 0px 0px;
}

.top-right-corner {
  border-radius: 0px 6px 0px 0px;
}

.bottom-right-corner {
  border-radius: 0px 0px 6px 0px;
}

.bottom-left-corner {
  border-radius: 0px 0px 0px 6px;
}

Agent ID

Country

Address

Date

007

Brazil

        Avenida Vieira Souto 168 Ipanema, Rio de Janeiro

Dec 17, 1995, 9:45:17 PM

005

Poland

Rynek Glowny 12, Krakow

Apr 5, 2011, 5:05:12 PM

007

Morocco

27 Derb Lferrane, Marrakech

Jan 1, 2001, 12:00:00 AM

005

Brazil

Rua Roberto Simonsen 122, Sao Paulo

May 5, 1986, 8:40:23 AM

10


texts: Algorithm to calculate semi perfect integers, lack of efficiency

texts:
I'm working on an algorithm to calculate weird numbers, and to do so there are several properties that needs to be calculated, one of them being, if it is NOT a semi-perfect/pseudoperfect number.

My code can surely be done a lot more effectively because semi perfect numbers have very interesting properties. The first one being, every multiple of a semiperfect number is semiperfect. So for every semi perfect number calculated, the multiple of that number can be stored so it will not have to be recalculated.

What I don't know is if there is a way to calculate if a number is NOT a semi perfect number without having to calculate if it is. It really is ineffective to calculate if a number is semi perfect, just to know if it is NOT.

Imagine infinity, which has infinite valid divisors, to prove if it is a semi perfect number would take infinite amount of calculations, but would proving the opposite also take infinite amount of calculations?

Anyways here is my code (written in Java) which will return a boolean indicating whether or not a number is semi perfect:

/**
 *
 * @param x
 *          a number to test if it is semiperfect or not.
 * @param list
 *          this is a array of the factors of x (e.g factors of 6 are 3, 2, 1 excluding itself).
 * @return true if x is semiperfect, false otherwise.
 */
public static boolean isSemiPerfect(int x, List<Integer> list) {
    if (x == 0)
        return true;
    for (int i = 0; i < list.size(); i++) {
        int temp = list.remove(i);
        if (isSemiPerfect(x - temp, list)) // using recursion
            return true;
        list.add(i, temp);
    }

    return false;
}

It seems like it is not possible to create a more effective algorithm to check if a number is NOT semi perfect, on the other hand, my current algorithm to check if a number is semi perfect or not can be improved.

I believe semi perfect numbers have some properties that would prevent the need to calculate every number, for instance. So far NO weird number has been discovered which is a odd number.

So unless the number in question (x) is above 1.8 * 1019, every odd number doesn't have to be checked if it is semi perfect or not, because every weird number below that is even.

Taking a look at this, a list of properties can be found, which can reduce the amount of numbers that needs to be checked.

I've realized that it will be hard to eliminate the calculation aspect completely, but can be reduced a lot. So I would like to have help with my algorithm to improve it, and perhaps implement a few of these properties to reduce the need to check every single number.


texts: Get first DateTime by given weekdays and a starttime

texts:
At work there is an input-system where customers are able to specify weekdays and a starting time for an event. The weekdays are integers in the range from 1 (Monday) to 7 (Sunday).
After the customer has given the needed input, I need to calculate the next possible DateTime for the event. If the event is on the same day as today and the current time is not yet over the submitted starting-time, the next possible DateTime would be today.

This is what I have came up with, but it looks awful and complicated. You can obviously shorten the linq-queries a little, but i let the intermediate objects in there for sake of debugging.

public static class Test
{
    public static void Main( string[] args )
    {
        var now = DateTime.Now;
        var startTimes = new List<TimeSpan> {
            now.TimeOfDay ,                                     // get the next possible starting point
            now.TimeOfDay.Add( new TimeSpan( 0 , 1 , 0 ) ) ,    // starting point is today
        };
        var weekdaysList = new List<int[]> {
            new [] { 1 , 4 , 5 } ,
            new [] { 1 , 2 } ,
        };

        foreach( var weekdays in weekdaysList )
        {
            foreach( var startTime in startTimes )
            {
                var dt = GetNext( weekdays , startTime );
            }
        }
    }

    public static DateTime GetNext( int[] weekdays , TimeSpan startTime )
    {
        // convert to german format (Monday:1 - Sunday:7)
        var currentWeekDay = (int)DateTime.Now.DayOfWeek;

        if( currentWeekDay == 0 )
            currentWeekDay = 7;

        // if today, and not yet passed, return todays starting time
        if( weekdays.Contains( currentWeekDay ) )
        {
            var today = DateTime.Now.Date.Add( startTime );

            if( DateTime.Now < today )
                return today;
        }

        // calculate the day index and keep the added days around (better debugging)
        var days = Enumerable.Range( 0 , 7 )
            .Select( addedDays => new { addedDays , dayIndex = ( currentWeekDay + addedDays ) % 7 } )
            .ToArray();
        // only days that are specified
        var validDays = days
            .Where( x => weekdays.Contains( x.dayIndex ) )
            .ToArray();
        // the first day is the one that has the least days added
        var daysToAdd = validDays.First().addedDays;
        // but we already sorted out today, so the next possible day is the second (if exists) or 1 week/ 7 days later
        if( daysToAdd == 0 )
        {
            if( validDays.Count() > 1 )
                daysToAdd = validDays.ElementAt( 1 ).addedDays;
            else
                daysToAdd = 7;
        }

        return DateTime.Now.Date
            .AddDays( daysToAdd )
            .Add( startTime );
    }
}

I feel like I am missing some obvious shortcuts or linq-fu to shorten this code down and make it easier understandable.

I let this code as it is, but it was bugging me the whole day, how could I improve this?

Only the basic algorithm in the GetNext()-Method is relevant, no error-checking etc.


texts: Convert object array to hash map using lodash

texts:
The use case is to convert an array of objects into a hash map where one property is the key and the other property is the value. Common case of using this is converting a "link" object in a hypermedia response into a hash map of links.

jsfiddle

function toHashMap(data, name, value) {
    return _.zipObject(_.pluck(data, name),
                       _.pluck(data, value));
}

function toMap(data, name, value) {
    return _.reduce(data, function(acc, item) {
        acc[item[name]] = item[value];
        return acc;
    }, {});
}

var data = [
    { rel: 'link1', href: 'url1'},
    { rel: 'link2', href: 'url2'},
    { rel: 'link3', href: 'url3'},
    { rel: 'link4', href: 'url4'},
];

console.log(toHashMap(data, 'rel', 'href'));

console.log(toMap(data, 'rel', 'href'));

toHashMap appears much more readable, but less efficient. toMap seems to have the best efficiency at the expense of readability.

Is there a more elegant solution - i.e. both readable and efficient? I suspect that Lodash might have a function to do this already, but I haven't found anything like this after looking at the API documentation.


texts:
This arises from the SO Question subclassing pathlib.Path.

The pathlib sources  show that Path, when invoked, selects one of its subclasses, WindowsPath or PosixPath, to invoke in place of itself, within it's __new__ method. The following diagram shows a rough idea, with black lines indicating inheritance, red the constructor and green the instance returned.

Kevin points out that while this works for Path itself it prevents any subclass from having the same functionality. Now I'm not entirely clear as to why this is and Kevin does not offer an explanation. Presumably the __new__ method is called before the MRO is setup and one can not rely on super to do the right thing just yet, namely bumping up to the super classes __new__ to select the appropriate subclass.

The answers provided for the question itself include the following alternatives and I'm curious as to which is the best method/better practice.

Since everyday should be Christmas let's Wrap the class (a.k.a. Encapsulation/Clojures). I find quite often this is actually the go to answer for a lot of inheritance questions which I feel kinda defeats the point of subclassing as one then has to manually expose the wrapped classes methods.

from pathlib import Path as _Path_

class Path():
 def __init__(*args, **kvps):
  super().__init__(*args, **kvps)
  self._path_ = _Path_(*args, **kvps)

Instantiate the type of an instantiated class. This is a bit of trickery as you're invoking the class you plan to subclass. It selects the final class for you and you then determine the type it selected and subclass that.

from pathlib import Path

class Path(type(pathlib.Path())):
 pass

Tack on the required features to the selected class. This is roughly what projetmbc did.

from pathlib import Path as _Path_, PosixPath, WindowsPath

class Path(_Path_):
 def __new__(cls, *args):
  if cls is Path:
    cls = WindowsPath if os.name == 'nt' else PosixPath
setattr(cls, "extramethod", _extramethod)
return cls._from_parts(args)

The following is probably a simpler means of achieving the same goal.

Path.extramethod = _extramethod
# Or possibly
WindowsPath.extramethod = _extramethod
PosixPath.extramethod = _extramethod

In the same vane we could simply copy the __new__ method from Path the pathlib sources but that just screams bad practice.
There is one solution missing from the suite of answers there that Kevin hints towards which is to specify the missing attribute reported in the original error message.

from pathlib import Path as _Path_, _windows_flavour, _posix_flavour
import os

class Path(_Path_):
 _flavour = _windows_flavour if os.name == 'nt' else _posix_flavour

BKSpurgeon prompted the following strategy. This sweeps the underlying API details away which is quite nice.

from pathlib import Path as _Path_, PosixPath as _PosixPath_, WindowsPath  as _WindowsPath_
import os

class Path(_Path_) :
 def __new__(cls, *args, **kvps):
  print("Path*")
  return super().__new__(WindowsPath if os.name == 'nt' else PosixPath, *args, **kvps)

class WindowsPath(_WindowsPath_, Path) :
 pass

class PosixPath(_PosixPath_, Path) :
 pass

The figure below illustrates how the interaction plays out in this case. Basically the constructor in Path* selects one of it's sub-classes, WindowsPath* or PosixPath*, whose MRO map back to Path* and Path and the respective intermediate subclass, WindowsPath or PosixPath.

I feel (1) is kind of cop out, (2) is a bit of a hack, (3)
 and (4) seem the better approaches but require peaking under the hood (5) is probably the best as it is quite clean.

If it's possible could one elaborate upon which method 1-5, or if applicable their sub-methods, should one really employ here. The real test is probably checking the MRO in each case and that the final instance includes all the subclasses methods and attributes. I'm quite convinced that pathlib should really be using Metaclasses under the hood and would be keen to hear any commentary upon this aswell.


texts: Searching a string for any permutation of words

texts:
Given a string and an array of words, return all indexes in string for which a concatenation of all words in the array,
  in any order (so ["eensie", "weensy", "spider"] has six orderings) can be matched. All words will be the same length.

I am new to programming so please tell me where my big slow down points are. I still am failing the time test.

 var findSubstring = function(s, words) {
         var concatLength =
         for (var i = 0; i < words.length; i++){
         concatLength += words[i].length;
       } //concatLength is now length of all possible concatentations
       var stringLength = s.length;
       var answers = [];

       if (concatLength > stringLength || concatLength === 0){
           return answers;
       }  //outlier cases where answer is inevitably an empty array
         var wordLength = words[0].length  //each word is the same length
         var currentPerm;  //this will be used in permutation function we call
       for (var i = 0; i < stringLength + 1 - concatLength; i++){
           try { //if a match is found in recursive permutations function, an object of type TrueValue is thrown up the stack
             wordsInString(words.slice(), -1, s.substr(i, concatLength));
           }
           catch(e){
               if (e.constructor === TrueValue)
                   answers.push(i);
               else
                  throw e;
           }

       }
       function TrueValue() { //constructor of instances to be thrown up stack in case of match
       }
       function wordsInString(words, index, string){ //permutations function
         if (index === -1)  //In each loop outside it is called with -1 as index, so we reset currentPerm to be empty
                    currentPerm = [];
         if (words.length === 0){  //if currentPerm is full, check if it matches string.  If so throw instance of TrueValue up the stack
                   if (currentPerm.join("") === string)
                       throw new TrueValue();
               }
          for (var i = 0; i < words.length; i++){
            if (string.substr(0,(currentPerm.length + 1) * wordLength) === currentPerm.join("") + words[i]){ //if what is already in currentPerm were to have this word concatenated onto it, would it be potential match of index of string we are currently on?  If so, move this word off of words array and onto currentPerm.  Continue to try all possible concatenations of words we have left via recursion
                     currentPerm.push(String(words.splice(i, 1)));
                     wordsInString(words, i, string);
                   }
               }
               if (index !== -1) //unless this is the first call to wordsInCurrentString, take last word of currentPerm off and move it back onto the place it was on in words before this particular call was made
                   words.splice(index, 0, currentPerm.pop());
               else
                   return false;
           }
       return answers;
    };


texts: Parallelizing identical long-running tasks with Go channels

texts:
I have written a program in Go to compute the discrete logarithm mod primes (find \$x\$ such that \$h=g^x\mod p\$), and the algorithm I am using can be easily parallelized. Essentially, I am trying to find a value \$a\$ satisfying some slow function, where \$a < 2^{20}\$; rather than check these one by one, I would like to dispatch a number of goroutines to check concurrently.
I haven't written a ton of programs using Go channels before, so I am mostly looking for suggestions about proper usage of channels with goroutines. My actual program is much longer and contains additional math and processing that isn't relevant to my question. If necessary, however, I am happy to post the full code.
Specific things I am wondering about:

Is there a standard way of determining how many goroutines I should spawn for running such nearly-identical tasks? Specifically, is it best to spawn approx. number of CPUs (4), or is the standard practice to have a goroutine spawned for each value I check? (i.e. move the goroutine inside the main loop, rather than feeding values through a channel; that would be \$\approx 2^{20}\$ calls.) I have heard the adage "goroutines are not threads" but I am not sure to what extent that can be (ab)used. I am aware I could performance-tune this parameter, but I'm curious how this question is usually answered when prototyping software.

I have buffered the tx channel so that, if multiple goroutines find a solution at approximately the same time, they don't deadlock waiting for additional reads from tx (I only care about one solution, but there may be many). There isn't a way to block writes to a channel, is there? Earlier, I was getting program panics after trying to write to a closed channel.

I have a single rx channel, to send data to my goroutines, which I close when I find my first solution. Is this the proper way to do so? I am aware that closing a channel only prevents further writes to it, not future reads. My goal is to have all goroutines stop once the first one completes.

In addition, is this single-sender/multiple-receiver structure acceptable? I'm not aiming for optimal load balancing, of course. Another thing I had tried earlier was to create multiple receivers \$rx_i\$ for each of \$N\$ goroutines, and assign \$a\$ to \$rx_{a \% N}\$. But that presupposes that each goroutine will take equal amounts of time, which isn't true in general.

Pseudocode:
package main

import (
    ...
)

func process_equation(rx <- chan *big.Int, tx chan *big.Int) int {
    for a := range rx {
        v := very_slow_function_call(a) // returns bool

        if v {
            // found it!
            tx <- fast_function_call(a) // returns big.Int
            return
        }
    }
}

func main() {
    NUM_GOROUTINES := 4

    rx := make(chan *big.Int)
    tx := make(chan *big.Int, NUM_GOROUTINES)

    var wg sync.WaitGroup
    wg.Add(NUM_GOROUTINES)

    for i := 0; i < NUM_GOROUTINES; i++ {
        go func() {
            process_equation(rx, tx)
            wg.Done()
        }()
    }

    a := big.NewInt(0)
    one := big.NewInt(1)
    solution := new(big.Int)
    done := false

    // nonblocking read of `tx`; increment `a` and send otherwise
    for !done {
        select {
        case solution = <-tx:
            close(rx)
            done = true
        default:
            // increment
            a.Add(a, one)
            rx <- new(big.Int).Set(a)
        }
    }

    fmt.Println("a =", solution)

    wg.Wait() // wait for other goroutines to exit

}

Thank you!


texts: Split redirecting to multiple files in bash

texts:
A function mycommand which runs command and:

Gives me three log-files which are:

*.stdout.log: everything from stdout
*.stderr.log: everything from stderr
*.full.log: everything (i.e., both stderr and stdout)

Prints all output to screen

The idea is that I can quickly see through the errors, skim for additional info in stdout. But in some cases both (stdout and stderr) messages should be seen as one as it gives context, thus I want a third file to do that. For real-time overview I obviously want to see it on my screen too.

This works but it is rather clumsy and doesn't look nice. I'm unsure whether this is the right way to do it or I should improve the code.

The snippet is from my *.*shrc.

mycommand () { command "$@" \
          > >(tee command_"$@"_$(date +%F_%T).stdout.log command_"$@"_$(date +%F_%T).full.log) \
          2> >(tee command_"$@"_$(date +%F).stderr.log command_"$@"_$(date +%F_%T).full.log >&2 ) } \


texts: Check string value of boolean to a mapped enum

texts:
In a project, a boolean can be mapped to an enum to display a custom string for true and false.
If I have a string interpretation of a value, I have a method that is checking against the custom enum names or/and against regular boolean expressions like true, false, 0 and 1.

The method looks like this

public Boolean createParameterObjectValue(String value) {
    if (getMetaData().getValidValues().isAvailable() && getMetaData().getValidValues().getType() == ValidValues.Type.ENUM) {
        if (getMetaData().getValidValues(EnumValidValues.class).getEnumName(1).equalsIgnoreCase(value)) {
            return true;
        }
        if (getMetaData().getValidValues(EnumValidValues.class).getEnumName(0).equalsIgnoreCase(value)) {
            return false;
        }
        //TODO refactor redundance
        return !("0".equals(value) || "FALSE".equalsIgnoreCase(value));
    } else {
            return !("0".equals(value) || "FALSE".equalsIgnoreCase(value));
    }
}

First I'll check if the object in my project (a parameter) that is handling the boolean value, has defined values and has an enum mapping.

If this is true, compare the value to the enum names. If none of them equals the given value,I assume that the given string is "0","1","false" or "true". The same happens if the parameter does not have an enum mapping.

As you see from the TODO comment I'm not really happy with the redundancy, even if it doesn't really affect the performance. How could I remove the redundancy from this code?


texts: Efficient way of code reuse for finding the largest prime factor

texts:
I was doing timing with variations of function largest_prime_factor. I was able to write a better one largest_prime_factor2. There were some repetitions in the new function so I wrote another function largest_prime_factor3.

I thought the 3rd one has to be faster than the 2nd because I broke it up into more functions but it wasn't faster but slower.

I wanted to know whether my method of code reuse is good or not?
Is there a better way of reusing code in Python?
Did I miss something due to which the new function became slower?

My functions alongwith the testing() function used to test all three.

def largest_prime_factor(num):
    '''returns the largest prime factor of a number'''
    ans = 0
    if num % 2 == 0:
        ans = 2
        num /= 2
        while num % 2 == 0:
            num /= 2

    i = 3
    while i <= num:
        if num % i == 0:
            ans = i
            num /= i
            while num % i == 0:
                num /= i

        i += 2

    return ans

def largest_prime_factor2(num):
    '''returns the largest prime factor of a number'''
    ans = 0
    if num % 2:
        pass
    else:
        ans = 2
        while True:
            num //= 2
            if num % 2:
                break

    i = 3
    while i <= num:
        if num % i:
            pass
        else:
            ans = i
            while True:
                num //= i
                if num % i:
                    break

        i += 2

    return ans

def largest_prime_factor3(num):
    '''returns the largest prime factor of a number'''
    def check(j):
        nonlocal ans
        nonlocal num
        if num % j:
            return
        ans = j
        while True:
            num //= j
            if num % j:
                return
    ans = 0
    check(2)
    i = 3
    while i <= num:
        check(i)
        i += 2

    return ans

def testing():
    from timeit import Timer
    import random

    def tests(f, times):
        def test1(f):
            f(random.randint(1, 1000))
        def test2(f):
            f(random.randint(100000, 1000000))

        print(f.__name__)
        print(Timer(lambda: test1(f)).timeit(number = times))
        print(Timer(lambda: test2(f)).timeit(number = times//10))
        print()

    tests(largest_prime_factor, 10000)
    tests(largest_prime_factor2, 10000)
    tests(largest_prime_factor3, 10000)

if __name__ == "__main__":
    testing()

The timing results that I found:

largest_prime_factor
0.338549207387318
16.599112750324068

largest_prime_factor2
0.21575289594063918
12.086949738861868

largest_prime_factor3
0.36032199674939847
18.893444539398857

This format of results is produced by the testing function. See that for details.


texts: Two error-reporting conventions for a command-parser

texts:
I need to implement some function and I would like to report about a fail made inside a function. If function doesn't fail I need to get a some result (for example, std::string). I see two ways to implement function:

// 1. report with exception
std::string foo() {
  std::string ret;
  ... // solving str
  if (is_fail())
    throw ...;
  return ret;
}

// 2. report with return value
bool foo(const std::string &str) {
  ... // solving str
  return is_fail();
}

What way is more preferable and why? Or, maybe, there is the best way I didn't write?

The following is the original code for both cases.

namespace fs = boost::filesystem;
namespace po = boost::program_options;

/////////////////////////////////////////////////
// 1. report with exception
fs::path parse(int argc, char *argv[]) {
  fs::path ret;
  po:options_description desc("Program options");
  desc.add_options()
    ("help,h", "Show help")
    ("output,o", po::value<fs::path>(&ret), "Output folder")
    ;
  po::variables_map vm;
  const po::parsed_options opts = po::command_line_parser(argc, argv).options(desc).run();
  po::store(opts, vm);
  ...
  return ret;
}

int main(int argc, char *argv[]) {
  fs::path output;
  try {
    output = parse(argc, argv);
  } catch (const std::exception &e) {
    cout << e.what() << std::endl;
    return 1;
  }
  ...
}

//////////////////////////////////////////////////////
// 2. report with return value
bool parse(int argc, char *argv[], fs::path &output) {
  po:options_description desc("Program options");
  desc.add_options()
    ("help,h", "Show help")
    ("output,o", po::value<fs::path>(&output), "Output folder")
    ;
  po::variables_map vm;
  try {
    const po::parsed_options opts = po::command_line_parser(argc, argv).options(desc).run();
    po::store(opts, vm);
  } catch (const std::exception &e) {
    cout << e.what() << endl;
    return false;
  }
  ...
  return true;
}

int main(int argc, char *argv[]) {
  fs::path output;
  if (!parse(argc, argv, output))
    return 1;
  ...
}

Actually speed is not critical here and parse function performs just once. Maybe, there is not big deal to choose right answer. However, I would like to know what good practice is.


texts: Translating month number into month name

texts:
Time is very important from times immemorial. Doing great things and making it happen in less time is more important as it can mean less effort. So I really like to know which way is faster and more efficient in the following codes, and I would happy to know any other way we can achieve the same code:

$month=date('m');
//Using If..else
 if($month==1){
    echo "January";
}elseif($month==2){
    echo "February";
}elseif($month==3){
    echo "March";
}elseif($month==4){
    echo "April";
}elseif($month==5){
    echo "May";
}elseif($month==6){
    echo "June";
}elseif($month==7){
    echo "July";
}elseif($month==8){
    echo "August";
}elseif($month==9){
    echo "September";
}elseif($month==10){
    echo "October";
}elseif($month==11){
    echo "November";
}else{
    echo "December";
}

//Using Switch
switch($month){
case 1:
    echo "January";
break;
case 2:
    echo "February";
break;
case 3:
    echo "March";
break;
case 4:
    echo "April";
break;
case 5:
    echo "May";
break;
case 6:
    echo "June";
break;
case 7:
    echo "July";
break;
case 8:
    echo "August";
break;
case 9:
    echo "September";
break;
case 10:
    echo "October";
break;
case 11:
    echo "November";
break;
default:
    echo "December";
break;
}

//Using Array
$month_s=array(1=>"January",2=>"February",3=>"March",4=>"April",5=>"May",6=>"June",
7=>"July",8=>"August",9=>"September",10=>"October",11=>"November",12=>"December");
echo isset($month_s[$month]) ? $month_s[$month] : '';


texts:
I implemented and and or:

-- or is like and, only it returns True if
-- any of the boolean values in a list is True.
or' :: [Bool] -> Bool
or' []     = False
or' (x:xs) = x || or' xs

--and takes a list of boolean values and returns True only if
-- all the values in the list are True.
and' :: [Bool] -> Bool
and' [] = False
and' (x:xs) = x && and' xs

Is pattern matching the most elegant solution here?

Also, should or' [] and and' [] return False? It makes sense for them to do so when passing in a non-null input.

Example: or' [False, False]

But, how about the behavior of or' [] or and' []? Does False make sense here?


texts:
I've been chewing through a bit of The Little Schemer and the Peano examples got me thinking about operation size and time.

I got some help on making Peano Multiplication linear -- however (time ...) didn't show much difference between a lexically scoped version and the let-loop version.

I do however find a massive difference between the lexically scoped and let-loop versions when minting a Peano Exponent function.

The obvious question is why it makes such a difference (or perhaps it does not and my attempt at a lexically scoped Peano Exponent has some fatal error)?

-- i had thought i understood what the let-loop was doing in terms of storing the value in the parent enclosure (making the two roughly equivalent); in which way is this wrong?

;; lexically scoped version of Peano Exp
(define (exxp-lex b ex)
  (define (exxp-aux ex prod)
    (cond
      ((zero? ex) 1)
      ((= ex 1) (mX-let b prod))
      (else
        (exxp-aux (- ex 1) (mX-lex b prod)))))
  (exxp-aux ex 1))

;; let version of Peano Exp
(define (exxp-let b ex)
  (let loop ((ex ex)
              (prod 1))
    (cond
      ((zero? ex) 1)
      ((= ex 1) (mX-let prod b))
      (else
        (loop (- ex 1) (mX-let prod b))))
             ))

If it's relevant, I am using petite-chez scheme.

For reference, here are the Peano Multiplication functions.

;; a lexically scoped version Peano Multiplication
(define (mX-lex n m)
  (define (mX-aux m product)
    (if (zero? m)
      product
      (mX-aux (- m 1) (+ product n))))
  (mX-aux m 0))

;; using let for Peano Mult
(define (mX-let n m)
  (let loop ((m m)
             (product 0))
    (if (zero? m)
      product
      (loop (- m 1) (+ product n)))))


texts: Replacing part of a string with filler characters

texts:
I came up with this function rangedReplace as an exercice to use recursion and try different ways to make it work (I made at least 3 completely different versions). I think this version is the best but I have a feeling I can improve the way the functions/arguments are handled especially in the censor and in the main functions. How can I get these functions to be more idiomatic Haskell-way of doing, ?

-- Replace the letters in the range [from:to[ ("to" not included) with chr
rangedReplace :: Int -> Int -> Char -> String -> String
rangedReplace from to chr str
    | from == to = str
    | otherwise  = (take from' str) ++ rangedReplace' chr n (drop from' str)
    where from' = min from to
          to'   = max from to
          n     = to' - from'

-- Helper function
rangedReplace' :: Char -> Int -> String -> String
rangedReplace' chr n str
    | n == 0    = str
    | str == "" = ""
    | otherwise = chr : (rangedReplace' chr (n-1) (tail str))

Usage example:

censor (from,to) = rangedReplace from to '*'

main = do
    putStrLn $ foldr id "Fork bombs" (map censor [(1,3),(6,8)])


texts:
I am taking a class on ruby and our assignment is to take user input and print out a polynomial. Wondering if I can get any feedback to how to improve my code.

class PolynomialElements
  attr_accessor :element, :size

  def printElement
    if size.to_i == 0
      num = "#{@element}"
    elsif size.to_i == 1
      if element.to_i.abs == 1
        num = "x"
      else
        num = "#{@element}x"
      end
    else
      if element.to_i.abs > 1
        num = "#{@element}x^#{@size}"
      elsif element.to_i.abs == 1
        num = "x^#{@size}"
      end
    end
  end
end

askAgain = true
polyArray = Array.new

while askAgain
  puts "How many numbers do you want to enter? "
  numString = gets
  num = numString.to_i
  while num > 0
    puts "Enter a value for the Polynomial "
    value = gets
    polyArray.push(value.chomp)
    num -= 1
  end
  outputArray = Array.new
  sizeOfArray = polyArray.length
  polyArray.each do |x|
    var = PolynomialElements.new
    sizeOfArray -= 1
    var.size = sizeOfArray
    if x.to_i != 0
      var.element = x
      if var.element.to_i > 0
        outputArray.push("+")
        outputArray.push(var.printElement)
      elsif var.element.to_i < 0
        outputArray.push(var.printElement)
      end
    end
  end

  if outputArray[0] == "+"
    outputArray.delete_at(0);
  end

  outputArray.each do |x|
    print x
  end
  puts

  puts "Enter y to enter new number or anything else to quit"
  cont = gets
  if cont.chomp != "y"
    askAgain = false
  else
    polyArray.clear
  end
end


texts: Locating empty field groups for saving data

texts:
The aim of the code below is to see if selected fields are empty so data can be saved in that field. Since I'm making a library system, I wanted to record the basic info on one record (all the books they have taken out so the ID's of them as well as author and title) but this proves to be quite tricky and quite long to code.

I was wondering whether there's an easier way to code this instead of the very long if loop. It would also help if I could use the same solution (obviously tweaked) when displaying their loans on the form as well.

procedure Save;
{ procedure to locate which field groups are empty so product and loan informati
 - on can be saved }
begin
  if LoanRecords.ProductID1 ='' then
  begin
    LoanRecords.ProductID1 := ProductRecords.UniqueId;
    LoanRecords.ProductTitle1 := ProductRecords.ProductTitle;
    LoanRecords.ProductAuthor1 := ProductRecords.ProductAuthor;
  end
  else if LoanRecords.ProductID2 = '' then
  begin
    LoanRecords.ProductID2 := ProductRecords.UniqueId;
    LoanRecords.ProductTitle2 := ProductRecords.ProductTitle;
    LoanRecords.ProductAuthor2 := ProductRecords.ProductAuthor;
  end
  else if LoanRecords.ProductID3 = '' then
  begin
    LoanRecords.ProductID3 := ProductRecords.UniqueId;
    LoanRecords.ProductTitle3 := ProductRecords.ProductTitle;
    LoanRecords.ProductAuthor3 := ProductRecords.ProductAuthor;
  end
  else if LoanRecords.ProductID4 ='' then
  begin
    LoanRecords.ProductID4 := ProductRecords.UniqueId;
    LoanRecords.ProductTitle4 := ProductRecords.ProductTitle;
    LoanRecords.ProductAuthor4 := ProductRecords.ProductAuthor;
  end
  else if LoanRecords.ProductID5 ='' then
  begin
    LoanRecords.ProductID5 := ProductRecords.UniqueId;
    LoanRecords.ProductTitle5 := ProductRecords.ProductTitle;
    LoanRecords.ProductAuthor5 := ProductRecords.ProductAuthor;
  end
  else if LoanRecords.ProductID6='' then
  begin
    LoanRecords.ProductID6 := ProductRecords.UniqueId;
    LoanRecords.ProductTitle6 := ProductRecords.ProductTitle;
    LoanRecords.ProductAuthor6 := ProductRecords.ProductAuthor;
  end
end;

This is the record structure-

  TLoan = record
    LoanUniqueId: integer; { of loan record }
    DateDue: TDateTime; { date when products are due to be returned }
    MemberUniqueID: integer; { from MemberDetails File }
    MemberName: string[50]; { from MemberDetails File }
    MemberSecondName: string[50]; { from MemberDetails File }
    AmountBorrowed: integer; { amount of items currently on loan }
    { Product 1 }
    ProductID1: integer; { product ID }
    ProductTitle1: string[80]; { product title }
    ProductAuthor1: string[80]; { product author }
    Return1: boolean;
    { has book been returned- true/false- set to false until book is returned }
    { Product 2 }
    ProductID2: integer;
    ProductTitle2: string[80];
    ProductAuthor2: string[80];
    Return2: boolean;
    { Product 3 }
    ProductID3: integer;
    ProductTitle3: string[80];
    ProductAuthor3: string[80];
    Return3: boolean;
    { Product 4 }
    ProductID4: integer;
    ProductTitle4: string[80];
    ProductAuthor4: string[80];
    Return4: boolean;
    { Product 5 }
    ProductID5: integer;
    ProductTitle5: string[80];
    ProductAuthor5: string[80];
    Return5: boolean;
    { Product 6 }
    ProductID6: integer;
    ProductTitle6: string[80];
    ProductAuthor6: string[80];
    Return6: boolean;
  end; { of TLoan- loan details }


texts: Google News scraper to fetch links with similar stories

texts:
The following code takes either a URL or the title to an existing news article.

Searches Google News using the title.
Collects all links from search results.

import urllib2
from lxml import html
import requests

def get_page_tree(url=None):
    page = requests.get(url=url, verify=False)
    return html.fromstring(page.text)

def get_title(url=None):
    tree = get_page_tree(url=url)
    return tree.xpath('//title//text()')[0].strip().split(' -')[0]

def find_other_news_sources(url=None, title=None):
    # Google forwards the url using <google_domain>/url?q=    <actual_link>. This might change over time
    forwarding_identifier = '/url?q='
    if not title:
        title = get_title(url=url)
    google_news_search_url = 'http://www.google.com/search?q=' + urllib2.quote(title) + '&tbm=nws'
    google_news_search_tree = get_page_tree(url=google_news_search_url)
    other_news_sources_links = [a_link.replace(forwarding_identifier, '').split('&')[0] for a_link in
                            google_news_search_tree.xpath('//a//@href') if forwarding_identifier in a_link]
    return other_news_sources_links


texts: One to one record mapping without any common column between two tables in SQL server

texts:
I'm trying to join two tables based on one to one mapping without any common column.

For example, I have 3 records in the first table and 2 records in the second table.

The mapping should be as follows:

As there is no third record in the second table, nulls should be displayed.

In order to implement this, I've tried the following code:

declare @FirstTable table (StudentId int, SubjectId int)
declare @SecondTable table (MarksId int, RankId int, LastRank int)

insert into @FirstTable values (1, 1)
insert into @FirstTable values (1, 2)
insert into @FirstTable values (1, 3)

insert into @SecondTable values (1, 4, 10)
insert into @SecondTable values (1, 5, 11)

;with XmlTable (RowNumber, StudentId, SubjectId) as
(
    select row_number() over(order by StudentId) as RowNumber, * from @FirstTable
)
,TechnicalIdsTable (RowNumber, MarksId, RankId, LastRank) as
(
    select row_number() over(order by MarksId) as RowNumber, * from @SecondTable
)
select x.StudentId, x.SubjectId, t.MarksId, t.RankId, t.LastRank from XmlTable x
left join TechnicalIdsTable t
on x.RowNumber = t.RowNumber

Based on the above code, I am able to achieve the output. Let me know whether this is a proper approach or not.

Here's a new example:

In this case, there are three students enrolled for sports, you can check the order in which they enrolled. But there are only two vacant sports available and the order in which they have to be selected.

Now using my query, which will be

declare @Students table (StudentId int, StudentName varchar(50), EnrolledOn datetime)
declare @Sports table (SportId int, SportName varchar(50))

insert into @Students values (1, 'John', '2013-05-25 10:00:00')
insert into @Students values (2, 'Jerry', '2013-05-25 14:30:00')
insert into @Students values (3, 'Jane', '2013-05-26 10:30:00')

insert into @Sports values (1, 'Golf')
insert into @Sports values (2, 'Foot ball')

;with Students (RowNumber, StudentId, StudentName, EnrolledOn) as
(
    select row_number() over(order by EnrolledOn) as RowNumber, * from @Students
)
,Sports (RowNumber, SportId, SportName) as
(
    select row_number() over(order by SportId) as RowNumber, * from @Sports
)
select s1.StudentId, s1.StudentName, s1.EnrolledOn, s2.SportId, s2.SportName from Students s1
left join Sports s2
on s1.RowNumber = s2.RowNumber

I'm getting the expected output.

My goal is to assign the 1st sport to the student who enrolled in the first and second sport to the second student, and for the third student there will be no sport.

Will this be proper now?


texts: TicTacToe where the computer plays random moves against itself

texts:
I wrote a quick program in Python to play against itself in a game of (random) tic-tac-toe.

It seems to work, but can you guys please look at it and let me know if I'm doing things the 'correct' (i.e. idiomatic) and efficient way.

import random

#  Tic Tac Toe

#  Board is laid out as:
#  0, 1, 2,
#  3, 4, 5,
#  6, 7, 8

winning_rows = [
    [0, 1, 2], [3, 4, 5], [6, 7, 8],    # Horizontal
    [0, 3, 6], [1, 4, 7], [2, 5, 8],    # Vertical
    [0, 4, 8], [2, 4, 6]                # Diagonal
    ]

def check_winner(board):
    for player in [1, 2]:
        for seq in winning_rows:
            for pos in seq:
                if (board[pos]!=player):
                    break
            else:
                return player

    #nobody won, check for draw (return 0 for draw, None for incomplete game)
    for pos in range(9):
        if (board[pos] == 0):
            return None

    #game is a draw
    return 0

def find_move(board, player):
    legal_moves = []

    for pos in range(9):
        if (board[pos] == 0):
            legal_moves.append(pos)

    return random.choice(legal_moves)

def make_move(board, move, player):
    board[move] = player

def write_board(board):
    #letter = {0: '-', 1: 'X', 2: 'O'}
    letter = "-XO"
    for row in range(3):
        for col in range(3):
            print letter[board[row*3+col]],
        print
    print

def play():
    board = []
    for pos in range(9):
        board.append(0)

    write_board(board)

    player = 1
    while True:
        move = find_move(board, player)
        make_move(board, move, player)
        write_board(board)
        winner = check_winner(board)
        if winner != None:
            if winner == 1:
                print "Player 1 (X) wins!"
            if winner == 2:
                print "Player 2 (O) wins!"
            if winner == 0:
                print "Game is a draw!"
            break
        player = 3 - player

play()


texts:
I have written this InsertSort program in F#.  It works, but I am not very happy with it.

let rec SubArrayBegin list n =
    list |> Seq.ofList |> Seq.take n |> List.ofSeq

let SubArrayEnd list n =
    List.rev (SubArrayBegin (List.rev list) ((List.length list) - n - 1))

let InsertSort list =
    let rec innerInsertSort list n =
        if n = (List.length list) then
            list
        else
            let key = List.nth list n
            let firstList = SubArrayBegin list n
            let (firstListA, firstListB) = List.partition (fun x -> x < key) firstList
            let remList = SubArrayEnd list n
            innerInsertSort (firstListA @ [key] @ firstListB @ remList) (n + 1)
    innerInsertSort list 1

[<EntryPoint>]
let main args =
    let a = [10; 2; 9; 1; 4; 5; -1]
    let b = InsertSort a
    List.iter (fun x -> printfn "%i" x) b
    0

List of annoyances:

@ symbol for joining the lists back.
If Condition being used instead of pattern matching.

I wonder if there is a better way of writing this.

Can you please review this and help me improve this code?


texts: Command and observer pattern to build installer wizard

texts:
I've done this mainly as an exercise to understand these design patterns. I'm writing a theoretical install wizard which will allow users to select different options throughout, and have it execute them all at the end. I think the correct way to do this would be to use a mixture of Command and Observer patterns.

I have a Command interface with just one method: "execute()". This will be implemented by all the different actions the installer might perform:

interface Command{
    public function execute();
}

class InstallRegistryKey implements Command{
    public function execute(){
        echo "installing a registry key\n";
    }
}

class AddDesktopShortcut implements Command{
    public function execute(){
        echo "adding a desktop shortcut\n";
    }
}

class InstallDependencies implements Command{
    public function execute(){
        echo "installing some dependencies\n";
    }
}

Then an abstract observer which adds commands to an internal list, and an Installer class which extends it:

abstract class AbstractObserver{
    protected $commands = array();

    public function notify(CommandInterface $command){
        $this->commands[] = $command;
    }

    abstract public function run();
}

class Installer extends AbstractObserver{

    public function run(){
        echo "starting installer\n";

        foreach($this->commands as $command){
            $command->execute();
        }
        echo "finished installing!\n";
    }
}

An abstract observable class which allows you to add/remove observers and notify them. It also allows you to attach a Command to the observable, which it will send to any Observers:

abstract class AbstractObservable{
    private $command;
    private $observers = array();

    //attach a command to this button
    public function __construct(CommandInterface $command){
        $this->command = $command;
    }

    //attach an observer to this button
    public function attach(AbstractObserver $observer){
        $this->observers[] = $observer;
    }

    //remove an observer from this button
    public function detach(AbstractObserver $observer){
        foreach($this->observers as $i=>$ob){
            if($ob == $observer){
                unset($this->observer[$i]);
            }
        }
    }

    //notify each observer of whatever has happened
    public function notify(){
        foreach($this->observers as $ob){
            $ob->notify($this->command);
        }
    }
}

Then we have a button class. This will be a button that users can click during the installer wizard to select various options (e.g. should we add a desktop shortcut, etc., etc.). It simply notifies its observers that its been clicked.

class Button extends AbstractObservable{
    //when the user clicks the button, notify observers
    public function click(){
        echo "clicked a button\n";
        $this->notify();
    }
}

Now, we can run the installer:

//create the installer
$installer = new Installer();

//create the buttons
$btn1 = new Button(new InstallRegistryKey());
$btn2 = new Button(new AddDesktopShortcut());
$btn3 = new Button(new InstallDependencies());

//attach the installer to the buttons
$btn1->attach($installer);
$btn2->attach($installer);
$btn3->attach($installer);

//now click some of the buttons
$btn1->click();
$btn3->click();

//now we can run the installer, using only the commands that were associated with the
//buttons we clicked. In this example the user asked only to install dependencies and
//registry key, but not the desktop shortcut.
$installer->run();

Does anyone have any feedback about this? Is this a "good" implementation?


texts: Pong game built on a minimal entity component system

texts:
This simple game is built on the ECS described here: Minimal entity component system, take 2

local ecs = require 'ecs'
local ui = require 'ui'

local entities = {}

local velocitySystem = ecs.createSystem(
  { 'position', 'velocity' },
  function (entity, pos, vel)
    pos.x = pos.x + vel.vx
    pos.y = pos.y + vel.vy
  end)

local rectangleRenderingSystem = ecs.createSystem(
  { 'position', 'rectangle' },
  function (entity, pos, rect)
    ui.drawRect(pos, rect)
  end)

local aiSystem = ecs.createSystem(
  { 'position', 'speed', 'ai' },
  function (entity, pos, speed)
    local closestBallPos
    for target, posB in ecs.each(entities, { 'position', 'ball' }) do
      if (not closestBallPos) or (posB.x > closestBallPos.x) then
        closestBallPos = posB
      end
    end
    pos.y = pos.y + (closestBallPos.y - pos.y) * speed
  end)

local inputSystem = ecs.createSystem(
  { 'position', 'player' },
  function (entity, pos)
    pos.y = ui.mouseY or 0
  end)

local outOfBoundsSystem = ecs.createSystem(
  { 'position', 'rectangle', 'velocity', 'ball' },
  function (entity, pos, rect, vel)
    if pos.x <= 0 then
      print('Right player scored')
      pos.x = 50
    elseif pos.x >= 100 then
      print('Left player scored')
      pos.x = 50
    end
  end)

local bounceSystem = ecs.createSystem(
  { 'position', 'rectangle', 'velocity', 'ball' },
  function (entity, pos, rect, vel)
    if pos.y <= 0 or pos.y >= 100 then
      vel.vy = vel.vy * -1
    end
  end)

local function checkCollision(posA, rectA, posB, rectB)
  local halfHeightA, halfHeightB = rectA.h / 2, rectB.h / 2
  local halfWidthA, halfWidthB = rectA.w / 2, rectB.w / 2
  if (posA.y + halfHeightA <= posB.y - halfHeightB) or
      (posA.y - halfHeightA >= posB.y + halfHeightB) or
      (posA.x + halfWidthA <= posB.x - halfWidthB) or
      (posA.x - halfWidthA >= posB.x + halfWidthB) then
    return false
  end
  return true
end

local collisionSystem = ecs.createSystem(
  { 'collidable', 'position', 'rectangle', 'velocity' },
  function (entity, col, pos, rect, vel)
    for target, posB, rectB in ecs.each(entities,
        { 'position', 'rectangle', 'solid' }) do
      if entity == target then next() end
      if checkCollision(pos, rect, posB, rectB) then
        vel.vx = vel.vx * -1
        vel.vy = vel.vy * -1
      end
    end
  end)

local ball = {
  ball = true,
  collidable = true,
  position = { x = 50, y = 33 },
  velocity = { vx = 1, vy = 1 },
  rectangle = { w = 2, h = 2 },
}

local leftPaddle = {
  player = true,
  solid = true,
  position = { x = 0, y = 50 },
  rectangle = { w = 4, h = 10 },
}

local rightPaddle = {
  ai = true,
  solid = true,
  speed = 0.5,
  position = { x = 100, y = 50 },
  rectangle = { w = 4, h = 10 },
}

table.insert(entities, ball)
table.insert(entities, leftPaddle)
table.insert(entities, rightPaddle)

ui.loop(function ()
  velocitySystem(entities)
  rectangleRenderingSystem(entities)
  aiSystem(entities)
  inputSystem(entities)
  outOfBoundsSystem(entities)
  bounceSystem(entities)
  collisionSystem(entities)
end)

I'm wondering if I have the right idea about how I should be using an ECS. If there are problems with the ECS itself, please address it in linked question rather than here.

The "ui" script that's required at the top is some uninteresting OpenGL/GLUT stuff using luaglut. I can post it if necessary, but it should be pretty clear what it's doing.

I realize there are lots of magic numbers. I don't care, it's just a throwaway project to make sure the ECS is doing its job. All of the coordinates and measurements are in percents, so just pretend I made constants named FIFTY_PERCENT and so on.


texts: Find relative filenames recursively in Emacs

texts:
I have a set of directories. For each directory I have a set of relative file names. I would like to select any of these relative filenames using completion, and then later reconstruct the absolute path of the filename.

In order to create a list of relative filenames for a given directory, I created this function:

(defun my-get-dir-files (dir pat &optional rel-dir)
"Finds relative filenames. Returns a list of relative filenames/pathnames to
 directory `dir' matching pattern `pat'. The variable `rel-dir` is only used internally
 by recursive calls and should usually not be supplied.

IMPORTANT: This function uses recursion. To avoid excessive copying of lists,
 the variable `files' is used as a dynamic list variable, and is assumed to be
 defined as non-lexical dynamic variable in the caller using a let binding"
  (let ((dir-files nil)
        (cur-dir nil))
    (unless rel-dir (setq rel-dir ""))
    (setq cur-dir (expand-file-name rel-dir dir))
    (setq dir-files (directory-files cur-dir nil nil t))
    (dolist (name dir-files)
      (unless (or (string= name ".") (string= name ".."))
        (let ((fn (expand-file-name name cur-dir)))
          (if (file-directory-p fn)
              (let ((new-rel-dir nil))
                (if (string= "" rel-dir)
                    (setq new-rel-dir name)
                  (setq new-rel-dir (concat rel-dir "/" name)))
                (my-get-dir-files dir pat new-rel-dir)) ;; recursive call
            (when (string-match pat name)
              (let ((rel-fn nil))
                (if (string= "" rel-dir)
                    (setq rel-fn name)
                  (setq rel-fn (concat rel-dir "/" name))
              (setq files (append files `(,rel-fn))))))))))))

Then I plan to use code like:

(let ((dir "/home/hakon/dir1")
      (files nil))
  (my-get-dir-files dir "\\.el$")
  files)

to set the list variable files.

One thing that worries me here is the use of the (non-lexical) dynamic variable files. Can or should this be avoided?

According to the manual I have violated this principle:

  If a variable has no global definition, use it as a local variable
  only within a binding construct


texts: Generate mask for non zero (or inverse) nibbles in integer

texts:
Apologies for the cryptic title, but the problem really is rather simple.
I have a 64 bit integer which I interpret as 16 4 bit nibbles, or a nibble array if you wish, and I needed generate a mask covering the nibbles which are zero, or the inverse.
I have already come up with a solution, but it seems to me that there has to be a better way.
uint64_t getNonZeroMask( uint64_t b )
{
    return ( ( ( b >> 2 | b ) >> 1 | ( b >> 2 | b ) ) & 0x1111111111111111 ) * 15;
}

The above is the most efficient I've found. I've tried numerous approaches, but they pretty much all use the same approach.
Just in case there should be any doubt what exactly I'm frying to do, a give value:
ex.
0x010203456000abc0

Should give the mask:
0x0f0f0ffff000fff0

or the inverse.
What I have works, of course, but I do believe it can be done better, and I'd very much like to know how. Preferably it would only involve bitwise operations. Intrinsics from bmi and similar are okay, but I haven't found anything that seems useful. It may be that I'm entirely in the wrong, and this is indeed the way of doing it, in which case I'd very much like to know that too.


texts: Implementing The Proper Undead's Cave Generator

texts:
I recently stumbled onto a very old article about procedural dungeon generation on this site. Unfortunately, the author did not provide any code, only a description of the algorithm he used. Wanting to use this in my game, I tried to write my own generator following their algorithm:

local random = math.random

local function grid()
    return {
        min = 0,
        max = 0,

        init = function(self, min, max)
            for i = min, max do
                self[i] = {}
            end

            self.min = min
            self.max = max
        end,

        set = function(self, x, y, c)
            if x >= self.min and x <= self.max then
                if y >= self.min and y <= self.max then
                    self[x][y] = c
                end
            end
        end,

        print = function(self)
            for y = self.max, self.min, -1 do
                for x = self.min, self.max do
                    io.write(self[x][y] or "#")
                end

                io.write"\n"
            end
        end
    }
end

local function point(x, y)
    p = {
        x = x,
        y = y,

        print = function(self)
            io.write("<" .. self.x .. ", " .. self.y .. ">\n")
        end,
    }

    setmetatable(p, {__eq = function(self, right)
        return self.x == right.x and self.y == right.y
    end})

    return p
end

local function contains_point(array, p)
    for i = 1, #array do
        if array[i] == p then
            return true
        end
    end

    return false
end

local function shuffle(array)
    local size = #array

    for i = 1, size do
        local swap = random(1, size)
        array[i], array[swap] = array[swap], array[i]
    end

    return array
end

local function offsets(p)
    return {
        point(p.x, p.y+1),
        point(p.x, p.y-1),
        point(p.x+1, p.y),
        point(p.x-1, p.y),
    }
end

local function circular_iterator_of(items, start)
    local index = start - 1
    return function()
        local ret =  items[index + 1]
        index = index + 1
        index = index % #items + 1
        return ret
    end
end

local function carve(list)
    local index = 1
    while index < #list + 1 do
        local currentPoint = list[index]
        local last
        if (index == #list) then
            last = true
        end

        local numChecks = random(last and 1 or 0, 4)
        local neighbors = circular_iterator_of(shuffle(offsets(currentPoint)), 1)

        for i = 1, numChecks do
            local neighbor = neighbors()

            if not contains_point(list, neighbor) then
                table.insert(list, neighbor)
            end
        end

        index = index + 1
    end
end

function generate_map(width, minTilesCarved, seed)
    local map = grid()
    map:init(-width/2, width/2)

    local start = point(0, 0)

    local carvedList = {}
    table.insert(carvedList, start)

    math.randomseed(seed)

    repeat
        carve(carvedList)
    until #carvedList > minTilesCarved

    for i = 1, #carvedList do
        p = carvedList[i]
        if i == 1 then
            map:set(p.x, p.y, "D")
        elseif i == #carvedList then
            map:set(p.x, p.y, "U")
        else
            map:set(p.x, p.y, ".")
        end
    end

    return map
end

map = generate_map(64, 170, os.time())

map:print()

First time posting here, please be somewhat gentle :)

Note:

While it doesn't appear to be on topic for this site, bonus points will be awarded to those who can suggest ways to make my algorithm produce results closer to those on the original site (my caves feel too chunky in general).

Ideal Caves:

My Results:


texts:
I'm currently following the tutorials over at RubyMonk, and one of the problems I need to solve is to write a subtract function that would meet these conditions:

  invoking subtract(4, 5) should return -1
  invoking subtract(-10, 2, 3) should return -15
  invoking subtract(0, 0, 0, 0, -10) should return 10

Coming from a traditional imperative programming background (C, Lua, Java, etc.), my first attempt would have been something like this:

def subtract *numbers
  start = numbers[0]
  tail  = numbers.drop(1)

  for i in tail do
    start -= i
  end

  return start
end

But, this just felt wrong in Ruby, and I don't doubt that it is. Trying to use a more Ruby-esque style, I thought it would be better to use some of Array's methods.

Here is my latest version:

def subtract *numbers
  (numbers.drop 1).inject(numbers[0]) { |x, y| x-y}
end

One thing to note is that this is essentially the same thing as above, I just moved most of the looping into Array#inject. To me, simply moving logic isn't a new style per se, and so conceptually this is nothing new to me.

Therefore my questions are:

Is this true Ruby style? If not, how could I make it so, and how would that new style differ from the current?
Is there any way to improve readability? ('Cause honestly the current version lacks quite a bit).


texts: SearchActivity to search through an ArrayList

texts:
I've coded this class that lets me search through an ArrayList displayed into a RecyclerView. This is the class:

public class SearchActivity extends AppCompatActivity {
    ArrayList<Accordo> chords;
    RecyclerView rv;
    SearchView sv;
    ArrayList<Accordo> filteredList;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.search_layout);

        /** gestisce la pubblicita */
        MobileAds.initialize(getApplicationContext(), "ca-app-pub-3940256099942544/6300978111");

        AdView searchBanner = (AdView) findViewById(R.id.search_ad);
        AdRequest adRequest = new AdRequest.Builder().build();
        searchBanner.loadAd(adRequest);

        /**-------------------------------*/

        Intent intent = this.getIntent();
        Bundle bundle = intent.getExtras();
        chords = bundle.getParcelableArrayList("chords");
        filteredList = bundle.getParcelableArrayList("chords");

        sv = (SearchView) findViewById(R.id.testo_ricerca);
        sv.setIconifiedByDefault(false);

        rv = (RecyclerView) findViewById(R.id.lista_ricerca);
        rv.setLayoutManager(new LinearLayoutManager(SearchActivity.this, LinearLayoutManager.VERTICAL, false));
        rv.setHasFixedSize(true);

        final SearchAdapter adapter = new SearchAdapter(this, chords);
        rv.setAdapter(adapter);

        //SEARCH
        sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                //FILTER AS YOU TYPE
                List<Accordo> filteredModelList = filter(chords, newText);
                adapter.setFilter(filteredModelList);
                return true;
            }
        });

        /** gestisce cosa succede quando un elemento della lista viene cliccato */
        ItemClickSupport.addTo(rv).setOnItemClickListener(new ItemClickSupport.OnItemClickListener(){
            @Override
            public void onItemClicked(RecyclerView recyclerView, int position, View v) {
                Intent intent = new Intent(SearchActivity.this, ChordActivity.class);
                Bundle bundle = new Bundle();
                bundle.putParcelable("selected", filteredList.get(position));
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });

    }

    private List<Accordo> filter(List<Accordo> models, String query) {
        query = query.toLowerCase();

        filteredList = new ArrayList<>();
        for (Accordo model : models) {
            final String text = model.getName().toLowerCase();
            if (text.contains(query)) {
                filteredList.add(model);
            }
        }
        return filteredList;
    }
}

As you can see from the code above, it is based on a filter that every time the user types something in the search box, creates a filteredList and puts it into the RecyclerView. Of course when the user did not type anything the filteredList should have contained the whole ArrayList chords

So I was getting an error (NPE) when I clicked on an Item while nothing had been typed into the search box, because the filteredList was null. I managed to solve it by having both:

chords = bundle.getParcelableArrayList("chords");

filteredList = bundle.getParcelableArrayList("chords");

I think this is a huge waste of memory and resources since we are talking about an ArrayList with ca 300 elements, each of which has 5 images, strings and sounds.

Is there a more efficient way to achieve the same result?


texts:
Challenge

https://leetcode.com/explore/interview/card/top-interview-questions-easy/93/linked-list/773/

  Given a linked list, determine if it has a cycle in it.

  To represent a cycle in the given linked list, we use an integer pos
  which represents the position (0-indexed) in the linked list where
  tail connects to. If pos is -1, then there is no cycle in the linked
  list.

  Example 1:

  Input: head = [3,2,0,-4], pos = 1 Output: true Explanation: There is a
  cycle in the linked list, where tail connects to the second node.

  Example 2:

  Input: head = [1,2], pos = 0 Output: true Explanation: There is a
  cycle in the linked list, where tail connects to the first node.

  Example 3:

  Input: head = [1], pos = -1 Output: false Explanation: There is no
  cycle in the linked list.

Follow up

Can you solve it using \$O(1)\$ (i.e. constant) memory?
Can you please review about performance?

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

namespace LinkedListQuestions
{
 public class ListNode
    {
        public int val;
        public ListNode next;

        public ListNode(int x)
        {
            val = x;
        }
    }

    [TestClass]
    public class HasCycleTest
    {
        [TestMethod]
        public void HasCycle()
        {
            ListNode head = new ListNode(3);
            head.next = new ListNode(2);
            head.next.next = new ListNode(0);
            head.next.next.next = new ListNode(-4);
            head.next.next.next.next = head.next; //2
            Assert.IsTrue(HasCycleClass.HasCycle(head));
        }

        [TestMethod] public void NoCycle()
        {
            ListNode head = new ListNode(3);
            head.next = new ListNode(2);
            head.next.next = new ListNode(0);
            Assert.IsFalse(HasCycleClass.HasCycle(head));
        }

        [TestMethod]
        public void OneItem()
        {
            ListNode head = new ListNode(3);
            Assert.IsFalse(HasCycleClass.HasCycle(head));
        }
    }

    public class HasCycleClass
    {
        public static bool HasCycle(ListNode head)
        {
            if (head == null || head.next == null)
            {
                return false;
            }
            ListNode slow = head.next;
            ListNode fast = head.next.next;
            while(fast!= null)
            {
                if (fast == slow)
                {
                    return true;
                }
                else
                {
                    slow = slow.next;
                    if (fast.next == null)
                    {
                        return false;
                    }
                    fast = fast.next.next;
                }
            }

            return false;
        }
    }
}


texts:
I have a class that reads key-value pairs from an Excel file. I want to store the values in variables and access them from the class instance.

I did this by putting in the constructor the method that reads the Excel file. Is this OK? AFAIK it's not a good practice to put methods in constructors.

public class ExcelReader{
    private Map<String, String> map = null;
    private String firstname;
    private String lastname;

    public ExcelReader(){
        map = new HashMap<String, String>();
        getExcelData();
        firstname = map.get("Firstname");
        lastname= map.get("Lastname");
    }

    private void getExcelData() { //reads data from excel and puts it in map
       //...
       map.put(key,value);
    }

}

This is how I want to get the values:

ExcelReader reader = new ExcelReader();
reader.firstname;


texts: Query for combining results of same query running across multiple databases

texts:
I wrote a query to run the same query across multiple databases and combine the results.  While it seems plenty quick I was wondering if there is a better way to do this.

create table #serverlist(
      ID smallint IDENTITY(1,1),
      dbName varchar(50)
      )

create table #browsercounts(
      ID smallint IDENTITY(1,1),
      --Email varchar(50),
      Browser varchar(50),
      Counts int)

insert into #serverlist
select name from sys.databases
where name like '%Test2Portal%'
and name not like '%_Test%'

Declare @counter int, @rows int
set @counter = 1
set @rows = (select COUNT(dbName) from #serverlist)

while (@counter <= (@rows))
Begin
      Declare @SQL varchar(1000)
      Declare @database varchar(50) =
        (select dbName from #serverlist where ID = @counter)

      Select @SQL = 'select Browser, COUNT(Browser) as Counts from ' +
        @database+ '.dbo.Session where Browser is not null group by Browser'

      insert into #browsercounts
      Exec (@SQL)

      set @counter += 1

End

Select * From #browsercounts

drop table #serverlist
drop table #browsercounts


texts:
Please critique my solutions to these simple exercises. I have no programming experience, so the more anal you are, the more I'll learn. I'm teaching myself, this is not for school:

  Write a function translate() that will translate a text into
  "rövarspråket". That is, double every consonant and place an
  occurrence of "o" in between. For example, translate("this is fun")
  should return the string "tothohisos isos fofunon".

var translate = function(x) {
  var string = x.toLowerCase();
  var vowels = ["a", "e", "i", "o", "u", " "];
  var y = "";
  for (i = 0; i < string.length; i++) {
     var current = string.charAt(i);
    if (vowels.indexOf(current) != -1)
    y = (y + (current));
   else
    y = (y + (current + "o" + current));
  }
  return y;
}

  Define a function sum() and a function multiply() that sums and
  multiplies (respectively) all the numbers in an array of numbers. For
  example, sum([1,2,3,4]) should return 10, and multiply([1,2,3,4])
  should return 24.

var sum = function(array) {
  var length = array.length;
  var total = 0;
  for (i = 0; i < length; i++) {
    total += array[i];
  }
  return total;
};

var multiply = function(array) {
  var length = array.length;
  var total = 1;
  for (i = 0; i < length;  i++) {
    total *= array[i];
  }
  return total;
};

  Define a function reverse() that computes the reversal of a string.
  For example, reverse("jag testar") should return the string "ratset
  gaj".

var reverse = function(string) {
  var length = string.length;
  var reversed = [];
  var joined = ("");
  for (i = length; i > 0; i--){
    reversed.push(string.charAt(i-1));
  };
  for (i = 0; i < (length) ; i++){
    joined += (reversed[i]);
  }
  return joined;
}

  Write a function findLongestWord() that takes an array of words and
  returns the length of the longest one.

var findLongestWord = function(array) {
  var elements = array.length;
  var count = 0;
  for (i = 0; i < elements; i++) {
    if (array[i].length > count)
      count = array[i].length;
  }
  return count;
}

  Write a function filterLongWords() that takes an array of words and
  an integer i and returns the array of words that are longer than
  i.

var filterLongWords = function(array, int){
  var length = array.length;
  var longestWords = [];
  for (i = 0; i < length; i++) {
    if (array[i].length > int) {
      longestWords[longestWords.length] = array[i];
    }
  }
  return longestWords;
}

  Write a function charFreq() that takes a string and builds a
  frequency listing of the characters contained in it. Represent the
  frequency listing as a JavaScript object. Try it with something like
  charFreq("abbabcbdbabdbdbabababcbcbab").

var charFreq = function(string){
  var list = {};
  var length = string.length;
  for (var i = 0; i < length; i++) {
  if (string.charAt(i) in list)
    list[string.charAt(i)] += +1;
  else
    list[string.charAt(i)] = 1;
  }
  return list;
}

EDIT: I forgot to mention that rather than use global methods, I tried to as much as possible code for the result I wanted, like reverse, and join, etc.


texts:
I wrote my first module in Verilog. The purpose is to maintain two counters and emit signals corresponding to VGA's HSync and VSync, as well as HBlank and VBlank pulses to be used by a video controller for the blanking intervals. The only input is a clock signal of 25.175 MHz. All timing information was acquired from here.

module sync (clk, hblank, hsync, vblank, vsync) ;
  input clk;
  output reg hblank = 0, hsync = 1, vblank = 0, vsync = 1;
  reg [9:0] hcnt = 0, vcnt = 0;

  always @(posedge clk) begin
    case (hcnt)
      640: hblank <= 1;
      656: hsync <= 0;
      752: hsync <= 1;
      800: begin
        hblank <= 0;
        hcnt <= 0;
        vcnt <= vcnt + 1;
      end
    endcase
    case (vcnt)
      480: vblank <= 1;
      490: vsync <= 0;
      492: vsync <= 1;
      525: begin
        vblank <= 0;
        vcnt <= 0;
      end
    endcase
    hcnt <= hcnt + 1;
  end
endmodule


texts: Class that calls initiates the validation of itself and then initiates the assignment of offers

texts:
Please see the code below:

public class Customer
{
    public int _iD { get; set; }
    public decimal _salary { get; set; }
    public List<String>_assignedOffers { get; set;  }
    private AbstractValidator<Customer> _validator;
    private IRulesOfferCalculator _rulesOfferCalculator;

    public Customer(AbstractValidator<Customer> validator, IRulesOfferCalculator rulesOfferCalculator)
    {
        _validator = validator;
        _rulesOfferCalculator = rulesOfferCalculator;
    }

    public void AssignOffers()
    {
        ValidationResult results = _validator.Validate(this);
        if (results.IsValid)
        {
            _assignedOffers = _rulesOfferCalculator.CalculateOffers(this);
        }
        else
        {
            _validator.ValidateAndThrow(this);
        }
    }
}

It is a Domain Layer class in a rich domain model.  I have used FluentValidation for the validation. The Service Layer (WFC) creates an instance of Customer and initialises it.

The concern I have is that the class has two responsibilities:

Validate the customer.  If validation fails then thrown an exception.  Validation can fail if the customer is under 21 years old etc
If validation fails then throw an exception with reason for failure in the exception string.  If validation is successful then assign offers (_assignedOffers  is an instance variable)

I have two questions:

Is it bad practice to throw an exception if validation fails? Is there a better way to notify the user if validation fails?
Does this class have too many responsibilities i.e.

validate and
assign offers.

Alternatively the Service Layer could call: Validate and then call AssignOffers if Validate is successful.  However, I believe this would make the domain model anemic.

Please be aware that I am building a rich domain model.