texts:
This code finds duplicate files in Linux.
I assume that MD5 hash will return unique hash number.
What can I improve in this code?

#!/usr/bin/python;

import sys
import subprocess
import os
import hashlib

FIND_CMD = "find . -name \*.* -print"
BUFFER = 65536

#Get path from the user
root_path = sys.argv[1]
#Checks that the user sent path
if not root_path:
 print("Error: No file specified.Please try again ")
 sys.exit(1)
#Chage working path
os.chdir(root_path)
#Get all the possible paths under the given directory
dirty_out = subprocess.run(FIND_CMD.split(" "), stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
file_list = dirty_out.stdout.decode("utf-8").splitlines()
#Find files with the same size and add to dic
same_size = dict()
for file in file_list:
   path = root_path + file[1:]
   if os.path.isdir(path):
        continue
   if os.path.exists(path):
        file_size = os.path.getsize(path)
        #Add the path to dictionary by size
        if file_size not in same_size:
         same_size[file_size] = list([path])
        else:
         same_size[file_size].append(path)

#Find files with the same size and hash code
file_signatures = dict()
for size in same_size:
 if len (same_size[size]) > 1:
    i = 0
    while i < len (same_size[size]):
     # Hash file content with read buffer
     md5 = hashlib.md5()
     path = same_size[size][i]
     md5 = hashlib.md5()
     with open(path, 'rb') as f:
            while True:
                data = f.read(BUFFER)
                if not data:
                    break
                md5.update(data)
            md5_sig = md5.hexdigest()
            # Add to dictionary only files with the same size and hash
            if md5_sig not in file_signatures:
                file_signatures[md5_sig] = list([path])
            else:
                file_signatures[md5_sig].append(path)
     i=i+1
#Prints the path of all the duplicate files separated with ,
for sig in file_signatures:
    if len(file_signatures[sig]) > 1:
        print("{0}\n".format(",".join(file_signatures[sig])))


texts:
I'm beginning to learn HTML and CSS, and since our lead developer is busy finishing up our project, I was asked to code the landing page.

I read up on some tutorials and beginning books, so I have a general grasp of things.  But I'm curious as to how I use HTML and CSS to layout images efficiently.

When I first made the site, I used relative and absolute positioning to layout all the images. That was not good.

This time I decided to use margins/padding to organize it, but I still feel like there is a much better to lay all this out.

Basically I just want to be able to code the website, where if I add an image or move around images, the original pieces of the website don't end up going all over the place.

This is a rough image of what our landing page is supposed to look like:

HTML

CSS

body{
    background:url(images/whiteBackground.png);
}

.container{
    width:1200px;
    margin:0 auto;
    position:relative;
}

#iphone{
    margin-left: 166px;
    margin-top: 88px;
}
/* images Block */

#imagesBlock{
    position:relative;
    left: 550px;
    bottom:592px;
    width: 515px;
}

#DashLogo{

}

#textQuestion{
    margin-top:35px;
}

#videoThumbnail{
    margin-top:20px;
}

#textQuestion{
}

#textResponse{
    margin-bottom: 50px;
    margin-left: 30px;
}

#appStoreOrange{
    margin-top: 20px;
}

.twitter{
    width:117px;
    height:112px;
    display: block;
    background: url(images/twitter.png);
    margin-left: 280px;
    margin-top:-105px;
}

/*.twitter:hover{
    background-image: url(images/twitterBlue.png);
}*/

.facebook{
    width:117px;
    height:112px;
    display:block;
    background: url(images/facebook.png);
    margin-left:400px;
    margin-top:-112px;
}

/*.facebook:hover{
    background-image:url(images/facebookBlue.png);
}*/


texts:
I read 99 Bottles of OOP, and one of the offhand comments was that doing the 99 bottles problem with composition was another route that one could take (the book used inheritance).  Here is my attempt.  Here are the lyrics needed: Beer Song

Some difficulties I had:

1) Implementation of successor was tricky.  I could not simply pass in a successor object because then BottleNumber(99) needed to hold BottleNumber(98) which needed to hold... Instead I used successor_number and generated a successor when needed.

2) Factory seemed messy - the arguments for the initialize method stacked up and up.  Named arguments only made things longer. Sometimes I had to implement a default_object and other times I could use default named parameters.  Should this be standardized throughout?

Comments welcome

class BeerSong

  def verse(number)
    bottle_number = BottleNumber.for(number)
    "#{bottle_number} of beer on the wall, #{bottle_number} of beer.\n".capitalize +
    "#{bottle_number.action}, #{bottle_number.successor} of beer on the wall.\n"
  end

  def verses(starting,ending)
    starting.downto(ending).map do |number|
      verse(number)
    end.join("\n")
  end

  def song
    verses(99,0)
  end
end

class BottleNumber
  attr_reader :number, :container, :pronoun, :quantity, :action, :successor_number

  class << self
    def for(number)
      return number if number.is_a? BottleNumber
      case number
      when 0
        BottleNumber.new(number, quantity: 'no more', successor_number: 99, action: 'Go to the store and buy some more')
      when 1
        BottleNumber.new(number, container: 'bottle', pronoun: 'it')
      else
        BottleNumber.new(number)
      end
    end
  end

  def initialize(number, container: 'bottles', pronoun: 'one', quantity: nil, action: nil, successor_number: nil)
    @number = number
    @container = container
    @pronoun = pronoun
    @quantity = quantity || default_quanity
    @action = action || default_action
    @successor_number = successor_number || default_successor_number
  end

  def to_s
    "#{quantity} #{container}"
  end

  def default_successor_number
    number - 1
  end

  def default_quanity
    number.to_s
  end

  def default_action
    "Take #{pronoun} down and pass it around"
  end

  def successor
    BottleNumber.for(successor_number)
  end
end


texts: Instantiate multiple classes in another class, invoke method from multiple classes

texts:
The goal here is to pull all alerts from a single iterable:
obj = Alerts(db, args)
for alert in obj.alerts()
    pass

Now, I need to add a few more sources and I'm not sure if this is a good approach to instantiate all classes in the AllAlerts constructor? I also don't like the fact that I'll have to add them to the self.sources attribute each time there is a new one (achieving loose coupling).
Based on the code snippet provided below could you recommend some different, perhaps a better approach?
Code:
from itertools import chain

from . import mappings
from .utils import converter

class BaseSource(object):
    def __init__(self, db, args):
        self.args = args
        self.db = db

    def alerts(self):
        raise NotImplementedError

    def _data(self, mapping, source):
        """
        This method do the parsing based on data source.
        """
        for entry in self._raw_data():
            yield converter(source, mapping, entry)

class NagiosSource(BaseSource):
    def __init__(self, *args, **kwargs):
        ...
        super().__init__(*args, **kwargs)

    def _raw_data(self):
        """
        The logic to get the data from Nagios.
        """

    def alerts(self):
        mapping = mappings.nagios
        return self._data(mapping, "nagios")

class ZabbixSource(BaseSource):
    def __init__(self, *args, **kwargs):
        ...
        super().__init__(*args, **kwargs)

    def _raw_data(self):
        """
        The logic to get the data from Zabbix.
        """

    def alerts(self):
        mapping = mappings.zabbix
        return self._data(mapping, "zabbix")

class AllAlerts(BaseSource):
    def __init__(self, db, args):
        self.sources = (
            NagiosSource(db, args),
            ZabbixSource(db, args),
        )
        super().__init__(db, args)

    def alerts(self):
        return chain.from_iterable(s.data() for s in self.sources)

I though about adding a class decorator that will register all sources but then again, I would have to use a global variable and not sure how I could pass args when creating objects...
test.py:
sources = set()

def register(cls):
    sources.add(cls())
    return cls

@register
class NagiosSource:
    pass

@register
class ZabbixSource:
    pass

Test:
$ python test.py
{<__main__.ZabbixSource object at 0x7f1a3b1d26d0>, <__main__.NagiosSource object at 0x7f1a3b1d2760>}


texts:
I am new to Java in general, but wanted to get some input on the code for a CS class I am taking.  It is a program that plays the Hi-Lo guessing game with numbers. A user may choose to quit mid-game by entering 0 and then they are prompted to play again if they choose.  If they guess correctly, they are also prompted to play again.

The code works fine, however, my original direction was to use the while loop as the main conditional instead of the do statement but I couldn't get the game to start again after the user entered 0 to exit the loop. I'm curious to know how I can use the while loop as the main conditional vs the do statement.

import java.util.Scanner;
import java.util.Random;

public class HiLo {
    public static void main(String[] args)
    {
        int guess, answer, count = 0;
        String restart;

        Random generator = new Random();
        Scanner scan = new Scanner(System.in);

        System.out.print("What number do you guess (enter 0 to quit)? ");
        guess = scan.nextInt();

        answer = generator.nextInt(100) + 1; // randomly generates a number between 1-100

        do // loops through game until user gets answer correct or quits
        {
            count++;

            if (guess == 0) // if user enters 0 to quit game, this message is displayed
            {
                System.out.println("\nQuitting game");
                System.out.println("\nWould you like to play again?");
                restart = scan.next();
                if (restart.equalsIgnoreCase("Y"))
                {
                    System.out.print("Enter a number to start playing");
                    guess = scan.nextInt();
                }
                else
                    break;
            }
            if (guess == answer)
            {
                System.out.println("That's correct! You made " + count + " guesses.");
                System.out.println("Would you like to play again?");
                restart = scan.next();
                if (restart.equalsIgnoreCase("Y"))
                {
                    System.out.print("Enter a number to start playing");
                    guess = scan.nextInt();
                }
                else
                    break;
            }
            if (guess < answer)
            {
                System.out.print("Your guess is too low, try again.");
                guess = scan.nextInt();
            }
            if (guess > answer)
            {
                System.out.print("Your guess is too high, try again.");
                guess = scan.nextInt();
            }

        }
        while (guess != 0);

        System.out.print("Thanks for playing!");
    }
}


texts:
I wanted to be able to tokenize a few different containers so I created a generic way to do it. I originally wrote this in Visual Studio 2012, but I had to modify it to get it to compile on Ideone.

Here is a brief description of my tokenizer functions:

Tokenize (): Tokenizes a container based on a single delimiter.

TokenizeIf (): Tokenizes a container based on a single delimiter and a condition.

BackInsertTokenize () and BackInsertTokenizeIf (): Wrapper for containers that can use a std::back_inserter iterator.

A specialized BackInsertTokenize () for character types (char, wchar, etc).

Here are my generic tokenizer functions:

#include <algorithm>
#include <iterator>
#include <string>
#include <utility>

template <typename Token, typename Iter, typename OutIter, typename Condition>
auto TokenizeIf (Iter begin, Iter end, OutIter out, typename std::iterator_traits <Iter>::value_type delimiter, Condition condition) -> OutIter
{
    if (begin == end) {
        return out ;
    }

    auto current = begin ;
    auto next = begin ;

    do {
        next = std::find (current, end, delimiter) ;
        Token token (current, next) ;

        if (condition (token) == true) {
            *out++ = std::move (token) ;
        }
        current = next ;

    } while (next != end && ++current != end) ;

    if (next != end) {
        Token token ;
        if (condition (token) == true) {
            *out++ = std::move (token) ;
        }
    }

    return out ;
};

template <typename Token, typename Iter, typename OutIter>
auto Tokenize (Iter begin, Iter end, OutIter out, typename std::iterator_traits <Iter>::value_type delimiter) -> OutIter
{
    if (begin == end) {
        return out ;
    }

    auto current = begin ;
    auto next = begin ;

    do {
        next = std::find (current, end, delimiter) ;
        *out++ = Token (current, next) ;
        current = next ;

    } while (next != end && ++current != end) ;

    if (next != end) {
        *out++ = Token () ;
    }

    return out ;
};

