Returning two dates based on input I created a function that will return 2 dates that depend on an input parameter.

When the parameter is:

1  - return start date of current week and end date of current week
2  - return start date of last week and end date of last week
3  - return start date of current month and end date of current month
4  - return start date of last month and end date of last month

Could you please suggest improvements? And what name would be more appropriate for this function?

CREATE FUNCTION [ufn_GetRangeOfDates]
( @Type int
)
RETURNS @Result TABLE
( StartDate date
, EndDate date
)
AS
BEGIN

  declare @Today date = GetDate()

  -- current weak
  declare @CurrentWeakStart date = dateadd(day, 1-datepart(dw, @Today), CONVERT(date, @Today))
  declare @CurrentWeakEnd date = dateadd(day, 7-datepart(dw,  @Today), CONVERT(date,  @Today))
  -- last week
  declare @LastWeakStart date = DATEADD(dd, DATEPART(DW,@Today)*-1-6, @Today)
  declare @LastWeakEnd date =DATEADD(dd, DATEPART(DW,@Today)*-1, @Today)
  --current month
  declare @CurrentMonthStart date = DateAdd( day, 1 - Day( @Today ), @Today )
  declare @CurrentMonthEnd Date = DateAdd( day, -1, DateAdd( month, 1, @CurrentMonthStart ) )
  -- last month
  declare @LastMonthStart date = DATEADD(MONTH, DATEDIFF(MONTH, 0, @Today)-1, 0)
  declare @LastMonthEnd date = DATEADD(MONTH, DATEDIFF(MONTH, -1, @Today)-1, -1)

  insert into @Result
  select CASE @Type
           WHEN 1 THEN @CurrentWeakStart
           WHEN 2 THEN @LastWeakStart
           WHEN 3 THEN @CurrentMonthStart
           WHEN 4 THEN @LastMonthStart
           ELSE NULL
         END
  ,      CASE @Type
           WHEN 1 THEN @CurrentWeakEnd
           WHEN 2 THEN @LastWeakEnd
           WHEN 3 THEN @CurrentMonthEnd
           WHEN 4 THEN @LastMonthEnd
           ELSE NULL
         END
  RETURN
END -- End of ufn_GetRangeOfDates

Misspellings
There are several misspelled words you should correct (see line comments):
  -- current weak -- should be 'week'
  declare @CurrentWeakStart date = dateadd(day, 1-datepart(dw, @Today), CONVERT(date, @Today)) -- should be '@CurrentWeekStart'
  declare @CurrentWeakEnd date = dateadd(day, 7-datepart(dw,  @Today), CONVERT(date,  @Today)) --should be '@CurrentWeekEnd'
  -- last week
  declare @LastWeakStart date = DATEADD(dd, DATEPART(DW,@Today)*-1-6, @Today) -- should be '@LastWeekStart'
  declare @LastWeakEnd date =DATEADD(dd, DATEPART(DW,@Today)*-1, @Today) -- should be '@LastWeekEnd'

Magic numbers
You use ints 1,2,3,4 as codes but no indication of what they mean. I'd suggest to take a moment to declare them and give them meaningful name:
declare @StartAndEndOfCurrentWeek  int = 1;
declare @StartAndEndOfLastWeek     int = 2;
declare @StartAndEndOfCurrentMonth int = 3;
declare @StartAndEndOfLastMonth    int = 4;

Then this becomes more clear:
  insert into @Result
  select CASE @Type
           WHEN @StartAndEndOfCurrentWeek  THEN @CurrentWeekStart
           WHEN @StartAndEndOfLastWeek     THEN @LastWeekStart
           WHEN @StartAndEndOfCurrentMonth THEN @CurrentMonthStart
           WHEN @StartAndEndOfLastMonth    THEN @LastMonthStart
           ELSE NULL
         END
  ,      CASE @Type
           WHEN @StartAndEndOfCurrentWeek  THEN @CurrentWeekEnd
           WHEN @StartAndEndOfLastWeek     THEN @LastWeekEnd
           WHEN @StartAndEndOfCurrentMonth THEN @CurrentMonthEnd
           WHEN @StartAndEndOfLastMonth    THEN @LastMonthEnd
           ELSE NULL
         END
  RETURN

Capitalization
You should try to stick to one style of capitalization throughout for keywords. It makes it easier to read and less distracting. This is especially true of something that could have some other code mixed it, for example this one could look like there is some VBA:

DateAdd( day, 1 - Day( @Today ), @Today )

What's the difference between day and Day? Well of course there isn't in SQL, but just the fact that it's capitalized differently may throw someone off that is less used to SQL and more to programming where capitalization makes a difference.

Overall
I think in general this is a good idea and seems like a useful function to have around. Especially if you work with finance stuff a lot. I think it could reasonably be broken into two functions though, one for week and one for month. Picture something like:

udf_getRangeOfDatesInWeek
udf_getRangeOfDatesInMonth

Then you only need to supply them an int parameter and put that in your datediff() operation. 0 for current, -1 for last, 1 for next, etc. I think that would be much more flexible and useful!


Creating and updating link to instagram image or video I've been using the InstagramPhotoLink extension for Opera for some time but instagram broke it recently. I thought I could try to fix it... and I did.

The original extension is rather limited and it supports only a link to the first image and no videos so while fixing it I completely rewrote it in order to extend it.

It works by looking for an image or video element with a specific class and extracts the src attribute from it and puts it in a new a-element inside the media-container.

Switching images/videos is supported by the MutationObserver that updates the links when either a div or an attribute changes.

I came across a problem where the MutatorObserver reacts too quickly and before the src attribute of the new image is set. I solved it by adding a small delay by adding a call to setTimeout to wait until everything is updated.

function createMediaLink() {

    let mo = new MutationObserver(mutations => {
        mutations.forEach(mutation => {
            if (mutation.type == "attributes") {
                //console.log(mutation.attributeName);
                addOrUpdateVideoLink();
            }
            if (mutation.type == "childList") {
                //console.log(mutation.childList);
                addOrUpdateImageLink();
            }
        });
    });

    return (
        addOrUpdateImageLink(mo) ||
        addOrUpdateVideoLink(mo)
    );
}

function addOrUpdateImageLink(mo) {

    let image = document.getElementsByClassName('FFVAD');

    if (image.length == 0) {
        return false;
    }

    image = image[0];

    if (mo) {
        // the nearest div to the image that stays there when switching images
        var div = document.getElementsByClassName("rQDP3");
        mo.observe(div[0], {
            childList: true
        });
    }

    setTimeout(() => {
        addOrUpdateMediaLink(image.src);
    }, 50);

    return true;
}

function addOrUpdateVideoLink(mo) {

    let video = document.getElementsByClassName('tWeCl');

    if (video.length == 0) {
        return false;
    }

    video = video[0];

    if (mo) {
        mo.observe(video, {
            attributes: true
        });
    }

    setTimeout(() => {
        addOrUpdateMediaLink(video.src);
    }, 50);

    return true;
}

function addOrUpdateMediaLink(src) {
    console.log(`src: ${src}`);
    let a = document.getElementsByClassName('_open_');
    if (a.length == 0) {
        a = document.createElement("a");
        a.className = "_open_";
        a.innerHTML = 'Open in new tab';
        a.target = "_blank";
        // media container
        document.getElementsByClassName("_97aPb")[0].appendChild(a);
    } else {
        a = a[0];
    }
    a.href = src;
}

createMediaLink();

I don't write javascript too often so this is the best I can do but I'm pretty sure this can still be improved. What do you think?

addOrUpdateImageLink() and addOrUpdateVideoLink() are essentially the same, therefore it would be better to create just one function that would accept different parameters dependent on whether our media is an image or video;
In createMediaLink() you invoke addOrUpdate………Link() functions before you declare them. It is not wrong, but it worsens readability and code flow;
Setting 50 ms delay is not the best way to achieve what you are trying to do. Since I don't know how the DOM workings look like, I left it unchanged though;
Use strict equality operator (===) wherever possible — it performs no type conversion;
Once you pick which quotes you use ('' or ""), stick to it. Generally, single quotes option is more popular and standard.

Rewrite

const addOrUpdateMediaLink = src => {
  if (!src) { return; }
  console.log(`src: ${src}`);

  let a = document.querySelector('._open_');

  if (!a) {
    a = document.createElement('a');
    [a.className, a.textContent, a.target] = ['_open_', 'Open in new tab', '_blank'];

    // media container
    document.querySelector('._97aPb').appendChild(a);
  }

  a.href = src;
};

const addOrUpdate = (selector, observeSelector, attr, mo) => {
  let media = document.querySelector(selector);

  if (!media) { return false; }

  if (mo) {
    const obj = {};
    obj[attr] = true;
    mo.observe(document.querySelector(observeSelector), obj);
  }

  setTimeout(() => addOrUpdateMediaLink(media.src), 50);

  return true;
};

const createMediaLink = () => {
  const selectors = {
    attributes: ['.tWeCl', '.tWeCl'],
    childList:  ['.FFVAD', '.rQDP3']
  };

  const mo = new MutationObserver(mutations => mutations.forEach(mutation => addOrUpdate(selectors[mutation.type][0])));

  return addOrUpdate(...selectors.childList, 'childList', mo) || addOrUpdate(...selectors.attributes, 'attributes', mo);
};

createMediaLink();


Pancake sort interview with Python I got asked this question during my interview. You can find information about this question here.

  Pancake Sort

  Given an array of integers arr:

  Write a function flip(arr, k) that reverses the order of the first k elements in the array arr.
  Write a function pancakeSort(arr) that sorts and returns the input array. You are allowed to use only the function flip you wrote in the first step in order to make changes in the array.
  Example:

input:  arr = [1, 5, 4, 3, 2]

output: [1, 2, 3, 4, 5]

  Note: it’s called pancake sort because it resembles sorting pancakes on a plate with a spatula, where you can only use the spatula to flip some of the top pancakes in the plate. To read more about the problem, see the Pancake Sorting Wikipedia page. https://en.wikipedia.org/wiki/Pancake_sorting

My solution is to use flip function to implement my pancake_sort(arr).

The following property of the flipping function - if we call flip(arr, k), then the previous k-th element in the array is now the first element. Hence, if we find the maximal element, we can shift it to be the first element by one call to flip(arr, k), and then shift it to the last place by calling flip(arr, arr.length - 1). We can exploit this method further, by iterating i from arr.length - 1 to 1, finding the maximal element in the current ith prefix, flipping the maximal element once to move it to the first place in the array, and a second time to put it in the ith place in the array.

def flip(arr, i):
    # reverse arr[0...i]
    start = 0
    while start < i:
        temp = arr[start]
        arr[start] = arr[i]
        arr[i] = temp
        start += 1
        i -= 1

def pancake_sort(arr):
    # the main function that complete sorting
    # start from the array and one by one reduce the current size
    output = []
    curr_size = len(arr) - 1
    # find the index of the maxmium element inside the arr[0..curr_size -1]
    while curr_size > 0:
        mi = findMaxUpTo(arr, curr_size)
        if mi != curr_size:
            flip(arr, mi)
            # once I flip it
            # now move the maximum number to the end by reversing current array
            flip(arr, curr_size)
        curr_size -= 1
    return arr

