texts: Simple ring/circular buffer c++ class V2

texts:
The Original Post (v1)

I'm looking for feedback on the updated version of the code posted at the link above.

#pragma once

#include <memory>
#include <cassert>
#include <type_traits>

namespace datastructures {

    template<class _Ty, size_t _Size>
    class CircularBufferv2 {

        // uses char as type to prevent default _Ty initialization.
        alignas(alignof(_Ty)) char buffer[_Size * sizeof(_Ty)];
        size_t head;
        size_t tail;
        bool isFull;

    public:
        constexpr CircularBufferv2() noexcept :
            buffer{0},
            head{0},
            tail{0},
            isFull{false} {
        }

        void push(const _Ty& item) noexcept {
            assert(!isFull && "Attempting to push item into full buffer!");

            new (&buffer[head * sizeof(_Ty)]) _Ty(std::move(item));

            head = ++head % _Size;
            isFull = head == tail;
        }

        _Ty pop() noexcept {
            assert(!is_empty() && "Attempting to pop item from empty buffer!");

            auto location = reinterpret_cast<_Ty*>(&buffer[tail * sizeof(_Ty)]);
            auto result = std::move(*location);
            std::destroy_at(location);

            tail = ++tail % _Size;
            isFull = false;

            return result;
        }

        _NODISCARD constexpr _Ty& peek() noexcept {
            assert(!is_empty() && "Attempting to peek in empty buffer!");

            return *reinterpret_cast<_Ty*>(&buffer[tail * sizeof(_Ty)]);
        }

        _NODISCARD constexpr const _Ty& peek() const noexcept {
            assert(!is_empty() && "Attempting to peek in empty buffer!");

            return *reinterpret_cast<_Ty*>(&buffer[tail * sizeof(_Ty)]);
        }

        _NODISCARD constexpr bool is_empty() const noexcept {
            return !isFull && tail == head;
        }

        _NODISCARD constexpr size_t get_capacity() const noexcept {
            return _Size;
        }

        _NODISCARD constexpr size_t get_size() const noexcept {
            if (isFull)
                return _Size;

            if (head >= tail)
                return head - tail;

            return _Size + head - tail;
        }

        _NODISCARD _CONSTEXPR17 _Ty* data() noexcept {
            return buffer;
        }

        _NODISCARD _CONSTEXPR17 const _Ty* data() const noexcept {
            return buffer;
        }
    };
}

I want to take advantage of all of the new features(c++17) while also supporting older compilers(preferably all older compilers but c++11 is probably as old as i'll actually be compiling for). Any suggestions welcome. (I'm attempting to use this class as an example class to follow when constructing other classes.)

Also, the use of _CONSTEXPR17 on the data functions I was wondering why use the macro vs just a constexpr? (I based the use of macros around the std::array struct, its data function uses _CONSTEXPR17 rather than just constexpr.)


texts:
The file is quite long, 1000 LOC so I want to separate it into smaller files.

https://github.com/anvoz/world-js/blob/v1.0/js/world.core.js

Here is a brief version of the code:

(function(window, undefined) {
    var WorldJS = window.WorldJS = function() {
        // WorldJS Constructor
        this.nextSeedId = 1;
        this.Statistic = { population: 0 };
        this.Knowledge = {
            completed: [],
            gain: function(world) { /* ... */ }
        };
    }
    WorldJS.prototype.someMethods = function() {};

    var Seed = WorldJS.prototype.Seed = function() {
        // Seed Constructor
    };
    Seed.prototype.someMethods = function() {};
})(window);

// Create a world
var world = new WorldJS();
// Create a seed
var seed = new world.Seed();

Seems like I was right with the Seed class. So I can put Seed in a new file. Like this:

(function(window, undefined) {
    var WorldJS = window.WorldJS;
    var Seed = WorldJS.prototype.Seed = function() {
        // Seed Constructor
    };
    Seed.prototype.someMethods = function() {};
})(window);

How can I put the Knowledge property to a new file? Is it a good practice if I change Knowledge to a class just like the Seed class and use a new lowercase property to hold data like this:

world.knowledge = new world.Knowledge();


texts: Fast counting of interactions between groups given users interactions and groups assignments

texts:
Given:

An array c that contains the group assignment of every user (c[i]=4 indicates that user i belongs to group 4)
A matrix y of 0 and 1 that indicates whether user i interacted with user j (y[i][j] = 1 if i interacted with j, 0 otherwise)

What is the fastest way to count the number of interactions and lack of interactions between every pair of groups?

This is what I have:

Solution 1:

This is what I have:

import numpy as np

def test1(y, c):

    N = len(c) # number of users
    C = len(set(c)) # number of clusters

    # Final counts matrices
    I = np.zeros((C,C))
    notI = np.zeros((C,C))

    # Loop every row i/ column j, look at the groups where the users belong
    # and update I accordingly
    for i in range(N):
        for j in range(N):
            if y[i][j] == 1:
                I[c[i]][c[j]] += 1
            else:
                notI[c[i]][c[j]] += 1

    return I, notI

timeit:

nusers = 100
nclusters = 4
y = np.random.random_integers(0, 1, (nusers,nusers))
c = np.random.choice(nclusters, nusers)

%timeit test1(y,c)

10 loops, best of 3: 42 ms per loop

Solution 2:

def test2(y, c):

    N = len(c)
    C = len(set(c))
    I = np.zeros((C,C))
    notI = np.zeros((C,C))

    for i, jj in enumerate(y):
        for j, value in enumerate(jj):
            if value:
                I[c[i]][c[j]] += 1
            else:
                notI[c[i]][c[j]] += 1

    return I, notI

timeit:
10 loops, best of 3: 30.8 ms per loop


texts:
(define (tridiagonal n)
   (build-list n
               (lambda (x)
                 (build-list n
                           (lambda (x)
                             (cond
                               [(= x n) 2]
                               [(or (= x (- n 1))
                                    (= x (+ n 1))) 1]
                               [else 0]))))))

The above is my attempt at making a tridiagonal patterns of lists.
Restrictions:

Consumed integer n is greater than 2
At most 3 non-zero value occour in a list.

Examples:

(tridiagonal 3) => (list (list 2 1 0) (list 1 2 1) (list 0 1 2))
(tridiagonal 5) => (list (list 2 1 0 0 0) (list 1 2 1 0 0) (list 0 1 2 1 0) (list 0 0 1 2 1) (list 0 0 0 1 2))


texts: Bank saving account class in Python (pandas)

texts:
I am setting up a kids bank account class to teach them how to save, and myself how to write a class in Python. The original idea was to create a pandas DataFrame that will show how the money gains interest by loading:

<AccountName>.df

First I created the DataFrame of 365 days with datetime.date.today() + datetime.timedelta(days=236) as the indices which I guess made the looking up of index for the daily interest increment a bit cumbersome... to say the least.

class  Account:

    def __init__(self, holder, start_date):
        import datetime
        import pandas as pd

        self.df = pd.DataFrame(index=pd.date_range(start_date, start_date + datetime.timedelta(365), freq='D'), columns=['deposit', 'withdrawl', 'balance'])
        self.df.withdrawl = 0.0
        self.df.deposit = 0.0
        self.df.balance = 0.0
        self.df.dif = 0.0

        for i in self.df.index[1:]:
            self.df.loc[i,('balance')] = self.df.loc[str(datetime.datetime.strptime(str(i)[:10], '%Y-%m-%d') - datetime.timedelta(days=1))[:10], ('balance')] * (1+(0.08 / 365))

        self.history = []

        self.holder = holder

    def __str__(self):
        return 'The account of: {0}, balance is: {1} '.format(self.holder, self.df.loc[str(datetime.datetime.today())[:10], 'balance'])

    def __repr__(self):
        return '{0.__class__.__name__}(name={0.holder})(balance={1})'.format(self, self.df.loc[str(datetime.datetime.today())[:10], 'balance'])

    def get_balance(self):
        return self.df.loc[str(datetime.datetime.today())[:10], 'balance']

    def make_deposit(self, amount, date):
        self.history.append((amount, date))
        if type(date) is datetime.datetime or datetime.date:
            self.df.loc[date.strftime('%Y-%m-%d'), ('deposit')] += amount
            self.df.loc[date.strftime('%Y-%m-%d'), ('balance')] += amount
        for i in self.df.index[self.df.index.slice_locs(date + datetime.timedelta(days=1))[0] :]:
            self.df.loc[i, 'balance'] = self.df.loc[i-datetime.timedelta(days=1), 'balance']* (1+(0.08 / 365)) + self.df.loc[i, 'deposit'] - self.df.loc[i, 'withdrawl']

    def withdraw_money(self, amount, date):
        self.history.append((amount*-1, date))
        if type(date) is datetime.datetime or datetime.date:
            self.df.loc[date.strftime('%Y-%m-%d'), ('withdrawl')] += amount
            self.df.loc[date.strftime('%Y-%m-%d'), ('balance')] -= amount
        for i in self.df.index[self.df.index.slice_locs(date + datetime.timedelta(days=1))[0] :]:
            self.df.loc[i, 'balance'] = self.df.loc[i-datetime.timedelta(days=1), 'balance']* (1+(0.08 / 365)) + self.df.loc[i, 'deposit'] - self.df.loc[i, 'withdrawl']

I am looking for improvement ideas for that (also repeating in all the functions). I am also looking for a neater way, within pandas of assigning yesterday's balance + todays deposit - today's withdraw + the daily interest rate. (I know it's an extremely generous interest, but they are my kids after all and with the little pennies they manage to collect it doesn't amount to much...)

I start an account like so:

import datetime
test = Account('my_name', datetime.date.today())

I've improved my __str__ and __repr__ methods after I read all the suggestions suggested on this question, didn't do anything about privacy and properties but first thing first.

Wouldn't changing the date from the index to its own column and using integer indices make it easier to access and lookup data?


texts:
This project has evolved a lot since I started learning Angular. I'm pretty happy with it now, and I'm wondering if there's anything I can improve upon, or have forgotten at this point...

HTML

FitText

ng-FitText

Inclusion & Customization

var myApp = angular.module( 'myApp', [ 'ngFitText' ] );

myApp.config( function( fitTextConfigProvider ) {
    fitTextConfigProvider.config = {
        debounce: true, //default is false
        delay: 1000 //default is 250
    };

    // OR

    fitTextConfigProvider.config.debounce = true;
    fitTextConfigProvider.config.delay = 1000;
});

The Module

'use strict';

angular.module( 'ngFitText', [] )
    .value( 'config', {
        'debounce': false,
        'delay': 250
    })

    .directive( 'fittext', [ 'config', 'fitTextConfig', function( config, fitTextConfig ) {
        return {
            restrict: 'A',
            scope: true,
            transclude: true,
            replace: true,
            template: function( element, attrs ) {
                var tag = element[0].nodeName;
                return "<"+tag+" data-ng-transclude data-ng-style='{fontSize:fontSize}'></"+tag+">";
            },
            link: function( scope, element, attrs ) {
                angular.extend(config, fitTextConfig.config);

                scope.compressor = attrs.fittext || 1;
                scope.minFontSize = attrs.fittextMin || Number.NEGATIVE_INFINITY;
                scope.maxFontSize = attrs.fittextMax || Number.POSITIVE_INFINITY;
                scope.elementWidth = element[0].offsetWidth;

                ( scope.resizer = function() {
                    scope.elementWidth = element[0].offsetWidth;
                    scope.fontSize = Math.max(
                        Math.min(
                            scope.elementWidth / ( scope.compressor * 10 ),
                            parseFloat( scope.maxFontSize )
                        ),
                        parseFloat( scope.minFontSize )
                    ) + 'px';

                    if( !scope.$$phase ) scope.$digest();
                })();

                config.debounce == true
                    ? angular.element( window ).bind( 'resize', debounce( scope.resizer, config.delay ))
                    : angular.element( window ).bind( 'resize', scope.resizer);

                function debounce(a,b,c){var d;return function(){var e=this,f=arguments;clearTimeout(d),d=setTimeout(function(){d=null,c||a.apply(e,f)},b),c&&!d&&a.apply(e,f)}}
            }
        }
    }])

    .provider( 'fitTextConfig', function() {
        var self = this;
        this.config = {};
        this.$get = function() {
            var extend = {};
            extend.config = self.config;
            return extend;
        };
        return this;
    });


