texts: Genetic algorithm fitness function for scheduling

texts:
For Job shop scheduling, I built a fitness function:

def makespan_timeCalculation(lot_size, RHS, setup_time, processing_time, sequence, mc_op):
    machine_assigne_time =[[0 for i in range(mc_op[k])] for k in range(len(mc_op))]
    max_c = [0 for i in range(len(lot_size))]  # Equal number of job
    completion_time = [0 for i in range(len(RHS))]

    # Check all indices of RHS (Step 2 + 3 + 6)
    for r in range(len(RHS)):
        procTime = run_time(r, lot_size, RHS, sequence, processing_time) + setup_time[RHS[r][2]]

        if lot_size[RHS[r][0]][RHS[r][1]] > 0:                                    # Lot size not zero (Step 4)
            if (machine_assigne_time[RHS[r][2]][RHS[r][3]] == 0 and RHS[r][2] == sequence[RHS[r][0]][0]):
                # Step 5.1: First assignment to machine m and operation equal first operation in sequence

                completion_time[r] = setup_time[RHS[r][2]] + procTime
                machine_assigne_time[RHS[r][2]][RHS[r][3]] +=1

            elif (machine_assigne_time[RHS[r][2]][RHS[r][3]] == 0 and RHS[r][2] != sequence[RHS[r][0]][0]):
                # Step 5.2: First assignment to machine m and operation over first operation in sequence

                curent_sequence_index = sequence[RHS[r][0]].index(RHS[r][2])                              # Calculate index sequence of current chromosome
                prev_sequence = sequence[RHS[r][0]][curent_sequence_index-1]                              # Return previous sequence operation of current chromosome
                prev_operation_comp_index = [i[0:3] for i in RHS].index([RHS[r][0], RHS[r][1], prev_sequence])      # Return previous chromosome of current job + sublot

                completion_time[r] = max(setup_time[RHS[r][2]], completion_time[prev_operation_comp_index]) + procTime
                machine_assigne_time[RHS[r][2]][RHS[r][3]] +=1
                #print(curent_sequence_index, RHS[r])
            elif (machine_assigne_time[RHS[r][2]][RHS[r][3]] > 0 and RHS[r][2] == sequence[RHS[r][0]][0]):
                # Step 5.3: First operation in sequence and machine m assignment > 1 (dung de xem xet khi co su khac nhau giua setup time ban dau, va setup time doi part)
                prev_op_mc_RHS_index = max([i for i, al in enumerate(RHS[:r]) if RHS[r][2:] == al[2:]])
                completion_time[r] = completion_time[prev_op_mc_RHS_index] + procTime
                machine_assigne_time[RHS[r][2]][RHS[r][3]] +=1

            elif (machine_assigne_time[RHS[r][2]][RHS[r][3]] > 0 and RHS[r][2] != sequence[RHS[r][0]][0]):
                # Step 5.4 Operation over first operation in sequence and machine m assignment > 1

                curent_sequence_index = sequence[RHS[r][0]].index(RHS[r][2])                              # Calculate index sequence of current chromosome
                prev_sequence = sequence[RHS[r][0]][curent_sequence_index-1]                              # Return previous sequence operation of current chromosome
                prev_operation_comp_index = [i[0:3] for i in RHS].index([RHS[r][0], RHS[r][1], prev_sequence])      # Return previous chromosome of current job + sublot
                prev_op_mc_RHS_index = max([i for i, al in enumerate(RHS[:r]) if RHS[r][2:] == al[2:]])
                completion_time[r] = max(completion_time[prev_operation_comp_index], completion_time[prev_op_mc_RHS_index]) + procTime
                machine_assigne_time[RHS[r][2]][RHS[r][3]] +=1

        max_c[RHS[r][0]] = max(max_c[RHS[r][0]], completion_time[r])

    return max(max_c)

The result is fine but speed is very slow. Could you help to have a look and advise on improvement?


texts:
In C# I wrote a method to move a folder into another existing folder:

public void MoveFolder(string folderToMove, string destination)
{
    String destinationFolder = Path.Combine(
        destination, Path.GetFileName(folderToMove));

    Directory.Move(folderToMove, destinationFolder);
}

Usage:

MoveFolder(@"D:\myfolder\mysubfolder", @"C:\");

It works, but I am sure there is a more readable and shorter way to do that? In particular, I feel bad using GetFileName.

No tricky things to worry about: The folders exist, and destination is not inside folderToMove nor the same.
It must work on .NET 4.0 without additional libraries.


texts:
What do you think about this core EF method ?

Also, Notice that it returns IQueryable:

Could that be a performance danger when extended improperly ? How ?

Please accept the fact that Includes and OrderBy parameters are string type.

public IQueryable<TEntity> GetEntitySetMultipleTables(Expression<Func<TEntity, bool>> WhereExpression = null,
                                                string OrderBy = null,
                                                int TotalResults = int.MaxValue, int SkippedResults = 0, string[] Includes = null)
    {
        if (OrderBy != null)
        {
            string orderbyProperty = OrderBy;
            if (OrderBy.IndexOf(' ') > -1) // Direction
            {
                orderbyProperty = OrderBy.Substring(0, OrderBy.IndexOf(' '));
            }

            if (typeof(TEntity).GetProperty(orderbyProperty) == null)
                OrderBy = null;
        }
        if ((SkippedResults > 0) && (OrderBy == null))
        {
            OrderBy = GetPrimaryKeyName();
        }

        //Base EntitySet
        IQueryable<TEntity> results;
        ObjectQuery<TEntity> objectSetResults = Context.CreateObjectSet<TEntity>();
        if (Includes == null)
            results = objectSetResults.AsQueryable();
        else
        {
            foreach (var include in Includes)
            {
                objectSetResults = objectSetResults.Include(include.Trim());
            }
            results = objectSetResults.AsQueryable();
        }

        //Filter by Where Expression
        if (WhereExpression != null)
            results = results.Where(WhereExpression);

        //Order Results
        if (OrderBy != null)
        {
            results = results.OrderBy(OrderBy);
        }

        //Skip Records
        if (SkippedResults > 0)
            results = results.Skip(SkippedResults);

        //Take Specific Amount of records
        if (TotalResults != int.MaxValue)
            results = results.Take(TotalResults);

        //Run the LINQ Query and return the results
        return results;
    }

Thanks in advance.


texts: User-defined function to split a 1D array into 2D array

texts:
The purpose of the UDF is to receive a 1D array and split it into a 2D array. The size of the new array should be dynamic.

Function SPLITARR(ByRef v() As Variant, MaxRow As Integer) As Variant
  Dim ArraySize As Integer
  Dim MaxCols As Integer
  Dim NewArray() As Variant
  Dim x As Integer, y As Integer, z As Integer

  ArraySize = (UBound(v(), 1) - LBound(v(), 1)) + 1
  MaxCols = ArraySize \ MaxRow

  If ArraySize Mod MaxRow > 0 Then MaxCols = MaxCols + 1
  ReDim NewArray(LBound(v(), 1) To MaxRow, 1 To MaxCols)
  For x = LBound(v(), 1) To UBound(v(), 1)
    y = x Mod MaxRow
    If y = 0 Then y = MaxRow
    z = x \ MaxRow
    If x Mod MaxRow = 0 Then z = z - 1
    NewArray(y, z + 1) = v(x, 1)
  Next
  SPLITARR = NewArray()
End Function

and should be called like;

Sub caller()
Dim a() As Variant
a() = Range("A4:A23")
a() = SPLITARR(a(), 5)
ActiveCell.Resize(UBound(a(), 1), UBound(a(), 2)).Value = a()
End Sub

Let range "A4:A23" have a value of (1,2,3,..20)
and this call will return

1,6,11,16
2,7,12,17
3,8,13,18
4,9,14,19
5,10,15,20


texts: Create 'worst case test' data for compression test

texts:
I am going to prepare some test data for a compression test.  One of the them is the 'worst case test', which should make the compressor work worst.  Use random number to generate such a file is an idea, but there still contain some kind of patterns in the data.  Using 7zip to compress such a file, I get a output file which is a little bit smaller than input file.

So I make a small piece of code to generate a file, which does not contain any repeated two bytes.  To make life difficult, I shuffle those byte pairs in special order, hope the compressor will have more difficulty to find any match, even with predication.

#include <iostream>
#include <fstream>

int main(int argc, char* argv[])
{
    const char* filename = "c:\\_Test\\hard.dat";

    std::ofstream ofs(filename, std::ios::binary | std::ios::out);
    if (ofs.bad())
    {
        std::cerr << "fail to open file\n";
        return -1;
    }

    for (unsigned int i = 0; i < 0x10000; ++i)
    {
        unsigned int t = (i * 0xc369) & 0xFFFF;
        ofs.write((char*)&t, 2);
    }
    std::cout << "job done\n";

    return 0;
}

It's running in windows, and I think it's easy to change filename to make it work on other system, or even use command line argument as filename, but that's not the point.

I tried use 7zip to compress it, both format (7z and zip) created file bigger than original file.  I have some other compressors, will test them later.

Any suggestions and help are appreciated.


texts:
I am pretty new to TDD and is following problems on spoj.pl for practice. I need help with following code; it was my first attempt.

Problem: Your program is to use the brute-force approach in order to find the Answer to Life, the Universe, and Everything. More precisely... rewrite small numbers from input to output. Stop processing input after reading in the number 42. All numbers at input are integers of one or two digits. Mentioned here.

Tests:

describe "life universe and everything" do

 before(:each) do
  @life = Life.new
 end

 it "should accept input" do
  @life.stub(:gets) { "5, 4, 23, 42,  4" }
  @life.input.should == [5,4,23,42,4]
 end

 it "check number validity" do
   @life.valid?(23).should be_true
   @life.valid?(42).should be_false
 end

 it "process input" do
   array1 = [5,4,23,42,4]
   @life.process_input(array1).should == [5,4,23]
   array2 = [1,4,76,34,90]
 @life.process_input(array2).should == [1,4,76,34,90]
end

end

Code:

class Life

 def input
  puts "List comma(',') seperated numbers. Press enter when done."
  numbers_string = gets
  numbers = numbers_string.split(',')
  numbers.map {|n| n.strip.to_i}
 end

 def valid?(number)
  (number==42) ? false : true
 end

 def process_input(numbers)
  processed_numbers = []
  numbers.each do |number|
  break unless valid?(number)
  processed_numbers << number
 end
  processed_numbers
end

end

I would like it to be reviewed and would be glad to know my mistakes and what can I do to improve quality of code. Thanks!


texts:
I have a STI table and want to be able to render a collection using

render @collection

with every elements of the collection using their own partial or, if they don't have one, the parent partial. You know, partial inheritance.

So I added to my parent model :

def to_partial_path
  self.class._to_partial_path
end

protected

# a little hack to get partial inheritance in views, check if the partial exist, if not
# return the parent's one. Provide class level cache, be sure to restart your app when
# adding/removing partials.
def self._to_partial_path
  @_to_partial_path ||= begin
    element = ActiveSupport::Inflector.underscore(ActiveSupport::Inflector.demodulize(self))
    collection = ActiveSupport::Inflector.tableize(self)
    if File.exists?(Rails.root.join('app', 'views', collection, "_#{element}.html.erb")) ||
    self.superclass == ActiveRecord::Base

      "#{collection}/#{element}"
    else
      self.superclass._to_partial_path
    end
  end
end

The original code is here.

This seems to work great so far but I want to have some opinions.

Should I have gone another way?

Are there any "gotchas" I might encounter doing it this way?

Any way to refactor this?

edit: No problem whatsoever, it's working great for now. I'm looking for a way to achieve something similar with form (ie render form in new and edit views render the child _form partial if their is one, the parent one otherwise).


texts: Finding the longest common substring between two tweets

texts:
I retrieved 200 tweets using the Jersey API. I want to find two tweets which have the longest common substring.

tweetList is an ArrayList of Tweet objects. The comapreTweets method compares tweet objects for longest substring.

Tweet t1=new Tweet();Tweet t2=new Tweet();
int longestString=0;

for(int i=0;i<tweetList.size();i++)
{int store=0;Tweet comparer=null;
    for(int j=i+1;j<tweetList.size();j++)
    {
        if(j!=i){
        int result=tweetList.get(i).compareTweets(tweetList.get(j));
        if(result>store){
            store=result;
            comparer=tweetList.get(j);
        }}
    }
    if(longestString<store)
    {
        longestString=store;
        t1=tweetList.get(i); t2=comparer;
    }
}

If I retrieve 200 tweets then this will loop approx. 40000 times. I require a more efficient way.


texts: Anti-pattern or acceptable way of using Promises?

texts:
Whenever I need to use a Promise interface in my NodeJs code and I don't have a promise to start off with, I do this:

var someResultPromise = Q.resolve()
    .then(function () {
        var something = 'value';

        var anotherPromise = callFunctionThatReturnsPromise(something)
            .then(function (result) {
                return processing(result);
            });

        return anotherPromise;
    });

Is this a good way to do it? If no, why not?


texts: Bash arrays and case statements - review my script

texts:
#!/bin/bash
# Change the environment in which you are currently working.
# Actually, it calls the relevant 'lettus.sh' script

if [ "${BASH_SOURCE[0]}" == "$0" ]; then
    echo "Try running this as \". chenv $1\""
    exit 0
fi

usage(){
    echo "Usage: . ${PROG}        -- Shows a list of user-selectable environments."
    echo "       . ${PROG} [env]  -- Select environment."
    echo "       . ${PROG} -h     -- Shows this usage screen."
    return
}

showEnv(){
    # check if index0 exists, assume we have at least the first (zeroth) element
    #if [ -z "${envList}" ]; then
    if [ -z "${envList[0]}" ]; then
        echo "array \$envList is empty! " >&2
        return 1
    fi

    # Show all elements in array (0 -> n-1)
    for i in $(seq 0 $((${#envList[@]} - 1))); do
        echo ${envList[$i]}
    done
    return
}
setEnv(){
    if [ -z "$1" ]; then
        usage; return
    fi

    case $1 in
        cold)       FILE_TO_SOURCE=/u2/tip/conf/ctrl/lettus_cold.sh;;
        coles)      FILE_TO_SOURCE=/u2/tip/conf/ctrl/lettus_coles.sh;;
        fc)         FILE_TO_SOURCE=/u2/tip/conf/ctrl/lettus_fc.sh;;
        fcrm)       FILE_TO_SOURCE=/u2/tip/conf/ctrl/lettus_fcrm.sh;;
        stable)     FILE_TO_SOURCE=/u2/tip/conf/ctrl/lettus_stable.sh;;
        tip)        FILE_TO_SOURCE=/u2/tip/conf/ctrl/lettus_tip.sh;;
        uat)        FILE_TO_SOURCE=/u2/tip/conf/ctrl/lettus_uat.sh;;
        wellmdc)    FILE_TO_SOURCE=/u2/tip/conf/ctrl/lettus_wellmdc.sh;;
        *)          usage; return;;
    esac

    if $IS_SOURCED; then
        echo "Environment \"$1\" selected."
        echo "Now sourcing file \"$FILE_TO_SOURCE\"..."
        . ${FILE_TO_SOURCE}
        return
    else
        return 1
    fi
}