def findMaxUpTo(arr, rightBound):
    best_index = 0
    max_val = None
    for i in range(rightBound + 1):
        if arr[i] > max_val:
            best_index = i
            max_val = arr[i]
    return best_index

I also ran my code against the following test cases:

Test Case #1
Input: [1]
Expected: [1]
Actual: [1]
Test Case #2
Input: [1,2],Expected: [1,2],
Actual: [1, 2]
Test Case #3
Input: [1,3,1],
Expected: [1,1,3],Actual: [1, 1, 3]
Test Case #4
Input: [3,1,2,4,6,5],
Expected: [1,2,3,4,5,6],
Actual: [1, 2, 3, 4, 5, 6]
Test Case #5
Input: [10,9,8,7,6,5,4,3,2,1],
Expected: [1,2,3,4,5,6,7,8,9,10],
Actual: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Test Case #6
Input: [10,9,8,6,7,5,4,3,2,1,9,10,8,7,6,5,4,3,2,1,10,9,8,7,6,5,4,3,2,1],
Expected: [1,1,1,2,2,2,3,3,3,4,4,4,5,5,5,6,6,6,7,7,7,8,8,8,9,9,9,10,10,10],
Actual: [1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 7, 7, 8, 8, 8, 9, 9, 9, 10, 10, 10]

flip

For starter, you can swap two variables in Python without using a temporary one:

>>> a = 3
>>> b = 5
>>> a, b = b, a
>>> print(a, b)
5 3

But above all, this function is better implemented using slices:

def flip(arr, i):
    arr[:i] = reversed(arr[:i])

Or

def flip(arr, i):
    arr[:i] = arr[i-1::-1]

findMaxUpTo

Same here, slices and builtin functions can go a long way into simplifying the code. A "max" function that doesn't use the max builtin feels wrong to me.

A naïve rewrite would be:

def findMaxUpTo(arr, i):
    val = max(arr[:i])
    return arr.index(val)

It is good for now. But a better rewrite would make use of enumerate and the key argument of max. Possibly involving operator.itemgetter in the process and itertools.takewhile to avoid copying the array.

pancake_sort

Not much to add here, except a note on your return value. Since you are mutating the array in-place, there is absolutely no reason to return a value. Once you call the function on an array, it will be sorted and all previous references to this array will now hold the sorted version. Returning a value can mislead the users that the original array remain untouched, which is false.

Similarly, you never make use of the output variable.

miscelaneous

Your naming style is inconsistent and some variable names don't convey much meaning, please fix it.


Reading a user credentials from file concurrently I came across the following code snippet:

static private volatile ConfigUserCredentails maintenanceUserCred = null;
static private Object maintenanceUserLock = new Object();

/**
 * This method is slower.  Recommend use the one from cache.
 *
 * @return The username/password credentials of the maintenance user.
 * @throws IOException
 */
public static ConfigUserCredentails getMaintenanceUserCredentials() throws IOException {
    return readCredentialsFromFile(MAINTENANCE_CREDENTIALS_PROPS, Crypt.getDefaultCrypt());
}

/**
 *
 * @return The username/password credentials of the maintenance user.
 * @throws IOException
 */
public static ConfigUserCredentails getMaintenanceUserCredentialsFromCache() throws IOException {
    if (maintenanceUserCred != null) {
        return maintenanceUserCred;
    }
    synchronized(maintenanceUserLock) {
        if (maintenanceUserCred == null) {
            maintenanceUserCred = getMaintenanceUserCredentials();
        }
    }
    return maintenanceUserCred;
}

'getMaintenanceUserCredentials()' just reads the user credentials from file and
creates new user object.

My questions are:

What is the purpose of 'volatile'?
Why would one need the 'synchronized' block?

Thanks,
Rafik

When a variable is volatile, then the code that access that variable is forced to read/write the value of variable from/to the memory. Without volatile, the value of variable can be (temporarily) stored to place (like register/cache) where changes are not immediately visible to other threads, or changes by other threads are not immediately visible.
synchronized is used in the code for avoiding concurrent and duplicate initialization of maintenanceUserCred. Without the synchronized block, two or more threads can enter to maintenanceUserCred = getMaintenanceUserCredentials(); line at the same time. The synchronized will pass only one thread at a time to the block, so maintenanceUserCred = getMaintenanceUserCredentials(); will be done only once.

Both synchronized and volatile will create memory barriers, that ensures that loads and stores are really from/to the main memory (not only local cache of current CPU core).

For example without volatile and synchronized the generated code could effectively work like the following code:

ConfigUserCredentails tmp = maintenanceUserCred;

if (tmp != null) {
    return tmp;
}
tmp = getMaintenanceUserCredentials();
maintenanceUserCred = tmp;
return tmp;

That will allow several threads to call getMaintenanceUserCredentials() at the same time and threads may obtain different ConfigUserCredentails objects.


Webservice class with parser using generics I'm currently building a small web stack in swift for use in my iOS apps. It consists of multiple components and I want to make it resource specific;
To that end, I have a WebService class composed of two parts; a part that handles the request logic, and a part that handles the parsing.

The catch here is that the parsing is defined by a ParserType protocol with an associated type ModelType, which needs to be specified by the adopter. It parses Any? to that ModelType:

public protocol ParserType {

    associatedtype ModelType

    func parse(_ data: Any?) throws -> ModelType
}

This is no problem on its own; a concrete parser could look like this (just forgive me the force casting here):

public class SimpleJSONParser<T: Codable>: ParserType {

    public typealias ModelType = T
    private let jsonDecoder: JSONDecoder

    public init(jsonDecoder: JSONDecoder = JSONDecoder()) {
        self.jsonDecoder = jsonDecoder
    }

    open func parse(_ data: Any?) throws -> T {
        let response = try jsonDecoder.decode(T.self, from: data as! Data)
        return response
    }
}

Now we have a concrete JSON parser that tries to parse Any? to T. That's cool, so we want to inject it into WebService, so it can be used. It looks like this:

public class WebService<ModelType, Parser: ParserType> {

    public typealias ModelType = Parser.ModelType
    public typealias WebServiceCompletion = (Result<ModelType>) -> Void

    private let endpoint: String
    private let parser: Parser
    private let transport: ServiceTransport

    public init(transport: ServiceTransport, endpoint: String, parser: Parser) {
        self.transport = transport
        self.endpoint = endpoint
        self.parser = parser
    }

    @discardableResult
    open func fetch(path: String? = nil, headers: [String: String]? = nil, parameters: [String: String]? = nil, autoResumeTask: Bool = true, completion: @escaping WebServiceCompletion) -> ServiceTransportTask {

        let endpointToUse = endpoint + (path ?? "")

        let task = transport.perform(action: .get, path: endpointToUse, parameters: parameters, headers: headers, body: nil)
                .completion { response in
                    switch response {
                    case .failure(let error):
                        completion(.failure(error))
                    case .success(let data):
                        do {
                            let result: ModelType = try self.parser.parse(data)
                            completion(.success(result))
                        } catch let error {
                            completion(.failure(error))
                        }
                    }
                }

        if autoResumeTask {
            task.resume()
        }

        return task
    }
}

The issue I have is that when I want to use this, I have to specify to the WebService that I want to use it for a type CategoryArray for example, with a parser that parses JSON to CategoryArray, i.e. JSONParser<CategoryArray>, and then also inject such a parser into the WebService:

let transport = HTTPTransport(baseURL: URL(string: baseURLString)!)
let parser = JSONParser<CategoryArray>()
let webService: WebService<CategoryArray, JSONParser<CategoryArray>> webService = WebService(transport: transport, endpoint: endPoint, parser: parser)

It feels a bit weird to me in the sense that I have to define the model type to use in both WebService and Parser, and also define the parser type.

Is my approach too generic, or can I factor out something here?

Turns out I can just use the generic ModelType defined in the ParserType, and I don't need the same generic parameter in WebService;

public class WebService<Parser: ParserType> {
...

The typealias is just for convenience, to not type ParserType.ModelType everywhere but just ModelType.

Results in this call site:

let transport = HTTPTransport(baseURL: URL(string: baseURLString)!)
let parser = JSONParser<CategoryArray>()
let webService: WebService<JSONParser<CategoryArray>> webService = WebService(transport: transport, endpoint: endPoint, parser: parser)

(And because of type inference, the last line can be reduced to let webService = WebService(transport: transport, endpoint: endPoint, parser: parser) which is neat)


Check balanced brackets in a text Given an input text that is a combination of {, }, [, ], (, ) characters, check whether the input text has balanced brackets or not.

This was a question from hackerrank, and the code below solves it in a little bit complicated way while favoring generality.

#include <stack>
#include <string>
#include <vector>
#include <iostream>
#include <unordered_map>

template<typename T>
class balancedBrackets
{
    enum class bracketType { OPENING, CLOSING };
    std::unordered_map<T, bracketType> mBracketIdentifiers;//which bracket symbol is the opening character and which is the closing character
    std::unordered_map<T, T> mBracketPairs;//which bracket symbol matches with which other
public:
    balancedBrackets(){}
    balancedBrackets(std::initializer_list< std::pair<T, T> > pairs)
    {
        addBracketPairs(pairs);
    }

    void addBracketPairs(std::initializer_list< std::pair<T, T> > pairs)
    {
        for (auto elem : pairs)
        {
            if (mBracketIdentifiers.find(elem.first) != mBracketIdentifiers.end() ||
                mBracketIdentifiers.find(elem.second) != mBracketIdentifiers.end())
            {
                continue;//if any member of this bracket pair already exist, skip.
            }
            mBracketPairs.emplace(elem);
            mBracketIdentifiers.emplace(elem.first, bracketType::OPENING);
            mBracketIdentifiers.emplace(elem.second, bracketType::CLOSING);
        }
    }

    void removeBracketPairs(std::initializer_list< std::pair<T, T> > pairs)
    {
        for (auto elem : pairs)
        {
            auto search = mBracketPairs.find(elem.first);
            if (search != mBracketPairs.end() && search->second == elem.second)//is this a valid pair?
            {
                mBracketPairs.erase(search);
                mBracketIdentifiers.erase(elem.first);
                mBracketIdentifiers.erase(elem.second);
            }
        }
    }

    void clearBracketPairs()
    {
        mBracketPairs.clear();
        mBracketIdentifiers.clear();
    }

