texts: How do I generate a list of n unique random numbers in Ruby?

texts:
I am trying to create a randomly generated array of x numbers with no duplicates. I am choosing numbers, one at a time, then comparing each new number to the numbers already in the array.

Here is my code. At the end I should have an array of seven numbers, none that match, but sometimes I get a nil:

array = [] #DEFINES THE ARRAY

array[0] = rand(10)  #THIS CHOOSES FIRST NUMBER (FN) AND PUTS IT IN THE FIRST ARRAY SPOT
p "fn = #{array[0]}"

for i in 1..6  #START OF FOR LOOP TO GET 6 NUMBERS IN THE ARRAY - WHY 6?  THE FIRST NUMBER THAT POPPED IN MY HEAD

  p "Iteration #{i} -------------------------"  # THIS IS JUST SO I KNOW WHERE I AM IN THE LOOPS

  @x = rand(10)  #THIS CHOOSES THE NEXT NUMBER AND ALL NUMBERS AFTER

  array.each do |uc|  # THIS IS THE LOOP THAT COMPARES ALL NUMBERS

    @type = @x == uc ? "yes" : "no"  #DOES THE CHOSEN NUMBER EQUAL ANY NUMBER IN THE ARRAY

    p "does #{uc} = #{@x}? #{@type}"
    if @type == "yes"  # IF THE COMPARE IS TRUE, I DON'T WANT ANYTHING DONE.  IT WILL CYCLE THRU AND GET A NEW NUMBER

      i = 1
      p "YES #{@x} = #{uc}"
      break
    end  #END OF IF YES
  end  #END OF ARRAY EACH

  if @type == "no"  #IF NO, PUT NEXT NUMBER (@X) INTO THE NEXT ARRAY SPOT.

    p "in last if type= #{@type}"  #THESE STATEMENTS JUST PRINT OUT THE DIFFERENT VARIABLES SO I KNOW I AM GETTING WHAT I EXPECT

    p "in last if x = #{@x}"
    p "in last if i = #{i}"
    @x = array[i]  #THIS "SHOULD" FILL THE NEXT ARRAY SPOT - BUT DOESN'T SEEM TO

    p "#{array[i]} is in the array"  #THIS PRINT OUT IS BLANK - STATEMENT ABOVE DID NOT WORK.

    p array[i]
  end  #END OF IF NO

end  #END OF FOR LOOP

p array #PRINTS OUT THE CONTENTS OF THE ARRAY

I know there are probably quicker and easier ways to do this, but I am starting out with what I know, and building up.


texts: Join strings with different delimiters and some possibly empty strings

texts:
I want to construct a string from several substrings, each one of those with a different delimiter. If the string is present, the delimiter and the string should be added, if not, none of them should be added.

This is my current code that looks a bit dirty to me:

def my_join(major, minor, patch=None, pre_release=None, build=None, revision=None):

   version = '.'.join(filter(None,(major, minor, patch)))

   if pre_release: version += '-%s'  % pre_release
   if build:       version += '+b%s' % build
   if revision:    version += '.%s'  % revision

   return version

my_join('0', '1',pre_release='alpha')
'0.1-alpha'
my_join('2','3','4', build='567', revision='aabbcc440')
'2.3.4+b567.aabbcc440'

My problem is basically an extension of join 4 strings to the one if they are not empty in python with the addition of using different delimiter strings.


texts: Greedy algorithms to find minimum number of coins (CS50)

texts:
I'm taking CS50, an Introduction to CS, and we're asked to do the following task:

Suppose that a cashier owes a customer some change and in that cashier’s drawer are quarters (25¢), dimes (10¢), nickels (5¢), and pennies (1¢). The problem to be solved is to decide which coins and how many of each to hand to the customer. Think of a “greedy” cashier as one who wants to take the biggest bite out of this problem as possible with each coin they take out of the drawer. For instance, if some customer is owed 41¢, the biggest first (i.e., best immediate, or local) bite that can be taken is 25¢. (That bite is “best” inasmuch as it gets us closer to 0¢ faster than any other coin would.) Note that a bite of this size would whittle what was a 41¢ problem down to a 16¢ problem, since 41 - 25 = 16. That is, the remainder is a similar but smaller problem. Needless to say, another 25¢ bite would be too big (assuming the cashier prefers not to lose money), and so our greedy cashier would move on to a bite of size 10¢, leaving him or her with a 6¢ problem. At that point, greed calls for one 5¢ bite followed by one 1¢ bite, at which point the problem is solved. The customer receives one quarter, one dime, one nickel, and one penny: four coins in total

Here is my solution to the problem:
#include <stdio.h>
#include <cs50.h>
#include <math.h>

float cents, money;
int ask_money(void);
int dollars_to_cents(int dollars);
int get_max_coins(int _cents, int coin_type);
int min_coins_exchanged(int _money, int _coin_types[], int _arr_length);
int quarter = 25, dimes = 10, nickles = 5, pennies = 1;

int main(void)
{
    money = dollars_to_cents(ask_money());
    int arr_length = 4;
    int coin_types[] = {quarter, dimes, nickles, pennies};
    printf("%i\n", min_coins_exchanged(money, coin_types, arr_length));
}

// Given some amount of money, this returns the maximum amount of coins of a certain type possible
// such that the remaining money is less than the value of the coin type, then it subtracts our money by that amount
int get_max_coins(int _cents, int coin_type)
{
    int max_coins = floor((float)((_cents) / coin_type));
    money -= max_coins * coin_type;
    return max_coins;
}

int ask_money(void)
{
    do
    {
        money = get_float("Change owed: ");
    }
    while (money < 0);
    return money;
}

// Necessary to avoid problems with floating point imprecision
int dollars_to_cents(int dollars)
{
    return round(money * 100);
}

// Calculates the minimum amount of coins exchanged such that when these coins are added up they are equal to the change owed
int min_coins_exchanged(int _money, int _coin_types[], int _arr_length)
{
    int _min_coins_exchanged = 0;
    for(int i = 0; i < _arr_length; i++)
    {
        _money = money;
        _min_coins_exchanged += get_max_coins(_money, _coin_types[i]);
    }
    return _min_coins_exchanged;
}

I'm looking for feedback on my code. How do I make my code better and cleaner? I.e in terms of readability, performance, comments, design principles, etc. There's a lot of ways to approach this problem, and indeed when trying to solve it I've tried many different ways but this is my current favorite. What do you think about my solution? Perhaps there's a better way to approach the problem?


texts:
I am trying to give show a UI friendly dump of the cache status

Cache Status

  Cache
  Created Time
  Last Updated
  Last Hit
  Hit Count
  Hit Count %
  Size

<cfoutput>
  <cfloop index="cache" array="#cacheGetAllIds()#">
    <cfset metaData = cacheGetMetadata(cache)>

      #cache#
      #LSTimeFormat(metadata.createdTime, "h:mm:ss")#
      #LSTimeFormat(metadata.lastHit, "h:mm:ss")#
      #LSTimeFormat(metadata.lastupdated, "h:mm:ss")#
      #metadata.hitcount#
      <cfset percent_of_hits = 100.0 * metadata.hitcount / metadata.cache_hitcount>
        #LSNumberFormat(percent_of_hits, '999.9')# %

      #LSNumberFormat(metadata.size)#

  </cfloop>
</cfoutput>

Bootstrap and Datatables formatting is applied. And it looks like this:

I want to make sure this is a good format and that I am not missing any easy to get at useful information


texts:
I'm making a website for a friend (just for fun) where we have to move a lot of svg images in absolute positions. To make it easier I wrote some code to calculate the % position of each element so we can do it faster.

I'm wondering what you think about it and what can I do to improve it. And also any improvements to my style of coding are welcome.


texts: Building XML elements from a list using LINQ and foreach

texts:
I wrote the following code:

var xmlArray = from m in (from row in data select row.Mitarbeiter).Distinct()
               select "<Value Type='Text'>" + m + "</Value>";
var xml = string.Join("",xmlArray);

Then I noticed there are two iteration (two from) and also the Distinct() and I rewrote it using a foreach:

var mitarbeiter = new List<string>();
var xmlArray = new List<string>();
foreach(var row in data)
{
    if (!mitarbeiter.Contains(row.Mitarbeiter)){
        mitarbeiter.Add(row.Mitarbeiter);
        xmlArray.Add("<Value Type='Text'>" + row.Mitarbeiter + "</Value>");
    }
}
var xml = string.Join("",xmlArray);

Ma opinion is that the first example is cleaner...but what about efficiency/performance?


texts: Creating and displaying a checkers board

texts:
I am learning clojure this week end and just starting to develop a simple checkers engine. I currently coded some basic functions to create the board and display it. I would love to get some feedback !

(ns sandbox.checkers)

(def standard-size 10)

(defn empty-board [size]
  (vec (replicate size (vec (replicate size :empty)))))

(defn str-piece [piece]
  (cond
    (= piece :empty) " "
    (= piece :white_man) "O"
    (= piece :black_man) "0"))

(defn str-board [board]
  (str "\n"
    (clojure.string/join
      "\n"
      (map
        #(clojure.string/join " | " (map str-piece %))
        board))))

(defn print-board [board]
  (println (str-board board)))

(defn fill-white [size]
  (apply comp
  (map
    (fn [pos]
      (fn [board] (assoc-in board pos :white_man)))
      (for [x (range size)
            y (range (inc (/ size 2)) size)
            :when (or (and (even? x) (even? y))
                      (and (odd? x) (odd? y)))]
        [y x]))))

(defn fill-black [size]
  (apply comp
    (map
      (fn [pos]
        (fn [board] (assoc-in board pos :black_man)))
      (for [x (range size)
            y (range 0 (dec (/ size 2)))
            :when (or (and (even? x) (even? y))
                      (and (odd? x) (odd? y)))]
        [y x]))))

(defn starting-board [size]
  ((fill-black size) ((fill-white size) (empty-board size))))

(print-board (starting-board standard-size))


texts: Generate N pairs of checkboxes and N textboxes

texts:
I've written a piece of code, where a pair of checkboxes and a textbox are generated N amount of times. Depending on what's in the DB, the checkbox/textbox may have a default value or are left empty.

I've pasted the code below, could anyone take a look to see if I haven't created an abomination?

    @if (singleItem != null && singleItem.FolderRead)
    {
        <input type="checkbox" id="canRead_@item.SecureFolderID" class="CHKreader" onchange="changePermissions(@item.SecureFolderID)" checked />
    }
    else
    {
        <input type="checkbox" id="canRead_@item.SecureFolderID" class="CHKreader" onchange="changePermissions(@item.SecureFolderID)" />
    }

    @if (singleItem != null && singleItem.FolderWrite)
    {
        <input type="checkbox" id="canWrite_@item.SecureFolderID" class="CHKwriter" onchange="changePermissions(@item.SecureFolderID)" checked />
    }
    else
    {
        <input type="checkbox" id="canWrite_@item.SecureFolderID" class="CHKwriter" onchange="changePermissions(@item.SecureFolderID)" />
    }

    @if (singleItem != null && singleItem.ExpireDate != null)
    {
        <input class="datepick" id="expDate-@item.SecureFolderID" onchange="changePermissions(@item.SecureFolderID)" value="@singleItem.ExpireDate.Value.ToString("yyyy-MM-dd")" />
    }
    else
    {
        <input class="datepick" id="expDate-@item.SecureFolderID" onchange="changePermissions(@item.SecureFolderID)" />
    }

I know the copy/paste code is not that clean. The textbox could be filled in with a variabele, which could remain empty if the DB record is as well. But I don't know if that makes the code more 'readable' or if such a method works for the Checkbox as well.


texts: Divide a set into subset with some constraints