texts: Imported data from CSV successfully, but slow

texts:
Currently I am using the gem activerecord-import to seed more than 55,000 records into my database, and it works fine. However, it takes too much time. I am wondering if there are any other ways to shorten the import time. Any suggestions would be appreciated.

ocean_routes_columns = [:origin_location_id, :destination_location_id, :n1st_lane_id, :n1st_pol_id, :n1st_pod_id, :n1st_skd_dir, :n2nd_lane_id, :n2nd_pol_id, :n2nd_pod_id, :n2nd_skd_dir, :n3rd_lane_id, :n3rd_pol_id, :n3rd_pod_id, :n3rd_skd_dir, :created_by_id, :updated_by_id]
ocean_routes = []
CSV.foreach(Rails.root.join('db/seeds/ocean_routes.csv'), headers: true) do |row|
  origin_location            = Location.find_by(code: row[0])
  destination_location       = Location.find_by(code: row[1])
  n1st_lane                  = ServiceLane.find_by(code: row[2])
  n1st_pol                   = Location.find_by(code: row[3])
  n1st_pod                   = Location.find_by(code: row[4])
  n1st_skd_dir               = OceanRoute.to_bound_code_value(row[5])
  n2nd_lane                  = ServiceLane.find_by(code: row[6])
  n2nd_pol                   = Location.find_by(code: row[7])
  n2nd_pod                   = Location.find_by(code: row[8])
  n2nd_skd_dir               = OceanRoute.to_bound_code_value(row[9])
  n3rd_lane                  = ServiceLane.find_by(code: row[10])
  n3rd_pol                   = Location.find_by(code: row[11])
  n3rd_pod                   = Location.find_by(code: row[12])
  n3rd_skd_dir               = OceanRoute.to_bound_code_value(row[13])
  val                        = OceanRoute.new(origin_location: origin_location, destination_location: destination_location, n1st_lane: n1st_lane, n1st_pol: n1st_pol, n1st_pod: n1st_pod, n1st_skd_dir: n1st_skd_dir, n2nd_lane: n2nd_lane, n2nd_pol: n2nd_pol, n2nd_pod: n2nd_pod, n2nd_skd_dir: n2nd_skd_dir, n3rd_lane: n3rd_lane, n3rd_pol: n3rd_pol, n3rd_pod: n3rd_pod, n3rd_skd_dir: n3rd_skd_dir)
  val.created_by                 = User.find_by(name: 'yo')
  val.updated_by                 = User.find_by(name: 'yo')
  ocean_routes << val
end
OceanRoute.import ocean_routes_columns, ocean_routes, validate: false


texts: Join arrays of objects by some identifier

texts:
The following is some JavaScript that I wrote to join two arrays of objects by an identifier. The goal is to extend the objects in a1 to include the extra fields in a2 and a3. What could I improve here? One question I have is, should I refactor this so the objects in a1 aren't modified in-place with Object.assign, instead having a new Object getting created so it follows a functional style?

function groupBy(keyExtract, arr) {
  return arr.reduce((result, item) => {
    const key = keyExtract(item);
    if (result.has(key)) {
      result.set(key, [...result.get(key), item]);
    } else {
      result.set(key, [item]);
    }

    return result;
  }, new Map());
}

function merge(groups, array, mergeKey) {
  array.forEach(it => {
    try {
      const group = groups.get(it[mergeKey]);
      if (!group) {
        throw `${mergeKey} ${it[mergeKey]} not found`;
      }
      group.map(item => {
        return Object.assign(item, it);
      });
    } catch (e) {
      console.log(it, `Error merging record with ${mergeKey}: ${it[mergeKey]}`, e);
    }
  });
}

function flatten(groups, arrayMap) {
    let arr = []
    for (const [index, group] of groups.entries()) {
      arr.push(...group);
    }
  return arr;
}

// usage example
const a1 = [{ssid: 123, score: 100, test_id: 456}, {ssid: 123, score: 50, test_id: 789}];
const a2 = [{ssid: 123, student_number: 321}];
const a3 = [{test_name: 'test', test_id: 456}, {test_name: 'test2', test_id: 789}];

const ssid_groups = groupBy(item => item.ssid, a1);
const test_id_groups = groupBy(item => item.test_id, a1);

merge(ssid_groups, a2, 'ssid');
merge(test_id_groups, a3, 'test_id');

const results = flatten(ssid_groups);


texts:
I've written a script in python using requests module in combination with selenium along with regex to parse email address (if any exists) from any website. I tried to create it in such a way so that it can traverse javascript enabled sites as well. My crawler is supposed to track any website link (given in it's list storage) then find contact us or about us etc keywords from that page and parsing the matching link it will go to the target page and using regular expression it will finally parse the email address from that page. It scrapes the email address along with the link address where it parses the email from. I tried with several links and most of the cases it succeeds. I know it's very hard to create a full-fledged one but I tried and it is not despairing at all. Any suggestion to improve this crawler will be vastly appreciated.

Here is what I have written:

from selenium import webdriver
import requests; import re
from lxml.html import fromstring
from urllib.parse import urljoin

main_url = [
'http://advanta.in/',
'http://warnaengineeringworks.com/',
'http://unifrostindia.com/',
'http://www.superrefrigerations.com/',
'http://www.westernequipments.com/',
]

def search_item(driver,url):
    driver.get(url)
    tree = fromstring(driver.page_source)
    for item in tree.xpath("//a/@href"):
        if "contact us" in item.lower() or "about us" in item.lower() or "contact" in item.lower() or "about" in item.lower():
            get_item(urljoin(url,item))
            break

def get_item(link):
    response = requests.get(link).text
    try:
        email = re.findall(r'[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+',response)[0]
    except: pass
    if email:
        print(link,email)

if __name__ == '__main__':
    driver = webdriver.Chrome()
    try:
        for link in main_url:
            search_item(driver,link)
    finally:
        driver.quit()


texts: How to catch exceptions in test code?(Python 3.8)

texts:
I have a script that includes some independent tests that run together (not parallelly).
The tests include calls for some libraries that might raise exceptions (which indicate of a failure in the test).
Instead of wrapping each call with "try - except" mechanism I thought about wrapping the each test with "try - except" using decorator of this kind:
def log_exceptions(func):
    def inner(*args, **kwargs):
        try:
            return func(*args, *kwargs)
        except Exception as e: # Can be more specific here, I know
            logging.error("Python Exception raised from {} - {}".format(func.__name__, e))
            ERROR_MSG.append("Python Exception raised from {} - {}".format(func.__name__, e))
            return False

    return inner

@log_exceptions
def test1():
    some_funciton_call()

Where ERROR_MSG is a list of the errors that occurred during the tests.
Do you think managing the exceptions and errors this way is a good practice?
Can you suggest a different way of capturing exceptions?
Thanks! :)


texts: Machine learning, kNN and Naïve Bayes algorithm

texts:
This is the task I am working on:

  In this assignment you will implement the K-Nearest Neighbour and Naïve Bayes algorithms and evaluate them on a real dataset using the stratified cross validation method. You will also evaluate the performance of other classifiers on the same dataset using Weka. Finally, you will investigate the effect of feature selection, in particular the Correlation-based Feature Selection method (CFS) from Weka.

I have done the weka part and also written seperate code for performance evaluation. Here, I need help with the main code where I am implementing kNN and NB algorithm.

Here is my code! I want to reduce the number of lines and possibly make it look more neat. Please help as much as you can. I have tried splitting into more functions and then calling them to do the work but is there a way I can do more? Also, is there a way the for loops can be written more compactly?

import heapq
import sys
import math as m
from decimal import Decimal


texts: Grouping an array of strings into anagrams

texts:
This program takes an arbitrary array of strings and group anagrams into arrays and return them in a array. Any string without any anagrams is still put in an array.

This code works perfectly and I would appreciate any comments on making this more efficient in terms of computation time.

import java.util.Arrays;
import java.util.HashMap;
import java.util.ArrayList;

public class AnagramSort{

    public static void main( String[] args ){
        HashMap< Integer, ArrayList< String >> hm = new HashMap();

        groupAnagrams( args, hm );
        System.out.println( hm );
    }

    public static void groupAnagrams( String[] list, HashMap< Integer, ArrayList< String >> hm ){

        for( int x=0; x<list.length; x++ ){
            if( list[ x ] == null ) continue;

            String curX    = list[ x ];
            int    hashX   = primeHash( curX );

            hm.put( hashX, new ArrayList( Arrays.asList( curX )));

            for( int y=x+1; y<list.length; y++ ){

                String curY    = list[ y ];
                int    hashY   = primeHash( curY );

                if( curY == null || curY.length() != curX.length())  continue;

                if( hashX == hashY ){
                    hm.get( hashX ).add( curY );

                    list[ y ] = null; // if its an anagram null it out to avoid checking again
                }
            }
        }
    }

// Utility Mehthods

    public static int primeHash( String word ){
        int productOfPrimes = 1;
        int prime[] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31,
            37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101 };

        for( char ch : word.toCharArray() ){
            productOfPrimes *= prime[ (int) ch - (int) 'a' ];
        }
        return productOfPrimes;
    }

}

Sample Input:

[ mother, mothre, dad, add, gift, gender ]

Output:

[ [mother, mothre], [dad,add], [gift], [gender] ]


texts: Decoupled chain of responsibility in Python

texts:
I've started to learn Python today. I'm trying to write decoupled middleware or chain of responsibility pattern.

In my app I have some two classes:

abstract class or interface named Processable
class ProcessorChain, which must locate implementations of the Processable, create objects of these implementations and call methods of these objects

In client code, user can:

create his own class based on Processable
write full path to his class to some global setting
and be sure what it will be processed in queue by my app processor chain :-)

So, the same thing we got using service container, when we call services by tag. In Symfony, for example, we use service tags and CompilerPass to process a group of decoupled objects which implement one interface.

The question is: how to get same in Python?

I've already learnt about __subclasses__ method, but it works only if sub-classes was imported. So, I've learnt about importlib.importmodule, then I got what I wanted.

The folder structure is:

patterns

main.py
settings.py
Chain

chain.py
processor.py

patterns.Chain.chain.py

import importlib
from abc import ABCMeta, abstractmethod
from patterns import settings

class Processable(metaclass=ABCMeta):
    """Meta class define required properties and methods"""
    __metaclass__ = ABCMeta

    @abstractmethod
    def execute(self) -> str:
        return 'Base class processing...'

class ProcessorChain:
    @staticmethod
    def process_directly():

        # load processors from settings list
        for definition in settings.CHAIN_PROCESSORS:

            # parse module and package
            m, p = definition.rsplit('.', 1)
            module = importlib.import_module(m, p)

            # get class
            cls = getattr(module, p)

            # check if the class is a child of Processable
            if issubclass(cls, Processable):

                # create an instance of the class
                processor = cls()

                # and do something
                print(processor.execute())

    @staticmethod
    def process_subclass():

        # still requires make dynamic imports
        for definition in settings.CHAIN_PROCESSORS:
            # parse module and package
            m, p = definition.rsplit('.', 1)
            # import a module
            importlib.import_module(m, p)

        # load all subclasses of Processable
        for processor in Processable.__subclasses__():
            # and do something
            print(processor().execute())