main(){
    if [ -z "$1" ]; then
        showEnv; return
    fi

    case $1 in
        -h) usage;;
         *) setEnv $1;;
    esac
    return
}

PROG="chenv"

# create array of user-selectable environments
envList=( cold coles fc fcrm stable tip uat wellmdc )

main "$@"
return

If I could, I'd like to get some feedback on a better way to accomplish any of the following:

run through the case statement
make script trivally simple to maintain/upgrade/update


texts:
In the near future, the app will have to start several actions after having read the content of the file (executing request based on the request module). I was wondering if this beginning makes sense, or if it should be written differently (it's my first app, so any advice is welcomed).

var EventEmitter = require('events').EventEmitter
var jeu = new EventEmitter()
jeu.on('readFile', function(msg) {
  var lineReader = require('readline').createInterface({
    input: require('fs').createReadStream(msg)
  })

  lineReader.on('line', function (line) {
    jeu.emit('outputLines', line)
  })
})

jeu.on('outputLines', function(line) {
  console.log(line);
})

jeu.emit('readFile', 'liste.txt')


texts:
Problem:

  Write an algorithm, to find the union and intersection sorted in ascending order, between the elements of two arrays

  Input Format

  The first line contains an integer, n1 , denoting the size of the first array.

  The second line contains n1 space-separated integers representing elements of the first array.

  The third line contains an integer, n2 , denoting the size of the second array.

  The fourth line contains n2 space-separated integers representing elements of the second array.

  Constraints

  Apart from Array, no other data structure can be used
      Output elements should be sorted in ascending order
      Array should be sorted using Bubble Sort

  Output Format

  First line, union of space-separated elements of both array elements, sorted in ascending order

  Second line, intersection of space-separated elements of both arrays elements, sorted in ascending order

Solution:

"""
   1) Sort two arrays
   2) Find union and intersecton of two sorted arrays
"""
def swap(array, indexI, indexJ):
    temp = array[indexI]
    array[indexI] = array[indexJ]
    array[indexJ] = temp

def bubbleSort(array):
    n = len(array)
    for indexI in range(n):
        exchanges = 0
        for indexJ in range(n-1, indexI, -1):
            if array[indexJ] < array[indexJ-1]:
                swap(array, indexJ, indexJ-1)
                exchanges += 1
        if exchanges == 0:
            break
def intersection(arrayOne, arrayTwo):
    arrayOneIndex = 0
    arrayTwoIndex =0
    sizeOfArrayOne = len(arrayOne)
    sizeOfArrayTwo = len(arrayTwo)
    array = []
    while arrayOneIndex < sizeOfArrayOne and arrayTwoIndex < sizeOfArrayTwo:
        if arrayOne[arrayOneIndex] < arrayTwo[arrayTwoIndex]:
            arrayOneIndex += 1
        elif arrayOne[arrayOneIndex] > arrayTwo[arrayTwoIndex]:
            arrayTwoIndex += 1
        else:
            array.append(arrayOne[arrayOneIndex])
            arrayOneIndex += 1
            arrayTwoIndex += 1
    return array

def union(arrayOne, arrayTwo):
    arrayOneIndex = 0
    arrayTwoIndex =0
    sizeOfArrayOne = len(arrayOne)
    sizeOfArrayTwo = len(arrayTwo)
    array = []
    while arrayOneIndex < sizeOfArrayOne and arrayTwoIndex < sizeOfArrayTwo:
        if arrayOne[arrayOneIndex] < arrayTwo[arrayTwoIndex]:
            array.append(arrayOne[arrayOneIndex])
            arrayOneIndex += 1
        elif arrayOne[arrayOneIndex] > arrayTwo[arrayTwoIndex]:
            array.append(arrayTwo[arrayTwoIndex])
            arrayTwoIndex += 1
        else:
            array.append(arrayOne[arrayOneIndex])
            arrayOneIndex += 1
            arrayTwoIndex += 1
    if arrayOneIndex == sizeOfArrayOne:
        while arrayTwoIndex < sizeOfArrayTwo:
            array.append(arrayTwo[arrayTwoIndex])
            arrayTwoIndex += 1
    else:
        while arrayOneIndex < sizeOfArrayOne:
            array.append(arrayOne[arrayOneIndex])
            arrayOneIndex += 1
    return array

if __name__ == '__main__':
    sizeOne = int(input())
    try:
        arrayOne = [int(x) for x in input().split()]
    except:
        print('Invalid input')
        sys.exit()
    sizeTwo = int(input())
    try:
        arrayTwo = [int(x) for x in input().split()]
    except:
        print('Invalid syntax')
        sys.exit()
    bubbleSort(arrayOne)
    bubbleSort(arrayTwo)
    intersectionArray = intersection(arrayOne, arrayTwo)
    unionArray = union(arrayOne, arrayTwo)
    print(*unionArray, sep=" ")
    print(*intersectionArray, sep=" ")

Correctness

Input

3
4 5 7
5
6 9 5 7 1

Output

1 4 5 6 7 9
5 7

Input

6
1 1 8 9 0 5
4
0 7 3 4

Output

0 1 3 4 5 7 8 9
0

Question:

0) How to avoid such syntax? while arrayOneIndex < sizeOfArrayOne and arrayTwoIndex < sizeOfArrayTwo

1) Does the code require better error handling?

2) Can this code get more pythonic?


texts: SafeBox StateMachine implemented with Enums

texts:
does someone has any opinions about this SafeBox StateMachine?

import java.util.Scanner;

public class SafeBoxStateMachine {

    public enum SafeBox {

        ACCEPT{
            private Scanner scan;
            private boolean askPassword(SafeBoxStateMachine safebox){

                System.out.println("Please type a password:");
                scan = new Scanner(System.in);
                String buffer = scan.nextLine();

                if (buffer.equals(safebox.password) == false){
                    ++safebox.counter;
                    return false;
                }
                else {
                    return true;
                }
            }
            public void process(SafeBoxStateMachine safebox){

                boolean res = askPassword(safebox);

                if (res == false)
                    System.out.println("try number:" + safebox.counter);

                if (safebox.counter == 3){

                    safebox.state = SafeBox.PENELTY;
                }

                if (res == true)
                {
                    safebox.state = SafeBox.SUCCESS;
                }
            }
        },
        PENELTY{
            public void process(SafeBoxStateMachine safebox){
                System.out.println("7 seconds penalty!");
                try{
                    Thread.sleep(7000);
                }
                catch(InterruptedException ex) {
                    Thread.currentThread().interrupt();
                }
                safebox.counter = 0;
                safebox.state = SafeBox.ACCEPT;
            }
        },
        SUCCESS{
            public void process(SafeBoxStateMachine safebox){

                System.out.println("Success!");
                safebox.stop = true;
            }

        };

        abstract public void process(SafeBoxStateMachine safebox);
    }

    int counter = 0;
    private SafeBox state = SafeBox.ACCEPT;
    String password;
    boolean stop = false;

    SafeBoxStateMachine (String password){
        this.password = password;
        counter = 0;
    }

    public void run(){
        while (stop == false)
            this.state.process(this);
    }

    public void setPass(String pass){
        this.password = pass;
    }

    public static void main(String[] args) {

        SafeBoxStateMachine pass = new SafeBoxStateMachine("hello");

        pass.run();

    }

}


texts: Implementing Function that Maps over Stream

texts:
I implemented the following function:

the ruler function
0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 4, . . .
where the nth element in the stream (assuming the first element
corresponds to n = 1) is the largest power of 2 which evenly
divides n

I'm giving it a vague name in the event that students try to cheat and search for it.
foo :: Stream Integer
foo = streamMap f startAtOne
    where f x        = if (odd x) then 0 else g x 0
          g y acc    = if y == 0 then acc else g (y-2) (acc+1)
          startAtOne = streamFromSeed 1 (+1)

Here's the streamFromSeed function and the Stream data type.
data Stream a = Stream (a, Stream a)
streamMap :: (a -> b) -> Stream a -> Stream b
streamMap f (Stream (x, rest)) = Stream (f x, streamMap f rest)