template <class ContainerOut, class ContainerIn, class Condition>
auto BackInsertTokenizeIf (ContainerIn const &in, typename ContainerIn::value_type delimiter, Condition condition) -> ContainerOut
{
    typedef typename ContainerOut::value_type Token ;

    ContainerOut out ;
    TokenizeIf <Token> (std::begin (in), std::end (in), std::back_inserter (out), delimiter, condition) ;
    return out ;
}

template <class ContainerOut, class ContainerIn>
auto BackInsertTokenize (ContainerIn const &in, typename ContainerIn::value_type delimiter) -> ContainerOut
{
    typedef typename ContainerOut::value_type Token ;

    ContainerOut out ;
    Tokenize <Token> (std::begin (in), std::end (in), std::back_inserter (out), delimiter) ;
    return out ;
}

template <class ContainerOut, class CharT>
auto BackInsertTokenize (const CharT *in, CharT delimiter) -> ContainerOut
{
    typedef typename ContainerOut::value_type Token ;

    ContainerOut out ;
    Tokenize <Token> (in, in + std::char_traits<CharT>::length (in), std::back_inserter (out), delimiter) ;
    return out ;
}

These are the test cases that I was interested in:

#include <vector>

int main ()
{
    std::string const s1 = ",hello,5,cat,192.3," ;
    auto const t1 = BackInsertTokenize <std::vector <std::string>> (s1, ',') ;

    std::vector <char> v1 = {'S', '1', '\0', 'S', '2', 'I', 'N', '\0', 'S', '3', '\0', '\0'} ;
    auto const t2 = BackInsertTokenizeIf <std::vector <std::string>> (v1, '\0', [] (const std::string &s) {
        return !s.empty () ;
    }) ;

    auto const t3 = BackInsertTokenize <std::vector <std::string>> ("C:\\Some\\Path\\To\\Nowhere", '\\') ;

    return 0 ;
}


texts: Take all the bits in a number and shift them to the left end

texts:
I wrote this program which takes all the bits in a number and shifts them to the left end (for example: 01010110 --> 11110000). It's and exercise from a book. It works, but it seems to be very wasteful to use integers (I only need 8 bits).

Can you tell me if the code is proper or not? Is the algorithm good?

#include <iostream>

void print_bit(const int bit)
{
    for(int i = 0x80; i != 0; i >>= 1)
    {
        if((bit & i) != 0)
        std::cout << "1";
        else std::cout << "0";
    }
    std::cout << std::endl;
}

int set_bits(const int bit)
{
    int lefted = 0xFF;
    for(int i = 0x80; i != 0; i >>= 1)
    {
        if((bit & i) == 0)
            lefted <<= 1;
    }
    return lefted;
}

int main()
{
    int bit = 11;
    print_bit(bit);
    print_bit(set_bits(bit));
    return 0;
}


texts:
So, in my first attempt I created a code that generated all fibonacci numbers and appended to a list. This list I then traversed to get the even numbers and added them up. It worked, but took like 5 complete seconds to work.
Then I decided to not create a list and add the even numbers as I'm generating them. It looked like this

a = 1
b = 1
c = 0
Sum = 0
while c<4000000:
    c = a + b
    if c%2==0:
        Sum+=c
    a = b
    b = c
print Sum