patterns.Chain.processor.py

from .chain import Processable

class FirstProcessor(Processable):
    """Provides required properties and methods"""
    context = 1

    def execute(self):
        return super(FirstProcessor, self).execute() + ' (implementation from meta class)'

class SecondProcessor(Processable):
    """Provides required properties and methods"""
    context = 2

    def execute(self):
        return str(self.context) + ' processing...' + ' (its own implementation)'

patterns.settings.py

CHAIN_PROCESSORS = [
    'patterns.Chain.processor.FirstProcessor',
    'patterns.Chain.processor.SecondProcessor'
]

patterns.main.py

from patterns.Chain.chain import ProcessorChain

ProcessorChain().process_directly()

The run of main.py as expected prints:

Base class processing... (implementation from meta class)
2 processing... (its own implementation)

https://github.com/xcono/py3-trials/tree/master/patterns

But, actually, I don't know is what pythonic way? May be there is a better way to acheive decoupled chain? May be better to use event listeners/dispatchers?

Dear Pythonists, please, tell the truth, how do you cook it?


texts: Improving efficiency for finding longest contiguous non-decreasing substring

texts:
I was working on a problem set and I came across this problem:

Assume s is a string of lower case characters.
Write a program that prints the longest substring of s in which the letters occur in alphabetical order. For example, if s = 'azcbobobegghakl', then your program should print:
Longest substring in alphabetical order is: beggh

In the case of ties, print the first substring. For example, if s = 'abcbcd', then your program should print
Longest substring in alphabetical order is: abc

I actually was able to get a solution, but it was the most inefficient ever! And here's what I came up with:
def test():
    index = 1
    prev_index = 0
    count = 0
    global largest
    largest = ''
    test = s[prev_index]

    while count < len(s):
        if ord(s[index]) > ord(s[prev_index]):
            test += s[index]
            index += 1
            prev_index += 1
        elif ord(s[index]) == ord(s[prev_index]):
            test += s[index]
            index += 1
            prev_index += 1
        else:
            if len(largest) < len(test):
                largest = test[:]
            test = s[index]
            prev_index += 1
            index += 1
        count += 1
    return largest
try:
     test()
except IndexError:
     pass
finally:
     print largest

Can anyone give me an example of better code that produces the same output?


texts:
I need to create two lists of Card objects in C#.

A Card class is defined as:

public class Card {
    public Suits Suit { set; get; }
    public Values Value { set; get; }
    public static Random rand = new Random();

    public Card() {

    }

    public Card(Suits s, Values v) {
        Suit = s;
        Value = v;
    }

    public override string ToString() {
        return Suit.ToString() + " that has a value of " + Value.ToString();
    }

    public Card RandomCardGenerator() {
        Suit = (Suits)rand.Next(4);
        Value = (Values)rand.Next(1, 14);
        return this;
    }

In a different class called Action:

   static class Action {
        static public List< Card > CreateRandomCardList() {
            List< Card > cardList1 = new List< Card >();

            for (int loop = 0; loop < 12; loop++) {
                cardList1.Add(new Card().RandomCardGenerator());
            }

            return cardList1;
        }

        static public List < Card > CreateFullSetCard() {
            List< Card > cardList2 = new List< Card >();

            for (int s = 0; s < 4; s++) {
                for (int v = 0; v < 13; v++)
                    cardList2.Add(new Card((Suits)s, (Values)v));
            }

            return cardList2;
        }
    }

CreateRandomCardList() is later called upon:

public partial class Form1 : Form {
        public Form1() {
            InitializeComponent();
            PopulateListBox1(Action.CreateRandomCardList());
        }

        private void PopulateListBox1(List< Card > l) {
            listBox1.DataSource = l;
        }
}

I used static for class Action.

It makes sense to create instances of Card, but is it necessary to create an instance of Action? Can I keep it static?


texts: AWS Lambda Python function, to enable / disable access to a VPC environment

texts:
We have a requirement that access to an AWS environment is enabled on demand, and said access disabled afterwards. In each case (up / down), this means we will do two things:

Enable access

Turn on the Bastion instance
Modify the Security Groups of the EC2 instances, so a SG allowing RDP access is added to the list of associated SGs.

Disable access

Turn off the Bastion
Modify the SGs of the EC2 instances, to remove the SG that grants RDP access.

The script is pretty straight forwards, but there is not much error handling / logging going on.

The script is designed to run either from local machine or in AWS lambda, without modification (providing environment variables, credentials/permissions setup correctly).

import boto3, os

region = os.environ['PFregion']
security_group_id = os.environ['PFSG']
bastion_iid = os.environ['PFbastion_iid']
aws_profile = 'profile_name'

def lambda_handler(event, context):
    if (__name__ == "__main__"):
        print 'using ENV creds'
        session = boto3.Session(profile_name=aws_profile)
        ec2_client = session.client('ec2', region_name=region)
        ec2_resx = session.resource('ec2', region_name=region)
    else:
        ec2_client = boto3.client('ec2', region_name=region)
        ec2_resx = boto3.resource('ec2', region_name=region)

    all_instances = ec2_resx.instances.filter()

    if (event['up'].lower() == 'true'):
    # Start the Bastion
        print 'inside up'
        ec2_client.start_instances(
            InstanceIds = [bastion_iid,],
            AdditionalInfo = 'Called from Lambda function to Up access',
            #DryRun = event['dry_run'],
        )
        # Modify the SGs accordingly
        for instance in all_instances:
            all_sg_ids = [sg['GroupId'] for sg in instance.security_groups]
            if security_group_id not in all_sg_ids:
                print 'SG not assigned currently'
                all_sg_ids.append(security_group_id)
                instance.modify_attribute(Groups=all_sg_ids)

    else:
        # Stop the Bastion
        print 'inside down'
        ec2_client.stop_instances(
            InstanceIds = [bastion_iid,],
            #DryRun = bool(event['dry_run']),
        )
        # Remove the SG rules
        for instance in all_instances:
            all_sg_ids = [sg['GroupId'] for sg in instance.security_groups]
            if security_group_id in all_sg_ids:
                print 'SG IS assigned currently'
                all_sg_ids.remove(security_group_id)
                instance.modify_attribute(Groups=all_sg_ids)

if __name__ == '__main__':
    event = { "up" : "true", "desc" : "this is a description field", "dry_run" : "false" }
    #print event
    lambda_handler(event, None)


texts: Circle Summation (30 Points) InterviewStree Puzzle cont

texts:
Further to the question
I solved it in following way.

#include <iostream>
#include <algorithm>
#include <iterator>
#include <stdio.h>

int main ( int argc, char **argv) {
    int T; // number of test cases
    std::cin >> T;
    for ( int i = 0 ; i < T; i++) {
        int N; // number of childrens
        std::cin >> N;
        int M; // number of rounds
        std::cin >> M;
        long long childrens[50];
        for ( int j = 0; j < N; j++ )
            std::cin >> childrens[j];

        int pos = 0;
        for ( int i = 0; i < N ; i++) {
            long long childs[50];
            for ( int j = 0; j < N; j++ )
                childs[j] = childrens[j];
            for ( int j = 0; j < M; j++) {
                int left  = ( pos     == 0)  ? N - 1  : pos - 1;
                int right = ( pos + 1 >= N ) ? 0      : pos + 1;
                childs[pos] = (childs[pos] + childs[left] + childs[right])% 1000000007;
                pos++;
                pos   = ( pos >= N ) ? 0 : pos;
            }
            std::copy(childs ,childs + N ,std::ostream_iterator<long long>(std::cout," "));
            std::cout << std::endl;
        }
        std::cout << std::endl;
    }
    return 0;
}

but the M can be 10^9, My code is going to take lot of time to finish, What are the various ways I can optize this.


texts:
Hello everyone
In today's assignment I had to write a function to determine if (and how many) the quadratic function defined by the formula f(x) = ax^2 + bx +c has roots. I had decorators to write.
Here is my solution:
from typing import List, Tuple
from math import sqrt
from datetime import datetime

class DeltaError(Exception):
    '''Error when calculating roots, and delta is lower than 0.'''
    def __init__(self):
        Exception.__init__(self, "Delta must be greater than 0!")

class Quadratic:

    def __init__(self, a: int, b: int, c: int):
        self.a = a
        self.b = b
        self.c = c
        self.x = -1

    @property
    def Roots(self):
        a, b, c = self.a, self.b, self.c
        d = sqrt(b * b - 4 * a * c)
        if d > 0:
            x1 = (-b + d) / (2 * a)
            x2 = (-b - d) / (2 * a)
            return x1, x2
        if d == 0:
            return -b / 2 * a
        if d < 0:
            raise ZeroError

    @property
    def Vietas_formula(self):
        a, b, c = self.a, self.b, self.c
        d = b * b - 4 * a * c
        if d > 0:
            return "x1 + x2 = {x}".format(x = -b / a), "x1 * x2 = {y}".format(y = c / a)

    @property
    def Vertex(self):
        a, b, c = self.a, self.b, self.c
        d = b * b - 4 * a * c
        return "W: ({p}, {q})".format(p = -b / 2 * a, q = -d / 4 * a)

    @property
    def Time_dependent(self):
        if datetime.now().hour + 2 in range(8, 16):
            return "Roots"
        else: return "Break"

    @property
    def x_plus_3(self):
        a, b, c, x = self.a, self.b, self.c, self.x
        x += 3
        return x * (x * a + b) + c

quad = Quadratic(1, 5, 6)
print(quad.Roots, quad.Vietas_formula, quad.Vertex, quad.Time_dependent, quad.x_plus_3)

I'm counting on advice, and a better use of classes, static assignment to a, b, c and delta values, so that through inheritance I can use in subsequent functions without having to declare them from scratch.
Have a nice day!


texts: Vectorizing a pixel-averaging operation in Numpy

texts:
I am reading from a file containing some segments (irregular parcels of the image) and trying to average the entire segment to have one pixel value. This is the code I use:

band = band[:,:,0] #take the first band of the image

for i in range(numSegments): #for every segment
    tx = band[segments==i]   #select all the pixels in segment
    avg = np.average(tx)     #average the values
    band[segments==i] = avg  #write the average back into the image

I am omiting some transformation steps and code for printing running time from the snippet.

This takes quite sometime to run for even one band. Almost 1000 seconds. I was wondering if there is a way to vectorize this operation to make it faster?

Data:
Segment2009: an image of all the segments in the image.
This is what the segments look like:

Bands: 3000x3000 pixels, float32 values.

Full context:

workFolder = '/home/shaunak/Work/ChangeDet_2016/SLIC/003_lee_m0_alpha'
bandlist=os.path.join(workFolder,'bandlist.txt')
configfile = os.path.join(workFolder,'config.txt')

segmentfile = os.path.join(workFolder,'Segments2009')

#%% Load the bands -- can refer to subfolders in the bandlist
files = utilities.readBandList(bandlist)
destinations = []
for f in files:
    destinations.append(f.split('.')[0]+"_SP."+f.split('.')[1])

(lines,samples,bands) = utilities.readConfigImSizeBand(configfile)
#%% Superpixel file
segments = np.fromfile(segmentfile,dtype='float32')
segments = np.reshape(segments,(lines,samples))
numSegments = int(np.max(segments))

#%% simple avg
for idx,f in enumerate(files):
    band = np.fromfile(f,dtype='float32').reshape((lines,samples))
    start = time.time()
    for i in range(numSegments):
        tx = band[segments==i]
        avg = np.average(tx)
        band[segments==i] = avg