-- Given a start value and function, generate a stream by applying fn to each Stream value
streamFromSeed :: a -> (a -> a) -> Stream a
streamFromSeed x f = Stream $ (x, streamFromSeed (f x) f)

Note that this technically is homework, but from 2013. I'm working on this material since Prof. Yorgey provides excellent lectures and homework assignments. I'm not in this class nor a student at the school.


texts:
I'm new to Scala, and would appreciate any notes about a better approach, correctness, or style.

/**
 * Call proc(f) for each file in the directory tree rooted at dir.
 *
 * proc will not be called for directories, just for files.
 */
def traverse(dir: File, proc: File => Unit): Unit = {
    dir.listFiles foreach { (f) => {
            if(f.isDirectory) {
                traverse(f, proc)
            } else {
                proc(f)
            }
        }
    }
}


texts:
I've been working on my first Angular JS app for the past few days.
It's in a very early stage (no real functionality), but that will only make it easier to review what IS there.

The client side is written in CoffeeScript.  The app used Requirejs to manage files AMD style (it loads compiled CoffeeScript).

The server side is very minimal at the moment.  It will have a local SQLite database and uses SQLAlchemy as an ORM.  Furthermore I make use of the (very nice) Flask framework to provide an restful API to the Angular app.

Right now the server side is not much concern to me; it works.

The client side works as well, but since I'm new to Angular I am really curious to know whether I do things correctly and using the Angular JS way.

The code lives in this repository.

The parts I'm not so sure about are the way I am dealing with scopes right now.

For example:

I have a general dialog directive and use it to display a dialog for importing images. I would think I could have the import directive live inside the dialog (transcluded), but to be able to handle the dialog apply "event" (handle by uploading the images in this particular instance...), the import directive needs to wrap the dialog. It works, but was rather counterintuitive. Is it the right way to do things?

Another example:

To display the dialog I have its visibile attribute linked to a root scope property. This also seems rather hacky.

    {# let angularjs compile the templating from here #}
    {% raw %}

Sight beta

            <button ng-click="show_import_dialog = ! show_import_dialog">Import</button>

                    Drag images into the dropzone below or click on it to browse.

                    <input type="file" accept="image/*" multiple />

    {% endraw %}

The directives and controllers live here.


texts:
Just to reiterate my prev. post, as I think it helps structure my weaknesses.

Coding methodology:  Is the algorithm I used feasible or mostly correct? If not, how do I correct it and why won't it work or scale? I realize in some cases there are always going to be optimal solutions that will be over my head mathematically, but generally you can yield a solution that is within a reasonable range of optimal that is passable without knowing a ton of number theory in my experience. Where possible, I hope to learn algorithms along the way (such as the Sieve of Eratosthenes for prime ranges).
Coding execution: Given some pseudocode that we determine algorithmically will work, is the code written executed without redundancies and minimizing runtime?
Being more pythonic: Is something I'm not doing pythonic or can it be done simpler with some sort of library I don't know about? I believe this is mostly semantic, though in some cases can have large effects on performance (for instance, using map() instead of a for loop to apply int()).

I submitted the following code as a solution to Project Euler's #12. It's extremely slow, running in mean 7.13 seconds over 100 trials (I think; just using other submitted solutions as a benchmark. It seems as though solutions <1 seconds are generally decent.)

def factors(n):
    return set(reduce(list.__add__,
                ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0)))

def triangle_number(n):
    for i in range(n):
        n += i
    return n

n = 1
while True:
    if len(factors(triangle_number(n))) >= 500:
        print n, triangle_number(n)
        break
    else:
        n +=1

The code for the factors function was borrowed from here.


texts:
I created a function to do that, and I want to know if there is a problem I'm overlooking about it ..

void replaceStr(buffer, haystack, needle, rep)
    char *buffer, *needle, *rep;
    const char *haystack;
{
    if (!buffer || !haystack || !needle || !rep)
        return;

    size_t rep_length = strlen(rep);
    long long diff = strlen(needle) - rep_length;
    memcpy(buffer, haystack, strlen(haystack) + 1);

    while ((buffer = strstr(buffer, needle))) {
        memcpy(buffer, rep, rep_length + 1); /* +1 for the null byte */
        if (diff > 0) {
            long long i;
            for (i = diff; i <= diff; ++i)
                buffer[i] = buffer[i+1];
            buffer[i] = 0;
        }
    }
}


texts: Count contiguous sub-array whose sum is a perfect square

texts:
I have to count the number of contiguous sub-arrays whose sum is a perfect square.

For instance, if we have an array:

number = [1,4,2,3,5]

Now the contiguous sub-arrays whose elements sum is a perfect square are:

[1] [4] [4,2,3]

Total count = 3

To solve this problem I took an array which stores the prefix sum and then I run two loops to get the answer:

int array[] = new int[n + 1];
int prefixSum[] = new int[n + 1];
int count = 0;
for (int index = 1; index <= n; index++) {
    array[index] = in.nextInt();
    prefixSum[index] = (prefixSum[index-1]+array[index]);
    count +=isPerfectSquare(prefixSum[index])?1:0;
}
for (int prev = 1; prev <= n; prev++) {
    for (int index = prev+1; index <= n; index++) {
        count += isPerfectSquare(prefixSum[index]-prefixSum[prev]) ? 1 : 0;
    }
}
System.out.println("count = " + count);

How can I improve this in terms of complexity?


texts: Parsing input in form of 'CMD NUM NUM' (num could be special char '%')

texts:
In the main() function of the following code, I wrote a very naive command parsing. Is there any more efficient way?

This program is aim to deal with ADD, SUB, MUL, DIV these four arithmetic operations for integers. The input would be in form like: ADD 1 1, MUL 12 90. And also there would be a special input character % which means use the last result. For example, ADD 1 1 would return 2, then ADD % 1 would return 3.

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

typedef int (*calc_function)(int, int);

typedef struct operation {
        char *name;
        calc_function calculate;

} Operation;

int add(int a, int b) { return a+b; }
int sub(int a, int b) { return a-b; }
int mul(int a, int b) { return a*b; }
int divi(int a, int b) { return a/b; }

int calc(int a, int b, int (*c)(int, int)) {
        return c(a, b);
}

int main() {

        char *command = malloc(9);
        int result = 0;
        int a;
        int b;

        Operation ADD = {"ADD", add};
        Operation SUB = {"SUB", sub};
        Operation MUL = {"MUL", mul};
        Operation DIV = {"DIV", divi};

        Operation ops[4] = {ADD, SUB, MUL, DIV};

        while((command = fgets(command, 9, stdin)) != NULL) {

                for(int i = 0; i < 4; ++i) {
                        if (0 == strncmp(ops[i].name, command, 3)) {
                                command = strchr(command, ' ');
                                command++;
                                if (*command == '%') {
                                        a = result;
                                } else {
                                        sscanf(command, "%d", &a);
                                }
                                command = strchr(command, ' ');
                                command++;
                                if (*command == '%') {
                                        b = result;
                                } else {
                                        sscanf(command, "%d", &b);
                                }
                                result = ops[i].calculate(a, b);
                                printf("%d\n", result);
                        }
                }
        }
        free(command);

        return 0;
}

Also, any advice on improving the performence and style of this program would be highly appreciated!


texts: Allocating memory for a matrix with a single malloc

texts:
For an interview, I was asked to write code allocate memory for a rows*cols matrix, using a single malloc(). I want your comments about this code that I wrote:

/*
Allots (in effect) space for a matrix of size rows*cols using a single malloc.
The whole space allotted consists of an array of size 'rows' of float ptrs,
followed by a float array of size  'rows' * 'cols'.
The float ptrs 1,2..,  are assigned to row no. 1, 2,..  in the matrix that follows.
*/

float** allotMatrix(const size_t &rows, const size_t &cols)
{
    // Compute size of allotment = rows * cols floats + rows float ptrs
    size_t ptrsize = rows * sizeof(float*);
    size_t datasize = rows * cols * sizeof(float);
    size_t matsize =  ptrsize + datasize;

    // Get if possible a memory allotment  of this size. We use char* for convenience
    char* cmatrix = (char*) malloc(matsize);
    if (cmatrix == NULL)
    {
        fprintf(stderr, "Unable to allot memory");
        exit(1);
    }

    memset((void*) cmatrix, 0, matsize);

    // Assign ptrs to data
    float** ptrstart = (float**) cmatrix;
    float* datastart = (float*) (cmatrix + ptrsize);
    for (size_t i = 0; i != rows; ++i)
    {

        *ptrstart =  datastart;
        // Move to next ptr
        ++ptrstart;
        // .. and move to the next data row
        datastart += cols;
    }

    return (float**) cmatrix;
}


texts:
When I realized that the code below has a major problem in what it'll do (it'll just update the database with information currently in the database), I was told that there are a lot of mistakes.

Please point out the mistakes to me, suggest improvements and how to avoid the mistakes in the future.

public User Get(int UserID)
{
    string sql = "select * from users where userid = :id";

    List<MySqlParameter> args = new List<MySqlParameter>();
    args.Add(new MySqlParameter("id", UserID));

    MySqlCommand cmd = new MySqlCommand(sql, db.conn);
    cmd.Parameters.AddRange(args.ToArray());

    db.createConnection();
    MySqlDataReader dr = cmd.ExecuteReader();
    db.closeConnection();

    User user = new User();

    if (dr.HasRows)
    {
        dr.Read();

        user.EmailAddress = (string)dr["email"];
        user.Password = (string)dr["passcode"];
    }

    return user;
}

public void  Update(int UserID)
{
    User user = Get(UserID);

    string sql = "update users set email = :email, passcode = :pass where userid = :id";

    List<MySqlParameter> args = new List<MySqlParameter>();
    args.Add(new MySqlParameter(":email", user.EmailAddress));
    args.Add(new MySqlParameter(":pass", user.Password));
    args.Add(new MySqlParameter("id", UserID));

    MySqlCommand cmd = new MySqlCommand(sql, db.conn);
    cmd.Parameters.AddRange(args.ToArray());

    db.createConnection();
    cmd.ExecuteNonQuery();
    db.closeConnection();
}


texts: Python code for checking request headers

texts:
I am trying to validate a HTTP REST API request in my python code. It checks for some request headers (X-Foo and X-Bar) and two keys in the json body/payload (someKey and someNestedKey). I have written this code with if/else conditions as well as a simple try-catch.

headers = event["headers"]
if "X-Foo" not in headers or "X-Bar" not in headers:
    return {
        'statusCode': 401,
        'body': '{"message":"Some error message"}'
    }

# Do something with request headers here
payload = json.loads(event["body"])

if "someKey" not in payload:
    some_flag = False
else:
    if "someNestedKey" not in payload["someKey"]:
        some_flag = False
    else:
        some_flag = True

if not some_flag:
    return {
        'statusCode': 400,
        'body': '{"message":"Some other error message"}'
    }

# if we get this far, then its ok
foo_bar = payload["someKey"]["someNestedKey"]

vs

try:
    headers = event["headers"]
    # Do something with request headers here
    payload = json.loads(event["body"])
    foo_bar = payload["someKey"]["someNestedKey"]
except KeyError:
    return {
            'statusCode': 401,
            'body': '{"message":"Some error message"}'
        }

I'd like a review on all aspects of this code.


texts:
The question is to find the sum of Digit XOR till \$N\$.

For eg:-
Digit XOR of a number 112

  112 => 1 xor 1 xor 2 =  2

So we need to find

