Rock, Paper, Scissors game I am very new to Ruby and building my first game. To be honest I did it this way because I was lazy to type so much. My friend told me that the correct way was to do this with case statement i.e. for scissor we have three cases, for rock we have three cases and similarly for paper.

puts "Rock, paper or scissor"
w = 0 and l =0 and t =0 and j=0
loop{
choice = ["paper" , "rock" , "scissor" ]
i=0

if j ==10
puts "wins : #{w}\nlosses : #{l}\ndraw:    #{t}"
       if w > l
           puts "You won the game"
       elsif w<l
           puts "You lost!"
       else
           puts "The game is a draw"
       end

         gets
      break
      end
while i == 0
human = gets.chomp.downcase
choice.each {
    |x|
    if human == x
        i+=1 and j+=1
        break
    end
    }
    puts "-----------------please enter rock paper or scissor-----------------" if i == 0
end
computer = rand(3)
com = choice[computer]
if (com == "scissor" and human != "rock") or (human == "scissor" and computer !=1)
   v = human <=> com
else
   v = com <=> human
end

puts "You chose #{human}, computer choose #{com}"
case v

    when 1
        puts "---->You win"
        w +=1
    when -1
        puts "---->Computer wins"
        l+=1
    else
        puts "---->draw"
        t+=1
end
}

Indentation
Be sure to indent your code properly. Indentation helps the reader understand where he is in the code (how deep). Some languages actually depend on correct indentation.

Meaningful names
You should give your variable names which will have meaning, and will help the reader of your code understand what each one is responsible for. Names like w, t, j should not be used for any variable other than immediate throw-away variables like if for(i = 1;....

A variable name l should never ever be used, since it is too easily confused with the digit 1, so in some fonts you will never know the difference between l+=1 and l+=l...

Your code should tell a story
Try to design your code in a way that a reader will be able to follow your logic. In your code, there is an endless loop, and in the first if you check whether a mysterious j is 10, and if it is you end the game... The story starts with the ending!

A more pleasing option might be:

while number_of_turns_played < 10 do

  # play a turn...
  number_of_turns_played += 1

end

if number_of_wins > number_of_losses
  puts "You won the game"
elsif number_of_wins < number_of_losses
  puts "You lost the game"
else
  puts "The game is a draw"
end

This way the story has a beginning, and an end, and it easier to follow.

Choose your types
What is i used for? As far as I can see it can have only two values - 0 and 1, and it is used to flag the get input loop that a valid input has been received. The name i is cryptic enough - why not at least make it a boolean?

Block format conventions
It is idiomatic in ruby to use {} syntax for one liner blocks, and do end syntax for multiline blocks.
Instead of writing:

choice.each {
  |x|
  # do something
}

You should write:

choice.each do |x|
  # do something
end

Too sophisticated for your own good
Let's look at the condition you worked so hard on for being lazy:

if (com == "scissor" and human != "rock") or (human == "scissor" and computer !=1)
 v = human <=> com
else
 v = com <=> human
end

First - be consistent - on one side check com and on the other you check computer - choose!
Using esoteric operators - the "spaceship" operator (a<=>b) is used when sorting arrays, and returns -1 if a is smaller than b, 1 if a is larger than b, and 0 if they are equal. It is very rarely used, and your usage, while cute, might be very unclear for most (I know I had to double check what it returns). Is it really needed?
Assumptions - you rely on the fact that "paper" is smaller than "rock", which is smaller than "scissor", and you write your algorithm around that assumption. You are relying on an incidental fact, which might change when, say, you translate it to another language! Don't make incidental assumptions, use your code to define your rules.
When there are too many exceptions to the rule - so you found a cool rule, which is good for [almost] all your cases. That is all but two, out of six... which is four... which is just about half the cases... Which you will need to explain to anybody who reads the code, since it is not apparent from how the code is written... Maybe it is not that good a rule?

So, what would I suggest?

Say I set the choices to %w(rock paper scissors), where each choice beats the one prior to it, now I can ask:

computer_choice_idx = rand(3)
if human_choice == choices[computer_choice_idx]
  # draw!
elsif human_choice == choices[computer_choice_idx - 1]
  # computer beats human!
else
  # human beats computer!
end

Since in ruby choice[-1] returns the last element in the array ("scissors"), there is no exception! If the computer chose "rock"(id 0) and the human chose "scissors" - computer will beat human, since "scissors" == choices[-1].

In short:

Choices = %w(rock paper scissors)

puts 'Rock, paper or scissors'
draws = wins = losses = 0
10.times do
  begin
    puts "-----------------please enter rock paper or scissors-----------------"
    human_choice = gets.chomp.downcase
  end until Choices.include?(human_choice)

  computer_choice_idx = rand(3)

  puts "You chose #{human_choice}, computer choose #{Choices[computer_choice_idx]}"

  if human_choice == Choices[computer_choice_idx]
    puts "---->draw"
    draws += 1
  elsif human_choice == Choices[computer_choice_idx - 1]
    puts "---->Computer wins"
    losses += 1
  else
    puts "---->You win"
    wins += 1
  end
end
puts "wins : #{wins}\nlosses : #{losses}\ndraw:    #{draws}"
if wins > losses
  puts "You won the game"
elsif wins < losses
  puts "You lost!"
else
  puts "The game is a draw"
end

Enjoy!


CMake - Usual Build System After wrestling with CMake I now have a fully working solution.
It works, however, I completely massacred the CMake File:
This is my main cmake file:
cmake_minimum_required(VERSION 3.17)
project(Odin)

include(ProcessorCount)
ProcessorCount(N)
if(NOT N EQUAL 0)
    set(CMAKE_BUILD_PARALLEL_LEVEL ${N})
endif()

message("Parallelizing with ${N} Cores")

set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED YES)
set(CMAKE_CXX_EXTENSIONS NO)

include_directories(Odin/engine)
include_directories(Odin/uci)
include_directories(Odin/util)
include_directories(Odin/util/iters)

# add our cmake modules under cmake/
list(APPEND CMAKE_MODULE_PATH "${PROJECT_SOURCE_DIR}/cmake")

# Include CPM dependency manager
include(CPM)

if(WIN64)
SET(BOOST_ROOT "C:/Program Files (x86)/boost/boost_1_74_0")
include_directories(${BOOST_ROOT})
include_directories(${BOOST_ROOT}/stage/lib)
endif()

find_package(Boost 1.74.0 REQUIRED serialization)

message(STATUS "---------------------")
message(STATUS "Boost_FOUND: ${Boost_FOUND}")
message(STATUS "Boost_INCLUDE_DIRS: ${Boost_INCLUDE_DIRS}")
message(STATUS "Boost_LIBRARY_DIRS: ${Boost_LIBRARY_DIRS}")
message(STATUS "Boost_LIBRARIES: ${Boost_LIBRARIES}")
message(STATUS "---------------------")

#EndBoost

add_executable(Odin
        Odin/engine/Odin.cc
        Odin/main.cc
        Odin/engine/Board.cc
        Odin/util/Utility.cc
        Odin/util/iters/BoardIterator.cc
        Odin/engine/Node.cc
        Odin/engine/Link.cc
        Odin/engine/Odin.h
        Odin/engine/Board.h
        Odin/engine/Figure.h
        Odin/util/Utility.h
        Odin/engine/Node.h
        Odin/engine/Link.h
        Odin/util/iters/BoardIterator.h)

add_library(Engine
        Odin/engine/Odin.cc
        Odin/main.cc
        Odin/engine/Board.cc
        Odin/util/Utility.cc
        Odin/util/iters/BoardIterator.cc
        Odin/engine/Node.cc
        Odin/engine/Link.cc
        Odin/engine/Odin.h
        Odin/engine/Board.h
        Odin/engine/Figure.h
        Odin/util/Utility.h
        Odin/engine/Node.h
        Odin/engine/Link.h
        Odin/util/iters/BoardIterator.h)

target_link_libraries(Engine PRIVATE Boost::serialization)
target_link_libraries(Odin PRIVATE Boost::serialization)

if(UNIX)
set(CMAKE_CXX_FLAGS "-O3 -march=native")
endif(UNIX)

#Make Tests
#enable testing
enable_testing()

# Pull doctest using CPM
cpmaddpackage("gh:onqtam/doctest#2.4.5")

# add the CMake modules for automatic test discovery so we can use
# doctest_discover_tests() CMake
set(CMAKE_MODULE_PATH "${doctest_SOURCE_DIR}/scripts/cmake"
        ${CMAKE_MODULE_PATH})

add_subdirectory(Testing)

To be honest, sometimes I had no idea what I was doing.
You see that I have to add every file into library and into the executable Odin.
This is not that smart.
I actually want my idea to still be able to add a .cpp file to the Odin - executable.
However my test must still run, and they require me to add all the files twice.
You can find my tests (cmake) here:
https://github.com/SuchtyTV/Odin/tree/master/Testing
Here are some questions:

How do I walk around this library/executable non-sense?
How do I ensure the Release build will be well optimized?
Can I download Boost with CPM, if so, how would I do that and how would that look in the cmake file?
Any other advices?

The code is mostly fine, however there are some problems:
SET(BOOST_ROOT "C:/Program Files (x86)/boost/boost_1_74_0")

^ This is wrong, because other developers may have Boost installed into different directory. Remove this line and let the user set BOOST_ROOT during configuration.
include_directories(${BOOST_ROOT})
include_directories(${BOOST_ROOT}/stage/lib)

^ Why is this required? The later find_package(Boost ...) call should set all required directories for you, which you can use in include_directories. This actually shouldn't be required at all, because linking to Boost using target_link_libraries should also set correct include directories.
add_executable(Odin ...
)

add_library(Engine ...
)

^ This looks wrong. First, you can remove code duplication by placing source files list into a variable:
set(SRCS ...
)

add_executable(Odin ${SRCS})
add_library(Engine ${SRCS})

Second, it looks strange that both library and executable consist of same source files. You probably want to keep most files being a part of the library and then link the library to executable. This is achieved by the same target_link_libraries command.
set(CMAKE_MODULE_PATH "${doctest_SOURCE_DIR}/scripts/cmake"
        ${CMAKE_MODULE_PATH})

^ Use list(APPEND ...), just like you did earlier in the code.


Tape Equilibrium O(n) Problem (Tape Equilibrium):

  A non-empty zero-indexed array A consisting of N integers is given.
  Array A represents numbers on a tape. Any integer P, such that 0 < P < N,
  splits this tape into two non−empty parts:

   A[0], A[1], ..., A[P − 1] and A[P], A[P + 1], ..., A[N − 1].

  The difference between the two parts is the value of:

 |(A[0] + A[1] + ... + A[P − 1]) − (A[P] + A[P + 1] + ... + A[N − 1])|

  In other words, it is the absolute difference
  between the sum of the first part and the sum of the second part.For
  example, consider array A such that:

  A[0] = 3
  A[1] = 1
  A[2] = 2
  A[3] = 4
  A[4] = 3

  We can split this tape in four places:

P = 1, difference = |3 − 10| = 7
P = 2, difference = |4 − 9| = 5
P = 3, difference = |6 − 7| = 1
P = 4, difference = |10 − 3| = 7

  Write a function: int solution(int A[], int N); that, given a
  non-empty zero-indexed array A of N integers, returns the minimal
  difference that can be achieved.