    bool isBalanced(std::vector<T> expression)
    {
        if (mBracketPairs.empty())//no bracket rules
        {
            throw std::logic_error("no bracket rules");
        }

        std::stack<T> myStack;
        for (auto elem : expression)
        {
            if (mBracketIdentifiers[elem] == bracketType::OPENING)
            {
                myStack.push(elem);
            }
            else
            {
                if (mBracketIdentifiers[elem] == bracketType::CLOSING)
                {
                    if (!myStack.empty() && mBracketPairs[myStack.top()] == elem)//do not call top on an empty stack
                    {
                        myStack.pop();
                    }
                    else //imbalanced text
                    {
                        return false;
                    }
                }
                else //invalid characters
                {
                    return false;
                }
            }
        }
        return myStack.empty();
    }
    bool isBalanced(std::basic_string<T> expression)//make this class work with std::string family too.
    {
        return isBalanced(std::vector<T>(expression.begin(), expression.end()));
    }
};

int main()
{
    balancedBrackets<char> a({ { '{','}' } ,{ '[',']' },{ '(',')' } });
    a.isBalanced(std::string("{{[[(())]]}}"));
    return 0;
}

I have tried to write an idiomatic and generalized version that can easily work with new bracket styles without changing the code. Moreover, a bracket pair is not necessarily be a char in this version.

This is looking pretty good! But there is definitely room for improvement:

Better template parameter name

T generally refers to "any type". Since your template is based on a character type, you should use something like CharT to be more explicit.

Is there really a reason for this to be mutable?

addBracketPairs(), removeBracketPairs() and clearBracketPairs() is just extraneous api surface to me.

I would personally have favored a public API consisting entirely of:

Construct a brackets matcher.
Use the bracket matcher to match brackets.
MAYBE have a join() function to combine two matchers together into 1.

On the surface, it looks less flexible, but it's as functional as your version, and takes a fraction of the time to wrap your head around.

It also means that your emptiness check can be moved to the constructor, so that you don't have to perform that check every single time isBalanced() is invoked.

isBalanced() should take a pair of iterators.

The correct signature for isBalanced() is:

template<typename IteT>
bool isBalanced(IteT begin, IteT end) const;

This way, you can consume from vectors, strings, character arrays, etc... and there is no need to make a copy of the data into a vector prior.

member functions that do not mutate the class should be marked const.

Pretty simole, isBalanced() should be marked const.

Use const references when not taking posession of the data.

For example:

bool isBalanced(const std::basic_string<T>& expression)

This avoids extra copies.


Retrieving album artist info from third party API I've recently just started with AngularJS and the best way for me to learn is to get some criticism to find out how I can do things better. I did a small project that calls a third party API and shows a bit of the return data.

HTML

      <input id="artist" type="text" placeholder="Enter artist name" ng-model="artist">
      <button ng-click="getAlbums()">Get Albums</button>

 0">

Album Info

            {{album.name}}

Controller

jamendoApp.controller('Album', function($scope, $http) {
  $scope.getAlbums = function() {
    $http.get("http://api.jamendo.com/v3.0/albums/?client_id=b6747d04&format=jsonpretty&artist_name=" + $scope.artist)
         .success(function(data) {
            if(data.headers.status == 'success') {
              $scope.albums = data.results;
            }
            else {
              alert("Error - " + data.headers.error_message);
            }
         })
         .error(function(x, status, error) {
           alert(error);
         });
     };
});

What I'm specifically interested in knowing is:

Am I writing the JavaScript for the controller correctly? It seems to work, but I can't help but feel like I'm not writing it the way actual JavaScript developers would.
Am I using the AngularJS directives correctly in the HTML? I'm especially concerned if I'm using the ng-if as it's intended.
Plus anything that may catch your eye that could be improved.

To view the whole application feel free to view it on GitHub.

Some pointers:

Move $http.get out of the controller to a service. Stuff that is not presentation logic should not be in your controller.
getAlbums should probably be a method of the controller and not the $scope , see this video on egghead.io on how to use controller as syntax.
I don't really see the point in your ng-if="albums.length > 0". Why is it there?
It's common practice to postfix your controllers - so AlbumController or AlbumCtrl are more common names. I usually try to stick to conventions like this to convey intent more clearly.
If you're considering minification - consider using the minification syntax - start by reading this.


AvoidRoads - TopCoder Challenge I'm learning Dynamic Programming, following the topcoder guide. I just solved the AvoidRoads challenge. It passes all the test cases, but I don't have much experience, so I don't know if it's good.

  Challenge Description

  Linked description contains images and better illustrates the problem.

  You are standing at the corner with coordinates 0,0. Your destination
  is at corner width,height. You will return the number of distinct
  paths that lead to your destination. Each path must use exactly
  width+height blocks. In addition, the city has declared certain street
  blocks untraversable. These blocks may not be a part of any path. You
  will be given a String[] bad describing which blocks are bad. If
  (quotes for clarity) "a b c d" is an element of bad, it means the
  block from corner a,b to corner c,d is untraversable. For example,
  let's say

width  = 6
length = 6
bad = {"0 0 0 1","6 6 5 6"}

Returns: 252

My Solution:

def allowed(i, j, x, y, banned_set):
    s = "{} {} {} {}"
    options = [
        s.format(i, j, x, y),
        s.format(x, y, i, j)
     ]

    for opt in options:
        if opt in banned_set:
            return False
    return True

def calc(lst, i, j, banned_set):
    result = 0
    if i-1 >= 0 and allowed(i, j, i-1, j, banned_set):
            result += lst[i-1][j]
    if j-1 >= 0 and allowed(i, j, i, j-1, banned_set):
            result += lst[i][j-1]

    return result

def avoid_roads(n, m, banned_set):
    n += 1
    m += 1

    matrix = [[0 for _ in xrange(m)] for _ in xrange(n)]
    matrix[0][0] = 1

    for i in xrange(n):
        for j in xrange(m):
            if i == j == 0:
                continue
            matrix[i][j] = calc(matrix, i, j, banned_set)
    return matrix[-1][-1]

Your logic seems solid, but there's a couple of things I would do differently.

One obvious improvement is that you don't need to hold the full dynamic programming array in memory: it is enough to keep the previous row and the one you are working on. It also leads to a pretty neat handling of edge cases, as you'll see soon enough.

I am also a little weary about the approach of your allowed function: relying on a string representation just doesn't feel right. I also frown at your adding both the forward and the reverse paths to your banned set: the only reason you can use DP in the first place is because you can only move forward in both directions, so you might as well take advantage of that knowledge, and store only the direction you will eventually find.

A possible implementation of all that could be:

def banned_roads(banned_strings):
    banned_paths = {}
    for banned_string in banned_strings:
        banned_coords = [int(item) for item in banned_string.split()]
        banned_coords = [tuple(banned_coords[:2]), tuple(banned_coords[2:])]
        banned_coords.sort()  # we always move towards larger coords
        src, dst = banned_coords
        banned_srcs = banned_paths.setdefault(dst, [])
        banned_srcs.append(src)
    return banned_paths

def avoid_roads(rows, cols, banned_paths):
    rows += 1
    cols += 1
    prev_row = [1] + [0] * (cols - 1)
    for row in range(rows):
        this_row = []
        before = 0
        for col, above in enumerate(prev_row):
            banned_srcs = banned_paths.get((row, col), [])
            if (row, col - 1) in banned_srcs:
                before = 0
            if (row - 1, col) not in banned_srcs:
                before += above
            this_row.append(before)
        prev_row = this_row
    return prev_row[-1]

if __name__ == '__main__':
    assert 252 == avoid_roads(6, 6, banned_roads(['0 0 0 1', '6 6 5 6']))
    assert 2 == avoid_roads(1, 1, {}})
    assert 112186277816662845432 == avoid_roads(35, 31, {}})
    assert 0 == avoid_roads(6, 6, banned_roads(['0 0 1 0', '1 2 2 2',
                                                '1 1 2 1']))

Note how the initialization of prev_row and before spares us from having to check if we are at the first row or column, which I think makes the logic cleaner. I am also a big fan of enumerate over iterating over a range and extracting the entry via indexing, but YMMV.


Splitting a String into words and add to an array, Only using StringBuffer and String Array I've been doing a Java for beginners course for a few weeks (2 hours a week), we had an exam question.

  Take a sentence as an input from a user for twitter. Using only String
  Arrays and String Buffers (do not use split() or any other methods not
  covered in class yet). Separate the sentence into words and add to an
  array. Then change any instance of the word "cannot" with "can't".
  Must use an instantiable class and all relevant set, compute, get
  methods covered. Comment all code to show you understand what
  everything you've used is doing.

This is the code I submitted (it works), looking for feedback before the results come out to see what I can expect.

Thanks

App Class
    enter code here

public class tweetApp{
    public static void main(String arg[]){
        //decalre variables
        String sentence;
        //create an array for the new sentence
        String [] newSentence;

        //instaniate classes
        tweet myTweet;
        Scanner input;
        //creat classes
        myTweet = new tweet();
        input = new Scanner(System.in);

        System.out.print("Enter a sentence: ");
        sentence = input.nextLine();

        //set method for the sentence inputted from the user
        myTweet.setSentence(sentence);
        //compute method for chaging the sentence given by the user
        myTweet.computeSentence();
        //set the array to the new changed sentence
        newSentence = myTweet.getNewSentence();
        //output each section of the array and a space, to print out the entire message
        for(int y = 0; y < newSentence.length; y++){
            System.out.print(newSentence[y]+" ");

        }
        //end the program by adding a blank print line to make sure the command line looks ok.
        System.out.println();
    }
}

enter code here

Instantiable class

enter code here
public class tweet{
    //declare variables
    private String sentence;
    private int strlen;
    private StringBuffer word;
    private String newSentence[];
    private String newWord;
    private int wordCount;
    //create constuctor
    public tweet(){
        sentence = " ";
        strlen = 0;
        word = new StringBuffer();
        wordCount = 1; //starting at 1 if user enters 1 word
        newSentence = new String[wordCount];
        newWord = " ";
    }
    //set method
    public void setSentence(String sentence){
        this.sentence = sentence;
    }
    //compute method
    public void computeSentence(){
        strlen = sentence.length();//get length of sentence
        for(int x = 0; x < strlen; x++){//transverse the string,
            if(sentence.charAt(x)==' '){//calculate word count
                wordCount = wordCount +1;
            }
        }
        newSentence = new String[wordCount]; //use word count to set size of the array
        for(int j = 0; j < newSentence.length; j++){//transverse the array,
            for(int i = 0; i< strlen; i++){//transverse string,
                if(sentence.charAt(i) == ' '){//check if char is a space,
                    j = j+1;//if so,increment j by 1
                    word = new StringBuffer();//start a new buffer
                }
                else{
                    word.append(sentence.charAt(i));//char at i, append to buffer,
                    newWord = word.toString();//convert buffer to string,
                    newSentence[j] = newWord;//add to j'th place of array
                    }
            }
        }
        for(int x = 0; x < newSentence.length; x++){//change any instance of cannot to can't
            if(newSentence[x].equalsIgnoreCase("cannot")){
                newSentence[x] = "can't";
            }
        }
    }
        //get method, returning new sentence to app class
        public String[] getNewSentence(){
            return newSentence;
        }
    }

Thanks for sharing your code,

This looks very good for just having a few weeks' experience.

Let's start with a some small things,

1 Initialization vs declaration

this line of code tweet myTweet; declares a variable, while this line of code myTweet = new tweet(); instantiates it. When possible it's preferable to do both on the same line. This has a few benefits.

There's less change for things to go wrong. In a larger application, there could be many things happening between declaration and initialization leading to potentially difficulty to track down bugs.
It makes the code easier to follow for other developers (and future you)

for these reasons, I would prefer to see

tweet myTweet = new tweet();
Scanner input = new Scanner(System.in);
String sentence = input.nextLine();

etc.

2 Java naming conventions