    band.tofile(destinations[idx])

I am writing the values back to the original after averaging. It is not necessary, also not the most expensive part -- and helps me visualize the results better so I kept it in. I used the following approach also:

avgOut = np.zeros((numSegments,bands),dtype='float32')
#avgOutJoined = np.zeros((lines,samples,bands),dtype='float32')

for i in range(numSegments):
    tx = band[segments==i]
    avgOut[i,:] = np.average(tx,axis=0)
#    avgOutJoined[segments==i,:] = np.average(tx,axis=0)

np.tofile(outputSeperated,avgOut)
#np.tofile(outputJoined,avgOutJoined)

Since not writing the averaged result back did not save much time, I kept it in.


texts: How would you ruby-fy this non-AR model class for Ruby on Rails app?

texts:
This is a class from my rails application. It is used as non-database model in my RoR application and uses syntax similar to AR design pattern. I wonder is there a way to make this look more like Ruby code?

class Role

  def self.all
    role_list = Array.new

    r1 = Role.new
    r1.id = 1
    r1.symbol = :owner
    r1.name = "Owner"
    r1.has_all_permissions = true
    role_list << r1

    r2 = Role.new
    r2.id = 2
    r2.symbol = :admin
    r2.name = "Administrator"
    r2.has_all_permissions = false
    role_list << r2

    r3 = Role.new
    r3.id = 3
    r3.symbol = :gamemaster
    r3.name = "Gamemaster"
    r3.has_all_permissions = false
    role_list << r3

    role_list
  end

  def self.find(id)
    roles = Role.all

    roles.each do |role|
      if role.id == id
        return role
      end
    end

    nil
  end

  def self.find_by_symbol(symbol)
    roles = Role.all

    roles.each do |role|
      if role.symbol == symbol
        return role
      end
    end

    nil
  end

  def assign_permission(symbol)
    permission = Permission.find_by_symbol(symbol)

    if permission == nil
      return nil
    end

    permission_roles = PermissionRole.where(:permission_id => permission.id, :role_id => self.id)

    if permission_roles.size == 0
      permission_role = PermissionRole.new
      permission_role.permission_id = permission.id
      permission_role.role_id = self.id
      return permission_role.save
    end

    true
  end

  def has_permission?(symbol)
    permission = Permission.find_by_symbol(symbol)

    if permission == nil
      raise StandardError, "Permission does not exist"
    end

    permission_roles = PermissionRole.where(:permission_id => permission.id, :role_id => self.id)

    if permission_roles.size > 0
      return true
    else
      return false
    end
  end

  attr_accessor :id
  attr_accessor :symbol
  attr_accessor :name
  attr_accessor :has_all_permissions

end


texts:
I came across this interview question to find water accumulated between towers:

  You are given an input array whose each element represents the height of the tower. The width of every tower is 1. You pour water from the top. How much water is collected between the towers?

Any suggestions?

def test(x):
    if len(x) <= 2 or x == sorted(x) or x == sorted(x, reverse=True):
        return 0

    area = 0
    count = 1
    max_height = x[0]

    while count < len(x) - 1:
        if x[count] < max_height and x[count:] != sorted(x[count:], reverse=True):
            temp_count = 0
            new_count = count
            temp_height = 0
            height = max_height
            while count < len(x):
                if x[count] >= height or count == len(x) - 1:
                    temp_count = count
                    temp_height = x[count]
                    height = min(max_height, temp_height)
                    break
                count += 1
            while new_count < temp_count:
                area += height - x[new_count]
                new_count += 1
        else:
            max_height = x[count]
            count += 1

    return area

try:
    a = [1,2,3,4,5]
    print a, test(a)

    b = [5,4,3,9,1]
    print b, test(b)

    c = [3,2,1,1,1,2,3]
    print c, test(c)

    e = [1,2,0,2,1]
    print e, test(e)

    f = [1, 4, 2, 5, 1, 2, 3]
    print f, test(f)

    g = [3, 2, 1, 1, 1, 2, 3]
    print g, test(g)

    a1 = [1001,1000,1002]
    print a1, test(a1)
except Exception as e:
    print e


texts: Ungrouping of values into multiple lists

texts:
Given is a list with (possibly) non-unique elements.

My goal is to split this list into multiple lists, in sum containing the same elements, but separated in a way that no sublist contains each element value more than once.

A few examples to show the supposed result:

[1, 2, 2] -> [[1, 2], [2]]

[1, 2, 2, 3, 3, 4, 4, 4] -> [[1, 2, 3, 4], [2, 3, 4], [4]]

[4, 4, 1, 1, 4, 1, 3, 2, 1, 2, 5, 1, 2, 4, 4, 2, 5] ->
[[4, 1, 3, 2, 5], [4, 1, 2, 5], [4, 1, 2], [4, 1, 2], [4, 1]]

The order of the elements is not important. The fact that is it preserved is just a side-effect of my current implementation, but not needed. So the following would also be valid:

[1, 2, 2] -> [[2, 1], [2]]

My current implementation looks as follows:

fun <T> ungroupDuplicateValues(values: List<T>): List<List<T>> {
    val result: MutableList<List<T>> = mutableListOf()
    var counts = values.groupingBy { it }.eachCount().toMutableMap()
    while (counts.isNotEmpty()) {
        val newCounts: MutableMap<T, Int> = mutableMapOf()
        val subResult: MutableList<T> = mutableListOf()
        for ((value, count) in counts) {
            subResult.add(value)
            if (count > 1) {
                newCounts[value] = counts.getValue(value) - 1
            }
        }
        result.add(subResult)
        counts = newCounts
    }
    return result
}

It works, but feels kind of clumsy. Is there a more elegant/idiomatic (maybe functional) solution?


texts:
I'm practicing my JavaScript skills by trying to create a Pokemon game. So far, I've made the dataset and the functions required to work the game. Can someone help me optimize the code and tell me why they made that change?

function pokemon(name, hp, critical_attack, lowest_attack, highest_attack) {
    this.name = name;
    this.hp = hp;
    this.critical_attack = critical_attack;
    this.lowest_attack = lowest_attack;
    this.highest_attack = highest_attack;
}

var Charizard = new pokemon("Charizard", 90, 30, 1, 15);
var Blastoise = new pokemon("Blastoise", 95, 28, 1, 14);
var Venasaur = new pokemon("Venasaur", 100, 26, 1, 13);

var poke_choice = new Array ("Charizard", "Blastoise", "Venasaur")

function player(type, name, pokemon) {
    this.type = type;
    this.name = name;
    this.pokemon = pokemon;
}

var user = new player("User", "Arhum", "Charizard");
console.log(window[user.pokemon].hp)

for(i = 0; i<= 2; i++) {
  if (poke_choice[i] === user.pokemon) {
    poke_choice.splice(i,1);
  }
}

var comp_choice = function() {
  return poke_choice[Math.round(Math.random())]
}

var comp = new player("Computer","Red", comp_choice());

var user_attack = function() {
  var uhigh = window[user.pokemon].highest_attack
  var ulow = window[user.pokemon].lowest_attack
  return Math.round(Math.random().toFixed(1)*uhigh)
}

var comp_attack = function() {
  var chigh = window[comp.pokemon].highest_attack
  var clow = window[comp.pokemon].lowest_attack
  return Math.round(Math.random().toFixed(1)*chigh)
}

console.log(window[comp.pokemon].name)
console.log(window[user.pokemon].name)
console.log(user_attack())
console.log(comp_attack())


texts: ES6 classes and ReactJS: implementing propTypes

texts:
I had a problem to define propTypes for my React class. I ran into solution that doesn't feel right:

let React = require('react')
let CallerCard = require('caller-card')

class CallerDetailsPanel {
  render() {
    return (
      <div className='caller-details-panel'>
        <CallerCard person={this.props.callerData.owner} />
        <CallerCard person={this.props.callerData.user} />
      </div>
    )
  }
}

CallerDetailsPanel.prototype.propTypes = {
    callerData: React.PropTypes.object
}

module.exports = React.createClass(CallerDetailsPanel.prototype)

Is this correct approach or how propTypes should be defined? If I try to define them inside class, I get a Parse error from 6to5 / esprima on console.


texts:
The problem with the original Lazy in C# is that you have to put the initialization in the constructor if you want to refer to this.

For me that is 95% of the cases. Meaning that I have to put half of my logic concerning the lazy property in the constructor, and having more boilerplate code.

See this question: https://stackoverflow.com/questions/53271662/concise-way-to-writy-lazy-loaded-properties-in-c-sharp/53316998#53316998

Now I made a new version where I actually move the initialization part to the 'Get' moment. This saves boilerplate code and I can group everything about this property together.

But:

is the current implementation 'safe'?
are there any important performance considerations vs the original one?
is there anything else I'm missing that I should be concerned about in a high traffic application?

Class:

public class MyLazy
{
    private object  _Value;
    private bool    _Loaded;
    private object  _Lock = new object();

    public T Get<T>(Func<T> create)
    {
        if ( _Loaded )
            return (T)_Value;

        lock (_Lock)
        {
            if ( _Loaded ) // double checked lock
                return (T)_Value;

            _Value   = create();
            _Loaded = true;
        }

        return (T)_Value;
    }

    public void Invalidate()
    {
        lock ( _Lock )
            _Loaded = false;
    }
}

Use:

MyLazy _SubEvents = new MyLazy();
public SubEvents SubEvents => _SubEvents.Get(() =>
{
    // [....]
    return x;
});

Or like:

MyLazy _SubEvents = new MyLazy();
public SubEvents SubEvents => _SubEvents.Get(LoadSubEvents);

public void LoadSubEvents()
{
    // [....]
    return x;
}


texts:
Write a program that, given a word and a list of possible anagrams,
  selects the correct sublist.

  Given "listen" and a list of candidates like "enlists" "google" "inlets" "banana" the program should return a list containing "inlets".

Here is my solution:

class Anagram(word: String) {
  val sorted_word = word.toLowerCase.sorted
  val origin_word = word.toLowerCase

  def matches(words: Seq[String]) = {
    words.filter(w => w.toLowerCase.sorted == sorted_word && w.toLowerCase != origin_word)
  }

}

Here is the gist with specs.


texts: Feedback on Object-Oriented ETL Class Structure for Computing Profit Summary Data

texts:
I am using Python 3 and pandas 0.24.2 to do some data processing and ETL flows. I have followed this pattern a couple of times and it is really bothering me but I am not sure which direction to go to majorly improve it. Any advice for what to do differently is greatly appreciated. This is a toy example but the logic is the same. The main method is below. How can the structure of the class be improved?

import pandas as pd
from collections import deque
from collections import defaultdict
from collections import namedtuple
from src.query_helper import postgres_query_helper as pgqh

class ComputeNetProfitSummary():
    def __init__(self, date=None, factory_id=None):
        self.date = date
        self.factory_id = factory_id
        self.pg_query_helper = pgqh.PostgresQueryHelper()

    def build_sql_query(self):
        sql_query = f"""Select * FROM factory_table
            WHERE date='{self.date}'
            AND factory_id={self.factory_id}
        """
        return sql_query

    def create_orders_df(self):
        """Create orders Data Frame"""
        if self.date and self.factory_id:
            sql_query = self.build_sql_query()
            df = self.pg_query_helper.execute_sql_return_df(sql_query)
            return df

    def compute_complex_metrics_on_df(self):
        """Some complicated logic using FIFO attribution"""
        ComplexData = namedtuple('ComplexData', ['ColumnNamesA', ..., 'ColumnNamesZ'])
        all_data = []