It still took quite a lot of time (didn't record it) compared to the people who got it done in like 100 milliseconds or something (I got this question on Project Euler).
Is there a way to make it faster?
Here's the link to the problem

https://projecteuler.net/problem=2


texts:
Is ProtectedObject really secure? Otherwise, do you have any advice?

public class ProtectedBinary : IDisposable
{
    private byte[] pBArray;
    private int originPBArraySize;

    public ProtectedBinary(byte[] data)
    {
        originPBArraySize = data.Length;
        Pad(ref data);
        ProtectedMemory.Protect(data, MemoryProtectionScope.SameProcess);

        pBArray = new byte[data.Length];
        Array.ConstrainedCopy(data, 0, pBArray, 0, data.Length);
    }

    public void Get(out byte[] outArray)
    {
        ProtectedMemory.Unprotect(pBArray, MemoryProtectionScope.SameProcess);

        outArray = new byte[originPBArraySize];
        Array.Copy(pBArray, outArray, originPBArraySize);
        Unpad(ref outArray);

        ProtectedMemory.Protect(pBArray, MemoryProtectionScope.SameProcess);
    }

    public void Clear()
    {
        pBArray.Clear(); // set all bytes to 0x00
        originPBArraySize = 0;
    }

    public void Dispose()
    {
        Clear();
    }

    private void Pad(ref byte[] bytes)
    {
        Array.Resize(ref bytes, 16 * ((bytes.Length + 15) / 16));
    }

    private void Unpad(ref byte[] bytes)
    {
        Array.Resize(ref bytes, originPBArraySize);
    }
}

public class ProtectedObject<T> : IDisposable
{
    private ProtectedBinary pBin;

    private bool isDisposed;

    public ProtectedObject(T obj)
    {
        byte[] serializedObject = ULBinConvert.Serialize(obj);
        pBin = new ProtectedBinary(serializedObject);
    }

    public void Get(out T obj)
    {
        if (isDisposed)
            throw new ObjectDisposedException("Protected object is disposed");
        byte[] serializedObject;
        pBin.Get(out serializedObject);
        obj = ULBinConvert.Deserialize<T>(serializedObject);
        serializedObject.Clear();
    }

    public void Dispose()
    {
        if (!isDisposed)
        {
            pBin.Dispose();
            isDisposed = true;
        }
    }
}


texts: RESTful APIs (Create, Read) with flask-restful

texts:
I wrote this simple API to be able to send logs from the client to MongoDB. Even though this works and fits my need, I would like to point out some concerns that I have regarding the following:

Is it efficient to be calling the instance of MongoClient for every request?
Do I need to close the instance of MongoClient after the request is successful?
A more Pythonic way to return responses?

from flask import Flask, jsonify, request, Response
from flask_restful import Resource, Api
from pymongo import MongoClient
import json

app = Flask(__name__)
api = Api(app)

USER = "user"
PASS = "pw"
MONGO_URI = 'mongodb://%s:%s@test.mlab.com/test' % (USER, PASS)
PORT = 19788

def db_conn():
    client = MongoClient(MONGO_URI, PORT)
    return client

def insert_record(args):
    client = db_conn()
    replycode = 0
    try:
        db = client['test']
        posts = db.users
        posts.insert(args)
    except:
        replycode = 1

    return replycode

def select_record(args={}):

    client = db_conn()
    db = client['test']
    result = db.users.find(args)
    return result

class CreatUser(Resource):

    def post(self):
        try:
            content = request.get_json()
            if "Vehicle" not in content:
                return jsonify({"Result": "Vehicle number not in passed arguments"}), 400

            else:
                vehicle = content['Vehicle']

            reply = insert_record(content)
            if reply == 0:
                return jsonify({"Result" : "Successfully inserted user: " + vehicle}), 201
            else:
                return jsonify({"Result" : "Failed to insert data. Check logs for more details"}), 400

        except Exception as e:
            return jsonify({'Error' : str(e)}), 500

class ViewUser(Resource):
    def get(self):
        from bson import json_util

        results = select_record()
        final = []
        for result in results:
            result.pop("_id")
            final.append(result)

        return jsonify(results=final), 200

api.add_resource(CreatUser, "/api/create")
api.add_resource(ViewUser, "/api/view")

if __name__ == "__main__":
    app.run(debug=True)


texts: Common Lisp macro: review for code quality & leaky name escaping

texts:
(defmacro with-condition-retries(retries expected-errors fail-function &body body)
  "Attempts to execute `body` `retries` times, watching for
`expected-errors`.  Optionally, if `fail-function` is set, each time a
failure occurs, prior to retrying, `fail-function` is executed.

Other conditions beside `expected-errors` will exit out of this macro"
   (let ((counter (gensym))
     (result (gensym))
     (start-tag (gensym))
     (error-handler
      #'(lambda (c)
        (let ((r (find-restart 'handler c)))
          (when r
        (invoke-restart r c))))))

     `(let ((,counter 0)
        (,result))
        (tagbody
           ,start-tag
           (restart-case
           (handler-bind
            ,(mapcar #'(lambda (error-val)
                     (list error-val   error-handler))
                 expected-errors)
             (setf ,result ,@body))
         ;;the restart pointed at by the error-handler lambda
         (handler (&rest args)
           (declare (ignore args))
           (incf ,counter)
           (unless (> ,counter ,retries)
             (when ,fail-function
               (funcall ,fail-function))
             (go ,start-tag)))))
    ,result)))


texts: Implementation of the basic matrix operations for embedded application in C++

texts:
I have been developing a control software in C++ and for implementation of the control algorithms I need basic matrix operations like addition, subtraction, multiplication and multiplication by scalar.
Due to the fact that the application is the real time application I need to avoid the dynamic memory allocation so I have decided to exploit the C++ templated class and the nontype parameters
template <class T, uint8_t ROWS, uint8_t COLUMNS>
class Matrix
{
public:
  T array[ROWS][COLUMNS];

  Matrix<T, ROWS, COLUMNS> operator+(const Matrix<T, ROWS, COLUMNS> &m) const
  {
    Matrix<T, ROWS, COLUMNS> result;

    for (uint8_t row = 0; row < ROWS; row++) {
      for (uint8_t column = 0; column < COLUMNS; column++) {
        result.array[row][column] = array[row][column] + m.array[row][column];
      }
    }

    return result;
  }

  Matrix<T, ROWS, COLUMNS> operator-(const Matrix<T, ROWS, COLUMNS> &m) const
  {
    Matrix<T, ROWS, COLUMNS> result;

    for (uint8_t row = 0; row < ROWS; row++) {
      for (uint8_t column = 0; column < COLUMNS; column++) {
        result.array[row][column] = array[row][column] - m.array[row][column];
      }
    }

    return result;
  }

  template <uint8_t N>
  Matrix<T, ROWS, N> operator*(const Matrix<T, COLUMNS, N> &m) const
  {
    Matrix<T, ROWS, N> result;

    for (uint8_t row = 0; row < ROWS; row++) {
      for (uint8_t column = 0; column < N; column++) {
        result.array[row][column] = 0;
        for (uint8_t element = 0; element < COLUMNS; element++) {
          result.array[row][column] +=
              array[row][element] * m.array[element][column];
        }
      }
    }

    return result;
  }

  friend Matrix<T, ROWS, COLUMNS> operator*(double k,
                                            const Matrix<T, ROWS, COLUMNS> &m)
  {
    Matrix<T, ROWS, COLUMNS> result;

    for (uint8_t row = 0; row < ROWS; row++) {
      for (uint8_t column = 0; column < COLUMNS; column++) {
        result.array[row][column] = k * m.array[row][column];
      }
    }

    return result;
  }

  friend Matrix<T, ROWS, COLUMNS> operator*(const Matrix<T, ROWS, COLUMNS> &m,
                                            double k)
  {
    return k*m;
  }
};

I have doubts regarding the decision to have the matrix itself i.e. the array as a public member of the Matrix classes.


texts: Showing a certain screen depending on a particular status

texts:
In this iOS app I'm working on, there are two landing screens shown to the user depending on a particular status. The screens are Login screen and Activate screen.

Let me explain what this Activate screen is. There is something called activating users. It's done by a web backend and the app has no control over it. Each device the app runs has a unique device ID. This unique ID is generated in the device. A person manually activates this ID from the backend. And there are two ways this ID gets to the backend. Either it's sent from the device at first launch, or it can be obtained by some other method and entered to the backend database manually.

When the app launches, you must get that ID and send it over to the backend to check if it's activated or not. You get two statuses, 100 - Activated, 101 - Not Activated. I keep a boolean flag called DeviceIsActive in NSUSerDefaults to store the result.

When the app launches first it checks if the DeviceIsActive is true, if it is, the user is directed to the Login screen. If its false, you're directed to the Activate screen where you're informed to contact the person at the backend to activate it.

Here is the code I have in the didFinishLaunchingWithOptions in the AppDelegate file which is the method that runs first when the app is launched.

var window: UIWindow?
private enum Screen {
    case ActivateScreen
    case LoginScreen
}
let api = API()

func application(application: UIApplication!, didFinishLaunchingWithOptions launchOptions: NSDictionary!) -> Bool {

    if Preferences.getDeviceIsActive() == true {
        // Checks if deviceIsActive flag is true.
        redirectToView(.LoginScreen)
    } else {
        // If there is not deviceID, generate one.
        if Preferences.getDeviceID() == nil {
            var deviceID = NSUUID.UUID().UUIDString
            deviceID = deviceID.stringByReplacingOccurrencesOfString("-", withString: "") // e,g: 70788AEB8586513C46B0599AEA4F82BF
            Preferences.setDeviceID(deviceID)

            // Send the ID to the backend to check.
            register()
        } else {
            // If there is a deviceID already, still send it to the server to check and make sure.
            register()
        }
    }

    return true
}

private func register() {
    api.registerDevice(Preferences.getDeviceID(), completionHandler: { (response, error) -> Void in
        let (status, code) = response

        if status == Status.DeviceIsActive.toRaw() { // Status is an enum. It has all the statuses (100, 101).
            Preferences.setDeviceIsActive(true)
            self.redirectToView(.LoginScreen)
        } else {
            self.redirectToView(.ActivateScreen)
        }
    })
}

private func redirectToView(screen: Screen) {
    self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
    let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)

    switch screen {
    case .ActivateScreen:
        let activateVC: ActivateViewController = storyboard.instantiateViewControllerWithIdentifier("ActivateController") as ActivateViewController
        let navigationVC = UINavigationController(rootViewController: activateVC)
        self.window?.rootViewController = navigationVC
    case .LoginScreen:
        let loginVC: LoginViewController = storyboard.instantiateViewControllerWithIdentifier("LoginController") as LoginViewController
        let navigationVC = UINavigationController(rootViewController: loginVC)
        self.window?.rootViewController = navigationVC
    default:
        println("No view controller specified")
    }

    self.window?.makeKeyAndVisible()
}

Now the code works fine. But it's just so ugly and messy with all the if else statements all over the place. Is there any way to make it cleaner?


texts:
I would really appreciate a general review of my Tic Tac Toe game in Python as I have spent a lot of time on it. Any improvements or suggestions?

def print_board(board):
    print "The board look like this: \n"
    for i in range(3):
        print " ",
        for j in range(3):
            if board[i*3+j] == 1:
                print 'X',
            elif board[i*3+j] == 0:
                print 'O',
            elif board[i*3+j] != -1:
                print board[i*3+j]-1,
            else:
                print ' ',

            if j != 2:
                print " | ",
        print

        if i != 2:
            print "-----------------"
        else:
            print

def print_instruction():
    print "Please use the following cell numbers to make your move"
    print_board([2,3,4,5,6,7,8,9,10])

def get_input(turn):

    valid = False
    while not valid:
        try:
            user = raw_input("Where would you like to place " + turn + " (1-9)? ")
            user = int(user)
            if user >= 1 and user <= 9:
                return user-1
            else:
                print "That is not a valid move! Please try again.\n"
                print_instruction()
        except Exception as e:
            print user + " is not a valid move! Please try again.\n"

def check_win(board):
    win_cond = ((1,2,3),(4,5,6),(7,8,9),(1,4,7),(2,5,8),(3,6,9),(1,5,9),(3,5,7))
    for each in win_cond:
        try:
            if board[each[0]-1] == board[each[1]-1] and board[each[1]-1] == board[each[2]-1]:
                return board[each[0]-1]
        except:
            pass
    return -1

def quit_game(board,msg):
    print_board(board)
    print msg
    quit()

def main():

    # setup game
    # alternate turns
    # check if win or end
    # quit and show the board

    print_instruction()

    board = []
    for i in range(9):
        board.append(-1)

    win = False
    move = 0
    while not win:

        # print board
        print_board(board)
        print "Turn number " + str(move+1)
        if move % 2 == 0:
            turn = 'X'
        else:
            turn = 'O'

        # get user input
        user = get_input(turn)
        while board[user] != -1:
            print "Invalid move! Cell already taken. Please try again.\n"
            user = get_input(turn)
        board[user] = 1 if turn == 'X' else 0

        # advance move and check for end game
        move += 1
        if move > 4:
            winner = check_win(board)
            if winner != -1:
                out = "The winner is "
                out += "X" if winner == 1 else "O"
                out += " :)"
                quit_game(board,out)
            elif move == 9:
                quit_game(board,"No winner :(")

if __name__ == "__main__":
    main()


texts: jQuery .validate() plugin, additional method to validate numbers

texts:
A while ago I've written a custom validation method for .validate(). It is a local validation plugin, with some limited validation.

I was required to write a validation method with the following requirements:

Must accept a custom string.
Must allow a maximum value.
Must allow a minimum value.
Has to allow to have dynamic values on the string.
Must validate using a regular expression.
Must allow numbers in the Portuguese and English formats.

At the time, it was quite a challenge and I was happy with the result, but the code is BAD. It works, but it is so hacky and kludged it hurts my soul.

(function(){
    var __c_number_between=new String('');

        __c_number_between.valueOf=function(){
                return 'The value must be between __MIN__ and __MAX__'
                    .replace(/__MIN__/g,this.min)
                    .replace(/__MAX__/g,this.max);
            };
        __c_number_between.toString=function(){return this.valueOf();};

    $.validator.addMethod('c_number_between',
        function(d,i,o){
            var num=d.replace(/\./g,'').replace(',','.')/1;
            __c_number_between.min=o.min;
            __c_number_between.max=o.max;
            return o.max>=num&&num>=o.min;
        },__c_number_between);
})();

Yes, that is the code. It fulfills all my needs, but relies on a really bad behaviour in Javascript, which is that objects are passed as a reference. It also relies on Javascript being executed linearly, instead of having multiple threads, which is REALLY bad!

How can I re-write this in a clean and decent way?

Also, worth noticing is that this is a cross-posting from StackOverflow, on the following question: jQuery .validation plugin: help cleaning aditional method


texts:
This class updates the console's title so it can tell the person using it the programs uptime, which can be pretty useful. The class holds a timer and each time the timer executes it will call the function to update the title (interval is in config file).

How can I improve on this?

using Apple.Application.Base.Config;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;

namespace Apple.Application.Base.Core
{
    class ConsoleWorker
    {
        /// <summary>
        /// Console timer
        /// </summary>
        private Timer _consoleTimer;

        /// <summary>
        /// ConsoleWorker
        /// </summary>
        /// <param name="config">Instance of AppleConfig</param>
        public ConsoleWorker(AppleConfig config)
        {
            _consoleTimer = new Timer(int.Parse(config.GetConfigElement("console.timer.interval")));
            _consoleTimer.Elapsed += new ElapsedEventHandler(OnElapsed);
            _consoleTimer.Enabled = true; // Enable it
        }

        public void OnElapsed(object sender, ElapsedEventArgs e)
        {
            DateTime Startup = Apple.ServerInformation.ServerStarted;
            TimeSpan Uptime = DateTime.Now - Startup;

            string days = Uptime.Days + " day" + (Uptime.Days != 1 ? "s" : "") + ", ";
            string hours = Uptime.Hours + " hour" + (Uptime.Hours != 1 ? "s" : "") + ", and ";
            string mins = Uptime.Minutes + " min" + (Uptime.Minutes != 1 ? "s" : "");
            string UptimeString = days + hours + mins;

            Console.Title = "Apple Server [" + UptimeString + "]";
        }
    }
}


texts: Calculating the number of coins in money change

texts:
I wrote a program that calculates the minimum number of coins required to give a user change.

One concern I have is: When do we initialize the value of a float to be negative or positive? I recently saw

float userInput = -1.0;

but what about

float userInput = 1.0;

Are there differences between the two, and when would one be used over the other?

#include <stdio.h>
#include <cs50.h>
#include <math.h>

    int main(void)
{
    float input = -1;
    int z = 0;
    int counter = 0;

    do
    {
        printf("The amount of changed owed(in dollars) is ");
        input = get_float();
    }
    while (input < 0);
    input = input * 100;
    input = round(input);
    z = input;

    while (z >= 25)
    {
        z = z - 25;
        counter++;
    }

    while (z >= 10)
    {
        z = z - 10;
        counter++;
    }

    while (z >= 5)
    {
        z = z - 5;
        counter++;
    }

    while (z >= 1)
    {
        z = z-1;
        counter++;
    }

    printf("The number of minimum coins needed is %d\n", counter);
}


texts: Get result from UI thread to non-UI thread when using await Task.Run

texts:
I have an application where I use Task to run an operation. During the operation, there can be a problem which will need some user interaction (continue or not). I need to bubble up a messagebox and get the user result back to the operation thread.

This is how I got it working:

public interface IPlugin
{
    void ConnectAndProduce(Func<string, bool> retryRequest);
}

public partial class MainWindow : MetroWindow
{
    [ImportMany(typeof(IPlugin))]
    private IEnumerable<IPlugin> Plugins;

    public MainWindow()
    {
        InitializeComponent();
    }

    private async void Button_Click(object sender, RoutedEventArgs e)
    {
        Func<string, bool> func = message =>
        {
            var result = Application.Current.Dispatcher.Invoke(new Func<Task<MessageDialogResult>>(async () =>
                {
                    var mySettings = new MetroDialogSettings()
                    {
                        AffirmativeButtonText = "YES",
                        NegativeButtonText = "NO",
                        ColorScheme = MetroDialogColorScheme.Accented
                    };

                    return await this.ShowMessageAsync("Hello!", message, MessageDialogStyle.AffirmativeAndNegative, mySettings);
                }));

            if ((result as Task<MessageDialogResult>).Result != MessageDialogResult.Negative)
                return true;

            return false;
        };

        ImportPlugins();
        var plugin = Plugins.FirstOrDefault();

        await Task.Run(() =>
        {
            plugin.ConnectAndProduce(func);
        });
    }

    public void ImportPlugins()
    {
        var catalog = new AggregateCatalog();
        catalog.Catalogs.Add(new DirectoryCatalog(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)));
        CompositionContainer container = new CompositionContainer(catalog);
        container.ComposeParts(this);
    }
}

And here is the Plugin what is going to do all the work:

[Export(typeof(IPlugin))]
public class Machine : IPlugin
{
    public void ConnectAndProduce(Func<string, bool> retryRequest)
    {
        var connection = MachineConnection();

        var retry = true;
        var retryCount = 0;
        while (retry)
        {
            if (connection != true)
                retry = retryRequest("Do you want to retry?");

            if (retryCount < 3)
                retryCount++;
            else
                retry = false;
        }

        connection.Produce();
    }
}

I use MEF to load the plugin and do all the work in non-UI thread by calling the plugin method in a new Task. Once the plugin has called MachineConnect(), the connection fails and I can't just stop the plugins from working and call it again. I need to continue, and that's why the plugin has to ask if I want to retry.

Is there any better way doing the retry request from plugin to UI thread? This looks very 'hacky' to me.


texts:
this code seems fine at once but the problem I see with this code maintainability I can imagine if one will have to add 10 or more routes the function will grow badly.
can we refactor this code for better maintainibility .
export const getMetaDescription = (pathname) => {
  if (pathname.includes("about")) return "About Us | " + BASE_SITE_NAME;
  else if (pathname.includes("fees")) return "Our Fees | " + BASE_SITE_NAME;
  else if (pathname.includes("legal")) return "Legal Info | " + BASE_SITE_NAME;
  else if (pathname.includes("register"))
    return "Registration | " + BASE_SITE_NAME;
  else if (pathname.includes("login")) return "Login | " + BASE_SITE_NAME;
  return BASE_SITE_NAME;
};

Edit:
i had a similar function which i refactor by using a map (kind of)
const titles = {
  about: "About Us",
  login: "Login",
  wallet: "Wallet",
  profile: "Profile",
  beneficiary: "Beneficiary",
};

export const getMetaTitle = pathname => {
  for (let key in titles) {
    if (pathname.includes(key)) {
      return titles[key] + " | " + BASE_SITE_NAME;
    }
  }
  return BASE_SITE_NAME;
};


texts:
I've got a simple JavaScript function that takes multiple types of arguments. Inside the function I'm doing a check on the arguments to determine which way the user called the function:

var build = function() {
    var args = Array.prototype.slice.call(arguments)
    var options = {
        to: {},
        from: {},
        relationship: null
    }

    if (_.isString(args[3]) && !_.isUuid(args[3]) && _.isString(args[4])) {
        options.to.type = args[3]
    } else if (_.isString(args[2]) && !_.isUuid(args[2]) && _.isString(args[3])) {
        options.to.type = args[2]
    }
}

// called like:
build(client, dataObj, 'relationship', 'type', 'name')
// or
build(client, dataObj, 'relationship', '<uuid>')

This looks messy and isn't really scalable. Is there a more succinct way I can write this (perhaps using .map(), .filter(), or .reduce())?


texts: Thread-safe sensor interface with observer and strategy patterns

texts:
I have a thread-safe API for an observable Sensor. The concrete type of the Sensor is chosen in the configure method (strategy pattern). To avoid deadlock when calling the stopmethod, I had to use two mutexes. The first one is to protect the observers list obs_ and the other one is to protect the strategy pointer sensor_.

I am not a fan of using multiple mutexes to make a thread-safe API. My hunch is that there may be a better way to do that.

#include <memory>
#include <thread>
#include <mutex>
#include <list>
#include <iostream>

class SensorImpl
{
public:
    virtual void start() = 0;
    virtual void stop() = 0;
};

class SensorA : public SensorImpl
{
public:
    typedef std::function<void(int)> DataCallback;

    SensorA(DataCallback cb) :
        dataCallback_(cb)
    { }

    virtual ~SensorA() { }

    void start() override
    {
        running_ = true;
        workerThread_.reset(new std::thread(&SensorA::dataProducer, this));
    }

    void stop() override
    {
        if(workerThread_)
        {
            running_ = false;
            workerThread_->join();
            workerThread_.reset();
        }
    }

private:

    void dataProducer()
    {
        while(running_)
        {
            std::this_thread::sleep_for(std::chrono::milliseconds(100));
            int data = 6;
            dataCallback_(data);
        }
    }

    DataCallback dataCallback_;
    std::unique_ptr<std::thread> workerThread_;
    bool running_{false};
};

class SensorObserver
{
    virtual void configured() = 0;
    virtual void started() = 0;
    virtual void dataReceived(int data) = 0;
    virtual void stopped() = 0;
    virtual void cleanup() = 0;
};

// Sensor API must be thread-safe
class Sensor
{
public:

    Sensor() { }
    ~Sensor() { }

    void configure()
    {
        std::lock_guard<std::mutex> lock(implMtx_);

        auto dataCallback =
            [this](int data)
            {
                std::lock_guard<std::mutex> lock(obsMtx_);
                std::cout << "dataReceived" << std::endl;
                // notify SensorObserver::dataReceived
            };

        sensor_.reset(new SensorA(dataCallback));
        {
            std::lock_guard<std::mutex> lock(obsMtx_);
            std::cout << "configured" << std::endl;
            // notify SensorObserver::configured()
        }
    }

    void start()
    {
        std::lock_guard<std::mutex> lock(implMtx_);
        if(sensor_)
        {
            sensor_->start();
            {
                std::lock_guard<std::mutex> lock(obsMtx_);
                std::cout << "started" << std::endl;
                // notify SensorObserver::started()
            }
        }
    }

    void stop()
    {
        std::lock_guard<std::mutex> lock(implMtx_);
        if(sensor_)
        {
            sensor_->stop();
            {
                std::lock_guard<std::mutex> lock(obsMtx_);
                std::cout << "stopped" << std::endl;
                // notify SensorObserver::stopped()
            }
        }
    }

    void cleanup()
    {
        std::lock_guard<std::mutex> lock(implMtx_);
        sensor_.reset();
        {
            std::lock_guard<std::mutex> lock(obsMtx_);
            std::cout << "cleanup" << std::endl;
            // notify SensorObserver::cleanup()
        }
    }

    // Observer attach/detach/notify code omitted

private:

    std::mutex obsMtx_, implMtx_;
    std::unique_ptr<SensorImpl> sensor_;
    std::list<SensorObserver*> obs_;
};

int main()
{
    Sensor sensor;

    sensor.configure();
    sensor.start();

    std::this_thread::sleep_for(std::chrono::milliseconds(500));

    sensor.stop();
    sensor.cleanup();

    return 0;
}


texts: Wrapping a telephony RESTful service for sending text messages and making phone calls

texts:
So I'm writing an abstraction layer that wraps a telephony RESTful service for sending text messages and making phone calls. I should build this in such a way that the low-level provider, in this case Twilio, can be easily swapped without having to re-code the higher level interactions.

I'm using a package that is pre-built for Twilio and so I'm thinking that I need to create a wrapper interface to standardize the interaction between the Twilio service package and my application. Let us pretend that I cannot modify this pre-built package.

<?php

namespace Telephony;

class Provider_Twilio implements Provider_Interface {

    public function send_sms(Provider_Request_SMS $request) {

        if (!$request->is_valid())
            throw new Provider_Exception_InvalidRequest();

        $sms = \Twilio\Twilio::request('SmsMessage');
        $response = $sms->create(array(
            'To' => $request->to,
            'From' => $request->from,
            'Body' => $request->body
        ));

        if ($this->_did_request_fail($response)) {
            throw new Provider_Exception_RequestFailed($response->message);
        }

        $response = new Provider_Response_SMS(TRUE);
        return $response;

    }

    private function _did_request_fail($api_response) {
        return isset($api_response->status);
    }

}

The idea is that I can write another file like this for any other telephony service provided that it implements Provider_Interface making them swappable. Here are my questions:

Do you think this is a good design? How could it be improved?
I'm having a hard time testing this because I need to mock out the Twilio package so that I'm not actually depending on Twilio's API for my tests to pass or fail. Do you see any strategy for mocking this out?


texts:
I need to select all checked checkboxes, except checkboxes having a class .checkall.

HTML:

<input type="checkbox" value="1961" class="checkbox">
<input type="checkbox" name="checkall" class="checkbox checkall">

Script:

$("input.checkbox:checkbox:checked:not(.checkall)").each(function () {
    var checkbox = $(this), machineId = checkbox.val()
}


texts: A simple 3D Wrapper class around std::vector

texts:
I am working on a very simple 3D vector class, which I can use to set up and access three-dimensional vectors using a wrapper around std::vector. It's not intended to be foolproof, just good enough to get by.

The main goal is to make it simple to use, explicit and easy to debug. I have often accidentally put in out-of-bounds coordinates or given invalid dimensions, so this at least can catch those cases and report back in an understandable way.

Hence all the debug prints, should it be used improperly for any reason.

The only thing I am unhappy with is resize. I would not have included it (too dangerous), but found some cases in my code where I could not set up its dimensions in advance, like if it was a member of another class. In those cases, it needed a default and resize option.

Since resize does all the checking, I just reused it for the constructor rather than copy-paste all that.

I'm still somewhat new to C++ and was taught from a C background, so I'm always looking to improve my style.

template <typename T>
class Vector3D
{
 private:
  std::vector<T> data;

 public:
  // Dimensions in each direction
  unsigned long xDim;
  unsigned long yDim;
  unsigned long zDim;

  // Constructor
  Vector3D(unsigned long _xDim, unsigned long _yDim, unsigned long _zDim)
  {
    resize(_xDim, _yDim, _zDim);
  }

  T& at(unsigned long _x, unsigned long _y, unsigned long _z)
  {
    if (_x >= xDim || _y >= yDim || _z >= zDim)
      {
        std::cerr << "Position: " << x << ", " << y << ", " << z << std::endl;

        std::cerr << "Vector width: " << xDim << ", " << yDim << ", " << zDim
                  << std::endl;

        std::cerr << "Invalid indices into 3D vector" << std::endl;

        // Throw an exception here..
      }

    unsigned position = _x + (_y * xDim) + (_z * xDim * yDim);

    return data[position];
  }

  /**
   * @brief Default constructor. Dangerous to use, should use the explicit one
   * if at all possible.
   */
  Vector3D()
  {
    xDim = 0;
    yDim = 0;
    zDim = 0;
  }

  /**
   * @brief Re-sizes a 3D vector with new dimensions.
   * @details This is a nuclear option. You're re-sizing the dimensions of a
   * three-dimensional vector. Do not expect results to be good. Only use this
   * explicitly when initialization is impossible up-front.
   * @param _xDim, _yDim, _zDim - The new dimensions of the vector
   */
  void resize(unsigned _xDim, unsigned _yDim, unsigned _zDim)
  {
    if (_xDim == 0 || _yDim == 0 || _zDim == 0)
      {
        // Throw an exception here...
      }

    xDim = _xDim;
    yDim = _yDim;
    zDim = _zDim;

    // Resize could fail, especially if the dimensions are too large. Just print
    // out the dimensions in x,y,z, number of elements and total bytes just in
    // case
    try
      {
        data.resize(xDim * yDim * zDim);
      }
    catch (std::exception& e)
      {
        std::cerr << e.what() << std::endl;

        std::cerr << "Error allocating 3D Vector. Dimensions: ";

        std::cerr << "X: " << xDim << " Y: " << yDim << " Z: " << zDim
                  << std::endl;
        std::cerr << "Number of elements: " << (xDim * yDim * zDim)
                  << std::endl;
        std::cerr << "Size in bytes: " << (xDim * yDim * zDim) * sizeof(T)
                  << std::endl;

        // Throw an exception here...
      }
  }

  unsigned long getSize() { return data.size(); }

  // Should only be used if the vector is storing pointers to some data
  void freeData()
  {
    for (unsigned long i = 0; i < data.size(); i++)
      {
        free(data[i]);
      }
  }

  // A couple methods to get the real vector, if they want it.
  std::vector<T>& getData() { return data; }

  const std::vector<T>& getData() const { return data; }
};


texts: How to avoid code duplication in ordering system

texts:
Here is the piece of order system.
And this is hierarchy of order classes in this system

Public MustInherit Class BaseItem
    Public Property Id() As Guid
    Public Property Sku() As String
    Public Property Quantity() As String
    Public Property TransactionId() As Integer?
End Class

Public Class SoOrderItem
    Inherits BaseItem

    Public Property BatchNumber() As String
    Public Property Lottable1() As String
    Public Property Lottable2() As String
    Public Property Lottable3() As String
    Public Property Lottable4() As String

End Class

Public Class AsnOrderItem
    Inherits BaseItem

   Public Property AdditionalInfo() As String

End Class

Public Class BaseOrder
    Public Property OrderReference() As String
    Public Property PoNumber() As String
    Public Property CustomerVat() As String
    Public Property CustomerReference() As String
    Public Property TransactionType() As String
End Class

Public Class SoOrder
    Inherits BaseOrder

    Public Property ConsigneeAddress() As String
    Public Property ConsigneeContact() As String
    Public Property ConsigneeName() As String
    Public Property OrderItems() As New List(Of SoOrderItem)
End Class

Public Class AsnOrder
    Inherits BaseOrder

    Public Property Account() As Account
    Public Property SupplierName() As String
    Public Property OrderItems() As New List(Of AsnOrderItem)
End Class

And here is confirm classes for them

Public Class SoConfirmation
     Private _itransactionService As ITransactionService

     Private Sub AssignNewTransactionsToOrderItems(soOrders As IEnumerable(Of SoOrder))

        For Each order In soOrders
            For Each item In order.OrderItems
                If (Not item.TransactionId.HasValue) Then
                    Dim newTransactionId =
_itransactionService.GenerateTransactionId()
   _itransactionService.AssignTransactionToOrderItem(order.OrderReference, item.Sku, item.Id, newTransactionId)
                    item.TransactionId = newTransactionId
                End If
            Next
        Next
    End Sub

    Private Sub FilterForConfirmation(soOrders As IEnumerable(Of SoOrder))

        For Each order In soOrders
            order.OrderItems.RemoveAll(Function(i) _itransactionService.IsTransactionProcessedSuccesfully(order.OrderReference, i.Id))
        Next
    End Sub
End Class

Public Class AsnConfirmation
     Private _itransactionService As ITransactionService

  Private Sub AssignNewTransactionsToOrderItems(asnOrders As IEnumerable(Of AsnOrder))

        For Each asn In asnOrders
            For Each item In asn.OrderItems
                If (Not item.TransactionId.HasValue) Then
                    Dim newTransactionId = _itransactionService.GenerateTransactionId()

_itransactionService.AssignTransactionToOrderItem(asn.OrderReference, item.Sku, item.Id, newTransactionId)
                    item.TransactionId = newTransactionId
                End If
            Next
        Next
    End Sub

    Private Sub FilterForConfirmation(asnOrders As IEnumerable(Of AsnOrder))

        For Each order In asnOrders
            order.OrderItems.RemoveAll(Function(i) _itransactionService.IsTransactionProcessedSuccesfully(order.OrderReference, i.Id))
        Next
    End Sub
End Class

As you can see confirmation classes have a lot of duplcited code and i don't know how to avoid it ...
Will be appreciate for any help.


texts: Searching for songs on an Android application

texts:
In my application I need to search for some songs on my external storage card every now and then. On startup I read everything, however when it comes to new activities I thought I could just pass the file paths and read the songs I need again.

I've created this function:

public static Song getSong(Context c, String songPath) {
    Cursor audioCursor = c.getContentResolver().query(
            MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
            new String[] { "*" }, MediaStore.Audio.Media.DATA + " = " + songPath, null, Media.TITLE + " ASC");

    if (audioCursor != null) {
        if (audioCursor.moveToFirst()) {

                String path = audioCursor.getString(audioCursor
                        .getColumnIndex(MediaStore.Audio.Media.DATA));
                String title = audioCursor.getString(audioCursor
                        .getColumnIndex(MediaStore.Audio.Media.TITLE));
                String album = audioCursor.getString(audioCursor
                        .getColumnIndex(MediaStore.Audio.Media.ALBUM));
                String artist = audioCursor.getString(audioCursor
                        .getColumnIndex(MediaStore.Audio.Media.ARTIST));
                int album_id = audioCursor.getInt(audioCursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID));
                int trackid = audioCursor.getInt(audioCursor.getColumnIndex(MediaStore.Audio.Media.TRACK));
                Long duration = audioCursor.getLong(audioCursor.getColumnIndex(MediaStore.Audio.Media.DURATION));

                Song s = new Song();
                s.setPath(path);
                s.setTitle(title);
                s.setArtist(artist);
                s.setAlbum(album);
                s.setAlbumId(album_id);
                s.setTrackId(trackid);
                s.setDuration( new Duration(duration) );

                return s;
        }
    }
    return null;
}

This function would either return null if not found or the song object created from the file's data.

Is it well-written?  Any improvements?
Is it better than using a singleton class?

Situation:

I click on a ListViewItem which represents an Album. It shows me a new Activity with another ListView which holds all the Songs from that Album. So I would just read every Song again via its path.

Intent i = new Intent( this, blabla.class );
i.putStringArrayListExtra( "paths", pathList );

When I use a Singleton class I would just set the selected Album to that Singleton class and read all the Songs from it again in the onCreate() method from the new Activity.


texts: Remove duplicates from string without using additional buffer

texts:
I wrote a simple program to remove duplicates from a String without using additional buffer.

The program should filter the duplicates and return just the unique string.

Example:

  Input:
  FOOOOOOOOLLLLLOWWWWWWWWWW UUUUP

  Output:
  FOLW UP

I just want to know if the below solution is a good solution for my problem statement.

public class compareString {
    public static void main(String args[]) {
        removeDuplicateString("FOOOOOOOOLLLLLOWWWWWWWWWW UUUUP");
    }

    public static void removeDuplicateString(String input) {
        String value1 = input;
        String value2 = input;
        String finalValue = "";
        int count = 0;
        char char1;
        char char2 = 0;
        for (int i = 0; i < value1.length(); i++) {
            flag = 0;
            char1 = value1.charAt(i);
            for (int j = 0; j < value2.length(); j++) {
                char2 = value2.charAt(j);
                if (char1 == char2) {
                    count++;
                }
            }

            if (count > 1) {
                finalValue=finalValue+char1;
                i=i+(count-1);
            } else {
                finalValue = finalValue + char1;
            }
            count = 0;
        }
        System.out.println(finalValue);
    }
}


texts:
I wrote a solution to the popularized FizzBuzz problem in Haskell to see how a functional solution looks. I'm more or less happy with my solution, except for the definition of list. It just looks sort of contorted.

Are there any language features in Haskell which can improve the readability of this code, especially the definition of list, while preserving the extensibility that table provides?

import Control.Arrow

main = mapM_ (putStrLn . fizzBuzzLogic) [1..100]

fizzBuzzLogic :: Int -> String
fizzBuzzLogic x
  | null list = show x
  | otherwise = foldl1 (++) list
  where
    list  = map snd . filter ((==0) .fst) $ map (first (mod x)) table
    table = [(3,"Fizz")
            ,(5,"Buzz")
            ] --add more modulo tokens if you wish


texts:
Please help make this code more cleaner. It's a part of window procedure that notifies my renderer before client area of window resized.

I need to check two combinations of bit blags: some of them must be set, and some must be not. How to do it without bunch of temp variables? (and probably calculate only 2 possible states and only once, not every call)

Thanks!

LRESULT CALLBACK MSWindow::Impl::WndProc( HWND hWnd, uint msg, WPARAM wParam, LPARAM lParam )
{
switch( msg )
{

// ...

// WM_WINDOWPOSCHANGING is sent just about window position, size or order changed.
case WM_WINDOWPOSCHANGING:
    {
        const WINDOWPOS* wp = ((WINDOWPOS*)lParam);
        const auto& flags = wp->flags;

        const bool NOCOPYBITS       = (flags & SWP_NOCOPYBITS)      > 0;
        const bool NOSIZE           = (flags & SWP_NOSIZE)          > 0;
        const bool FRAMECHANGED     = (flags & SWP_FRAMECHANGED)    > 0;
        const bool NOOWNERZORDER    = (flags & SWP_NOOWNERZORDER)   > 0;
        const bool NOZORDER         = (flags & SWP_NOZORDER)        > 0;
        const bool NOACTIVATE       = (flags & SWP_NOACTIVATE)      > 0;
        const bool SHOWWINDOW       = (flags & SWP_SHOWWINDOW)      > 0;

        const bool IsResizingAboutToEnd  = !(NOSIZE) && NOOWNERZORDER && NOZORDER && (!NOACTIVATE);
        const bool IsGoingToMaximizeOrRestore = FRAMECHANGED && (!NOACTIVATE) && (!NOCOPYBITS) && (!SHOWWINDOW);

        if ( IsGoingToMaximizeOrRestore || IsResizingAboutToEnd )
        {
            Resize(Point(wp->cx, wp->cy));
        }

        break;
    }
// .....
}


texts:
It's a string problem I have been making on Hackerrank. It is executing fine on all test cases except the last two. These last two test case are declaring it "Terminated due to time out".

C programs are allowed 2 seconds on this site and somehow my program is taking a fraction beyond 2 seconds. How am I supposed to reduce that time taken?

  For two strings A and B, we define the similarity
  of the strings to be the length of the longest prefix common to both
  strings. For example, the similarity of strings "abc" and "abd" is 2,
  while the similarity of strings "aaa" and "aaab" is 3.

  Calculate the sum of similarities of a string S with each of its suffixes.

   #include<stdio.h>
#include<string.h>
void stringMatch(char strMain[]) {
        int similarity = 0,i,j;
        for(i =0;i<strlen(strMain);i++){
            for(j =0;j+i<strlen(strMain);j++){
                if(strMain[j] == strMain[j+i]){
                    similarity++;
                }else{
                    break;
                }

            }
        }
        printf("%d\n",similarity);
}

int main(){
        int T,i;
        scanf("%d",&T);
        char str[1000000];
        for(i =0;i<T;i++){
            scanf("%s",str);
            stringMatch(str);
        }
}


texts:
This is my first Go program. I would like to know what could be improved, what is done wrong, and anything else that I should know. The CSV contains 10 questions with the 10 answers separated by a comma. For example:

10+10,20
4+5,32

If you want the full context this is from gophercises which are some exercises to practice Go.

package main

import (
    "encoding/csv"
    "flag"
    "fmt"
    "math/rand"
    "os"
    "strings"
    "time"
)

var points int

func main() {
    fPtr := flag.String("csv", "problems.csv", "FileName in csv (question, answer)")
    tPtr := flag.Int("time", 10, "Time in seconds")
    sPtr := flag.Bool("shuffle", true, "shuffle your questions order")
    flag.Parse()
    questions := readCSV(*fPtr)

    fmt.Print("Press enter to start you have ", *tPtr, " seconds")
    fmt.Scanln()

    askQuestions(&questions, *tPtr, *sPtr)

    fmt.Println("You got ", points, " points")
}

func askQuestions(questions *[][]string, time int, s bool) {

    go startTimer(time)
    for _, i := range shuffle(s, len(*questions)) {
        fmt.Println("Question ", (*questions)[i][0], ":")
        var a string
        fmt.Scan(&a)
        a = strings.ToLower(strings.Trim(a, " "))
        if a == (*questions)[i][1] {
            points++
        }
    }
}

func shuffle(shuffle bool, sliceLen int) []int {
    var r []int
    for i := 0; i < sliceLen; i++ {
        r = append(r, i)
    }
    if shuffle {
        rand.Seed(time.Now().Unix())
        rand.Shuffle(len(r), func(i, j int) {
            r[i], r[j] = r[j], r[i]
        })
    }

    return r
}

func readCSV(s string) (questions [][]string) {
    f, err1 := os.Open(s)
    records, err2 := csv.NewReader(f).ReadAll()
    for err1 != nil || err2 != nil {
        fmt.Println("Error: ", err1, err2)
        fmt.Println("Please re-enter the name of the CSV file: ")
        fmt.Scan(&s)
        f, err1 = os.Open(s)
        records, err2 = csv.NewReader(f).ReadAll()
    }
    return records
}

func startTimer(seconds int) {
    time.Sleep(time.Duration(seconds) * time.Second)
    fmt.Println("Time is up! You got ", points, " points")
    os.Exit(0)
}


texts: AppEngine get/post on webapp2.RequestHandler

texts:
I was receiving 405 method not supported errors on get requests to my save controller, so I created a get method which just calls the existing post one as follows:

class Save(webapp2.RequestHandler):

    def get(self):
        self.post()

    def post(self):
        #...

This seems to be working, but is there a more Pythonic way to define both request handlers at once?


texts: Time calculation to identify current phase

texts:
I have a program that works by periodic phases, and I need to understand, depending on the current time, which phase should be executed. The following is not for busy wait, it's just a check.

I'm trying to improve the reliability of the calculations, not to heavily refactor the whole thing.

Disclaimer: I'm on C++03. If I were using Java, a Timer would probably look like a good choice for a situation like this. However, I'd rather avoid using it in this specific case, because of the way the bigger programs works.

Here is a file with the constants defining the first time a phase is started (...TIME_0) and the time that passes before its next execution (TIME_TO_NEXT_...):

/* Times for phase changes */
const double CONF_0_TIME = 1.0;
const double GEN_MODEL_TIME = 1.5;
const double CONF_1_TIME = 2.0;
const double ATK_TIME = 2.5;
const double ATK_CK_TIME = 3.0;
const double UPD_MODEL_TIME_0 = 3.5;

const double TIME_FOR_1_CK = 1.0;
const double TIME_TO_NEXT_CK = TIME_FOR_1_CK * 4.0;
const double TIME_TO_NEXT_UPD = TIME_FOR_1_CK;

const double INTER_CK_B_TIME_0 = 4.0;
const double INTRA_CK_A_TIME_0 = INTER_CK_B_TIME_0 + TIME_FOR_1_CK;
const double INTER_CK_A_TIME_0 = INTRA_CK_A_TIME_0 + TIME_FOR_1_CK;
const double INTRA_CK_B_TIME_0 = INTER_CK_A_TIME_0 + TIME_FOR_1_CK;

Here is the file checking the current time and trying to deduce the phase:

char msg [200];

double cur_time = op_sim_time();
double adj_time = fmod (cur_time - (UPD_MODEL_TIME_0 - ATK_CK_TIME), TIME_TO_NEXT_CK);

if (cur_time == UPD_MODEL_TIME_0)
    {
    snprintf (msg, 200, "time %f) supervisor updating model after initial attack checks", cur_time);
    }
else if (adj_time == fmod (INTER_CK_B_TIME_0, TIME_TO_NEXT_CK))
    {
    snprintf (msg, 200, "time %f) supervisor updating model after inter B checks", cur_time);
    }
else if (adj_time == fmod (INTRA_CK_A_TIME_0, TIME_TO_NEXT_CK))
    {
    snprintf (msg, 200, "time %f) supervisor updating model after intra A checks", cur_time);
    }
else if (adj_time == fmod (INTER_CK_A_TIME_0, TIME_TO_NEXT_CK))
    {
    snprintf (msg, 200, "time %f) supervisor updating model after inter A checks", cur_time);
    }
else if (adj_time == fmod (INTRA_CK_B_TIME_0, TIME_TO_NEXT_CK))
    {
    snprintf (msg, 200, "time %f) supervisor updating model after intra B checks", cur_time);
    }
else
    {
    snprintf (msg, 200, "time %f) supervisor updating model, adj_time = %f", cur_time, adj_time);
    }

op_sim_message (msg, "");


texts: Calculate admission prices of different days

texts:
Children are admitted free on Sundays, and pay only $6 each, any other day
Adults admission is $12 any day, except on Tuesdays, when it is only $8
Monday, Wednesday, Thursday, Friday, Saturday are same prices.
How do I shorten Mon/Wed-Sat so the code isn't repeated and can be single-line?
Sunday and Tuesday prices vary.

#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
int Children, Adults, tickets, persons, pricea, pricec, total_price;
char day;

cout << "Enter the number of Adults attending? ";
cin >> Adults;
cout << "Enter the number of Children attending? ";
cin >> Children;
cout << "What is the day of the week? ";
cin >> day;

cout << "The day entered is: " << day << endl;
switch (day)
{
case 'm': case 'M':
    cout << "Monday" << endl;
    pricea = 12;
    pricec = 6;
    total_price = (Adults*pricea) + (Children*pricec);
    cout << "Total price is: " << total_price << endl;
    break;
case 't': case 'T':
    cout << "Tuesday" << endl;
    pricea = 8;
    pricec = 6;
    total_price = (Adults*pricea) + (Children*pricec);
    cout << "Total price is: " << total_price << endl;
    break;
case 'w': case 'W':
    cout << "Wednesday" << endl;
    pricea = 12;
    pricec = 6;
    total_price = (Adults*pricea) + (Children*pricec);
    cout << "Total price is: " << total_price << endl;
    break;
case 'r': case 'R':
    cout << "Thursday" << endl;

    pricea = 12;

    pricec = 6;
    total_price = (Adults*pricea) + (Children*pricec);
    cout << "Total price is: " << total_price << endl;
    break;
case 'f': case 'F':
    cout << "Friday" << endl;

    pricea = 12;

    pricec = 6;
    total_price = (Adults*pricea) + (Children*pricec);
    cout << "Total price is: " << total_price << endl;
    break;
case 's': case 'S':
    cout << "Saturday" << endl;

    pricea = 12;

    pricec = 6;
    total_price = (Adults*pricea) + (Children*pricec);
    cout << "Total price is: " << total_price << endl;
    break;
case 'u': case 'U':
    cout << "Sunday" << endl;
    pricea = 12;
    pricec = 0;
    total_price = (Adults*pricea) + (Children*pricec);
    cout << "Total price is: " << total_price << endl;
    break;
default:
    cout << "Not a valid day" << endl;
}
system("pause");
return 0;
}


texts:
This hides div.extended then creates a button that toggles its text and div.extended's visibility.

While the below works, I was wondering if there was a more concise way of writing this code.

(function() {

var extended = $('.extended').hide();

$('<button></button>', {
    text: 'Read more'
    }).appendTo('.intro')
        .on('click', function(){
            extended.slideToggle();
        }).toggle(
            function(){
                $(this).text('Read Less')
            },
            function(){
                $(this).text('Read More')
            });

})()


texts: Laravel generate category list from product results

texts:
I have product results with some filter, and the one is category. I'll get the category list from product results. the model category and products is one to many relationship.

This is the search query:

$results = Product::where('available','=', 1)->whereRaw('stock_available > min_quantity');
$results = $results->where(function($query) use($search){
$query->where('name', 'LIKE', '%' . $search . '%')
->orWhere('sku', 'LIKE', '%' . $search . '%')
->orWhere('part_number', 'LIKE', '%' . $search . '%');
});

I try to get the category list from the results, like this:

$arrayCategory = $results->pluck('category_id');
$arrayType = $results->pluck('product_type_id');
$arrayManufactur = $results->pluck('manufacturer_id');
$arrayOem = $results->pluck('is_oem');
$arrayUsedStatus = $results->pluck('newused');

$resultCategory = array_unique($arrayCategory);
$arrayCountCategory = array_count_values($arrayCategory);
$categories = Categories::whereIn('id', $resultCategory)->with('products')->pluck('name', 'id');

$resultType = array_unique($arrayType);
$arrayCountType = array_count_values($arrayType);
$types = ProductType::whereIn('id', $resultType)->with('products')->pluck('name', 'id');

$resultManufacturer = array_unique($arrayManufactur);
$arrayCountManufactur = array_count_values($arrayManufactur);
$manufacturList = Manufactur::whereIn('id', $resultManufacturer)->with('products')->pluck('name', 'id');

$resultOem = array_unique($arrayOem);
$arrayCountOem = array_count_values($arrayOem);

$resultUsedStatus = array_unique($arrayUsedStatus);
$arrayCountUsedStat = array_count_values($arrayUsedStatus);

This code takes too much time loading, and I want to know how I can optimize it to achieve faster loading.


texts:
def tictactoe():
    Board = [1,2,3,4,5,6,7,8,9]
    w = True
    PlayerX = []
    PlayerO = []
    while len(PlayerO) < 9:
        while True:
            z = int(input("Player X: Select a place (1-9)\n"))
            if z in Board:
                Board[z-1] = []
                PlayerX.append(z)
                break
            else:
                print("Place not available! Choose another X")
        while True:
            y = int(input("Player O: Select a place (1-9)\n"))
            if y in Board:
                Board[y-1] = []
                PlayerO.append(y)
                break
            else:
                print("Place not available! Choose another O")
        if len(PlayerX) > 2:
            if set([1,2,3]).issubset(set(PlayerX)) or set([4,5,6]).issubset(set(PlayerX)) or set([7,8,9]).issubset(set(PlayerX)) or set([1,4,7]).issubset(set(PlayerX)) or set([2,5,8]).issubset(set(PlayerX)) or set([3,6,9]).issubset(set(PlayerX)) or set([1,5,9]).issubset(set(PlayerX)) or set([3,5,7]).issubset(set(PlayerX)):
                print("Player X won!")
                w = False
                break
            elif set([1,2,3]).issubset(set(PlayerO)) or set([4,5,6]).issubset(set(PlayerO)) or set([7,8,9]).issubset(set(PlayerO)) or set([1,4,7]).issubset(set(PlayerO)) or set([2,5,8]).issubset(set(PlayerO)) or set([3,6,9]).issubset(set(PlayerO)) or set([1,5,9]).issubset(set(PlayerO)) or set([3,5,7]).issubset(set(PlayerO)):
                print("Player O won!")
                w = False
                break
    if w is True:
        print("Tie")
    if input("Play Again (y/n)?\n") == "y":
        tictactoe()
tictactoe()

I'm trying to make this code as efficient as possible. I'm new to Python and kinda limited with the knowledge I have. How can I simplify the code and especially the line shown below?

if set([1,2,3]).issubset(set(PlayerX)) or set([4,5,6]).issubset(set(PlayerX)) or set([7,8,9]).issubset(set(PlayerX)) or set([1,4,7]).issubset(set(PlayerX)) or set([2,5,8]).issubset(set(PlayerX)) or set([3,6,9]).issubset(set(PlayerX)) or set([1,5,9]).issubset(set(PlayerX)) or set([3,5,7]).issubset(set(PlayerX)):


texts: Channels vs. "for loop" prime number generator

texts:
I've found a question on SO (here), which is a prime number generator that uses channels. First of all, I had some trouble to find out how this code works, but later on, I saw the fun of it. Then, all the sudden, I saw the light! The code can be used perfectly to benchmark the difference between channels versus a for loop.  The question on SO uses a channel to store the total range of integers, then pulls the numbers one by one to figure out if it's prime or not. So I used my fasted code to calculate a prime number, versus the channel one. The question is, can it be improved?

This is the channel version:

package main

import "fmt"
import "time"

func Generate(ch chan<- int) {
    for i := 2; ; i++ {
        ch <- i
    }
}

func Filter(in <-chan int, out chan<- int, prime int) {
    for {
        i := <-in
        if i%prime != 0 {
            out <- i
        }
    }
}

func main() {
    ch := make(chan int)
    go Generate(ch)
    t0 := time.Now()
    for i := 0; i < 170; i++ {
        prime := <-ch
        fmt.Println(prime)
        ch1 := make(chan int)
        go Filter(ch, ch1, prime)
        ch = ch1
    }
    t1 := time.Now()
    fmt.Printf("The call took %v to run.\n", t1.Sub(t0))
}

This is my own version:

package main

import "fmt"
import "time"

func isPrime(number int) bool {
    switch {
    case number < 2:
        return false
    case number == 2:
        return true
    case number%2 == 0:
        return false
    default:
        for i := 3; (i * i) <= number; i += 2 {
            if number%i == 0 {
                return false
            }
        }
        return true
    }
}

func main() {
    t0 := time.Now()
    for i := 1; i < 1014; i++ {
        if isPrime(i) {
            fmt.Println(i)
        }
    }
    t1 := time.Now()
    fmt.Printf("The call took %v to run.\n", t1.Sub(t0))
}

The channel version runs in 21 ms. My own version runs in 11 ms.


texts:
I've made a little colour conversion app, and below is my JavaScript.

The app converts HEX values to RGB values and vice versa, as well as using a simple colour picker to get colours and convert them to both HEX and RGB.

Here is a picture so it is easier to understand what the code does. Basically you enter a HEX or RGB value into HTML input fields, and then the converted RGB/HEX value gets printed out.

You can also choose a colour from the 'Pick A Colour' section, and the colour selected also gets converted into HEX/RGB:

Does anyone have any suggestions to shorten this?

var svgPath = document.getElementById('path');
var colorInput = document.getElementById('color-input');
var hexOutput = document.getElementById('hex-output');
var rgbOutput = document.getElementById('rgb-output');
var rgb = document.getElementById("rgb");
var rgb2 = document.getElementById("rgb2");
var rgb3 = document.getElementById("rgb3");

// HEX to RGB
function hexToRGB(hex) {
    var bigint = parseInt(hex, 16);
    var r = (bigint >> 16) & 255;
    var g = (bigint >> 8) & 255;
    var b = bigint & 255;
    return r + ', ' + g + ', ' + b;
}

// RGB to HEX
function rgbToHEX(red, green, blue) {
    var rgb = blue | (green << 8) | (red << 16);
    return '#' + (0x1000000 + rgb).toString(16).slice(1);
}

// Gets HEX input
document.getElementById("hex").addEventListener("input", function() {
    // Sets colours for SVG, picker, converts HEX to RGB and prints out HEX
    svgPath.style.fill = '#' + this.value;
    colorInput.value = '#' + this.value;
    hexOutput.innerHTML = 'HEX: #' + this.value.toUpperCase();
    rgbOutput.innerHTML = 'RGB: rgb(' + hexToRGB(this.value) + ')';
}, false);

// Selects elements under .rgb class
var rgbInput = document.querySelectorAll('.rgb');
for(var i = 0; i < rgbInput.length; ++i){
    rgbInput[i].addEventListener("input", rgbCalc);
}

function rgbCalc() {
    // Skips to next input box if 3 characters have been entered
    if (rgb.value.length >= this.maxLength) {
        rgb2.focus();
    }
    if (rgb2.value.length >= this.maxLength) {
        rgb3.focus();
    }

    // Stores the r, g, b values
    var r = rgb.value;
    var g = rgb2.value;
    var b = rgb3.value;

    // Sets colours for SVG, picker, converts RGB to HEX and prints out RGB
    svgPath.style.fill = rgbToHEX(r, g, b);
    colorInput.value = rgbToHEX(r, g, b);
    rgbOutput.innerHTML = 'RGB: rgb(' + r + ', ' + g + ', ' + b + ')';
    hexOutput.innerHTML = 'HEX: ' + rgbToHEX(r, g, b).toUpperCase();
}

// Gets colour picker input value
colorInput.addEventListener("input", function() {
    // Sets colours for SVG, converts Hex to RGB and prints out HEX
    svgPath.style.fill = colorInput.value;
    hexOutput.innerHTML = "HEX: " + colorInput.value.toUpperCase();
    rgbOutput.innerHTML = "RGB: rgb(" + hexToRGB(colorInput.value.replace('#', ''))  + ')';
}, false);


texts: How to find the common factors of 2 numbers

texts:
Print the number of common factors of a and b.

input  > 10, 15

Output > 2

The common factors of 10, 15 are 1 and 5

My code

def print_factors(x,y):
    l = []
    for i in range(1, x + 1):
        if x % i == 0:
            l.append(i)
    m = []
    for i in range(1, y + 1):
        if y % i == 0:
            m.append(i)
    print (list(set(l).intersection(m)))
    #len(print (list(set(l).intersection(m))))

num1 = int(input("Enter a number: "))
num2 = int(input("Enter a number: "))

print_factors(num1,num2)

Is there any better way to optimize, like list comprehension. or using zip module


texts: Filter one array based on values of another, is this the best way?

texts:
categories = [{id: "761601bc-4daf-4db2-a0cf-fe7f443fcb94", name: "Shoes"},{id: "601ebcfe-fcbd-4075-a4b4-a42e356c5747", name: "Hats"},{id: "238933cf-77a5-4443-b290-7d7c836f80ff", name: "Eyewear"}];

voucher = {id:1,categories:["761601bc-4daf-4db2-a0cf-fe7f443fcb94","601ebcfe-fcbd-4075-a4b4-a42e356c5747"]};

filterCategories(voucher) {
  const result = voucher.categories
    ? categories
        .filter(cat => {
          return voucher.categories.includes(cat.id);
        })
        .map(v => v.name)
        .sort()
        .join()
    : "";

  return result;
}

Expecting: "Hats,Shoes"

The result needs to be filtered and sorted and returned as a string. Is there a faster, more efficient way of doing this. Maybe using Lodash?


texts: Writing and reading code from a text file

texts:
Using file stream object, write a program to read an external text file ("myCourse.txt") which contains all the course name and numbers you are taking this semester, and to generate an analysis (total number of courses) into an external file ("myCourseSummay.txt").

This is a past question my teacher has been hinting at us to practice, so my friend and I made this and wanted to know if would be acceptable. Personally, I think we messed the writing to the .txt file.

#include <iostream>
#include <fstream>
#include<string>
using namespace std;

int intro()
{
    cout << "Hello World!";
    return 0;
}

int main()
{
    ofstream myCourse;
    myCourse.open("myCourse.txt");
    char course1[20], course2[20], course3[20], course4[20];

    cout << "Enter number of courses. max of 4" << endl;
    cout << "Enter 1st course: ";
    cin >> course1;
    myCourse << course1 << endl;
    cout << "Enter 2nd course: ";
    cin >> course2;
    myCourse << course2 << endl;
    cout << "Enter 3rd course: ";
    cin >> course3;
    myCourse << course3 << endl;
    cout << "Enter 4th course: ";
    cin >> course4;
    myCourse << course4 << endl;

    myCourse.close();

    ifstream myCourseSummary;
    string word;
    int count = 0;
    myCourseSummary.open("myCourseSummary.txt");

    while(!myCourseSummary.eof())
    {
        myCourseSummary >> word;
        count++;
    }

    cout << "Total number if courses is(are) " << count << "!";
    myCourseSummary.close();

    cin.get();
    return 0;
}


texts: Select input that is generated and populated with options

texts:
I started to learn PHP OOP recently and searched the web for some practical exercises and I found one that said to build a select input that is generated and populated with options by the object.  I just want to ask for some opinions on code quality.  Could it be done better?  What is the biggest flaw?

The class:

class completeSelect{

    private $setIn;
    private $option;

    public function __construct($val = array()) {
        $this->setIn=$val;

        $this->buildOptions();
    }

    public function buildOptions()
    {
        $this->option = "";
        foreach($this->setIn as $value)
        {
            $this->option .= '<option value="'.$value.'">'.$value.'</option>';
        }

        return $this->option;
    }

    public function BuildSelect() {
        $bs  = '<select name="select_brwoser">';
        $bs .= $this->option;
        $bs .= '</select>';

        return $bs;
    }
}

The output:

require_once("class.php");

$n = new completeSelect(array("Mozilla","Opera","Internet Explorer"));
echo $n->buildSelect();


texts: Is this a sensible form iteration pattern for a web form with an unknown number of fields?

texts:
I'm designing a small intranet-based time-tracking web app that accepts an unknown number of data "rows" which each consist of 7 form fields. Rows can by dynamically added by the browser.

Can I do better?

Given this (partial) example POST data:

$_POST['project'] =>
 Array
 (
     [0] => PROJECT_CODE_1
     [1] => PROJECT_CODE_1
 )

$_POST['task']
 Array
 (
     [0] => 21
     [1] => 4
 )

$_POST['date']
 Array
 (
     [0] => 2012-07-31
     [1] => 2012-07-31
 )

And this iterator:

<?php
$insert_values = array();

for ($i = 0; $i < count($_POST['project']); $i++)
{
    $insert_values[] = array(
        'entry_id' => null,
        'user_id' => $this->session->userdata('user_id'),
        'project_id' => $_POST['project'][$i],
        'task_id' => $_POST['task'][$i],
        'date' => $_POST['date'][$i]
    );
}

$this->db->insert_batch('entries', $insert_values);
?>

In general, is this iteration pattern safe and sensible? POST['project'] is a drop-down, is validated and will always be filled.


texts: Checking locked users using Identity 2.0

texts:
I'm writing a theoretical MVC application to aid in learning more about ASP Identity 2. In real terms I'm new to ASP Identity as a whole but thought I'd jump in in this release as

it's the default in new projects and
everything I read about it seems to mostly suit my needs.

There is one issue that I need to be able to overcome. That issue is locking out users. I want to allow administrators the facility to be able to lock out a user should they wish to restrict their access.

From what I've read so far, there is a temporary lockout solution for example when the user tries their password incorrectly x number of times for y number of minutes. This doesn't seem to be the recommended method for more long term solutions.

For a longer term solution, I've added a Locked property to the ApplicationUser class in Entity Framework code first:

public class ApplicationUser : IdentityUser
{
    public string FirstName { get; set; }
    public string Surname { get; set; }
    public bool Locked { get; set; }
    [NotMapped]
    public string FullName
    {
        get
        {
            return FirstName + " " + Surname;
        }
    }
}

Getting to the point of my question though, which is, is my modified ActionResult Login method secure and efficient? I don't want to make unnecessary roundtrips to the database and I also don't want to unwillingly do anything unsecure.

public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
    {
        if (!ModelState.IsValid)
        {
            return View(model);
        }
        // MY LOCKED CHECK CODE:
        // Check if the user is locked out first
        // 1. Fail if it is
        // 2. If user isn't found then return invalid login atempt
        // 3. If the user is found and it isn't locked out then proceed with the login as usual
        var user = UserManager.Users.Where(u => u.UserName == model.Email).SingleOrDefault();
        if (user != null)
        {
            if (user.Locked)
            {
                return View("Lockout");
            }
        }
        else
        {
            ModelState.AddModelError("", "Invalid login attempt.");
            return View(model);
        }
        // END MY CODE

        // This doesn't count login failures towards account lockout
        // To enable password failures to trigger account lockout, change to shouldLockout: true
        var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
        switch (result)
        {
            case SignInStatus.Success:
                return RedirectToLocal(returnUrl);
            case SignInStatus.LockedOut:
                return View("Lockout");
            case SignInStatus.RequiresVerification:
                return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
            case SignInStatus.Failure:
            default:
                ModelState.AddModelError("", "Invalid login attempt.");
                return View(model);
        }
    }


texts: Extract the largest value for each day from a matrix


texts:
I've not played with SupportsPaging before, so wanted to knock up some demo code & get feedback on whether my implementation is OK, or if I've misunderstood something.  I created the function 'Invoke-DummyRestMethod' to simulate calling Invoke-RestMethod with a URI for a web service which supported paging; only this Dummy version just spits out numbers, to keep things uncomplicated.

Function Invoke-DummyRestMethod {
    [CmdletBinding()]
    Param (
        [Parameter(Mandatory = $true)]
        [string]$Uri #= 'http://demo.com?start=20&limit=10' #example
    )
    begin {
        [string]$regex = '(?:[\?&]limit=(?<limit>\d+)|[\?&]start=(?<start>\d+))+'
        [long]$maxResults = 1000 #i.e. function will return 0 to 999 if no paging
    }
    Process {
        [long]$start = 0 #nb: these must be declared as int; otherwise (as the results later come from a regex match) they'll be treated as strings / will cause issues with the Math.Min function!
        [long]$limit = 0 #should 0 be a valid value / we use -1 for non valid?  Assuming 0 is invalid
        if ($Uri -match $regex) {
            if($matches.start){$start = $matches.start}
            if($matches.limit){$limit = $matches.limit}
        }
        write-verbose "Start: $start"
        write-verbose "Limit: $limit"
        if ($limit -le 0){$limit = $maxResults}
        $start..([Math]::Min(($start+$limit),$maxResults) - 1)
    }
}

Function Get-PagedData {
    [CmdletBinding(SupportsPaging = $True)]
    Param (
        [parameter(Mandatory = $true)]
        [uri]$Uri
    )
    Begin {
        Add-Type -AssemblyName 'System' #NameValueCollection (ok, we don't need to add this type; but I like to be explicit)
        Add-Type -AssemblyName 'System.Web'  #HttpUtility
        [long]$PagingSkip = [Math]::Max($PSCmdlet.PagingParameters.Skip,0)
        [long]$PagingFirst = [Math]::Max($PSCmdlet.PagingParameters.First, 0)
    }
    Process {
        [System.UriBuilder]$UriBuilder = New-Object -TypeName 'System.UriBuilder' -ArgumentList $Uri
        [System.Collections.Specialized.NameValueCollection]$Query = [System.Web.HttpUtility]::ParseQueryString($UriBuilder.Query)
        if ($PagingSkip -gt 0) {$Query['start'] = $PagingSkip}
        if ($PagingFirst -gt 0) {$Query['limit'] = $PagingFirst}
        $UriBuilder.Query = $Query.ToString()
        Invoke-DummyRestMethod -Uri $UriBuilder.ToString() | Tee-Object -Variable 'Results'
    }
    End{
        If ($PSCmdlet.PagingParameters.IncludeTotalCount){
            [bool]$knownCount = ($PagingFirst -eq 0) -or ($PagingFirst -gt $Results.Count) #if we got less results than our limit (or we've not applied a limit) then we've reached the end, so we know the number of result
            #$PSCmdlet.PagingParameters.NewTotalCount($Results.Count + $PagingSkip, 1.0 * $knownCount) #use this if we want to avoid estimates; i.e. if we don't have all the results, we don't have a clue how many there are
            $PSCmdlet.PagingParameters.NewTotalCount($Results.Count + $PagingSkip, [Math]::Min(1.0, (1.0 * $knownCount + 0.5))) #use this if we want the number of results (plus any skipped) to be used as the estimated amount (i.e. there are at least this many results)
        }
    }
}

Get-PagedData 'http://demo.com' -Skip 10 -First 20 -IncludeTotalCount -Verbose

I'm particularly interested in the rules for estimation; i.e. where you know the exact number of items clearly the accuracy should be 1.0; but where this figure's not known, is it OK to claim that because we have some results we can say that that's an estimate (since we know there are at least that many; so the total's not completely unknown); should we claim 0.0 as we don't know how far out this figure is, or is there some other guidance on this?

Related Gist: https://gist.github.com/JohnLBevan/70ee8247ae7c324f8710c8a8bedd2b96/


texts: Separating integers substrings from those with alphabetical letters

texts:
The goal of my code is given a string, to separate the integer substrings from those containing solely alphabetical letters, with the individual substrings in a list.

For example:

Input: 1h15min
Output: ["1", "h", "15", "min"]

Here is the code:

def separate_text(input_text):
    if not input_text:
        return None
    character_list = []
    current_substring = ""
    string_type = ""
    for character in input_text:
        if character in "0123456789":
            if string_type in ("Int", ""):
                current_substring += character
                if string_type == "":
                    string_type = "Int"
            else:
                character_list.append(current_substring)
                string_type = "Int"
                current_substring = character
        elif character not in "0123456789":
            if string_type in ("Str", ""):
                current_substring += character
                if string_type == "":
                    string_type = "Str"
            else:
                character_list.append(current_substring)
                string_type = "Str"
                current_substring = character
    character_list.append(current_substring)
    return character_list

The function functions as follows:

Take an input string (if empty, return None)
Begin looping through the string, character by character
If the character is an integer

If string_type is Int or "", append the character to current_substring and change string_type if needed
If string_type is Str, append the substring to the character_list, reassign current_substring to whatever the character is, and change the string_type to "Int".

If the character is an string

If string_type is Str or "", append the character to current_substring and change string_type if needed
If string_type is Int, append the substring to the character_list, reassign current_substring to whatever the character is, and change the string_type to "Str".

End of the whole string? Append current_substring to the list and return the character_list.

My questions here are:

Is there any way to make the program for Pythonic?
Can I possible shorten my code? The two main if statements in the for loop have nearly identical code.

Note that I do not count floats so 1.15min returns ['1', '.', '15', 'min'].


texts:
So I'm currently using python to unscramble words that are retrieved from an OCR program, and checked in the 'dictionary'.

The current code I am using to unscramble words is this:

import numpy as nm
import pytesseract
import cv2
import ctypes
from PIL import ImageGrab

def imToString():

    # Path of tesseract executable
    pytesseract.pytesseract.tesseract_cmd =r'C:\Program Files (x86)\Tesseract-OCR\tesseract'
    while(True):

        # ImageGrab-To capture the screen image in a loop.
        # Bbox used to capture a specific area.
        cap = ImageGrab.grab(bbox =(687, 224, 1104, 240))

        # Converted the image to monochrome for it to be easily
        # read by the OCR and obtained the output String.
        tesstr = pytesseract.image_to_string(
                cv2.cvtColor(nm.array(cap), cv2.COLOR_BGR2GRAY),
                lang ='eng')
        checkWord(tesstr)

def checkWord(tesstr):

    dictionary =['orange', 'marshmellow']

    scrambled = tesstr
    for word in dictionary:
        if sorted(word) == sorted(scrambled):
            print(word)

imToString()

I want to know if there is anyway to reduce the time it takes to look through the 'dictionary', as there are many more words to go through.


texts: Expressing multiple AND conditions in ruby

texts:
In ruby, is there a more concise way of expressing multiple AND conditions in an if statement?

For example this is the code I have:

    if first_name.blank? and last_name.blank? and email.blank? and phone.blank?
      #do something
    end

Is there a better way to express this in Ruby? 1.9.2 or 1.9.3


texts: Convert a string into an R vector expression

texts:
Problem: Given a arbitrary string, split by a given regex and format into an R vector expression. E.g. Convert "a..,b..,c,d" into 'c("a","b","c","d")', when the given regex is "[.,]+".

Solution in haskell:

module Lib
    ( toRVec
    ) where

import           Data.List  (intersperse)
import           Data.Maybe (fromMaybe)
import           Data.Text  ()
import           Data.Text  (pack, strip, unpack)
import           Text.Regex (mkRegex, splitRegex)

(//) :: Maybe a -> a -> a
(//) = flip fromMaybe

stripString = (unpack . strip . pack)

toRVec :: String -> Maybe String -> Maybe Bool ->  String
toRVec orig delim' toStrip' =
  let
      delim = delim' // "[ \n]+"
      toStrip = toStrip' // True
      ws = splitRegex (mkRegex delim) $ stripString orig
      ws1 = map (\w -> "\"" ++ w ++ "\"") $ if toStrip then
                                                      map stripString ws
                                                    else
                                                      ws
      ws2 = intersperse "," ws1
      res = foldl (++) "" ws2
   in "c(" ++ res ++ ")"

Any suggestion for improvements are welcome.


texts:
I'm currently learning C with "The C Programming Language" by K&R. At the moment I'm at the chapter about pointers (since I come from Java, they are new to me). In the book is an example code for a method getint(), which is supposed to read integers from input, but doesn't handle freestanding '+' and '-' correctly.

  As written, getint treats a + or - not followed by a digit as a valid representation of zero. Fix it to push such a character back on the input.

This is what I wrote:

int getint(int *pn)
{
   int c, sign;

   while(isspace(c = getch()))
      ;

   if(c == EOF)
      return EOF;

   if(!isdigit(c) && c != '+' && c != '-')
      return 0;

   sign = (c == '-') ? -1 : 1;

   if(c == '+' || c == '-')
      c = getch();

   if(!isdigit(c)) {
      ungetch(c);
      return 0;
   }

   *pn = 0;
   while(isdigit(c)) {
      *pn = *pn * 10 + c - '0';
      c = getch();
   }

   *pn *= sign;
   ungetch(c);

   return 1;
}

I modified the version inside K&R quite a bit and was wondering if I did a good job at doing so. My getint() is supposed to return EOF when end of file is reached, 0 if it failed to read the current character as an integer and 1 if it successfully wrote the int into *pn.

The K&R code begins with the follwing lines:

int c, sign;
while(isspace(c = getch()))
    ;

if(!isdigit(c) && c != EOF && c != '+' && c != '-') {
    ungetch(c);
    return 0;
}

And I think that the code will stuck if a non-digit, non-'+/-' and non EOF file character is found. Since it'll just unget this char and read it again in the next function call. Is this made on purpose? I left out the ungetch(), since I think that the function is supposed to just read the next char of input in the next function call...


texts: Code style: Should prints be high or low level?

texts:
Where should i put print statements describing the flow of the program? Is there any convetion or code style for this?
Should they be in higher level functions?
def create_collage():
    print('finding images ...')
    image_paths = get_image_paths()

    print('loading images ...')
    images = load_images(image_paths)

    print('assembling output image ...')
    output = assemble_output(images)

    ...

Or in lower level functions?
def get_image_paths():
    print('finding images ...')
    ...

def load_images(image_paths):
    print('loading images ...')
    ...

def assemble_images(images):
    print('assembling output image ...')
    ...

```


texts:
I've implemented the following code which allows me to bolt modules of code on to my core library via the prototype chain. It's quite prescriptive so any user creating a module has to create an init method and also has to define a queue method:

(working fiddle: http://jsfiddle.net/wG9Pv/)

//Constructor
test = function() {
    this.tester = 'The instance was successfully created';
};

//A core method
test.prototype.amethod = function() {

};

//Extend method which facilitates the module system
test.extend = function(name,plugin) {
    test.prototype[name] = plugin.init;
    //later do something with the queue method that's been fed in via the 'plugin' object
};

//Add a module
test.extend('method1', {

    init: function(val) {
        console.log(this.tester);
    },

    queue: function() {

    },

    render: function() {

    }
});

//add another module
test.extend('method2',{

    init: function() {
        console.log('Init of the plugin has been fired');
    },

    draw : function() {}
});

var test = new test();
test.method1('boom!');
test.method2();

Now this all works well but is this a good way of achieving it?


texts: Project Euler #8 - Largest product in a sequence