Classes should start with a capital letter. You'll notice all the standard library classes begin with a capital letter (String, List, Scanner etc.) while primitive types (int, float, double) start with a lower case letter. With this in mind, it would be better to have your class called Tweet

3-0 Add setters to classes only if you absolutely need to

If your code, you call myTweet.setSentence(sentence); setters generally exist when you need to update the state of an object some time after its creation, in this case, we update it right away! Why not simply pass sentence as another constructor argument, it could look like this.

Scanner input = new Scanner(System.in);
String sentence = input.nextLine();
Tweet myTweet = new Tweet(sentence);

No need to update the Tweet once it has been created.

3-1

Staying on the topic of unnecessary mutation, we call myTweet.computeSentence(); the first thing I notice about this method is that it has a void return type. This usually means one thing. side effects. In this context, a side effect means we call a method and something else is happening (in this case, we're mutating the state of the object.)

One other potential problem, is that in order for me to get the expected result from myTweet.getNewSentence(); I need to remember to call myTweet.computeSentence(); first! In a small program, not a big deal, but as our objects get more and more complicated, this becomes more of an issue. What if my entire main method could look like this.

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    System.out.print("Enter a sentence: ");
    String sentence = input.nextLine();
    Tweet myTweet = new Tweet(sentence);
    String [] newSentence = myTweet.getNewSentence();
    for(int y = 0; y < newSentence.length; y++){
        System.out.print(newSentence[y]+" ");
    }
    System.out.println();
}

This is very similar to what you already have. But there area few notable changes.
1. I declare and initialize variables at the same time.
2. I pass all dependencies to the Tweet constructor (the sentence) at creation time.
3. I don't need to remember to call certain setup methods (computeState)
4. Conform to Java naming standards (Tweet vs tweet)

4 Storing unneeded instance variables

Let's take a quick look at the Tweet class, so we store all these

private String sentence;
private int strlen;
private StringBuffer word;
private String newSentence[];
private String newWord;
private int wordCount;

I was curious as to why we need to store all these. In our constructor, we initialize a lot of them. Why not just do that in the getNewSentence method instead

We end up with a Tweet class that looks like

public class Tweet {

    private String sentence;

    public Tweet(String sentence){
        this.sentence = sentence;
    }

    //get method, returning new sentence to app class
    public String[] getNewSentence(){
        StringBuffer word = new StringBuffer();
        String newWord = " ";
        int wordCount = 1;

        int strlen = sentence.length();//get length of sentence
        for(int x = 0; x < strlen; x++){//transverse the string,
            if(sentence.charAt(x)==' '){//calculate word count
                wordCount = wordCount +1;
            }
        }
        String[] newSentence = new String[wordCount]; //use word count to set size of the array
        for(int j = 0; j < newSentence.length; j++){//transverse the array,
            for(int i = 0; i< strlen; i++){//transverse string,
                if(sentence.charAt(i) == ' '){//check if char is a space,
                    j = j+1;//if so,increment j by 1
                    word = new StringBuffer();//start a new buffer
                }
                else{
                    word.append(sentence.charAt(i));//char at i, append to buffer,
                    newWord = word.toString();//convert buffer to string,
                    newSentence[j] = newWord;//add to j'th place of array
                }
            }
        }
        for(int x = 0; x < newSentence.length; x++){//change any instance of cannot to can't
            if(newSentence[x].equalsIgnoreCase("cannot")){
                newSentence[x] = "can't";
            }
        }
        return newSentence;
    }
}

With this class, we don't need to worry about who used it before, or how they used it. It will never be in a bad state we can call getNewSentence all day long and it will always return the same thing, no need to worry about set up with setSentence or computerState

Hopefully you found this review useful, I'd like to reiterate again that this looks very good for just a few weeks! Keep it up!


Finding dictionary keys whose values are duplicates I currently have a dictionary (Duplicate_combos) that has a unique identifying number for the key value and the value is a list with two elements, a company code and then either a yes or no (both of these values are currently stored as strings). I am essentially just trying to see where the company code is equal and the second term is no for both.
So if this was my dictionary:

{1234: ['123' , 'No'] , 1235:['123', 'No'], 1236: ['123','Yes'], 1237: [124,'No']}

I would only want to return 1234 and 1235. The code below is what I currently have and I really need to optimize it because while it does work when I tested it on a small data set, I will need to use it on a much larger one (43,000 lines) and in early testing, it is taking 45+ minutes with seemingly no sign of ending soon.

def open_file():

    in_file = open("./Data.csv","r")
    blank = in_file.readline()
    titles = in_file.readline()
    titles = titles.strip()
    titles = titles.split(',')

    cost_center = [] # 0
    cost_center_name = []# 1
    management_site = [] # 15
    sub_function = [] #19
    LER = [] #41
    Company_name = [] #3
    Business_group = [] #7
    Value_center = [] #9
    Performance_center = [] #10
    Profit_center = [] #11

    total_lines = {}

    for line in in_file:

        line = line.strip()
        line = line.split(',')
        cost_center.append(line[0])
        cost_center_name.append(line[1])
        management_site.append(line[15])
        sub_function.append(line[19])
        LER.append(line[41])
        Company_name.append(line[3])
        Business_group.append(line[7])
        Value_center.append(line[9])
        Performance_center.append(line[10])
        Profit_center.append(line[11])

        # create a dictionary of all the lines with the key being the unique cost center number (cost_center list)
        total_lines[line[0]] = line[1:]

    return(cost_center, cost_center_name, management_site, sub_function, LER, Company_name, Business_group, total_lines, titles, Value_center, Performance_center, Profit_center)

def find_duplicates(Duplicate_combos):

    Real_duplicates = []
    archive_duplicates = []

    # loop through the dictionary of duplicate combos by the keys
    for key in Duplicate_combos:
       code = Duplicate_combos[key][0]
       for key2 in Duplicate_combos:
           # if the two keys are equal to each other, it means you are comparing the key to itself, which we don't want to do so we continue
            if key == key2:
               continue
            # if the company codes are the same and they are BOTH NOT going to be consolidated, we have found a real duplicate
            elif Duplicate_combos[key2][0] == code and Duplicate_combos[key2][1] == 'No' and Duplicate_combos[key][1] == 'No':
                # make sure that we haven't already dealt with this key before
                if key not in archive_duplicates:
                    Real_duplicates.append(key)
                    archive_duplicates.append(key)

                if key2 not in archive_duplicates:
                    Real_duplicates.append(key2)
                    archive_duplicates.append(key2)
            continue
    return(Real_duplicates)

It's easier to read code that tuple unpacks the values in the for from dict.items().

for key1, (code1, option1) in Duplicate_combos.items():

archive_duplicates is a duplicate of Real_duplicates. There's no need for it.
It doesn't seem like the output needs to be ordered, and so you can just make Real_duplicates a set. This means it won't have duplicates, and you don't have to loop through it twice each time you want to add a value.

This alone speeds up your program from \$O(n^3)\$ to \$O(n^2)\$.
Your variable names are quite poor, and don't adhere to PEP8. I have changed them to somewhat generic names, but it'd be better if you replace, say, items with what it actually is.

def find_duplicates(items):
    duplicates = set()
    for key1, (code1, option1) in items.items():
       for key2, (code2, option2) in items.items():
            if key1 == key2:
               continue
            elif code1 == code2 and option1 == option2 == 'No':
                duplicates.add(key1)
                duplicates.add(key2)
    return list(duplicates)

You don't need to loop over Duplicate_combos twice.

To do this you need to make a new dictionary grouping by the code. And only adding to it if the option is 'No'.

After building the new dictionary you can iterate over it's values and return ones where the length of values is greater or equal to two.

def find_duplicates(items):
    by_code = {}
    for key, (code, option) in items.items():
        if option == 'No':
            by_code.setdefault(code, []).append(key)

    return [
        key
        for keys in by_code.values()
        if len(keys) >= 2
        for key in keys
    ]

This now runs in \$O(n)\$ time rather than \$O(n^3)\$ time.

>>> find_duplicates({
        101: ['1', 'No'], 102: ['1', 'No'],
        103: ['1','Yes'], 104: ['1', 'No'],
        201: ['2', 'No'], 202: ['2', 'No'],
        301: ['3', 'No'], 401: ['4', 'No'],
})
[101, 102, 104, 201, 202]


Notification system using PHP+jQuery+Ajax I have this code to display a counter on the side of . I want to know if this code is good on security and perfomance.

I just started using jquery and ajax, i had heard people saying that someone could disable the javascript and do bad things. What you guys think about my code?

                    titutlo

script:

select.php

<?php
require_once 'db.php';

if(!isset($_SESSION))session_start();