int digit_xor_sum=0
for(i=1;i<=N;i++){
  digit_xor_sum+= digit_xor(i);
}
return digit_xor_sum

My Solution Approach was as follows,

 int digit_xor(int n){
    if(n<=9){
        return n; // because there is only 1 digit
    }

    int digit_xor_sol=(n%10); // intialising digit_xor_sol with last digit
    n/=10; // removing the last digit

    while(n){
        digit_xor_sol = digit_xor_sol ^ (n%10);  // xor the current last digit and current xor solution
        n/=10;
    }

    return digit_xor_sol;
}

But this is \$O(nlogn)\$, which is time expensive.

Then I found a better solution like the below, which takes \$O(n)\$:

int digit_xor[1000];

int find_digit_xor(int n){
    if(n<=9)
        return digit_xor[n]=n;

    if(digit_xor[n]!=-1){ // there are multiple test-cases, so no need to recompute again
       return digit_xor[n];
    }
    return digit_xor[n] = digit_xor[n/10]^(n%10);
}

int main(){

 int sum;
 memset(digit_xor,-1,sizeof digit_xor);

 int testcase;
 scanf("%d",&testcase);

 while(testcase--){
     int n;
     scanf("%d",&n);

     sum=0;

     for(int i=0;i<=n;i++)
         sum+=find_digit_xor(i);

     printf("%d\n",sum);
 }
 return 0;
}

But this too is time expensive for larger \$N\$.

Is there any direct formula to calculate this SUM in \$O(1)\$.


texts: Idiomatic F# unit test using xunit and unquote

texts:
I'm writing some unit tests for testing C# code but I'm using F# and Unquote for the first time for the unit tests and would like some input as to how I might make the tests more 'f-sharpier' to take advantage of and learn more about the functional approach in F#. Here's an example of one of my tests - please make recommendations:

[<Fact>]
let ``Two courses, one with one time and one with two times that all differ, returns two unique schedules with two entries each``() =
    // arrange
    let course1 = getCourse1()
    let course2 = getCourse2()
    let time1 = getTime1()
    let time2 = getTime2()
    let time3 = getTime3()
    time1 |> course1.AddTime
    time2 |> course2.AddTime
    time3 |> course2.AddTime

    let courses = List<Course>()
    [|course1; course2 |] |> courses.AddRange

    let scheduleEntry1 = ScheduleEntry(course1, time1)
    let scheduleEntry2 = ScheduleEntry(course2, time2)
    let scheduleEntry3 = ScheduleEntry(course2, time3)

    // act
    let schedules = courses |> ScheduleGenerator.Schedulize

    // assert
    test <@ schedules.Count() = 2 @>

    let allSchedulesHave2Entries = schedules.All(fun schedule -> schedule.Count() = 2)
    test <@ allSchedulesHave2Entries @>

    let hasSchedule entries = schedules.Any(fun schedule -> schedule.ToArray() = entries)
    test <@ hasSchedule [| scheduleEntry1; scheduleEntry2 |] @>
    test <@ hasSchedule [| scheduleEntry1; scheduleEntry3 |] @>

ScheduleGenerator.Schedulize returns an IEnumerable<IEnumerable<ScheduleEntry>> which is the type of schedules. So the type of schedule is just IEnumerable<ScheduleEntry>.

What ScheduleGenerator.Schedulize does is take a set of courses IEnumerable<Course>, where each course contains all available times for the course, and computes the Cartesian product for all the times across all the courses and then filters out any schedule which contains conflicting times.


texts: Count how many times values has appeared in list so far

texts:
I have a list of non-unique values. I want to output a list of the same length where each value corresponds to how many times that value has appeared so far.

The code I have written to do this seems over-complicated, so I think there has to be a better way.

x = [1,1,2,3,1,3]

def times_so_far(ls):

    out = [0]*len(x)
    counted = {}
    for i,v in enumerate(x):
        if v in counted:
            counted[v] += 1
        else:
            counted[v] = 0

        out[i] = counted[v]
    return out

times_so_far(x)
#[0, 1, 0, 0, 2, 1]


texts: Returning the size of the largest clique in a graph

texts:
This function is to return the size of the largest clique in a graph. When I run this code, I am running out of space at runtime. Also, it is insanely slow, so any speed tips would be appreciated.

int cliqueSize(graph &g, std::vector<VertexID> nodes, std::vector<EdgeID> edges)
{
    std::vector<std::vector<VertexID> > previous_cliques;

    // start with all the singular nodes...
    for (unsigned i = 0; i < nodes.size(); i++)
    {
        std::vector<VertexID> tmp;
        tmp.push_back(nodes[i]);
        previous_cliques.push_back(tmp);
    }

    for (unsigned clique_size = 1; clique_size < nodes.size(); clique_size++)
    {
        std::vector<std::vector<VertexID> > new_cliques;
        // go through all the nodes to try to add to the clique.
        for (unsigned i = 0; i < nodes.size(); i++)
        {
            // try to add node i to clique j.
            for (unsigned j = 0; j < previous_cliques.size(); j++)
            {
                // make sure node j is not already in the clique.
                if (std::find(previous_cliques[j].begin(), previous_cliques[j].end(), nodes[i]) == previous_cliques[j].end())
                {
                    std::vector<VertexID> potential_clique(previous_cliques[j]);
                    potential_clique.push_back(nodes[i]);

                    // isClique has no issues, just checks if the given graph is a clique...
                    if (isClique(g, potential_clique, edges))
                    {
                        new_cliques.push_back(potential_clique);
                    }
                }
            }
        }
        // no new cliques?
        if (new_cliques.size() == 0) { return clique_size; }
        else { previous_cliques = new_cliques; }
    }
    return nodes.size();
}


texts:
I am trying to go through the problems on CodeChef and came across this problem:

  In Byteland they have a very strange monetary system. Each Bytelandian
  gold coin has an integer number written on it. A coin n can be
  exchanged in a bank into three coins: n/2, n/3 and n/4. But these
  numbers are all rounded down (the banks have to make a profit). You
  can also sell Bytelandian coins for American dollars. The exchange
  rate is 1:1. But you can not buy Bytelandian coins. You have one gold
  coin. What is the maximum amount of American dollars you can get for
  it?

I approached it using the following algorithm:

Check if the total amount on gold coin is greater than (Total/2)+(Total/3)+(Total/4), return total amount on gold coin.
Otherwise, recursively evaluate the maximum total amounts for (Total/2),(Total/3) and (Total/4) and return the sum total of these maximums.

My attempt:

public class ByteLandGold{

public static void main(String[] args){
        System.out.println("Printing the bytelandian equivalent for:");
        int byteLandCoin = Integer.parseInt(args[0]);
        System.out.println(ByteLandianConversion(byteLandCoin));
}

private static int ByteLandianConversion(int goldCoinAmount){
        int halfValue = (goldCoinAmount/2);
        int thirdValue = (goldCoinAmount/3);
        int fourthValue = (goldCoinAmount/4);

        int totalIntermediate = halfValue + thirdValue + fourthValue;
        if(goldCoinAmount > totalIntermediate)
                return goldCoinAmount;
        else{
                int maxHalfPortion = ByteLandianConversion(halfValue);
                int maxThirdPortion = ByteLandianConversion(thirdValue);
                int maxFourthPortion = ByteLandianConversion(fourthValue);
                return maxHalfPortion+maxThirdPortion+maxFourthPortion;
        }
}
}

One thing that I see in my code is that the recursive steps are calculating the overlapping sub-problems repeatedly. What would be one way to ensure that doesn't happen? Can somebody go through my code and give me some pointers on how to optimize it further and what can I change this snippet to solve it in a better way?


texts: 2D model simulating water breaking a floodbank

texts:
For a homework assignment we have to write a class that simulates water breaking a floodbank (very simplistic 2D simulation).