texts:
Note - I am not sure whether this question belongs to stackoverflow or CSE stackexchange or here
Problem:
Given a list Lconsisting of not necessarily unique non-negative integers, find the minimum number of subset with maximum sum k(given) in which it can be divided such that:
each subset shouldn't contain consecutive elements from the list*.
(*): I can see an obvious ambiguity:
Q: If there is 3 4, is the restriction is on all 3 or just the adjacent three?
A: Just on adjacent 3.
Examples:

1. L = [2, 1, 1, 2], k = 2 => 4

Explanation: First set can take 0th index element
             second set can take 1st index element and similarly third and fourth can take 2nd and 3rd index element respectively

Here, you can see that k is working as a bottleneck

More examples:

L = [2, 4, 1, 0] k = 8 => 2

L = [3, 2, 3, 0, 0] k = 5 => 3

This seems to have some features of dynamic programming problems, so I went for dynamic programming and wrote the following recursive code:
from functools import lru_cache
def min_count(L, k):
    '''
    index - stores the current state's index
    sets - this stores information of already stored sets:
            It is tuple of tuple,
                In each tuple:
                    First element - index of last stored element
                    Second element - stores the sum of current set
    k - It is limit|capacity of each subset(same as the one given in arugment)

    '''
    @lru_cache(maxsize=None)
    def recurse(index, sets, k):
        #If control reaches to the end of the list
        if index == len(L):
            return len(sets)

        #In case the current indexes is zero
        if L[index] == 0:

            #If this is the last index, then
            if index + 1 == len(L):
                return len(sets)
            return recurse(index + 1, sets, k)

        '''

        The job of this for loop is iterate all of the stored sets:
            And if that's capable of storing further, then add current index
            to it, and recurse
        '''
        m = 1e10
        for i, j in sets:
            if i - index < -1 and j + L[index] <= k:
                if index + 1 == len(sets):
                    return len(sets)
                m = min(m, recurse(index + 1,tuple(_ if _ != (i, j) else (index, j + L[index]) for _ in sets) , k))

        m = min(m, recurse(index + 1, sets + ((index, L[index]), ), k))
        return m

    return recurse(0, (), k)

The problem is that this code works, but is very slow(the expected time complexity must be lower than O(n^2)).
How can I make it fast?


texts:
Create an application class named LetterDemo that instantiates objects
  of two classes named Letter and CertifiedLetter and that demonstrates
  all their methods. The classes are used by a company to keep track of
  the letter they mail to clients. The letter class includes
  auto-implemented properties for the name of the recipient and date
  mailed. Also , include a ToString() method that overrides the Object
  class's ToString() method and returns a string that contains the name
  of the class (using GetType()) and the Letter's data field values.
  Create a child class named CertifiedLetter that includes an auto
  implemented property that holds the tracking number for the letter.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Console;

namespace ConsoleApp16
{
class Program
{
    static void Main(string[] args)
    {

        Letter letter1 = new Letter();
        letter1.name = "\nSender: Justin";
        letter1.date = ("\nDate: March 4,2017 ");

        CertifiedLetter track = new CertifiedLetter();

        Write("Your letter has been recieved!");
        Write("\n");

        Write(letter1);
        Write("\n");
        Write("Tracking number:"+ track.GetHashCode());
        Write("\n");

    }
}
}

class Letter
{
public string name { get; set; }
public string date { get; set; }

public override string ToString()
{
    return (GetType() + ":" + this.name + "" + this.date);

}

}

class CertifiedLetter : Letter
{
    public string tracking { get; set; }

}

Looking to see how I could tighten up the code or if there is a better way to do this.


texts:
This is my first Haskell program, a command-line sdl-based(so, hopefully, cross-platform), parameter-less sound recorder. Tutorials, articles or chapters that concern mistakes in my code are just as welcome as concrete code corrections.