        for row in self.orders_df.iterrows():
            """Do complicated stuff"""
            transform_row = # some computations on row
            complex_output = ComplexData(transform_row)
            all_data.append(complex_output)

        complex_df = pd.DataFrame(all_data)
        return complex_df

    def compute_summary_statistics(self):
        """Compute summary data"""
        summary_data = defaultdict(dict)
        # Create summary data, I am fine with this
        return summary_data

    def compute_summary_data(self):
        self.orders_df = self.create_orders_df()
        self.complex_df = compute_complex_metrics_on_df()
        self.summary_statistics = compute_summary_statistics()

if __name__ == '__main__':
    cnp = ComputeNetProfitSummary(date='2019-01-01', factory_id='A')

    summary_data = cnp.compute_summary_data()

    for key, value in summary_data.items():
        print(key)
        print(value)

NOTE: I am one of the only Python developers on my team so I do not get a lot of feedback on this type of code very often. Any feedback or constructive criticism is welcome, from design patterns to PEP8.


texts: What pattern can I use to write CRUD functionality?

texts:
I am writing a console application. CRUD functionality.I would like to try to apply the pattern. Is it possible to apply a "state" pattern? In the AddCustomer () method at the end, the call to the InputMenu () method, I do not think that this is correct. I would like to remake the "InputMenu", is it possible to apply the state pattern? Can I get rid of the switch case this way?

 public class DataFunction
    {

        readonly DataContext _dataContext = new DataContext();
        public DataFunction()
        {

        }

        public void AddCustomer()
        {

            Console.WriteLine("Input Name");
            string _name = Console.ReadLine();
            Console.WriteLine("Input Adress");
            string _adress = Console.ReadLine();

            _dataContext.Customers.Add(
                new Customer
                {
                    Name = _name,
                    Adress = _adress
                });
            _dataContext.SaveChanges();

            InputMenu();
        }

        public void ShowAllCustomers()
        {
            Console.WriteLine("All customers in database");
            Console.WriteLine();

            foreach (var customer in _dataContext.Customers)
            {
                Console.WriteLine("ID - {0} Name - {1}, Adress - {2}", customer.CustomerId, customer.Name, customer.Adress);
            }
            InputMenu();
        }

        public void ShowAllCustomersForRemoveMethod()
        {
            Console.WriteLine("All customers in database");
            Console.WriteLine();
            foreach (var customer in _dataContext.Customers)
            {
                Console.WriteLine("ID - {0} Name - {1}, Adress - {2}", customer.CustomerId, customer.Name, customer.Adress);
            }

        }

        public void RemoveCustomer()
        {
            Console.WriteLine();
            ShowAllCustomersForRemoveMethod();
            Console.WriteLine();
            Console.WriteLine("Enter the number to delete the user");
            Console.WriteLine();
            int _id = int.Parse(Console.ReadLine());
            Console.WriteLine();

            Customer customer = _dataContext.Customers.Find(_id);
            _dataContext.Customers.Remove(customer);
            _dataContext.SaveChanges();
            Console.WriteLine();
            InputMenu();
        }

        public void InputMenu()
        {
            Console.WriteLine("Add Customer? --- 1, Remove customer? --- 2, Show All Customer? --- 3");
            string _value = Console.ReadLine();

            switch (_value)
            {
                case "1":
                    AddCustomer();
                    break;
                case "2":
                    RemoveCustomer();
                    break;
                case "3":
                    ShowAllCustomers();
                    break;
                default:
                    Console.WriteLine("You clicked an unknown letter");
                    break;
            }
        }
    }

    static void Main(string[] args)
    {
        DataFunction dataFunction = new DataFunction();
        dataFunction.InputMenu();
    }
}


texts: Are the returns within my session function actually needed?

texts:
I have the following object oriented class revolving about the PHP super global $_SESSION  I shown the script to a fellow developer and he mentioned that all my returns are not necessary needed, whereas I believe that they are?

My code is as followed:

/*
*
*
*   This class will allow control of the super global $_SESSION within PHP
*       It's possible to import this class within websites which are already working with session variables.
*   Currently the functionality provides:
*       Invoking a new session
*       Getting the current session stats
*       Setting a session key/value
*       Getting the session value
*       displaying the session array
*
*
*
*/

class Session {
    protected $Session_Started = false;

    public function __construct(){
        /*
        *
        *   If session is already invoked,  the constructor
        *   will switch the protected variable to true, and the session_start function will not be called
        *       If session is not already invoked, the protected variable will remain false and provide the ability
        *           To invoke a session_start() by calling $Class->init();
        */
            if (session_status() === 1){
                $this->Session_Started = true;
                return false;
            }
            return true;
    }
    public function init(){
        /*
            Invoke a session

        */
        if ($this->Session_Started === false){
            session_start();
            $this->Session_Started = true;
            return true;
        }
        return false;
    }
    public function Status_Session(){
        /*
            Getting the current session status, and return readable information on the current status
        */
        $Return_Switch = false;
        if (session_status() === 1){
            $Return_Switch = "Session Disabled";
        }elseif (session_status() === 2){
            $Return_Switch = "Session Enabled, but no sessions exist";
        }elseif (session_status() === 3){
            $Return_Switch = "Session Enabled, and Sessions exist";
        }
        return $Return_Switch;
    }
    public function Set ($Key = false, $Value){
        /*
            Set a value within the $_SESSION global
                this function will return true, if a sucessfull addition has been made
                and return false if a problem is enountered
        */
        if ($this->Session_Started === true){
            $_SESSION[$Key] = $Value;
            return true;
        }
        return false;
    }
    public function Get ($Key){
        /*
            Invoking this function will return the current value of the session key, else return false is an error is encountered
        */
        if (isset($_SESSION[$Key])){
            return $_SESSION[$Key];
        }
        return false;
    }
    public function Display(){
        /*
            If session is started, this function will return a readable and formatted array
        */
        if ($this->Session_Started === true){
            return "<pre>".$_SESSION."</pre>";
        }
    }

} // Close class

Now, for example:

$Class = new Session();

if ($Class->Set("Key","Value")){
  echo "Created Value/key within the Session array, and returned true";
}

I understand that people like to validate a successful/fail boolean based on true and false, so I have included the correct return, but my overall question is just to confirm which I believe is correct.. Which is regarding the returns... Is it a perfectly acceptable thing to do, over having no returns? and within best preference?


texts:
I wrote this program to convert binary to hex, it ignores other characters between the binary digits. I would like to receive any recommendations on how to improve it.

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

const char table[] = "0123456789abcdef";

int main(int argc, char* argv[])
{
  int flip = argc - 2;
  unsigned char* ubin = argv[1];
  unsigned int nibble = 0;
  int i = 0;
  int nothing = 1;

  if((argc != 2) && (argc != 3 || strcmp(argv[2], "-f") != 0)){
    fprintf(stderr, "Usage: %s 00001111 [-f]\n", argv[0]);
    return EXIT_FAILURE;
  }

  printf("%s", "0x");

  while(*ubin){
    if((*ubin != '0') && (*ubin != '1')){
      ++ubin;
      continue;
    }

    nibble <<= 1;
    nibble |= *ubin - '0';

    if(++i == 4){
      i = 0;
      if(flip)
        nibble = ~nibble & 0xf;
      putchar(table[nibble]);
      nibble = 0;
      nothing = 0;
    }

    ++ubin;
  }

  if(nothing)
    putchar('0');

  putchar('\n');

  if(i)
    fprintf(stderr, "Error: %d bits were discarded, min unit is a nibble\n", i);

  return 0;
}


texts:
The following is a code to detect a loop in a linked list. This question is prepared strictly for interview purposes. This code has been modeled as per Linkedlist.java

How should I decide if a function like hasLoop() should be included as an instance method or should be a static method similar to sort in Collections.java?
Ideally I would inherit Linkedlist and add an extra function mergeSort to the subclass, but the interviewer would not like it, thus I should keep my solution without inheriting linkedlist for interview sake.  Do you agree?

    public class DetectLoopExistance<E> {

    private Node<E> first;
    private Node<E> last;

    public void add(E element) {
        final Node<E> l = last;
        final Node<E> newNode = new Node<E>(element, null);
        last = newNode;
        if (first == null) {
            first = newNode;
        } else {
            l.next = newNode;
        }
    }

    private static class Node<E> {
        E element;
        Node<E> next;

        Node(E element, Node<E> next) {
            this.element = element;
            this.next = next;
        }
    }

    public boolean hasLoop() {
        Node<E> fast = first;
        Node<E> slow = first;

        while (fast != null && fast.next != null) {
            fast = fast.next.next;
            slow = slow.next;
            if (slow == fast) {
                return true;
            }
        }
        return false;
    }
   }


texts: Replacing strings of blanks by tabs and blanks to achieve same spacing

texts:
#include <stdio.h>

#define MAXLINE 1000    /* Maximum length of a line */
#define TABSTOP 4       /* Length of tabstop */

int getLine(char line[], int limit);
int lookAhead(char line[], int start, int end);

    /*
     * Exercise 1-21
     * Write a program entab that replaces strings of blanks
     * by the minimum number of tabs and blanks to achieve the
     * same spacing.
     */

int main(void)
{
    int tabIndex, i;
    char line[MAXLINE];

    while ((getLine(line, MAXLINE)) > 0) {
        i = 0;
        while (line[i] != '\0') {
            if (line[i] == ' ') {
                tabIndex = i + (TABSTOP - (i % TABSTOP));
                if ((lookAhead(line, i + 1, tabIndex)) == 1) {
                    putchar('\t');
                    i = tabIndex;
                } else {
                    putchar(line[i]);
                    ++i;
                }
            } else {
                putchar(line[i]);
                ++i;
            }
        }
    }
    return 0;
}

int getLine(char line[], int limit)
{
    int inputVal, i;

    for (i=0; i < (limit - 1) && (inputVal = getchar()) != EOF &&
            inputVal != '\n'; ++i) {
        line[i] = inputVal;
    }
    if (inputVal == '\n') {
        line[i] = inputVal;
        ++i;
    }
    line[i] = '\0';
    return i;
}

int lookAhead(char line[], int start, int end)
{
    int i, clearPath;

    clearPath = 1;
    for (i = start; i < end; ++i) {
        if (line[i] != ' '){
            clearPath = 0;
        }
    }
    return clearPath;
}


texts: Movie info website (React, axios and Semantic UI)

texts:
import React, { Component } from 'react';
import { Grid, Header, Divider, Image, Embed, Button, Icon } from 'semantic-ui-react'
import axios from 'axios';

class Movie extends Component {
  constructor(props) {
    super(props);
    this.state = {
      title: '',
      year: '',
      poster: '',
      plot: '',
      rating: '',
      genres: '',
      runtime: ''
    };
  }

  componentWillMount() {
    axios.get('http://www.omdbapi.com/?i=tt0096895')
      .then((response) => {
      console.log(response.data);
        this.setState(
          {
            title: response.data.Title,
            year: response.data.Year,
            poster: response.data.Poster,
            plot: response.data.Plot,
            rating: response.data.imdbRating,
            genres: response.data.Genre,
            runtime: response.data.Runtime
          })
      })
      .catch((err) => {
        console.log(err);
      });
  }