My solution to it is:

class Solution {
    public int solution(int[] A) {
        long minDiff = Integer.MAX_VALUE;
        long[] leftSums = new long[A.length];
        long totalSum = 0;

        //init
        totalSum += A[0];
        leftSums[0] += 0;  //whatever, don't use leftSums[0] anyway

        for (int i = 1; i < A.length; ++i) {
            totalSum += A[i];
            leftSums[i] += leftSums[i-1] + A[i-1];
        }

        for (int i = 1; i < A.length; ++i) {
            long diff = Math.abs(totalSum - 2 * leftSums[i]);
            if(diff < minDiff){
                minDiff = diff;
            }
        }

        return (int) minDiff;
    }
}

Correctness
I assume this is a toy problem and you don't need to worry about overflow/underflow? If you do, you should be using longs to do all your math, and either returning a long or casting back to an int before you return it.
Performance
You don't need to keep an array of all the left sums. You can get away with just two ints, one containing the sum of numbers on the left and the other containing the sum of numbers on the right. In your second loop, look at the ith element. Add it to the leftSum and subtract it from the rightSum. Use that to do your math.
General
This also cleans up the math you're doing. totalSum - 2 * leftSums[i] is not at all intuitive. Using Math.abs is nice. Using Math.min() would be even nicer.
Java variables start with lowercase letters. int[] A doesn't conform to that standard. Also, abbreviations should be avoided in variable names. minDiff would be better as minimumDifference, and diff would be better as difference.
If I were to code this, it would look something like:
public final class Summer {

    public int solve(final int[] values) {

        long leftSum = 0;
        long rightSum = 0;
        for (int i = 0; i < values.length; i++) {
            rightSum += values[i];
        }

        long minDifference = Integer.MAX_VALUE;
        for (int i = 0; i < values.length; i++) {
            leftSum += values[i];
            rightSum -= values[i];
            final long difference = Math.abs(leftSum - rightSum);
            minDifference = Math.min(minDifference, difference);
        }

        return (int) minDifference;
    }
}


Grouping Date Objects by year and month I have an array of date objects, which I want to group by year and month. The data structure I have chosen for my target is an array of arrays of Date objects.

Two Date objects should be in the same array if year AND month match up.

I'm supplying two extensions I added to Date and Formatter to easily extract year and month of a given date, as well as creating date objects more easily.

import Foundation

extension Formatter {

    static let year: DateFormatter = {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy"
        return formatter
    }()

    static let monthString: DateFormatter = {
        let formatter = DateFormatter()
        formatter.dateFormat = "LLL"
        return formatter
    }()

    static let monthInt: DateFormatter = {
        let formatter = DateFormatter()
        formatter.dateFormat = "LL"
        return formatter
    }()
}

extension Date {

    var monthString: String  { return Formatter.monthString.string(from: self) }
    var monthInt: Int { return Int(Formatter.monthInt.string (from:self))! }
    var yearInt: Int { return Int(Formatter.year.string(from: self))!}

    static func from(year: Int, month: Int, day: Int) -> Date {
        let gregorianCalendar = NSCalendar(calendarIdentifier: .gregorian)!

        var dateComponents = DateComponents()
        dateComponents.year = year
        dateComponents.month = month
        dateComponents.day = day

        let date:Date = gregorianCalendar.date(from: dateComponents)!
        return date
    }

    static func parse(_ string: String, format: String = "yyyy-MM-dd") -> Date {
        let dateFormatter = DateFormatter()
        dateFormatter.timeZone = NSTimeZone.default
        dateFormatter.dateFormat = format

        let date = dateFormatter.date(from: string)!
        return date
    }
}

I then created a helper class with a static method to encapsulate the functionality:

class DateArrayConversionHelper {

    static func sortDateByMonth(dateArray:[Date]) -> [[Date]] {

        //create a copy of input array and sort it

        var inputArray:[Date] = dateArray
        inputArray.sort()

        //create target data structure

        var resultArray:[[Date]] = [[]]

        //set initial variable and add it to target data structure

        resultArray[0].append(inputArray[0])
        var k = 0

        for i in 1 ..< (inputArray.count) {

            if (inputArray[i].yearInt == inputArray[i-1].yearInt)
                && (inputArray[i].monthInt == inputArray[i-1].monthInt) {
                    resultArray[k].append(inputArray[i])
                }
            else {
                    k = k+1
                    resultArray.append([])
                    resultArray[k].append(inputArray[i])
                }
        }

    return resultArray
    }
}

For testing:

let randomDates:[Date] = [Date.parse("2014-05-20"), Date.parse("2012-07-21"), Date.parse("2012-07-01"), Date.parse("2017-01-24"), Date.parse("2017-01-11"), Date.parse("2017-01-14"), Date.parse("2000-01-02"), Date.parse("2000-05-20")]

let resultData:[[Date]] = DateArrayConversionHelper.sortDateByMonth(dateArray: randomDates)

I'm looking for ways to improve my algorithm. I'm also still pretty new to Swift so if you're wondering why I didn't do/use x, it's usually because I didn't know better.

My end game is to use these arrays as a source for a UITableView.

I'll focus first on

static func sortDateByMonth(dateArray:[Date]) -> [[Date]]

because that contains the main logic, then mention some other points, and finally
present an alternative solution.

Your code seems to work correctly (as far as I can tell), with one exception: Apparently
it is assumed that the given array is not empty, and it will crash at

resultArray[0].append(inputArray[0])

otherwise. Adding

if dateArray.isEmpty {
    return []
}

right at the top of the function would solve that problem.
In

var inputArray:[Date] = dateArray
inputArray.sort()

the type annotation is not needed because the type can be inferred automatically:

var inputArray = dateArray
inputArray.sort()

But this can be shortened to

let inputArray = dateArray.sorted()

Similarly as above,

var resultArray:[[Date]] = [[]]
resultArray[0].append(inputArray[0])

can be combined to

var resultArray = [[inputArray[0]]]

In

for i in 1 ..< (inputArray.count) { ... }

the parentheses on the right are not needed. But I prefer

for i in inputArray.indices.dropFirst() { ... }

because that works for other collection types as well, where the index is not
necessarily zero-based (such as ArraySlice).
Inside the loop, the statement

        resultArray[k].append(inputArray[i])

appears twice, this can be improved to

for i in inputArray.indices.dropFirst() {
    if inputArray[i].yearInt != inputArray[i-1].yearInt
        || inputArray[i].monthInt != inputArray[i-1].monthInt {
        resultArray.append([])
        k += 1
    }
    resultArray[k].append(inputArray[i])
}

Accessing the count of an array is a O(1) operation, therefore one can get even
get rid of the variable k:

for i in inputArray.indices.dropFirst() {
    if inputArray[i].yearInt != inputArray[i-1].yearInt
        || inputArray[i].monthInt != inputArray[i-1].monthInt {
        resultArray.append([]) // Start new row
    }
    resultArray[resultArray.count - 1].append(inputArray[i])
}

Now let's try to make the date comparison simpler and more efficient. Your code
requires 4 calls to a format parsing method in each iteration. Generally, if you
are interested in the numerical values of the date components (such as year and
month number) then using

let yearAndMonth = calendar.dateComponents([.year, .month], from: inputArray[i])

is more efficient, it computes both numbers in a single call and gives you
integers instead of strings.

But here we can do even better: There is a dedicated Calendar method to check
if two dates are equal down to some specified component:

calendar.isDate(date1, equalTo: date2, toGranularity: .month)

so that the loop becomes

    let calendar = Calendar(identifier: .gregorian)
    for i in inputArray.indices.dropFirst() {
        if !calendar.isDate(inputArray[i-1], equalTo: inputArray[i], toGranularity: .month) {
            resultArray.append([]) // Start new row
        }
        resultArray[resultArray.count - 1].append(inputArray[i])
    }

This makes your extension Formatter and some of the extension Date
properties obsolete, at least for this application.

Note also that I used the Swift Calendar type instead of the Foundation NSCalendar
type.

One can even get rid of the index i in the above loop by iterating over
the inputArray and a shifted version of that array, and then the
complete function looks like this:

static func sortDateByMonth(dateArray:[Date]) -> [[Date]] {

    if dateArray.isEmpty {
        return []
    }

    let inputArray = dateArray.sorted()
    var resultArray = [[inputArray[0]]]

    let calendar = Calendar(identifier: .gregorian)
    for (prevDate, nextDate) in zip(inputArray, inputArray.dropFirst()) {
        if !calendar.isDate(prevDate, equalTo: nextDate, toGranularity: .month) {
            resultArray.append([]) // Start new row
        }
        resultArray[resultArray.count - 1].append(nextDate)
    }
    return resultArray
}

Now some additional remarks:

Setting the timezone to NSTimeZone.default is not needed because that is the default. On the other hand, it is
a good idea to set the locale to some well-defined value, such as "en_US_POSIX",
because otherwise the formatter behavior can depend on the user's regional settings
(see Technical Q&A QA1480 – NSDateFormatter and Internet Dates):

extension Date {

    static func parse(_ string: String, format: String = "yyyy-MM-dd") -> Date {
        let dateFormatter = DateFormatter()
        dateFormatter.locale = Locale(identifier: "en_US_POSIX")
        dateFormatter.dateFormat = format
        return dateFormatter.date(from: string)!
    }
}

Of course this will crash if the string does not match the provided date format.
An alternative is to define a (failable) initializer method:

extension Date {

    init?(_ string: String, format: String = "yyyy-MM-dd") {
        let dateFormatter = DateFormatter()
        dateFormatter.locale = Locale(identifier: "en_US_POSIX")
        dateFormatter.dateFormat = format
        guard let date = dateFormatter.date(from: string) else { return nil }
        self = date
    }
}

which can be used as

let date = Date("2014-05-20")

and the caller decides whether to force-unwrap the result, or to safely unwrap it
with optional binding.
Your

class DateArrayConversionHelper

is apparently used to provide a namespace for the static helper function.
If that is the only purpose and no instances of that type are ever created, then
a struct with a private init method:

struct DateArrayConversionHelper {
    private init() {}

    static func sortDateByMonth(dateArray:[Date]) -> [[Date]] { ... }
    // ... other helper methods ...
}

or a caseless enum

enum DateArrayConversionHelper {

    static func sortDateByMonth(dateArray:[Date]) -> [[Date]] { ... }
    // ... other helper methods ...
}

are good alternatives, compare for example
Swift constants: Struct or Enum
on Stack Overflow.

Finally an alternative approach, which might be simpler for the usage as
a table view data source.

The Dictionary(grouping:by:)
initializer (introduces in Swift 4)

  creates a new dictionary whose keys are the groupings returned by the given closure
  and whose values are arrays of the elements that returned each key.

and can in your case be used as

let calendar = Calendar(identifier: .gregorian)
let groupedDates = Dictionary(grouping: dateArray.sorted()) { (date) in
    return calendar.dateInterval(of: .month, for: date)?.start ?? Date.distantPast
}

This returns a dictionary of type [Date : [Date]] where each key is a date
representing a start of the month, and the corresponding values are the dates in
that month.

Then

let availableMonths = groupedDates.keys.sorted()

is an array of dates, each date representing the start of one month, this can be used to compute the number
of sections and the section titles.

For each month,

let datesInMonth = groupedDates[month]