if(isset($_SESSION['userid'])) {
  $userid = $_SESSION['userid'];
}

    $status = 'unread';

    $sql = $conn->prepare("SELECT * FROM noti WHERE status = :status AND
    userid = :userid");
    $sql->bindParam(':userid', $userid, PDO::PARAM_INT);
    $sql->bindParam(':status', $status, PDO::PARAM_STR);
    $sql->execute();
    $countNT = $sql->rowCount();

    echo $countNT;

    $conn = null;

    ?>

update.php

<?php
require_once 'db.php';

if(!isset($_SESSION))session_start();

if(isset($_SESSION['userid'])) {
  $userid = $_SESSION['userid'];
}

$status = 'read';
$sql = $conn->prepare("UPDATE noti SET status = :status WHERE userid = :userid");
$sql->bindParam(':user_id', $userid, PDO::PARAM_INT);
$sql->bindParam(':status', $status, PDO::PARAM_STR);
$sql->execute();
$countNT = $sql->rowCount();

echo $countNT;

$conn = null;
?>

JAVASCRIPT SECURITY
Javascript is running on the client, and is therefore under full control of the user. It can be disabled, inspected, manipulated, and everything else that can done in a programming language. You knew this, didn't you?
Javascript is, almost by definition, insecure. Things that have to do with the security of your site, like validating passwords, should not be done in Javascript. And in your code you don't do anything security related in Javascript. All you do is set a timer running and call two PHP scripts. No risks there.

PHP SECURITY
The PHP scripts are another matter. Here is where things really happen, and you should implement your security measures here. Even though these scripts implement AJAX calls, they can be executed by anybody.
You seem to have users, that can log in. Their user ID is stored in $_SESSION['userid']. I notice that you don't do anything, in your PHP scripts, when this ID is absent. You still execute the database queries. That is a bad idea.
When the two current PHP scripts are called, without an user ID, they will probably just perform database queries that are invalid. No real harm done. But you shouldn't rely on just pure luck. Good security should leave no doubts about what will happen.
I therefore propose I slight change to your code. Instead of writing this:
if (isset($_SESSION['userid'])) {
  $userid = $_SESSION['userid'];
}

you could write this:
if (!isset($_SESSION['userid'])) die('Not logged in.');
$userid = $_SESSION['userid'];

this means that the PHP scripts will halt execution when there's no user, as they should.

PERFORMANCE
You code is evidently not very efficient. Polling the database every second does not scale very well. There are other ways to do this. For instance with web sockets: https://developer.mozilla.org/en-US/docs/Web/API/Websockets_API ( you would use a combination of the tools mentioned there). Updates will be quicker, without polling.
For now polling will probably be fine for you, after all you're still learning Jquery and that is a challenge in itself. It takes time to understand how everything hangs together.


REST web service in Express I have made a REST web service using the Express framework. Here is my snippet of code, which has repeated code. I am creating a currencyItem object in two blocks and push it into an array.

I think it is not bad practice. Can anyone suggest if it is OK? If not, how can I improve it?

/** API to get all currency price */
router.get("/:ticker?", function(req, res, next) {
  var currencyList = [];

  // it can be null as ticker is optional parameter
  let reqCurrencyName = req.params.ticker;

  rp(baseUrl)
    .then(body => {
      const $ = cheerio.load(body);
      $("tr").each(function name(i, elem) {
        // currency name
        var currencyName = $(this)
          .find("td")
          .eq(1)
          .text()
          .replace(/\r?\n|\r/g, " ")
          .trim();

        // market cap value
        var marketCap = $(this)
          .find("td")
          .eq(2)
          .text()
          .replace(/\r?\n|\r/g, " ")
          .trim();

        // currency price
        var price = $(this)
          .find("td")
          .eq(3)
          .text()
          .replace(/\r?\n|\r/g, " ")
          .trim();

        // date supply value
        var dataSupply = $(this)
          .find("td")
          .eq(4)
          .text()
          .replace(/\r?\n|\r/g, " ")
          .trim()
          .replace(/ /g, "");

        // volume value
        var volume = $(this)
          .find("td")
          .eq(5)
          .text()
          .replace(/\r?\n|\r/g, " ")
          .trim();

        // negative change value
        var negativeChange = $(this)
          .find("td")
          .eq(6)
          .text()
          .replace(/\r?\n|\r/g, " ")
          .trim();

        // first item is empty in response so lets not push it into an array
        if (currencyName !== "") {
          if (reqCurrencyName !== undefined) {
            if (currencyName === reqCurrencyName) { // execute single time
              const currencyItem = {
                currencyName: currencyName,
                marketCap: marketCap,
                price: price,
                dataSupply: dataSupply,
                volume: volume,
                negativeChange: negativeChange
              };

              currencyList.push(currencyItem);
            }
          } else {
            const currencyItem = {
              currencyName: currencyName,
              marketCap: marketCap,
              price: price,
              dataSupply: dataSupply,
              volume: volume,
              negativeChange: negativeChange
            };

            currencyList.push(currencyItem);
          }
        }
      });
      res.send(currencyList);
    })
    .catch(err => {
      rollbar.log(err);
      res.send({ error: err });
    });
});

What you're essentially doing is transforming a list to another list (a list of <tr> to an array). Instead of jquery.each() and pushing to an array, use jquery.map() instead. jquery.map() works like array.map() except it returns a jQuery collection (an array-like object with jQuery metadata). You can bolt on jquery.get() at the end to convert it to a plain array afterwards.

There's also a shorter version of jquery.find - using the $ function with two arguments. The first being the selector, the second being the context. Internally, this just does jquery.find but from an authoring point of view, it's just shorter. In addition, you can use the :eq() selector in place of jquery.eq().

Now the above advice is for jQuery. I'm not exactly sure how identical the Cheerio API is to the jQuery API, but if they are, the above advice will probably hold.

As mentioned in the other answer, your code is heavily duplicated. A common advice is to move it out to a function and call that function. But you do not simply do that. I recommend taking a functional approach. You pass in all the arguments needed for the function to work, and operate on those arguments. This keeps the function independent from scope, variable visibility, side effects and so on.

Also suggesting using let and const whenever possible, preferrably const if you don't expect a variable's value to change. This signals other readers of your code what a variable should be, if it's supposed to be block-scoped or not, if the value can be changed or not.

There's also object property shorthands. If the variable you're assigning to an object property has the same name as the property, you can omit the : and the right-hand side.

Update: I've always been told (and I always forget) to pull filter operations early on in the stream. This reduces the number of iterations down the stream, avoiding unnecessary iterations. In this case, we filter out all entries without currency name first to avoid scraping and data generation for them.

const getText = element => element.text().replace(/\r?\n|\r/g, " ").trim();

router.get("/:ticker?", function(req, res, next) {
  const reqCurrencyName = req.params.ticker

  rp(baseUrl).then(body => {
    const $ = cheerio.load(body);
    const currencies = $("tr").filter((i, e) => {
      // Filter rows with no currency name
      return Boolean(getText($('td:eq(1)', e)))
    }).map((i, e) => ({
      // Construct the object
      currencyName: getText($('td:eq(1)', e))
      marketCap: getText($('td:eq(2)', e))
      price: getText($('td:eq(3)', e))
      dataSupply: getText($('td:eq(4)', e)).replace(/ /g, "")
      volume: getText($('td:eq(5)', e))
      negativeChange: getText($('td:eq(6)', e))
    }))

    // Respond
    res.send(currencies.get())
  })
  .catch(error => {
    rollbar.log(error)
    res.send({ error })
  })
})


Contest Solution: Packet Sniffer The Problem

  Sniffed any good packets lately, dude? Hopefully you haven’t done this illegally, but rest assured that there
  are some who have. If you surf the Internet, you have probably visited companies’ net sites where they sell
  their products online: you give them your credit card number and they ship you the goods. That’s a
  convenient way to shop if you can ensure that your credit card number isn’t being “sniffed” up by wily
  hackers and used illicitly.

  The Internet is an example of a packet-switched network. This means that information is sent in
  discrete groups of bits called packets from computer to computer. For example, when I send email to
  someone in the Philippines, my message (at the binary level) is broken up into packets, and routed packet
  by packet (not all at once) from computer to computer, ultimately to the recipient’s computer.

  “Packet sniffing” refers to writing a program that grabs the individual packets that come your
  computer’s way and reads their contents. Now the term “packet sniffing” has obvious unethical
  connotations: usually it refers to writing a program that reads packets addressed to computers other than
  your own. But the principle is exactly the same when you only intercept those packets that are intended for
  you.

  Let’s suppose that a network packet consists of three parts: a special start-of-packet bit pattern,the packet content, and a special end-of-packet bit pattern. Suppose that the start- and end-of-packet
  pattern are both 1000001 and that the packet content is no more than three consecutive sequences of 7 bits(1’s and 0’s). So, to write a program to “sniff” packets you need only to write a program that scans its
  input and “decodes” everything between pairs of 1000001.

  For this problem assume that the content of each packet is binary representation of no more than
  three ASCII characters, each encoded in 7 “bits” (0’s and 1’s). Your task is to write a program that prints
  out the message (in English) that is being transmitted by a sequence of packets.

  Sample Input

  Take your input from the text file prob4.in. Here’s a sample of its content:

10000011100010110111111011111000001100000101000011000001

  You are guaranteed two things: (1) the encoding is correct, and (2) only lower case letters and punctuation are encoded in the packet.

  Sample Output

  Your program should direct its output to the screen. The correct output for the sample input above is:

boo!

packetsniffer.py

with open('prob4.in') as f:
    for line in f:
        line = line.strip().replace('1000001', '')
        print(''.join([chr(int(c, 2)) for c in [line[i:i+7] for i in range(0, len(line), 7)]]))

Any advice on performance enhancement, solution simplification or that is topical is appreciated!

Your code looks good, except that you do not really need the c, and hence the nesting, in the list comprehension. You can use line[i:i+7] directly in int, making it a bit shorter:

''.join([chr(int(line[i:i+7], 2)) for i in range(0, len(line), 7)])

However, just removing the 1000001 in the line before seems a bit arbitrary, since (a) the pattern might also be present within a package, spanning two bytes. Instead, you could keep the c variable and ignore the current c if it equals the package delimiter:

>>> line = "10000011100010110111111011111000001100000101000011000001"
>>> ''.join([chr(int(c, 2)) for c in (line[i:i+7] for i in range(0, len(line), 7)) if c != "1000001"])
'boo!'

But, you still lose the information where the packages start and end.
Instead, you could use regular expressions for first detecting the packages, and then finding the bytes within those:

>>> p = r"1000001((?:[01]{7}){,3})1000001"
>>> re.findall(p, line)
['110001011011111101111', '0100001']

Here, p means "package delimiter, followed by up to three groups of seven 0 or 1, followed by delimiter. Then you can use another regex q to split those into bytes.

>>> q = r"[01]{7}"
>>> [''.join(chr(int(x, 2)) for x in re.findall(q, y)) for y in re.findall(p, line)]
['boo', '!']

Of course, the regex q is a bit redundant, since we already checked the same in p. You could also do this part using a range and string slicing, but personally I still find the regex approach cleaner.

>>> [''.join(chr(int(y[i:i+7], 2)) for i in range(0, len(y), 7)) for y in r e.findall(p, bits)]
['boo', '!']

Another way, without regex, might be to first separate the line into groups of 7 bits, and then using itertools.groupby to group those parts into package-delimiter and package-contents:

>>> parts = [line[i:i+7] for i in range(0, len(line), 7)]
>>> groups = [list(g) for k, g in groupby(parts, key="1000001".__ne__) if k]
>>> [''.join(chr(int(b, 2)) for b in g) for g in groups]
['boo', '!']


Embedding code into a website I'm using an HTML editor to insert code into a website. When you embed media like an iframe element, it deletes the code.

It's apparently a bug with TINYMce and grappelli, so as a workaround, I insert non-media content into the HTML editor:

width="854" height="480" src="https://www.youtube.com/embed/knYelygG1fI" frameborder="0" allowfullscreen

and then use DOM manipulation to replace the necessary elements.

It might be better to select by class, but I'm not sure how to do that in JavaScript. I've used jQuery innerWrap(), append() and prepend() too, which works. However, as soon as the YouTube embed URL is inserted into the iframe element:

iframe src="youtube/embed/movie"

the videos don't show and the iframes disappear.

This code works, but it just isn't very DRY. I've tested it on an Nginx server, hosted by Digital Ocean. The number of videos is also limited by the number of var strMessage, etc. I have physically written into the template, which isn't very dynamic.

width="854" height="480" src="https://www.youtube.com/embed/knYelygG1fI" frameborder="0" allowfullscreen

width="854" height="480" src="https://www.youtube.com/embed/_9RhLQvr0oc?autoplay=1

width="854" height="480" src="https://www.youtube.com/embed/_9RhLQvr0oc?autoplay=1

You can use querySelectorAll how @Pavlo says in his comment. It would work:


I couldn't figure out a cleaner solution than an infinite loop. Is this approach considered bad practice?

You can't do much better, since Python doesn't have the equivalent of a C-style do/while.
This is a trivial program so I doubt it's even worth adding functions (etc.); the one thing that can be improved is
if (z >= 0 and z <= 20):

can be
if 0 <= z <= 20:


Printing a 2-D array diagonally The case scenario:

A  2-D array is given:

1  3  6  10 15
2  5  9  14 19
4  8  13 18 22
7  12 17 21 24
11 16 20 23 25

and its size N is given as 5.

The program should output it as

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25

The code I wrote for this problem:

#include <stdio.h>

void main()
{
    int N = 5;
    int pixel_array[5][5] = {
        {1, 3, 6, 10, 15}, {2, 5, 9, 14, 19}, {4, 8, 13, 18, 22}, {7, 12, 17, 21, 24}, {11, 16, 20, 23, 25}

    };

    for (int row = 0; row < N; row++)
    {
        if (row < N - 1)
        {
            for (int temp_row = row, col = 0; temp_row >= 0; temp_row--, col++)
                printf("%d ", pixel_array[temp_row][col]);
        }
        else
        {
            for (int col = 0; col < N; col++)
                for (int temp_col = col, temp_row = N - 1; temp_col < N; temp_col++, temp_row--)
                    printf("%d ", pixel_array[temp_row][temp_col]);
        }
    }
}

The above code works fine and outputs the required result.

Some specific questions:

Since there are many for loops here -

how can I decrease code length?
how can I improve the efficiency of this program?
Any other programming practices to be implemented?

Any advice would help.

How can I decrease code length?

You could split your big for loop into 2 smaller ones. The first one would print all diagonals up to the main one, and the other one the remaining ones.

For instance, let's say there's a matrix like:

1 2 3
4 5 6
7 8 9

Then, your first loop would print 1 4 2 7 5 3 and the second one 8 6 9. The code would look conciser and more readable too:

for (int i = 0; i < N; i++) {
    for (int j = 0; j <= i; j++) {
        printf("%d ", pixel_array[i - j][j]);
    }
}

for (int j = 0; j < N - 1; j++) {
    for (int i = N - 1; i > j; i--) {
        printf("%d ", pixel_array[i][N - i + j]);
    }
}

  How can I improve the efficiency of this program?

I don't think it's possible to make it more efficient than O(n²) as you have to go through all matrix elements to print them diagonally. So, the suggested solution is efficient enough.

  Any other programming practices to be implemented

Rather than using an int type for defining a size of your array, you could use uint32_t (or uint16_t or uint64_t - it depends on your requirements). Your size cannot be negative, anyways. So, change int N = 5; to const uint32_t N = 5.

Rename your array to squareMatrix because you're actually dealing with square matrices in your app.

Also, create a method out of your algorithm block - but I'll leave it up to you.


PDO Database Auto Table Creator How can I do the following with less nested loops.
How can I output the Table names above their corresponding tables without having to loop.

Functions for returning the DB Info:

// Return all the Table names in an array
public function getDbTables() {
    $result = $this->query("SHOW TABLES");
    while ($row = $result->fetchAll(PDO::FETCH_COLUMN)) {
        return $row;
    }
}

// Return ALL column names for each Table available
public function getColumnNames($table){
    $sql = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = :table";
    try {
        $stmt = $this->dbh->prepare($sql);
        $stmt->bindValue(':table', $table, PDO::PARAM_STR);
        $stmt->execute();
        $output = array();
        while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
            $output[] = $row['COLUMN_NAME'];
        }
        return $output;
    }

    catch(PDOException $pe) {
        trigger_error('Could not connect to MySQL database. ' . $pe->getMessage() , E_USER_ERROR);
    }
}

