texts:
I am designing a new asp.net MVC4 application. I know that context class generated by EF is Unit of work and Dbset is the repository class. I am just avoiding the extra abstraction. I want to know whether I am following the correct pattern or not.

Entity

  public partial class ProductMaster
  {
    public long ID { get; set; }
    public string ProductCode { get; set; }
    public string ProductName { get; set; }

  }
  public partial class CompanyMaster
  {
    public long ID{ get; set; }
    public string CompanyName { get; set; }
    public string CompanyCode { get; set; }
  }

Context class(Generated By EF)

public partial class SampleEntities : DbContext,IUnitOfWork
{
    public SampleEntities()
        : base("name=SampleEntities")
    {
    }
    public void Commit()
    {
       SaveChanges();
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        throw new UnintentionalCodeFirstException();
    }

    public DbSet<ProductMaster> ProductMaster { get; set; }
    public DbSet<CompanyMaster> CompanyMaster { get; set; }
    public DbSet<UserMaster> UserMaster{ get; set; }

    public virtual ObjectResult<SP_UserMaster_Result> SP_UserMaster(Nullable<long> tM_UM_ID, string userName, string userPassword, Nullable<byte> userType)
    {
        var tM_UM_IDParameter = tM_UM_ID.HasValue ?
            new ObjectParameter("TM_UM_ID", tM_UM_ID) :
            new ObjectParameter("TM_UM_ID", typeof(long));

        var userNameParameter = userName != null ?
            new ObjectParameter("UserName", userName) :
            new ObjectParameter("UserName", typeof(string));

        var userPasswordParameter = userPassword != null ?
            new ObjectParameter("UserPassword", userPassword) :
            new ObjectParameter("UserPassword", typeof(string));

        var userTypeParameter = userType.HasValue ?
            new ObjectParameter("UserType", userType) :
            new ObjectParameter("UserType", typeof(byte));

        return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<SP_UserMaster_Result>("SP_UserMaster", tM_UM_IDParameter, userNameParameter, userPasswordParameter, userTypeParameter);
    }
}

Unit of Work Interface

public Interface IUnitOfWork
{
    public DbSet<ProductMaster> ProductMaster;
    public DbSet<CompanyMaster> CompanyMaster;
    public Dbset<UserMaster> UserMaster;
    public virtual ObjectResult SP_UserMaster(Nullable<long> tM_UM_ID, string userName, string userPassword, Nullable<byte> userType){};
    public void Commit();
}

Business Logic(Implementation)

 public class ProductMaster
 {
    IUnitOfWork _unitOfWork;
    public ProductMaster(IunitOfWork unitOfWork)//Injected using Ninject
    {
        this._unitOfWork = unitOfWork;
    }
    public void AddProduct(Product product)
    {
        _unitofWork.ProductMaster.Add(product);
        _unitOfWork.Commit();
    }
 }

Interface of Product Logic

 public class IProductMaster
  {
    public ProductMaster(IunitOfWork unitOfWork);
  }

Product Controller

  public class ProductController : Controller
  {
     IProductMaster _productMaster;
     public ProductController(IproductMaster productMaster)
     {
       this._ProductMaster=productMaster;//Injecting using Ninject
     }
     public void SaveProduct(ProductMaster product)
     {
        this._productMaster.AddProduct(product.ToEntity());
     }
  }


texts: Recording all instances of a class - Python

texts:
In a programme that I am writing, I need to loop through all the instances of a class, the way I got around this was by appending every class to a list like below:

allPeople = []
class Person:

    def __init__(self, name, age, height):
        self.name = name
        self.age = age
        self.height = height
        allPeople.append(self)

Jeff = Person("Jeff", 20, "1.6")
Bob = Person("Bob", 39, "1.4")
Helen = Person("Helen", 19, "1.3")

for person in allPeople:
    print(person.name + " is " + str(person.age))

Is this the best way of doing things or is there a built in python function for this?


texts: Efficient way to get value from a dataframe and append new dataframe

texts:
I have a dataframe that have about 200 million rows. the example of dataframe is like this:

date         query
29-03-2019   SELECT * FROM table WHERE ..
30-03-2019   SELECT * FROM ... JOIN ... ON ...WHERE ..
....         ....
20-05-2019   SELECT ...

I have a function to get table(s) name, attribute(s) name from dataframe above and append to new dataframe.

import sqlparse
from sqlparse.tokens import Keyword, DML
def getTableName(sql):
    def getTableKey(parsed):
        findFrom = False
        wordKey = ['FROM','JOIN', 'LEFT JOIN', 'INNER JOIN', 'RIGHT JOIN', 'OUTER JOIN', 'FULL JOIN']
        for word in parsed.tokens:
            if word.is_group:
                for f in getTableKey(word):
                    yield f
            if findFrom:
                if isSelect(word):
                    for f in getTableKey(word):
                        yield f
                elif word.ttype is Keyword:
                    findFrom = False
                    StopIteration
                else:
                    yield word
            if word.ttype is Keyword and word.value.upper() in wordKey:
                findFrom = True
    tableName = []
    query = (sqlparse.parse(sql))
    for word in query:
        if word.get_type() != 'UNKNOWN':
            stream  = getTableKey(word)
            table   = set(list(getWord(stream)))
            for item in table:
                tabl = re.sub(r'^.+?(?<=[.])','',item)
                tableName.append(tabl)
    return tableName

and the function to get attribute is just like getTableName the different is the wordKey.

function to process dataframe is like this:

import pandas as pd
def getTableAttribute(dataFrame, queryCol, date):
    tableName       = []
    attributeName   = []
    df              = pd.DataFrame()
    for row in dataFrame[queryCol]:
        table       = getTableName(row)
        tableJoin   = getJoinTable(row)
        attribute   = getAttribute(row)
        #append into list
        tableName.append(table+tableJoin)
        attributeName.append(attribute)
    df = dataFrame[[date]].copy()
    df['tableName']      = tableName
    df['attributeName']  = attributeName
    print('Done')
    return df

The result of the function is like this:

date        tableName  attributeName
29-03-2019  tableN     attributeM
30-03-2019  tableA     attributeB
....        ...        ...
20-05-2019  tableF     attributeG

But as this is my first try, I need an opinion about what I've tried, because my code runs slow with large file.


texts:
Based on my previous post I completely re-factored my code to make it object oriented.

Anything I could improve when it comes to:

Object oriented code;
Efficiency;
Readability.

Any other suggestions are also welcome!

Validator class:

class Validator
{
    private $rules  = [];
    private $errors = [];

    public function getErrors($rulename = null)
    {
        if ($rulename) {
            return isset($this->errors[$rulename]) ? $this->errors[$rulename] : null;
        }

        return $this->errors;
    }

    # rules will be checked against in same order as specified
    public function setRule($name, Array $rules)
    {
        if (!array_key_exists($name, $this->rules)) {
            foreach ($rules as $rule) {
                if (!$rule instanceof IRule) {
                    throw new Exception('Array must only contain instances of IRule.');
                }
            }

            $this->rules[$name] = $rules;
        } else {
            throw new Exception(sprintf('Rule %s already exists.', $name));
        }
    }

    public function validate($rulename, $input)
    {
        foreach ($this->rules[$rulename] as $rule) {
            try {
                $rule->check($input);
            } catch (Exception $e) {
                $this->errors[$rulename][] = $e->getMessage();
            }
        }

        if (isset($this->errors[$rulename])) {
            return false;
        }

        return true;
    }
}

One of the rule classes:

class Between implements IRule
{
    private $errMsg = 'Must be between %s and %s.';

    private $inclusive;
    private $max;
    private $min;

    public function __construct($min, $max, $inclusive = true, $errMsg = null)
    {
        $this->min       = $min;
        $this->max       = $max;
        $this->inclusive = $inclusive;

        if ($errMsg !== null) {
            $this->errMsg = $errMsg;
        }
    }

    public function check($input)
    {
        if ($this->inclusive && $input >= $this->min && $input <= $this->max) {
            return true;
        } elseif (!$this->inclusive && $input > $this->min && $input < $this->max) {
            return true;
        } else {
             throw new Exception(sprintf($this->errMsg, $this->min, $this->max));
        }
    }
}

Example:

$validator = new Validator();

$validator->setRule('name',  [new NotEmpty(), new MaxChars(20), new Alpha(true)]);
$validator->setRule('email', [new NotEmpty(), new Email()]);

$validator->setRule('age',
    array(
        # last constructor argument overrides default error message
        new NotEmpty('You did not enter your age.'),
        new Numeric('Your age can only be numerical.'),
        new Between(13, 17, true, 'Only teenagers are allowed.')
    )
);

$validator->validate('name',  'John');
$validator->validate('email', 'Doe');
$validator->validate('age',   'Hello');

# report
if (!$validator->getErrors()) {
    echo 'Input(s) valid: Passed complete validation.';
} else {
    echo 'Input(s) invalid: Failed complete validation.';
}


texts:
Description

Your task is to imitate a turn-based variation of the popular "Snake" game.
You are given the initial configuration of the board and a list of commands which the snake follows one-by-one. The game ends if one of the following happens:

the snake tries to eat its tail
the snake tries to move out of the board
it executes all the given commands.

Output the board configuration after the game ends. With the snake replaced by 'X' if the game ends abnormally.

Examples
input:
snakeGame([['.', '.', '.', '.'],
           ['.', '.', '<', '*'],
           ['.', '.', '.', '*']],
          "FFFFFRFFRRLLF")

output:
          [['.', '.', '.', '.'],
           ['X', 'X', 'X', '.'],
           ['.', '.', '.', '.']]

input:
snakeGame([['.', '.', '^', '.', '.'],
           ['.', '.', '*', '*', '.'],
           ['.', '.', '.', '*', '*']],
          "RFRF")

output:
          [['.', '.', 'X', 'X', '.'],
           ['.', '.', 'X', 'X', '.'],
           ['.', '.', '.', 'X', '.']]

input:
snakeGame([['.', '.', '*', '>', '.'],
           ['.', '*', '*', '.', '.'],
           ['.', '.', '.', '.', '.']],
          "FRFFRFFRFLFF")

output:
          [['.', '.', '.', '.', '.'],
           ['<', '*', '*', '.', '.'],
           ['.', '.', '*', '.', '.']]

Code
def snakeGame(gameBoard, commands):
    heads = {'v': (1, 0), '^': (-1, 0), '<': (0, -1), '>': (0, 1)}
    new_direc = {'v': {'L': '>', 'R': '<'},
                 '^': {'L': '<', 'R': '>'},
                 '<': {'L': 'v', 'R': '^'},
                 '>': {'L': '^', 'R': 'v'}}

    def find_snake():
        def get_next(x, y):
            for key, direc in heads.items():
                new_x, new_y = x + direc[0], y + direc[1]
                if new_x in range(len(gameBoard)) and new_y in range(len(gameBoard[0])):
                    if (new_x, new_y) not in snake:
                        if gameBoard[new_x][new_y] == '*':
                            return (new_x, new_y)

        # Get the head and the next body opposite of snake's direction
        snake = []
        for i, row in enumerate(gameBoard):
            for head in heads:
                if head in row:
                    snake.append((i, row.index(head)))
                    snake.append((snake[0][0] + heads[head][0] * -1, snake[0][1]  + heads[head][1] * -1))

        # Append the rest of the body
        while True:
            n = get_next(snake[-1][0], snake[-1][1])
            if n is None:
                break
            snake.append(n)

        return snake

    def move_snake(snake):
        head = gameBoard[snake[0][0]][snake[0][1]]
        new_x, new_y = snake[0][0] + heads[head][0], snake[0][1]  + heads[head][1]
        new_snake = []
        if new_x in range(len(gameBoard)) and new_y in range(len(gameBoard[0])) and (new_x, new_y) not in snake:
            new_snake.append((new_x, new_y))

            for pos in snake[:-1]:
                new_snake.append(pos)

            return new_snake

    # Find starting snake
    snake = find_snake()

    for command in commands:
        if command in "LR":
            # Change the head
            gameBoard[snake[0][0]][snake[0][1]] = new_direc[gameBoard[snake[0][0]][snake[0][1]]][command]
        else:
            temp = move_snake(snake)

            # if not valid move return dead snake
            if temp is None:
                for pos in snake:
                    x, y = pos
                    gameBoard[x][y] = 'X'
                return gameBoard

            # else move snake
            for a, b in zip(snake, temp):
                gameBoard[b[0]][b[1]] = gameBoard[a[0]][a[1]]

            gameBoard[snake[-1][0]][snake[-1][1]] = '.'
            snake = temp

    return gameBoard