is an array of dates in that month, this can be used to compute the number of rows in a section and for the
tableView(_:cellForRowAt:) method.


Get Elapsed Time as Human Friendly String In lieu with several other Facebook-esque concepts I am trying to replicate, this working code will take the span of time from a given date to now, and try to convert it into the most convenient English-friendly word. For example, if I post a comment on an article or status, and I want to show when it was posted to a user who views it, it would indicate something like "5 minutes ago", versus a date itself.

Concerns: Does this cover all possible use cases? Is it done optimally in the least lines of code?

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

namespace Schloss.Text
{
    public static class Date
    {
        public static string GetElapsedTime(DateTimeOffset datetime)
        {
            TimeSpan ts = DateTimeOffset.Now.Subtract(datetime);

            int years = ts.Days / 365;
            int months = ts.Days / 30;
            int weeks = ts.Days / 52;

            if (years == 1) // one year ago
                return "A year ago";

            if (years > 1) // greater than one year
            {
                if (ts.Days % 365 == 0) // even year
                    return (int)(ts.TotalDays / 365) + " years ago";
                else // not really entire years
                    return "About " + (int)(ts.TotalDays / 365) + " years ago";
            }

            if (months == 1) // one month
                return "About a month ago";

            if (months > 1) // more than one month
                return "About " + months + " months ago";

            if (weeks == 1) // a week ago
                return "About a week ago";

            if (weeks > 1) // more than a week ago, but less than a month ago
                return "About " + weeks + " weeks ago";

            if (ts.Days == 1) // one day ago
                return "Yesterday";

            if (ts.Days > 1) //  more than one day ago, but less than one week ago
                return ts.Days + " days ago";

            if (ts.Hours == 1) // An hour ago
                return "About an hour ago";

            if (ts.Hours > 1 && ts.Hours <= 24) // More than an hour ago, but less than a day ago
                return "About " + ts.Hours + " hours ago";

            if (ts.Minutes == 1)
                return "About a minute ago";

            if (ts.Minutes == 0)
                return ts.Seconds + " seconds ago";

            return ts.Minutes + " minutes ago";
        }
    }
}

Does this cover all possible use cases?

Maybe, but it doesn't calculate timespan components (year, month, etc) exactly.

  Is it done optimally in the least lines of code?

Probably no.
You could generalize check of different TimeSpan elements using the following approach:

private static string GetElapsedTime(DateTime datetime)
{
    TimeSpan ts = DateTime.Now.Subtract(datetime);

    // The trick: make variable contain date and time representing the desired timespan,
    // having +1 in each date component.
    DateTime date = DateTime.MinValue + ts;

    return ProcessPeriod(date.Year - 1, date.Month - 1, "year")
           ?? ProcessPeriod(date.Month - 1, date.Day - 1, "month")
           ?? ProcessPeriod(date.Day - 1, date.Hour, "day", "Yesterday")
           ?? ProcessPeriod(date.Hour, date.Minute, "hour")
           ?? ProcessPeriod(date.Minute, date.Second, "minute")
           ?? ProcessPeriod(date.Second, 0, "second")
           ?? "Right now";
}

private static string ProcessPeriod(int value, int subValue, string name, string singularName = null)
{
    if (value == 0)
    {
        return null;
    }
    if (value == 1)
    {
        if (!String.IsNullOrEmpty(singularName))
        {
            return singularName;
        }
        string articleSuffix = name[0] == 'h' ? "n" : String.Empty;
        return subValue == 0
            ? String.Format("A{0} {1} ago", articleSuffix, name)
            : String.Format("About a{0} {1} ago", articleSuffix, name);
    }
    return subValue == 0
        ? String.Format("{0} {1}s ago", value, name)
        : String.Format("About {0} {1}s ago", value, name);
}


Morse code encoder decoder I created this morse code encoder and decoder.

class DecodeError(BaseException):
    __module__ = Exception.__module__

class EncodeError(BaseException):
    __module__ = Exception.__module__

code_letter = {
    '.-': 'A', '-...': 'B', '-.-.': 'C', '-..': 'D', '.': 'E', '..-.': 'F', '--.': 'G',
    '....': 'H', '..': 'I', '.---': 'J', '-.-': 'K', '.-..': 'L', '--': 'M', '-.': 'N',
    '---': 'O', '.--.': 'P', '--.-': 'Q', '.-.': 'R', '...': 'S', '-': 'T', '..-': 'U',
    '...-': 'V', '.--': 'W', '-..-': 'X', '-.--': 'Y', '--..': 'Z',

    '.----': '1', '..---': '2', '...--': '3', '....-': '4', '.....': '5',
    '-....': '6', '--...': '7', '---..': '8', '----.': '9', '-----': '0',

    '--..--': ', ', '.-.-.-': '.', '..--..': '?', '-..-.': '/',
    '-....-': '-', '-.--.': '(', '-.--.-': ')', '/': ' '
}

letter_code = {value: key for key, value in zip(code_letter.keys(), code_letter.values())}

def morse_encode(string: str) -> str:
    try:
        return ' '.join(letter_code[i.upper()] for i in string)
    except:
        raise EncodeError('Unknown value in string')

def morse_decode(string: str) -> str:
    try:
        return ''.join(code_letter[i] for i in string.split())
    except:
        raise DecodeError('Unknown value in string')

if __name__ == '__main__':
    string = input()
    print(morse_encode(string))

Is it possible to make the code shorter while maintaining neatness?

Thanks!

Some suggestions:

I believe the idiomatic way to declare custom exceptions is to inherit from Exception rather than BaseException, and to just use the no-op pass as the class body. I've not seen the __module__ = Exception.__module__ pattern before, but if that does what it looks like (making the class effectively part of the exceptions module) that's probably going to be misleading. It's not a generic error, after all.
It might be faster to put both upper and lower case characters in the dict than to use upper(). You could test this with timeit.
If you're processing a big string of Morse code you might want to use an iterator. That way the string is processed one word at a time, rather than having to split the entire text into a list in memory before starting to output anything.
Rather than parsing input() I would expect this sort of script to either read standard input or to accept a list of file path arguments which would each be read and converted.
If the script also accepted --encode and --decode parameters (possibly with --encode as the default) it could easily be used to script a conversion of any text.


NumPy Scipy optimization I have an optimization issue and I'm not sure if I can improve the overall speed of my function.

The function draw_w is my actual implementation that gives me the right update for my vector w. You can see that the code is running for 1000 iterations in 9s.
I had a first implementation (draw_w_fw) that was quiet good because, well-vectorized, that is an order of magnitude quicker by 0.8s. Unfortunately, this implementation is wrong because the cache[0] is not updated correctly.

I would like to know if someone knows a way to speed up draw_w from what I've wrote.

import scipy.sparse as sps
import numpy as np
import timeit

def draw_w(X, w, cache):

    X = X.tocsr()

    for i in xrange(w.shape[0]):
        x_li = X.getrow(i)
        Y = w[i] * x_li
        Y.data -= np.take(cache[0], Y.indices)
        h = x_li.multiply(-Y)

        w_mean = h.sum()
        w_sigma_sqr = (x_li.multiply(x_li)).sum()

        w_sigma_sqr = 1.0 / w_sigma_sqr
        w_mean = - w_sigma_sqr * w_mean

        # update w:
        w_old = np.copy(w[i])

        if np.isinf(w[i]):
            w[i] = 0
        elif np.isnan(w[i]):
            w[i] = 0
        else:
            w[i] = w_mean

        # update error:
        cache[0] -= (w_old - w[i]) * x_li

    #print 'draw_w', w
    #True result w [ 2.34125626  2.37726446  4.00792293  3.71059779  4.00792293  0.11100713
    # -0.28899287 -0.04393113  0.21429929]

####################

def draw_w_fw(X, w, cache):

    x_li = X.tocsr()
    nnz_per_row = np.diff(x_li.indptr)
    Y = sps.csr_matrix((x_li.data * np.repeat(w, nnz_per_row), x_li.indices, x_li.indptr), shape=x_li.shape)
    Y.data -= np.take(cache[0], Y.indices)   #not good because cache[0] is updated...
    h = x_li.multiply(-Y)

    w_mean = np.asarray(h.sum(axis=1).transpose())[0]
    w_sigma_sqr = np.asarray(( x_li.multiply(x_li) ).sum(axis=1).transpose())[0]

    w_sigma_sqr = 1.0 / w_sigma_sqr
    w_mean = - w_sigma_sqr * w_mean

    # update w:
    w_old = np.copy(w)

    w[~np.isnan(w) & ~np.isinf(w)] = w_mean[~np.isnan(w) & ~np.isinf(w)]

    w[np.isinf(w)] = 0.0
    w[np.isnan(w)] = 0.0

    # update error:
    cache[0] -= (w_old - w) * x_li

    #print 'draw_w_fw', w

##########################

def test():

    data = [ 1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.]
    cols = [ 0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,14,14]
    rows = [0,5,1,5,2,5,3,5,4,5,0,6,1,6,2,6,3,6,4,6,1,7,3,7,0,8,2,8,4,8]

    X = sps.coo_matrix((data, (rows, cols)), shape = (9,15))
    X = X.tocsr()

    w = np.array([ 0.16243454, -0.06117564, -0.05281718, -0.10729686,  0.08654076, -0.23015387,  0.17448118, -0.07612069,  0.03190391])

    cache = np.zeros((2, 15))
    cache[0] =  np.asarray([-5.06771933, -5.29132951, -4.28297104, -1.33745073, -2.14361311, -0.66308429,
     -0.88669446, -2.878336,  -4.93281569, -4.73897806, -1.13729633, -5.18341755,
     -0.80566155, -5.02091327, -4.88155533])
    #draw_w(X, w, cache)
    draw_w_fw(X, w, cache)

if __name__ == '__main__':
    print(timeit.timeit("test()", setup="from __main__ import test", number=1000))
    #draw_w:    9.26 for 1000 iterations
    #draw_w_fw: 0.80 for 1000 iterations

Before streamlining the code, it almost always pays off to streamline the math. The h you calculate is the dot product of two vectors, X[i] and Y[i] = cache[0] - w[i]*X[i], so we can rewrite it as

h = X[i].cache[0] - w[i]*X[i].X[i]

When you go on to calculate w_mean, you are actually negating h and then dividing it by a number that turns out to be X[i].X[i], so you can calculate w_mean as

w_mean = w[i] - X[i].cache[0] / X[i].X[i]

Setting aside the np.isnan and np.isinf checks you are doing, you then update cache[0] with a value where w[i] cancels out, and you are basically doing:

cache[0] -= X[i] * (X[i].cache[0] / X[i].X[i])

Putting it all together into a single function, I got this very compact code:

from numpy.lib.stride_tricks import as_strided

def draw_w_bis(X, w, cache):
    X = X.tocsr()
    x_rows_sqr = np.add.reduceat(X.data*X.data, X.indptr[:-1])
    rows, cols = X.shape
    row_start_stop = as_strided(X.indptr, shape=(rows, 2),
                                strides=2*X.indptr.strides)
    for row, (start, stop) in enumerate(row_start_stop):
        data = X.data[start:stop]
        cols = X.indices[start:stop]
        delta = np.dot(data, cache[0, cols]) / x_rows_sqr[row]
        w[row] -= delta
        cache[0, cols] -= delta * data