  render() {
    return (

        <Grid container>
          <Grid.Column width={5}>
            <Image
              src={this.state.poster}
              fluid
            />
            <Button attached='top'>
              <Icon name='plus'/>
              Add to watchlist
            </Button>

            <Divider section/>

RATING

            <img className='imdb-icon' src="https://lh3.googleusercontent.com/lOC6oCAWrB7TNqvPdgJkQzUyC2pLc63n0iLCBtIE9CF-FFUjbbiAyW9AUPiCfkz3nOUxNE0SVZtxGsKRwDPsHqpOuHYadm2lEhx6wfobYyoPp8CfV3tO65ZTjJ8-91vT9Q7lwrOvDQF_sIOUGJ32TeIYdgWXHLiM3RNYS5LUq1fL71l5nL_37He7XokgUO6lbuwPOm7nNEAyBuyQgYzPgB-hxkzSGeUg6o4Tp7dAz8O3X6Cuhhxew-N23-zgqr4ag3dZ9L4De21WLO-WppAmgh752F4uY4Zt-IrbtxldHnOkve8OX3ktlRCHkrtcdHVL9jCWruyBpn3KZhL2fuMZ9oeWSVU3v4Gpkxb5xlh3MTveT8N45ih3WAYoP6Hm-Jz8qAhMQpfnmSRGzuQaX22FITypo_XeKcvkoSLUQMC1V68nuWcOT2MphDFyMgTjunmLBca74UpL5s3k2_FhJfS0RX0k0Y6IC6bUOL5gWcEu0d4rJv8iJHnXKft4zohH4PryAuE-G2q7rs4Vnb_65grz89QQGmF6OLGUhZowBfnGD8_MRE6Ev9Q92x8hMSFWZJZsz2wNk0eUxnCVSJFNVO1jphG2bSHy6ojYNVe9b-JVVQ3NlJr9KjB6=w64-h32-no"/>
            {this.state.rating}

GENRES

{this.state.genres}

RUNTIME

{this.state.runtime}

            <Divider section/>
          </Grid.Column>
          <Grid.Column width={11}>

              {this.state.title}

                ({this.state.year})

            <Embed id='O6Xo21L0ybE' source='youtube'/>

PLOT

{this.state.plot}

          </Grid.Column>
        </Grid>

    );
  }
}

export default Movie;

I am very new to React. This is for a school project and I would love to if someone reviewed my code. What improvements can I do?


texts: Count non-transparent pixels in a canvas

texts:
I need to count non-transparent pixels in a canvas. I am pretty sure there is a nice and elegant syntax for doing this. Note that the data returned by getImageData is not a regular array and cannot be sliced, for example, or it does not have a reduce method.

data = context.getImageData(0, 0, canvas.width, canvas.height).data
count = 0
i = 0
for x in data
  if (i + 1) % 4 == 0 && x > 0
    count++
  i++


texts: Reimplementation of call() method in JavaScript

texts:
I was try to reimplement the native call method in JavaScript.
Here we need to handle the object which we pass in the call function and additional params. I handle the additional params using eval() method. Is there any more efficient way to write it?

var name = {
    name: "JavaScript",
  version: "6",
}

function printName(location, district){
    alert(this.name + ", " + this.version + ", " + location + ", " + district);
}

Function.prototype.myCall = function(...args){
  var param = args.slice(1),
      paramLength = param.length,
      paramString = "JSONarg.myFun(";
  for(var i = 1; i <= paramLength; i++){
    paramString += "args["+i+"],";
  }
  paramString += ")";

  if(typeof this != 'function'){
    throw new Error(this + " is not a Function");
  }

  var JSONarg =  {
    ...args[0],
    myFun: this
  }
  return eval(paramString);
}

printName.myCall(name, "Chrome", "browser");


texts: VBA code to underline numbers in the header takes significant time and sometimes crashes excel

texts:
Background:

For several of my workbooks I run Overview sheets with charts in them.  When printing the Overview sheet, I put my workbook name as header, where the workbook name includes the criteria for the generating the source data (e.g., date range and time stamp plus non-numeric strings).

To draw attention to these numbers/dates/times, I can manually highlight on the print out, but when others print (using a button on the Overview sheet) they don't seem to remember to do that.

I am looking to add some "flare" to my header by underlining the numeric values.

Issue:

The workbook name character length varies, so I assess character by character.  In some cases the code executes after a delay (time varies, but will say that I had a 60 character length name take ~30 seconds), and other times Excel simply doesn't complete execution after several minutes (i will press escape and get the "code execution has been interupted" msgbox; this recently happened for a 48 character name).

Question:

As this is working code (sometimes), would you please help critique and possibly help resolve the time delay?

If my approach is inferior, I am open to suggestions, though I understand that, from my time on StackOverflow, subjective questions tend to be closed.

Code in question:

Option Explicit

Sub underline_numbers_in_header()
    Dim i As Long, n As String, z As String
    n = ActiveWorkbook.Name
    'Debug.Print Len(n)
    For i = 1 To Len(n)
        If IsNumeric(Mid(n, i, 1)) Then
            z = z & "&U" & Mid(n, i, 1) & "&U"
        Else
            z = z & Mid(n, i, 1)
        End If
        ActiveSheet.PageSetup.CenterHeader = "" & z & ""
    Next i
End Sub


texts: Template heap/priority-queue data structure with update-key operation

texts:
I implemented the following priority-queue/heap with an update-key operation. The update key uses the map from STL, which still requires lg(n) time for lookup. However, replacing it with an unordered_map would require the client program to write hash and equal operations for each class, which is a problem in my case.

#ifndef IZ_HEAP_H
#define IZ_HEAP_H

#include <map>
#include <vector>
#include <iostream>
#include <cassert>

using namespace std;

template <class T>
class IzHeap {
  class IzHeapItem {
    int key;
    T item;
  public:
    IzHeapItem(const int key, const T& item)
      : key(key), item(item) {}
    T getItem() const {return item;}
    int getKey() const {return key;}
    void updateKey(const int newKey) {key = newKey;}
    void updateItem(const T& newItem) {item = newItem;}
    IzHeapItem& operator=(const IzHeapItem& heapItem) {
      this->key = heapItem.getKey();
      this->item = heapItem.getItem();
      return *this;
    }
  };
  std::vector<IzHeapItem> heap;
  std::map<T, int> itemToHeapIndex;
  int leftChild(const int index) const {return index*2 + 1;}
  int rightChild(const int index) const {return index*2 + 2;}
  int parent(const int index) const {return (index - 1)/2;}
  void heapSwap(const int i, const int j) {
    /*
    IzHeapItem temp = heap[i];
    heap[i] = heap[j];
    heap[j] = temp;
    */
    std::swap(heap[i], heap[j]);

    itemToHeapIndex[getItem(i)] = i;
    itemToHeapIndex[getItem(j)] = j;
  }
  int getKey(const int index) const {return heap[index].getKey();}
  T getItem(const int index) const {return heap[index].getItem();}
protected:
  void shiftUp(const int index) {
    int largest{index}, p{parent(index)};
    if (p >= 0 && getKey(p) > getKey(index)) {
      largest = p;
    }
    if (largest != index) {
      heapSwap(largest, index);
      shiftUp(largest);
    }
  }
  void shiftDown(const int index) {
    int smallest{index}, lc{leftChild(index)}, rc{rightChild(index)};
    if (lc < heap.size() && getKey(lc) < getKey(smallest)) {
      smallest = lc;
    }
    if (rc < heap.size() && getKey(rc) < getKey(smallest)) {
      smallest = rc;
    }
    if (smallest != index) {
      heapSwap(smallest, index);
      shiftDown(smallest);
    }
  }
public:
  T extract() {
    assert(heap.size() > 0);
    heapSwap(0, heap.size() - 1);
    T item = heap.back().getItem();
    heap.pop_back();
    itemToHeapIndex.erase(item);
    shiftDown(0);
    return item;
  }
  T peak() {
    return heap[0];
  }
  bool empty() {
    return heap.size() == 0;
  }
  void insert(const T& item, const int key) {
    heap.push_back(IzHeapItem(key, item));
    itemToHeapIndex[item] = key;
    shiftUp(heap.size()-1);
  }
  void updateKey(const T& item, const int newKey) {
    assert(itemToHeapIndex.count(item) > 0);
    int index = itemToHeapIndex[item];
    int oldKey = getKey(index);
    heap[index].updateKey(newKey);
    if (newKey > oldKey) {
      shiftDown(index);
    }
    else {
      shiftUp(index);
    }
  }
  void heapify(const std::vector<T>& items, const std::vector<int>& keys) {
    assert(items.size() == keys.size());
    for (int i = 0; i < items.size(); ++i) {
      heap.push_back(IzHeapItem(keys[i], items[i]));
      itemToHeapIndex[items[i]] = i;
    }
    for (int i = heap.size()/2 - 1; i >=0; --i) {
      shiftDown(i);
    }
  }
  friend std::ostream& operator<<(std::ostream& out, const IzHeap<T>& heap) {
    for (auto& hi : heap.heap) {
      out << "(" << hi.getKey() << "->" << hi.getItem() << "), ";
    }
    return out;
  }
};

#endif

Please comment on any improvements that can be done on this code. This is my first time posting on code review, so please let me know of any norms I should follow.


texts: Keeping history of Django model (by using memoization?)

texts:
I'm working on a Django project for which I'll need to store the historic information of many models.
So far, I'm using the following strategy:

Memoize the relevant values in __init__.
When saving, check if a relevant value has changed.
If a relevant value has changed, save memoized values into a "history" model.

My code goes as follows:
from django.db import models
from core.models import User

class Spam(models.Model):
    user= models.OneToOneField(User, on_delete=models.PROTECT, related_name='spam')
    ham = models.CharField(max_length=10)
    eggs = models.IntegerField()

    def __init__(self, *args, **kwargs):
        super(Spam, self).__init__(*args, **kwargs)
        self.__relevant_fields = ['ham', 'eggs']
        self._memoize()

   def _memoize(self):
       for f in self.__relevant_fields:
           setattr(self, '__prev_%s' % f, getattr(self, f))

   def _get_prev_value(self, f):
       return getattr(self, '__prev_%s' % f)

   def _dirty_field(self, f) -> bool:
       return getattr(self, '__prev_%s' % f) != getattr(self, f)

   def _dirty(self) -> bool:
       return any([self._dirty_field(f) for f in self.__relevant_fields])

   def _save_history(self):
       history = dict()
       for f in self.__relevant_fields:
           history[f] = self._get_prev_value(f)
       self.user.spam_history.create(**history)

   def save(self, *args, **kwargs):
       super(Spam, self).save(*args, **kwargs)
       if self._dirty():
           self._save_history()

class SpamHistory(models.Model):
    user = models.ForeignKey(User, on_delete=models.PROTECT, related_name='spam_history')
    ham = models.CharField(max_length=10)
    eggs = models.IntegerField()

Although this approach works, there are some things that make me uncomfortable:

I need to do this for many models, so I'm repeating myself a lot! I'm looking into inheritance, mixins or the like, but so far I haven't found a right way to make it work.
Is this the best approach to achieve what I want? Considering that I will need to fetch historic records frequently, I need the "history" model for each model I need to keep history from.

So, my specific questions are:

Am I implementing a good strategy for keeping the history of my model(s)?
Is there a way to improve this strategy by using an inheritance or mixin strategy?


texts: Hand crafted longest common sub sequence

texts:
I know that the below solution is not the best one and I am in the way to learn that stuff till then I have applied the brute force to see how far I can go with my intuition.

console.clear();

function allButLast(arr) {
  return arr.slice(0, arr.length - 1);
}

function last(xs) {
  return xs.slice(-1);
}

function map(xs, cb) {
  return [].map.call(xs, cb);
}

function powerset(xs) {
  if (xs.length === 0) return [[]];
  var res = powerset(allButLast(xs));

  return res.concat(map(res, function(el) { return el.concat(last(xs)); }));
}

console.log(powerset([]));           // [[]]
console.log(powerset([1]));          // [[], [1]]
console.log(powerset([1, 2]));       // [[], [1], [2], [1, 2]]
console.log(powerset([1, 2, 3]));    // [[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]]