My implementation works fine but I found that there were many downcasts (in my opinion, a flaw in Greenfoot's API, which should be using generic functions rather than functions that take classes as arguments, but I'm not sure if this is possible in Java since this is the first time I'm writing Java code).

Sandstone and Sand both derive from Actor, which is from Greenfoot.

import greenfoot.*;

public class Water extends Actor {
    public Water() {
        getImage().scale(64, 64);
    }

    public void act() {
        if (((DoorbraakWorld)getWorld()).stopped) return;

        if (Math.random() < 0.9) return;

        int dx = 0, dy = 0;
        switch ((int)(3.0 * Math.random())) {
            case 0: dx = 0; dy = 1; break;
            case 1: dx = 1; dy = 0; break;
            case 2: dx = -1; dy = 0; break;
        }

        // The next line looks so incredibly ugly…
        Sandstone sandstone = (Sandstone)getOneObjectAtOffset(dx, dy, Sandstone.class);
        if (sandstone != null) {
            getWorld().removeObject(sandstone);
            getWorld().addObject(new Water(), getX() + dx, getY() + dy);
        }

        Sand sand = (Sand)getOneObjectAtOffset(0, 1, Sand.class);
        if (sand != null) {
            ((DoorbraakWorld)getWorld()).stopped = true;
            return;
        }
    }
}

Could I reduce the number of downcasts or is it normal for Java code to contain many downcasts? What else could I improve?


texts:
I got a question:
Design a parking system. There are 3 types of parking spaces: big, medium and small.
Implement ParkingSystem class(int big, int medium, int small). Constructor takes a number of places of types. So ParkingSystem(1,2,3) means there are 1 big place, 2 medium and 3 small.
Add method addCar(int carType) - carType takes one of three values [1,2,3] which represents big car, medium car and small car.
Method should check if there is a place for a car of such size or bigger, if yes then it parks the car in this place and returns true, else false.
For now there is no method to free parking space (when a car is leaving) but it can be added in future.
Example:

ParkingSystem ps = new ParkingSystem(1, 2, 3); // creates parking with 1 big place, 2 medium and 3 small
ps.addCar(2); //true, medium car takes medium place
ps.addCar(2); //true, medium car takes medium place
ps.addCar(2); //true, medium car takes big place
ps.addCar(1); //false, no place for big car

I wrote:
public class ParkingSystem {
    private int big;
    private int medium;
    private int small;

    public ParkingSystem(int big, int medium, int small) {
        this.big = big;
        this.medium = medium;
        this.small = small;
    }

    public boolean addCar(int car) {
        if (car == 1 && isPlaceForBigCar()) {
            return parkBigCar();
        } else if (car == 2 && isPlaceForMediumCar()) {
            return parkMediumCar();
        } else if (car == 3 && isPlaceForSmallCar()) {
            return parkSmallCar();
        }
        return false;
    }

    private boolean parkBigCar() {
        this.big--;
        return true;
    }

    private boolean parkMediumCar() {
        if (medium > 0) {
            this.medium--;
        } else if (big > 0) {
            this.big--;
        }
        return true;
    }

    private boolean parkSmallCar() {
        if (small > 0) {
            this.small--;
        } else if (medium > 0) {
            this.medium--;
        } else if (big > 0) {
            this.big--;
        }
        return true;
    }

    private boolean isPlaceForBigCar() {
        return this.big > 0;
    }

    private boolean isPlaceForMediumCar() {
        return (this.big > 0 || this.medium > 0);
    }

    private boolean isPlaceForSmallCar() {
        return (this.big > 0 || this.medium > 0 || this.small > 0);
    }
}

so it seems to be a little better than the worst solution but I believe there is still a lot to improve. Should I use strategy pattern to park cars or is there even better solution?
Main/Test class:
public class Main {
    public static void main(String[] args) {
        ParkingSystem ps = new ParkingSystem(1, 2, 3); // creates parking with 1 big place, 2 medium and 3 small
        System.out.println(ps.addCar(2)); //true, medium car takes medium place
        System.out.println(ps.addCar(2)); //true, medium car takes medium place
        System.out.println(ps.addCar(2)); //true, medium car takes big place
        System.out.println(ps.addCar(1)); //false, no place for big car
    }
}


texts:
I'm very new to programming and I decided to start my journey with Python. It's my fifth day of learning and decided to try myself out and make a very simple slot machine. I was stuck for hours because I had issues with the balance counter but finally managed to make it work.
Would you please rate it or give your opinion on where the code could have been simpler? Many thanks!
import random
global a
a = [1000]
global bet
bet = 20
# This is the user's wallet, the list "a" contains the balance

def win1():
    # I did different wins, the win1,2,3 function contains them
    print("WIN!WIN!WIN! \n You won " , bet * 2 , "credits! ")
    a.append(a[-1] + (bet * 2))
    print("Actual balance : ", a[-1])

def win2():
    print("WIN!WIN!WIN! \n You won " , bet * 4 , "credits! ")
    a.append(a[-1] + (bet * 4))
    print("Actual balance : ", a[-1])

def win3():
    print("WIN!WIN!WIN! \n You won " , bet * 6 , "credits! ")
    a.append(a[-1] + (bet * 6))
    print("Actual balance : ", a[-1])

def reels():
    # Here is the random number calculation.As you can see, theres a pretty good chance to win so it
    # would not be a good casino game for the house :)
    reel_1 = random.randint(1,3)
    reel_2 = random.randint(1,3)
    reel_3 = random.randint(1,3)

    if reel_1 + reel_2 + reel_3 == 9 :
        print("Jackpot!!!!!!!!!!")
        a.append(a[-1] + bet * 100)
        print ("Actual balance : " , a[-1])

    elif reel_1 + reel_2 + reel_3 == 8:
        win3()

    elif  reel_1 + reel_2 + reel_3 == 7:
        win2()

    elif  reel_1 + reel_2 + reel_3 == 6:
        win1()

    else :
        print("No win this time")

def spin() :

    # And this is the main function, the spin

    spin1 = input("Balance : "+ str(a[-1])+ " Press enter to spin the wheel ")

    if spin1 == (""):
        print("****************************THE WHEEL IS SPINNING**************************** \n "
              "")
    else :
        print("You can only spin the wheel with enter")
        spin()

    a.append(a[-1] - bet)
    print("Balance : " , (a[-1]))
    reels() , spin()

spin()


texts:
I'm just learning the basics of animating with Javascript and HTML5. I'm trying to create this scrolling logos element for my site, and I'm pretty sure that my code is very inefficient. Can anyone give me any tips on how to do a better job of what I'm trying to do here?

http://jsbin.com/anagug/1/edit

Thanks!

EDIT: Here is the code:

        var ctx;
        var count = 0;
        var xpos;
        var ypos;
        var revealTimer;

        var img = new Image();
        img.src = "http://www.firewalkcreative.com/2012/images/logos_1.png";

        function switchImage(){

            xpos = count * 150;
            ypos = 0;

            count++;
            ctx.globalAlpha = 0.1;
            revealTimer = setInterval(revealImage,100);

            if(count == 5)
                count = 0;

        }

        function revealImage() {
            ctx.drawImage(img, 0, 0, 840, 90, xpos, count, 840, 90);
            ctx.drawImage(img, 0, 0, 840, 90, xpos-900, 0, 840, 90);
            ctx.save();
            ctx.globalAlpha += 0.1;
            if (ctx.globalAlpha >= 1.0)
                clearInterval(revealTimer);
            ctx.restore();
        }

        function init() {

            ctx = document.getElementById("canvas").getContext("2d");
            setInterval(switchImage,3000);
        }


texts:
My solution to the LeetCode's Subtree of Another Tree passes all the test cases, but the code feels and looks ugly. Would appreciate an advice on how to improve it.

The problem:

  Given two non-empty binary trees s and t, check whether tree t has exactly the same structure and node values with a subtree of s. A subtree of s is a tree consists of a node in s and all of this node's descendants. The tree s could also be considered as a subtree of itself.

Example:

  Given tree s:

     3
    / \
   4   5
  / \
 1   2

  Given tree t:

   4
  / \
 1   2

  Return true, because t has the same structure and node values
  with a subtree of s.

My solution:

class Solution {
private:
    bool isSame(TreeNode* root_s, TreeNode* t) {

        if (!root_s && !t) return true;
        if (root_s && !t) return false;
        if (!root_s && t) return false;

        if (root_s->val != t->val) return false;

        return isSame(root_s->left, t->left) &&
            isSame(root_s->right, t->right);
    }

    void preorder (TreeNode* s, TreeNode* t, bool& is_subtree) {
        if (!s) return;

        if (s->val == t->val) {
            if (isSame(t,s)) {
                is_subtree = true;
                return;
            }
        }
        preorder (s->left, t, is_subtree);
        preorder (s->right, t, is_subtree);
    }

public:
    bool isSubtree(TreeNode* s, TreeNode* t) {

        bool is_subtree = false;
        preorder (s, t, is_subtree);

        return is_subtree;
    }
};

For context, here's the definition of TreeNode given by LeetCode:

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};


texts: Redirect for subdomains and secondary domains

texts:
I've just edited my .htaccess file. All works as it should, but I'm not too familiar with regular expressions and want to make sure that there aren't any unintended consequences.

I want to:

Add www to the domain if it's not there (i.e. domain.com becomes www.domain.com)
redirect from secondary.primary.com to www.secondary.com (the site is a subdomain of another site but the two aren't related and the primary domain shouldn't be included in the URL for the site).
redirect domain.com/staging to staging.domain.com.

Here are my rules:

# Add www if not there
RewriteCond %{HTTP_HOST} ^secondary\.com$ [NC]
RewriteRule (.*) http://www.secondary.com/$1 [R=301,L]

# Prevent search engine from using secondary domain i.e. secondary.primary.com and instead use secondary.com
RewriteCond %{HTTP_HOST} ^(www\.)?secondary\.primary\.com$ [NC]
RewriteRule (.*) http://www.secondary.com/$1 [R=301,L]

# Prevent access to staging through secondary.com/staging and instead use staging.secondary.com
RewriteCond %{HTTP_HOST} ^secondary.com [NC]
RewriteRule ^(.*)$ http://www.secondary.com$1 [L,R=301]
RedirectMatch 301 ^/staging/(.*)$ http://staging.secondary.com/$1


texts: Creating a python dataframe by parsing JSON API response

texts:
In this SO question the OP is unable to scrape a table from a dynamically loaded website. In monitoring the web traffic, via Chrome dev tools, I found that there is an API request made that returns a JSON string with the required info.

The following is the answer I wrote to extract the columns of interest from the API response.

Guide to columns of interest:

Course Title = title
Trainer = name (within trainers)
Rating = rating
Vendor = name (within vendors)
IT Path = path_label (within paths)
Skill Level = display (within difficulty)
Course URL = concatenation of base with seoslug

The Vendors field has missing items hence my use of an if statement in the assigment to vendors. I am not sure what the usual placeholder value is for missing string values in Python.

I use repeated list comprehensions in loops over the JSON object data; where data = response.json()

I couldn't think of a way to remove these repeated loops and still have legible code.

I generate a dataframe by joining the lists in a dictionary and then converting with pandas.

I welcome any and all feedback please.

JSON response:

Example JSON dictionary within response. The response has a collection of such dictionaries.

Python 3

import requests
import pandas as pd

def main():
    base = 'https://www.cbtnuggets.com/it-training/'
    response  = requests.get('https://api.cbtnuggets.com/site-gateway/v1/all/courses/for/search?archive=false')

    data = response.json()

    titles = [item['title'] for item in data]
    trainers = [item['trainers'][0]['name'] for item in data]
    ratings = [item['rating'] for item in data]
    vendors = [item['vendors'][0]['display'] if len(item['vendors']) != 0 else 'N/A' for item in data]
    paths = [item['paths'][0]['path_label'] for item in data]
    skillLevel = [item['difficulty']['display'] for item in data]
    links = [base + item['seoslug'] for item in data]

    df=  pd.DataFrame(
      {'Course Title': titles,
       'Trainer': trainers,
       'Rating': ratings,
       'Vendor': vendors,
       'IT Path': paths,
       'Skill Level': skillLevel,
       'Course URL': links
      })

    #print(df)
    df.to_csv(r'C:\Users\User\Desktop\Data.csv', sep=',', encoding='utf-8',index = False )

if __name__ == "__main__":

    main()


texts: How should I format my code to make it easier to read and understand in the future

texts:
I am using this query to generate a conversation stream between user 184 and 192-

SELECT events.event_time, messages . *
FROM   events , messages
WHERE  events.global_id=messages.global_ref_id  AND
       (messages.to =184 AND messages.from =192) OR
       events.global_id=messages.global_ref_id AND
       (messages.to =192 AND messages.from =184) AND
       messages.global_ref_id < 495
ORDER BY `messages`.`global_ref_id` ASC

This query is working good for generating conversation between two users.
Can you help me with converting this query to something more readable. Because I believe it is just a workaround and will cause some problems in future.
Schema of messages table

Field         Type
global_ref_id int(12)
to            int(12)
from          int(12)
message       text
status        int(1)
viewed        int(1)

where global_ref_id is foreign key.


texts: Floating point representation in IEEE 754 format

texts:
The following code takes a decimal number and gives its IEEE 754 floating point representation. However, the code is not complete and I am totally fine because it does the job for me:

It does not consider negative numbers.
The input number is not a fraction. Its always in the form xx.yy
As of now, it does not give representation in 32-bit or 64-bit format, it just gives exponent and significant value.

function toBinary (decimal) {
    return decimal.toString(2);
}

function getIntegerPart (binary){
    return binary.slice(0, binary.indexOf('.'));
}

function getFractionalPart (binary){
    return binary.slice(binary.indexOf('.')+1);
}

function toNormalize (binary) {
    var normalizedRep = new Object();
    exponentValue = binary.indexOf('.')-1;
    floatPosition = binary.indexOf('.');
    normalizedRep.floatRep = binary[0]+ '.' + binary.slice(1, floatPosition) + binary.slice(floatPosition+1);
    normalizedRep.exponentValue = exponentValue;
    normalizedRep.floatPosition = floatPosition;
    return normalizedRep;
}

function getSignificand (normalizedRep) {
    return normalizedRep.floatRep.slice(normalizedRep.floatRep.indexOf('.')+1);
}

function twosComp() {
    var decimal = 15.22;
    var binary = toBinary(decimal);
    var integerPart = getIntegerPart(binary);
    var fractionalPart = getFractionalPart(binary);
    var floatPosition = binary.indexOf('.');
    var normalizedRep = toNormalize(binary);
    var significand = getSignificand(normalizedRep);
    var exponentValue = normalizedRep.exponentValue;

    console.log(binary);
    console.log(floatPosition);
    console.log(normalizedRep.floatRep);
    console.log(significand);
    console.log(exponentValue);
}


texts: Speeding up a complex array function in excel

texts:
I have a complex array function that takes way too much time to calculate, which is why I'm looking for ways to make it more efficient. Basically, I have a transaction sheet in which I list all goods sold in a bunch of different stores. The formula that I've written picks the last stock amount in the list where a specific good was sold at a specific store. An index match doesn't work here as I have 2 different row arguments. The formula looks as follows:

{=INDEX($O$20:O57,MAX(IF($K$20:K57=K58,IF($D$20:D57=D58,ROW($O$20:O57)-MIN(ROW($O$20:O57))+1))),1)}

To explain in more detail:

In column O is the amount of stock after each transaction listed (of which I need the last entry in the list)
In column K is the item code for the specific good
In column D is the name of the branch where the good was sold

With increasing transactions, the sheet grows quite substantially and becomes already with ~1,000 rows a time-consuming nightmare. I have written a vba code that copies the entire table except for the last few rows and pastes everything as values back into the table to avoid having too many array formulas in the table, but I can still watch the extended Lord of the Ring cuts while it's computing.

I appreciate any ideas, I'm sure there are ways to make this thing a little faster ;)


texts:
I watched a presentation by Dave Thomas on Elixir where he gave an example problem that he solved using functional programming. He mentioned using Ruby to solve the same problem, but did not show an example. I decided to give it a try. The problem goes something like this:

For a list (Ruby doesn't have lists, but for our purposes an Array is close enough) of n numbers, create a new list where unique numbers are represented once, and repeated numbers are represented by a tuple (again, Ruby doesn't have tuples, but for our purposes a Hash or an Array would do) where the first element is the number itself, and the second is its count.

For Example, the following list:

[ 1, 2, 2, 2, 3, 4, 4, 5, 6, 6, 6, 6 ]

Would become:

[ 1, {2, 3}, 3, {4, 2}, 5, {6, 3} ]

I came up with the following solution.

list = [ 1, 2, 2, 2, 3, 4, 4, 5, 6, 6, 6, 6 ]
list.each_with_object(Hash.new(0)) { |n, hash| hash[n] += 1 }.map { |k, v| v > 1 ? { k => v } : k }
#=> [ 1, {2 => 3}, 3, {4 => 2}, 5, {6 => 3} ]

How would you go about solving this problem?


texts: Environment variable check with default value in csharp

texts:
Looking for more simple one liner for environment variable check with default value in csharp, any help is appreciated.
public static string GetEnvironmentVariable1(string envName, string defaultValue)
{
   var env = Environment.GetEnvironmentVariable(envName);
   return string.IsNullOrEmpty(env) ? defaultValue : env;
}

Tried this code, but getting compiler error that possible null reference could be returned
public static string GetEnvironmentVariable2(string envName, string defaultValue)
{
  return string.IsNullOrEmpty(Environment.GetEnvironmentVariable(envName)) ? defaultValue : Environment.GetEnvironmentVariable(envName);
}


texts: Speeding up Python depth-first search in large graph

texts:
I'm building a Markov text poetry generator. The main method, which is attached below, performs a depth-first search through the Markov chain, which is implemented as a NetworkX digraph of Word objects, which have methods for determining whether e.g. a Word rhymes with another Word instance.

At each level of the search, I filter the successor nodes to those that match user-supplied constraints - for example, "first word in sequence must rhyme with last word in sequence", so lines of poetry with different poetic devices can be built from the Markov chain.

The code I have works, but with large amounts of text (27412 unique words, 160892 edges between words) for certain combinations of constraints, especially rhyming ones, it takes a very long time to come up with a sequence that satisfies the constraints, if there is a possible sequence in the chain. Here's an example:

>>> vg = VerseGenerator(some_very_long_text)
>>> cs = [Constraint(Word.rhymeswith, [0, 3])]
>>> vg.build_sequence(4, [], cs)
[Word(among), Word(the), Word(white), Word(young)] - 204ms via IPython %timeit
>>> cs = [Constraint(Word.rhymeswith, [0, 9])]
>>> vg.build_sequence(10, [], cs) - Doesn't terminate for at least 10 minutes

Can anyone see a way I could speed this up, if any? I'm experimenting with Cython, but it will be a while before I get up to speed on it. Perhaps there is some clever graph theory property or algorithm I could use to preprocess it, or something?

The code in its entirety is available at my Github. I'm using Python 3. I hope I have explained it clearly enough, but if not please point out what other information I should include.

def build_sequence(self, length, predicates, constraints, order='roulette'):
    ''' Traverse the graph in depth first order to build a sequence
    of the given length which fits the supplied predicates. If a
    matching sequence is not found, return partially constructed
    sequence. Begins with a randomly selected word from the graph
    '''

    # If there are any multiple-word constraints that begin at
    # this level, we need to create predicates so they can be
    # applied at future search levels
    def apply_constraints(cands, path, level, preds, cons):
        cs = [c for c in cons if c.indices[0] == level]
        search_nodes = []
        for can in cands:
            new_preds = []
            for con in cs:
                curried = partial(con.method, can)
                sub = con.indices[1:]
                new_preds.extend([Predicate(curried, i) for i in sub])
            rec = {'word': can, 'parent': path, 'level': level,
                   'preds': preds + new_preds}
            search_nodes.append(rec)
        return search_nodes

    stack = []
    level = 0

    # Get candidate starting nodes
    apply = [p.partial for p in predicates if p.index == level]
    cands = self.filter_words(self.chain.nodes(), apply)
    random.shuffle(cands)
    branches = apply_constraints(cands, None, level, predicates, constraints)
    stack.extend(branches)

    while stack and level < length:
        path = stack.pop()
        prev = path['word']
        level = path['level'] + 1
        preds = path['preds']

        # Filter nodes following previous word to get candidates for
        # the next word in the sequence.
        apply = [p.partial for p in preds if p.index == level]
        succ = self.shuffled_successors(prev, order=order)
        cands = self.filter_words(succ, apply)

        branches = apply_constraints(cands, path, level, preds, constraints)
        stack.extend(branches)

    # Walk backward through final recursive record to build the
    # resulting sentence
    result = []
    for i in range(level):
        result.append(path['word'])
        path = path['parent']

    return reverse(result)


texts: Split function using C and dynamic memory allocation

texts:
I have programmed a function to split strings, and it gives the expected output.
I am looking forward to write better code and I was told here is a good place to start.
Here's my program:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char **split(char *str) {
    int str_length = 0;
    int i = 0;
    int separator_count = 0;
    while (str[i] != '\0') {
        if (str[i] == ' ') {
            separator_count++;
        }
        i++;
    }

    char **word_array;

    word_array = malloc((separator_count + 2) * sizeof(char *));

    int word_len = 0;
    int separator_index = 0;
    int b = 0;                                     //to iterate over "str"

    for (int a = 0; a < (separator_count + 2); a++) {
        word_len = 0;
        while (str_length < strlen(str) + 1) {
            str_length++;

            if (str[b] == ' ' || str[b] == '\0') {
                separator_index = b;
                word_array[a] = malloc(word_len * sizeof(char));
                int word_depth = 0;
                for (int c = (separator_index - word_len); c < separator_index; c++) {
                    chrctr = str[c];
                    word_array[a][word_depth] = str[c];
                    word_depth++;
                }
                word_array[a][word_len] = '\0';         //terminate found and stored word with null charachter
                word_len = 0;                           //reset word length counter to 0
                b++;                                    //skip to next charachter
                break;                                  // break to go to next index of word_array
            }
            word_len++;
            b++;
        }
    }
    word_array[separator_count + 2] = NULL;
    return word_array;
}

int main() {
    char s[] = "A complete toolkit for building search into your product.";  //test string
    char **ss = split(s);
    for (int i = 0; i < sizeof(ss); i++) {        //here is the problem, and doing sizeof(ss)/sizeof(ss[0])=1 !!
        for (int j = 0; j < strlen (ss[i]); j++) {
            printf("%c", ss[i][j]);
        }
        printf ("\n");
    }
}

Please comment with any advice or remarks on how to make this better.


texts: Missing element from array (D&C) - code design/aesthetic improvement

texts:
I am trying to implement in C/C++ a 'classical' Divide and Conquer algorithm which solves the following problem "Given an array of n-1 numbers (int) from 0 to n, find the missing number".

I am using the typical algorithm:
start from MSB
(1) find out how many bits of 1, 0 I should have (MSB bits)
(2) find out how many bits of 1, 0 I actually have (MSB bits)

split the array into 2 subarrays: one with MSBs of 0, the other with MSBs of 1.
By using (1) and (2) I figure out in which subarray my number should be and I recursively call the function for the next bit (MSB-1), until my subarray contains only 1 element.

I've written the code, and it works, but I have the feeling that it isn't really that aesthetic (the function has a lot of parameters), because I had some difficulties.

Let's say that we have v = {0,1,2,3,5,6,7}.
exp1 = 4 (expected number of "1" MSB bits).
I know how to calculate exp1, because I know that one number is missing from 0 to 7.
act1 = 3 (actual ...)
So, we will have something like this: 0 1 2 3 | 5 6 7.
Because act1 < exp1, we recursively call the function for the 5 6 7 part and for MSB-1.

exp1 = ? I will be unable to calculate this, because I will have no information upon the missing number. That is why I use the flagR and flagL flags. So that I know which part of the array I recursively called in order to compute exp1. But I really don't like the fact that I have been forced to use this 'trick'.

I have noticed myself that I should've forced an order in the partitioning process: the numbers that have 0 as MSB (current MSB) should be in the first part, the others in the second. I will rewrite the code.

The main() function isn't really that important for now, it serves for testing, currently.

Here is my spaghetti code:

#include <cstdio>
#include <cmath>

// get bit #j from int i
unsigned int get_bit(int i, int j)
{
  return i & (1<<j);
}

int find(int v[], int left, int right, int max_bit, int flagL, int flagR)
{
  if (left == right)
    if (flagR != 0)
      return v[left] + 1;
    if (flagL != 0)
      return v[left] - 1;
  else
  {
    int exp0 = 0; // expected bits of 0
    int act0 = 0; // actual bits of 0
    int act1 = 0; // actual bits of 1
    int exp1 = 0; // expected bits of 1

    for (int i=left+flagL;i<=right+flagR;i++)
      if (get_bit(i,max_bit) == 0)
        exp0++;
      else
        exp1++;

    for (int i=left;i<=right;i++)
      if (get_bit(v[i],max_bit) == 0)
        act0++;
      else
        act1++;

    // val_cur is the max_bit of the pivot (v[right])
    unsigned int val_cur = get_bit(v[right],max_bit);
    int i = 0;
    int k = 0;
    int man = 0;

    // divides the array into 2 subarrays
    // one subarray contains elements with max_bit = 0
    // the other contains elements with max_bit = 1
    for (k=1;k<right;k++)
    {
      if (get_bit(v[k],max_bit) == val_cur)
      {
        i++;
        man = v[i];
        v[i] = v[k];
        v[k] = man;
      }
    }
    i++;
    man = v[i];
    v[i] = v[k];
    v[k] = man;
    // i is the "border" between the subarrays

    // recursively call the function for the next bit (max_bit-1)
    // and with the correct partition
    if (get_bit(v[i],max_bit) == 1)
      if (act1 < exp1)
        return find(v,left,i,max_bit-1,0,1);
      else
        return find(v,i+1,right,max_bit-1,-1,0);
    else
      if (act0 < exp0)
        return find(v,left,i,max_bit-1,0,1);
      else
        return find(v,i+1,right,max_bit-1,-1,0);
  }
}

int main()
{
  int n = 7;
  int v[] = {7,0,4,1,3,6,2};

  // find the maximum number of bits
  int bits = 0;
  bits = floor(log(n*1.0)/log(2*1.0));

  // call the function
  printf("%d",find(v,0,6,bits,0,1));
  return 0;
}


texts:
I am getting information from an XML document and for the most part everything runs as it should. Occasionally, I get a php fatal error Call to a member function children() on a non-object. I have tried to use this

if(isset($current->AttributeSets->children('ns2', true)->ItemAttributes->ListPrice->Amount))
{
    $listPrice = $current->AttributeSets->children('ns2', true)->ItemAttributes->ListPrice->Amount;
} else {
    $listPrice = 0;
}