If you are not comfortable with calling as_strided you could replace the definition of row_start_stop with:

row_start_stop = np.column_stack((X.indptr[:-1], X.indptr[1:]))

On my system your test code runs the 1000 iterations over an order of magnitude faster (6 sec vs. 0.4 sec) which seems to be what you were after. There still is a for loop in there, so if you are going to run this on large arrays, it is still going to be slow, and you may want to consider using things like Cython.


Best practice for Constant Class in Java I create a constant class by looking at some of the best practices described here in stackoverflow. Many of those have a single Constant class with variables. Some of the answers suggested creating separate Contant Classes. The way I create a constant class is by naming it Parameters and creating classes i.e. Variables and Constants. Then these classes further have child classes e.g. URL, Columns etc. This time I created a constant class with same structure and a separate class named ReportTemplate. This is my first time creating a Constant class of Objects that don't have a primitive datatype.

public final class ReportTemplate {

    public final static class ColumnIds {
        public static final String TITLE_COLUMN_ID = "title";
        public static final String TYPE_COLUMN_ID = "type";
        public static final String LIFECYCLESTATUS_COLUMN_ID = "lifecyclestatus";
        public static final String INSERTIONTIMESTAMP_COLUMN_ID = "insertionTimestamp";
    }

    public final static class Columns {
        public static final TextColumnBuilder<String> TITLE = col.column(
                "Title", ColumnIds.TITLE, type.stringType());

        public static final TextColumnBuilder<String> LIFECYCLESTATUS = col.column(
                "Lifecycle Status", ColumnIds.LIFECYCLESTATUS,
                type.stringType());

        public static final TextColumnBuilder<String> TYPE = col.column("Type",
                ColumnIds.TYPE, type.stringType());

        public static final TextColumnBuilder<String> INSERTIONTIMESTAMP = col
                .column("Insertion Timestamp",
                        ColumnIds.INSERTIONTIMESTAMP,
                        type.stringType());
    }

    public final static class Styles {
        public static final StyleBuilder HEADING1 = stl.style()
                .setName("heading1").bold().setFontSize(15);

        public static final StyleBuilder HEADING2 = stl.style().setName("heading2")
                .bold().setFontSize(12);

        public static final StyleBuilder HEADING3 = stl.style().setName("heading3")
                .bold().setFontSize(10);
    }

}

I want to know if my

Naming Scheme is correct
Constant class structure is among best practices.
Should I create separate constant classes or having them encapsulated in a parent Constant class is fine?

Edit: April 19, 2016

I have accpeted an answer but i would like more suggestions anytime.

Thank you.

Answer to your questions :

Naming Scheme is correct? -

Ideally you should not create class with names like Variables, Parameters, etc. as these names also has literal meanings with them in many languages. Besides that, these classes are going to store Constants! You can simply create single class with name Constants! No need to create different Constant classes till it's absolutely necessary. Perhaps, in that case you should go for enums. Why? Check these links :

Link 1.
Link 2

Constant class structure is among best practices ?

This is answered in above point. Keep your naming convention readable enough so that you won't require separate constant classes.
Always try to implement KISS(Keep it Simple Stupid) and DRY(Don't repeat yourself!)

Should I create separate constant classes or having them encapsulated in a parent Constant class is fine?

Ideally not. If you need such requirement then go for enums. As enums are typesafe, you wont end up creating misleading statements. For ex.
If you write following potentially incorrect code then Constant class won't mind:

String playerType = Constants.MALE;

But, if you use enums, that would end up as:

// Compile-time error - incompatible types!
PlayerType playerType = Gender.MALE;


Implementing use of 'with CustomClass() as foo' in own class with DB-Connection I'm building a GameClient-Class in Python which handles user input and has to read from a database (MongoDb). I want to know if that is the best practice to implement it, so that I can use it with Python's with statement.

Because I want to use different functions of my Client class, __enter__ has to return self, so that I can use the instance of that class like normal. Is that best practice?

class Client(object):

    def __init__(self, playerid):
        self.MongoClient = MongoClient()
        self.db = self.MongoClient['worldbg-database']
        self.id = playerid

    def __exit__(self, exception_type, exception_val, trace):
        self.MongoClient.close()

    def __enter__(self):
        return self

    def handle_input(self, input):
    if input == "exit":
        return False

with Client("id") as GameClient:
    GameClient.select_my_tile(GameClient.get_my_tiles()[0]['_id'])
    while GameClient.handle_input(raw_input('command: ')):
        pass

The reason to use a with clause is 1) clarity and 2) exception handling. Clarity because you have explicitly called out "right here, I am working with the object" and exception handling because you are guaranteed to have the exit handler called and any cleanup accomplished.

Canonical examples are:

with open(filename, "w") as fp:
    data = generate_some_data()
    fp.write(data)
    data2 = more_generation()
    fp.write(data2)

with lock:
    # all code in here is locked

You don't provide a lot of information about what you intend to accomplish in the with clause in your code. Typically the with block is not too long and focused on a task. If Client is meant to represent a player then you are probably putting the abstraction in the wrong place. A GameClient class could contain a DBConnection object. This way you could mock out the DB for testing for instance. Or switch to another DB type. If you meant Client to be DBClient I would rename it.


Quicksort implementation equivalent to Collections.sort() Here is my go at understanding generics, Comparables and Comparators, as well as type bounds. I believe I made it as close to Collections.sort as possible in terms of interface. Please review.

import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Random;

public class QuickSort {
    private static final Random rng = new Random();

    public <T extends Comparable<? super T>> void sort(List<T> xs) {
        sort(xs, 0, xs.size() - 1);
    }

    public <T> void sort(List<T> xs, Comparator<? super T> cmp) {
        sort(xs, 0, xs.size() - 1, cmp);
    };

    private static <T extends Comparable<? super T>>
    void sort(List<T> xs, int fst, int lst) {
        sort(xs, fst, lst, (x, y) -> x.compareTo(y));
    }

    private static <T>
    void sort(List<T> xs, int fst, int lst, Comparator<? super T> cmp) {
        if (fst >= lst) return;

        int i = fst, j = lst;

        T pivot = xs.get(rng.nextInt(xs.size()));

        while (i <= j) {
            while (cmp.compare(xs.get(i), pivot) < 0)
                i++;
            while (cmp.compare(pivot, xs.get(j)) < 0)
                j--;

            if (i <= j)
                Collections.swap(xs, i++, j--);
        }

        sort(xs, fst, j, cmp);
        sort(xs, i, lst, cmp);
    }
}

As far as your understanding of generics, I think you've pretty much got it.

On other matters:

(x, y) -> x.compareTo(y) - that can be reduced to a function reference Comparable::compareTo.  In this specific case, it's also available to you as Comparator.naturalOrder()
You should double check your random number generator for getting your pivot.  It looks to me like you're taking a pivot element from anywhere in the list, not in the sublist that you're sorting.


Is this code for getting the dependency tree of a file correct? function dep_tree(graph,node,prev_deps){
    return uniq(flatten(graph[node].map(function(child_node){
        if (contains(prev_deps,child_node))
            throw "Circular reference between "+child_node+" and "+node;
        return dep_tree(graph,child_node,prev_deps ? prev_deps.concat(node) : [node])
    })).concat(node));
};

graph is an object such as {a:[],b:["a"],c:[],d:["b","c"]}, that links a file, ex: "d" to it's dependencies "b" "c".
file is the the node to search.
prev_deps is internal, to keep track of visited nodes

The function returns the full dependency tree of that node. For example, dep_tree(that_obj_above,"d") = ["b","c","a"]. Is this code correct, overall? Is it correctly checking for circular dependencies? Is there a name for what I'm doing?

Not a lot of code to review,

To reduce confusion, I would use _.uniq() rather than point straight to uniq()
lowerCamelCase is preferred, child_node -> childNode
dep_tree is unfortunate, I like recursiveDependencies better
I would have set prev_deps = prev_deps || []; prior to return, it would make your recursive call less golfic:

return dep_tree(graph,child_node, prev_deps.concat(node) )


Is this program susceptible to a buffer overflow exploit? I use it in a number of embedded devices. It loads the query parameters from an HTTP GET/POST request and prints them to stdout in FORM_key=value format which then get set as an environment variable.

Source:

char *
FP_strdup (char *string)
{
  char *result;

  if (string == NULL)
    return NULL;

  if ((result = (char *) malloc (strlen (string) + 1)) == NULL) {
    fprintf (stderr, "proccgi -- out of memory dupping %d bytes\n",
         (int) strlen (string));
    return NULL;
  }

  strcpy (result, string);
  return result;
}

/*
 * Read CGI input
 */

char *
LoadInput (void)
{
  char *result, *method, *p;
  int length, ts;

  if ((method = getenv ("REQUEST_METHOD")) == NULL) {
    return NULL;
  }

  if (strcmp (method, "GET") == 0) {
    if ((p = getenv ("QUERY_STRING")) == NULL)
      return NULL;
    else
      result = FP_strdup (p);
  }
  else if (strcmp (method, "POST") == 0) {
    if ((length = atoi (getenv ("CONTENT_LENGTH"))) == 0)
      return NULL;

    if ((result = malloc (length + 1)) == NULL) {
      fprintf (stderr, "proccgi -- out of memory allocating %d bytes\n",
           length);
      return NULL;
    }

    if ((ts = fread (result, sizeof (char), length, stdin)) < length) {
      fprintf (stderr, "proccgi -- error reading post data, %d bytes read, %d expedted\n",
           ts, length);
    }
    result[length] = '\0';
  }
  else {
    return NULL;
  }

  return result;
}

/*
 * Parse + and %XX in CGI data
 */

char *
ParseString (char *instring)
{
  char *ptr1=instring, *ptr2=instring;

  if (instring == NULL)
    return instring;

  while (isspace (*ptr1))
    ptr1++;

  while (*ptr1) {
    if (*ptr1 == '+') {
      ptr1++; *ptr2++=' ';
    }
    else if (*ptr1 == '%' && isxdigit (*(ptr1+1)) && isxdigit (*(ptr1+2))) {
      ptr1++;
      *ptr2    = ((*ptr1>='0'&&*ptr1<='9')?(*ptr1-'0'):((char)toupper(*ptr1)-'A'+10)) << 4;
      ptr1++;
      *ptr2++ |= ((*ptr1>='0'&&*ptr1<='9')?(*ptr1-'0'):((char)toupper(*ptr1)-'A'+10));
      ptr1++;
    }
    else
      *ptr2++ = *ptr1++;
  }
  while (ptr2>instring && isspace(*(ptr2-1)))
    ptr2--;

  *ptr2 = '\0';

  return instring;
}

/*
 * break into attribute/value pair. Mustn't use strtok, which is
 * already used one level below. We assume that the attribute doesn't
 * have any special characters.
 */

void
HandleString (char *input)
{
  char *data, *ptr, *p2;

  if (input == NULL) {
    return;
  }

  data = FP_strdup   (input);
  ptr  = ParseString (data);

  /*
   * Security:
   *
   * only accept all-alphanumeric attributes, and don't accept empty
   * values
   */

  if (!isalpha(*ptr) && *ptr != '_') {free (data); return;}
  ptr++;
  while (isalnum(*ptr) || *ptr == '_') ptr++;
  if (*ptr != '=') {free (data); return;}

  *ptr = '\0';
  p2 = ptr+1;

  fprintf (stdout, "FORM_%s=\"", data);

  /*
   * escape value
   */

  while (*p2) {
    switch (*p2) {
    case '"': case '\\': case '`': case '$':
      putc ('\\', stdout);
    default:
      putc (*p2,  stdout);
      break;
    }
    p2++;
  }
  putc ('"',  stdout);
  putc ('\n', stdout);
  *ptr = '=';
  free (data);
}