function increasing(xs) {
  var i = 1,
      l = xs.length;
  for (;i < l; i++) {
    if (xs[i] < xs[i - 1]) return false;
  }
  return true;
}

console.log(increasing([1, 2]));

function LIS(xs) {
  var res = [];
  [].forEach.call(powerset(xs), function(subset){
    if (increasing(subset) && subset.length > res.length) res = subset;
  });
  return res;
}

console.log(LIS([2, 3, 1, 4, 0, 5])); // [2, 3, 4, 5]

I have tried to be as much naive as possible because sometimes the best solution doesn't come to your mind most probably in the case of interview etc. I need to know if the code is clear and readable?


texts:
I am translating this next permutation algorithm in C++:

template<class BidirIt>
bool next_permutation(BidirIt first, BidirIt last)
{
    if (first == last) return false;
    BidirIt i = last;
    if (first == --i) return false;

    while (true) {
        BidirIt i1, i2;

        i1 = i;
        if (*--i < *i1) {
            i2 = last;
            while (!(*i < *--i2))
                ;
            std::iter_swap(i, i2);
            std::reverse(i1, last);
            return true;
        }
        if (i == first) {
            std::reverse(first, last);
            return false;
        }
    }
}

Into this Rust code:
struct Solution;
impl Solution {
    pub fn next_permutation(nums: &mut Vec<i32>) -> bool{
        if nums.len() < 2 {
            return false;
        }
        let first = 0;
        let last = nums.len();
        let mut i = last - 1;
        loop {
            let i1 = i;
            i -= 1;

            if nums[i] < nums[i1] {
                let mut i2 = last;

                loop {
                    i2 -= 1;
                    if nums[i] < nums[i2] {
                        break;
                    }
                }
                let tmp = nums[i];
                nums[i] = nums[i2];
                nums[i2] = tmp;
                nums[i1..last].reverse();
                return true;
            }
            if i == first {
                nums[first..last].reverse();
                return false;
            }
        }
    }
}

Though it works, I think it's not very good-looking. I am a beginner in Rust; any improvement will be welcome!


texts:
I solved this problem on Leetcode

  There is a brick wall in front of you. The wall is rectangular and has
  several rows of bricks. The bricks have the same height but different
  width. You want to draw a vertical line from the top to the bottom and
  cross the least bricks.

  The brick wall is represented by a list of rows. Each row is a list of
  integers representing the width of each brick in this row from left to
  right.

  If your line go through the edge of a brick, then the brick is not
  considered as crossed. You need to find out how to draw the line to
  cross the least bricks and return the number of crossed bricks.

  You cannot draw a line just along one of the two vertical edges of the
  wall, in which case the line will obviously cross no bricks.

Input:
[[1,2,2,1],
 [3,1,2],
 [1,3,2],
 [2,4],
 [3,1,2],
 [1,3,1,1]]
Output: 2

  Explanation:

The time complexity is O(height of the wall * total bricks in the wall) assuming Add, Remove, ContainsKey in Dictionary is O(1) and the space complexity is O(height of the wall).

I'm not sure if there is a better algorithm or more suited data structure that could improve the performance.

public int LeastBricksDictionary(IList<IList<int>> wall)
{
    var totalRows = wall.Count;
    var values = new SortedDictionary<int, List<Tuple<int, int>>>();
    int leastBrick = int.MaxValue, bricksNotCrossing = 0;
    for (int i = 0; i < wall.Count; i++)
    {
        var newTuple = new Tuple<int, int>(i, 0);
        if (values.ContainsKey(wall[i][0]))
        {
            values[wall[i][0]].Add(newTuple);
        }
        else
        {
            values.Add(wall[i][0], new List<Tuple<int, int>>() { newTuple });
        }
    }
    while (values.Count > 0)
    {
        int minSum = values.Keys.First();
        var minList = values[minSum];
        values.Remove(minSum);
        bricksNotCrossing = 0;
        foreach (var temp in minList)
        {
            int row = temp.Item1, col = temp.Item2;

            if (wall[row].Count > 1 && col + 1 < wall[row].Count)
            {
                ++bricksNotCrossing;
            }
            if (col + 1 < wall[row].Count)
            {
                int newSum = minSum + wall[row][col + 1];
                var newTuple = new Tuple<int, int>(row, col + 1);
                if (values.ContainsKey(newSum))
                {
                    values[newSum].Add(newTuple);
                }
                else
                {
                    values.Add(newSum, new List<Tuple<int, int>>() { newTuple });
                }
            }
        }
        leastBrick = Math.Min(leastBrick, totalRows - bricksNotCrossing);
    }
    return leastBrick;
}


texts: In memory data access for CSV files that may have changed

texts:
I'm reading data from CSV files and store the result in a simple DataContext instance that gets injected throughout my application.

public class DataContext
{
    private static readonly IDictionary<Type, IEnumerable<BaseEntity>> EntityMap =
        Assembly.GetExecutingAssembly().GetTypes()
        .Where(t => t.IsClass && !t.IsAbstract && t.IsSubclassOf(typeof(BaseEntity)))
        .ToDictionary(t => t, t => Enumerable.Empty<BaseEntity>());

    public IEnumerable<T> Get<T>() where T : BaseEntity
    {
        return EntityMap[typeof(T)].Cast<T>();
    }

    public void Set<T>(IEnumerable<BaseEntity> value) where T : BaseEntity
    {
        EntityMap[typeof(T)] = value.ToList();
    }
}

I listen for changes in a folder. As soon as a CSV file gets updated, I'll update the corresponding list. Something like this:

void OnFileChange(string fileName)
{
    // handle in a separate thread to decrease the load of FileSystemWatcher
    Task.Run(() => {
        var parsedFileData = parser.Parse<DataType>(fileName);
        dataContext.Set<DataType>(parsedFileData);
    });
}

I never do a delta update of entities. It's always a complete replacement of the collection, which is by intention.

Some thoughts:

What do you think of this in memory approach with variables vs something like Redis?
Any other comments?


texts:
I need to find a specific string of text from a large source of material. I've just used Excel VBA up to this point, so I don't know the Word objects and I ended up just recording some macros and working with what I had. However, this way is very inefficient. I looked on Stack Overflow, but I didn't understand what they were doing, so I just did it this way.

What I am mostly looking for is the objects used in Word VBA that are equivalent to the Excel 'Range', 'Cells', 'Row', and 'Column'.  I looked on MSDN, but there is so much material there that you need to have an idea of what you are looking for, and I couldn't find any other sites that would help.

This is what I wrote, and it did the job, but it is very inefficient.

Sub FindMediaInBraces()

    ' Separate needed text
    Selection.HomeKey Unit:=wdStory
    With Selection.Find
        .Text = "[Media"
        .Replacement.Text = "^p^p[Media"
        .Forward = True
        .Wrap = wdFindContinue
    End With
    Selection.Find.Execute Replace:=wdReplaceAll

    Selection.HomeKey Unit:=wdStory
    With Selection.Find
        .Text = ".jpg]"
        .Replacement.Text = ".jpg]^p^p"
        .Forward = True
        .Wrap = wdFindContinue
    End With
    Selection.Find.Execute Replace:=wdReplaceAll

    Selection.HomeKey Unit:=wdStory
    With Selection.Find
        .Text = ".png]"
        .Replacement.Text = ".png]^p^p"
        .Forward = True
        .Wrap = wdFindContinue
    End With
    Selection.Find.Execute Replace:=wdReplaceAll

    ' Remove text that doesn't start correctly
    Dim i As Long

    Selection.HomeKey Unit:=wdStory
    For i = 1 To ActiveDocument.Paragraphs.count
        Selection.MoveDown Unit:=wdParagraph, count:=1, Extend:=wdExtend
        With Selection.Find
            .Execute FindText:="[Media"
            .Forward = True
            If .Found = True Then
                Selection.MoveDown Unit:=wdParagraph, count:=1
            Else
                Selection.Delete Unit:=wdCharacter, count:=1
            End If
        End With
    Next

End Sub

Example Text

Original

Type: MC
Objectives: 2.6
16) [HTML]If y varies directly with x, write an equation for the direct variation. Then find the value. If y = -4 when x = -28, what is the value of x when y = 5?[/HTML]
*a. `$y=\frac{1}{7}x;\,\, 35$`
b. `$y=-\frac{1}{7}x;\,\, -35$`
c. `$y=7x;\,\, \frac{5}{7}$`
d. `$y=-7x;\,\, -\frac{5}{7}$`

Type: MC
Objectives: 3.3
21) Select the graph that correctly represents the following system of equations:
  `$y=-\frac{5}{3}x+3$`
  `$y=\frac{1}{3}x-3$`
*a. [Media:Media/Images/Problem 21a.jpg]
b. [Media:Media/Images/Problem 21b.jpg]
c. [Media:Media/Images/Problem 21c.jpg]
d. [Media:Media/Images/Problem 21d.jpg]

After Macro

[Media:Media/Images/Problem 21a.jpg]
[Media:Media/Images/Problem 21b.jpg]
[Media:Media/Images/Problem 21c.jpg]
[Media:Media/Images/Problem 21d.jpg]

This is what I found on Stack Overflow, but I don't know the objects to use to apply it, and I don't know if it would actually work in this case.

dim str as string
dim openPos as integer
dim closePos as integer
dim midBit as string

str = "NUMBER(8,3)"
openPos = instr (str, "(")
closePos = instr (str, ")")
midBit = mid (str, openPos+1, closePos - openPos - 1)