texts:
Ive been sitting here for the past 20 minutes trying to make this simple/tiny function more 'readable' and 'clean'. Am I overthinking this or am I missing some major tips that could help me out?

string findSameSales (int numSold, int salesArray[], string namesArray[])
 {
  string ssList = " ";
  for (int counter = 0; counter <= NUM_OF_POS; counter++)
    {
      if (numSold == salesArray[counter])
        {
         if (ssList == " ")
           ssList = namesArray[counter];
         else
           ssList += (", " + namesArray[counter]);
        }
      else;
    }

  return ssList;
 }


texts: Answering Master Clojure for the Brave and True - concurrency exercises

texts:
I recently answered the two exercises at the end of this chapter of Clojure for the Brave and True (see the end of the page).

First exercise: count words in random quotes (in parallel)

This is my answer:

(defn count-quote-words [num-quotes]
  (let [wc (atom {})
        tasks (map
                (fn [_] (future (let [quote (slurp "http://www.braveclojure.com/random-quote")
                                      words-seq (re-seq #"\w+" quote)
                                      words (reduce (fn [coll word] (merge-with + coll {word 1})) {} words-seq)
                                      merge-words (partial merge-with + words)]
                                  (swap! wc merge-words))))
                (range num-quotes))]
    (dorun (map deref tasks))
    @wc))

Second exercise: use transaction in refs

(let [c1 (ref {:hp {:current 15 :max 40}
               :inventory []})
      c2 (ref {:hp {:current 40 :max 40}
               :inventory [:healing-potion]})
      heal (fn [c amount] (assoc-in c [:hp :current] (+ (get-in c [:hp :current]) amount)))
      dispose-item (fn [c item] (assoc c :inventory (into [] (remove #(= % item) (c :inventory)))))]
  (dosync
    (alter c1 heal 15)
    (alter c2 dispose-item :healing-potion))
  (println @c1)
  (println @c2))

What do you think about those code blocks? What can I improve?


texts: struct.unpack on a bytearray that works under Python 2.6.6, 2.7 and 3.3?

texts:
Given the test code:

import struct
buf = bytearray(b'\xef\xf8\t\xf2')
number = struct.unpack("<I", buf)[0]

How do I cleanly make it work both under Python 2.6 and Python 3.3? The problem is that struct.unpack in Python 2.6 seems to expect a str object (not unicode), so the only way I managed to come up with in order to get it working on both versions is:

buf_raw = bytearray(b'\xef\xf8\t\xf2')
buf_decoded = buf_raw.decode('latin1')
buf_encoded = buf_decoded.encode('latin1')
number = struct.unpack("<I", buf_encoded)[0]

...though I'm abusing the fact that latin1 translates every 0-255 ASCII character to itself. What's the better way?


texts:
A while back, I posted a question involving code of the same function. This post contains improved code.

From the last post, I have improved size, my work with conventions, and my comments. I was also able to minimalism memory interaction to speed things up/make things more efficient.

%define KERNEL_CALL int 80h

%define STDOUT 1
%define SYS_WRITE 4

%define EXIT 1

%define NEWLINE 0xA
%define ASCII_NUM 30h

; @params: AX - a number that is converted to ASCII, then printed
; @return: no return
%macro put_num 0
    push ax;        push ax onto the stack(for restoring value)
    add ax, ASCII_NUM;  numerical to ascii
    push ax;        push ax onto the stack(for reference by ESP)

    mov edx, 1;     message length
    mov ecx, esp;   the number from the stack pointer
    mov ebx, STDOUT
    mov eax, SYS_WRITE
    KERNEL_CALL;    logs the number to the console

    pop ax;         getting it out of the way
    pop ax;         restoring the original value of ax
%endmacro

section .text
    global _start;  for gnu linker
_start:
    push '10';      push '10' to the stack for reference by ESP

    mov edx, 2;     length
    mov ecx, esp;   message(number)
    mov ebx, STDOUT
    mov eax, SYS_WRITE
    KERNEL_CALL;    logs '10' to the console

    mov ax, 9;      initialize ax
countdown:
    put_num;        log the current number to stdout
.subtract:
    sub ax, 1;      subtract 1

    cmp ax, 0;      compare ax with 0...
    je .blast_off;  if equal, jump to .blast_off
    jmp countdown;  if not equal, go back to countdown
.blast_off:
    mov edx, len;   message length
    mov ecx, msg;   message
    mov ebx, STDOUT
    mov eax, SYS_WRITE
    KERNEL_CALL;    logs 'Blast off!' to the console

    xor ebx, ebx
    mov eax, EXIT
    KERNEL_CALL;    exit
section .data
    msg db "Blast off!", NEWLINE
    len equ $ - msg

Output (I know - the formatting still needs work):

  10987654321Blast off!

Assembled: nasm -f elf bo7_working.s

Linked:: ld -m elf_i386 -s -o bo bo7_working.o

Some concerns:

After I learned about macros, I started to use them a lot. Am I using them in place of headers (and is this bad), or is how I am using them fine?
Am I over-using/misusing %defines (more specifically, KERNEL_CALL)?
Do I have too many or too few comments?
Are my comments unclear?
Are there any unnecessary lines? I'm a little worried about the popping at the end of put_num...
Am I following convention, or are there more things I should do?
Is my code understandable?


texts: Ignore exceptions when changing column formula in Excel table

texts:
The new table feature on Excel is excellent and you can specify a column formula as well as exceptions on the column. However, if you want to change the column formula, Excel will rewrite the whole column including the exceptions. I've tried to avoid this issue with the following code:

Private Sub Worksheet_Change(ByVal Target As Range)
    On Error GoTo ErrHandler

    'Prevent from firing if changed cell is outside a table
    If Target.ListObject Is Nothing Then Exit Sub
    'Prevent from firing if cell is changed to a value
    If Val(Target.Formula) = Target.Value Then Exit Sub
    'Prevent from firing if multiple cells where changed
    If Target.Count > 1 Then Exit Sub
    'Disable events
    ToggleWaitMode

    'Prevent change if user already stated calculation as manual
    Dim bCheckCalculationMode As Boolean
    If Application.Calculation = xlCalculationAutomatic Then
        Application.Calculation = xlCalculationManual
        bCheckCalculationMode = True
    End If

    'Declarations
    Dim sTableName As String
    Dim lNbLines As Long
    Dim i As Long
    Dim sFieldName As String
    Dim cel As Range
    Dim sOldFormula As String
    Dim sNewFormula As String
    Dim aExceptionFormulas() As String
    Dim aExceptionAddresses() As String

    sTableName = Target.ListObject.Name
    lNbLines = Range(sTableName).Rows.Count
    sFieldName = "[" & Intersect(Target.ListObject.HeaderRowRange, Target.EntireColumn).Value & "]"

    'Add a new row to get the column formula
    Range(sTableName).ListObject.ListRows.Add
    sOldFormula = Range(sTableName & sFieldName)(lNbLines).Formula

    sNewFormula = Target.Formula

    'Loop on each cell of the column to get each exception formulas and addresses in arrays
    i = 1
    For Each cel In Range(sTableName & sFieldName)
        If cel.Formula <> sOldFormula Then
            ReDim Preserve aExceptionFormulas(1 To i)
            ReDim Preserve aExceptionAddresses(1 To i)
            aExceptionFormulas(i) = cel.Formula
            aExceptionAddresses(i) = cel.Address
            i = i + 1
        End If
    Next cel

    'Delete added row and replace column to new formula
    Range(sTableName).ListObject.ListRows(lNbLines).Delete
    Range(sTableName & sFieldName).Formula = sNewFormula

    If i > 1 Then
        For i = 1 To UBound(aExceptionFormulas)
            Range(aExceptionAddresses(i)).Formula = aExceptionFormulas(i)
        Next i
    End If
    ActiveSheet.Calculate

CleanExit:
    If bCheckCalculationMode Then Application.Calculation = xlCalculationAutomatic
    ToggleWaitMode False
    Exit Sub
ErrHandler:

End Sub

Private Sub ToggleWaitMode(Optional ByVal bWait As Boolean = True)
    Application.EnableEvents = Not bWait
    Application.AutoCorrect.AutoFillFormulasInLists = Not bWait
End Sub

The code works but it's really ugly. Do you think it's possible to optimize it? For example by finding the Inconsistent Formulas?

Edit: I've modified the code accordingly to the great advices of Mat's Mug. I hope it got better. Can the added row be avoided? It's just a workaround to get the column formula.


texts:
Solving it by the logic:

find the length
traverse to length-n+1
remove item

I've written the following code

class ListNode:
 def __init__(self, x):
     self.val = x
     self.next = None

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    # @param A : head node of linked list
    # @param B : integer
    # @return the head node in the linked list
    def removeNthFromEnd(self, A, B):
        temp = A
        len = 0
        while temp is not None:
            len += 1
            temp = temp.next
        result = ListNode(None)
        result.next =  A

        if B >= len:
            if B ==1:
                result.next = None
            else:
                result.next = A.next
        else:
            for i in range(len-B-1):
                A = A.next
            if B == 1:
                A.next = None
            else:
                A.next = A.next.next
        return result.next

if __name__ == "__main__":
        a = ListNode(1)
        b = ListNode(2)
        c = ListNode(3)
        d = ListNode(4)
        e = ListNode(5)
        a.next = b
        b.next = c
        c.next = d
        d.next = e
        A = Solution().removeNthFromEnd(a, 1)
        while A is not None:
            print A.val
            A = A.next

It seems duplicating some logic. How can we improve this code?


texts:
import csv
class CSV:
    def __init__(self,title, row=[]):
       self.row = row
       self.title = title

    def create(self):
       csvfilename = "{}".format(self.title)
       csvFileObj = open(csvfilename, 'w' , encoding='utf-8-sig', newline='')
       csvWriterObj = csv.writer(csvFileObj)
       csvWriterObj.writerow(self.row)
       csvFileObj.close()

    def createConsolidate(self):
       csvfilename = "{}".format(self.title)
       csvFileObj = open(csvfilename, 'w' , encoding='utf-8-sig', newline='')
       csvWriterObj = csv.writer(csvFileObj)
       for row in self.row:
          csvWriterObj.writerow(row)
       csvFileObj.close()

    def appendConsolidate(self):
       csvfilename = "{}".format(self.title)
       csvFileObj = open(csvfilename, 'a' , encoding='utf-8-sig', newline='')
       csvWriterObj = csv.writer(csvFileObj)
       for row in self.row:
          csvWriterObj.writerow(row)
       csvFileObj.close()

    def open(self):.
       rowData = []
       csvfilename = "{}".format(self.title)
       csvFileObj = open(csvfilename, encoding='utf-8-sig')
       readerObj = csv.reader(csvFileObj)
       for row in readerObj:
         rowData.append(row)
       return rowData
       csvFileObj.close()

it's working but not DRY. It can be easy to make it just a function but for learning purposes. Not familiar with python classes. Thank you for your help in advance.


texts:
I want my code to be reviewed and I'd like to hear your opinions.

Sun's code to compute hash of string:

public int hashCode() {
    int h = hash;
  if (h == 0 && value.length > 0) {
      char val[] = value;
      for (int i = 0; i < value.length; i++) {
          h = 31 * h + val[i];
      }
      hash = h;
  }
    return h;
}

My code:

public int hashCode2() {
    if (hash == 0) {
        for (int i = 0; i < value.length; i++) {
            hash = 31 * hash + value[i];
        }
    }
    return hash;
}

Why I consider my code an improved version:

There is no need to create variables h and val as done in Sun's method.
The premature check of value.length > 0 is not good enough to add this complexity.


texts: Find a sum using just two different digits

texts:
The problem statement was pretty easy and I was able to run half of the test cases, but some of the test cases in the end gave me the error of memory limit reached. What can I do here to improve the memory efficiency of my code?
Question: Find the min number of "usable" integers required to reach the N. The "usable integers" are those that contain only 4 or 5 in their decimal representation, e.g. 4,5,455,545454.
So to reach 9, answer would be 2 (4+5) My approach: Creating a vector consisting of all usable numbers up to N and using dynamic programming solution on that vector to find the minimum number of elements required to reach N.
My code:
int getCount(int N) {
    vector<int> vec;vec.push_back(4);vec.push_back(5);
    int i = 0;int temp = 0;
    while(true) {
        temp = vec[i] * 10 + 4;
        if(temp > N)
            break;
        vec.push_back(temp);
        temp = vec[i] * 10 + 5;
        if(temp > N)
            break;
        vec.push_back(temp);
        i++;
    }

    return getCountDP(vec,vec.size(),N);
}

int getCountDP(vector<int> vec,int size, int N){

    int dp[size+1][N+1];

    for(int i = 0 ; i <= N; i++) {
        dp[0][i] = INT_MAX - 1;
    }

    for(int i = 0 ; i < size+1; i++) {
        dp[i][0] = 0;
    }

    for (int i = 1; i <= size; i++) {
        for (int j = 1; j <= N; j++) {
            if (vec[i - 1] > j) {
                dp[i][j]= dp[i-1][j];
            }
            else {
                dp[i][j]= min(dp[i-1][j],dp[i][j-vec[i-1]]+1);
            }
        }
    }
    return dp[size][N];
}


texts: A function which collates data from various API calls. Help on design-pattern

texts:
Help on the appropriate design pattern for this.

Program details:

  A scheduled script that fetches all the data from various framework-based API's - executeSearch('webservice_name') - ,
  then, collate the data and pass it to another framework-API - saveToReportTemplate('report_template_name') -
  which persists the collated data to the database.

var Report = Report || {};

(function (R) {

    var _data1 = 0,
        _data2 = 0,
        _data3 = 0,
        _data4 = 0;

    function initData() {
        _data1 = 0;
        _data2 = 0;
        _data3 = 0;
        _data4 = 0;
    }

    function fetchData1() {
        //executeSearch is a framework API
        var result = executeSearch('transactions');

        _data1 = result.getValue('transactions.done');
    }

    function fetchData2() {
        //executeSearch is a framework API
        var result = executeSearch('company');

        _data2 = result.getValue('company.investors');
    }

    function fetchData3and4() {
        //executeSearch is a framework API
        var result = executeSearch('employee');
        _data3 =  result.getValue('employee.name');
        _data4 =  result.getValue('employee.salary');
    }

    function populateReport() {
        //framework API
        saveToReportTemplate('some_report_template', _data1, _data2, _data3, _data4);
    }

    R.generateReport = function () {
        initData();
        fetchData1();
        fetchData2();
        fetchData3and4();
    };

})(Report);

//usage
R.generateReport();

Need help/advice/criticisms on:

overall structure of the program
my usage of private variables and functions
usage of javascript's closure
is there anything I can improve?
any good design patterns for solving this kind of problem?

Note:
There is no way we can implement a new database table/view for this, because we are just interacting on external APIs.
Also, there is no SQL-based method provided for us to solve such problems.


texts:
I'm trying to create an effiecent way to shut down my console application. To do this I have a while loop in my program's main method waiting for a request to shutdown.

var rebootAfterClose = false;

while (true)
{
    var input = Console.ReadKey();

    if (input.Key == ConsoleKey.C && input.Modifiers == ConsoleModifiers.Control)
    {
        break;
    }

    if (input.Key != ConsoleKey.R || input.Modifiers != ConsoleModifiers.Control)
    {
        continue;
    }

    rebootAfterClose = true;

    break;
}

Server?.Stop(rebootAfterClose);

I then have these methods, the stop is the one that gets called, Dispose gets called in Stop().

public void Dispose()
{
    if (Disposing)
    {
        return;
    }

    Disposing = true;

    BaseHandler.PlayerHandler.Dispose();

    ConsoleUpdater.Dispose();
    SocketHandler.Dispose();
}

public void Stop(bool restart)
{
    Task.Factory.StartNew(() =>
    {
        var shutdownMessage = PlusEnvironment.GetLanguageManager().TryGetValue("server.shutdown.message");
        var shutdownPacket = new BroadcastMessageAlertComposer(shutdownMessage);

        Program.Server.BaseHandler.PlayerHandler.SendPacketToPlayers(shutdownPacket);

        ConsoleUpdater.Stop();

        Console.Clear();
        Console.WriteLine();
        Console.Title = "Stopping...";

        Logger.Warn("Server is " + (restart ? "rebooting" : "shutting down") + "....");

        Thread.Sleep(5000);

        // not sure if I should use this instead? : Task.Delay(5000);

        Dispose();

        if (restart)
        {
            Process.Start(Assembly.GetExecutingAssembly().Location);
        }

        Environment.Exit(0);
    });
}

I used a thread as I didn't want to block the thread with the 5 second delay. I'm currently looking to just tidy this mechanism up as I am really new to multithreading and just want to know if I did okay, I appreciate everyone who contributes a comment or answer.

Another thing I'm worried about is the while (true) loop in my main method, is there any better way to do this? I need to avoid closing the console application on any other key other than the ones in the while loop (CTR+C], or CTRL+R) but I can't think of a better way to do that.


texts: C# Winforms: Is there any way to improve this simple custom Textbox code?

texts:
I have been working on Custom TextBox control, which only allows alphanumeric characters. Note that I have not restricted characters from KeyPress, KeyUp event as I don't want to restrict copy/paste or any other operation that should be allowed generally. I have only trimmed non-alphanumeric character on paste operation. However, I am not sure whether the code I wrote is good or bad as I have very little experience of desktop application.

using System;
using System.Windows.Forms;
using System.Text.RegularExpressions;

namespace SaintThomas.UserControls
{
    class TextBoxForUserName : TextBox
    {
    protected override void OnTextChanged(EventArgs e)
    {
        base.OnTextChanged(e);

        this.SuspendLayout();
        int startPos = this.SelectionStart;
        if (Regex.IsMatch(this.Text, "[^0-9_A-Z]", RegexOptions.IgnoreCase))
        {
        int reduceStartPos = this.Text.Length;
        this.Text = Regex.Replace(this.Text, "[^0-9_A-Z]", "", RegexOptions.IgnoreCase);
        startPos = (startPos <= 0) ? 0 : startPos - (reduceStartPos - this.Text.Length);
        if (this.Text.Length < startPos)
        {
            startPos = this.Text.Length;
        }
        this.SelectionStart = startPos;
        }
        this.ResumeLayout();
    }
    }
}


texts: Iterating X times (where X > Y) over Y element dictionary

texts:
I need to write a procedure, that will take a dictionary consisting of server names and their available slots and a number of slots required, and redispatch it over the servers, so that every server would accept only that many assignments as he has free slots; servers with higher number of free slots would be assigned in first place; whole procedure would be robust and not prone to any stupid math errors I might have done. So far I've came up with something like that:

import operator

slots_required = 8
hosts = {'server1': 3, 'server2': 7, 'server3': 1}
jobs = {}

if slots_required > sum(hosts.values()):
    print " [!] Not enough resources! Exiting."
else:
    print " [x] entering while loop"
    while slots_required > 0:
        print " [x] while loop on interation: %s" % slots_required
        for host in sorted(hosts.iteritems(), key=operator.itemgetter(1), reverse=True):
            # if for any reason slots_required number is 0 or less, break
            if slots_required <= 0:
                break
            # if the host has no slots free we're not iterating over it and removing it
            if host[1] == 0:
                hosts.pop(host[0])
                break
            else:
                print " [x] for loop, host: %s" % host[0]
                jobs[slots_required] = host
                slots_required -= 1
                hosts[host[0]] = host[1] - 1
                print " [x] slots_required value after decreasing: %s" % slots_required

        print " [x] exited the for loop"
    print " [x] Iteration down to ZERO! Exiting!"
    print " [x] exiting while loop"

print jobs
print hosts
print slots_required

Feel free to play around and change server numbers, their free slots and slots required of course. The numbers I've added are only for example and testing purposes, and the print functions can be taken out as well, the only thing I am interested in at the end is the jobs dictionary with server names and their assignments (there will be jobID inserted next to server name in jobs dictionary instead of a number, as it is right now). Is there a better, nicer, safer and quicker way of doing that? I've feeling the code although working in my tests, is extremely ugly and could be more functional.


texts: Find the minimum number of characters to add to make password strong

texts:
This is the criteria:

Its length is at least 6. It contains at least one digit. It contains at least one lowercase English character. It contains at least one uppercase English character. It contains at least one special character. The special characters are: !@#$%^&*()-+

My code is working for all test cases but I'm afraid it seems way longer than necessary. I'm trying to trim it down.

import math
import os
import random
import re
import sys

# Complete the minimumNumber function below.
def minimumNumber(n, password):
    # Return the minimum number of characters to make the password strong
    flag = 0
    if len(password) >= 6:
        passRegex = re.compile(r"^(?=.*[\d])")
        mo = passRegex.search(password)
        if mo is None:
            flag+=1
        passRegex = re.compile(r"^(?=.*[A-Z])")
        mo = passRegex.search(password)
        if mo is None:
            flag+=1
        passRegex = re.compile(r"^(?=.*[a-z])")
        mo = passRegex.search(password)
        if mo is None:
            flag+=1
        passRegex = re.compile(r'[!@#$%^&*()-+]')
        mo = passRegex.search(password)
        if mo is None:
            flag+=1
        return flag
    else:
        if any(x in "0123456789" for x in password) is False:
            flag+=1
        if any(x in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" for x in password) is False:
            flag+=1
        if any(x in "abcdefghijklmnopqrstuvwxyz" for x in password) is False:
            flag+=1
        if any(x in "!@#$%^&*()-+" for x in password) is False:
            flag+=1
        if (flag+len(password)<6):
            return 6-len(password)
        if (flag+len(password)>=6):
            return flag

if __name__ == '__main__':

    n = int(input())

    password = input()

    answer = minimumNumber(n, password)

Any advice is appreciated.


texts: Select Records Constituting Percentage of Total

texts:
The Setup
I have a table (call it myTable) in MS Access with two fields: Item (Text) and Quantity (Long).
For example, the first 10 records might be:
Item      |  Quantity
----------+----------
Item001   |       706
Item002   |       533
Item003   |       580
Item004   |       289
Item005   |       302
Item006   |       775
Item007   |        14
Item008   |       761
Item009   |       815
Item010   |       709

The Task
I'm looking to obtain a table/query containing the top N records whose Quantity constitutes a given percentage of the total Quantity across all records.
For example:
If the total of the Quantity field for all records is 1000 and the given percentage is 80%, the output table/query would contain sufficient records in decreasing Quantity until the total Quantity is 800.

My Code
Here is my current approach:
Function Percentile(dblPct As Double)
    On Error GoTo Cleanup
    Dim dbsCdb As DAO.Database
    Dim rstRs1 As DAO.Recordset
    Dim rstRs2 As DAO.Recordset
    Dim lngTot As Long
    Dim lngSum As Long
    Dim lngRcd As Long

    Set dbsCdb = CurrentDb
    Set rstRs1 = dbsCdb.OpenRecordset("SELECT Sum(Quantity) FROM myTable")

    With rstRs1
        If Not .EOF Then
            .MoveFirst
            lngTot = .Fields(0) * dblPct
        End If
        .Close
    End With
    Set rstRs1 = Nothing

    If 0 < lngTot Then
        Set rstRs2 = dbsCdb.OpenRecordset("SELECT * FROM myTable ORDER BY Quantity DESC")
        With rstRs2
            If Not .EOF Then
                .MoveFirst
                Do Until .EOF Or lngSum >= lngTot
                    lngRcd = lngRcd + 1
                    lngSum = lngSum + !Quantity
                    .MoveNext
                Loop
            End If
            .Close
        End With
        Set rstRs2 = Nothing

        DoCmd.RunSQL "SELECT TOP " & lngRcd & " * INTO OutputTable FROM myTable ORDER BY Quantity DESC"
    End If

Cleanup:
    On Error Resume Next
    If Not (rstRs1 Is Nothing) Then rstRs1.Close: Set rstRs1 = Nothing
    If Not (rstRs2 Is Nothing) Then rstRs2.Close: Set rstRs2 = Nothing
    If Not (dbsCdb Is Nothing) Then Set dbsCdb = Nothing
End Function

I first calculate the total Quantity of all records in myTable and multiply this by the given percentage argument (e.g. 0.8 for 80%).
I then iterate over the records in descending order of Quantity and calculate a running total, ceasing when this total is greater than or equal to the target, counting the number of records it takes to do so.
Finally, I select the calculated number of records from the table to create an OutputTable.

What I'm Hoping For

I'm relatively new to VBA, so feedback on any obvious bad practices in my code would be appreciated.

I feel like I'm missing something obvious - could this be achieved using one or two SQL statements?

Many thanks in advance for your time!


texts: Searching and sorting ranges in excel with toggle buttons

texts:
I have a spreadsheet containing ±100 named ranges (5 rows, 15 colums) which are sorted based on time.

My plan was to make toggle buttons to hide or unhide named ranges when they contain a certain value.

So when I select the toggle button for 'Opel' for instance, all the named ranges containing 'Opel' are displayed. And when I select 'Opel' and 'Ford. All the ranges containing 'Opel' and 'Ford' are displayed while also being able to sort the ranges in that view.

For the sorting I use the following code:

Sub SorterenOpdrachten()

Dim Detail As Worksheet
Dim I As Long
Dim ListRng As Range
Dim LijstWks As Worksheet
Dim NamedRng As Name
Dim R As Long
Dim Rng As Range
Dim SortWks As Worksheet

'Worksheet declareren als variabele
Set Detail = Worksheets("detail")
Set LijstWks = Worksheets("LijstWks")
Set SortWks = Worksheets("SortWks")

'Startrij voor de lijst instellen = Rij 1 fungeert als "hoofding"
R = 2

'Ranges naar lijst kopiëren - Opdracht en uur
For Each NamedRng In ActiveWorkbook.Names

LijstWks.Cells(R, 1) = NamedRng.Name
LijstWks.Cells(R, 2) = NamedRng.RefersToRange.Cells(1, 2)
R = R + 1
Next NamedRng

'Ranges sorteren in de lijst
R = R - 1
Set ListRng = LijstWks.Range("A2").Resize(R - 1, 2)
ListRng.Sort Key1:=ListRng.Cells(1, 2), Order1:=xlAscending

'Ranges kopiëren naar SortWks
R = 1
For I = 1 To ListRng.Rows.Count
Set Rng = ActiveWorkbook.Names(ListRng.Cells(I, 1).Text).RefersToRange
Rng.Copy
SortWks.Cells(R, 1).PasteSpecial Paste:=xlPasteAll
R = R + Rng.Rows.Count
Next I

'Opdrachten naar detail kopiëren
R = 1
Worksheets("SortWks").Range("A1:T499").Copy
Worksheets("detail").Range("A5:T504")

Next intCounter
End Sub

This works fine.

But when I use it in combination with the toggle buttons it is too slow.

For the toggle buttons I use the following code:

Sub Tegels()

Dim nm As Name

For Each nm In Application.Names
Range(nm).EntireRow.Hidden = True
Next nm

If TglOpel Then
For Each nm In Application.Names
If Application.CountIf(Range(nm), "*" & "Opel" & "*") Then
Range(nm).EntireRow.Hidden = False
Next nm
End If

If TglChevrolet Then
For Each nm In Application.Names
If Application.CountIf(Range(nm), "*" & "Chevrolet" & "*") Then
Range(nm).EntireRow.Hidden = False
Next nm
End If

If TglFord Then
For Each nm In Application.Names
If Application.CountIf(Range(nm), "*" & "Ford" & "*") Then
Range(nm).EntireRow.Hidden = False
Next nm
End If

If TglBuick Then
For Each nm In Application.Names
If Application.CountIf(Range(nm), "*" & "Buick" & "*") Then
Range(nm).EntireRow.Hidden = False
Next nm
End If

If TglDodge Then
For Each nm In Application.Names
If Application.CountIf(Range(nm), "*" & "Dodge" & "*") Then
Range(nm).EntireRow.Hidden = False
Next nm
End If

End Sub

Sub CheckTegels()

If TglOpel Then
Call Tegels
Exit Sub
Else
If TglChevrolet Then
Call Tegels
Exit Sub
Else
    If TglFord Then
    Call Tegels
    Exit Sub
    Else
        If TglBuick Then
        Call Tegels
        Exit Sub
        Else
            If TglDodge Then
            Call Tegels
            Exit Sub
            Else

                        Dim nm As Name

For Each nm In Application.Names
Range(nm).EntireRow.Hidden = False
Next nm

End If
End If
End If
End If
End If
End If
End If
End If
End Sub

Do you have any tips for speeding this process up?

As you can probably tell I am quite new to this. Any help would be greatly appreciated!


texts:
I am somewhat new to ruby (but not to programming) and I want to develop a small web-app with Sinatra. I started creating a small password utility script that hashes and secures entered password. I am not sure it is finished. I would like to know if there are any ruby tricks to make my code better or more verbose, and what else needs to be done / changed to make passwords more secure. Any criticism is appreciated. here is my code:

require 'digest'

def random_salt
    hash = ''
    for i in 1..64
        rand_seed = rand(0..61)
        hash << 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'[rand_seed]
    end
    return hash
end

# password format: salt + password + length_of_salt_and_hash
def hash_password(password)
    salt = random_salt
    hashed_pass = Digest::SHA512.hexdigest password.chomp
    length = salt.length + hashed_pass.length

    return salt + hashed_pass + length.to_s
end

# just a test
print 'Enter a password: '
word = gets
new_word = hash_password word
puts new_word


texts:
As a simple programming exercise, I wrote a piece of Node.JS code which generates random poems. It is based on a list of articles (kind of), nouns, linking verbs, and adjectives. It then combines them into lines, and eventually stanzas.

var articles = "The,All of the,Most of the,Some of the,My,Your,His,Her,Their,Our,Everybody's,Almost all of the,That,I knew that the,We knew that the,She knew that the,He knew that the,They knew that the".split(",");
var nouns = "darkness,morning,light,feeling,beauty,love,hatred,expression,message,happiness,sadness,anger,frustration".split(",");
var lv = "was,had been.will be,could be,might be,should have been,would have been,could have been".split(",");
var adjectives = "abstract,mysterious,permanent,unfortunate,intricate,confusing,true,false,fake,a lie,a stranger,a friend,serene,confusing,an enemy,terrible,enchanting,mine,yours,his,hers,theirs,ours,fortunate,understood,mine,interesting,mutual,artistic,musical".split(",");
var x;

var ta = articles[Math.floor(Math.random() * articles.length)];
var tb = nouns[Math.floor(Math.random() * nouns.length)];
var final = ta + " " + tb + "\nby Julian Lachniet\n------------------\n"

for (x = 0; x < 16; x++) {
  var a = articles[Math.floor(Math.random() * articles.length)];
  var b = nouns[Math.floor(Math.random() * nouns.length)];
  var c = lv[Math.floor(Math.random() * lv.length)];
  var d = adjectives[Math.floor(Math.random() * adjectives.length)];
  final += a + " " + b + " " + c + " " + d + ".\n";
  if (x % 4 == 3) {
    final += "\n";
  }
}

cr = new Date
final += "(c) " + cr.getFullYear();

console.log(final);

The poems are really quite silly, but any individual line out of context might seem normal.

He knew that the darkness
by Julian Lachniet
------------------
They knew that the darkness was mutual.
All of the sadness would have been serene.
Most of the feeling could have been artistic.
We knew that the sadness was intricate.

We knew that the feeling could be mine.
Your light had been.will be a lie.
They knew that the beauty would have been understood.
Their love would have been intricate.

They knew that the happiness should have been mine.
His frustration should have been mysterious.
Some of the darkness should have been musical.
That message might be unfortunate.

Your light might be enchanting.
Everybody's hatred should have been enchanting.
His expression could be interesting.
Their hatred would have been mine.

(c) 2017

I have several issues with my code already, which I don't really know how to change:

What is a better way to name the "dictionary" arrays (articles, nouns, lv, adjectives)?
Is there a more effective way to represent arrays than CSVs? I decided against using a standard array due to how much space it takes up.

Any tips/pointers would be appreciated.


texts: Haskell function to generate prime numbers up to argument

texts:
I made a function to generate a list of prime numbers using list comprehensions. Here it is:

let primes n = [x, x <- [2..n], length [y, y <- [2..x-1], mod x y == 0] == 0]

Is this a good approach? I am sure that there are much better ways of approaching this.


texts:
I wrote a solution in Java to solve the problem here. I use BigInteger to convert first from base 16 to base 10, then base 10 to base 64.

This seems quite inefficient to me, and I would have no idea how to do this if I couldn't use BigInteger.  I'm sure there's a nice and clever way to do this using a lot more bit manipulation.

import java.math.BigInteger;

public class Base64{

    //according to RFC 4648 and RFC 2045
    public final static char[] base64alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".toCharArray();
    public final static char base64pad = '='; //unused

    public static void main(String[] args){

        String test = "49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d";
        System.out.println( base16to64( test ) );
    }

    /**Return the base 64 value of an input base 16 string.
     */
    public static String base16to64(String hex){
        BigInteger value = base16to10(hex); //base 10 value

        // --- convert base 10 to 64 ---
        int digits = 1; // # digits in base 64 we'll need
        while( value.compareTo(new BigInteger("64").pow(digits)) != -1 ){ //while the decimal value >= 64^i
            digits++;
        }

        String ret = "";
        for(int i = digits - 1; i >= 0; i--){ //start at most significant digit

            //this digit must be an A (represents 0)
            if( value.subtract(new BigInteger("64").pow(i)).compareTo(BigInteger.ZERO) == -1){
                ret += "A";
            }
            else{
                for(int d = 63; d >= 1; d--){
                    //digit found: [ value - (64^i)*d >= 0 ]  with d the greatest possible
                    if( value.subtract(new BigInteger("64").pow(i).multiply(
                            new BigInteger(Integer.toString(d)))).compareTo(BigInteger.ZERO) != -1){
                        value = value.subtract(new BigInteger("64").pow(i).multiply( new BigInteger(Integer.toString(d))));
                        ret += base64alphabet[d];
                        break;
                    }
                }
            }//end else
        }

        return ret;
    }//end base16to64()

    /**Return the BigInteger decimal value of an input hexadecimal string.
     */
    public static BigInteger base16to10(String hex){
        hex = hex.toLowerCase();

        //hex is 0-9 then a-f
        BigInteger value = BigInteger.ZERO; //base 10 value
        for(int i = 0; i < hex.length(); i++){ //moving from most significant digit towards 16^0

            int digit = (int) hex.charAt(i);
            //if the hex digit is 0-9
            if( '0' <= hex.charAt(i) && hex.charAt(i) <= '9')
                digit = digit - '0';
            //else the hex digit is a-f
            else
                digit = digit - 'a' + 10;

            BigInteger temp = new BigInteger("" + digit); // digit as BigInt
            temp = temp.multiply( new BigInteger("16").pow( hex.length() - 1 - i) ); // digit * 16^index
            value = value.add(temp);
        }

        return value;
    }//end base16to10()
}


texts: Do I need to use a callback function here, or is there another way?

texts:
Here is the pertinent code:

index.html

<!--  DOM INITIALIZATION -->
<script type="text/javascript">
$().ready(function() {

getThemeInfo();

if (themeSelect==2) {
   ReplaceJSCSSFile("css/skin1.css", "css/skin2.css", "css");   // overwrite CSS
}

AJAX_LoadResponseIntoElement("skinContainer", "skin" + themeSelect + ".txt", function() {
    AJAX_LoadResponseIntoElement("contentdiv", "index.txt", initPage);
    });

});
</script>

funcs.js

function initPage()
{
    setContentDimensions();
    replaceCSSMenu();
    showContainer();
    setContentPositions();
}

function setContentPositions()
{
    var contentTop = findTop(document.getElementById('NavMenu')) + 4;
    var contentLeft = findLeft(document.getElementById('kwick1')) + 226;

    document.getElementById('contentdiv').style.top = (contentTop)+ "px";
}

Quick recap: It fetches the theme selection, and if it's not the default (1), then it changes the CSS file to skin2.css.  Then, it fetches the page with AJAX and initializes it, and part of initialization is setting the div dimensions and positions.

Although the theme swap works perfectly through the button (code not shown here,) it does not work in Opera if the theme setting, stored in cookies, is a non-default theme, causing the CSS to be swapped during the loading of the page (i.e. this code here.)  For whatever reason, the .top and .left of my "contentdiv," which is set in ContentPositions() function, is wrong.

I'd assumed this was happening because the CSS styles were not loaded prior to the JavaScript attempting to set contentdiv's position.  To test this theory, I put an alert() in setContentPositions() to test that contentTop & contentTop were indeed wrong (they were,) and then another alert() after the DOM init line that changes the CSS file.  With the addition of the alert() after the CSS change within DOM init, it loads perfectly.

Why is the CSS file not processed by the time it does two AJAX fetches?  Is a callback function the proper way to fix this?

Edit...

The code for some of the functions used in the above code was requested.  Here it is:

function ReplaceJSCSSFile(oldfilename, newfilename, filetype){
 var targetelement=(filetype=="js")? "script" : (filetype=="css")? "link" : "none";
 var targetattr=(filetype=="js")? "src" : (filetype=="css")? "href" : "none";
 var allElements=document.getElementsByTagName(targetelement);

 for (var i=allElements.length; i>=0; i--){
  if (allElements[i] && allElements[i].getAttribute(targetattr)!=null && allElements[i].getAttribute(targetattr).indexOf(oldfilename)!=-1){
   var newelement=CreateJSCSSFile(newfilename, filetype);
   allElements[i].parentNode.replaceChild(newelement, allElements[i]);
  }
 }
}

function CreateJSCSSFile(filename, filetype){
 if (filetype=="js"){
  var fileref=document.createElement('script');
  fileref.setAttribute("type","text/javascript");
  fileref.setAttribute("src", filename);
 }
 else if (filetype=="css"){
  var fileref=document.createElement("link");
  fileref.setAttribute("rel", "stylesheet");
  fileref.setAttribute("type", "text/css");
  fileref.setAttribute("href", filename);
 }
 return fileref;
}

function AJAX_LoadResponseIntoElement (elementId, fetchFileName, cfunc) {
  var XMLHRObj;
  if (window.XMLHttpRequest) { XMLHRObj=new XMLHttpRequest(); }
    else { XMLHRObj=new ActiveXObject("Microsoft.XMLHTTP"); }

  XMLHRObj.onreadystatechange=function()
    {
    if (XMLHRObj.readyState==4 && XMLHRObj.status==200)
      {
      document.getElementById(elementId).innerHTML=XMLHRObj.responseText;
      cfunc();
      }
    }
  XMLHRObj.open("GET",fetchFileName,true);
  XMLHRObj.send();
}


texts:
The problem is that I have executed the program for the last hour and it hasn't returned a value till now for input 1022. How can I make the program a bit faster? How can I increase the efficiency of program? Is there a faster algorithm?

I have Intel Core2 Duo (2.93GHz).

#include <stdio.h>
int main() {
    unsigned long long n;
    double m;
    double sum=0;
    scanf("%llu", &n);
    while (n>0) {
        m=1.0/n;
        sum+=m;
        n--;
    }
    printf("%lf",sum);
    return(0);
}


texts:
I tried to implement the shell-sort algorithm using this Java code:

// Using Pratt sequence
public static void hSort(int tab[]) {
    int N = tab.length;
    int k = 0;
    int sequence = 1;

    // Getting the final term of the pratt sequence
    while(((int)(Math.pow(3, k) - 1) / 2) < N/3) {
        sequence = (int)(Math.pow(3, k) - 1) / 2;
        k++;
    }
    k--;

    while(sequence > 0) {
        hInsertionSort(tab, sequence);
        k--;
        sequence = (int)(Math.pow(3, k) - 1) / 2;
    }
}

// H sorting using insertion sort
public static void hInsertionSort(int[] tab, int h) {
    int N = tab.length;
    int k = 0;
    while (k < h) {
        for (int i = k; i < N; i+=h) {
            for (int j = i; j > k+h-1; j-=h) {
                if (less(tab[j], tab[j-h]) == -1) exch(tab, j, j-h);
                else break;
            }
        }
    k++;
    }
}

You can use the hsort method to try sort a table of integers.

Is the complexity of this implementation the same as the usual implementation?


texts:
Looking to confirm that I am doing this in the most efficient way.

func convrtisbn10(isbn: String) {
    var checkSum: Int = 0
    var completeISBN = ""
    let newISBN = "978" + "\(isbn)"
    let result = String(newISBN.characters.dropLast(1))
    var oddSum = 0, evenSum = 0
    let reversedArray = result.characters

    for (i, s) in reversedArray.enumerate() {

        let digit = Int(String(s))!

        if i % 2 == 0 {
            evenSum += digit
        } else {
            oddSum += digit * 3
        }
    }
    let total = evenSum + oddSum
    let remander = total % 10
    if (10 - remander) == 10 {
        checkSum = 0
    } else {
        checkSum = 10 - remander
        completeISBN = result + "\(checkSum)"
    }
    getBookInfo(completeISBN)

}


texts:
I've done a function that does the following :

It takes an argument length that it will be the length of the result array.
The Array should start with alphabet values first : ['A', 'B', 'C', ...]
If the length of the Array is greater than 26 (The number of letters) it should look like :  ['A', 'B', 'C', ..., 'A1', 'B1', 'C1'], if greater than 52 : ['A', 'B', 'C', ..., 'A1', 'B1', 'C1', ..., 'A2', 'B2', 'C2'] and so on.

The following function i've done uses some new Array features :

let getNums = length =>{

  if(length <= 26) return Array.from({length}, (el, i)=> String.fromCharCode(i + 65));

  let nums = Math.floor( length / 26 );
      nums = nums == 0 ? 0 : nums - 1;
  let rest = length - (26 * (nums + 1) );

  return [...Array.from({length : 26}, (el, i)=> String.fromCharCode(i + 65)),
          ...Array.from({length : nums}, (el, i)=> i + 1)
            .reduce( (a, b)=> a.concat(Array.from({length : 26},
                     (el, i)=> String.fromCharCode( i + 65 ) + b ) ),
            []),
         ...Array.from({length : rest}, (el, i)=> String.fromCharCode(i + 65) + (nums + 1) )
 ];

}

console.log(getNums(53));

This works, but I'm worried about the efficiency of this function because several Arrays are created and concatenated. So, this would be better if done with loops and some if...else statements?


texts: Parameter list too long in initialize method

texts:
I have an initialize method for a class that looks like this:

def initialize(
  site:,
  name:,
  date_online: '-',
  date_offline: '-',
  date_modified: '-',
  date_tagged: '-',
  tags: []
)
  @site          = site
  @name          = name
  @date_online   = date_online
  @date_offline  = date_offline
  @date_modified = date_modified
  @date_tagged   = date_tagged
  @tags          = tags
end

However, RuboCop is telling me that I should:

Metrics/ParameterLists: Avoid parameter lists longer than 5 parameters. [7/5]

So, what is the best way to rectify this? It's an initializer, so all those parameters are necessary. Is the desired solution to use a hash?

def initialize(args)
  @site          = args[:site]
  @name          = args[:name]
  @date_online   = args[:date_online]   || '-'
  @date_offline  = args[:date_offline]  || '-'
  @date_modified = args[:date_modified] || '-'
  @date_tagged   = args[:date_tagged]   || '-'
  @tags          = args[:tags]          || []
end

Then how should I manually handle the fact that site and name are required? I could add some code after the assignments that will throw an error if the required fields aren't present:

raise ArgumentError unless @site && @name

That makes sense to me. But I assume the makers of RuboCop know what they're talking about, which leads me to suspect that there's a standard for this sort of thing.


texts:
I need to HTML table output like:

    ITEM
    ITEM
    ITEM

    ITEM
    ITEM
    ITEM

    ITEM
    ITEM
    ITEM

My code before:

<?php $i = 1;?>
<?php foreach ($items as $item): ?>
<?php if ($i == 1 || $i == 4 || $i == 7 ......): ?>

<?php endif; ?>
     CONTENT
<?php if ($i == 3 || $i == 6 || $i == 9 ......):?>

<?php endif;?>
<?php $i++ ?>
<?php endforeach; ?>

My code now:

<?php $i = 1;?>
<?php foreach ($items as $item): ?>
<?php if ($i % 3 == 1): ?>

<?php endif; ?>
     CONTENT
<?php if ($i % 3 == 0):?>

<?php endif;?>
<?php $i++ ?>
<?php endforeach; ?>


texts: Checking the presence of certain variables in a dataframe

texts:
I'm writing an Exploratory Data Analysis using R Markdown. First of all, I need to check the "sanity" of the input data set. Among the other check I perform, I need to check if at least one between the variables var_in and var_out are present in the dataset. If at least one is present, the other one can be computed from the first one. Thus, I want to check which of them is missing, and store its name in a character vector. If both are missing, the analysis is impossible and I need to exit, preferably throwing a meaningful error.

I cannot include the actual dataset on which the check is performed, because it's \$10^6\$ rows with confidential data, so I need to use fake data. The code, however, is as similar to the real code as possible.

# fake data
n <- 10^6
input_df <- data.frame(wind_speed = 10*abs(rnorm(n)), wind_direction = runif(n, 0, 2*pi),
                       var_in = NA, var_out = 3)

# nearly real code
missing_variables <- character(0)

var_in_is_missing <- all(is.na(input_df$var_in))
var_out_is_missing <- all(is.na(input_df$var_out))

if (var_in_is_missing & var_out_is_missing) {
  stop("both var_in and var_out are completely missing, so I cannot continue the EDA")
}
if (var_in_is_missing) {
  missing_variables <- c("var_in", missing_variables)
}
if (var_out_is_missing) {
  missing_variables <- c("var_out", missing_variables)
}

Note that according to the principle of early return, I put the stopping test before the other two. The code runs, but it doesn't seem that readable to me:

I test both var_in_is_missing and var_out_is_missing twice: this is definitely not going to impact notably the performance of my code, but it still feels useless
is it really necessary to use three separate if statements? Isn't there a way to do it in R in a more...compact way, without sacrificing readability?


texts: Plot daily time spent on codereview.stackexchange.com

texts:
This draws an xyplot from csv data obtained from RescueTime API for activity time for "http://codereview.stackexchange.com".

# -------------------------------------------------------
# PLOT TIME SPENT ON CODEREVIEW SE
# USING RESCUE TIME API AND R
# -------------------------------------------------------

# -------------------------------------------------------
# LIBRARIES
if(!require("RCurl")){
  install.packages("RCurl")
}
if(!require("lattice")){
  install.packages("lattice")
}
require("RCurl")
require("lattice")
# -------------------------------------------------------

print("Initializing...")

# -------------------------------------------------------
# RESCUE TIME API ACCESS

# api key
# get from https://www.rescuetime.com/anapi/manage
api_key <- "..."

# query from date
from_date <- "2014-01-01"

# query to date
to_date <- format(Sys.Date(), "%Y-%m-%d")

# activity to get details of
activity <- "codereview.stackexchange.com"

# --api description--
# for more details see https://www.rescuetime.com/anapi/setup/documentation
# key - API key
# format - Output format
# rb - Restrict Start Date ("%Y-%m-%d")
# re - Restrict End Date ("%Y-%m-%d")
# rk - Restrict Kind (in this case it's activity)
# pv - Perspective (in this case it's interval)
# rs - Resolution Time (if it is day it's a daily report)
# rt - Restrict Thingy (Restrict Kind of Type)
url_format  <- "https://www.rescuetime.com/anapi/data?key=%s&format=csv&rb=%s&re=%s&rk=activity&pv=interval&rs=day&rt=%s"

# create url
api_url  <- sprintf(url_format,api_key,from_date,to_date,activity)
# -------------------------------------------------------

# -------------------------------------------------------
# PLOT

# get csv as a text
csv_text_data <- textConnection(getURL(api_url))

# parse csv
activity_data <- read.csv(csv_text_data,header = TRUE)

print(sprintf("Mean Time Spent on '%s':%f (seconds)",activity,mean(activity_data$Time)))

activity_time_spent <- activity_data$Time
activity_dates <- activity_data$Date

# create an index for dates
activity_date_index  <- 1:length(activity_dates)

# plot
print(xyplot(activity_time_spent ~ activity_date_index, type="b", xlab = "Date Index", ylab = "Time (seconds)" ))
# -------------------------------------------------------

# -------------------------------------------------------
# CLEAN UP
detach("package:RCurl", unload = TRUE)
detach("package:lattice", unload = TRUE)
rm(list = ls())
# -------------------------------------------------------

Does this follow R conventions?

Execute by loading it to R console using source("./codereview.R")

Download

CSV and R file

Output

Loading required package: RCurl
Loading required package: bitops
Loading required package: lattice
[1] "Initializing..."
[1] "Mean Time Spent on 'codereview.stackexchange.com':2764.559322 (seconds)"


texts:
I have this code that duplicates a byte array 5 times.

class Multiple {
    public static void main(String[] args) {
        byte[] result = new byte[] {0x41,0x42,0x43,0x44};
        int len = result.length;
        byte[] multipled = new byte[len*5];
        for (int i = 0; i < 5; i++) {
            for (int j = 0; j < len; j++) {
                multipled[i*len + j] = result[j];
            }
        }
        System.out.println(new String(multipled));
        System.out.println(new String(result));
    }
}

Example:

ABCDABCDABCDABCDABCD
ABCD

The code uses multiple loops and assignment, can it be better or shorter?


texts:
Below is my implementation of dynamic array without help of library functions. Kindly provide your suggestions on design, coding style and algorithm.

MyDynamicArray.java

import java.util.NoSuchElementException;

public class MyDynamicArray<T>
{
    private int positionPointer=0;
    private int arraySize;
    private T[] dynamicArray;
    private static final int DEFAULT_ARRAY_SIZE=10;

    public MyDynamicArray()
    {
        this(DEFAULT_ARRAY_SIZE);
    }

    public MyDynamicArray(int arraySize)
    {
        this.arraySize=arraySize;
        dynamicArray=(T[]) new Object[arraySize];
    }

    public void addElement(T element)
    {
        adjustSize();
        dynamicArray[positionPointer]=element;
        positionPointer++;
    }

    public void addElementAtNode(int index, T element)
    {
        if(index<positionPointer)
        {
            dynamicArray[index]=element;
        }
        else
        {
            addElement(element);
            throw new ArrayIndexOutOfBoundsException("index "+index+" is greater than the size of array "+(positionPointer-1)+" \nElement added to end of array..");
        }
    }

    private void adjustSize()
    {
        if(positionPointer==arraySize)
        {
            increaseSize();
        }
        else if(positionPointer==(arraySize/4-1))
        {
            decreaseSize();
        }
    }

    private void increaseSize()
    {
        T[] tempArray=(T[]) new Object[2*arraySize];
        for(int i=0;i<positionPointer;i++)
        {
            tempArray[i]=dynamicArray[i];
        }
        dynamicArray=tempArray;
        arraySize=2*arraySize;
    }

    private void decreaseSize()
    {
        T[] tempArray=(T[]) new Object[(arraySize/4)];
        for(int i=0;i<positionPointer;i++)
        {
            tempArray[i]=dynamicArray[i];
        }
        dynamicArray=tempArray;
        arraySize=arraySize/4;
    }

    public int searchElement(T element)
    {
        for(int i=0;i<positionPointer;i++)
        {
            if(dynamicArray[i].equals(element))
            {
                return i;
            }
        }
        throw new NoSuchElementException("Element not found : "+element.toString());
    }

    public T getElementAtIndex(int index)
    {
        if(index<positionPointer)
        {
            return dynamicArray[index];
        }
        else
        {
            throw new ArrayIndexOutOfBoundsException("index "+index+" is greater than the size of array "+positionPointer);
        }
    }

    public void removeElement(T element)
    {
        int index=searchElement(element);
        if(index>0)
        {
            removeElementAtIndex(index);
        }
    }

    public void removeElementAtIndex(int index)
    {
        if(index<positionPointer)
        {
            for(int i=index;i<positionPointer-1;i++)
            {
                dynamicArray[index]=dynamicArray[index+1];
            }
            dynamicArray[positionPointer-1]=null;
            positionPointer--;
            adjustSize();
        }
        else
        {
            throw new ArrayIndexOutOfBoundsException("index "+index+" is greater than the size of array "+positionPointer);
        }
    }

    public int size()
    {
        return positionPointer;
    }

}


texts:
I'm developing a Python script which looks up over a huge-prelexicographically sorted list of different words (such as 33.000) and the goal is to remove those words which have less than two letter differences between them.

An example input may be:

ball
bill
bull
cow
hot
hoth
shot
zcow

And the example output is:

ball
cow
hot

The code which is currently working is:

def twoLetterDifferential2(selectedWords):
    i=0
    while i < len(selectedWords):
        j = i + 1
        if i < len(selectedWords):
           while j < len(selectedWords):
            if fuzzy_compare(selectedWords[i], selectedWords[j]) < 2:
                    selectedWords.remove(selectedWords[j])
            j=j+1
        i=i+1
return selectedWords

I don't care the output to be optimal (I'm not looking for the best combination that would result the biggest word output). I'm looking for the fastest way to produce the desired result.

The word comparison algorithm is taken from Jack's answer here. And its code is:

def compare(string1, string2, no_match_c=' ', match_c='|'):
    if len(string2) < len(string1):
        string1, string2 = string2, string1
    result = ''
    n_diff = 0
    for c1, c2 in itertools.izip(string1, string2):
        if c1 == c2:
            result += match_c
        else:
            result += no_match_c
            n_diff += 1
    delta = len(string2) - len(string1)
    result += delta * no_match_c
    n_diff += delta
    return result, n_diff

def fuzzy_compare(string1, string2):
    (fwd_result, fwd_diff) = compare(string1, string2)
    (rev_result, rev_diff) = compare(string1[::-1], string2[::-1])
    diff = min(fwd_diff, rev_diff)
    return diff

Please note that the words of the input word list are already sorted lexicographically and there is only one copy of each word.


texts:
I am working on an Android unit converter application, but I came to the point where I have to assign the formulas to the calculation method. At the moment I am using a switch-case statement, as it is more neat than an if-else, but still this proves to be very, very lengthy.

The way the application works is the user selects type of unit to convert, e.g. length. Then 2 spinners show up, one for the "From" unit and one for the "To" unit. On calculation the code picks up what is chosen in the spinners and determines the right formula to use.

Here is a code snippet for only one unit conversion:

switch (unitFrom) {
    case "Kilometers": switch (unitTo){
        case "Miles": initialValue = (initialValue / 1.6);
            break;
        case "Metres": initialValue *= 1000;
            break;
        case "Centimetres": initialValue *= 100000;
            break;
        case "Millimetres": initialValue *= 1000000;
            break;
        case "Feet": initialValue *= 3280.8399;
            break;
        case "Yards": initialValue *= 1093.6133;
            break;
        case "Inches": initialValue *= 39370.0787;
            break;
        case "Nautical Miles": initialValue *= 0.539956803;
            break;
        case "Fathoms": initialValue *= 546.806649;
            break;
        case "Light Years": initialValue *= (1.05702341*(10^-13));
            break;
    }
}

This will become so, so long after just few units being written down, so I was wondering if there's a better way of doing things. I am open to all sort of changes.


texts: Replace anchor tags with spans, and place the href attribute into the span

texts:
I'm required to perform a slight conversion on a string which contains html.

The conversion should transform a elements such that they become span elements. The conversion should also place the href attribute from the original a element into the span.

I have what I think is a working solution, but the code feels overcomplicated. I had hoped this may be possible with relatively little code, so I was wondering if anyone could suggest ways to make this code neater.

Browser compatibility is not an issue, as this will be transpiled by babel.

Here's what I have:

const testHtml = `

This is a test paragraph

  Google is here
  Msn is here

This is a heading

`

const splitByLinkEnds = html => {
  const split = html.split('')
  const allButLast = split.slice(0, -1)
  const last = split.slice(-1)[0]

  return [
    ...allButLast.map(x => `${x}</a>`),
    last
  ]
}

const splitByLinks = html => {
  const split = html.split(' `<a${x}`)
  ]

  return withReaddedOpeningTags
    .reduce((prev, curr) => [
      ...prev,
      curr.indexOf(' -1 ?
        splitByLinkEnds(curr) : curr
    ], []).flat()
}

const transformLinkToTextOnly = linkHtml => {
  const linkHref = linkHtml
    .match('href="[^"]*"')[0]
    .replace('href="', '')
    .replace('"', '')

  const htmlWithSpan = linkHtml
    .replace('<a', '<span')
    .replace('', '')

  return `${htmlWithSpan} (${linkHref})</span>`
}

const transformLinksToTextOnly = html =>
  splitByLinks(html)
    .map(x => x.indexOf(' - 1 ?
      transformLinkToTextOnly(x) : x
    ).join('')

const result = transformLinksToTextOnly(testHtml)

document.body.innerHTML += testHtml
document.body.innerHTML += '
'
document.body.innerHTML += result

Edit
I should note that the solution ought to work in node, ideally. I appreciate that the fact I include dom manipulation in the question is quite misleading, I included this more to attempt to create an easy working example that to demonstrate how the code might actually be used.

A further note, the performance of this code is not particularly important. It's only for relatively small amounts of html and gets run once when the application loads.


texts:
All of the class here share these same property

Country, Total and Date.

Total property are integer in some classes and decimal in some classed.

The extension method below has a lot of duplication. i have tried to refactor it using interface but i can't find a way to refactor it at the last step on selection since it need different class

    public static class TotalApprovedPOAmountStatisticExtension
{
    public static void MergeNullAndEmplyCountry(this IEnumerable<TotalApprovedPOAmountStatistic> totalUserStatistic)
    {
        foreach (var item in totalUserStatistic)
        {
            if (string.IsNullOrWhiteSpace(item.Country))
            {
                item.Country = "";
            }
        }

        totalUserStatistic = totalUserStatistic
                            .GroupBy(item => new { item.Country, item.Date })
                            .Select(groupedUser => new TotalApprovedPOAmountStatistic()
                            { Country = groupedUser.Key.Country, Total = groupedUser.Sum(item => item.Total), Date = groupedUser.Key.Date }).ToList();

    }
}

    public static class TotalPOStatisticListExtension
{
    public static void MergeNullAndEmplyCountry(this IEnumerable<TotalPOStatistic> totalUserStatistic)
    {
        foreach (var item in totalUserStatistic)
        {
            if (string.IsNullOrWhiteSpace(item.Country))
            {
                item.Country = "";
            }
        }

        totalUserStatistic = totalUserStatistic
                            .GroupBy(item => new { item.Country, item.Date })
                            .Select(groupedUser => new TotalPOStatistic() { Country = groupedUser.Key.Country, Total = groupedUser.Sum(item => item.Total), Date = groupedUser.Key.Date }).ToList();

    }
}

    public static class TotalProjectAmountStatisticListExtension
{
    public static void MergeNullAndEmplyCountry(this IEnumerable<TotalProjectAmountStatistic> totalUserStatistic)
    {
        foreach (var item in totalUserStatistic)
        {
            if (string.IsNullOrWhiteSpace(item.Country))
            {
                item.Country = "";
            }
        }

        totalUserStatistic = totalUserStatistic
                            .GroupBy(item => new { item.Country, item.Date })
                            .Select(groupedUser => new TotalProjectAmountStatistic() { Country = groupedUser.Key.Country, Total = groupedUser.Sum(item => item.Total), Date = groupedUser.Key.Date }).ToList();

    }
}

    public static class TotalProjectStatisticListExtension
{
    public static void MergeNullAndEmplyCountry(this IEnumerable<TotalProjectStatistic> totalUserStatistic)
    {
        foreach (var item in totalUserStatistic)
        {
            if (string.IsNullOrWhiteSpace(item.Country))
            {
                item.Country = "";
            }
        }

        totalUserStatistic = totalUserStatistic
                            .GroupBy(item => new { item.Country, item.Date })
                            .Select(groupedUser => new TotalProjectStatistic() { Country = groupedUser.Key.Country, Total = groupedUser.Sum(item => item.Total), Date = groupedUser.Key.Date }).ToList();

    }
}

    public static class TotalUserStatisticListExtension
{
    public static void MergeNullAndEmplyCountry(this IEnumerable<TotalUserStatistic> totalUserStatistic)
    {
        foreach (var item in totalUserStatistic)
        {
            if (string.IsNullOrWhiteSpace(item.Country))
            {
                item.Country = "";
            }
        }

        totalUserStatistic = totalUserStatistic
                            .GroupBy(item => new { item.Country, item.Date })
                            .Select(groupedUser => new TotalUserStatistic() { Country = groupedUser.Key.Country, Total = groupedUser.Sum(item => item.Total), Date = groupedUser.Key.Date }).ToList();

    }
}


texts:
I'm sure there are better ways to code this.  I spent a lot of time re-working the code to get it as clean as possible.  I would appreciate any input on what I could change to have the program run more efficiently and look cleaner.

outer = False
while outer == False:
    room_list = []
    room = ["This place stinks, better get moving. Door to the N or E", 1, 8, None, None]
    room_list.append(room)
    room = ["You are in a safe room. There are doors to the N,E,S and W", 2, 9, 0, 4]
    room_list.append(room)
    room = ["This room is filled with garbage. There is a door to the S", None, None, 1, None]
    room_list.append(room)
    room = ["You encounter goblins and die!"]
    room_list.append(room)
    room = ["You encounter orcs and kill them all! There is a door to the N,E and S", 3, 1, 5, None]
    room_list.append(room)
    room = ["You encounter rats, easy fight. Theres a door to the N", 4, None, 7, None]
    room_list.append(room)
    room = ["You found a companion! Theres a door to the S", None, None, 9, None]
    room_list.append(room)
    room = ["You found the treasure! Congratulations!"]
    room_list.append(room)
    room = ["Ouch, you were hit by a fireball! There's a door to the W", None, None, None, 0]
    room_list.append(room)
    room = ["You found a treasure map! It says 'Rats dwell, south it lies'. Theres a door to the N and W",6,None,None,1]
    room_list.append(room)
    current_room = 0
    print (room_list[current_room][0])
    inner = False
    new_room = 0
    while inner == False:
        user_choice = input ("What would you like to do? ")
        print ()
        if user_choice in('north','n','North','N'):
            new_room = room_list[current_room][1]
        elif user_choice in('east','e','East','E'):
            new_room = room_list[current_room][2]
        elif user_choice in('south','s','South','S'):
            new_room = room_list[current_room][3]
        elif user_choice in('west','w','West','W'):
            new_room = room_list[current_room][4]
        else:
            print ("I don't know what", user_choice, "means")

        if new_room == None:
            print ("You can't go that way.")
        else:
            current_room = new_room
            print (room_list[new_room][0])

        if current_room == 3:
            play_again = input("Would you like to play again? ")
            if play_again in("y","Y","Yes","yes"):
                print()
                break
                    else:
                        outer = True
                        break
        if current_room == 7:
            outer = True
            break


texts: Returning data reference with mutex lock guard struct

texts:
I'm writing a multi-threaded program where some external part of the program needs access to a large piece of data that's controlled by my class. I'm trying to return a reference to this data in a thread-safe way.
class Chunk
{
public:

    Chunk(){
        chunkData = std::make_shared<vector<XMFLOAT3>>();
        chunkMutex = std::make_shared<std::mutex>();
    };

    struct LockedData
    {
        LockedData(std::vector<float> const& d, std::mutex& mtx) : data(d), lk(mtx) {};
        std::vector<XMFLOAT3> const& data;
    private:
        std::lock_guard<mutex>lk;
    };

    inline LockedData const&& RequestChunkData()const { return LockedData(*chunkData,chunkMutex); };

private:

    mutable std::shared_ptr<std::mutex> chunkMutex;
    std::shared_ptr<vector<float>> chunkData;

}

Is this over-complicated? will this actually protect my data, and am I using the rvalue references (&&) correctly?


texts: onChange vs onKeyPress for input in React

texts:
I have an input form, and when you press enter I want it to call a function. I was wondering what "the right" way of doing this is.

Right now I have an input looking like this:

<input
    type="text"
    placeholder="Enter key words"
    value={this.state.value}
    onChange={this.handleChange}
    onKeyPress={this.handleEnter}
/>

And two functions that look like this

handleChange(event) {
    this.setState({value: event.target.value});
}

handleEnter(event) {
    if (event.key === 'Enter') {
        this.setState({value: event.target.value},function(){
            this.props.theFunction(this.state.value);
        });
    }
}

Another solution was to point both onChange and onKeyPress to the same function and write it like

handleChangeAndEnter(event) {
    if (event.key === 'Enter') {
        this.setState({value: event.target.value},function(){
            this.props.theFunction(this.state.value);
        });
    } else {
        this.setState({value: event.target.value});
    }
}

If I remove the onChange-binding the input-field stops updating itself on input (not entirely sure why this is) and if I remove the onKeyPress-binding the event-object no longer has a key-property.

My current solution works, but it still feels like a hack.


texts:
I'm a junior who wants to refactor a big method in my code, which has been tested and works:

  def self.authorized_status plugin_id, store_id, application_id, version, locale=nil
    if plugin_id.match /^(\w|-)+$/
      I18n.locale = locale || :en # I think I can move it to a concern

      # for this I thought about an external method how return two values, or a hash. Any idea?
      found_by = :iid
      plugin = Plugin.find_by_iid(plugin_id)
      if !plugin
        plugin = Plugin.find_by_aid(plugin_id)
        found_by = :aid
      end

      application_id_and_version = { application_id: application_id, version: version, status: Application::PUBLISHED_STATUS }

      update_by_application_id = ApplicationUpdate.where(application_id: application_id).joins(application: :store).where(application: {store_id: store_id} )
      is_store = update_by_application_id.first.application.is_store? if !update_by_application_id.first.nil?

      # for the rest of the code I don't know what to do expect put validations into separate methods.
      if plugin.nil? || plugin.user.nil?
        { status: UNREGISTERED_PLUGIN, message: I18n.t('....') }
      elsif ApplicationUpdate.where(application_id_and_version).count == 0 && !is_store
        { status: UNKNOWN_APPLICATION, message: I18n.t('....') }
      else
        if !is_store
          groups = Group.joins(users: :plugins).where(users: {plugins: {found_by => plugin_id}})
          .joins(:application_updates)
          .where(application_updates: application_id_and_version)
        end

        if !is_store && groups.empty?
          { status: NOT_AUTHORIZED, message: I18n.t('....') }
        else
          store = Store.find store_id
          authorized = (!store.preauthorized?) || is_store || plugin.authorized_for_store?(store)
          if !authorized || BlacklistedPlugin.find_by_organisation_id_and_plugin_id(store.organisation_id, plugin.id)
            { status: NOT_AUTHORIZED, message: I18n.t('....') }
          else
            { status: AUTHORIZED, message: I18n.t('....') }
          end
        end
      end
    else
      { status: PLUGIN_ID_FORMAT_ERROR, message: I18n.t('....') }
    end
  end

I saw recently to get some help a talk from Andy Pike (slide) with some nice principle like OCP or SOLID. I don't think the way he refactors the code is something I should do but maybe I'm wrong. To be honest, the method sometimes looks so weird, especially with all the ifs, that I don't know where to start.


texts: Grid Overlay For Browser Using HTML5 Canvas

texts:
I wanted to create a grid overlay for my browser that I can use when building websites. I decided on HTML5 canvas because it allows me to create lots of lines without adding loads of elements to the DOM.

The code is below and you can demo it on GitHub pages here. I'd appreciate your guys feedback on the following areas:

How can I make the code more efficient/faster/lighter?
Do you think this grid is accurate, or will it be of any use?

These are the outstanding issues I currently want to address:

Need to add a max and min value (don't want grid squares of 1 pixel)
Need a "clear grid" button (still deciding the best way to implement it, does the "show grid" button change text when grid is visible?
Prevent non-numeric input

CODE:

window.onload = init;

function init() {

// grid controls
var controls = getById('gridControls');
controls.style.position = 'absolute';
controls.style.right = "30px";
controls.style.padding = "10px";
controls.style.backgroundColor = "#ffffff";
controls.style.borderLeft = "1px solid #aaa";
controls.style.borderRight = "1px solid #aaa";
controls.style.borderBottom = "1px solid #aaa";
controls.style.zIndex = '100001';

// get our canvas
var grid = getById('grid');
hide(grid);

// get the button to show grid
var button = getById('showGrid');
button.onclick = drawCanvas;
}

function drawCanvas() {

var horizontalSpace = 0;
var verticalSpace = 0;

// input for setting the grid squares
var input = getById('widthHeight');
var gridSize = parseInt(input.value);

show(grid);

var context = grid.getContext('2d');

// set the canvas style to positions absolute
// and set z-index high to keep it on top
grid.style.position = 'absolute';
grid.style.zIndex = '100000';

// get window width and height
var w = window.innerWidth;
var h = window.innerHeight;

// set the canvas width and height to be the window w/h
grid.width = w;
grid.height = h;

// create the horizontal lines
for(var horizontal = 0; horizontal < w; horizontal++) {
    context.beginPath();
    context.moveTo(0, horizontalSpace);
    context.lineTo(w, horizontalSpace);
    context.lineWidth = 1;
    context.strokeStyle = "lightblue";
    context.stroke();
    horizontalSpace += gridSize;
}

// create the vertical lines
for(var vertical = 0; vertical < h; vertical++) {
    context.beginPath();
    context.moveTo(verticalSpace, 0);
    context.lineTo(verticalSpace, h);
    context.lineWidth = 1;
    context.strokeStyle = "lightblue";
    context.stroke();
    verticalSpace += gridSize;
}

}

function hide(element) {
    element.style.display = 'none';
}

function show(element) {
    element.style.display = 'block';
}

function getById(id) {
    return document.getElementById(id);
}


texts: Optimize function that returns length of a subarray

texts:
I did an exercise today on where the task is to write a function that returns the length of the longest subarray where the difference between the smallest and biggest value in the subarray is no more than 1. I had a solution that works but it's too slow to pass the tests that have big arrays. What is it about my solution that makes it very slow with huge arrays?
def longestSubarray(arr):
    longest = 0
    arr_len = len(arr)
    for i in range(arr_len):
        for j in range(i, arr_len):
            sub = arr[i: j+1]
            if max(sub) - min(sub) > 1:
                continue
            length = len(sub)
            if length > longest:
                longest = length
    return longest


texts: Using RemoteChannels for an parallel iterable map

texts:
RemoteChannels hit with julia v0.5
There are no examples online, but I managed to get them to work.

They are still very new, and all this whole area of multithreading code continues to have running changes -- there was one just a few days ago.

"A kind of async parallel iterator map, that does not quiet  presever order."
immutable WorkFarmerIterator{T}
    func :: Function #Must take an tuple of const_data, and an element of source_iter and do work on them
    source_iter
    const_data::T
    channel_sizes::Int64
end

type WorkFarmerState
    pending::RemoteChannel
    complete::RemoteChannel
    job_submitter::Future
end

function Base.start(iter::WorkFarmerIterator)

    o_pending = RemoteChannel(()->Channel(iter.channel_sizes),myid())
    o_complete = RemoteChannel(()->Channel(iter.channel_sizes),myid())

    o_job_submitter = remotecall(myid(), o_pending, iter.source_iter) do pending, source_iter
        #Can prob do this without a remotecall
      for wk in source_iter
          put!(pending, wk)
      end
      true
    end

    # Fire off workers that Read Pending (until closed exception)
    # And write to complete
    @sync for pid in workers()
        @async remotecall(pid, iter.func, iter.const_data, o_pending,o_complete) do func, const_data, pending, complete
            try
                while(true)
                    wk = take!(pending) #Block til work arrives
                    res = func(const_data, wk)
                    put!(complete, res) #Block til I can hand work over
                end
            catch ee
                #Break out of loop when a stream is closed and we try to read pending`
                #Or in the case of a unfortunte timing error we try to write to complete
                if !(ee|>typeof ==InvalidStateException && ee.state == :closed)
                    rethrow()
                end
                #otherwise eat the InvalidStateException
            end
        end
    end

    #Register Finalizer
    state=WorkFarmerState(o_pending,o_complete, o_job_submitter)
    function finalize_state(st::WorkFarmerState)
        close(st.pending)
        close(st.complete)
    end
    finalizer(state, finalize_state)
    state
end

function Base.done(iter::WorkFarmerIterator, state::WorkFarmerState)
    #Check that job_submitter is done
    isdone= (isready(state.job_submitter) #Finish submitting
            &&  !isready(state.complete) #and complete work closed or empty
            &&  !isready(state.pending)  #and pending empty
            )
    #We can't actually check if the RemoteChannel is closed.
    if isdone
        finalize(state) #Done not hurt to finalize it twice
    end
    isdone
end

function Base.next(iter::WorkFarmerIterator, state::WorkFarmerState)
    #Read complete -- this is a blocking operation so if nothing is ready we'll sit here til it is.
    #All of the sending (by job_submitter) basically has to happen here since this is the only garenteed time the local process will yield
    res = take!(state.complete)
    (res,state)
end

Base.iteratorsize(iter::WorkFarmerIterator) = Base.iteratorsize(iter.source_iter)

Base.length(iter::WorkFarmerIterator) = Base.length(iter.source_iter)

Example of use:

@everywhere function wkfun(data,ele)
       sleep(0.5*rand())
       (data*ele, myid())
end

witer  = WorkFarmerIterator(wkfun,1:1000, 1, 1024)

open("temp.txt","w") do
    t0=time()
    for ii in witer
        println(fp,ii,"\t", time()-t0)
    end
end

Potential Issues:

Right now I see a few issues:

I am not sure if it is a good idea to infinite loop in a WorkerProcess while reading a Channel vs firing off new tasks continually (either with remote_call, or via pgenerator etc.)
I don't see anyway to profile it at all. Not even a good way of logging how full the Channels are. (Maybe a log call in Base.next?)
The exact requirements for iter.func to be serialize/available are poorly known by me, and the code (nor the comments) do thus not make it clear to the user what the requirements on iter.func are.


texts:
This is a follow up to my previous post as it contained a lot of errors and wasn't accurate.
I am using the Bubble sort algorithm to sort an array of integers and I would like to know whether I could optimize it in any way.
#include<iostream>

void printarr(int *arr,const int siz){
    for(int i = 0;i < siz;i++) std::cout << arr[i] << " ";
    std::cout << "\n";
}

int main(){
    const int siz = 6;
    int arr[siz] = {4,6,3,1,3,8};
    std::cout << "Before sort\n";
    printarr(arr,siz);
    for(int i = 0;i < siz;i++){
        for(int j = i+1;j < siz;j++){
            if(arr[i] > arr[j]){
                int temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
            }
        }
    }
    std::cout << "After sort\n";
    printarr(arr,siz);
}
```


texts:
For the "First they came" golfing challenge, I wrote the following:

(defn ftc []
  ; Loop over the lines numbers for reference
  (doseq [i (range 4)
          :let [; Added a dummy last "class" since "me-" wasn't necessary,
                ;  and only having 3 elements was causing OOB errors.
                classes ["Socialist" "Trade Unionist" "Jew" ""]

                ; A helper function that executes either its first or second argument
                ;  depending on if the current line is one of the first 3 lines.
                if-first-three-lines #(if (< i 3) % %2)]]

    ; An implicit space is inserted between each of the args to println
    (println
      ; Decide on the opener
      (if (= i 0) "First" "Then")

      "they came for"

      ; Start string concatenation because the implicit space
      ;  begins complicating things.
      (str
        ; Decide which "class" the line belongs to
        (if-first-three-lines
          (str "the " (classes i) "s, ")
          "me-")

        ; Decide on the line ending
        (if-first-three-lines
          "and I did not speak out-\n"
          "and there was no one left to speak for me.")

        ; Then pick the trailer
        (if-first-three-lines
          (str "Because I was not a " (classes i) ".\n")
          "")))))

I generally like how it turned out, but I have a problem with it: the redundancy of the use of the if-first-three-lines function. I've racked my brain to think of a way to simplify it, but haven't been able to figure out a way that doesn't add to the byte count. I call the same function 3 times in a row inside an argument list, just with different arguments. I thought of juxtaposing a application of the arguments, but it was still too long.

The code generally turned out well, but I'm open to any recommendations; whether related to golfing or not.

Keep in mind I minimized the code before submitting. I'm looking for language-specific related golfing tips.


texts: Preventing XSS attacks in a Spring MVC application controller

texts:
One of the URL in my application is vulnerable to XSS attack, so I am handling it in the below way.

I created a util class:

import java.util.regex.Pattern;

public class HtmlUtils {
    public final static String tagStart = "\\<\\w+((\\s+\\w+(\\s*\\=\\s*(?:\".*?\"|'.*?'|[^'\"\\>\\s]+))?)+\\s*|\\s*)\\>";

    public final static String tagEnd = "\\</\\w+\\>";

    public final static String tagSelfClosing = "\\<\\w+((\\s+\\w+(\\s*\\=\\s*(?:\".*?\"|'.*?'|[^'\"\\>\\s]+))?)+\\s*|\\s*)/\\>";

    public final static String htmlEntity = "&[a-zA-Z][a-zA-Z0-9]+;";

    public final static Pattern htmlPattern = Pattern.compile("(" + tagStart + ".*" + tagEnd + ")|(" + tagSelfClosing
            + ")|(" + htmlEntity + ")", Pattern.DOTALL);

    public static boolean isHtml(String s) {
        boolean ret = false;
        if (s != null) {
            ret = htmlPattern.matcher(s).find();
        }
        return ret;
    }
}

And in the controller, I am throwing an exception if the requested value has an HTML script:

def isValidRequest(request){
    def htmlRequest = false
    def params = request.getParameterNames();

    while(params.hasMoreElements()){
      String paramName = (String)params.nextElement();
      def value = request.getParameter(paramName);
       htmlRequest = HtmlUtils.isHtml(value);
         if(BooleanUtils.isTrue(htmlRequest))
          break;
      }

  if(BooleanUtils.isTrue(htmlRequest))
      throw new AccessDeniedException("Access Denied");
}

Does this look good or is there a better way to handle the XSS attack in the controller?