int
main (int argc, char *argv[])
{
  char *ptr, *data = LoadInput();
  int i;

  /*
   * Handle CGI data
   */

  if (data) {
    ptr = strtok (data, "&");
    while (ptr) {
      HandleString (ptr);
      ptr = strtok (NULL, "&");
    }
    free (data);
  }

  /*
   * Add Path info
   */

  if (getenv ("PATH_INFO") != NULL) {
    data = FP_strdup (getenv ("PATH_INFO"));
    ptr = strtok (data, "/");
    while (ptr) {
      HandleString (ptr);
      ptr = strtok (NULL, "/");
    }
    free (data);
  }

  /*
   * Add args
   */

  for (i=1; i<argc; i++) {
    HandleString (argv[i]);
  }

  /*
   * done
   */

  return 0;
}

Your program parses the Content-Length header and stores its value in an int called length:

length = atoi (getenv ("CONTENT_LENGTH")))

Then it increments this value and uses it as the argument of a call to malloc():

result = malloc (length + 1))

Suppose I were to post 232−1 bytes of data to your program (about 4 GB in other words). If it's running in a 32-bit environment, the value of length + 1 will overflow to zero. The subsequent call to malloc() will probably succeed, but the call to fread() will crash the program immediately.


Collect several API call results Want to brush up my rusty web dev skills. I want to call the twitch API for several channels and eventually call a callback function when all results are in without using a sync call.

I didn't work with JavaScript for a long time, so I'm not sure if my solution is a good way, especially how I figure out if the callback function should be called.

var Twitch = function() {
    var baseUrl = 'https://api.twitch.tv/kraken/streams/';
    var channels = ["freecodecamp", "storbeck", "terakilobyte", "habathcx", "RobotCaleb", "thomasballinger", "noobs2ninjas", "beohoff"];

    this.update = function(callback) {
        var result = {};
        for (var i = 0; i < channels.length; i++) {
            var qUrl = baseUrl + channels[i];
            var name = channels[i];
            $.getJSON(qUrl, success(name, result, callback));
        }
    }

    function success(name, result, callback) {
        return function(data) {
            result[name] = data;
            if (results.length == channels.length) {
                callback(result);
            }
        }
    }
};

I suppose this code is used like:

var twitch = new Twitch();
twitch.update(function(){
  // called each time a site responds
});

A few things:

First, I see little benefit of this functionality being written using a constructor. It appears to be a singleton by functionality as it makes no sense spawning multiple instances. Consider a singleton instead:

var Twitch = (function(){

  // stuff

  return {
    update: function(){...}
  };

}());

Next is your AJAX. As pointed in the comments, use $.when to listen to multiple jqXHR objects and call the callback once everyone is resolved. The native counterpart to $.when is Promise.all.

Next is to make update return a promise instead of handing it a callback. This way, your caller is allowed to listen not only for the success but also the failures.

Next is to take advantage of array methods like map instead of loops.

Your code could be simplified into:

var Twitch = (function(){

  var baseUrl = 'https://api.twitch.tv/kraken/streams/';
  var channels = ["freecodecamp", "storbeck", "terakilobyte", "habathcx", "RobotCaleb", "thomasballinger", "noobs2ninjas", "beohoff"];

  return {
    update: function(){
      var promises = channels.map(function(channel){
        return $.getJSON(baseUrl + channel).then(function(data){
          var result = {};
          result[channel] = data;
          return result;
        });
      });

      return $.when.apply(null, promises).then(function(){
        var args = Array.prototype.slice.call(arguments);
        return args.reduce(function(results, result){
          return $.extend(results, result);
        }, {});
      });
    }
  };

}());

// Usage
Twitch.update().then(function(results){
  // Succeeded
}, function(){
  // Failed
});

Now if you have ES6 available (via transpiler, or a modern browser), this can be simplified further by using the new syntax and making it more compact.

var Twitch = (function(){

  var baseUrl = 'https://api.twitch.tv/kraken/streams/';
  var channels = ["freecodecamp", "storbeck", "terakilobyte", "habathcx", "RobotCaleb", "thomasballinger", "noobs2ninjas", "beohoff"];

  return {
    update(){
      var promises = channels.map(channel => {
        return $.getJSON(`${baseUrl}${channel}`)
                .then(data => ({[channel]: data}));
      });

      return Promise.all(promises)
                    .then((...args) => args.reduce((results, result) => Object.assign(results, result), {}));
    }
  };

}());

// Usage
Twitch.update().then(function(results){
  // Succeeded
}, function(){
  // Failed
});


Number letter counts I'm trying to become more proficient in Python and have decided to run through the Project Euler problems.

In any case, the problem that I'm on (17) wants me to count all the letters in the English words for each natural number up to 1,000. In other words, one + two would have 6 letters, and so on continuing that for all numbers to 1,000.

I wrote this code, which produces the correct answer (21,124). However, I'm wondering if there's a more pythonic way to do this.

I have a function (num2eng) which translates the given integer into English words but does not include the word "and".

for i in range (1, COUNTTO + 1):
    container = num2eng(i)
    container = container.replace(' ', '')
    print container
    if i > 100:
        if not i % 100 == 0:
            length = length + container.__len__()  + 3 # account for 'and' in numbers over 100
        else:
            length = length + container.__len__()
    else:
        length = length + container.__len__()
    print length

There is some repetition in my code and some nesting, both of which seem un-pythonic.

I'm specifically looking for ways to make the script shorter and with simpler loops; I think that's my biggest weakness in general.

Here are a few things:

container.__len__() – You should never call magic methods directly. Just use len(container).
As you don’t know to what amount you need to increment (i.e. your COUNTTO), it would make more sense to have a while loop that keeps iterating until you reach your final length result:

while length < 1000:
     # do stuff with i
     length += # update length
     i += 1

You could also make use of itertools.count:

length = 0
for i in itertools.count(1):
    length += # update length
    if length > 1000:
        break

not i % 100 == 0 – When you already have a operator (==) then don’t use not to invert the whole condition, but just use the inverted operator: i % 100 != 0
Also having additional counting logic outside of your num2eng does not seem to be appropriate. What does that function do exactly? Shouldn’t it rather produce a real number using a complete logic? Ideally, it should be as simple as this:

length = 0
for i in itertools.count(1):
    length += len(num2eng(i))
    if length > 1000:
        break


Double buffering Gdiplus and GDI I have this working code and was wondering how I can optimize it. Is there anything I can declare globally so it does not need to be be created over and over? This function is called around 30 times a second.

bmScreenBuffer is a global Bitmap.

Contents of drawScreen():

// Buffer - Get the main window handle to create 2 dcs (device contexed)
HWND hwndMain = programInfoPtr->hWnd;
HDC hdcMain = GetDC(hwndMain);
HDC hdcBuffer = CreateCompatibleDC(hdcMain);

// Current buffer and old
HBITMAP hbm_Buffer = CreateCompatibleBitmap(hdcMain, bmScreenBuffer->GetWidth(), bmScreenBuffer->GetHeight());
HBITMAP hbm_oldBuffer = (HBITMAP)SelectObject(hdcBuffer, hbm_Buffer);

// Tells GDI+ to draw to the "GDI" DC
Graphics* g = new Graphics(hdcBuffer);
g->DrawImage(bmScreenBuffer, 0, 0);

// Now copy the image to the screen
BitBlt(hdcMain, 0, 0, bmScreenBuffer->GetWidth(), bmScreenBuffer->GetHeight(), hdcBuffer, 0, 0, SRCCOPY);

// Clean Up
ReleaseDC(hwndMain, hdcMain);
SelectObject(hdcBuffer, hbm_oldBuffer);
DeleteDC(hdcBuffer);
DeleteObject(hbm_Buffer);
delete g;

There's probably a faster way to grab the display like with DirectX or something. WinGDI (BitBlt) is probably pretty slow.
GetDC has no effect on class or private DCs, so it is always sensible to call ReleaseDC after GetDC.
Watch out GetClassInfoEx function.
HBITMAP hbm_Buffer = CreateCompatibleBitmap(hdcMain, bmScreenBuffer->GetWidth(), bmScreenBuffer->GetHeight());: assuming your machine is running in 32-bit color, this generates a 32-bit bitmap (ie: compatible with the current display). Don't use CreateCompatibleBitmap here. Use CreateBitmap instead. Also note that you no longer really need hdcMain for this.
Remember that the Graphics class itself is a managed object and it will be garbage collected sooner or later. This class also uses unmanaged memory, the garbage collector doesn't "see" that memory and doesn't know that the actual memory used by the Graphics class may be much higher than the size of a Graphics instance. But fortunately you did it correctly: it's better to delete such objects as soon as you no longer need them, deleting will free any unmanaged memory or any other resources like opened files.


Echoing student ranks I echo a rank of a student whose regd is equal to $regd. In fact, this is working code. However, I was advised by a friend that the MySQL statements Distinct and Group By should not be used together. But as a newbie, I could not figure out how I could implement it without using Distinct because it does not return rows without Distinct.

Can anyone suggest how I can improve this code?

<?php
mysql_select_db($database_dbconnect, $dbconnect);
$query_myrank = "SELECT Distinct regd, Name_of_exam,
                    Name_of_Student, TOTALSCORE, Rank
             FROM (SELECT *, IF(@marks = (@marks := TOTALSCORE),
                          @auto, @auto := @auto + 1) AS Rank
                   FROM (SELECT Name_of_Student, regd,
                               Name_of_exam, SUM(Mark_score) AS TOTALSCORE
                         FROM cixexam, (SELECT @auto := 0,
                                               @marks := 0) AS init
                                        GROUP BY regd
                         ORDER BY TOTALSCORE DESC) t) AS result
             HAVING (Name_of_exam='First Terminal Exam' OR
                     Name_of_exam='First Term Test')";

$myrank = mysql_query($query_myrank, $dbconnect) or die(mysql_error());

$i = 0;
$j = 0;
$data = array();
while($row_myrank = mysql_fetch_assoc($myrank))
{
   $data[$i] = $row_myrank;
   if(isset($data[$i - 1])
        && $data[$i - 1]['TOTALSCORE'] == $data[$i]['TOTALSCORE'])
{
   $data[$i]['Rank'] = $j;
   }else{
     $data[$i]['Rank'] = ++$j;
}
   $i++;
}
foreach($data as $key => $value)
{
 if($value['regd'] == $regd)
    {
    echo $value['Rank'];
    }
  }
 ?>

Since you use it in a subquery, I don't see the problem. If you used both in the same query, that would be redundant. But the subquery needs to use it to obtain the required data.

Did the person give a reason as to why he/she thinks this, or was it simply a general statement?

The only thing I can think of is that DISTINCT is rather slow compared to GROUP BY: stackoverflow.com/questions/1887953/


Swap the names/properties in a JavaScript object Is there a more elegant way to do this in JavaScript?