to catch any times there is no information in $current, but it does not always work. How do I handle the errors so it works all the time?


texts: Best way to locate Find on List with reflection

texts:
I am locating the find method of List in C# with the single Expression type  parameter

I am using the following ( where T is a List, in my case a SubSonic IActiveRecord )

MethodInfo info = typeof(T).GetMethods(BindingFlags.Static | BindingFlags.Public)
                             .FirstOrDefault(m => m.Name == "Find" && m.GetParameters().Count() == 1);

This works perfectly well, but feels clunky (especially the parameter count part) and I'm not sure how future proof it is.


texts:
I'm teaching myself BigDecimal and would appreciate a critique. In the code fragment below, I calculate a tip from user input: check and tip percentage (entered as integer):

 txt_check = txtcheck.getText().toString();
 tpercent = txttippct.getText().toString();

 BigDecimal hundred = new BigDecimal("100");
 BigDecimal pct = new BigDecimal(tpercent);

 BigDecimal bdpercent = pct.divide(hundred, 2,BigDecimal.ROUND_UNNECESSARY);
 BigDecimal bdcheck = new BigDecimal(txt_check);
 BigDecimal bdtip = new BigDecimal(txt_check);
 bdtip = bdtip.multiply(bdpercent);
 BigDecimal bdtotal = new BigDecimal(txt_check);
 bdtotal = bdtotal.add(bdtip);

The code above appears to function correctly. To display these values I convert to string:

 scheck = new DecimalFormat("####.00").format(bdcheck.doubleValue());
 scheck = StringUtils.leftPad(scheck,7," ");

Thanks for any input.


texts:
Given an input string, reverse the string word by word.
For example: Given s = "the sky is blue", return "blue is sky the".
What constitutes a word?

A sequence of non-space characters constitutes a word.

Could the input string contain leading or trailing spaces?

Yes. However, your reversed string should not contain leading or trailingspaces.

How about multiple spaces between two words?

Reduce them to a single space in the reversed string.

public static String reverseWords(String s){
    StringTokenizer strTok = new StringTokenizer(s, " ");
    Stack<String> stack=new Stack<String>();
    StringBuilder buff=new StringBuilder();
    while(strTok.hasMoreElements()) {
        String str = (String)strTok.nextToken();
        if(!str.equals("")) stack.push(str);
    }
    while(!stack.isEmpty()){
        buff.append(stack.pop());
        if(!stack.isEmpty()) buff.append(" ");
    }
    return buff.toString();
 }


texts: Returning the result of whichever method finishes first

texts:
Consider a method (let's call it IsPrimeHybrid) which calls at least two methods (let's call them IsPrimeNaive and IsPrimeBySearch) that calculate an identical result using different approaches and the outer method returns the result when any of the inner methods finishes.

The following is my first attempt to write such a method, but I'd like to hear what issues it may have and what's a good way to fix them. (For example, how to implement thread safety in a scenario like this.)

    public static bool IsPrimeHybrid(BigInteger number)
    {
        var result = default(bool);
        var byPureCalc = Task.Run(() => result = IsPrimeNaive(number));
        var bySearchFirst = Task.Run(() => result = IsPrimeBySearch(number));
        Task.WaitAny(byPureCalc, bySearchFirst);
        return result;
    }

For the sake of simplicity, please assume that none of the called methods will consume any common resources, apart from processing power and memory (that is, there will never be two methods that both use file I/O or network I/O, etc).


texts: Easy Bit IO. Very simple interface works up to N == 64

texts:
After reading this question Easy bitset I/O. I wanted to see if there was a simpler way of doing it.

This is how I would define a way of outputting std::bitset<N> to the stream and reading it back in. It works perfectly with current containers.

BitIO.h

// Include guards deliberately not included for simplicity.

#include <bitset>
#include <iostream>

template<int S>
class BitIO
{
    public:
    std::bitset<S>&     data;
    BitIO(std::bitset<S>& data)
        : data(data)
    {}

    friend std::ostream& operator<<(std::ostream& stream, BitIO const& value)
    {
        // Currently using just an integer.
        //
        // But we could easily take this a step further and use hex.
        // and pad with 0 to get an exact width (that way we don't need a
        // trailing space).
        //
        // Using a fixed width means we may potentially waste space but can
        // be made to waste the least amount of space possible quite easily.
        //
        // Amount of wasted space would be (4 - (S % 4)) % 4

        return stream << value.data.to_ullong() << " ";
    }
    friend std::istream& operator>>(std::istream& stream, BitIO& value)
    {
        // As the current output uses a white space separated
        // unsigned long long it is easy to read it back in using the
        // normal `operator>>`
        //
        // Would be just as simple to convert this function to use
        // a fixed width format to mirror the output.
        unsigned long long tmp;
        if (stream >> tmp)
        {
            value.data  = std::bitset<S>(tmp);
        }
        return stream;
    }
};

main.cpp

#include "BitIO.h"
#include <vector>

int main()
{
    std::vector<std::bitset<16> >    values { std::bitset<16>(1), std::bitset<16>(2), std::bitset<16>(255) };

    std::copy(std::begin(values), std::end(values), std::ostream_iterator<BitIO<16>>(std::cout));

    std::bitset<16>  data { 129 };
    std::cout << BitIO<16>(data);

}


texts:
I have started learning Java and was trying to solve some easy problems from different websites like HackerRank and leetcode.I am relatively new to programming so please don't mind if this is too naive. I found a problem in LeetCode to rotate array.The problem can be found here

I have implemented the solution using two different methods:

The first method(my initial solution) rotateArray1 is very straightforward where we divide the array into two parts and then copy the elements back into the main array.

I found the logic for the second method in programcreek which says :

  1. Divide the array two parts: 1,2,3,4 and 5, 6
  2. Reverse first part: 4,3,2,1,5,6
  3. Reverse second part: 4,3,2,1,6,5
  4. Reverse the whole array: 5,6,1,2,3,4

This is my solution where I implemented both the methods.I am trying to get better at writing good code for my solutions. Please give me your suggestions and also can anyone please tell me which one of these two methods is more efficiant in terms of time complexity.

 import java.util.Scanner;

/*Problem: Rotate an array of n elements to the right by k steps.
 For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7]
 is rotated to [5,6,7,1,2,3,4]. */

public class RoatateArray {
    public static Scanner Keyboard = new Scanner(System.in);

    public static void main(String[] args) {

        int size = Keyboard.nextInt();
        int[] array = new int[size];
        fillArray(array);
        System.out.println("Array before rotation is :");
        printArray(array);
        System.out
                .println("\nEnter the number of steps the array needs to be rotated");
        int order = Keyboard.nextInt();
        if (order == array.length) {
            System.out
                    .println("The order of the array will be same after rotation of "
                            + order + "steps");

        } else {
            System.out
                    .println("enter choice 1 : arrayRotate1  or choice 2 for : arrayrotate2");
            int choice = Keyboard.nextInt();
            switch (choice) {
            case 1:
                arrayRotate1(array, order);

                break;
            case 2:
                arrayRotate2(array, order);
                break;
            default:
                break;
            }

        }

    }

    private static void arrayRotate1(int[] array, int order) {
        if (order > array.length) {
            order = order % array.length;
        }
        int[] arr1 = new int[order];
        int[] arr2 = new int[array.length - order];
        System.arraycopy(array, array.length - order, arr1, 0, arr1.length);
        System.arraycopy(array, 0, arr2, 0, arr2.length);
        // copy arr1 and arr2 into original array
        System.arraycopy(arr1, 0, array, 0, arr1.length);
        System.arraycopy(arr2, 0, array, arr1.length, array.length - order);
        printArray(array);

    }

    private static void printArray(int[] array) {
        for (int i = 0; i < array.length; i++) {
            System.out.print(array[i] + " ");
        }

    }

    private static int[] fillArray(int[] array) {

        for (int i = 0; i < array.length; i++) {
            array[i] = Keyboard.nextInt();
        }

        return array;
    }

    private static void arrayRotate2(int[] array, int order) {

        if (order > array.length) {
            order = order % array.length;
        }

        // get the length of the first part

        int a = array.length - order;

        reverse(array, 0, a - 1);
        reverse(array, a, array.length - 1);
        reverse(array, 0, array.length - 1);
        printArray(array);

    }

    private static void reverse(int[] array, int left, int right) {
        while (left < right) {
            int temp = array[left];
            array[left] = array[right];
            array[right] = temp;
            left++;
            right--;
        }

    }

}


texts: Calculate subtotals and totals from a form with many decimal values

texts:
I've got 17 currency fields on a form and need to do some calculations with their values. I wrote this method some time ago and have come back to try and refactor it to make it more efficient and/or more readable. Could I have some pointers please?

Note: The variables appended with d are the decimals used to hold the field values, their counterparts without the d are the fields themselves. I am aware that variables could do with renaming to make more sense. Hopefully it's fairly clear what this is doing by looking at the comments.

private void getTotals() {

    //declarations of decimal variables
    decimal curPurc1d; decimal curPurc2d; decimal curPurc3d; decimal curPurc4d; //purItemxCost
    decimal curItem1Totd; decimal curItem2Totd; decimal curItem3Totd; decimal curItem4Totd; //curItemxTot
    decimal LessItem1Costd; decimal LessItem2Costd; decimal LessItem3Costd; decimal LessItem4Costd; decimal LessItem5Costd; //LessItemxCost
    decimal ditem1Cost = 0; decimal ditem2Cost = 0; decimal ditem3Cost = 0; decimal ditem4Cost = 0; //Full cost of items

    //Check if we have some valid numbers, stop if we don't
    if (   !decimal.TryParse(curPurc1.Value.ToString(), out curPurc1d)
        || !decimal.TryParse(curPurc2.Value.ToString(), out curPurc2d)
        || !decimal.TryParse(curPurc3.Value.ToString(), out curPurc3d)
        || !decimal.TryParse(curPurc4.Value.ToString(), out curPurc4d)
        || !decimal.TryParse(curItem1Tot.Value.ToString(), out curItem1Totd)
        || !decimal.TryParse(curItem2Tot.Value.ToString(), out curItem2Totd)
        || !decimal.TryParse(curItem3Tot.Value.ToString(), out curItem3Totd)
        || !decimal.TryParse(curItem4Tot.Value.ToString(), out curItem4Totd)
        || !decimal.TryParse(LessItem1Cost.Value.ToString(), out LessItem1Costd)
        || !decimal.TryParse(LessItem2Cost.Value.ToString(), out LessItem2Costd)
        || !decimal.TryParse(LessItem3Cost.Value.ToString(), out LessItem3Costd)
        || !decimal.TryParse(LessItem4Cost.Value.ToString(), out LessItem4Costd)
        || !decimal.TryParse(LessItem5Cost.Value.ToString(), out LessItem5Costd)
        )
        return;

        //For each of the 4 'items', try to get the value as a decimal, but only if the related checkbox is checked.
        if (Item1RateYN.Checked)
        {
            decimal.TryParse(curItem1Cost.Value.ToString(), out ditem1Cost);
        }
        if (Item2RateYN.Checked)
        {
            decimal.TryParse(curItem2Cost.Value.ToString(), out ditem2Cost);
        }
        if (Item3RateYN.Checked)
        {
            decimal.TryParse(curItem3Cost.Value.ToString(), out ditem3Cost);
        }
        if (Item4RateYN.Checked)
        {
            decimal.TryParse(curItem4Cost.Value.ToString(), out ditem3Cost);
        }

    //Add up some values which are always part of the subtotal and then the ditemx ones, which will be 0 or set to a numerical value depending if the checkbox is checked
    decimal subtotals = curPurc1d + curPurc2d + curPurc3d + curPurc4d + curItem1Totd + curItem2Totd + curItem3Totd + curItem4Totd
                      + ditem1Cost + ditem2Cost + ditem3Cost + ditem4Cost;
    subtotal.Value = subtotals;

    //Get total minus the cost of the property (curPurc1d)
    costPlusSubTotal.Value = subtotals - curPurc1d;

    //add up all the "less" items to know how much to reduce by
    decimal lessTotals = LessItem1Costd + LessItem2Costd + LessItem3Costd + LessItem4Costd + LessItem5Costd;
    totalLess.Value = lessTotals;

    //Total Balance due
    //subtotal minus the 'less' values total
    decimal total = (subtotals - lessTotals);
    //set the final figure into the relevant field
    balanceDueTot.Value = total;
}