// Populate HTML Table with the DB Table Data
public function populateTable($table) {
    $sql = "SELECT * FROM $table";
    try {
        $stmt = $this->dbh->prepare($sql);
        $stmt->execute();
        while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
            return $row;
        }

    }
        catch(PDOException $pe) {
        trigger_error('Could not connect to MySQL database. ' . $pe->getMessage() , E_USER_ERROR);
    }
}

HTML Output:

<?php print_r($phpCore->getDbTables()); ?>

<form>

<?php
foreach($phpCore->getDbTables() as $tablename) {
    echo '
';
    foreach($phpCore->getColumnNames($tablename) as $fieldnames) {
        echo ''.$fieldnames.'	';
    }
    echo '
';

    echo '
';
    foreach($phpCore->populateTable($tablename) as $tabledata) {
        echo '<input type="text" value="'.$tabledata.'"></input>	';
    }
    echo '
';
}
?>

</form>

Visual Output:

Ok, so I'm happy with the foreach loops now.

To get the Table names where I wanted them I simply had to encapsulate the PHP in HTML tags:

<?php print_r($phpCore->getDbTables()); ?>

<form>

<?php
foreach($phpCore->getDbTables() as $tablename) {
    echo '
'.$tablename.'
';
    echo '
';
    foreach($phpCore->getColumnNames($tablename) as $fieldnames) {
        echo ''.$fieldnames.'	';
    }
    echo '
';

    echo '
';
    foreach($phpCore->populateTable($tablename) as $tabledata) {
        echo '<input type="text" value="'.$tabledata.'"></input>	';
    }
    echo '
';

}
?>

</form>


Tornado: async calls and DB caching import tornado.web
from selenium import webdriver
import sys
import psycopg2
from selenium.common.exceptions import NoSuchElementException

class LevelHandler(tornado.web.RequestHandler):
    def __init__(self, application, request, **kwargs):
        super().__init__(application, request, **kwargs)
        self.conn_string = "credentials_here"
        self.conn = psycopg2.connect(self.conn_string)
        self.cursor = self.conn.cursor()

    def get(self, word):
        driver = webdriver.PhantomJS(executable_path=r'bin/phantomjs')
        driver.get(url="http://dictionary.cambridge.org/dictionary/english/%s" % word)
        is_word_cached = self.check_cache(word)
        if is_word_cached:
            response = {'level': is_word_cached[0][0]}
        elif self.check_word_404(driver):
            response = {'level': "This word wasn't found"}
        else:
            try:
                level = driver.find_element_by_xpath(xpath="//span[@class='def-info']/span[contains(@title,'A1-C2')]")
                level = level.text
            except NoSuchElementException:
                level = "The word level isn't known"
            self.write_cache(word, level)
            response = {'level': level}

        self.write(response)

    def check_cache(self, word):
        self.cursor.execute("SELECT level FROM eng_level WHERE word = '{0}'".format(word))
        records = self.cursor.fetchall()
        return records

    def write_cache(self, word, level):
        self.cursor.execute("INSERT INTO eng_level (word, level) values (%s, %s)", (word, level,))
        self.cursor.execute("COMMIT")

    def check_word_404(self, driver):
        try:
            return driver.find_element_by_xpath(xpath="//h1[contains(text(),'404. Page not found.')]")
        except NoSuchElementException:
            return False

application = tornado.web.Application([
    (r"/([A-Za-z]+)", LevelHandler)
])

if __name__ == "__main__":
    application.listen(str(sys.argv[1]))
    tornado.ioloop.IOLoop.instance().start()

The idea is to fetch the word complexity from a dictionary. I use Selenium and XPath to do this, but once a word is fetched from the external HTML I store it in the database as a cache.

Questions:

Is everything asynchronous here?
I'm only 1.5 times faster: the average response from the external website is 4s and from Postgres cache 2.5s. Can I do better?

1.This handler isn't asynchronous.

The easiest way to accomplish this with tornado is to make a coroutine like so:

@gen.coroutine
def get(self, word):
    driver = webdriver.PhantomJS(executable_path=r'bin/phantomjs')
    yield driver.get(url="http://dictionary.cambridge.org/dictionary/english/%s" % word)
    is_word_cached = self.check_cache(word)
    if is_word_cached:
        response = {'level': is_word_cached[0][0]}
    elif self.check_word_404(driver):
        response = {'level': "This word wasn't found"}
    else:
        try:
            level = driver.find_element_by_xpath(xpath="//span[@class='def-info']/span[contains(@title,'A1-C2')]")
            level = level.text
        except NoSuchElementException:
            level = "The word level isn't known"
        self.write_cache(word, level)
        response = {'level': level}

    self.write(response)

The main thing is to decorate the get method with @gen.coroutine and then have a yield statement in the blocking line, in your case the fetching of the data. Documentation here

You can store the cache in a in-memory database like Redis, Memcached, in plain Python or in a pickle.


Calculation of elasticity for non-linear curve I've written this code to calculate the elasticity for econometric analysis. Basically, this algorithm estimate the function:

$$\epsilon(x) = \frac{x}{f(x)}\ f'(x)$$

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

    elasticity<-function(y.p,x.p,band){
        require(KernSmooth)
        as.vector(y.p);as.vector(x.p)
            loess.fun<-locpoly(x.p,y.p,bandwidth=band)
                plot(loess.fun,type='l',lwd=2,lty=4,
                    ylim=c(0,100),xlab="Price",
                    ylab="Share", col=2,
                    main="Local Polynomials Estimation")
            loess.der<-locpoly(x.p,y.p,drv=1,bandwidth=band,
                          gridsize = length(y.p))
            y1<-as.vector(loess.der$y)
            eps<-matrix(NA,length(y.p),2)
            eps[,1]<-x.p
                for(i in 1:length(y.p)){
                    eps[i,2]<-x.p[i]/y.p[i]*y1[i]
                }
            j<-order(x.p)
            colnames(eps)<-c("Price","Elasticity")
        return(eps[j,])
    }

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

Can I improve this algorithm?

I'll provide feedback from top to bottom:

1. elasticity<-function(y.p,x.p,band){

It's recommended to use spaces to make your code easier on the eyes. Spaces also avoid ambiguous situations for people who are not experts in R's syntax rules; for example, when someone sees a<-b, is it assigning b to a, or is it asking if a is less than -b? Maybe another way to convince you is to make you notice that R's compiled code does contain spaces (run print(lapply) for example); it shows that R's authors agreed that code readability was more important than compactness.

Now about the choice of arguments. Why not use the same argument names (and order) as locpoly since it is the main function being called here? So I'd recommend x, y, bandwidth. Or maybe x.price, y.price, bandwidth if it really helps knowing these are prices.

2. require(KernSmooth)

To convince you to use library instead of require, check http://www.r-bloggers.com/library-vs-require-in-r/.

3. as.vector(y.p);as.vector(x.p)

These two calls to as.vector do nothing if you do not assign the output. You probably meant to do:

y.p <- as.vector(y.p)
x.p <- as.vector(x.p)

11. y1<-as.vector(loess.der$y)

If you check using is.vector(), you will see that loess.der$y is already a vector, so as.vector is unnecessary.

12. eps<-matrix(NA,length(y.p),2)

Would a data.frame make more sense? Or if you really want a matrix, should use be using cbind?

14. for(i in 1:length(y.p)){
15.    eps[i,2]<-x.p[i]/y.p[i]*y1[i]
16. }

Here, you are really missing up on vectorization. This should be:

eps[, 2] <- x.p / y.p * y1

Overall, if defining a data.frame, appreciate the simplicity and readability of:

eps <- data.frame(Price = x.p,
                  Elasticity = x.p / y.p * loess.der$y)

Or if you want a matrix, just replace data.frame() with cbind().

Taking all of my comments into account, your code could look like this:

elasticity <- function(x, y, bandwidth) {
   library(KernSmooth)
   x <- as.vector(x)
   y <- as.vector(y)
   loess.fun <- locpoly(x = x, y = y, bandwidth = bandwidth)
   plot(loess.fun, type = 'l', lwd = 2, lty = 4,
        ylim = c(0, 100), xlab = "Price", ylab = "Share", col = 2,
        main = "Local Polynomials Estimation")
   loess.der <- locpoly(x = x, y = y, drv = 1, bandwidth = bandwidth,
                      gridsize = length(y))

   eps <- data.frame(Price = x,
                     Elasticity = x / y * loess.der$y)

   return(eps[order(eps$Price), ])
}


Test 2 time ranges to see if they overlap I am doing a project for school and had to create a function to check if 2 time ranges overlap. I searched the net a bit but failed to find a simple function to do that. I played around a bit with my code and I think I created a working one.

Note: it works for 24 hour times only & don't forget the 0 in front of AM time e.g "08:15"

If anyone has a better function to do this or finds some bugs in the code below - please post below.

Here is the code you can test directly on.

$start_time1 = "10:15";
$end_time1 = "12:20";

$start_time2 = "13:15";
$end_time2 = "14:25";

function testRange($start_time1,$end_time1,$start_time2,$end_time2)
{
    $timeCheck;

    if(($end_time1 < $start_time2))
    {
        $timeCheck = true;
        return $timeCheck;
    }
    else if(($start_time1 > $start_time2) && ($start_time1 > $end_time2))
    {
        $timeCheck = true;
        return $timeCheck;
    }
    else
    {
        $timeCheck = false;
        return $timeCheck;
    }

}

if(testRange($start_time1,$end_time1,$start_time2,$end_time2))
{
    echo "Not In Range";
}
else
{
    echo "In Range";
}

As s3rius pointed out, you don't need the $timeCheck variable. You can just use return true; or return false;.
To parse a time use the DateTime class. You can find the supported time formats here. The constructor will throw an exception if it cannot parse the string. Consider if you want to handle the exception yourself or let the caller handle it.
What if the start time is after the end time? You can throw an exception, switch the start and end times, or not handle the error.
The meaning of the return value is not obvious based on your function name. How does it test the range? Change it to something like rangesNotOverlap or something similar so that it is apparent that true means they don't overlap.
Are time ranges open or close intervals? If one range ends at 10:00 and the other starts at 10:00, do they overlap?
Lets consider all cases:

.

             1
Case 01:  |-----|
          |-----|
             2

             1
Case 02:  |-----|
             |-----|
                2

                1
Case 03:     |-----|
          |-----|
             2

               1
Case 04:  |---------|
            |-----|
               2

               1
Case 05:    |-----|
          |---------|
               2

             1
Case 06:  |-----|
                  |-----|
                     2

                     1
Case 07:          |-----|
          |-----|
             2

             1
Case 08:  |-----|
                |-----|
                   2

                   1
Case 09:        |-----|
          |-----|
             2

             1
Case 10:     |
          |-----|
             2

             1
Case 11:  |-----|
             |
             2

          1
Case 12:  |
          |-----|
             2

                1
Case 13:        |
          |-----|
             2

             1
Case 14:  |-----|
          |
          2

             1
Case 15:  |-----|
                |
                2

          1
Case 16:  |
          |
          2

        |                         |    Operlap    |     Overlap
  Case  |         Example         | Open Interval | Closed Interval
--------|-------------------------|---------------|-----------------
Case 01 | 09:00-11:00 09:00-11:00 |      Yes      |        Yes
Case 02 | 09:00-11:00 10:00-12:00 |      Yes      |        Yes
Case 03 | 10:00-12:00 09:00-11:00 |      Yes      |        Yes
Case 04 | 09:00-12:00 10:00-11:00 |      Yes      |        Yes
Case 05 | 10:00-11:00 09:00-12:00 |      Yes      |        Yes
Case 06 | 09:00-10:00 11:00-12:00 |      No       |        No
Case 07 | 11:00-12:00 09:00-10:00 |      No       |        No
Case 08 | 09:00-10:00 10:00-11:00 |      No       |        Yes
Case 09 | 10:00-11:00 09:00-10:00 |      No       |        Yes
Case 10 | 10:00-10:00 09:00-11:00 |      Yes      |        Yes
Case 11 | 09:00-11:00 10:00-10:00 |      Yes      |        Yes
Case 12 | 09:00-09:00 09:00-10:00 |      No       |        Yes
Case 13 | 10:00-10:00 09:00-10:00 |      No       |        Yes
Case 14 | 09:00-10:00 09:00-09:00 |      No       |        Yes
Case 15 | 09:00-10:00 10:00-10:00 |      No       |        Yes
Case 16 | 09:00-09:00 09:00-09:00 |      No       |        Yes

Your function returns the correct result on the closed interval for all cases.

We can make your code simpler by noticing that we only have to check for two cases. The ranges don't overlap only if end1 < start2, (the same as your first if), or if end2 < start1 (which is included in your second if). The other check you do start1 > start2 is redundant, because it is always true if end2 < start1.

Put it all together:

function rangesNotOverlapClosed($start_time1,$end_time1,$start_time2,$end_time2)
{
  $utc = new DateTimeZone('UTC');

  $start1 = new DateTime($start_time1,$utc);
  $end1 = new DateTime($end_time1,$utc);
  if($end1 < $start1)
    throw new Exception('Range is negative.');

  $start2 = new DateTime($start_time2,$utc);
  $end2 = new DateTime($end_time2,$utc);
  if($end2 < $start2)
    throw new Exception('Range is negative.');

  return ($end1 < $start2) || ($end2 < $start1);
}

function rangesNotOverlapOpen($start_time1,$end_time1,$start_time2,$end_time2)
{
  $utc = new DateTimeZone('UTC');

  $start1 = new DateTime($start_time1,$utc);
  $end1 = new DateTime($end_time1,$utc);
  if($end1 < $start1)
    throw new Exception('Range is negative.');

  $start2 = new DateTime($start_time2,$utc);
  $end2 = new DateTime($end_time2,$utc);
  if($end2 < $start2)
    throw new Exception('Range is negative.');

  return ($end1 <= $start2) || ($end2 <= $start1);
}


Dollar value of coins and calculating interest compounded annually I've made this program to do a few integer calculations.  Do the methods for converting the numbers look good?  Do you have any other basic tips?

/* Dollar Value of Coins, Investment Compounded Annually
 * B, Morris
 */

import java.util.*;
import java.lang.*;
import java.text.*;
public class HW3_DollarValuOfCoinsInvestmentCompoundedAnnually {
public static void main(String args[]) {
Scanner keyboard = new Scanner(System.in);
NumberFormat priceFormat = NumberFormat.getCurrencyInstance();

//Dollar value of coins

System.out.println("How many quarters do you have?");
double quarters = keyboard.nextDouble();

System.out.println("How many dimes do you have?");
double dimes = keyboard.nextDouble();

System.out.println("How many nickles do you have?");
double nickles = keyboard.nextDouble();

quarters = quarters * (0.25);
dimes = dimes * (0.10);
nickles = nickles * (0.05);
double total =(quarters + dimes + nickles);
System.out.println("You have: " + priceFormat.format(total));

//Investment Compounded Annually

System.out.println("What is the initial investment?");
double investment = keyboard.nextDouble();

System.out.println("At what intrest rate is the intrest compounded annually?");
double intrestRate = keyboard.nextDouble();

double futureValueFive = investment * (Math.pow((1 + intrestRate), (double) 5));
System.out.println("In five years the investment will be worth : " + priceFormat.format(futureValueFive));

double futureValueTen = investment * (Math.pow((1 + intrestRate), (double) 10));
System.out.println("In ten years the investment will be worth : " + priceFormat.format(futureValueTen));

double futureValueTwenty = investment * (Math.pow((1 + intrestRate), (double) 20));
System.out.println("In twenty years the investment will be worth : " + priceFormat.format(futureValueTwenty));

}
}

Choose the right types

You used double for the coin types, for example:

System.out.println("How many quarters do you have?");
double quarters = keyboard.nextDouble();
quarters = quarters * (0.25);

To the question "how many quarters ...",
it's logical to get an integer (whole number) as the answer, not a double.

I can guess that you choose the double type because you want to use the quarters variable for two different purposes:

Count the quarters
Count the dollar value of the quarters

These are conflicting meanings, and the right thing to do is to not mix them,
for example:

int quarters = keyboard.nextInt();
double dollarValueOfQuarters = quarters * .25;

The Single Responsibility Principle

The main is doing too much: it has too many responsibilities:

Calculate the dollar value of coins
Calculate the compound interest

It would be better to split the method into, and give them a name according to their main responsibility, for example:

private static void calculateDollarValueOfCoins(Scanner scanner, NumberFormat moneyFormat) { ... }

private static void calculateCompoundInterest(Scanner scanner, NumberFormat moneyFormat) { ... }

public static void main(String args[]) {
    Scanner scanner = new Scanner(System.in);
    NumberFormat moneyFormat = NumberFormat.getCurrencyInstance();

    calculateDollarValueOfCoins(scanner, moneyFormat);
    calculateCompoundInterest(scanner, moneyFormat);
}

Now the responsibilities are clearly separated.
I also renamed some variables to better match their purposes:

scanner instead of keyboard, because you don't really "scan" things from a keyboard. A scanner is a more abstract concept than a keyboard: for all you care, the input values could come as radio signals from the moon, as long as it implements the Scanner's API, your method can work.
moneyFormat instead of priceFormat, which works for both responsibilities nicely: the dollar value of your coins is certainly not a "price", and the worth of your investment is not exactly a "price". They are both about money, and formatting money, so this more general name seems appropriate.

Modeling coins

It might be a good idea to model coins using an enum:

enum Coin {
    NICKLE(.05),
    DIME(.1),
    QUARTER(.25);

    private final double value;

    Coin(double value) {
        this.value = value;
    }
}

And to add a helper class for adding coins:

private static class CoinAdder {
    private double value = 0;

    CoinAdder addCoins(Coin coin, int number) {
        value += coin.value * number;
        return this;
    }

    public double getValue() {
        return value;
    }
}

This way, the calculateDollarValueOfCoins method I suggested above can be implemented in a somewhat more natural way,
and without embedding the dollar value of coins in it:

private static void calculateDollarValueOfCoins(Scanner scanner, NumberFormat moneyFormat) {
    System.out.println("How many quarters do you have?");
    int quarters = scanner.nextInt();

    System.out.println("How many dimes do you have?");
    int dimes = scanner.nextInt();

    System.out.println("How many nickles do you have?");
    int nickles = scanner.nextInt();

    double total = new CoinAdder()
            .addCoins(Coin.QUARTER, quarters)
            .addCoins(Coin.DIME, dimes)
            .addCoins(Coin.NICKLE, nickles)
            .getValue();
    System.out.println("You have: " + moneyFormat.format(total));
}

Now we have separated the responsibilities even further:
calculateDollarValueOfCoins doesn't know anymore the value of the different types of coins, and it doesn't know how to add them.
Those responsibilities are delegated to the Coin enum and the CoinAdder class,
which is a good thing.

Quick tips

Instead of this:

quarters = quarters * (0.25);

Better:

quarters *= 0.25;

You can write 0.25 as .25.

You can write 5. instead of (double) 5.

Suggested implementation

Putting the above suggestions together, something like this would be better:

class InterestCalculator {

    enum Coin {
        NICKLE(.05),
        DIME(.1),
        QUARTER(.25);

        private final double value;

        Coin(double value) {
            this.value = value;
        }
    }

    private static class CoinAdder {
        private double value = 0;

        CoinAdder addCoins(Coin coin, int number) {
            value += coin.value * number;
            return this;
        }

        public double getValue() {
            return value;
        }
    }

    private static void calculateDollarValueOfCoins(Scanner scanner, NumberFormat moneyFormat) {
        System.out.println("How many quarters do you have?");
        int quarters = scanner.nextInt();

        System.out.println("How many dimes do you have?");
        int dimes = scanner.nextInt();

        System.out.println("How many nickles do you have?");
        int nickles = scanner.nextInt();

        double total = new CoinAdder()
                .addCoins(Coin.QUARTER, quarters)
                .addCoins(Coin.DIME, dimes)
                .addCoins(Coin.NICKLE, nickles)
                .getValue();
        System.out.println("You have: " + moneyFormat.format(total));
    }

    private static void calculateCompoundInterest(Scanner scanner, NumberFormat moneyFormat) {
        System.out.println("What is the initial investment?");
        double investment = scanner.nextDouble();

        System.out.println("At what intrest rate is the intrest compounded annually?");
        double intrestRate = scanner.nextDouble();

        double futureValueFive = investment * Math.pow(1 + intrestRate, 5.);
        System.out.println("In five years the investment will be worth : " + moneyFormat.format(futureValueFive));

        double futureValueTen = investment * Math.pow(1 + intrestRate, 10.);
        System.out.println("In ten years the investment will be worth : " + moneyFormat.format(futureValueTen));

        double futureValueTwenty = investment * Math.pow(1 + intrestRate, 20.);
        System.out.println("In twenty years the investment will be worth : " + moneyFormat.format(futureValueTwenty));
    }

    public static void main(String args[]) {
        Scanner scanner = new Scanner(System.in);
        NumberFormat moneyFormat = NumberFormat.getCurrencyInstance();

        calculateDollarValueOfCoins(scanner, moneyFormat);
        calculateCompoundInterest(scanner, moneyFormat);
    }
}


Hamming distance in Scala Problem

Write a program that can calculate the Hamming difference between two DNA strands.
GAGCCTACTAACGGGAT
CATCGTAATGACGGCCT
^ ^ ^  ^ ^    ^^

Code
object Hamming {
  def compute(s1: String, s2: String): Int = {
    if (s1.length != s2.length)
      throw new IllegalArgumentException()
    (s1.toList).zip(s2.toList)
               .filter(current => current._1 != current._2)
               .length
  }
}

Test Suite
import org.scalatest._

class HammingSpecs extends FlatSpec with Matchers {
  it should "detect no difference between empty strands" in {
    Hamming.compute("", "") should be (0)
  }

  it should "detect no difference between identical strands" in {
    Hamming.compute("GGACTGA", "GGACTGA") should be (0)
  }

  it should "detect complete hamming distance in small strand" in {
    Hamming.compute("ACT", "GGA") should be (3)
  }

  it should "give hamming distance in off by one strand" in {
    Hamming.compute("GGACGGATTCTG", "AGGACGGATTCT") should be (9)
  }

  it should "give small hamming distance in middle somewhere" in {
    Hamming.compute("GGACG", "GGTCG") should be (1)
  }

  it should "give a larger distance" in {
    Hamming.compute("ACCAGGG", "ACTATGG") should be (2)
  }

  it should "be undefined for strands of unequal length" in {
    an[IllegalArgumentException] should be thrownBy {
      Hamming.compute("AAACTAGGGG", "AGGCTAGCGGTAGGAC")
    }
  }
}

Source

Strings have a .zip() method; calling .toList() is superfluous.

Instead of .filter(…) and .length(), use .count(…).

I'm not a fan of the name current, which has a connotation of iteration.

Avoid omitting braces with if statements.  If you want to do so, put the body on the same line to avoid accidents.

object Hamming {
  def compute(s1: String, s2: String): Int = {
    if (s1.length != s2.length) throw new IllegalArgumentException()
    s1.zip(s2).count(pair => pair._1 != pair._2)
  }
}


Helper methods for working with the WPF Dispatcher I've written the following small helper class for use in my WPF applications. It comes up from time to time that I need to display message boxes, or otherwise interact with the UI from a non UI thread.

public static class ThreadContext
{
    public static InvokeOnUiThread(Action action)
    {
        if (Application.Current.Dispatcher.CheckAccess())
        {
            action();
        }
        else
        {
            Application.Current.Dispatcher.Invoke(action);
        }
    }

    public static BeginInvokeOnUiThread(Action action)
    {
        if (Application.Current.Dispatcher.CheckAccess())
        {
            action();
        }
        else
        {
            Application.Current.Dispatcher.BeginInvoke(action);
        }
    }
}

Here is a small example of how this might be used.

public static MyFunction()
{
    ThreadContext.InvokeOnUiThread(
        delegate()
        {
            MessageBox.Show("Hello world!");
        });
}

This works, but declaring the delegate the way I do seems overly verbose.

Is there anyway to make the syntax less verbose while still allowing for arbitrary functions to be passed? Is there anything else that you would suggest to improve this solution -- including an entirely different solution?

anonymous methods to the rescue! I saw somebody griping about this syntax recently on a blog and found it unfortunate they were dissimenating this. The cleaner new and happy way to define a delegate, is quite simply:

The method signature without a name or types, so for example:

Sum(int a, int b)

becomes:

(a, b)

Follow this with our trusty lambda operator => and then our method body! This may be in a statement block between our trusty {} or just in a single line the same way you can put a single line after an if or while etc.

So in conclusion there are 3 ways to create a method:

Standard (must be declared as class member level):

public int Sum(int a, int b)
{
  return a+b;
}

Delegate (can be declared and instantiated as a method local):

delegate(int a, int b)
{
  return a+b; // god help me if this syntax is correct, I haven't created a delegate in years
}

Anonymous method (can be declared and instantiated as a method local):

(a, b) => { return a+b; };

Back to your example...

ThreadContext.InvokeOnUiThread(
    delegate()
    {
        MessageBox.Show("Hello world!");
    });

In anonymous method format becomes:

ThreadContext.InvokeOnUiThread(() => { MessageBox.Show("Hello world!"); });

Or if you prefer:

Action actionToInvokeOnUiThread = () => { MessageBox.Show("Hello world!"); };
ThreadContext.InvokeOnUiThread(actionToInvokeOnUiThread);


JSON API client to manage user accounts I have the following class in Typescript (using the Aurelia SPA-framework).

import { inject } from "aurelia-framework";
import {Apiclient} from "../services/apiclient";
import * as gravatarUrl from "gravatar-url";

// Dialogs
import {DialogService} from "aurelia-dialog";
import {RedigerBruker} from "./dialogs/rediger-bruker";

@inject(Apiclient, DialogService)
export class Brukere {
    users;
    lastFetchSuccess:boolean = true;

    constructor(private api:Apiclient, private dialog:DialogService) {

    }

    gravatar(email) {
        return gravatarUrl(email, { size: 48, default: "mm" });
    }

    activate() {
        return this.api.getUsers().then(
            res => {
                if(res.status == 200) {
                    res.resultObject.then(json => this.users = json);
                    this.lastFetchSuccess = true;
                } else {
                    this.lastFetchSuccess = false;
                };
            });
    }

    editUser(userId) {
        this.api.getUser(userId).then(
            res => {
                if(res.status == 200) {
                    res.resultObject.then(json => {
                        this.dialog.open({ viewModel: RedigerBruker, model: json })
                            .then(response => {
                                if (!response.wasCancelled) {
                                    console.log("MKS: Good - " + response.output);
                                } else {
                                    console.log("MKS: Bad");
                                }

                            });
                    });
                } else {
                    console.log(`MKS: Error retrieving user ${userId}: ${res.status} - ${res.statusText}`);
                }
            });
    }
}

This code works. The API-client is just a simple wrapper around the fetch-client that returns simplified objects with status, statustext and the JSON-result promise. If you look at the editUser function. This function takes a user-id, passes it to the api-client which fetches the data from the server, and then returns the result-object. This code looks like the usual callback-pyramid-of-doom. Which makes me think I'm not using promises correctly.

Am I completely fumbling the use of promises, or is this just the way it works and I have to deal with it? Maybe there is some other way to code this?

The promise just allows you to act when the asynchronous call has been completed. So all you need to do in your 'Then' is say what to do with the result when it is there. Nothing stops you from calling a nice function in there that handles the result. ;) You've got two functions in there at least: process the result of the GetUser call, and then open the Edit dialog. So split those out and things will start to look much better.