function swapKey(obj, oldKey, newKey) {
  if (obj[oldKey]) {
    obj[newKey] = obj[oldKey];
    delete obj[oldKey];
  }
  return obj;
}

(I understand that it mutates the original object and is not functional and makes the returning of obj somewhat redundant and that's okay for this particular question.)

So the idea is to change the key of a given pair. Few issues:

Your code doesn't guard against existing keys. If my newKey is an already existing key, it would overwrite the existing value, and delete the old key.
Like mentioned, mutation. Unless you're fully aware of the things that reference the object or have mechanisms in place to capture suddenly missing properties, you shouldn't mutate in-place. In the case above, if you accidentally delete an existing key another piece of code expects to exist, this will cause unexpected breakage.
Your condition will return true for prototype members. Always do a hasOwnProperty check to ensure that you're only checking the instance, not the prototype.


Hangman game in Ruby I'm just a few months in learning to code and never had my code reviewed.
Is this class structure ok? Should I split it differently? How is the code overall?

require "json"
class Hangman

  def initialize
    @secret_word = select_word
    @display_content = "_" * @secret_word.length
    @failed_attemps = 0
  end

  def main_menu
    option = "3"
    until option == "1" || option == "2"
      puts "(1) New game"
      puts "(2) Load game"
      print "Play new game or load the saved game? "
      option = gets.chomp[0]
      if option == "2"
        if File.exist?("saved_state.json")
          load_state
        else
          puts "There is no saved game, save one first"
          option = "3"
        end
      end
    end
    start_game
  end

  private

  def save_state
    json_object = {
      :secret_word => @secret_word,
      :display_content => @display_content,
      :failed_attemps => @failed_attemps
    }.to_json
    File.open("saved_state.json", "w") { |file| file.write(json_object) }
  end

  def load_state
    save_file = File.read("saved_state.json")
    json_hash = JSON.parse(save_file)
    @secret_word = json_hash["secret_word"]
    @display_content = json_hash["display_content"]
    @failed_attemps = json_hash["failed_attemps"]
  end

  def start_game
    player_won = false
    while @failed_attemps != 10
      puts @display_content
      puts "#{10 - @failed_attemps.to_i} turns left"
      print "Enter a letter or attempt the full word: "
      letters = gets.chomp
      if letters == "save"
        save_state
        next
      end
      break if letters == "exit"
      update_display(letters) if letters
      player_won = player_won?
      break if player_won
    end
    puts "Game over, the secret word was: #{@secret_word}" if @failed_attemps == 10
  end

  def select_word
    words = File.readlines("5desk.txt").select { |word| word.length.between?(5, 12) }
    words[rand(words.length)].strip
  end

  def update_display(letters)
    letters.downcase!
    current_state = "#{@display_content}"
    if letters.length == 1
      @display_content.length.times do |index|
        @display_content[index] = letters if @secret_word[index].downcase == letters
      end
    else
      @display_content = letters if letters == @secret_word.downcase
    end

    current_state == @display_content ? print_toon(1) : print_toon(0)
  end

  def player_won?
    unless @display_content.include?("_")
      puts "You found the correct word!"
      true
    end
  end

  def print_toon(increment)
    @failed_attemps += increment

    case @failed_attemps
    when 0
      puts "  ______"
      puts "        |"
      puts "        |"
      puts "        |"
      puts "        |"
    when 1
      puts "  ______"
      puts " |      |"
      puts "        |"
      puts "        |"
      puts "        |"
    when 2
      puts "  ______"
      puts " |      |"
      puts "(oo)    |"
      puts "        |"
      puts "        |"
    when 3
      puts "  ______"
      puts " |      |"
      puts "(oo)    |"
      puts " |      |"
      puts "        |"
    when 4
      puts "  ______"
      puts " |      |"
      puts "(oo)    |"
      puts " ||     |"
      puts "        |"
    when 5
      puts "  ______"
      puts " |      |"
      puts "(oo)    |"
      puts "/||     |"
      puts "        |"
    when 6
      puts "  ______"
      puts " |      |"
      puts "(oo)    |"
      puts "/||\\    |"
      puts "        |"
    when 7
      puts "  ______"
      puts " |      |"
      puts "(oo)    |"
      puts "/||\\    |"
      puts "/       |"
    when 8
      puts "  ______"
      puts " |      |"
      puts "(oo)    |"
      puts "/||\\    |"
      puts "/  \\    |"
    when 9
      puts "  ______"
      puts " |      |"
      puts "(ox)    |"
      puts "/||\\    |"
      puts "/  \\    |"
    when 10
      puts "  ______"
      puts " |      |"
      puts "(xx)    |"
      puts "/||\\    |"
      puts "/  \\    |"
    end
    puts ""
  end

end

my_game = Hangman.new
my_game.main_menu

It looks good and is readable.

A few notes :

current_state = "#{@display_content}" could be written current_state = @display_content.clone
words[rand(words.length)].strip could be words.sample.strip
select { |word| word.length.between?(5, 12) } will select words with a length between 4 and 11 due to the newline.
It would be nice to have some more feedback:

when the game has been successfully saved
when the game has been loaded, what the drawing looks like
when the last letter has been guessed, what the complete word was. Here's an example output:

_u_ar_
4 turns left
Enter a letter or attempt the full word: s
  ______
 |      |
(oo)    |
/||\    |
        |

su_ars
4 turns left
Enter a letter or attempt the full word: g
  ______
 |      |
(oo)    |
/||\    |
        |

You found the correct word!

You could replace the whole case;when statement with an array of strings.

Keep up the good work!


Hash Tables: Ransom Note - Hacker Rank in Javascript I'm preparing for an interview doing the preparation questions on Hacker Rank and I want to become better at this. Is it possible to get some feedback on this? How can I improve my code? How did you solve this question?

function getCount(array){
    let counts = {}
    for(let word of array){
        let count = counts[word]
        counts[word] = count ? counts[word] + 1: 1;
    }
    return counts
}
// Complete the checkMagazine function below.

function compareNoteMag(note,mag){
    let noteKeys = Object.keys(note)
    let string = 'Yes'
    for(let key of noteKeys){
        if(!mag[key]) string = 'No'
        if(mag[key] < note[key]){
            string = 'No'
        }
    }
     console.log(string)
}

function checkMagazine(magazine, note) {
    let magazineCount = getCount(magazine);
    let noteCount = getCount(note);
    compareNoteMag(noteCount,magazineCount)
};

Performance

There are several performance issues in the posted code:

The loop over noteKeys continues even after it knows that a word is missing. It should stop.
The map of counts of words in the magazine is unnecessary internal storage. A likely question for discussion during an interview is "what if the magazine doesn't fit in memory, how would you change your implementation?". Food for thought.

Program organization

It's best when a function does one thing.
compareNoteMag does two: computes if there are enough words in the magazine, and prints "Yes" or "No".
This should have been a function returning boolean,
with an appropriate descriptive name.

Safety

The second if should have been an else if here:

if(!mag[key]) string = 'No'
if(mag[key] < note[key]){
    string = 'No'
}

Not only this is inefficient (the second if is sometimes evaluated unnecessarily), the expression in the second if is sometimes a comparison between undefined and a number, which can be confusing and lead to mistakes.

Naming

Some of the names could be better:

getCount returns a map of counts (plural), so I would rename to getCounts (plural).
getCount takes an array of words: words would be a natural and intuitive name instead of array.
compareNoteMag computes the answer to print: answer would be a natural and intuitive name instead of string.

Technique

Instead of this:

let count = counts[word]
counts[word] = count ? counts[word] + 1: 1;

A common technique in JavaScript:

counts[word] = (counts[word] || 0) + 1;

Attention to detail

This is very minor, but I notice some sloppiness:

Semicolons are mostly omitted but not always
The semicolon is unnecessary at the end of function checkMagazine(...) { ... };
The comment // Complete the checkMagazine function below. should not be there
The common convention is to put spaces around the parentheses in for(...){ and if(...){


Prepending a string to alternate elements in a Python tuple So I have this piece of Python code that essentially takes a tuple, then modifies the second (and every other) element by prepending a string to it.  Unfortunately the only way I can think to do it is convert it to a list (as tuples are immutable), step through, edit and then convert back to a tuple.

It works so I can't put it on SO but it's ugly and I'm sure there's a more Pythonic way to do this using slices or something.

def prependPackageToEnpoints(urls, packageName):
    """Take web.py formatted url/endpoint tuples and prepend
    a packageName to each of the endpoints, e.g.
    ('/Test/(.*)', 'test') becomes ('/Test/(.*)', 'Test.test')"""
    lst = list(urls)
    for i in xrange(1, len(lst), 2):
        lst[i] = packageName + "." + lst[i]
    t = tuple(lst)

    return t

I don't get to decide what the structure is, I'm using web.py and the structure it uses is a tuple.

What's the prettiest, and perhaps the most efficient way to do something like this in Python?

There may be other ways to do it, but none that I can think of that stands out as being better than what you wrote.  You could tighten up the code by adhering to PEP 8 naming conventions (use lower_case_with_underscores) and eliminating the variable t.

All I can offer is my condolences for being stuck with this stupid interface.  Note that the first thing that webpy does, as you might expect, is split up the tuple into pairs, using their own utils.group() function.

class application:
    def __init__(self, mapping=(), fvars={}, autoreload=None):
        if autoreload is None:
            autoreload = web.config.get('debug', False)
        self.init_mapping(mapping)
        …

 def init_mapping(self, mapping):
    self.mapping = list(utils.group(mapping, 2))


Electricity Calculator This is a calculator for Ohm's Law and Power Law. It works but I'd like some suggestions on making the code look a little cleaner, or run more efficiently.

 # ohm's law calculator

#These functions perform ohm's law and power law calculations based on variables from user input.
def voltage(i, r):
    return i * r

def current(r, v):
    return r / v

def resistance(i, v):
    return i / v

def power(v, i):
    return v * i

def pvolt(w, i):
    return w / i

def pcurrent(w, v):
    return w / v

# First user interface menu. let's user choose between ohm's law and power law calculations.

print "Ohm's Law Calculations:"

print "1. Voltage"
print "2. Current"
print "3. Resistance"

print "Power Law Calculations:"

print "4. Wattage"
print "5. Voltage"
print "6. Current"

#Line 48 is taking the user's menu choice and passing it to the "choice" options below.
choice = raw_input(">>> ")

#These if statements are calling the functions.

#This gives values to "i" "v"  "w" and "r" from user input as floating point numbers the print line calls the "voltage" function and prints out the results of its calculation using the "format" function which automatically displays the needed decimal places.

if choice == "1":
    i=float(raw_input("Enter current:"))
    r=float(raw_input("Enter resistance:"))
    print "{0} volts" .format(voltage(i, r))

elif choice == "2":
    r=float(raw_input("Enter resistance:"))
    v=float(raw_input("Enter voltage:"))
    print "{0} amps" .format(current(r, v))

elif choice == "3":
    i=float(raw_input("Enter current:"))
    v=float(raw_input("Enter voltage:"))
    print "{0} ohms" .format(resistance(i, v))

elif choice == "4":
    i=float(raw_input("Enter current:"))
    v=float(raw_input("Enter voltage:"))
    print "{0} watts" .format(power(i, v))

#Line 82 solves voltage according to power law
elif choice == "5":
    w=float(raw_input("Enter wattage:"))
    i=float(raw_input("Enter current:"))
    print "{0} volts" .format(pvolt(w, i))

#Line 89 solves current according to power law. I am attempting to make it round of the answer
elif choice == "6":
    w=float(raw_input("Enter wattage:"))
    v=float(raw_input("Enter voltage:"))
    print "{0} amps" .format(pcurrent(w, v))

#This line is here partly because its funny, and partly because I thought it would be cool to create my own error message

else:
    print  "Invalid number. Your computer will now self destruct."

You should think more about how you arrange and style your code. Additionally, you should be aware of DRY methodology and keep from repeating code wherever possible.

I made a couple of modifications to your code. Primarily, I cleaned up the arrangement and styling. After that, I added an Ohm class - which places all of your Ohm related functions as methods (again for code cleanliness):

"""
This class contains functions which perform Ohm's law and power
law calculations based on variables from user input
"""
class Ohm():
    @staticmethod
    def voltage(i, r): return i * r

    @staticmethod
    def current(r, v): return r / v

    @staticmethod
    def resistance(i, v): return i / v

    @staticmethod
    def power(v, i): return v * i

    @staticmethod
    def pvolt(w, i): return w / i

    @staticmethod
    def pcurrent(w, v): return w / v

After that, I changed how you output the block of text from a bunch of print statements, to 1 multiline print statement:

# First user interface menu. let's user choose between ohm's law and power law calculations.
print """Ohm's Law Calculations:
    1. Voltage
    2. Current
    3. Resistance

Power Law Calculations:
    4. Wattage
    5. Voltage
    6. Current
"""

After that, I added a call to int() on the choice = raw_input(...) call so that all input is shunted to an integer. After that, we initialize our Ohm class to an Ohm variable. Then, instead of having multiple definitions for i, r, v,  and w - we ask if the choice is in a list, define i/r/v/w. This lessens the amount of duplicated code:

### Since we're asking for the current in multiple locations, simplify it
if choice in [1, 3, 4, 5]:
    i = float(raw_input("Enter current:"))

### Again, since we're asking for voltage in multiple locations, simplify it
if choice in [2, 3, 4, 6]:
    v = float(raw_input("Enter voltage:"))

### Simplifying input for resistance
if choice in [1, 2]:
    r = float(raw_input("Enter resistance:"))

## And lastly, simplifying for wattage
if choice in [5, 6]:
    w = float(raw_input("Enter wattage:"))

After that, we continue with an if/else block which calls the function according to the user input. Our i/v/r/w should already be defined in the block above. One major change here is that we are no longer printing directly from here. Rather we are setting the output in an output variable, which we later use to print.

output = None
if choice == 1:
    output = "{0} volts".format(Ohm.voltage(i, r))
elif choice == 2:
    output = "{0} amps".format(Ohm.current(r, v))
elif choice == 3:
    output = "{0} ohms".format(Ohm.resistance(i, v))
elif choice == 4:
    output = "{0} watts".format(Ohm.power(i, v))
elif choice == 5:
    output = "{0} volts".format(Ohm.pvolt(w, i))
elif choice == 6:
    output = "{0} amps".format(Ohm.pcurrent(w, v))

Finally, we check if output variable is None. If it is not None, then we print it, otherwise we print an error. As for your 'funny' error, remember that error messages should be informative (ie, should tell the end user where the error occurred and/or why it occurred):

if output is not None:
    print output
else:
    print "Invalid input values, please try again"

Lastly, here is all of the code put together (and a REPL):

"""
Ohm's law calculator
"""

"""
This class contains functions which perform Ohm's law and power
law calculations based on variables from user input
"""
class Ohm():
    @staticmethod
    def voltage(i, r): return i * r

    @staticmethod
    def current(r, v): return r / v

    @staticmethod
    def resistance(i, v): return i / v

    @staticmethod
    def power(v, i): return v * i

    @staticmethod
    def pvolt(w, i): return w / i

    @staticmethod
    def pcurrent(w, v): return w / v

# First user interface menu. let's user choose between ohm's law and power law calculations.
print """Ohm's Law Calculations:
    1. Voltage
    2. Current
    3. Resistance

Power Law Calculations:
    4. Wattage
    5. Voltage
    6. Current
"""

# Grab the user input
choice = int(raw_input(">>> "))

# Initialize our Ohm class
Ohm = Ohm()

### Since we're asking for the current in multiple locations, simplify it
if choice in [1, 3, 4, 5]:
    i = float(raw_input("Enter current:"))

### Again, since we're asking for voltage in multiple locations, simplify it
if choice in [2, 3, 4, 6]:
    v = float(raw_input("Enter voltage:"))

### Simplifying input for resistance
if choice in [1, 2]:
    r = float(raw_input("Enter resistance:"))

## And lastly, simplifying for wattage
if choice in [5, 6]:
    w = float(raw_input("Enter wattage:"))

output = None
if choice == 1:
    output = "{0} volts".format(Ohm.voltage(i, r))
elif choice == 2:
    output = "{0} amps".format(Ohm.current(r, v))
elif choice == 3:
    output = "{0} ohms".format(Ohm.resistance(i, v))
elif choice == 4:
    output = "{0} watts".format(Ohm.power(i, v))
elif choice == 5:
    output = "{0} volts".format(Ohm.pvolt(w, i))
elif choice == 6:
    output = "{0} amps".format(Ohm.pcurrent(w, v))

if output is not None:
    print output
else:
    print "Invalid input values, please try again"


Populating two lists, each from their respective with user input field I've simplified this for posting, since there are going to be more than 4 options sets for this function to cycle through:

function redundantSee() {

  var optionSet1 = $('.wrapper:eq(0)'),
      optionSet2 = $('.wrapper:eq(1)');

  optionSet1.find('.options').each(function(){
      var self = $(this),
          input = self.find('input'),
          title = self.find('.title').text(),
          value = input.val(),
          source = self.find('img').attr('src'),
          id = input.attr('id'),
          listItem = $('<li/>', {'value': value, 'id': id }),
          imageElement = $('<img/>', {'src': source, 'title': title});

      $('div.corresponding1').append(nameListItem);
      listItem.append(imageElement);
  });

  optionSet2.find('.options').each(function(){
      var self = $(this),
          input = self.find('input'),
          title = self.find('.title').text(),
          value = input.val(),
          source = self.find('img').attr('src'),
          id = input.attr('id'),
          listItem = $('<li/>', {'value': value, 'id': id }),
          imageElement = $('<img/>', {'src': source, 'title': title});

      $('div.corresponding2').append(listItem);
      listItem.append(imageElement);
  });
}

I'm having a problem figuring out how to turn all of the repetitive code into something much more manageable. But since each option set has its own each loop, the $(this) variable (and all corresponding variables) are specific to the loop that is run on the ('.options') element.

If I do one each loop and use a counter, like this:

$('wrapper').each(function(i){ // ... });

I still run into the problem of needing to re-declare all my new variables specific to that optionSet's turn in the loop.

Can someone help me figure out how I can condense this so that I'm not constantly repeating the same code every time I add a new option set to the function?

Create a function with the common code:

function redundantSee() {

  var optionSet1 = $('.wrapper:eq(0)'),
      optionSet2 = $('.wrapper:eq(1)');

    function addImage(correspond, item) {
      var self = $(this),
          input = self.find('input'),
          title = self.find('.title').text(),
          value = input.val(),
          source = self.find('img').attr('src'),
          id = input.attr('id'),
          listItem = $('<li/>', {'value': value, 'id': id }),
          imageElement = $('<img/>', {'src': source, 'title': title});

      $(correspond).append(item);
      item.append(imageElement);
    }

    optionSet1.find('.options').each(function() {addImage('div.corresponding1', nameListItem);})
    optionSet1.find('.options').each(function() {addImage('div.corresponding2', listItem);})
}

Here's a further reduced version that is also a little more efficient:

function redundantSee() {
    function processSet(set, correspond, item) {
        set.find('.options').each(function() {addImage(correspond, item);})
    }

    function addImage(correspond, item) {
      var self = $(this),
          input = self.find('input'),
          title = self.find('.title').text(),
          value = input.val(),
          source = self.find('img').attr('src'),
          id = input.attr('id'),
          listItem = $('<li/>', {'value': value, 'id': id }),
          imageElement = $('<img/>', {'src': source, 'title': title});

      $(correspond).append(item);
      item.append(imageElement);
    }

    var wrappers = $('.wrapper');
    processSet(wrappers.eq(0), 'div.corresponding1', nameListItem);
    processSet(wrappers.eq(1), 'div.corresponding2', listItem);
}


Merging values with lists as flat-lists I'm merging dictionaries together in series. Each one may/may not have lists as values. I'd like to merge indefinitely and, have the final merged dictionary contain only flat lists as values.

Any advice for how to write this as a single/simpler function?

def merge_dlist(dict_1, dict_2):
    """Merge_dlist accepts dictionaries to be merged."""
    merged_dict = defaultdict(list)
    merged_dict = merge_type(dict_1, merged_dict)
    merged_dict = merge_type(dict_2, merged_dict)
    return merged_dict

def merge_type(dictionary, merged_dict):
"""Merge dictionary keys. Append value items as strings to value list."""
for key, value in dictionary.items():
    if isinstance(value, list):
        for item in value:
            merged_dict[key].append(item)
    if isinstance(value, str):
        merged_dict[key].append(value)
return merged_dict

Merging many dictionaries

Instead of merging just 2 dictionaries, how about allowing to merge many?

def merge_dlist(*args):
    """Merge_dlist accepts dictionaries to be merged."""
    merged_dict = defaultdict(list)
    for dictionary in args:
        merged_dict = merge_type(dictionary, merged_dict)
    return merged_dict

Improving merge_type like this:

def merge_dictionary(dictionary, merged):
    """Merge dictionary keys. Append value items to value list."""
    for key, value in dictionary.items():
        if isinstance(value, list):
            merged[key].extend(value)
        else:
            merged[key].append(value)
    return merged

Improvements:

Naming: "merge_type" is a strange name, I don't know what it means. I think "merge_dictionary" makes more sense.
Instead of appending list items one by one with .append, it's better to add all at once using .extend
Why limit to string types? Why not append any kind of non-list values in general?


How would you count in the Fibonacci Sequence? I was wondering if I did this in a remotely acceptable way:

var fib = function(params) {
    var iterations = params;
    var output = [0];

    for(var i = 1, j = 1; j < iterations; j++){
        //i is the fibonacci sequence
        //j counts iterations
        output.push(i);
        i = parseInt(output[j]) + parseInt(output[j-1]);

    }
        console.log(output[iterations-1]);
}

fib("4");

Here the function takes in a parameter (eg 4), then a for loop counts through and adds every Fibonacci number until that iteration to an array (so in this example, 4 values are in the output array).

Mostly I'd just like to know if you guys would reach a similar conclusion and if I did anything that's a huge no-no, particularly using output[iterations-1] to force the counter to be at the same point as the array (due to 0th index) seems iffy.

var fib = function(params) {
    var iterations = params;

Why are you copying params into iterations, rather than just naming your parameter iterations?

    var output = [0];

That's not really your output is it? Perhaps there is a better name?

    for(var i = 1, j = 1; j < iterations; j++){
        //i is the fibonacci sequence
        //j counts iterations
        output.push(i);
        i = parseInt(output[j]) + parseInt(output[j-1]);

Output already contains ints. There is no reason to parseInt it. Why don't you directly push on the array rather then storing it in an int? Furthermore, you don't actually need an array, you only need the last two elements.

    }
        console.log(output[iterations-1]);

Fix the indent here.
    }

fib("4");

Why are you passing a string?


Simple content management system I'm working on a simple CMS. It's working quite ok, but I think my code can be improved a bit. I work with a section.php, which is included from the index.php with (example):

switch($_GET['key'])
{
case '': $page='section'; $id='1'; break;
case 'home': $page='section'; $id='1'; break;
}
include ('header.php');
include ($page.'.php');
include ('footer.php');

But I would like some feedback on my section.php code. I have very little knowledge of OOP, but if possible I would like to use it for section.php. I used it a little for $validator which checks for clean URLs. But I have trouble with re-using the same $sql_queries.

section.php:

<?php

        #-------------------------------------------#
        # SIDEBAR                                   #
        #-------------------------------------------#

echo "
";
$result = mysql_query('SELECT ID,title,tagline FROM cmsarticles WHERE section = '.$id.' ORDER BY id ASC LIMIT 4');
    while ($row = mysql_fetch_array($result)){
    $path = 'photos/';
    $safeid = $validator->clean_url($row['title'].'-'.$row['ID']);
    $get_photo = "SELECT name,artId,posId FROM images WHERE artId = ".$row['ID']." AND posId = 2 LIMIT 3";
    $photothumbs = mysql_query($get_photo) or die(mysql_error());
        while($photothumb = mysql_fetch_array($photothumbs)){
        echo '';
        }
    }
echo "
";

        #-------------------------------------------#
        # CONTENT                                   #
        #-------------------------------------------#

echo "
";
$query= mysql_query('SELECT cmsarticles.ID AS artID, cmsarticles.title, cmsarticles.tagline, cmsarticles.thearticle, cmsarticles.section, cmssections.ID, cmssections.name
FROM cmsarticles, cmssections
WHERE cmsarticles.section = cmssections.ID
AND cmsarticles.section ='.$id.' ORDER BY cmsarticles.ID ASC');
$num_results = mysql_num_rows($query);
if ($num_results == 0){
echo 'Nothing here at the moment.';
}else{
    while($result = mysql_fetch_array($query)) {
    $safeid = $validator->clean_url($result['title'].'-'.$result['artID']);
    echo "

".$result['title']."
";
    $query2 = mysql_query('SELECT name,artId,posId FROM images WHERE artId = '.$result['artID'].' AND posId = 1 LIMIT 1');
        while($result2 = mysql_fetch_array($query2)){
        echo '';
        }
    echo"
".$result['thearticle']."

";
    }
}
echo "
";

?>

I'd rewrite the first part like this:

if(empty($_GET['key']) or !strcmp($_GET['key'], 'home')){
    $page = 'section';
    $id = 1; // integer not string
}elseif(!strcmp($_GET['key'], 'blahblah')){
    $page = 'blahblah';
    $id = 2; // integer not string
} // ...
include ('header.php');
include ("{$page}.php");
include ('footer.php');

Switch for strings is not always the best idea. You might want case insensitive compare and that's the strcasecmp realm.
If $_GET['key'] is missing, you will get a notice with the switch while empty() is safe.
$id seems to be an integer 1 so why make it a string '1'?
Why concatenate like this $page.'.php' when you can have php do it for you "{$page}.php"?

As of the second part, things are not too great:

Why concatenate on echo like this echo 'string'.'string' when echo is a language construct and allows this echo 'string', 'string' which skips the concatenation?
Why use $num_results == 0 when you can just use !$num_results?
Why not escape arguments in MySQL Query (let's just say you have an $id integer and might get away with it here) when SQL injections are so nasty :)

PS: AND YOU need to work on your formatting A LOT... like very much!


Collection of Actions I am trying to create a class to queue up a series of commands. (Not really a queue as events happen based on time). Each command has a callback (Action) that get's called. However, each Action has a different set of parameters (signature), so I am using an object[] to pass them and then have to do lots of casting.

Example: the Queue class:

class RfxQueue {
    public enum CMD {DISPLAY, REPLACE_TMPLT, SCALE_DVE, etc };
    private Dictionary<CMD, Action<object []>> actions = new Dictionary<CMD,Action<object[]>>();
    // Struct to hold command info
    public struct QItem
    {
        public CMD cmd;           // The CMD to exec
        public long ttd;          // Time to be executed
        public object[] param;    // Parameters to Action
    }
    private List<QItem> q = new List<QItem>();   // The queue of events

    // Create a new callback
    public void addAction(CMD cmd, Action<object []> action)
    {
        actions.Add(cmd, action);
    }

    // Add to Q
    public void pushEvent(CMD Cmd, float Delay, params object[] Param)
    {
        q.Add(new QItem() { cmd = Cmd, param = Param, ttd = DateTime.Now.AddMilliseconds(Delay * 1000).Ticks });
    }

    // This is actually done in a thread. Simplified here
    private void execEvent()
    {
        QItem item;
        // item is pulled from q here
        actions[item.cmd].Invoke(item.param);
    }
}

And the owner class creates events like this:

// "q" is a RfxQueue and the internal Invoke is required to run on main thread
q.events.Add(RfxQueue.CMD.SCALE_DVE, new Action<object[]>(o =>
{
    dispatcher.Invoke(new Action<string, string, bool>((a,b,c) =>
    {
        _cgManager.ScaleDVE(a, b, c);
    }), (string)o[0], (string)o[1], (bool)o[2]);
}));
q.events.Add(RfxQueue.CMD.PLAY_ANIMATION, new Action<object[]>(o =>
{
    dispatcher.Invoke(new Action<VideoTemplate, string>((v, s) => {
        _cgManager.playAnimation(v, s);
    }), (VideoTemplate)o[0], (string)o[1]);
}));

Lastly, an event is added like this:

// Play animation "inserton" in 3 seconds
q.add(RfxQueue.CMD.PLAY_ANIMATION, template, 3f, "inserton");

Is there a way to do this without all that casting? Thanks!

Starting from minor issues - please follow naming conventions (variables should be camelCased and methods PascalCased, do add access modifiers, give variables meaningful names).

Your design breaks Open-Closed principle: Queue knows all the possible commands it can handle. In case when you need to add a new command you'll have to change the queue rather than add new code.

Also it breaks Single Responsibility Principle since queue knows not only about scheduling the execution but also serves as a repository for all possible actions to be run for commands.

Both issues as well as those you have mentioned (type casting, different signatures) can be easily solved if you create a separate class per command type. Command will encapsulate parameters required for execution as well as the action to be executed:

public interface ICommand
{
    void Execute();
}

public class ScaleDveCommand : ICommand
{
    public CgManager CgManager { get; set; }
    public string FirstString { get; set; } //TODO:Rename to meaningful name
    public string SecondString { get; set; } //TODO:Rename to meaningful name
    public bool SomeBool { get; set; } //TODO:Rename to meaningful name

    public void Execute()
    {
        dispatcher.Invoke(() => CgManager.ScaleDVE(FirstString, SecondString, SomeBool));
    }
}

public class PlayAnimationCommand : ICommand
{
    public CgManager CgManager { get; set; }
    public VideoTemplate VideoTemplate { get; set; }
    public string SomeMeaningfulNameHere { get; set; } //TODO:Rename to meaningful name

    public void Execute()
    {
        dispatcher.Invoke(() => { CgManager.playAnimation(VideoTemplate, SomeMeaningfulNameHere); });
    }
}

And your "queue" class will look like:

public class RfxQ
{
    private readonly SortedList<long, ICommand> _queue = new SortedList<long, ICommand>();   // The queue of events

    public void PushEvent(ICommand command, TimeSpan delay)
    {
        _queue.Add(DateTime.Now.Add(delay).Ticks, command);
    }

    // This is actually done in a thread. Simplified here
    private void ExecEvent()
    {
        ICommand command;
        // item is pulled from _queue here
        command.Execute();
    }
}

And usage will look like:

q.pushEvent(new PlayAnimationCommand
    {
        CgManager = _cgManager,
        VideoTemplate = template,
        SomeMeaningfulNameHere = "inserton"
    }, TimeSpan.FromSeconds(3));


Dockerfile to install Apache I'm getting started with Docker, and I've set up a very simple image built from a Dockerfile. It's based FROM the ubuntu image, and I'm downloading and building apache from source.

I'm just curious if I'm on the right tracks, if there's a more "Docker" way of doing what I'm doing, or any other things that I could be doing different/better.

It's running in the default VM that Kitematic adds for me, and I'm building the image with docker build -t webserver ., then testing with docker run -p 80:80 -i -t webserver /bin/bash

FROM ubuntu:latest

RUN apt-get -qq  update -y
RUN apt-get -qq install build-essential -y

RUN mkdir install-files
WORKDIR /install-files
RUN mkdir apache
WORKDIR /install-files/apache
RUN apt-get -qq install wget -y >/dev/null
RUN wget http://mirrors.ukfast.co.uk/sites/ftp.apache.org//apr/apr-1.5.2.tar.gz >/dev/null
RUN tar -xvzf apr-1.5.2.tar.gz >/dev/null
WORKDIR /install-files/apache/apr-1.5.2
RUN ./configure >/dev/null
RUN make >/dev/null
RUN make install >/dev/null

WORKDIR /install-files/apache
RUN wget http://apache.mirror.anlx.net//apr/apr-util-1.5.4.tar.gz >/dev/null
RUN tar -xvzf apr-util-1.5.4.tar.gz >/dev/null
WORKDIR /install-files/apache/apr-util-1.5.4
RUN ./configure --with-apr=/usr/local/apr/ >/dev/null
RUN make >/dev/null
RUN make install >/dev/null

WORKDIR /install-files/apache/
RUN apt-get -qq install libpcre3 libpcre3-dev >/dev/null
RUN wget http://mirror.ox.ac.uk/sites/rsync.apache.org//httpd/httpd-2.4.18.tar.gz >/dev/null
RUN tar -xvzf httpd-2.4.18.tar.gz >/dev/null
WORKDIR /install-files/apache/httpd-2.4.18
RUN ./configure --with-apr=/usr/local/apr/ >/dev/null
RUN make >/dev/null
RUN make install >/dev/null

RUN mkdir /tech
RUN ln -s /usr/local/apache2/ /tech/httpd

RUN apt-get -qq install nano -y
ADD startup.sh /root/startup.sh
RUN chmod 777 /root/startup.sh

WORKDIR /

Do you really have a good reason for this permission setup?

RUN chmod 777 /root/startup.sh

It's a bit ironic to use the -v flag of tar, and then redirecting the output to /dev/null here:

RUN tar -xvzf httpd-2.4.18.tar.gz >/dev/null

You can drop that flag and the redirection, the outcome should be the same.

I'm not very familiar with Docker, but I'm wondering what will happen if any of the commands fail. For example, if make fails, you probably don't want to run the make install command that follows it.
I don't have a solution for that, but error handling is something to think about.

The repetitive redirections and duplicated strings don't look pretty, and look hard to maintain. There gotta be a better way. Perhaps you could put the shell commands into a proper .bash script, enjoy all the power of regular bash scripting (variables, functions), and in the docker file just fetch that script using wget, and then execute it.