{-# OPTIONS_GHC -Wall #-}

-- Dependant on cabal packages: sdl2, wave.

module Main where

import qualified Control.Concurrent as C
--import qualified Control.Monad as M
import qualified Data.Vector.Storable.Mutable as V
import qualified Data.Set as S
import Foreign.ForeignPtr as P

import qualified SDL
import qualified SDL.Audio as A

import qualified Codec.Audio.Wave as W

import qualified System.IO as IO

micSpec :: IO.Handle -> A.OpenDeviceSpec
micSpec h = A.OpenDeviceSpec {A.openDeviceFreq = A.Mandate 48000
                             ,A.openDeviceFormat = A.Mandate A.Signed16BitNativeAudio
                             ,A.openDeviceChannels = A.Mandate A.Mono
                             ,A.openDeviceSamples = 4096
                             ,A.openDeviceCallback = \_ (V.MVector size ptr) -> P.withForeignPtr ptr (\p -> IO.hPutBuf h p size)
                             ,A.openDeviceUsage = A.ForCapture
                             ,A.openDeviceName = Nothing}

waveSpec :: W.Wave
waveSpec = W.Wave {W.waveFileFormat = W.WaveVanilla
                  , W.waveSampleRate = 48000
                  , W.waveSampleFormat = W.SampleFormatPcmInt 16
                  , W.waveChannelMask = S.singleton W.SpeakerFrontCenter
                  , W.waveDataOffset = 0
                  , W.waveDataSize = 0
                  , W.waveSamplesTotal = 0
                  , W.waveOtherChunks = []}

record :: IO.Handle -> IO ()
record h = do
  SDL.initialize [SDL.InitAudio]
  (dev, _) <- A.openAudioDevice $ micSpec h
  A.setAudioDevicePlaybackState dev A.Play
--  _ <- M.forever (C.threadDelay maxBound)
  _ <- C.threadDelay 10000000
  return ()

main :: IO ()
main =  W.writeWaveFile "mic.rec" waveSpec record

  $ hlint Main.hs
  No hints

Some of the concerns:

code duplication - micSpec and waveSpec should be somehow automatically connected, e.g. setting different frame rates should be impossible
what is an idiomatic approach for imports for such and application?
A.openDeviceCallback feels logically separate from the constants of the file format; with c function pointer thinking, there would be a factory micSpec :: (AudioFormat t -> IOVector t -> IO ()) -> A.OpenDeviceSpec; this looks like nonsense in Haskell
record() feels superfluous


texts:
I'm trying to get the URL of the browser with Mac OS X app. I wrote some AppleScript and am trying to use it in Cocoa. The problem is, when I watch it with instruments, memory is increasing, and at the end of 3-4 hours it's nearly 20MB.

First generation

Second generation (5 min. later)

#import "AppDelegate.h"
#import <Carbon/Carbon.h>

@interface AppDelegate ()
@property (weak) IBOutlet NSWindow *window;
@end

@implementation AppDelegate

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {

    [NSTimer scheduledTimerWithTimeInterval:1
                                     target:self
                                   selector:@selector(collect)
                                   userInfo:nil
                                    repeats:YES];
}

- (void)collect{
    [self runWithEvent];
}

- (void)runWithEvent{
    NSURL *URL = [[NSBundle mainBundle] URLForResource:@"frontmostapptitle" withExtension:@"scpt"];
    if (URL) {
        NSAppleScript *appleScript = [[NSAppleScript alloc] initWithContentsOfURL:URL error:NULL];

        NSAppleEventDescriptor *returnDescriptor = [self lookUpRunningApp];

        NSDictionary *error = nil;
        NSAppleEventDescriptor *resultEventDescriptor = [appleScript executeAppleEvent:returnDescriptor error:&error];

        if (! resultEventDescriptor) {
            NSLog(@"%s AppleScript run error = %@", __PRETTY_FUNCTION__, error);
        }
        else {
            NSLog(@"%@", [self stringForResultEventDescriptor:resultEventDescriptor]);
        }
    }
}

- (NSAppleEventDescriptor *)lookUpRunningApp{
    // target
    ProcessSerialNumber psn = {0, kCurrentProcess};
    NSAppleEventDescriptor *target = [NSAppleEventDescriptor descriptorWithDescriptorType:typeProcessSerialNumber bytes:&psn length:sizeof(ProcessSerialNumber)];

    // function
    NSAppleEventDescriptor *function = [NSAppleEventDescriptor descriptorWithString:@"LookUpRunningApp"];

    // event
    NSAppleEventDescriptor *event = [NSAppleEventDescriptor
                                     appleEventWithEventClass:kASAppleScriptSuite
                                     eventID:kASSubroutineEvent
                                     targetDescriptor:target
                                     returnID:kAutoGenerateReturnID
                                     transactionID:kAnyTransactionID];
    [event setParamDescriptor:function forKeyword:keyASSubroutineName];
    return event;
}

- (NSString *)stringForResultEventDescriptor:(NSAppleEventDescriptor *)resultEventDescriptor
{
    NSString *result = nil;

    if (resultEventDescriptor) {
        if ([resultEventDescriptor descriptorType] != kAENullEvent) {
            if ([resultEventDescriptor descriptorType] == kTXNUnicodeTextData) {
                result = [resultEventDescriptor stringValue];
            }
        }
    }
    return result;
}

@end


texts: Two-layer RAII to support a critical section

texts:
For the code, if one considers using RAII to encapsulate CriticalSection (global scope), two RAII layers are needed: InitializeCriticalSection layer (main function scope), enter EnterCriticalSection layer (multi-thread based Proc scope).

// Global variable
CRITICAL_SECTION CriticalSection;

int main( void )
{
    // Initialize the critical section one time only.
    if (!InitializeCriticalSection(&CriticalSection) )
        return;
    ...

    // Release resources used by the critical section object.
    DeleteCriticalSection(&CriticalSection);
}

DWORD WINAPI ThreadProc( LPVOID lpParameter )
{
    // Request ownership of the critical section.
    EnterCriticalSection(&CriticalSection);

    // Access the shared resource.

    // Release ownership of the critical section.
    LeaveCriticalSection(&CriticalSection);

    return 1;
}

As CriticalSection and the two layers all have different scopes, and also enter InitializeCriticalSection layer must be on top of EnterCriticalSection layer.

class CriticalSectionGuard {
public:
    CriticalSectionGuard(CRITICAL_SECTION * cs) : m_CS(cs) {
        InitializeCriticalSection(m_CS);
    }
    ~CriticalSectionGuard() {
        DeleteCriticalSection(m_CS);
    }
    void lock() {
        EnterCriticalSection(m_CS);
    }
    void unlock{
        LeaveCriticalSection(m_CS);
    }
private:
    CRITICAL_SECTION * m_CS;
}

class GetLock {
public:
    GetLock(CriticalSectionGuard* plock) : m_csg(plock) {
        m_csg->lock();
    }
    ~GetLock(void) {
        m_csg->unlock();
    }
private:
    CriticalSectionGuard * m_csg;
};

// Global variable
CRITICAL_SECTION CriticalSection;

int main(void)
{
    // Initialize the critical section one time only.
    CriticalSectionGuard CSG(&CriticalSection);
    ...
}
DWORD WINAPI ThreadProc(LPVOID lpParameter)
{
    // we need pass along the CSG Pointer, which is messy.
    GetLock(&CSG);
    ...

        return 1;
}

It looks quite bad, as the CriticalSectionGuard object is not in the global scope, it need pass along to threads.

Please share any suggestions or criticisms to improve the code.


texts: Mapping values. Should a single use variable be declared as a variable at all?

texts:
Where I have, let us say an object, that I will only use once, what is considered general best practice in terms of declaring it as var vs. simply putting the object directly into the method it will be used in? I'm thinking this is going to come down to "which do you think is more readable", but given my lack of experience thought I'd see if there was a consensus.
This came about when looking at the following code:
      var aiPersonalities = model.aiPersonalities();

      var newPersonalities = {
        qCasual: {
          ai_path: "/pa/q_casual",
          display_name: "!LOC:Q-Casual",
          metal_drain_check: 0.64,
          energy_drain_check: 0.77,
          metal_demand_check: 0.95,
          energy_demand_check: 0.92,
          micro_type: 0,
          go_for_the_kill: false,
          priority_scout_metal_spots: true,
          enable_commander_danger_responses: false,
          neural_data_mod: 2,
          adv_eco_mod: 0.5,
          adv_eco_mod_alone: 0,
          factory_build_delay_min: 0,
          factory_build_delay_max: 12,
          per_expansion_delay: 60,
          personality_tags: ["queller"],
          min_basic_fabbers: 10,
          min_advanced_fabbers: 3,
        },
        // imagine another 11 objects of the same size here
      };

      var baseline = aiPersonalities.Absurd;

      newPersonalities = _.mapValues(
        newPersonalities,
        function (personality, name) {
          var result = _.assign(_.clone(baseline), personality);
          result.name = name;
          return result;
        }
      );

      _.assign(aiPersonalities, newPersonalities);

      model.aiPersonalities.valueHasMutated();

This could be written in a way which removes aiPersonalities, baseline, and avoids newPersonalities referencing itself:
      var newPersonalities = _.mapValues(
        {
          qCasual: {
            ai_path: "/pa/q_casual",
            display_name: "!LOC:Q-Casual",
            metal_drain_check: 0.64,
            energy_drain_check: 0.77,
            metal_demand_check: 0.95,
            energy_demand_check: 0.92,
            micro_type: 0,
            go_for_the_kill: false,
            priority_scout_metal_spots: true,
            enable_commander_danger_responses: false,
            neural_data_mod: 2,
            adv_eco_mod: 0.5,
            adv_eco_mod_alone: 0,
            factory_build_delay_min: 0,
            factory_build_delay_max: 12,
            per_expansion_delay: 60,
            personality_tags: ["queller"],
            min_basic_fabbers: 10,
            min_advanced_fabbers: 3,
          },
        // imagine another 11 objects of the same size here
        },
        function (personality, name) {
          var result = _.assign(
            _.clone(model.aiPersonalities().Absurd),
            personality
          );
          result.name = name;
          return result;
        }
      );

      _.assign(model.aiPersonalities(), newPersonalities);

      model.aiPersonalities.valueHasMutated();

I'm just interested in how people would approach this. My instinct is that aiPersonalities and baseline could be ditched, per approach 2, but that keeping the initial declaration of the newPersonalities object may make it easier to see what the _.mapValues bit is doing.
There aren't any style guidelines or anything, this is a purely me project.


texts:
I started learning Python recently and I really like it, so I decided to share one of my first projects mainly in hopes of someone telling me what I can do to make it run faster (threading/multiprocessing?).

from requests import get
from bs4 import BeautifulSoup
from time import time
from re import compile

print('***PYTHON LEAGUE OF LEGENDS USERNAME SCRAPER***')
print('This script scrapes usernames from lolprofile.net')
region = input('Enter the region for scraping(eune/euw/na/br/tr/kr/jp/lan/las/oce/ru)\n')
numStart = input('What page to start on? Min 0\n')
numEnd = input('What page to end on? Min starting page + 1\n')

size = [] #for logging
#count = -1 #for logging

def setUrl(pageNum, region):
    global url
    url = 'http://lolprofile.net/leaderboards/'+region+'/'+pageNum

def is_ascii(i):
    return all(ord(c) < 128 for c in i)

setUrl(numStart, region)

start = time()

while int(numStart) != int(numEnd):
    print(len(size))
    page = get(url)
    soup = BeautifulSoup(page.text, "lxml")
    userName = [a.string for a in soup.findAll(href=compile('http://lolprofile.net/summoner/*'))]
    with open('usernames1.txt', 'a') as file:
        for i in userName:
            if is_ascii(i) and (' ' in i) == False:
                file.write('%s\n' % i.lower())
                size.append('0')
    numStart = int(numStart)
    numStart += 1
    setUrl(str(numStart), region)
    #count += 1
    #if count % 250 == 0: #every n iterations print progress
    #    print(len(size))

end = time()

print(len(size),'usernames scraped in a total of',end-start,'seconds')


texts: creating own javascript join and push methods

texts:
I'm a newbie trying to write my own push() and join(). This isn't very serious, just an exercise.
This is what I got so far

function Errey(...values){
    this.name=values
    }
Errey.prototype={
  constructor:Errey,
    //join method
  myJoin(union = ' '){
  let result=""
  const length = this.name.length
  for(let i=0; i<length; i++)
  {
   i<length-1 ? result += this.name[i] + union: result+=this.name[i]
  }
  return result
  },
    //push method
    myPush(value){
    this.name = [...this.name, value]
    return this.name.length
    }
  }

//run a few examples
const myArray = new Errey("3","blue","1","brown")
//we'll mutate myArray anyways using const or let
let joined  = myArray.myJoin()
let a = myArray.myPush("hey")
console.log("joined new array: ",joined, "\n\npush-mutated array: ", myArray.name, "\n\npush return value: ", a)

I'm aware an object is returned instead of an array. I guess you might help me out there. Should I use factory functions here? I don't know how would I create a prototype for such a thing...
Any improvements on the main code you'd suggest?


texts:
Could you please review my code and let me know if there is something wrong? I'm getting the expected results.

I'm trying to do change data capture using hive. We already have an existing CDC in DataStage, but we are trying to implement in HIVE now. Here is what I have done, please correct me if I'm doing something wrong.

Here is the source data:

Table name: month1

e_id, e_name, e_ad
11, john, singapore
22, jack, Melbourne
33, jessy, sydney
44, lampard, canada
55, pomer, perth

Table name2: month2

e_id, e_name, e_add
11, john, odisha
22, jack, Melbourne
44, lampard, canada
55, pomer, perth
66, rahul, mumbai

Here, the key field is the e_id, and value field is e_name and e_add:

select
    case    when cdc_codes ='Updates' Then month2s
        when cdc_codes = 'NoChange' then month1s
        when cdc_codes = 'New' then month2s
        when cdc_codes = 'Deletes' then month1s
        else 'Error' end as fin_cols
from (select
    case    when m1.e_id = m2.e_id and concat(m1.e_name,m1.e_add) = concat(m2.e_name,m2.e_add)     then  'NoChange'
            when m1.e_id = m2.e_id and  concat(m1.e_name,m1.e_add) <> concat(m2.e_name,m2.e_add) then  'Update'
            when m1.e_id is null then 'New'
            when m2.e_id is null then 'Deletes'
            else 'Error' end as cdc_codes,
        concat(m1.e_id,',',m1.e_name,',',m1.e_add) as month1s,
        concat(m2.e_id,',',m2.e_name,',',m2.e_add) as month2s
    from    month1 as m1
    full outer join
    month2 as m2
    on  m1.e_id = m2.e_id) as b1


texts:
In the Java world while writing the data access layer (for CRUD) and the model layer, I have done something like this:

public abstract class AbstractDao<N extends AbstractModel>{
        protected Class<N> persistentClass;
        public N findById(String id){

                return (N)mongoOperation.findById(id, persistentClass,persistentClass.getSimpleName());

        }
}

class FlightDao extends AbstractDao<Flight>
class AirlineDaoImpl extends AbstractMongoDao<Airline>

Where Flight extends AbstractModel and ,Airline extended AbstractModel

Now calling the findById was as trivial as

Flight flight = flightDao.findById("FlightId1");

I feel this was a decent way of doing things because it kept my code DRY. And most of the model objects needed the same CRUD methods.

Now coming to Scala, Play framework 2, anorm, I would like to know what is the right way of doing something such as this.

I read that model classes should be case classes but then that prevents us from inheritance. And moreover the data access definitions were given in the companion objects. This is what I have at the moment.

case class Airline(id:Pk[Long]=NotAssigned,name:String)
case class Flight(id:Pk[Long]=NotAssigned,code:String,airlineId:Long,date:DateTime)

object Flight{
    def getById(id:Long):Option[Flight] = {
    DB.withConnection { implicit connection =>
       SQL(
        """
          select * from flight
          where flight.id =  {id}
        """
      ).on(
        'id -> id
      ).as(Flight.simple.singleOpt)
    }

  }
}

object Airline{
    def getById(id:Long):Option[Airline] = {
    DB.withConnection { implicit connection =>
       SQL(
        """
          select * from airline
          where airline.id =  {id}
        """
      ).on(
        'id -> id
      ).as(Airline.simple.singleOpt)
    }

  }
}

I'm certain there must be a better way to do this.  I would love to know how I could write neat / clean Scala code for this. Any pointers, design patterns and feedback is much appreciated.


texts: Characters set permutations with repetitions

texts:
The code bellow generates all the permutation(with repetitions) for given character set. Is there any better(simpler, more performant) way to do that?

var assert = require('chai').assert
var _ = require('underscore')

var multStr = function(left, rigth) {
  return _.chain(left).map(function(el) {
    return _(rigth).map(function(chr) {
      return el + chr
    })
  })
  .flatten()
  .value()
}

function solution(space, len) {
  return _.chain(
      _(len - 1).range()
    )
    .reduce(
      function(acc, next) {
          acc.push(
            multStr(
              _.last(
                acc
              ),
              space
            )
          )
          return acc
      },
      [space.split('')]
    )
    .flatten()
    .value()
}

assert.deepEqual(multStr(['ab'], 'ab'), ['aba', 'abb'])
assert.deepEqual(solution('abc', 1), ['a', 'b', 'c'])
assert.deepEqual(solution('a', 2), ['a', 'aa'])
assert.deepEqual(solution('ab', 2), ['a', 'b', 'aa', 'ab', 'ba', 'bb'])
assert.deepEqual(solution('abc', 3), [ 'a', 'b', 'c',
  'aa', 'ab', 'ac', 'ba', 'bb', 'bc', 'ca', 'cb', 'cc',
  'aaa', 'aab', 'aac', 'aba', 'abb', 'abc', 'aca', 'acb', 'acc',
  'baa', 'bab', 'bac', 'bba', 'bbb', 'bbc', 'bca', 'bcb', 'bcc',
  'caa', 'cab', 'cac', 'cba', 'cbb', 'cbc', 'cca', 'ccb', 'ccc'
])


texts: Safely aborting thrid-party code using TPL

texts:
I'm using some third-party libraries in my project. Once in a while the code in these libraries freaks out and produces infinite loops and other nasty things. My goal is to write a wrapper that allows me to abort execution of this third-party code after some timeout. Here's my current implementation:

public static class SafeExecutor
{
    public static async Task DoAsync(Action action, TimeSpan timeout)
    {
        if (action == null) throw new ArgumentNullException("action");
        if (timeout <= TimeSpan.Zero) throw new ArgumentOutOfRangeException("timeout");

        var completed = await tryCompleteAsync(action, timeout).ConfigureAwait(false);
        if (!completed)
        {
            throw new TimeoutException();
        }
    }

    public static void Do(Action action, TimeSpan timeout)
    {
        DoAsync(action, timeout).Wait();
    }

    public static async Task<T> ReturnAsync<T>(Func<T> function, TimeSpan timeout)
    {
        if (function == null) throw new ArgumentNullException("function");
        if (timeout <= TimeSpan.Zero) throw new ArgumentOutOfRangeException("timeout");

        var value = default(T);
        var completed = await tryCompleteAsync(() => value = function(), timeout).ConfigureAwait(false);
        if (!completed)
        {
            throw new TimeoutException();
        }

        return value;
    }

    public static T Return<T>(Func<T> function, TimeSpan timeout)
    {
        return ReturnAsync(function, timeout).Result;
    }

    private static async Task<bool> tryCompleteAsync(Action action, TimeSpan timeout)
    {
        using (var tokenSource = new CancellationTokenSource(timeout))
        {
            var task = Task.Factory.StartNew(
                () =>
                {
                    var abortCookie = Guid.NewGuid();
                    try
                    {
                        var currentThread = Thread.CurrentThread;
                        using (tokenSource.Token.Register(() => currentThread.Abort(abortCookie)))
                        {
                            action();
                        }

                        return true;
                    }
                    catch (ThreadAbortException ex)
                    {
                        if (ex.ExceptionState != null && ex.ExceptionState.Equals(abortCookie))
                        {
                            Thread.ResetAbort();
                            return false;
                        }

                        throw;
                    }

                }, tokenSource.Token);

            return await task.ConfigureAwait(false);
        }
    }
}

Any suggestions?


texts: Input string, output vowels and consonants to log, separately but in order

texts:
I completed a short coding challenge and just want to know if I should use shorter methods of which I am unaware, or make it more readable.

 /*
 *
 * Complete the vowelsAndConsonants function.
 * Print your output using 'console.log()'.
 */
function vowelsAndConsonants(s) {
var strConsonants = "";
var strVowels = "";
var i;

for (i in s) {
    if (s.charAt(i) == "a" || s.charAt(i) == "e" || s.charAt(i) == "i" ||
s.charAt(i) == "o" || s.charAt(i) == "u") {
        strVowels += s.charAt(i);
    }
    else if (s.charAt(i) != "a" || s.charAt(i) != "e" || s.charAt(i) != "i"
|| s.charAt(i) != "o" || s.charAt(i) != "u") {
        strConsonants += s.charAt(i);
    }
}

// console.log(strVowels);

i = 0;
for (i in strVowels) {
    console.log(strVowels.charAt(i));
}

// console.log(strConsonants);

i = 0;
for (i in strConsonants) {
     console.log(strConsonants.charAt(i));
}

}


texts: Payment function with too many parameters

texts:
I have a method with too many parameters.

How would you refactor it?

Things I considered so far:

pass an array to the object and check for required keys (no code hint, phpdoc, programmer doesn't know which are required)
pass an object (silly method with getters and setters, programmer still doesn't know which are required)

Here's the method:

public function doDirectPayment(
    $amount,
    $credit_card_type,
    $credit_card_number,
    $expiration_month,
    $expiration_year,
    $cvv2,
    $first_name,
    $last_name,
    $address1,
    $address2,
    $city,
    $state,
    $zip,
    $country,
    $currency_code,
    $ip_address,
    $payment_action = 'Sale'
)
{
    $client = $this->getClient();

    $client->setParameterGet('METHOD', 'DoDirectPayment');

    $month = str_pad(ltrim((string)$expiration_month, 0), 2, '0', STR_PAD_LEFT);
    $expiration_date = $month . $expiration_year;

    $client->setParameterGet('PAYMENTACTION', urlencode($payment_action));
    $client->setParameterGet('AMT', urlencode($amount));
    $client->setParameterGet('CREDITCARDTYPE', urlencode($credit_card_type));
    $client->setParameterGet('ACCT', urlencode($credit_card_number));
    $client->setParameterGet('EXPDATE', urlencode($expiration_date));
    $client->setParameterGet('CVV2', urlencode($cvv2));
    $client->setParameterGet('FIRSTNAME', urlencode($first_name));
    $client->setParameterGet('LASTNAME', urlencode($last_name));
    $client->setParameterGet('STREET', urlencode($address1));

    if (!empty($address2)) {
        $client->setParameterGet('STREET2', urlencode($address2));
    }

    $client->setParameterGet('CITY', urlencode($city));
    $client->setParameterGet('STATE', urlencode($state));
    $client->setParameterGet('ZIP', urlencode($zip));
    $client->setParameterGet('COUNTRYCODE', urlencode($country));
    $client->setParameterGet('CURRENCYCODE', urlencode($currency_code));
    $client->setParameterGet('IPADDRESS', urlencode($ip_address));

    $response = $client->request(Zend_Http_Client::GET);

    return $response;
}


texts:
In a personal project I was working on, I had a vector of std::vector< std::pair<unsigned,char>>'s that represented a character and its position in the alphabet. I found that using/manipulating that vector to be clumsy so I wrote this implementation. Essentially, it just wraps the usual vector operations. I'm hoping for the following things to be considered, as well as the usual areas of review:

Are there any other operations that should be implemented?
I didn't have a C++20 compiler available at the time of writing this, what needs to be done to "modernize" the code?
Are there specific ways to change or improve the code?

And a few notices

I know that begin() and end() should return a std::vector::iterator, but I was having difficulties making that compile so I kept it as auto for the time begin. (Yes,I know that is a dirty hack. It's on my to do list.
There are other operators that need to be overloaded ( = and == especially), but I wanted to improve the existing code before adding more.

The code is licensed under the BSD Clause 3 license, if you wish to use it/change it.

#include <iostream>
#include <vector>

template< typename Left, typename Right>
class Vecpair
{
  public:

    auto begin(void);
    auto end(void);

    void pushBack(Left,Right);
    void pushBack( std::pair<Left,Right> );
    void popBack(void);
    void clear(void);

    std::size_t getSize(void);
    std::pair<Left,Right> atPos(unsigned);
    std::pair<Left,RIght> front(void);
    std::pair<Left,Right> back(void):

    std:::pair<Left,Right> operator [] (unsigned i){ return( internal.at(i) ); }

  private:

    std::size_t numElem = 0;
    std::vector< std::pair<Left,Right>> internal;
};

//  Returns an iterator to the beginning of 'internal'.
template< typename Left, typename Right>
auto Vecpair<Left,Right>::begin(void)
{
  return( internal.begin() );
}

//  Returns an iterator to the end of 'internal'.
template< typename Left, typename Right>
auto Vecpair<Left,Right>::end(void)
{
  return( internal.end() );
}

// Takes two separate values and pushes them to the back of 'internal' as a pair.
template< typename Left, typename Right>
void Vecpair<Left,Right>::pushBack(Left l, Right r)
{
  internal.push_back( {l,r} );
  numElem++;
}

//  Takes a pair and pushes to the back of 'internal'.
template< typename Left, typename Right>
void Vecpair<Left,Right>::pushBack( std::pair<Left,Right> p )
{
  internal.push_back( p );
  numElem++;
}

//  Pops the last element.
template< typename Left, typename Right>
void Vecpair<Left,Right>::popBack(void);
{
  internal.pop_back();
  numElem--;
}

//  Clears 'internal'.
template< typename Left, typename Right>
void Vecpair<Left,Right>::clear(void)
{
  internal.clear();
  numElem = 0;
}

// Returns the number of elements;
template< typename Left, typename Right>
std::size_t Vecpair<Left,Right>::getSize(void)
{
  return( numElem );
}

//  Returns the pair at the given position.
template< typename Left, typename Right>
std::pair<Left, Right> Vecpair<Left,Right>::atPos(unsigned idx)
{
  return( internal.at(idx) );
}

//  Returns the first pair.
template< typename Left, typename Right>
std::pair<Left,Right> Vecpair<Left,Right>::front(void)
{
  return( internal.front() );
}

//  Returns the last pair.
template<typename Left, Typename Right>
std::pair<Left,Right> Vecpair<Left,Right>::back(void)
{
  return( internal.back() );
}


texts:
After a bit of work, I've changed my code a lot from the previous question:

I was recommended by George Mauer and schism to make a better structural design, so hopefully this new build is a bit sleeker in design. I will note that my main target is optimal performance. But like Mr. Mauer said, it is most likely negligible in this particular case.

What I've attempted since is removing duplicate code at the same time optimizing performance and fixing design. Here is what I came up with:

var MediaMaster = new (function(){
  var sounds = {};// a container of Audio instances and names(keys) as a reference to their respective values.

  // Master Controll of sounds
  var liveSounds = [],
      instanceVolume = {},
      globalVolume = 1;

  var SB = {muted: false, previousVolume:1};
  this.soundBatch = this.sBatch = SB;
  SB.toggleMute = function(){
    if( SB.muted === false ){
      // mute everything
      liveSounds.forEach(function(snd){
        snd.previousVolume = snd.volume;
        snd.volume = 0;
      });
      SB.previousVolume = globalVolume;
      globalVolume = 0;
      return (SB.muted = true);
    }
    //unmute everything
    liveSounds.forEach(function(snd){
      snd.volume = snd.previousVolume;
      delete snd.previousVolume;
    });
    globalVolume = SB.previousVolume;
    return (SB.muted = false);
  };

  // Hide specific soundBatch functionality
  (function(SB){
    function killSound(snd){
      snd.pause();
      snd.onended();
      snd.currentTime = 0;
    }
    function globalVolumeChange(v){ globalVolume = Math.pow(v,2);}
    function globalStop(){liveSounds.forEach(function(snd){killSound(snd)});}
    function globalPause(){ liveSounds.forEach(function(snd){snd.pause();}); }
    function globalGetLive(){return liveSounds.slice();}
    //Applies a callback to anything that passes the filter
    function instanceApply(name, callback){
      var match = sounds[name].src;
      liveSounds.forEach(function(snd){
        if( snd.src !== match ) return;
        callback(snd);
      });
    }

    SB.volume = function(name, v){
      if(!name)return globalVolumeChange(v);
      instanceVolume[name] = Math.pow(v,2);
    };
    SB.stop = SB.kill = function( name ){
      if(!name)return globalStop();
      instanceApply(name, killSound);
    };
    SB.pause = function( name ){
      if(!name)return globalPause();
      instanceApply(name, function(snd){ snd.pause(); });
    }
    SB.getLive = function( name ){
      if(!name)return globalGetLive();
      return liveSounds.filter(function(snd){ return( snd.src === match );});
    }
  })(this.soundBatch);

  var prototypePlay = Audio.prototype.play;//keep a reference

  // Getting  sounds
  this.sound = function(name){
    var snd = new Audio( sounds[name].src );

    snd.volume = instanceVolume[name];
    snd.play = function(){
      var that = this;// used for removing "liveSounds" this conflict.
      that.volume *= globalVolume;
      prototypePlay.apply(that);
      liveSounds.push(that);
      this.onended = function(){ liveSounds.splice( liveSounds.indexOf(that), 1 );};
    };
    return snd;
  };
})();

If you're looking for an ever bigger picture of what this belongs too, it is a part of my Game Framework I started July 4th. Look for "mediaManager.js"


texts:
So I was playing with writing FizzBuzz in Elixir; this is my first, naive implementation:

defmodule FizzBuzz do
  def getFB(n) do
    cond do
      rem(n,15) == 0 ->
        IO.puts "FizzBuzz"
      rem(n,3) == 0 ->
        IO.puts "Fizz"
      rem(n,5) == 0 ->
        IO.puts "Buzz"
      true ->
        IO.puts "#{n}"
    end
  end
end

So then I thought to myself--this is Elixir! I should be able to spawn a secondary process for my FizzBuzz needs.  So after a bit of hacking I got this:

defmodule FizzBuzz do
  @fizz_buzz 15
  @fizz 3
  @buzz 5
  @default_timeout 60_000

  def getFB() do
    receive do
      {pid,n} when rem(n,@fizz_buzz) == 0 ->
        send pid,"FizzBuzz"
      {pid,n} when rem(n,@fizz) == 0 ->
        send pid,"Fizz"
      {pid,n} when rem(n,@buzz) == 0 ->
        send pid,"Buzz"
      {pid,n} ->
        send pid,"#{n}"
    after
      @default_timeout -> raise "Timed out"
    end
    getFB() #Keep the process alive
  end
end

and I would use it like so:

fbPid = spawn &FizzBuzz.getFB/0

send fbPid,{self(),15}
receive do
   r -> IO.puts(r)
after
  1000 -> raise "Timed out"
end

I realize this is a small/simple example but I'd still love to hear the thoughts of other experienced Elixir devs.  Where can I make this better?


texts: Decorator for setting up bracketing rootfinding functions

texts:
I'm looking for comments on the use of decorators for the following problem (validating initial guesses for bracketing rootfinding methods), as well as any other comments you might have on the design below.

def bracketing(rootfinder):
    def wrapper(func, x0, x1, *args, **kwargs):
        func_x0, func_x1 = func(x0), func(x1)

        if func_x0 * func_x1 > 0.0:
            return None

        return rootfinder(func, x0, x1, *args, **kwargs)

    return wrapper

@bracketing
def bisection(func, x0, x1, max_iterations, tolerance):
    if x1 < x0:
        x0, x1 = x1, x0

    func_x0 = func(x0)

    for _ in range(max_iterations):
        x_mid = 0.5 * (x0 + x1)
        func_x_mid = func(x_mid)

        if func_x0 * func_x_mid > 0.0:
            x0 = x_mid
            func_x0 = func_x_mid
        else:
            x1 = x_mid

        if x1 - x0 < tolerance:
            return x_mid

    return None

@bracketing
def false_position(func, x0, x1, max_iterations, tolerance):
    func_x0, func_x1 = func(x0), func(x1)

    for _ in range(max_iterations):
        x2 = (x0 * func_x1 - x1 * func_x0) / (func_x1 - func_x0)
        func_x2 = func(x2)

        if func_x0 * func_x2 > 0.0:
            x0, func_x0 = x2, func_x2
        else:
            x1, func_x1 = x2, func_x2

        if abs(func_x2) < tolerance:
            return x2

    return None


texts: Creating a global font handler for a Qt widget application

texts:
A widget-based Qt application has to run on a wide variety of platforms, some of which don't include fonts at all. Therefore I created a global font loader utility class, with the justification that the fonts are used in a large number of classes, and it would look bloated to pass around the fonts everywhere using dependency injection in each GUI class which has to display some text (there are many).

header:

class Fonts
{
    private:
        Fonts() {}
        static QFont m_myFont;
        static QFont m_someOtherFont;
        // and so on for other fonts...

    public:
        static QFont &myFont() {return m_myFont;}
        static QFont &someOtherFont() {return m_someOtherFont;}
        static bool initialize();
};

c++:

bool Fonts::initialize()
{
    int id = QFontDatabase::addApplicationFont(":/fonts/myFont.ttf");
    if (id < 0)
        return false;

    QString family = QFontDatabase::applicationFontFamilies(id).at(0);
    m_myFont = QFont(family);

    // and so on for all the other fonts
    // ...

    return true;
}

QFont Fonts::m_myFont;
QFont Fonts::m_someOtherFont;

At the very beginning of my application, I just call

Fonts::initialize();

And whenever I have to use a font, I can just use

label->setFont(Fonts::myFont());

However, if I need other properties, I have to declare a local QFont.

QFont font = Fonts::myFont();
font.setPointSize(20);
label->setFont(font);

This works just fine, however, I'm thinking whether this is really the most elegant approach.


texts: Implement a function that prints all possible combinations of the characters in a string

texts:
I came across this interview question and it has been asked to print combinations of the characters in a string. For example: "abc" --> a, b, c, ab, ac, bc, abc. Also it has been mentioned that 'ab' and 'ba' are same.

I want to know if there is any improvement I can make in terms of memory usage/performance.

public string[] Combination(string str)
{
    if (string.IsNullOrEmpty(str))
        throw new ArgumentException("Invalid input");

    if (str.Length == 1)
        return new string[] { str };

    // read the last character
    char c = str[str.Length - 1];

    // apart from the last character send remaining string for further processing
    string[] returnArray = Combination(str.Substring(0, str.Length - 1));

    // List to keep final string combinations
    List<string> finalArray = new List<string>();

    // add whatever is coming from the previous routine
    foreach (string s in returnArray)
        finalArray.Add(s);

    // take the last character
    finalArray.Add(c.ToString());

    // take the combination between the last char and the returning strings from the previous routine
    foreach (string s in returnArray)
        finalArray.Add(s + c);

    return finalArray.ToArray();
}


texts:
This is a sample exercise tutorial that would be used to test understanding of how simple classes communicate/message and are designed.

Tester class

public class GuessingGameTester {

    public static void main(String[] args){
        //create a new game
        GuessingGame g1 = new GuessingGame();

        //call the start method
        g1.startGame();

    }
}

Player class

public class GuessingGamePlayer {

    boolean areTheyRight = false;

    //player random guess
    int getPlayerGuess(){
        return (int) (Math.random()* 20);
    }
}

Game class

public class GuessingGame {

    private int numberToGuess;
    private boolean keepPlaying;
    private int round;

    //constructor
    GuessingGame(){
        //create a random number for players to guess
        numberToGuess = (int) (Math.random() * 20);//cast to int
        keepPlaying = true;
        round = 1;
    }

    void startGame(){

        //create 3 players to play
        GuessingGamePlayer p1 = new GuessingGamePlayer();
        GuessingGamePlayer p2 = new GuessingGamePlayer();
        GuessingGamePlayer p3 = new GuessingGamePlayer();

        System.out.println("The number to guess is : " + numberToGuess);

        //giving 100 attemps for the computer to guess the correct number
        while(keepPlaying && round <= 100){

            //get their guess
            int p1guess = p1.getPlayerGuess();
            int p2guess = p2.getPlayerGuess();
            int p3guess = p3.getPlayerGuess();

            System.out.println("round " + round);
            System.out.println("p1 guessed: " + p1guess);
            System.out.println("p2 guessed: " + p2guess);
            System.out.println("p3 guessed: " + p3guess);

            System.out.println("\n");

            if(p1guess == numberToGuess){
                p1.areTheyRight = true;
                keepPlaying = false;
            }else if(p2guess == numberToGuess){
                p2.areTheyRight = true;
                keepPlaying = false;
            }else if(p3guess == numberToGuess){
                p3.areTheyRight = true;
                keepPlaying = false;
            }

            round ++;
        }//end while

        //game over - echo who guessed the correct num and the round
        System.out.println("\n");
        if(p1.areTheyRight){
           System.out.println("p1 guessed the correct number during round " + round);
        }else if(p2.areTheyRight){
            System.out.println("p2 guessed the correct number during round " + round);
        }else{
            System.out.println("p3 guessed the correct number during round " + round);
        }

    }//end startGame
}


texts: Validating the model outside of the controller in ASP.NET

texts:
I wasn't quite sure whether I should do it this way or create a validation service and inject it, but this works:
Controller:
[HttpPost]
public async Task<IActionResult> NewUser(NewUsertVm viewModel)
{
    if (UserValidator.NewUserIsValid(viewModel, ModelState) == false)
    {
        return View(nameof(NewUser), viewModel);
    }

// Code omitted for brevity
}

UserValidatorClass
public static bool NewUserIsValid(NewUserVm viewModel, ModelStateDictionary modelState)
{
    if (string.IsNullOrEmpty(viewModel.RefOne) && string.IsNullOrEmpty(viewModel.RefTwo) && string.IsNullOrEmpty(viewModel.RefThree))
    {
        var validationMessage =
            "At least one of either the first, second or third ref numbers must be entered to add a new user. Please enter one of these numbers and try again.";
        modelState.AddModelError(nameof(viewModel.RefOne), validationMessage);
    }

    var regEx = new Regex("(^\\d{10}$)");

    if (viewModel.RefOne != null)
    {
        if (!regEx.IsMatch(viewModel.RefOne))
        {
            var validationMessage =
                "Ref One must be 10 digits and contain only numbers.";
                modelState.AddModelError(nameof(viewModel.RefOne), validationMessage);
        }
    }

    return modelState.IsValid;
}

The idea behind the validator is that it needs to ensure at least one of the three properties are not null (RefOne, RefTwo & Ref Three. Property names have been changed for post). If RefOne is used, it needs to match the RegEx pattern.
This appears to work as intended but is there a better way of achieving the same result?


texts:
I have tried the following code:

SystemUser user = (SystemUser)Session["CurrentUser"];
Data.Configuration configuration = db.Configurations.Single(c => c.ID == user.ID);
MailAddress from = new MailAddress("noreply@test.com", "Test");
if (configuration.EmailFromAddress != null)
{
    from = new MailAddress(configuration.EmailFromAddress, "Test");
}

Here I declare the from variable of the MailAddress class with a default value, and if configuration.EmailFromAddress exists, I am assigning that value to the from.

Is this following best practice?

Here, the MailAddress class is calling twice to assign the value.  Is it good performance and memory wise? Another implementation is using a string variable:

SystemUser user = (SystemUser)Session["CurrentUser"];
Data.Configuration configuration = db.Configurations.Single(c => c.ID == user.ID);
string fromAddress = "noreply@test.com";
if (configuration.EmailFromAddress != null)
{
    fromAddress = configuration.EmailFromAddress;
}
MailAddress from = new MailAddress(fromAddress, "Test");

Which one follows best practice?


texts:
I know that there are several ways to handle exceptions and probably a good way is to keep the handling consistently and use the pattern which feels comfortable for himself, but I would like to get some advice or hints, what would you do in following situation or how I could improve such a case.

I created a custom URLClassLoader which checks the certification and some advanced stuff. With following function I load the X509 certificate into the instance:

public boolean loadX509Certificate(File file) {
    try {
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        InputStream is = new FileInputStream(file);
        this.setCertificate(cf.generateCertificate(is));
        is.close();
    } catch (CertificateException e) {
        return false;
    } catch (FileNotFoundException e) {
        return false;
    } catch (SecurityException e) {
        return false;
    } catch (IOException e) {
        return false;
    }
    return true;
}

In that function I catch four exceptions, what would you do in this situation? Return false if the certificate cannot load, rethrow the exception or create a custom exception which tells the user what went wrong?

In generally the Class will work without the certification, but if the value doesn't exist, the class will not check the classes and resources signature.


texts:
This is the second project for my CS1 class, this time I'm actually getting it reviewed before I submit it ;)

  The Harris-Benedict equation estimates the number of calories your
  body needs to maintain your weight if you do no exercise.  This is
  called your basal metabolic rate, or BMR.

  The formula for the calories needed for a woman to maintain her weight
  is

  $$ \text{BMR} = 655 + \left( 4.3 \cdot \text{weight in pounds} \right) + \left( 4.7 \cdot \text{height in inches} \right) - \left( 4.7 \cdot \text{age in years}\right)$$

  The formula for the calories needed for a man to maintain his weight
  is

  $$ \text{BMR} = 66 + \left( 6.3 \cdot \text{weight in pounds} \right)
 + \left( 12.9 \cdot \text{height in inches} \right) - \left( 6.8 \cdot \text{age in years}\right)$$

  A typical chocolate bar will contain around 230 calories.  Write a
  program that allows the user to input his or her weight in pounds,
  height in inches, age in years, and the character 'M' for male and 'F'
  for female.  The program should then output the number of chocolate
  bars that should be consumed to maintain one's weight for the
  appropriate sex of the specified weight, height, and age.

calorie.cpp:

/**
 * @file calorie.cpp
 * @brief Determines the number of chocolate bars you need to eat in order to live
 * @author syb0rg
 * @date 9/12/14
 */

#include <iostream>
#include <cctype>
#include <limits>

int main()
{
    double weight = 0;
    double height = 0;
    double age = 0;
    double bmr = 0;
    char gender = 'm';

    // get input for weight, re-read input if not a number
    std::cout << "Enter the weight in pounds: ";
    while(!(std::cin >> weight))
    {
        std::cin.clear();
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        std::cout << "Invalid input.  Please enter a number: ";
    }
    // get input for height, re-read input if not a number
    std::cout << "Enter the height in inches: ";
    while(!(std::cin >> height))
    {
        std::cin.clear();
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        std::cout << "Invalid input.  Please enter a number: ";
    }
    // get input for age, re-read input if not a number
    std::cout << "Enter your age: ";
    while(!(std::cin >> age))
    {
        std::cin.clear();
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        std::cout << "Invalid input.  Please enter a number: ";
    }
    // get input for weight
    std::cout << "Enter your gender (M/f): ";
    std::cin >> gender;

    if ('m' == gender)
    {
        bmr = 66 + (6.3 * weight) + (12.9 * height) - (6.8 * age);
    }
    else if ('f' == gender)
    {
        bmr = 655 + (4.3 * weight) + (4.7 * height) - (4.7 * age);
    }
    else std::cout << "You aren't human." << std::endl;

    const double numBars = bmr / 230; // divide by the number of calories in a chocolate bar
    std::cout << "The person with the entered metrics is allowed to consume " << numBars << " bars of chocolate." << std::endl;
}


texts: Better pythonic way to pass condition to multiple functions

texts:
I have the following scenario where most of my functions require to return different things based on a condition.

def get_root_path(is_cond_met=False):
    if is_cond_met:
        return "something"
    else
        return "something else"

def get_filename(is_cond_met=False):
    if is_cond_met:
        return "file name A"
    else
        return "file name B"

is_cond_met is going to be common for all the functions I am calling. I have just put two here however I have more than 15.

The above code works, however, doesn't seem optimal, or pythonic. Is there a better solution for this?


texts:
At the time I try to write some code to handle an IRController, I got this following classes:

public class UsbDataInputListener implements UsbPipeListener {

    @Override
    public void errorEventOccurred(UsbPipeErrorEvent upee) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void dataEventOccurred(UsbPipeDataEvent upde) {
        final byte[] recData = upde.getData(); //Übertragene Bytes
        //Input wird überprüft
        //Aktion für die jeweilige Taste wird durchgeführt
        if(Arrays.equals(recData, Keys.POWER)){
            Key_Action.callShutdown();
        }
        ....
        ....
}

This class waits for a DataEvent (pressing a button on the controller):

public final class Keys {

    public static final byte[] POWER = {4,1};
    //Direkt Zugriff aus Musi,Spiele,Gallerie und Videos
    public static final byte[] MUSIC = {2,5,0,4,0,0,0,0,2,5,0,30,0,0,0,0};
    public static final byte[] GAME = {2,5,0,5,0,0,0,0,2,5,0,31,0,0,0,0};
    public static final byte[] GALLERY = {2,5,0,6,0,0,0,0,2,5,0,32,0,0,0,0};
    public static final byte[] VIDEO = {2,5,0,7,0,0,0,0,2,5,0,33,0,0,0,0};
    //Steurung für Film und Musik
    public static final byte[] BEFORE = {3,-74,0};
    public static final byte[] BEFORE2 = {2,0,0,0,0,0,0,0,3,-74,0};
    public static final byte[] NEXT = {3,-75,0};
    public static final byte[] NEXT2 = {2,0,0,0,0,0,0,0,03,-75,0};
    public static final byte[] BACKWARD = {3,-53,0};
    public static final byte[] BACKWARD2 = {2,0,0,0,0,0,0,0,03,-53,0};
    public static final byte[] FORWARD = {3,-54,0};
    public static final byte[] FORWARD2 = {2,0,0,0,0,0,0,0,03,-54,0};
    public static final byte[] PLAY = {3,-51,};
    public static final byte[] PLAY2 = {2,0,0,0,0,0,0,0,03,-51,0};
    public static final byte[] STOP = {3,-73,0};
    public static final byte[] STOP2 = {2,0,0,0,0,0,0,0,03,-73,0};
    //Nummernfeld und Navigation durch das Menü
    public static final byte[] NUMBER_ONE = {2,0,0,43,0,0,0,0,2,0,0,0,0,0,0,0};
    public static final byte[] UP = {2,0,0,82,0,0,0,0,2,0,0,0,0,0,0,0};
    public static final byte[] NUMBER_THREE = {2,-128,0,0,0,0,0,0,2,0,0,0,0,0,0,0};
    public static final byte[] LEFT = {2,0,0,80,0,0,0,0,2,0,0,0,0,0,0,0};
    public static final byte[] ENTER = {2,0,0,40,0,0,0,0,2,0,0,0,0,0,0,0};
    public static final byte[] RIGHT = {2,0,0,79,0,0,0,0,2,0,0,0,0,0,0,0};
    public static final byte[] NUMBER_SEVEN= {2,1,0,18,0,0,0,0,2,0,0,0,0,0,0,0};
    public static final byte[] DOWN = {2,0,0,81,0,0,0,0,2,0,0,0,0,0,0,0};
    public static final byte[] ESCAPE = {2,0,0,41,0,0,0,0,2,0,0,0,0,0,0,0};
    public static final byte[] ZERO = {2,0,0,0,0,0,0,0,2,4,0,43,0,0,0,0};
    //Lautstärkeregelung
    public static final byte[] VOL_UP = {3,-23,0};
    public static final byte[] VOL_DOWN = {3,-22,0};
    public static final byte[] MUTE = {3,-30,0};
}

This class represents the bytcode for every key

public class Key_Action {

    private static final Runnable SHUTDOWN = new Runnable(){
        @Override
        public void run() {
            try {
                ShutdownInfoController isc = new ShutdownInfoController();
                Window shtdnWin = new Window("/app/view/ShutdownInfoView.fxml","Info zum Herunterfahren",
                              isc,false);
            } catch (IOException ex) {
                Logger.getLogger(Keys.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    };

    //Ruft das neue Fenster auf
    public static void callShutdown(){
        Platform.runLater(SHUTDOWN);
    }

    //PC wird heruntergefahren
    public static void actShutdown() throws IOException{
        String cmdtext = "shutdown.exe /s /hybrid /t 0 "; // Befehl um PC herunterzufahren
        Runtime.getRuntime().exec(cmdtext); // Befehl wird ausgeführt;
    }
}

This class performs some action when a button is pressed.

My question is: Is this code design ok? Or is it a bad style?


texts: Return path to a value in a nested object

texts:
Description:

Its not a programming challenge but I though to write a small utility which will return the path to a primitive value in a possibly nested object. The idea is not original.

Code:

console.clear();

function each(obj, cb, path) {
  path = path || [];
  for (let k in obj) {
    let val = obj[k];
    if (isLeaf(val)) {
      if (cb(val, path.concat(k)) === false) return false;
    }
    else {
      if (each(val, cb, path.concat(k)) === false) return false;
    }
  }
  return true;
}

let deep = {foo: {bar: true}, baz: 2, blurg: {fop: {hif: []}}};

// If the value is one of the primitive type?
function isLeaf(val) {
  return val !== Object(val) || Array.isArray(val);
}

each(deep, (val, path) => {
  console.log(val);
  console.log(path);
  //return false;
});

/*
          { }
    (foo) / \  (baz)
{bar: true} {2}
  (bar) /
  {true}
*/

Note:

Initially I had no return statement and it worked fine but I thought to give client code to give opportunity to stop the iteration once it finds the desired path/value so after fiddling a bit I had to add couple to return statement and it worked. So, I gained an useful insight on how to
unroll the recursive call from any level.

Questions:

As always I had trouble designing the recursive solution and it was done after some hit and try. I need to know if there is some mental model to keep in mind while doing these kinds of problems?

Having said that I would like to know if the solution is readable, clear and concise?

What modifications I need to make if need to make it part of open source library?


texts: Measure a given method's execution time - follow-up

texts:
A long time ago, I've written a method that would allow me to measure the amount of time a method takes to run. I've decided to tweak this method and make use of TPL since measuring a method may take some time.

public static class ComparableUtils
{
    public static T Min<T>(this T t1, T t2)where T:IComparable
    {
        if (t1.CompareTo(t2) <= 0)
        {
            return t1;
        }
        return t2;
    }

    public static T Max<T>(this T t1, T t2) where T : IComparable
    {
        if (t1.CompareTo(t2) >= 0)
        {
            return t1;
        }
        return t2;
    }
}
public static class TestUtils
{
    private static readonly Stopwatch Watch = new Stopwatch();

    //This determines a minimum amount of iterations needed to perform to get a significative time measurment
    private static Task<int> GetIterations(Action action)
    {
        return Task.Run(() =>
        {
            const int minimumTime = 20;
            int iterations = 0;
            Watch.Start();
            while (Watch.Elapsed.Milliseconds < minimumTime)
            {
                action();
                ++iterations;
            }
            return iterations;
        });
    }

    private static TimeSpan MeasureTime(Action action, int iterations)
    {
        Watch.Restart();
        while (iterations-- > 0)
        {
            action();
        }
        Watch.Stop();
        return Watch.Elapsed;
    }

    public static Task<Time> Measure(Action action, int? iterations = null, int times = 1)
    {
        return Task.FromResult(iterations)
            .ContinueWith(async t => t.Result.GetValueOrDefault(await GetIterations(action)))
            .Unwrap()
            .ContinueWith(t =>
            {
                var iters = t.Result;
                TimeSpan timeTaken = TimeSpan.MaxValue;
                for (int i = 0; i < times; ++i)
                {
                    timeTaken = MeasureTime(action, iters).Min(timeTaken);
                }
                return new Time(timeTaken.Ticks*100/iters);
            });
    }
}

public class Time
{
    private readonly long _nanoSeconds;
    public Time(long nanoSeconds)
    {
        _nanoSeconds = nanoSeconds;
    }

    public override string ToString()
    {
        if (_nanoSeconds < 9999)
        {
            return _nanoSeconds.ToString()+"ns";
        }
        return new TimeSpan(_nanoSeconds / 100).ToString("g");
    }
}

Is this a well conducted measurement algorithm? Is there something that is amiss?


texts: Find a list of objects in an array with JavaScript

texts:
Having an array of objects, such as numbers, what would be the most optimal (Memory and CPU efficiency) way if finding a sub group of objects?

As an example:

demoArray = [1,2,3,4,5,6,7]

Finding [3,4,5] would return 2, while looking for 60 would return -1. The function must allow for wrapping, so finding [6,7,1,2] would return 5

I have a current working solution, but I'd like to know if it could be optimized in any way.

var arr = [
  1,
  5,2,6,8,2,
  3,4,3,10,9,
  1,5,7,10,3,
  5,6,2,3,8,
  9,1]
var idx = -1
var group = []
var groupSize = 0

function findIndexOfGroup(g){
  group = g
  groupSize = g.length
  var beginIndex = -2

  while(beginIndex === -2){
    beginIndex = get()
  }

  return beginIndex
}

function get(){
    idx = arr.indexOf(group[0], idx+1);

    if(idx === -1 || groupSize === 1){
      return idx;
    }
    var prevIdx = idx

    for(var i = 1; i < groupSize; i++){
      idx++

      if(arr[getIdx(idx)] !== group[i]){
        idx = prevIdx
        break
      }

      if(i === groupSize - 1){
        return idx - groupSize + 1
      }
    }
    return -2
}

function getIdx(idx){
  if(idx >= arr.length){
    return idx - arr.length
  }
  return idx
}

console.log(findIndexOfGroup([4,3,10])) // Normal
console.log(findIndexOfGroup([9,1,1,5])) // Wrapping


texts:
I have 3 tables, 1 where voters information is stored, 2 where their address is stored and 3 where voter ids are matched with address ids. I thought this approach was best as several voters can occupy the same address.

Now I have Query that selects all the voters on a given street / road. Although it works, I'm not sure if I should be using joins or keep using where, and if locate is the best way to search a field.

SELECT `voter_name`, `address_full`
FROM `tr_voter`, `tr_voter_address`, `tr_voter_address_assigned`
WHERE tr_voter_address_assigned.voter_id = tr_voter.voter_id
AND tr_voter_address_assigned.address_id = tr_voter_address.address_id
AND LOCATE('insert street name here', `address_full`)
ORDER BY `address_2`, `address_1`
LIMIT 0 , 200

address_full is the full address, where each component is broken down into address_1, address_2 etc. This does mean however, in some cases with house names, that a street may be stored in 1 2 or 3, so searching the full field seemed the full proof way to do it.

Voter Table

`voter_id` int(11) NOT NULL AUTO_INCREMENT,
`voter_name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`voter_number` varchar(11) COLLATE utf8_unicode_ci NOT NULL,
 `voter_title` varchar(20) COLLATE utf8_unicode_ci NOT NULL,
`voter_first_name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`voter_last_name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`voter_notes` text COLLATE utf8_unicode_ci NOT NULL,
`voter_last_vote_date` datetime DEFAULT NULL,
`voter_entry_date` datetime NOT NULL,
`voter_last_update` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00' ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`voter_id`),
UNIQUE KEY `number` (`voter_number`)

Address Table

`address_id` int(11) NOT NULL AUTO_INCREMENT,
`address_full` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`address_1` varchar(255) COLLATE utf8_unicode_ci NOT NULL COMMENT 'address name or number',
`address_2` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`address_3` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`address_4` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`address_5` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`address_6` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`address_lat` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`address_long` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`address_id`),
UNIQUE KEY `address_full` (`address_full`)

Assigned Table

`assigned_id` int(11) NOT NULL AUTO_INCREMENT,
`voter_id` int(11) NOT NULL,
`address_id` int(11) NOT NULL,
PRIMARY KEY (`assigned_id`)


texts:
For this flowchart on finding the minimum of 2 numbers:

I've created XML for this flowchart:

<start>
    <InOut>
      <in>  a </in>
      <in>  b </in>
      <out> min </out>
    </InOut>
    <calc>
         a=3
         b=5
         min=a
    </calc>
    <con gurd="min>b"  type="if">
        <calc>
            min=b
        </calc>
    </con>
    <con gurd="min>b" type="else">
        <calc>
            min=a
        </calc>
    </con>
</start>

But I don't think it's not good XML coding.  What are your suggests for improving this?


texts:
I wrote a simple concept of an event system in cpp.
It is uses a namespace and a global state, but normally a global state with namespaces is bad practice.

Is there a better way to do simple event handling with multiple callback functions?

header:

#ifndef EVENTS_EVENTMANAGER_H
#define EVENTS_EVENTMANAGER_H
#include <glad/glad.h>
#include <GLFW/glfw3.h>
#include <vector>
#include <functional>

namespace eventmanager
{

    //resize event
    static std::vector<std::function<void(GLFWwindow*, int, int)>> resizeEventCallbacks;
    void resizeEvent(GLFWwindow *window, int width, int hight);
    void subscribeResize(std::function<void(GLFWwindow*, int, int)> callback);
}

#endif //EVENTS_EVENTMANAGER_H

cpp:

#include "events/eventmanager.h"

void eventmanager::resizeEvent(GLFWwindow *window, int width, int hight)
{
    for (auto &callback: eventmanager::resizeEventCallbacks)
    {
        callback(window, width, hight);
    }
}

void eventmanager::subscribeResize(std::function<void(GLFWwindow *, int, int)> callback)
{
    eventmanager::resizeEventCallbacks.push_back(callback);
}

usage:

eventmanager::subscribeResize([&](GLFWwindow *window, int width, int hight) {
            ...

            });


texts: Validating that all open/close parentheses are correctly matched

texts:
It returns true for:

a*(b+c)
()()
(())
((!!(123(x))))

and returns false for:

(a((b+c))
)()(
))((
(rsd+3)*(-3-a))

As you can see, the logic is simple. Can you confirm for me that it works for all-cases? I mean the logic isn't flawed.

It must be efficient and by that I mean not go over the linked list more than once.

public boolean parentheses()
{
    return parentheses(0,_head);
}

public boolean parentheses(int p, CharNode current)
{
    if (current == null)
    {
        if (p == 0)
         return true;
        else
         return false;
    }
    else
    {
        if(current.getData() == ')' && p == 0)
         return false;
        else if (current.getData() == '(')
         return parentheses(p+1,current.getNext());
        else if (current.getData() == ')')
         return parentheses(p-1,current.getNext());
        else
         return parentheses(p,current.getNext());
    }
}


texts: Anchoring an element to the browser's vertical scrollbar

texts:
The problem

I'm trying to position a chosen element so that it's always horizontally aligned against the right-hand side of the page, and vertically aligned with the center of the web browser's vertical inner scrollbar, i.e. the part of the scrollbar that moves as you scroll up and down the page. The "handlebar", if you will.
I've been tweaking this code for so long that it's starting to do my head in, so would like a sanity check, i.e. am I going about this the right way?
The key part of this function is the line beginning offset = scroll_position ...
The code
barFollower = function (e) {
  var target = $(e.data.target),
    scrollbar_button_height = 20,
    window_height = $(window).height(),
    window_height_adj = window_height - (scrollbar_button_height * 2),
    scroll_position = $(window).scrollTop(),
    body_height = $('body').height(),

  offset = scroll_position // The top of window
    + ((scroll_position / body_height) * window_height_adj) // The position of the top of scrollbar
    + (((window_height_adj / body_height) * window_height_adj) / 2) // Half the height of the scrollbar
    + scrollbar_button_height // The scrollbar button height (depends on browser chrome, unfortunately) - see notes below
    - element_offset; // offset for chosen 'position' based on element height - see notes below

  /* Some catches for when element height might mean it would get positioned outside the window */
  if (body_height < window_height) { // If there's no scrollbar.
    offset = (window_height / 2) + (target.height() / 2); // Position halfway down the window
  } else if (offset < scroll_position) { // Top bounds
    offset = scroll_position; // Fix it to the top of the window
  } else if (offset > scroll_position + window_height - target.height()) { // Bottom bounds
    offset = scroll_position + window_height - target.height(); // Fix it to the bottom of the window
  }
  target.css('top', offset);
};

Notes
Triggering
This function is triggered once on page load, and subsequently on every window scroll event.
Scrollbar button size
The tricky part here is that I can't find a way to determine the height of the scrollbar 'up' and 'down' buttons, so I have made an assumption (20px), although this will potentially vary from browser to browser, and depends the browser chrome.
If anyone knows a way to accurately determine scrollbar button sizes, please let me know.
The element_offset variable
The element_offset is set outside this function, and can have one of three values to offset the element so that either the top, middle, or bottom of the element align with the middle of the vertical scrollbar. How it is set is not relevant at this point, so I've left it out to keep things simple.


texts: How to make this csv-reading PHP code more efficient?

texts:
I have the following code that reads a .csv file that than outputs the result in the form of a HTML table:

$fhdrop = fopen("ac.csv", "r");

while (!feof($fhdrop) ) {

$at[] = fgetcsv($fhdrop, 1024);

}

$fhdrop2 = fopen("rc.csv", "r");

while (!feof($fhdrop2) ) {

$at2[] = fgetcsv($fhdrop2, 1024);
}
?>

a
b
c
d

<?php echo $at[0][0] ?>
<?php echo $at[0][1] ?>
<?php echo number_format($at[0][1]*$at2[0][1],2) ?>
<?php echo number_format($at[0][1]*$at2[1][1],2) ?>

<?php echo $at[1][0] ?>
<?php echo $at[1][1] ?>
<?php echo number_format($at[1][1]*$at2[0][1],2) ?>
<?php echo number_format($at[1][1]*$at2[1][1],2) ?>

<?php echo $at[2][0] ?>
<?php echo $at[2][1] ?>
<?php echo number_format($at[2][1]*$at2[0][1],2) ?>
<?php echo number_format($at[2][1]*$at2[1][1],2) ?>

<?php echo $at[3][0] ?>
<?php echo $at[3][1] ?>
<?php echo number_format($at[3][1]*$at2[0][1],2) ?>
<?php echo number_format($at[3][1]*$at2[1][1],2) ?>

The contents of ac.csv are:

a, 5,
b, 10,
c, 24,
d, 21

The contents of rc.csv are:

not, 1.87,
notatall, 1.78

As you can guess from the original code, I need to do multiplication in the second column.  In the second row and third column, for instance, I need 5*1.87 and 5*1.78. So basically a * not and a * notatall.

My code is not very efficient.  How can I make it more efficient?


texts: Docker script to set up a Python development environment with some Git projects

texts:
I've create a Docker script momodock.script that does some installation for a set of tools that I'll need to install on multiple machines:

FROM ubuntu:latest
MAINTAINER Momo <mo@mo.com>
LABEL description="TL;DR instructions to install Moses with Docker."
RUN apt-get update
RUN apt-get install -y apt-utils debconf-utils
RUN echo 'debconf debconf/frontend select Noninteractive' | debconf-set-selections
RUN apt-get update
RUN apt-get -y upgrade
RUN apt-get install -y sudo nano
RUN apt-get install -y perl
RUN apt-get install -y python-dev python3-dev python-pip python3-pip
RUN apt-get install -y libboost-all-dev
RUN apt-get install -y build-essential git-core pkg-config automake libtool wget zlib1g-dev python-dev libbz2-dev
RUN apt-get install -y cmake
RUN useradd -m -p mosesdocker -s /bin/bash ubiwan
RUN usermod -aG sudo ubiwan  # add user to sudo list
USER ubiwan
ENV HOME /home/ubiwan
WORKDIR $HOME
CMD /bin/bash
RUN cd $HOME
RUN git clone https://github.com/moses-smt/mosesdecoder.git
WORKDIR $HOME/mosesdecoder
RUN make -f $HOME/mosesdecoder/contrib/Makefiles/install-dependencies.gmake
RUN ./compile.sh  --max-kenlm-order=20 --max-factors=1000
WORKDIR $HOME
RUN git clone https://github.com/moses-smt/mgiza.git
WORKDIR $HOME/mgiza/mgizapp
RUN cmake .
RUN make
RUN make install
RUN cp $HOME/mgiza/mgizapp/scripts/merge_alignment.py bin/
WORKDIR $HOME
RUN git clone https://github.com/jonsafari/clustercat.git
WORKDIR $HOME/clustercat
RUN make -j 4
WORKDIR $HOME
RUN mkdir moses-training-tools
RUN cp mgiza/mgizapp/bin/* moses-training-tools/
RUN cp clustercat/bin/clustercat moses-training-tools/
RUN cp clustercat/bin/mkcls moses-training-tools/mkcls-clustercat
RUN mv moses-training-tools/mkcls moses-training-tools/mkcls-original
RUN cp moses-training-tools/mkcls-clustercat moses-training-tools/mkcls

And building it works smoothly:

docker build -t momo-docker.image - < momodock.script

But I've written the script like how one would emulate a human in the interactive docker environment.

Are there ways to simplify how I'm installing the required dependencies and software?


texts: Java - Something similar to Abstract Factory?

texts:
I have many repositories stored in a map. User chooses some of them and then a downloading begins. Repository may be one of 4 types (see code below).

/**
 * Data class that stores settings of a connection to repository.
 * Lombok's annotations are used to generate some methods.
 */
@Getter
@EqualsAndHashCode
public class Repository {
    public enum Type {
        FILE, FOLDER, GITHUB, BITBUCKET
    }

    private Type type;
    private String username;
    private char[] password;
    /*...*/
}

/**
 * A class that contains common stuff for all repository tools (such as connection to remote repository, download, logging, etc.)
 */
public abstract class AbstractRepositoryTools {

    /**
     * This method is implemented in child classes and actually it does the job.
     */
    protected abstract void doDownloadZip(Repository repo, String branch, Path saveTo);

    public static void downloadZip(Repository repo, String branch, Path saveTo) {
        AbstractRepositoryTools tools = Resolver.getToolsFor(repo);
        tools.doDownloadZip(repo, branch, saveTo);
    }

}

There are package-private classes that implement AbstractRepositoryTools for GitHub, BitBucket, and local repositories (folder or zip file).

/**
 * Resolver of a RepositoryTools implementation (with caching)
 */
class Resolver {

    // cache
    private static volatile BitbucketTools bitbucketTools = null;
    private static volatile GitTools gitTools = null;
    private static volatile LocalFileTools localFileTools = null;
    private static volatile LocalFolderTools localFolderTools = null;

    public static synchronized AbstractRepositoryTools getToolsFor(Repository repo) {
        switch (repo.getType()) {
            case GITHUB:
                if (gitTools == null)
                    gitTools = new GitTools();
                return gitTools;
            case BITBUCKET:
                if (bitbucketTools == null)
                    bitbucketTools = new BitbucketTools();
                return bitbucketTools;
            case FILE:
                if (localFileTools == null)
                    localFileTools = new LocalFileTools();
                return localFileTools;
            case FOLDER:
                if (localFolderTools == null)
                    localFolderTools = new LocalFolderTools();
                return localFolderTools;
            default:
                throw new NotImplementedException("Repository.TYPE = " + repo.getType());
        }
    }
}

Then I can take a repository from the map and download it like:

Repository repo = getRepo();
Path output = Paths.get("C:\\out")
AbstractRepositoryTools.downloadZip(repo, "develop", output);

It works but...

Does this code smell?
If yes, how to improve it?
If no, is there a name for such architecture pattern?


texts: Mapping DNA nucleotides into two-dimensional coordinates

texts:
I am the author of this package that turns DNA sequences into two dimensional visualizations. DNA, for the unaware, consists of four letters (A, T, G, and C). To convert the sequence, I am using this code:

import numpy as np

def transform(sequence):
    running_value = 0
    x, y = np.linspace(0, len(sequence), 2 * len(sequence) + 1), [0]
    for character in sequence:
        if character == "A":
            y.extend([running_value + 0.5, running_value])
        elif character == "C":
            y.extend([running_value - 0.5, running_value])
        elif character == "T":
            y.extend([running_value - 0.5, running_value - 1])
            running_value -= 1
        elif character == "G":
            y.extend([running_value + 0.5, running_value + 1])
            running_value += 1
        else:
            y.extend([running_value] * 2)
    return list(x), y

Note that seq may be a very long sequence, and this transformation process may be done (hundreds of) thousands of time.

What are some things I could do to improve performance?

Edit:

The else clause is the because some DNA sequences have ambiguity (i.e. non ATGC characters) which must be accounted for as horizontal lines.
sequence may safely assumed to be a string. For example, "GATTACA" is a valid DNA sequence that should return ([0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0, 5.5, 6.0, 6.5, 7.0],
[0, 0.5, 1, 1.5, 1, 0.5, 0, -0.5, -1, -0.5, -1, -1.5, -1, -0.5, -1]).
By "long", I mean anywhere from thousands to billions. That being said, the most common use case likely will involve fewer than ten thousand characters, although this process may be done to thousands of such sequences. For context, I am currently running this function over 400,000 sequences with a median length of 800 characters.


texts: Performance: repeated sweep through large binary dataset

texts:
As part of a bigger mcmc sampling algorithm, I'm repeatedly looping through my entire dataset. When the data grows large this becomes a pretty large bottleneck in my algorithm and I'm looking for ways to make it faster.

Some things I'm considering are:

What are the most efficient datatypes? For example, for the variable x I use std::vector< std::vector<bool> > because data are binary; 0 or 1. However, this leads to many type conversions. Is there a better way?
Can I use iterators to loop over the data more efficiently?

All suggestions are welcome!

Edit: the performance critical function does the following:

The goal of the code is to simulate a dataset of size np by ni, while simultaneously evaluating a likelihood ratio. The simulated new data is binary, and created by rlogis(0.0, 1.0) <= val ? 1 : 0. The subsequent evaluation of the ratio happens via acc += theta[i][d] * (x[i][j] -
 xnew) * C[j][d];. These two steps seem optimal from a performance perspective to me; my question is primarily about the surrounding structure.

Code:

#include <iostream>
#include <vector>
#include <chrono>

using namespace std; // <-- only here for the example; I don't normally do this

typedef unsigned int uint;
typedef std::vector<double> vec;
typedef std::vector<vec> mat;

// will be replaced by actual random number generator
double rlogis() {
    return rand() % 5 - 2;
}

// improving performance of this function is my goal
double orig(const uint np, const uint ni, const uint nd,
               const mat& theta, const mat& C,
               const vec& delta, const vec& lambdaNew,
               const int d, std::vector<std::vector<bool> >& x) {

    double acc = 0.0;
    bool xnew;
    vec tmp(nd);
    for (uint j = 0; j < ni; ++j) {

        for (uint d2 = 0; d2 < nd; ++d2) {
            tmp[d2] = lambdaNew[d2] * C[j][d2];
        }

        for (uint i = 0; i < np; ++i) {

            double val = delta[j];
            for (uint d2 = 0; d2 < nd; ++d2) {
                val += tmp[d2] * theta[i][d2];
            }

            xnew = rlogis() <= val;
            acc += theta[i][d] * (x[i][j] - xnew) * C[j][d];

        }
    }
    return acc;
}

// wrapper function for timing
int main() {

    // dimensions of the data
    const uint np = 2E4; // this could be larger, easily 1E5
    const uint ni = 200; // this stays constant
    const uint nd = 3;   // could be 4-5, but not 10

    // objects
    std::vector<double> delta(ni);
    std::vector<double> lambdaNew(nd);
    vector< std::vector<double> > theta(np, std::vector<double>(nd));
    vector< std::vector<double> > C(ni, std::vector<double>(nd));
    std::vector< std::vector<bool> > x(np, std::vector<bool>(ni));

    // fill objects with values (exact values are irrelevant)
    srand(1);
    int d = rand() % nd;
    for (uint i = 0; i < np; ++i) {
        for (uint d = 0; d < nd; ++d) {
            theta[i][d] = 2 * rand() - 1;
        }
        for (uint j = 0; j < ni; ++j) {
            x[i][j] = bool(int(rand() + .5));
        }
    }
    for (uint j = 0; j < ni; ++j) {
        delta[j] = 2 * rand() - 1;
        for (uint d = 0; d < nd; ++d) {
            C[j][d] = 2 * rand() - 1;
        }
    }
    for (uint d = 0; d < nd; ++d) {
        lambdaNew[d] = 5 * rand() + 1;
    }

    // start timing
    {
        srand(2);
        auto start = chrono::steady_clock::now();
        auto ans = orig(np, ni, nd, theta, C, delta, lambdaNew, d, x);
        auto time1 = chrono::steady_clock::now() - start;

        cout << "Orig: " << ans << "\n"
             << "Time: " << chrono::duration <double, milli> (time1).count() << " ms\n" << endl;
    }

    return 0;
}


texts: Retrieve records from the database based on a possible id

texts:
This code will retrieve all records from the database if the id is null or return records by the available id.  Is there a way to combine the query instead of having two separate queries?

// retrieve standard orders
let retrieveStdOrders id =

    if id = null then
        query{
            for row in tool.db.Order_Order_StandardOrder do
            select {
                Id = row.Id;
                BusinessLocationId = row.BusinessLocationId;
                ProductOptionId = row.ProductOptionId;

            }
        }
    else
        query{
            for row in tool.db.Order_Order_StandardOrder do
            where(row.Id = id)
            select {
                Id = row.Id;
                BusinessLocationId = row.BusinessLocationId;
                ProductOptionId = row.ProductOptionId;

            }
        }


texts:
The font size scales up/down based on the size of the browser to fit the nav bar buttons (using @media).

.navButtonText p{
    text-align: center;
    margin: auto;
    font-family: 'Indie Flower', serif;
                 font-weight:900;
                 color: gray;
                 font-size: 20px;
line-height: 20px;
  vertical-align: middle;
    margin-top: 6px;
}
}
@media only screen and (max-width: 650px) {
    .navButtonText p{
    text-align: center;
    margin: auto;
    font-family: 'Indie Flower', serif;
                 font-weight:900;
                 color: gray;
                 font-size: 18px;
line-height: 20px;
  vertical-align: middle;
    margin-top: 6px;
}
}
@media only screen and (max-width: 550px) {
    .navButtonText p{
    text-align: center;
    margin: auto;
    font-family: 'Indie Flower', serif;
                 font-weight:900;
                 color: gray;
                 font-size: 16px;
line-height: 20px;
  vertical-align: middle;
    margin-top: 6px;
}
}
@media only screen and (max-width: 450px) {
    .navButtonText p{
    text-align: center;
    margin: auto;
    font-family: 'Indie Flower', serif;
                 font-weight:900;
                 color: gray;
                 font-size: 14px;
line-height: 20px;
  vertical-align: middle;
    margin-top: 6px;
}
}
@media only screen and (max-width: 350px) {
    .navButtonText p{
    text-align: center;
    margin: auto;
    font-family: 'Indie Flower', serif;
                 font-weight:900;
                 color: gray;
                 font-size: 12px;
line-height: 20px;
  vertical-align: middle;
    margin-top: 6px;
}
}

As you can see, it is quite a bit of styling for one thing. I was wondering if there was a way I could clean up this code, so I wouldn't need to have it in these many lines.

I have SASS and Compass which I am willing to use.


texts:
I'm trying to write a C++ multiplication program using classes (for the first time - I usually try to avoid OOP) and am having trouble freeing my memory. What I'd ideally like is a matrix class with a function for allocating, initializing, multiplying, and freeing my matrices. What I currently have is

#include <iostream>
#include <cstdio>
#include <ctime>
#include <stdlib.h>

using namespace std;

class matrix
{
   static const int nrows = 40000;
   static const int ncols = 40000;

   // Allocate matrices for multiplication
   double (*matrix_a)[ncols] = (double (*)[ncols])malloc(sizeof(double) * (nrows) * (ncols));
   double (*matrix_b)[ncols] = (double (*)[ncols])malloc(sizeof(double) * (nrows) * (ncols));
   double (*matrix_c)[ncols] = (double (*)[ncols])malloc(sizeof(double) * (nrows) * (ncols));

   public:
      matrix()
      {
         // Initialize matrices
         for (int i = 0; i < nrows; i++)
         {
            for (int j = 0; j < nrows; j++)
            {
               matrix_a[i][j] = (double)rand() / (double)RAND_MAX;
               matrix_b[i][j] = (double)rand() / (double)RAND_MAX;
            }
         }
      }

      void multiplication()
      {
         // Multiply matrices
         for (int i = 0; i < nrows; i++)
         {
            for (int j = 0; j < ncols; j++)
            {
               matrix_c[i][j] = 0.0;
               for (int k = 0; k < ncols; k++)
               {
                  matrix_c[i][j] += matrix_a[i][k] * matrix_b[k][j];
               }
            }
         }
      }

      void free()
      {
         free(matrix_a);
         free(matrix_b);
         free(matrix_c);
      }
};

int main()
{
   matrix matMul = matrix();
   matMul.multiplication();
   matMul.free();
   return 0;
}

This currently works if you cut out the free() public function (and call to it within main), but I'd like to have this more like my intended description. If anyone could help me mold this into a more close format to my desired program, it would be much appreciated! Thanks in advance.