Simplify a powerset function in C# I would like to simplify to following function as much as possible:

public string[] GetPowerSet(string input)
    {
        IEnumerable<IEnumerable<string>> seed = new List<IEnumerable<string>>() { Enumerable.Empty<string>() };

        return input.Split(',').ToList().Aggregate(seed, (a, b) =>
          a.Concat(a.Select(x => x.Concat(new List<string>() { b })))).Select(subset => string.Join(",", subset.ToArray())).Skip(1).ToArray();
    }

Can't say I've simplified it much... but I've removed some syntactic extras that were unnecessary in the original version, made the method itself static (no reliance on instance data or methods) and hoisted out the seed to a one-time initialized class-level variable for speed/GC (over multiple calls) sake:

private static readonly IEnumerable<IEnumerable<string>> seed =
    new List<IEnumerable<string>> { Enumerable.Empty<string>() };

public static string[] GetPowerSet(string input)
{
    return input.Split(',').Aggregate(
        seed,
        (a, b) => a.Concat(a.Select(x => x.Concat(new[] { b })))).Select(subset => string.Join(",", subset)).Skip(1).ToArray();
}


Partition array to hash in ruby Problem: convert this array of hashes:

cars = [
  { :model=>"Ferrari 458", :speed=>320 },
  { :model=>"Maserati MC12", :speed=>330 },
  { :model=>"Ferrari Enzo", :speed=>350 },
  { :model=>"Lamborghini Huracan", :speed=>325 }
]

to this data structure:

{
  above_320: [
    { :model=>"Maserati MC12", :speed=>330 },
    { :model=>"Lamborghini Huracan", :speed=>325 },
    { :model=>"Ferrari Enzo", :speed=>350 }
  ],
  the_rest: [
    { :model=>"Ferrari 458", :speed=>320 }
  ]
}

My solution:

cars.partition {|car| car[:speed] > 320}
.map.with_index {|cars,i| [ i == 0 ? :above_320 : :the_rest, cars ]}
.to_h

Any feedback would be greatly appreciated!

I would go with the chunk method:

cars.chunk { |c| c[:speed]>320 ? :above_320 : :the_rest }.to_h

Though it's important to underline that chunk doesn't work if the array is not ordered (by speed in this case). In that case we need to prepend it with sort_by:

cars.sort_by {|car| car[:speed]}.chunk { |c| c[:speed]>320 ? :above_320 : :the_rest }.to_h

(Moreover, if we want to order the hash keys, like in the example, we need to call sort after chunk):

cars.sort_by {|car| car[:speed]}.chunk { |c| c[:speed]>320 ? :above_320 : :the_rest }.sort.to_h