texts: Am I violating any sound coding principles with this approach?

texts:
I am creating a C# service that will be doing some specialized processing of data coming into our ODS (Operational Data Store) DB. To support this, I’m building a DAL that will be used to access our ODS. In my DAL, I’ll have a number of GetItem (get a single item) and GetList (get a list of items) methods with a number of overrides to support a number of combinations of parameters for each method.

I was think that instead of having a number of overrides, I would do the following, using GetList as an example, using an Expression as the only parameter:

/// <summary>
/// Gets a list of Marker entities based on a predicate.
/// </summary>
/// <param name="predicate">The predicate</param>
/// <returns>List of Marker entities</returns>
public List<Entities.Marker> GetList(Expression<Func<MarkerRecord, bool>> predicate)
{
    return this.Database.Marker.Where(predicate).Map();
}

And it would be called like this:

MarkerData markerData = new MarkerData();
var markerList = markerData.GetList(row => row.ReadTime >= new DateTime(2012, 1, 7));

I could even modify this to make it generic to handle any data type. While this solution offers flexibility and saves some coding, something tells me I'm violating one or more best practices, perhaps like separation of concerns by passing code as data. Do you see any problems with this approach?


texts:
Right now in my weather app, I have one section of code in my View Controllers to set up the condition image and the background image. It has about 400 lines of if-else statement at the end.

The app's performance is fine, but is it bad to have this? Would it be something that, say, Apple would consider rejecting? The code is very easy to read, and makes perfect sense in my opinion.

- (void)updateImages:(ICB_WeatherConditions *)weather {
    if ([condition isEqualToString:@"113"]) {
        conditionsImageView.image = [UIImage imageNamed:@"Sun.png"];
        BGView.image = [UIImage imageNamed:@"Sun.jpg"];
    } else {
        if ([condition isEqualToString:@"116"]) {
            conditionsImageView.image = [UIImage imageNamed:@"Mostly_Sunny.png"];
            BGView.image = [UIImage imageNamed:@"Partly_Cloudy.jpg"];

        } else {
            if ([condition isEqualToString:@"119"]) {
                conditionsImageView.image = [UIImage imageNamed:@"Overcast.png"];
                BGView.image = [UIImage imageNamed:@"Overcast.jpg"];
            }
            else {
                if ([condition isEqualToString:@"122"]) {
                    conditionsImageView.image = [UIImage imageNamed:@"Overcast.png"];
                    BGView.image = [UIImage imageNamed:@"Overcast.jpg"];
                }
                else {
                    if ([condition isEqualToString:@"143"]) {
                        conditionsImageView.image = [UIImage imageNamed:@"Mist.png"];
                        BGView.image = [UIImage imageNamed:@"Foggy.jpg"];
                    }
                    else {
                        if ([condition isEqualToString:@"176"]) {
                            conditionsImageView.image = [UIImage imageNamed:@"Scattered_Thunderstorms.png"];
                            BGView.image = [UIImage imageNamed:@"Scat_Tstorms.jpg"];
                    }

It keeps going on after that. As you can see, I have a lot of nearly identical statements, which is because I have a lot of conditions. Is it bad practice to do this? If it is, then how can this become more efficient?


texts: Is it acceptable to use a function property as its own private storage?

texts:
I need to write a function that accepts a function as argument, if this function is new, adds it to an array otherwise do not add it.

I assigned a property a my function StoreFunctions and use it as the private storage space, is this an acceptable way to do it? I tested it with function c and d, I did get the correct results back.

function StoreFunctions(func) {
  if (StoreFunctions.funcArray.includes(func))
    return 'function already added';
  else {
    StoreFunctions.funcArray.push(func);
    return 'a new function is added';}
}

StoreFunctions.funcArray = [];

function c() {return 1};
function d() {return 2};
console.log(StoreFunctions(c));
console.log(StoreFunctions(d));
console.log(StoreFunctions(c));


texts:
Because I have been writing more multithreaded C++14 code lately, I've developed some tools that help me make sure that my threads are all working as intended.  In the real code, it's often difficult to detect race conditions or unintended sequence dependencies among threads, so I have found that temporarily substituting a work simulator (worksim in the code) for the real thread code, leaving any other locks, mutexes, etc. in place, allows me to gain some insight as to how the various threads might run.

There are three main pieces in the code below.  The first is the Logger class which is more or less a mutex-protected interface to std::cout.  It takes a std::stringstream & as input, emits the contents of it to std::cout and the clears the input stringstream.

The second piece is the worksim itself which employs a binomial random number distribution to generate delays that are typically around 25ms, emitting status to the passed Logger object until the stop flag is set.  I deliberately do not want to use a conditional variable here because I want to simulate the work that the thread would do.

The third piece is a simple main showing how these are used.  It creates 10 threads, waits five seconds and then shuts everything down.

I'm interested in comments on the worksim portion in particular.  Specifically,

is the intent clear?
is the use of a static number generator OK here?
is there a better way to handle the logging?

threadplay.cpp

#include <iostream>
#include <atomic>
#include <mutex>
#include <thread>
#include <random>
#include <chrono>
#include <vector>
#include <sstream>

class Logger {
public:
    Logger &operator<<(std::stringstream &ss) {
        std::lock_guard<std::mutex> lock(m);
        std::cout << ss.str();
        ss.str(std::string{});
        return *this;
    }
private:
    std::mutex m;
};

void worksim(Logger &mylog, std::atomic<bool> &stop, int n) {
    using namespace std::chrono_literals;
    static std::mt19937 gen(std::random_device{}());
    std::binomial_distribution<int> dist(50, 0.5);
    std::stringstream ss;
    ss << "Checking " << n << "\n";
    mylog << ss;
    for (auto delay = dist(gen); !stop; delay = dist(gen)) {
        ss << "Thread " << n << " sleeping for " << delay << "ms\n";
        mylog << ss;
        std::this_thread::sleep_for(1ms * delay);
    }
    ss << "Leaving " << n << "\n";
    mylog << ss;
}

int main()
{
    using namespace std::chrono_literals;
    std::atomic<bool> stop{false};
    std::vector<std::thread> th;
    Logger mylog;
    for (int i=0; i<10; ++i) {
        th.push_back(std::thread(worksim, std::ref(mylog), std::ref(stop), i));
    }
    std::this_thread::sleep_for(5s);
    stop = true;
    for (std::thread &thread : th) {
        thread.join();
    }
}


texts:
I have been playing around with the Io language, and this is my second toy, after the yes program that is just loop ("yes" printl) and on which not much review is possible, I wrote a FizzBuzz program. I like the shortness of it, but any improvement is welcome as I am very beginner in this programming language.

toBuzzWord := method(n,
   if (n % 15 == 0, "FizzBuzz",
   if (n % 5 == 0, "Fizz",
   if (n % 3 == 0, "Buzz", n))))

for (i, 1, 100, toBuzzWord(i) println)


texts: Traversing an array with a pointer to the array

texts:
I was thinking about how to traverse an array without an int iterator, and I'm curious if my answer is good/bad.
The first for loop simply populates each element of the array.
The second for loop traverses through the array. The int pointer, curr, initially points to the first address of the array then goes on to momentarily hold the address of each element of the array. The int pointer, ptrLastElement, contains the address of the last element of the array arr.
The check condition is essentially the difference of the address contained in ptrLastElement and the address contained in curr. If the difference is less than 0, then we've ran out of elements to display.
My main questions are:

Would this idea ever be useful?
Is this a terrible idea?
Did I do anything incredibly stupid?
How can I improve this and/or make it more generic?

main.cpp
#include <iostream>

int main()
{
    const size_t SIZE = 10;
    int arr[SIZE];
    int * ptrLastElement = arr + (SIZE-1);

    // Populate the array, arr, using int iterator
    for (int i = 0; i < SIZE; ++i)
    {
        arr[i] = i;
    }

    // Traversing arr using a pointer
    for (int * curr = arr; (ptrLastElement - curr) >= 0 ; ++curr)
    {
        std::cout << curr << "\t" << *curr << std::endl;
    }

    return 0;
}


texts:
I got asked at an interview to write a program that, given a NxM matrix with zeros and ones, prints out the list of clusters of 1s. The clusters are defined as patches of 1s connected horizontally, vertically or diagonally.

Here's the code I submitted but I'm wondering if there is a better way, e.g. a well-known algorithm to produce the solution.

namespace ConsoleApplication1
{
    /// <summary>
    /// Usage:
    /// <![CDATA[
    ///
    ///            var m = 4; // rows
    ///            var n = 5; // cols
    ///            var matrix = new[]
    ///            {
    ///                0,1,0,0,0,  // 0-4
    ///                0,0,1,1,0,  // 5-9
    ///                0,0,0,0,0,  // 10-14
    ///                0,1,1,0,0   // 15-19
    ///            };
    ///
    ///            var finder = new MatrixClusterFinder(matrix, m, n);
    ///            finder.PrintClusters();
    /// PRINTS:
    /// (0,1)(1,2)(1,3)
    /// (3,1)(3,2)
    ///
    /// ]]>
    ///
    ///
    ///
    /// </summary>
    public class MatrixClusterFinder
    {
        private int m;
        private int n;
        private int[] matrix;

        public MatrixClusterFinder(int[] matrix, int m, int n)
        {
            this.m = m;
            this.n = n;
            this.matrix = matrix;
        }

        public void PrintClusters()
        {
            var visited = new bool[m * n];

            for (var i = 0; i < m * n; i++)
            {
                var isClusterFound = Traverse(i, visited);

                if (isClusterFound)
                {
                    Console.WriteLine(); //crlf
                }
            }

        }

        private bool Traverse(int curr, bool[] visited)
        {
            if (visited[curr])
            {
                return false;
            }

            bool result = false;
            visited[curr] = true;
            if (matrix[curr] == 1)
            {
                result = true;
                var thisM = curr / n;
                var thisN = curr % n;
                Console.Write("({0},{1})", thisM, thisN);

                var adjs = GetAdjacent(curr);
                foreach (var adj in adjs)
                {
                    Traverse(adj, visited);
                }
            }
            return result;
        }

        private int[] GetAdjacent(int curr)
        {
            var thisM = curr / n;
            var thisN = curr % n;
            var result = new List<int>();
            for (var i = thisM; i <= thisM + 1; i++)
            {
                if (i < 0 || i > m - 1)
                {
                    continue;
                }
                for (var j = thisN - 1; j <= thisN + 1; j++)
                {
                    if (j < 0 || j > n - 1 || (i == thisM && j < thisN))
                    {
                        continue;
                    }
                    var res = i * n + j;
                    if (res == curr)
                    {
                        continue;
                    }
                    result.Add(res);
                }
            }
            return result.ToArray();
        }

    }
}