texts:
The purpose of this code to is check the 3 float switches in the laminator chamber for water. The float switches vote with the majority winning. A momentary switch must be pressed for the section of code (//// START FILL LAMINATOR FROM 70GALLON RES ///) to be active.

We can also take water from the reservoir using a different button (latching):

///// START Fill Water Bucket

///START set pins  ///
const int startBucket =5;
const int pumpBucketValve =6;
const int startButton = 7;
const int floatSwitch1 = 8;
const int floatSwitch2 = 9;
const int floatSwitch3 = 10;
const int pumpPower = 11;
const int pumpBallValve = 12;
///END set pins  ///

///START set pins values  ///
int floatSwitchState1 = 0;
int floatSwitchState2 = 0;
int floatSwitchState3 = 0;
int summedValue = 0;
int pumpPowerState = 0; //turns pump on and opens the ball valve to the laminator
int startButtonState = 0;
int startBucketState = 0;
int pumpBucketValveState = 0;

///END set pins values  ///

///START set pins mode  ///
void setup() {

pinMode(floatSwitch1, INPUT);
pinMode(floatSwitch2, INPUT);
pinMode(floatSwitch3, INPUT);
pinMode(pumpPower, OUTPUT);
pinMode(pumpBucketValve, OUTPUT);
pinMode(startButton, INPUT);
pinMode(startBucket, INPUT);
}

///END set pins modes  ///

void loop() {
//// START FILL LAMINATOR FROM 70GALLON RES ///
startButtonState = digitalRead(startButton);
if (startButtonState == HIGH) {
    while (checkFloat >= 2) {
      digitalWrite(pumpPower, HIGH);
    }
      digitalWrite(pumpPower, LOW);
}
//// END FILL LAMINATOR FROM 70GALLON RES ///

///// START Fill Water Bucket
startBucketState = digitalRead(startBucket);
while (startButtonState == HIGH) {
      digitalWrite(pumpBucketValve, HIGH); //turn ball valve to on
    }

digitalWrite(pumpBucketValve, LOW); //turn ball valve to off

///// END FILL Water Bucket
}

int checkFloat() {
    summedValue = 0;
    floatSwitchState1 = digitalRead(floatSwitch1);
    if (floatSwitchState1 == HIGH) {
      summedValue = summedValue + 1;
    }
    floatSwitchState2 = digitalRead(floatSwitch2);
    if (floatSwitchState2 == HIGH) {
      summedValue = summedValue + 1;
    }
    floatSwitchState3 = digitalRead(floatSwitch2);
    if (floatSwitchState3 == HIGH) {
      summedValue = summedValue + 1;
    }
    return summedValue;
}


texts:
I'm attempting to create a function that will select the correct carton based on the qty of the carton content.

Here are my cartons that have the number of items they can hold:

SMALL_PASCAL = 300
BIG_PASCAL = 600
BABY_BOX = 1200
A485_1201 = 1800
A4140_1901 = 3000
A485 = 5000

And here is the method that will return the CartonType:

/// <summary>
/// Get Carton Type
/// </summary>
/// <param name="qty"></param>
/// <returns></returns>
[Test]
private static CartonType GetCartonType(int qty)
{
     if (qty <= 300)
     {
         return CartonType.SMALL_PASCAL;
     }
     else if (qty > 300 && qty <= 600)
     {
         return CartonType.SMALL_PASCAL;
     }
     else if (qty > 600 && qty <= 1200)
     {
         return CartonType.BABY_BOX;
     }
     else if (qty > 1200 && qty <= 1800)
     {
         return CartonType.A485_1201;
     }
     else if (qty >1800 && qty <=3000)
     {
         return CartonType.A4140_1901;
     }
     else // 5000 or more.
     {
         return CartonType.A485;
     }
}

Calling the method like so:

int qty = 1540;
Console.WriteLine(GetCartonType(qty));

Output:

A485_1201

Is there a better way to achieve this rather than an if statement? Also, I just had a thought that what if the qty is like 10,000? I would then require 2 A485.


texts: Avoid indexing the keys in a Javascript array

texts:
I need a data structure to store feeds in columns into tabs.

So the pseudo structure would be:

First Tab : name (string)
    First column
        First feed : (url (str), type (str), limit (int))
        Second feed : (url (str), type (str), limit (int))
    Second column
        First feed : (url (str), type (str), limit (int))
        Second feed : (url (str), type (str), limit (int))
        Third feed : (url (str), type (str), limit (int))
Second Tab : name (string)
    First column
        First feed : (url (str), type (str), limit (int))
    Second column
        First feed : (url (str), type (str), limit (int))

... And so on.

Now this works:

  var feeds = [
    {"groupName":"News",
     "0": [
       {"url":"http://xkcd.com/rss.xml","type":"mixed","limit": 8},
       {"url":"http://xkcd.com/rss.xml","type":"photo","limit": 4}
     ],
     "1": [
       {"url":"http://xkcd.com/rss.xml","type":"mixed","limit": 8},
       {"url":"http://xkcd.com/rss.xml","type":"mixed","limit": 8},
       {"url":"http://xkcd.com/rss.xml","type":"photo","limit": 4}
     ]
    },
    {"groupName":"Comics",
     "0": [
       {"url":"http://xkcd.com/rss.xml","type":"photo","limit": 8},
       {"url":"http://superphazed.tumblr.com/rss","type":"photo","limit": 8}
     ]
    }
  ];

But

I want to avoid maintaining a numerical index for the column keys ;
I'm not sure it's the right data structure type.

Apparently the form above is a JavaScript literal object, that is, not an array and not JSon. This is a problem, I want to use the right data structure for what I intend to do with it : At one point in time, I need to validate variables against this data structure, that is to say "OK, this variable is a proper list of feeds". I also need to easily add, delete and rename elements, and from what I can see, there are at least 3 approaches to "arrays" in JavaScript, each with its own set of idiosyncrasies, methods and tools, dos and don'ts ; The context is JavaScript (module pattern) in the browser, and JQuery is available.

So I guess my question is twofold:

What is the best data structure in this context to allow easy manipulation later ;
Is there a way to have unnamed columns containing non-indexed feeds?


texts: Remove specified number of characters from a string

texts:
From an exercise in Kochan's Programming in C, following a chapter on C's null-terminated strings:

  Write a function called removeString to remove a specified number of
  characters from a character string. The function should take three
  arguments: the source string, the starting index number in the source
  string, and the number of characters to remove. So, if the character
  array text contains the string "the wrong son", the call

  removeString (text, 4, 6);

  has the effect of removing the characters “wrong “ (the
  word “wrong” plus the space that follows) from the array text. The
  resulting string inside text is then "the son".

I found the exercise interesting to implement. I know I could have used strlen to get the length of the string, but I like the idea of handling everything in a single pass (I imagine strlen has to traverse the characters looking for a null-byte).

Any comments/criticisms are welcome. Here's my solution:

void removeString (char text[], int index, int rm_length)
{
    int i;

    for ( i = 0; i < index; ++i )
        if ( text[i] == '\0' )
            return;

    for ( ; i < index + rm_length; ++i )
        if ( text[i] == '\0' ) {
            text[index] = '\0';
            return;
        }

    do {
        text[i - rm_length] = text[i];
    } while ( text[i++] != '\0' );
}

And a test drive

int main (void)
{
    char string1[] = "the wrong son";
    char string2[] = "the wrong son";
    char string3[] = "the wrong son";

    printf ("string1: %s\n", string1);
    printf ("string2: %s\n", string2);
    printf ("string3: %s\n\n", string3);

    printf ("removeString (string1, 13, 6)\n");
    removeString (string1, 13, 6);
    printf ("string1: %s\n\n", string1);

    printf ("removeString (string2, 11, 6)\n");
    removeString (string2, 11, 6);
    printf ("string2: %s\n\n", string2);

    printf ("removeString (string3, 4, 6)\n");
    removeString (string3, 4, 6);
    printf ("string3: %s\n\n", string3);

    return 0;
}

Output:

string1: the wrong son
string2: the wrong son
string3: the wrong son

removeString (string1, 13, 6)
string1: the wrong son

removeString (string2, 11, 6)
string2: the wrong s

removeString (string3, 4, 6)
string3: the son


texts: Is there a better, more efficient way than Dictionary(Of Tuple(), MyClass)?

texts:
Suppose I have data coming from different sources that tells me information about a large group of stores that has the following (just an example):

Necessary to define what store we're dealing with:

Store_Name (String)
Location (String)

Store characteristics:

Square_Feet (Double)
No_Employees (Double)
Years_Open (Double)
... (Whatever else)

And the structure of the program I'm working with is such that we will always get the first 2 (defining) characteristics and one or more of the store-specific characteristics. My goal is to conglomerate all the characteristics for each of the specific stores together.

To do this, I have created the following class:

Public Class StoreChars
    Public Property Square_Feet as Double = 0
    Public Property No_Employees as Double = 0
    Public Property Years_Open as Double = 0
    ...
End Class

And then, in my program, I have created the following:

Dim StoreData As New Dictionary(Of Tuple(Of String, String), StoreChars)

The key being the Store_Name and Location as the defining tuple.

So, now, in my code, supposing I just got some data together with the defining characteristics for a set of stores (might be some, might be all... we don't know if we've seen these before or not even), my loop to put in that data looks as follows:

For Each PieceOfInfo in ReturnedData
   Dim TupleKey As New Tuple(Of String, String)(PieceOfInfo.Store_Name,
                                                PieceOfInfo.Location)

   If Not StoreData.ContainsKey(TupleKey) Then
        StoreData.Add(TupleKey, New StoreChars With
                                {
                                 .Square_Feet = PieceOfInfo.Square_Feet
                                     ... (whatever else we got) ...
                                })
   Else
        StoreData(TupleKey).Square_Feet = PieceOfInfo.Square_Feet
                     ... (whatever else we got) ...
   End If
Next

But this seems to be very slow and I'm wondering if it isn't overly-processor-intensive to create a tuple in each loop, check the existence as a key, etc, but I can't think of a better way to do this.

The other solution I was thinking of was to create a Dictionary(Of String, Dictionary(Of String, StoreChars)). That would eliminate having to create a Tuple with each loop, but it would mean having to check existence of the keys in 2 separate dictionaries.

If there is a better way to do this, I would LOVE to hear what it is because I find myself having to program solutions like this fairly often!

Also, even though I wrote this code in VB, I'm just as comfortable with a C# solution - I'm just currently working in a VB environment.


texts:
This is regards to one of my answers: Linq Expression Calling Combines. The question wasn't very well received, but it proved to be an interesting task that I enjoyed working on.

I ended up with the following:

public static class ExpressionHelpers
{
    public static TExpressionType InlineInvokes<TExpressionType>(this TExpressionType expression)
        where TExpressionType : Expression
    {
        return (TExpressionType)new InvokeInliner().Inline(expression);
    }

    public static Expression InlineInvokes(this InvocationExpression expression)
    {
        return new InvokeInliner().Inline(expression);
    }

    public class InvokeInliner : ExpressionVisitor
    {
        private Stack<Dictionary<ParameterExpression, Expression>> _context = new Stack<Dictionary<ParameterExpression, Expression>>();
        public Expression Inline(Expression expression)
        {
            return Visit(expression);
        }

        protected override Expression VisitInvocation(InvocationExpression e)
        {
            var callingLambda = e.Expression as LambdaExpression;
            if (callingLambda == null) //Fix as per comment
                return base.VisitInvocation(e);
            var currentMapping = new Dictionary<ParameterExpression, Expression>();
            for (var i = 0; i < e.Arguments.Count; i++)
            {
                var argument = Visit(e.Arguments[i]);
                var parameter = callingLambda.Parameters[i];
                if (parameter != argument)
                    currentMapping.Add(parameter, argument);
            }
            _context.Push(currentMapping);
            var result = Visit(callingLambda.Body);
            _context.Pop();
            return result;
        }

        protected override Expression VisitParameter(ParameterExpression e)
        {
            if (_context.Count > 0)
            {
                var currentMapping = _context.Peek();
                if (currentMapping.ContainsKey(e))
                    return currentMapping[e];
            }
            return e;
        }
    }
}

At its core, it simply in-lines Invoke() calls in the expression tree, replacing them with the called expression's code verbatim.

Examples:

INPUT:
Invoke(i => (i + 1), 3)

OUTPUT:
(3 + 1)

INPUT:
i => Invoke((i, j) => (i * j), Invoke(i => (i + 1), i), Invoke(i => (i + 2), i))

OUTPUT:
i => ((i + 1) * (i + 2))

INPUT:
b => Invoke((d, e) => (d * e), Invoke(b => (50 + Invoke(z => (25 + Invoke(h => (h * 8), z)), b)), b), Invoke(c => (c + 2), b))

OUTPUT:
b => ((50 + (25 + (b * 8))) * (b + 2))

Example usage:

Expression<Func<int, int>> f1 = i => i + 1;
Expression<Func<int, int>> f2 = i => i + 2;
Expression<Func<int, int, int>> f3 = (i, j) => i * j;

var p = Expression.Parameter(typeof(int), "i");
var r = Expression
    .Invoke(f3, new[] {
        Expression.Invoke(f1, p),
        Expression.Invoke(f2, p) })
    .InlineInvokes();

Expression<Func<int, int>> lam = Expression.Lambda<Func<int, int>>(r, p);

The only 'issue' I can come up with is that if one were to modify f1 after InlineInvokes() was called, they might be surprised if they were expecting f1 to be captured and lazily executed, but in my opinion, this is probably to be expected (any other opinions?).

In summary, my questions are:

Are there any pitfalls in in-lining invocations (that is, is my idea fundamentally flawed, and cannot be solved 'properly')?
Are there any issues with the code I've written itself?