HasPostgres instance for IO with Snap framework I want to write my database access code for a Snap application in a way that makes the queries easy to test from the ghci repl, while also working within the Snap context. My solution so far is to define a HasPostgres instance for IO and to write all my DB access functions following the pattern of allUsers in the code snippet below. Am I doing this correctly?

{-# LANGUAGE OverloadedStrings #-}

module Database where
import Core
import Control.Applicative
import Database.PostgreSQL.Simple.FromRow (field, fromRow)
import Database.PostgreSQL.Simple.ToRow (toRow)
import Database.PostgreSQL.Simple.ToField (toField)
import Snap.Snaplet.PostgresqlSimple
import           Data.Pool
import qualified Database.PostgreSQL.Simple as P
import Data.Text (Text)
import qualified Data.Text as T
import Control.Monad.CatchIO

instance FromRow User where
  fromRow = User <$> field <*> field

instance ToRow User where
  toRow (User a b) = [toField a, toField b]

allUsers :: (HasPostgres m) => m [User]
allUsers = query_ "SELECT user_id, email from users"

instance HasPostgres IO where
  getPostgresState = do
    let stripes = 1
    let idle = 5
    let resources = 20
    let ci = P.ConnectInfo "localhost" 5432 "choi" "" "testDatabase"
    pool <- createPool (P.connect ci) P.close stripes (realToFrac (idle :: Double)) resources
    return $ Postgres pool

Yes, this looks good to me.  I've done exactly the same thing to facilitate debugging in my projects.  However, I would recommend that you put the IO instance in some special module where all your debugging code lives.  You really do not want instances like this making their way into any other code because it is akin to making a global statement that IO always has a test database available at localhost on port 5432.


Sort by a custom date field I've got this code to work, but being really new to PHP, I don't know if this is proper. I've sorted a CPT loop by a custom date.

I'm displaying items from most recent (or future date) to oldest
if the custom date is in the future I display an additional HTML element that says Coming Soon. I've used strtotime for the custom date and compared it to today.

I'm most interested in knowing a better method for converting and comparing time, and if this loop is a proper method of using orderby with a custom date.

get_field() is from the Advanced Custom Fields WordPress plugin.

<?php

    //Loop arguments

    $today = date('Ymd');
    $args = array(
                'post_type' => 'release',
                'showposts' => 6,
                'meta_key'  => 'release_date',
                'orderby'   => 'meta_value_num', // orderby meta field date
                'order'     => 'DESC'
            );
    // query and loop
    $release_query = new WP_Query( $args );

    // $release_date = get_field('release_date');

    while ( $release_query->have_posts() ) : $release_query->the_post();
    // don't duplicate featured posts
    if ( in_array($post->ID, $do_not_duplicate) ) continue;
        update_post_caches( $posts );
?>

    <div class="cd"
        <?php

            $image = get_field('cd_cover');

            if( !empty($image) ): ?>

                <a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><img src="<?php echo $image['url']; ?>" alt="<?php echo $image['alt']; ?>" />

            <?php endif; ?>

            <a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>">
                <?php the_title(); ?>

        <?php
        $cd_date = get_field('release_date');
        $release_date = date('Ymd', strtotime($cd_date)); // convert custom date to something manageable?
        if ( $release_date > $today ) {
            echo '
Coming Soon!
';
        }

        ?>

    <?php
        //release loop ends
        endwhile;
        // reset
        wp_reset_postdata();
    ?>

I do know nothing about WordPress, so I will not be able to answer if the loop is a proper method for using order by.

Converting and comparing time

The DateTime class has great utilities for exactly this kind of thing. You have DateTime::createFromFormat to use your custom format, DateTime->format for formatting, and DateTime->sub and DateTime->diff for comparing.

Timestamp

For very simple comparing like "is this date bigger than that date," you could use timestamps (AKA time()) and compare them with <> as a timestamp is just a big number (seconds from 1970 until now). This will be more reliable than comparing date strings.


Simple object pool template container in C++ The main advantage of this pattern is when I often create and destroy objects, which in this case are often used.

I made this because I needed to track several short timers at the same time, but it can also  be used for stuff like missiles or else.

#include <vector>
#include <queue>

#define itv(TYPE) std::vector<TYPE>::iterator

using namespace std;
template <class TYPE>
struct object_pool
{
    std::vector<TYPE> pool;
    std::queue<size_t> avail;
    TYPE & operator[](const size_t & i) { return pool[i]; }
    void add(size_t & pos)
    {
        if(avail.empty()) // no reusable object
        { pool.push_back(TYPE()); pos = pool.size()-1; }
        else
        { pos = avail.back(); avail.pop(); }
    }
    void rem(size_t & a) { avail.push(a); }
    size_t size() { return pool.size(); }
};

What do you think ?

Don't do this:

using namespace std;

In anything other than a toy this will cause problems.

I don't like this:

#define itv(TYPE) std::vector<TYPE>::iterator

With C++11 this type if thing has been resolved by auto.

I would also define the iterator in terms of the object pool:

template <class TYPE>
struct object_pool
{
    typedef std::vector<TYPE>::iterator  iterator;

I would hide the fact that internally the object_pool uses a vector and queue. I would then add the obligatory functions to extract information:

template <class TYPE>
class object_pool
{
    std::vector<TYPE> pool;
    std::queue<size_t> avail;

  public:
    typedef std::vector<TYPE>::iterator       iterator;
    typedef std::vector<TYPE>::const_iterator const_iterator;

    iterator       begin()       { return pool.begin();}
    iterator       end()         { return pool.end();}
    const_iterator begin() const { return pool.begin();}
    const_iterator end()   const { return pool.end();}

To access elements I would also provide const version

    TYPE&       operator[](std::size_t index)       { return pool[index];}
    TYPE&       at(std::size_t index)               { return pool.at(index);}

    TYPE const& operator[](std::size_t index) const { return pool[index];}
    TYPE const& at(std::size_t index) const         { return pool.at(index);}

The methods that can be const should be const:

    size_t size() const { return pool.size(); }
             //  ^^^^^^^

The implementation details are fine.

    void add(size_t & pos)
    {
        if(avail.empty()) // no reusable object
        { pool.push_back(TYPE()); pos = pool.size()-1; }
        else
        { pos = avail.back(); avail.pop(); }
    }
    void rem(size_t & a) { avail.push(a); }

I would change the add() so it returned pos:

    size_t add();

Also the vector starts off very small and re-sizes to get bigger.
To make sure that it does not re-size too often I would add a constructor that gives the vector a reasonable size to start with:

object_pool::object_pool()
{
    pool.reserve(1000);
}

But I think you are using the wrong technique.
I would use a pool allocator and plug it into the vector.

You can read more about it here: https://stackoverflow.com/q/2984434/14065


Improving sqlite3 code in swift using c api Trying to come up with a pattern where the code to open db, writing queries is elegant and clean while handling all possible error conditions.
Following code
let file = try! FileManager.default.url(for: .cachesDirectory, in: .userDomainMask, appropriateFor: nil, create: false).appendingPathComponent("mydb.db")

var result = sqlite3_open(file.path, &database)

if result == SQLITE_OK {
    defer { sqlite3_close(database) }
} else {
    print("couldn't open database")
    return
}

result = sqlite3_exec(database, "CREATE TABLE IF NOT EXISTS department(id INTEGER PRIMARY KEY, name TEXT NOT NULL)", nil, nil, nil)
if result != SQLITE_OK {
    print("couldn't insert into department")
    return
}

result = sqlite3_exec(database, "INSERT OR REPLACE INTO department(id, name) VALUES(0, 'HR'), (1, 'Sales'), (2, 'Accounts'), (3, 'Shipping')", nil, nil, nil)
if result != SQLITE_OK {
    print("error inserting")
    return
}

A few observations:

The .cachesDirectory is deleted when your device runs low in storage. Are you sure you want to delete your app database in this scenario? Usually we would use .applicationSupportDirectory, which is not deleted when storage runs low and is backed up when you back up your device. But we avoid the use of the .documents folder, because that is reserved for user-facing files.
Also, we would also generally use use the create option of true.

If opening a database failed for any reason, you still need to call sqlite3_close. As the documentation says:

Whether or not an error occurs when it is opened, resources associated with the database connection handle should be released by passing it to sqlite3_close() when it is no longer required.

So I would move the defer out of that if statement. You want to move it out of there, anyway, because defer will run at the end of the current scope (at the end of your if statement in your current implementation), not at the end of the function. But if you move the defer to the right place, that observation is moot.

If a SQL statement fails for any reason, if you are going to print an error, you really should include the sqlite3_errmsg. Without that, it will be exceedingly difficult to debug problems.

I would generally advise using guard in situations where you want to exit upon failure. The compiler will make sure that you properly return when an error condition occurs.
So, pulling that together with the above points, you get something like:
let folder = try! FileManager.default
    .url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
    .appendingPathComponent("AppData")

try? FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)

let fileURL = folder.appendingPathComponent("mydb.db")

var database: OpaquePointer?
var result = sqlite3_open(fileURL.path, &database)

defer { sqlite3_close(database) }

guard result == SQLITE_OK else {
    printError(in: database, message: "couldn't open database")
    return
}

result = sqlite3_exec(database, "CREATE TABLE IF NOT EXISTS department(id INTEGER PRIMARY KEY, name TEXT NOT NULL)", nil, nil, nil)
guard result == SQLITE_OK else {
    printError(in: database, message: "couldn't insert into department")
    return
}

result = sqlite3_exec(database, "INSERT OR REPLACE INTO department(id, name) VALUES(0, 'HR'), (1, 'Sales'), (2, 'Accounts'), (3, 'Shipping')", nil, nil, nil)
guard result == SQLITE_OK else {
    printError(in: database, message: "error inserting")
    return
}

Where
func printError(in database: OpaquePointer?, message: String) {
    let error = sqlite3_errmsg(database).flatMap { String(cString: $0) } ?? "Unknown error"
    print(message, error)
}

Usually we do not open and close the database with every method call. We generally open the database once, and leave it open. SQLite is very good about committing changes to the file as you go along, so opening and closing the database for every call is a tad inefficient.

As a broader observation, I would suggest abstracting the SQLite API from this department related SQL. E.g., perhaps
do {
    let database = try openDatabase()
    try database.exec("CREATE TABLE IF NOT EXISTS department(id INTEGER PRIMARY KEY, name TEXT NOT NULL)")
    try database.exec("INSERT OR REPLACE INTO department(id, name) VALUES(0, 'HR'), (1, 'Sales'), (2, 'Accounts'), (3, 'Shipping')")
} catch {
    print(error)
}

Where:
func openDatabase() throws -> Database {
    let folder = try! FileManager.default
        .url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
        .appendingPathComponent("AppData")

    try? FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)

    let fileURL = folder.appendingPathComponent("mydb.db")

    let database = Database(fileURL: fileURL)

    try database.open()

    return database
}

Now, the above is using my own personal SQLite database wrapper:
//  Database.swift
//
//  Created by Robert Ryan on 3/8/19.

import Foundation
import SQLite3

private let SQLITE_STATIC = unsafeBitCast(0, to: sqlite3_destructor_type.self)
private let SQLITE_TRANSIENT = unsafeBitCast(-1, to: sqlite3_destructor_type.self)

// MARK: - Database

/// Thin wrapper for SQLite C interface

public class Database {
    // MARK: - Properties

    /// The URL for the database
    let fileURL: URL

    /// The `sqlite3_open` options
    public var options: OpenOptions

    /// A `DateFormatter` for writing dates to the database
    public static var dateFormatter: DateFormatter = {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSX"
        formatter.timeZone = TimeZone(secondsFromGMT: 0)
        formatter.locale = Locale(identifier: "en_US_POSIX")
        return formatter
    }()

    /// The SQLite database pointer
    private var database: OpaquePointer?

    /// Array of prepared statements that have not yet been finalized
    private var openStatements: [Statement] = []

    // MARK: - Initialization

    /// Database initializer
    ///
    /// Note: You must still `open` this database before using it.
    public init(fileURL: URL, options: OpenOptions = .default) {
        self.fileURL = fileURL
        self.options = options
    }

    /// Deinitializer that will finalize any open statements and then close the database if not already closed.
    deinit {
        finalizeStatements()
        try? close()
    }
}

// MARK: - Types

public extension Database {
    enum DatabaseError: Error {
        case failed(ReturnCode, String)
        case unknownType(Any)
        case notOpened
        case noStatementPrepared
        case closeFailed
    }

    struct OpenOptions: OptionSet {
        public let rawValue: Int32

        public static let readOnly     = OpenOptions(rawValue: SQLITE_OPEN_READONLY)
        public static let readWrite    = OpenOptions(rawValue: SQLITE_OPEN_READWRITE)
        public static let create       = OpenOptions(rawValue: SQLITE_OPEN_CREATE)
        public static let noMutex      = OpenOptions(rawValue: SQLITE_OPEN_NOMUTEX)
        public static let fullMutex    = OpenOptions(rawValue: SQLITE_OPEN_FULLMUTEX)
        public static let sharedCache  = OpenOptions(rawValue: SQLITE_OPEN_SHAREDCACHE)
        public static let privateCache = OpenOptions(rawValue: SQLITE_OPEN_PRIVATECACHE)

        public static let `default`:  OpenOptions = [.readWrite, .create]

        public init(rawValue: Int32) {
            self.rawValue = rawValue
        }
    }

    enum ReturnCode: Equatable {
        // non error codes

        case ok
        case done
        case row

        // error codes

        case auth
        case busy
        case cantOpen
        case constraint
        case corrupt
        case empty
        case error
        case fail
        case format
        case full
        case `internal`
        case interrupt
        case ioerr
        case locked
        case mismatch
        case misuse
        case nolfs
        case nomem
        case notadb
        case notfound
        case notice
        case perm
        case `protocol`
        case range
        case readonly
        case schema
        case toobig
        case warning

        case unknown(Int32)

        static func code(for code: Int32) -> ReturnCode {
            switch code {
            case SQLITE_OK:         return .ok
            case SQLITE_DONE:       return .done
            case SQLITE_ROW:        return .row

            case SQLITE_AUTH:       return .auth
            case SQLITE_BUSY:       return .busy
            case SQLITE_CANTOPEN:   return .cantOpen
            case SQLITE_CONSTRAINT: return .constraint
            case SQLITE_CORRUPT:    return .corrupt
            case SQLITE_EMPTY:      return .empty
            case SQLITE_ERROR:      return .error
            case SQLITE_FAIL:       return .fail
            case SQLITE_FORMAT:     return .format
            case SQLITE_FULL:       return .full
            case SQLITE_INTERNAL:   return .internal
            case SQLITE_INTERRUPT:  return .interrupt
            case SQLITE_IOERR:      return .ioerr
            case SQLITE_LOCKED:     return .locked
            case SQLITE_MISMATCH:   return .mismatch
            case SQLITE_MISUSE:     return .misuse
            case SQLITE_NOLFS:      return .nolfs
            case SQLITE_NOMEM:      return .nomem
            case SQLITE_NOTADB:     return .notadb
            case SQLITE_NOTFOUND:   return .notfound
            case SQLITE_NOTICE:     return .notice
            case SQLITE_PERM:       return .perm
            case SQLITE_PROTOCOL:   return .protocol
            case SQLITE_RANGE:      return .range
            case SQLITE_READONLY:   return .readonly
            case SQLITE_SCHEMA:     return .schema
            case SQLITE_TOOBIG:     return .toobig
            case SQLITE_WARNING:    return .warning

            default:                return .unknown(code)
            }
        }
    }
}

// MARK: - Public methods

public extension Database {
    /// Open database
    func open() throws {
        do {
            try call { sqlite3_open_v2(fileURL.path, &database, options.rawValue, nil) }
        } catch {
            try? close()
            throw error
        }
    }

    /// Close database
    func close() throws {
        if database == nil { return }
        finalizeStatements()
        try call {
            defer { database = nil }
            return sqlite3_close(database)
        }
    }

    /// Execute statement
    ///
    /// - Parameter sql: SQL to be performed.
    /// - Throws: SQLite errors.
    func exec(_ sql: String) throws {
        guard database != nil else { throw DatabaseError.notOpened }

        try call { sqlite3_exec(database, sql, nil, nil, nil) }
    }

    /// Prepare SQL
    ///
    /// - Parameters:
    ///   - sql:        SQL to be prepared
    ///   - parameters: Any parameters to be bound to any `?` in the SQL.
    /// - Returns: The prepared statement.
    /// - Throws: SQLite errors.
    func prepare(_ sql: String, parameters: [DatabaseBindable?]? = nil) throws -> Statement {
        guard database != nil else { throw DatabaseError.notOpened }

        var stmt: OpaquePointer?

        try call { sqlite3_prepare_v2(database, sql, -1, &stmt, nil) }

        let statement = Statement(database: self, statement: stmt!)

        openStatements.append(statement)

        try statement.bind(parameters)

        return statement
    }

    /// The `rowid` of the last row inserted
    ///
    /// - Returns: The `rowid`.
    func lastRowId() -> Int64 {
        sqlite3_last_insert_rowid(database)
    }

    /// Returns number of rows changed by last `INSERT`, `UPDATE`, or `DELETE` statement.
    ///
    /// - Returns: Number of rows changed.
    func changes() -> Int32 {
        sqlite3_changes(database)
    }

    /// Returns number of rows changed `INSERT`, `UPDATE`, or `DELETE` statements since the database was opened.
    ///
    /// - Returns: Number of rows changed.
    func totalChanges() -> Int32 {
        sqlite3_total_changes(database)
    }

    /// Finalize a previously prepared statement
    ///
    /// - Parameter statement: The previously prepared statement.
    /// - Throws: SQLite error.
    func finalize(_ statement: Statement) throws {
        guard let index = openStatements.firstIndex(where: { $0.sqlite3_stmt == statement.sqlite3_stmt }) else {
            return
        }

        openStatements.remove(at: index)

        try call {
            defer { statement.sqlite3_stmt = nil }
            return sqlite3_finalize(statement.sqlite3_stmt)
        }
    }

    /// The version of SQLite being used.
    ///
    /// - Returns: Version string.
    func version() -> String? {
        sqlite3_libversion()
            .flatMap { String(cString: $0) }
    }
}

// MARK: Private methods

fileprivate extension Database {
    /// Call block containing SQLite C function
    ///
    /// - Parameter block: Block that returns value from SQLite C function.
    /// - Returns: Returns return value from that C function if it returned `.ok`, `.done`, or `.row`.
    /// - Throws: SQLite error.
    @discardableResult
    func call(block: () -> (Int32)) throws -> Database.ReturnCode {
        let result = Database.ReturnCode.code(for: block())
        switch result {
        case .ok, .done, .row:
            return result

        default:
            let message = String(cString: sqlite3_errmsg(database))
            throw DatabaseError.failed(result, message)
        }
    }

    /// Finalize all open statements (those prepared but not yet finalized).
    func finalizeStatements() {
        for statement in openStatements {
            try? finalize(statement)
        }
    }
}

// MARK: - Statement

/// SQLite statement.
public class Statement {
    public fileprivate(set) var sqlite3_stmt: OpaquePointer?
    private weak var database: Database?

    init(database: Database, statement: OpaquePointer) {
        self.database = database
        self.sqlite3_stmt = statement
    }

    deinit {
        try? database?.finalize(self)
    }
}

// MARK: Public methods

public extension Statement {
    /// Bind array of parameters to `?` placeholders in SQL
    ///
    /// - Parameter parameters: The array of parameters.
    /// - Throws: SQLite error.
    func bind(_ parameters: [DatabaseBindable?]?) throws {
        try parameters?.enumerated().forEach { index, value in
            let offset = Int32(index + 1)
            if let value = value {
                try database?.call { value.bind(to: self, offset: offset) }
            } else {
                try database?.call { sqlite3_bind_null(sqlite3_stmt, offset) }
            }
        }
    }

    @discardableResult
    /// Perform the prepared statement.
    ///
    /// - Returns: The return code if `.done`, `.row` (or `.ok`, which it never can be).
    /// - Throws: The SQLite error if return code is not one of the aforementioned values.
    func step() throws -> Database.ReturnCode {
        guard
            let database = database,
            let statement = sqlite3_stmt
        else {
            throw Database.DatabaseError.notOpened
        }

        return try database.call { sqlite3_step(statement) }
    }

    /// Reset the values bound to this prepared statement.
    ///
    /// Used if you want to bind new values and perform the statement again without re-preparing it.
    ///
    /// - Throws: SQLite error.
    func reset() throws {
        guard let database = database,
            let statement = sqlite3_stmt else { throw Database.DatabaseError.notOpened }

        try database.call { sqlite3_reset(statement) }
    }

    /// Determines if the particular column value is `NULL` or not.
    ///
    /// - Parameter index: The column index number.
    func isNull(index: Int32) -> Bool {
        sqlite3_column_type(sqlite3_stmt, index) == SQLITE_NULL
    }

    /// Retrieve the value returned for a column of the particular `index`.
    ///
    /// - Parameters:
    ///    - type: The type to be returned for the column (e.g. `Int.self`).
    ///    - index: The zero-based column index number.
    /// - Returns: Returns the value found at the specified column index. If the value cannot be converted to that type, it will return `nil`.
    /// - Throws: The SQLite error if return code is not one of the aforementioned values.
    func column<T: DatabaseBindable>(_ type: T.Type, index: Int32) -> T? {
        T(from: self, index: index)
    }

    /// Retrieve the name of the column of the particular `index`.
    ///
    /// - Parameter index: The zero-based column index number.
    /// - Returns: The name of the column or `nil` if it couldn't determine the name.
    func columnName(index: Int32) -> String? {
        sqlite3_column_name(sqlite3_stmt, index)
            .flatMap { String(cString: $0) }
    }

    /// Retrieve the origin name of the column of the particular `index`.
    ///
    /// - Parameter index: The zero-based column index number.
    /// - Returns: The name of the column or `nil` if it couldn't determine the name.
    func columnOriginName(index: Int32) -> String? {
        sqlite3_column_origin_name(sqlite3_stmt, index)
            .flatMap { String(cString: $0) }
    }

    /// Retrieve the name of the table associated with the column of the particular `index`.
    ///
    /// - Parameter index: The zero-based column index number.
    /// - Returns: The name of the column or `nil` if it couldn't determine the name.
    func columnTableName(index: Int32) -> String? {
        sqlite3_column_table_name(sqlite3_stmt, index)
            .flatMap { String(cString: $0) }
    }

    /// Retrieve the name of the table associated with the column of the particular `index`.
    ///
    /// - Parameter index: The zero-based column index number.
    /// - Returns: The name of the column or `nil` if it couldn't determine the name.
    func columnDatabaseName(index: Int32) -> String? {
        sqlite3_column_database_name(sqlite3_stmt, index)
            .flatMap { String(cString: $0) }
    }
}

// MARK: - Data binding protocol

public protocol DatabaseBindable {
    /// Initializer used when returning value from result set of performed SQL `SELECT` statement.
    ///
    /// - Parameters:
    ///   - statement: The prepared and performed SQLite statement.
    ///   - index: The 0-based index for the column being returned.
    init?(from statement: Statement, index: Int32)

    /// When binding a value to a prepared (but not yet performed) SQL statement.
    ///
    /// - Parameters:
    ///   - statement: The prepared SQLite statement to be performed.
    ///   - offset: the 1-based index for the column being bound.
    /// - Returns: The SQLite return code.
    func bind(to statement: Statement, offset: Int32) -> Int32
}

// MARK: Specific type conformances

extension String: DatabaseBindable {
    public init?(from statement: Statement, index: Int32) {
        guard !statement.isNull(index: index), let pointer = sqlite3_column_text(statement.sqlite3_stmt, index) else { return nil }
        self = String(cString: pointer)
    }

    public func bind(to statement: Statement, offset: Int32) -> Int32 {
        sqlite3_bind_text(statement.sqlite3_stmt, offset, cString(using: .utf8), -1, SQLITE_TRANSIENT)
    }
}

extension Decimal: DatabaseBindable {
    public init?(from statement: Statement, index: Int32) {
        guard
            !statement.isNull(index: index),
            let string = String(from: statement, index: index),
            let value = Decimal(string: string, locale: Locale(identifier: "en_US_POSIX")) else { return nil }
        self = value
    }

    public func bind(to statement: Statement, offset: Int32) -> Int32 {
        var value = self
        let string = NSDecimalString(&value, Locale(identifier: "en_US_POSIX"))
        return sqlite3_bind_text(statement.sqlite3_stmt, offset, string.cString(using: .utf8), -1, SQLITE_TRANSIENT)
    }
}

extension IntegerLiteralType: DatabaseBindable {
    public init?(from statement: Statement, index: Int32) {
        guard !statement.isNull(index: index) else { return nil }
        let value = sqlite3_column_int64(statement.sqlite3_stmt, index)
        self = .init(value)
    }

    public func bind(to statement: Statement, offset: Int32) -> Int32 {
        sqlite3_bind_int64(statement.sqlite3_stmt, offset, Int64(self))
    }
}

extension BinaryFloatingPoint {
    public init?(from statement: Statement, index: Int32) {
        guard !statement.isNull(index: index) else { return nil }
        self = Self(sqlite3_column_double(statement.sqlite3_stmt, index))
    }

    public func bind(to statement: Statement, offset: Int32) -> Int32 {
        sqlite3_bind_double(statement.sqlite3_stmt, offset, Double(self))
    }
}

extension Data: DatabaseBindable {
    public init?(from statement: Statement, index: Int32) {
        guard !statement.isNull(index: index) else { return nil }

        let count = sqlite3_column_bytes(statement.sqlite3_stmt, index)
        if count == 0 { return nil }

        guard let bytes = sqlite3_column_blob(statement.sqlite3_stmt, index) else { return nil }
        self = Data(bytes: bytes, count: Int(count))
    }

    public func bind(to statement: Statement, offset: Int32) -> Int32 {
        withUnsafeBytes { pointer in
            let bytes = pointer.baseAddress
            return sqlite3_bind_blob(statement.sqlite3_stmt, offset, bytes, Int32(count), SQLITE_TRANSIENT)
        }
    }
}

extension Date: DatabaseBindable {
    public init?(from statement: Statement, index: Int32) {
        guard
            !statement.isNull(index: index),
            let pointer = sqlite3_column_text(statement.sqlite3_stmt, index) else { return nil }

        let string = String(cString: pointer)
        guard let date = Database.dateFormatter.date(from: string) else { return nil }

        self = date
    }

    public func bind(to statement: Statement, offset: Int32) -> Int32 {
        let string = Database.dateFormatter.string(from: self)
        return sqlite3_bind_text(statement.sqlite3_stmt, offset, string.cString(using: .utf8), -1, SQLITE_TRANSIENT)
    }
}

Now, that is my personal thin wrapper around the SQLite API, but there are lots of them out there and you probably want to find one that is publicly supported. Or roll your own. But I would advise abstracting the SQLite code away from your app-specific SQL.
Even if you do this (using my wrapper, your own, or some established third-party wrapper), I'd also abstract the “department” repository code out in its own controller. You do not want to entangle your model object and general controller code with any particular storage mechanism. You should be able to change your database API at a future date without impacting your app-specific logic.

When inserting into a database, we often would avoid using string interpolation, but rather bind values to ? placeholders in our SQL using sqlite3_bind_xxx(). Or, using the above SQLite wrapper:
do {
    let database = try openDatabase()
    try database.exec("CREATE TABLE IF NOT EXISTS department(id INTEGER PRIMARY KEY, name TEXT NOT NULL)")
    let statement = try database.prepare("INSERT OR REPLACE INTO department(id, name) VALUES (?, ?)")
    for (id, string) in [(5, "Bob's Department"), (6, "Susan's Department")] {
        try statement.bind([id, string])
        try statement.step()
        try statement.reset()
    }
} catch {
    print(error)
}

This gets us out of worrying about the presence of apostrophes or other SQLite reserved string literals in our SQL. In the case of this fixed list of departments, it is not much of an issue, but if you start inserting values supplied by the end user, making sure that values are inserted correctly with sqlite3_bind_xxx() functions and ? placeholders in your SQL.

Personally, I would not just open a database with sqlite3_open.

I would use sqlite3_open_v2 with the SQLITE_OPEN_READWRITE option (or the .readWrite option in my wrapper), but not the SQLITE_OPEN_CREATE option (or my .create option).
If open failed, then I would go through the creation process (creating tables, populating them, etc.; or frequently I would put an initialized database in my bundle, and if opening in app support directory failed, then I'd copy from the bundle to app support directory and then open again).

In your simple example, it is not terribly relevant, but as the app/db grows in complexity, you may want to avoid having to write a ton of “create and populate the database” code. It is convenient to have a saved “initial state” database ready and waiting in the bundle. It is your call, though, but just a recommendation.
Either way, it is often preferable to avoiding sqlite3_open, which silently creates a database if it is not there, but use sqlite3_open_v2 without the “create” option, and use the success or failure of that to determine whether you need to initialize the database or not.


Print total occurrences of a char in a string Scenario: Count the total number of times a char occurs in a word.

For instance, "aaabbcccdddaaaa" should print out "a7b2c3d3".

Can you please  critique my code?

import java.util.HashMap;
import java.util.Map;

public class Demo {

    public static void main(final String[] args) {
        final Demo d = new Demo();
        final String name = "aaabbcccdddaaaa";
        System.out.println(d.countNoOfInteger(name));
    }

    public String countNoOfInteger(final String str) {
        if (str.equals(null)) {
            throw new IllegalArgumentException();
        }
        if (str.isEmpty()) {
            return "";
        }

        final Map<Character, Integer> map = new HashMap<>();
        int count = 0;
        final char[] charArray = str.trim().toCharArray();

        for (final char element : charArray) {
            if (map.get(element) != null) {
                count = map.get(element);
                map.put(element, ++count);
            } else {
                count = 0;
                map.put(element, ++count);
            }
        }

        int total;
        char ch;
        final Map<Character, Boolean> visited = new HashMap<>();
        final StringBuilder sb = new StringBuilder();
        for (final char element : charArray) {
            if ((visited.get(element) == null)) {
                ch = element;
                sb.append(ch);
                total = map.get(element);
                sb.append(total);
                visited.put(element, true);
            }
        }
        return sb.toString();
    }
}

The use of Map is unnecessary overhead. You can leverage the fact that chars can be mapped as ints along with a simple array to solve this problem.

private static final int OFFSET = 'a';

public String countNoOfInteger(final String str) {
    final int[] counts = new int[26];  // or 'z' - 'a' + 1, if you prefer
    for (final char character : str.toCharArray()) {
        counts[character - OFFSET]++;
    }

    final StringBuilder output = new StringBuilder();
    for (int i = 0; i < counts.length; i++) {
        if (counts[i] == 0) {
            continue;
        }
        output.append((char) (i + OFFSET));
        output.append(counts[i]);
    }

    return output.toString();
}

Some notes:

OFFSET could probably have a better name. I'll leave that as an exercise for the reader.
Contrary to other respondents, I heartily encourage the use of final as a statement of intent.
In a "real" system, it would be preferable to separate the business logic (find the letter counts) from the display logic (print them to the screen). In such a system, your method would return the counts int[] (or Map) and the caller (main(), in this case) would be responsible for displaying it (everything after the first for loop).
Note that this solution will fail spectacularly for invalid input. If that's something you need to handle, add a check to the first loop to ensure that character is between offset and offset + counts.length.


Creating a CSV stream from an object I have this code that gets a CSV string from a list of objects where the first row in the string is the object's properties and the rows underneath are the properties values. I then create a MemoryStream of the string so it's about the same as reading from an actual .csv file into a Stream. Is there any way to cutdown on this code and perhaps do more with LINQ?
public class Lead
{
    public string FirstName { get; set; }
    public string MiddleName { get; set; }
    public string LastName { get; set; }
}
...

List<Lead> leads = new List<Lead>();
Lead lead1 = new Lead();
lead1.FirstName = "Joe";
lead1.MiddleName = "M";
lead1.LastName = "DiFabio";
leads.Add(lead1);

Lead lead2 = new Lead();
lead2.FirstName = "Dave";
lead2.MiddleName = "";
lead2.LastName = "Palacios";
leads.Add(lead2);

Lead lead3 = new Lead();
lead3.FirstName = "Andy";
lead3.MiddleName = "A";
lead3.LastName = "Nevers";
leads.Add(lead3);

List<string> headers = typeof(Lead).GetProperties().Select(x => x.Name).ToList();
string s = string.Join(",", headers);

foreach (Lead lead in leads)
{
    List<object> values = typeof(Lead).GetProperties().Select(prop => prop.GetValue(lead)).ToList();
    string ss = string.Join(",", values);
    s = $"{s}\n{ss}\n";
}

MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(s));

Let's do some performance tweaks.
I will measure the time simply with Stopwatch and first of all I'll cleanup your code to generate proper CSV (without reduntant empty lines as initial).
List<string> headers = typeof(Lead).GetProperties().Select(x => x.Name).ToList();
string s = string.Join(",", headers) + Environment.NewLine;

foreach (Lead lead in leads)
{
    List<object> values = typeof(Lead).GetProperties().Select(prop => prop.GetValue(lead)).ToList();
    string ss = string.Join(",", values);
    s += $"{ss}{Environment.NewLine}";
}

Environment.NewLine returns \r\n on Windows and \n on Linux.
Output will be
FirstName,MiddleName,LastName
Joe,M,DiFabio
Dave,,Palacios
Andy,A,Nevers

Looks like CSV :)
Then to measure performance I'll imagine that you have very large amount of data e.g. 30000 lines. I'll run the test in a loop of 10000 iterations.
TestOriginal
private static string TestOriginal(List<Lead> leads)
{
    List<string> headers = typeof(Lead).GetProperties().Select(x => x.Name).ToList();
    string s = string.Join(",", headers) + Environment.NewLine;

    for (int i = 0; i < 10000; i++)
        foreach (Lead lead in leads)
        {
            List<object> values = typeof(Lead).GetProperties().Select(prop => prop.GetValue(lead)).ToList();
            string ss = string.Join(",", values);
            s += $"{ss}{Environment.NewLine}";
        }
    return s;
}

Let's run.
Stopwatch sw = new Stopwatch();
sw.Start();
string s = TestOriginal(leads);
sw.Stop();
Console.WriteLine("Original: {0}ms", sw.ElapsedMilliseconds);

Original: 3162ms

Ugh. :)
Almost everyone knows that Reflection is slow. Let's somewhat optimize that.
ReflectionTweak
private static string ReflectionTweak(List<Lead> leads)
{
    PropertyInfo[] properties = typeof(Lead).GetProperties();
    List<string> headers = properties.Select(x => x.Name).ToList();
    string s = string.Join(",", headers) + Environment.NewLine;

    for (int i = 0; i < 10000; i++)
        foreach (Lead lead in leads)
        {
            List<object> values = properties.Select(prop => prop.GetValue(lead)).ToList();
            string ss = string.Join(",", values);
            s += $"{ss}{Environment.NewLine}";
        }
    return s;
}

Go go go
sw.Restart();
string sr = ReflectionTweak(leads);
sw.Stop();
Console.WriteLine("Reflection tweak: {0}ms, match: {1}", sw.ElapsedMilliseconds, s == sr);

Output with matching the string to original one
Reflection tweak: 3040ms, match: True

Better but still slow
One more idea - StringBuilder. Afaik, it's the fastest way to build a string (maybe except some unsafe/unmanaged code).
StringBuilderTweak
private static string StringBuilderTweak(List<Lead> leads)
{
    StringBuilder sb = new StringBuilder();
    PropertyInfo[] properties = typeof(Lead).GetProperties();
    sb.AppendLine(string.Join(",", properties.Select(x => x.Name)));

    for (int i = 0; i < 10000; i++)
        foreach (Lead lead in leads)
        {
            sb.AppendLine(string.Join(",", properties.Select(prop => prop.GetValue(lead))));
        }
    return sb.ToString();
}

Interesting...
sw.Restart();
string sb = StringBuilderTweak(leads);
sw.Stop();
Console.WriteLine("StringBuilder tweak: {0}ms, match: {1}", sw.ElapsedMilliseconds, s == sb);

Output
StringBuilder tweak: 24ms, match: True

WOW!!!
By the way, you may write the output directly to MemoryStream with StreamWriter.
StreamWriterTweak
private static MemoryStream StreamWriterTweak(List<Lead> leads)
{
    MemoryStream ms = new MemoryStream();
    // Encoding.UTF8 produces stream with BOM, new UTF8Encoding(false) - without BOM
    using (StreamWriter sw = new StreamWriter(ms, new UTF8Encoding(false), 8192, true))
    {
        PropertyInfo[] properties = typeof(Lead).GetProperties();
        sw.WriteLine(string.Join(",", properties.Select(x => x.Name)));

        for (int i = 0; i < 10000; i++)
            foreach (Lead lead in leads)
            {
                sw.WriteLine(string.Join(",", properties.Select(prop => prop.GetValue(lead))));
            }
    }
    ms.Position = 0;
    return ms;
}

Must be fast too...
sw.Restart();
MemoryStream stream = StreamWriterTweak(leads);
sw.Stop();
Console.WriteLine("StreamWriter tweak: {0}ms, match: {1}", sw.ElapsedMilliseconds, s == Encoding.UTF8.GetString(stream.ToArray()));

Output
StreamWriter tweak: 28ms, match: True

Yes!

The fastest
StringBuilder sb = new StringBuilder();
PropertyInfo[] properties = typeof(Lead).GetProperties();
sb.AppendLine(string.Join(",", properties.Select(x => x.Name)));

foreach (Lead lead in leads)
{
    sb.AppendLine(string.Join(",", properties.Select(prop => prop.GetValue(lead))));
}
string s = sb.ToString();

The whole code to reproduce and play more
internal class Program
{
    public static void Main(string[] args)
    {
        List<Lead> leads = new List<Lead>();
        Lead lead1 = new Lead();
        lead1.FirstName = "Joe";
        lead1.MiddleName = "M";
        lead1.LastName = "DiFabio";
        leads.Add(lead1);

        Lead lead2 = new Lead();
        lead2.FirstName = "Dave";
        lead2.MiddleName = "";
        lead2.LastName = "Palacios";
        leads.Add(lead2);

        Lead lead3 = new Lead();
        lead3.FirstName = "Andy";
        lead3.MiddleName = "A";
        lead3.LastName = "Nevers";
        leads.Add(lead3);

        Stopwatch sw = new Stopwatch();
        sw.Start();
        string s = TestOriginal(leads);
        sw.Stop();
        Console.WriteLine("Original: {0}ms", sw.ElapsedMilliseconds);
        sw.Restart();
        string sr = ReflectionTweak(leads);
        sw.Stop();
        Console.WriteLine("Reflection tweak: {0}ms, match: {1}", sw.ElapsedMilliseconds, s == sr);
        sw.Restart();
        string sb = StringBuilderTweak(leads);
        sw.Stop();
        Console.WriteLine("StringBuilder tweak: {0}ms, match: {1}", sw.ElapsedMilliseconds, s == sb);

        //MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(s));

        sw.Restart();
        MemoryStream stream = StreamWriterTweak(leads);
        sw.Stop();
        Console.WriteLine("StreamWriter tweak: {0}ms, match: {1}", sw.ElapsedMilliseconds, s == Encoding.UTF8.GetString(stream.ToArray()));

        Console.ReadKey();
    }

    private static string TestOriginal(List<Lead> leads)
    {
        List<string> headers = typeof(Lead).GetProperties().Select(x => x.Name).ToList();
        string s = string.Join(",", headers) + Environment.NewLine;

        for (int i = 0; i < 10000; i++)
            foreach (Lead lead in leads)
            {
                List<object> values = typeof(Lead).GetProperties().Select(prop => prop.GetValue(lead)).ToList();
                string ss = string.Join(",", values);
                s += $"{ss}{Environment.NewLine}";
            }
        return s;
    }

    private static string ReflectionTweak(List<Lead> leads)
    {
        PropertyInfo[] properties = typeof(Lead).GetProperties();
        List<string> headers = properties.Select(x => x.Name).ToList();
        string s = string.Join(",", headers) + Environment.NewLine;

        for (int i = 0; i < 10000; i++)
            foreach (Lead lead in leads)
            {
                List<object> values = properties.Select(prop => prop.GetValue(lead)).ToList();
                string ss = string.Join(",", values);
                s += $"{ss}{Environment.NewLine}";
            }
        return s;
    }

    private static string StringBuilderTweak(List<Lead> leads)
    {
        StringBuilder sb = new StringBuilder();
        PropertyInfo[] properties = typeof(Lead).GetProperties();
        sb.AppendLine(string.Join(",", properties.Select(x => x.Name)));

        for (int i = 0; i < 10000; i++)
            foreach (Lead lead in leads)
            {
                sb.AppendLine(string.Join(",", properties.Select(prop => prop.GetValue(lead))));
            }
        return sb.ToString();
    }

    private static MemoryStream StreamWriterTweak(List<Lead> leads)
    {
        MemoryStream ms = new MemoryStream();
        // Encoding.UTF8 produces stream with BOM, new UTF8Encoding(false) - without BOM
        using (StreamWriter sw = new StreamWriter(ms, new UTF8Encoding(false), 8192, true))
        {
            PropertyInfo[] properties = typeof(Lead).GetProperties();
            sw.WriteLine(string.Join(",", properties.Select(x => x.Name)));

            for (int i = 0; i < 10000; i++)
                foreach (Lead lead in leads)
                {
                    sw.WriteLine(string.Join(",", properties.Select(prop => prop.GetValue(lead))));
                }
        }
        ms.Position = 0;
        return ms;
    }

    public class Lead
    {
        public string FirstName { get; set; }
        public string MiddleName { get; set; }
        public string LastName { get; set; }
    }
}


Solution to 99 lisp problems: P08 with functional javascript Solution to 99 lisp problems: P08, with functional javascript

  If a list contains repeated elements they should be replaced with a single copy of the element. The order of the elements should not be changed.

* (compress '(a a a a b c c a a d e e e e))
  (A B C A D E)

Anyone want to review?

function cond( check, _then, _continuation ) {
  if(check) return _then( _continuation )
  else return _continuation()
}

function compress( list ) {
  return (function check( index, item, nextItem, compressed ) {
    return cond( item !== nextItem, function _then( continuation ) {
        compressed = compressed.concat([ item ])
        return continuation()
      },
    function _continueation() {
      return cond(!nextItem, function _then() {
          return compressed
      },
      function _continuation() {
          return check( index + 1, list[index + 1], list[index + 2], compressed )
      })
    })
  })( 0, list[0], list[1], [] )
}

ref:
http://www.ic.unicamp.br/~meidanis/courses/mc336/2006s2/funcional/L-99_Ninety-Nine_Lisp_Problems.html

I don't think you need so much complexity in javascript. It's not a fully functional language, don't try to make it so.

var arr = [
    'a', 'a', 'a', 'b', 'b', 'c', 'd', 'd', 'a', 'e', 'e', 'e'
];

arr = arr.filter( function( el, i ) {
    // return if the current isn't the same as the next
    return el !== arr[ i + 1 ];
});

console.log( arr ); // ["a", "b", "c", "d", "a", "e"]

This is 2 lines.


Memoization-based puzzle solution - sums in a triangle I am trying to solve a problem at Codechef. As I am new to programming, I am not familiar with dynamic programming. However, I do know the basics of recursion and memoization. Hence I implemented a solution to the above mentioned problem. The problem with my solution is that it exceeds the time limit given. As far as I can guess, the problem seems to be with my memoization logic. Please help me optimize the code.

#include <iostream>
#include <algorithm>
#include <vector>
#include <string>

using namespace std;

typedef vector<int> vector1D ;
typedef vector<vector1D > vector2D ; // Two Dimensional vector

int rownum;
int noOfCalls = 0;
vector2D a;
vector2D cache; // The cache to implement memoization

int solve (int i, int j)
{

    int t1,t2,total;
    if( i > rownum-1 ) {
        return 0;
    }
    else {
        if (cache[i][j] != 0 && ( i < 50) && ( j < 50)) { //for small values use memoization
            return cache[i][j];
        }
        t1 = solve(i+1,j);
        t2 = solve(i+1,j+1);
        total = max(t1,t2) + a[i][j];
        cache[i][j] = total;//store in cache
    }
    return total;
}
int main(int argc, char *argv[])
{
    int tries;
    cin>>tries;
    while(tries--) {
        cin>>rownum;
        int temp = rownum;
        for ( int i = 0 ; i < rownum ; i++) {
            a.push_back(vector1D(rownum,0));//initialize memory
        }
        for ( int j = 0; j < 10; j++) {
            cache.push_back(vector1D(10,0));//initialize cache
        }
        for ( int i = 0; i < rownum; i++) {
            for ( int j = 0 ; j <= i; j++) {
                cin>>a[i][j];
            }
        }
    cout<<solve(0,0)<<endl;//call the solving function
    cache.clear();
    }
    return 0;
}

General Comments.
I hate your use of global variables.
int rownum;
int noOfCalls = 0;
vector2D a;
vector2D cache; // The cache to implement memoization

I suppose it is an attempt at better performance.
The test for j here is redundant:
if (cache[i][j] != 0 && ( i < 50) && ( j < 50))

If i is smaller than 50 then j can not be greater than 50. If i is greater than 50 then the test will fail and there is no need to test what the value of j is.
Bugs
    for ( int i = 0 ; i < rownum ; i++) {
        a.push_back(vector1D(rownum,0));//initialize memory
    }

As you never clear a the size increases for every puzzle.
This can become quite expensive as a will continuously keep breaking its buffer and have to be re-allocated (copying all those internal arrays).
Speed
If you are solely going for speed then operator>> is about half the speed of scanf as it (operator>>) takes into account a lot of local stuff that is not done with scanf.
Your recursive algorithm is computing some spots multiple times.
// Your Triangle
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15

// Number of times each spot is hit with recursion
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1

As you can see some of the spots in the center bottom of the triangle are being hit many many times by recursion when you only want to hit each location once. Thus an iterative solution is probably better.
You are using a 2D array to represent the triangle which requires two de-references (which can be inefficient (but without measuring I am not convinced this is a major issue)). Rather than do that use a 1-D array given the number of rows n you can quickly compute the number of elements in the triangle as n*(n+1)/2 and thus re-size the array in one statement. Element access for a child of m is m+row(m)+0 and m+row(m)+1 (note the calculation of row(m) does not need to be done each time you can keep track of this as you increment m).


Return the first number found greater than the provided input number (13 digits) This script converts the numbers to be at least 13 characters long (for UNIX_MS strings). For use with timestamps, I'm having issues with it being very slow. I wanted an alternative to grepping for one specific UNIX_MS timestamp and not finding it and then having to grep multiple more times.

For the output I wanted the line number in the file (for slicing) as well as the original line (to confirm/inspect).

I'm very specifically looking for optimizations as I'd like this to be as-close-to-as-fast as grepping a single timestamp.

Usage: ./script.sh file UNIX_MS

#! /bin/bash
# return the first number found that's greater than the provided input number
res=
linenum=
count=0
returnline=             # hold onto the line for return
tocheck=$2
tocheck=$(($tocheck*(10**(( ${#tocheck} - 13) * -1))))
inseconds=$(($tocheck/1000))
date=$(date -r $inseconds)
echo "Looking for first timestamp -ge to $date.."
while read line;
  do
    count=$(($count + 1))
    timearray=$(grep -o -E "^(.*?)([0-9]{10,13})?" <<< $line)
    if [ -z "$timearray" ]; then
    echo "PROBLEM"
        echo "grep -o -E '^(.*?)([0-9]{10,13})?' <<< $line"
        exit 1
    fi
    timestamp=$(sed -Ee "s/[0-9]+\://" <<< $timearray)
# normalize timestamp to be 13 digits
    if [ "${#timestamp}" -lt "13" ]; then
        mult=$((10**(( ${#timestamp} - 13) * -1)))
        timestamp=$(($timestamp * $mult))
    fi
    echo "$timestamp >= $tocheck?"
    linenum=$([ "$timestamp" -ge "$tocheck" ] && echo $count)
    if [ -z "$linenum" ]; then
        :;
    else
        returnline=$line
    break;
    fi
done < $1
echo "$linenum:$returnline"
echo ""

I'm having issues with it being very slow.

What makes your script code slow is that you're reading in the file yourself with the while loop, and apply grep to each single input line, instead of passing grep the file itself and let it just do it's job.

No matter what you want to search for with grep, you should always first pass your input to it with a single call, and inspect the results afterwards.

  For the output I wanted the line number in the file (for slicing) as well as the original line (to confirm/inspect).

grep already has this feature intrinsically (at least as it says from this documentation):

    -n, --line-number
           Prefix each line of output with the line number within its input file.

you simply can do what you want using this option.

Thus you can get rid of your while loop and count variable to determine the line number yourself.


Programmatically getting the GUID of an application Intrigued by the events chronicled here (also here and here), I saw the inherent utility in having a program-specific GUID available. The SO answers that were correct seemed a bit tightly-coupled and verbose. So I set out to make my own for use. Looking for a critique on the idea itself as well as maintainability, performance, etc. Improvements welcome.

public static class AssemblyExtensions
{
    /// <summary>
    /// The <see cref="GuidAttribute"/> for the entry assembly lazily gotten as a <see cref="Guid"/> if it exists,
    /// <see cref="Guid.Empty"/> otherwise.
    /// </summary>
    private static readonly Lazy<Guid> _MyGuid = new Lazy<Guid>(() => Assembly.GetEntryAssembly().GetGuid());

    /// <summary>
    /// Lazily gets the <see cref="GuidAttribute"/> for the entry assembly as a <see cref="Guid"/> if it exists,
    /// <see cref="Guid.Empty"/> otherwise.
    /// </summary>
    /// <returns>The <see cref="GuidAttribute"/> for the entry assembly as a <see cref="Guid"/> if it exists,
    /// <see cref="Guid.Empty"/> otherwise.</returns>
    public static Guid GetMyGuid() => _MyGuid.Value;

    /// <summary>
    /// Gets the <see cref="GuidAttribute"/> for the given assembly as a <see cref="Guid"/> if it exists,
    /// <see cref="Guid.Empty"/> otherwise.
    /// </summary>
    /// <param name="assembly">The assembly.</param>
    /// <returns>The <see cref="GuidAttribute"/> for the given assembly as a <see cref="Guid"/> if it exists,
    /// <see cref="Guid.Empty"/> otherwise.</returns>
    public static Guid GetGuid(this Assembly assembly) => Guid.TryParse(
        ((GuidAttribute)assembly?.GetCustomAttributes(typeof(GuidAttribute), false).SingleOrDefault())?.Value,
        out Guid guid) ? guid : Guid.Empty;
}

Well, there isn't much to say here. But I still see some stuff I don't really like.

The implementations of Lazy<Guid> _MyGuid and Guid GetMyGuid() are quite simple and easy to read and understand. What bothers me here is that for the variable, and both methods the documentation is almost the same. But, at least for me, more critical is the documentation of Guid GetMyGuid() which states "Lazily gets ..." which is clearly an implementation detail which I wouldn't show.

The method Guid GetGuid() is another thing. IMO its very hard to read and understand by sprawling the Guid.TryParse() over 3 lines.

The change I will suggest is a little bit longer but its more readable, at least for me

public static Guid GetGuid(this Assembly assembly)
{
    var guidAttribute = (GuidAttribute)assembly?.GetCustomAttributes(typeof(GuidAttribute), false).SingleOrDefault();
    if(Guid.TryParse(guidAttribute?.Value, out Guid guid)) { return guid; }
    return Guid.Empty;
}

which could also be written like so

public static Guid GetGuid(this Assembly assembly)
{
    var guidAttribute = (GuidAttribute)assembly?.GetCustomAttributes(typeof(GuidAttribute), false).SingleOrDefault();
    Guid.TryParse(guidAttribute?.Value, out Guid guid); // If Guid.TryParse returns false the out Guid is Guid.Empty
    return guid;
}


Octave classdef enumeration workaround AFAIK Octave still does not support enumerations, so I've done my best to write a workaround. The question is if there is something missing in code below, or maybe something can be improved?

The reason for the enumConstructor method is that with Octave 4.2.0 I had errors when overloading the constructor.

classdef Enum < handle
    methods (Static = true)
        function [out] = test ()
            out = Enum.enumConstructor("test");
        endfunction
    endmethods

    # implementation

    properties (Access = private)
        value
    endproperties

    properties (Dependent = true)
        Value
    endproperties

    methods (Access = private, Static = true)
        function [this] = enumConstructor (in_val)
            this = Enum();
            this.value = in_val;
        endfunction
    endmethods

    methods
        function [out] = get.Value (this)
            out = this.value;
        endfunction

        function [out] = getValue (this)
            out = this.value;
        endfunction

        function [out] = eq (this, in_obj)
            out = false;
            if isa(in_obj, "Enum")
                out = strcmp(this.value, in_obj.value);
            endif
        endfunction
    endmethods
endclassdef

Edit:
I was a bit inspired with Java enumerations, rather than MATLAB.

When I run your code in Octave I see the following:

>> a=Enum.test()
a =

<object Enum>

Simply overloading the disp operator will solve this issue:

       function disp(this)
           disp(['Enum with value ',this.value])
        end

Now:

>> a=Enum.test()
a =

Enum with value test

You created a handle class to define your enumerator object. I don't see the benefit of using a handle class for this. Handle classes are meant as an interface to resources (a file, memory) that cannot (or should not) be copied. The handle class is always passed by reference, and the assignment operator causes the new variable to refer to the same object rather than making a copy.

This means that a=Enum; function(a) can modify a. Also, b=a; b.Value='foo' will change the value of a. This is highly uncommon and unexpected behavior in the MATLAB language. In general, MATLAB/Octave data is never a handle class, and I think an enumerator class should not be a handle class either.

I'm not sure what problem enumConstructor is avoiding. I'm running Octave 5.1 and don't have any issues overloading the constructor. A static function is a good workaround. I'm not sure why it is marked private though, since this makes it impossible to create an object of the class (I'm assuming the method test is just for show, not actually meant as part of the class).

Octave has a few additions to the MATLAB language that I feel are unfortunate. I always suggest to people not to use these additions. In particular, comments should start with %, not with #, and you should use end rather than endfunction, endif, etc. I don't feel that these additions improve the language sufficiently to break comparability between the two systems.

When you define a function with a single output argument, the square brackets around the output are superfluous. Thus, instead of writing

function [out] = getValue (this)

you can write

function out = getValue (this)

The use of a private property to hold data, and a public, dependent property to read and write from it, adds unnecessary complexity. It is possible to define accessor functions to protect public properties. For example, if the class only had a public value property, then the function set.value(this, value) can prevent the user from changing the value to an illegal value. A function value = get.value(this) likewise can control the reading of the property. The advantage is that one does not need to define the reading property if it's not necessary (there are default property reading and writing functions if one doesn't explicitly define them).

Putting all these things together, I would implement an enumerator class this way:

classdef Enum
   properties
      value
   end

   methods
      function this = Enum(value)
         if nargin > 0
            this.value = value;
         else
            this.value = 'none';
         end
      end

      function this = set.value(this, value)
         if ~ischar(value) || ~any(strcmp(value, {'foo','bar','baz','none'}))
            error(['Illegal value! ', value])
         end
         this.value = value;
      end

      function out = eq(this, other)
         out = strcmp(this.value, other.value);
      end

      function disp(this)
         disp(['Enum with value ',this.value])
      end
   end
end

You can use it as follows:

a = Enum;
b = Enum('foo');
c = Enum('foo');
>> a==b
ans = 0
>> c==b
ans = 1

Alternatively, if you don't want to allow the user to change the value of the enumerator (which, I gues, is not really necessary at all), then it is possible to keep the value property as read-only (SetAccess=private), or even completely private (Access=private), and remove the set.value function. With a private value property, the Enum class can still be copied, examined (using disp) and compared.


Poor man's lazy evaluation in Java 8 I have an class that cheaply imitates a lazy evaluation scheme. The class is for representing a file and additionally providing meta data on the file.  Some of the meta-data can be expensive to evaluate so I only want to evaluate it when requested, and only evaluate it once.

My implementation is such: All private members are stored in an EnumMap and each member is associated with a value in the enum Field.

private enum Field {
    FILE_CODE
    //, ...
};
private Map<Field, Optional> lazyAttributes = new EnumMap<Field, Optional>(Field.class);

The values in the EnumMap are Optionals in case evaluation failed (value not in database etc.)  Accessors methods get the member by providing the Field value associated with the member and a Supplier which will evaluate member if it hasn't yet been evaluated.

private <T> Optional<T> lazyLookup(Field field, Supplier<Optional<T>> answer) {
    if (lazyAttributes.containsKey(field)) { // field was already evaluated, get answer.
        return lazyAttributes.get(field);    // unchecked Optional to Optional<T>
    } else {                                 // field is unevaluated;
        Optional result = answer.get();      // evaluate,
        lazyAttributes.put(field, result);   // then store
        return result;                       // unchecked Optional to Optional<T>
    }
}

This is an example of what an accessor looks like.

public Optional<String> getFileCode() {
    return lazyLookup(Field.FILE_CODE,
            () -> FileCodeKeyWords.apply(getName())); // consider this expensive
}

I am concerned about the unchecked operations in lazyLookup and it seems to be an overly complicated setup.  I can provide the rest of the class if requested.

Your lazy method is not thread safe. If two threads check for the key at the same time they will both find it absent and both create a new object.

Wrapping your EnumMap in a ConcurrentMap will get around this.

private ConcurrentMap<Field, Optional> lazyThreadSafeAttributes = new ConcurrentHashMap(lazyAttributes);

private <T> Optional<T> lazyThreadSafeLookup(Field field, Supplier<Optional<T>> answer) {
    return lazyThreadSafeAttributes.computeIfAbsent(field, k -> answer.get());
}


Accessing SQL stored procedures The following code is from the DataAccess layer that calls the SQL stored procedure and returns the result set back to the calling code.

public class CoffeeDataAccess : ICoffeeDataAccess
    {
        private readonly Database coffeeDatabase;

        public CoffeeDataAccess(ICoffeeShopDatabaseFactory factory)
        {
            this.coffeeDatabase = factory.GetCoffeeDatabase();
        }

        public async Task<IEnumerable<Coffee>> GetAllAvailableCoffees()
        {
            IEnumerable<Coffee> coffees = await this.ExecuteCommandAsync("spGetAllCoffees");
            return coffees;
        }

        public async Task<IEnumerable<Coffee>> GetCofeesOfTheWeek()
        {
            IEnumerable<Coffee> coffees = await this.ExecuteCommandAsync("spGetCoffeesOfTheWeek");
            return coffees;
        }

        private async Task<IEnumerable<Coffee>> ExecuteCommandAsync(string spName)
        {
            IList<Coffee> coffees;

            using (DbCommand command = this.coffeeDatabase.GetStoredProcCommand("dbo" + spName))
            {

                Task<IDataReader> dataReaderTask =
                    Task<IDataReader>.Factory.FromAsync(this.coffeeDatabase.BeginExecuteReader, this.coffeeDatabase.EndExecuteReader, command, null);

                using (IDataReader reader = await dataReaderTask)
                {
                    coffees = new List<Coffee>();
                    while (reader.Read())
                    {
                        Coffee c = new Coffee();
                        c.Id = int.Parse(reader["ID"].ToString());
                        c.Name = reader["Name"].ToString();
                        c.ShortDesc = reader["ShortDesc"].ToString();
                        c.LongDesc = reader["LongDesc"].ToString();
                        c.Price = decimal.Parse(reader["Price"].ToString());
                        c.ImageUrl = reader["ImageUrl"].ToString();
                        c.ImageThumbnailUrl = reader["ImageThumbnailUrl"].ToString();
                        c.CategoryId = int.Parse(reader["CategoryId"].ToString());
                        coffees.Add(c);
                    }
                }
            }

            return coffees;
        }

    }

The CoffeeDataAccess object is newly instantiated every time when a client code asks for it from the IoC container (registered as Trasient in ASP.NET Core - startup class). Is the method name ExecuteCommandAsync thread safe or not?

I think it is because each time a new instance of the CoffeeDataAccessclass is created but I'm not sure.

Haven't tested the code, but the code should be thread safe! All ExecCommandAsync methods are called from within asynchronous functions.


Object-oriented purchase data structure I wrote a code where customer can buy an item according to customer balance, price and quantity of item to be bought. Here is the code:

#include "bits/stdc++.h"
using namespace std;

class Item{
private:
string itemName;
string itemidNo;
int itemQuantity;
double itemPrice;
public:
Item(){
    itemPrice = 500;
    itemQuantity = 1;
}
//getters and setters
void setName(string name){itemName = name;}
void setId(string id){itemidNo = id;}
void setQuantity(int quantity){itemQuantity = quantity;}
void setPrice(double price){itemPrice = price;}

string getName(){return itemName;}
string getId(){return itemidNo;}
int getQuantity(){return itemQuantity;}
double getPrice(){return itemPrice;}

};

class customer {
private:
string Custname;
string CustidNo;
double Custbalance;
Item Custitem;
public:
customer(){
    Custbalance = 5000;
}
//getters and setters
void setName(string name){Custname = name;}
void setidNo(string id){CustidNo = id;}
void setbalance(double balance){Custbalance = balance;}

string getName(){return Custname;}
string getidNo(){return CustidNo;}
double getbalance(){return Custbalance;}

void print(){
    cout << Custitem.getName() << " " << Custitem.getId() << " " << Custitem.getQuantity() << " " << Custitem.getPrice() << "\n";
    Custbalance -= Custitem.getQuantity()*Custitem.getPrice();
    cout << Custbalance << "\n";
}

void buyItem(Item item){
    if(Custbalance < (item.getQuantity()*item.getPrice())){
        cout << "Insufficient Balance for " << item.getName() << "\n";
        return ;
    }
    if(item.getQuantity() < 1){
        cout << "order not valid";
        return;
    }
    Custitem = item;
    print();
}
};

int main(int argc, char const *argv[])
{
customer harsh;
harsh.setName("harsh");
harsh.setidNo("23");

Item item1;
item1.setName("mobile");
item1.setId("44");

harsh.buyItem(item1);

Item item2;
item2.setName("speakers");
item2.setId("F&D");
item2.setQuantity(2);
item2.setPrice(3000);

harsh.buyItem(item2);

return 0;
}

I am a bit confused as I think there is too much redundancy in my code, such as the getters and setters.  How can I make my code more object-oriented?

Headers and namespaces
#include "bits/stdc++.h"

That's not a standard C++ header; prefer to use standard headers so that others can use your code.
using namespace std;

Bringing all names in from a namespace is problematic; namespace std particularly so. See Why is “using namespace std” considered bad practice?.
Naming
Choose a consistent naming convention and stick to it.  A common one that's closest to the majority of your code is to use PascalCase for types, camelCase for members and snake_case for variables.
Class Base
A default-constructed Base will have default-constructed Id and Name members.  It probably makes no sense to default-construct; I think it's better to explicitly declare a constructor:
public:
    Base(std::string id, std::string name)
      : id(std::move(id)), name(std::move(name))
    {}

Once initialized, there should be no reason to change the name or id, so we can remove the setters.  The accessors can be made const, so we can call them on instances of const Base:
    std::string getName() const { return name; }
    std::string getId() const { return id; }

Class Item
This seems mis-named - it's more like an "order line" that specifies how many items and their price.  Again, a default constructor seems wrong, although defaulting the quantity to 1 makes sense:
public:
    Item(std::string id, std::string name, double price, int quantity = 1)
      : Base(std::move(id), std::move(name)),
        itemPrice(price),
        itemQuantity(quantity)
    {
        if (itemQuantity <= 0)
            throw new std::domain_error("negative quantity");
        if (itemPrice <= 0)
            throw new std::domain_error("negative price");
    }

Whether it's reasonably to modify the price and quantity after construction really depends on your application, so I can't comment on that, but the getters should both be marked const, like the ones for id and name.
Also, I'll add the standard warning that floating-point is usually a poor choice for financial accounting - you'll avoid numeric rounding if you choose instead to represent currency amounts in integer values of the smallest denomination.
Class customer
Although customers may have names and identifiers, does that really make them the same kind of thing as items?  Unless you have a use case where you may want to use them interchangeably, public inheritance isn't really what you need here.  It's a common trap in OO design to assume that because two things are made from similar pieces that they must be similar things.  In some cases, it really is mere coincidence.  By way of analogy, chairs and dogs are both quadrupeds, but blindly choosing to treat them alike is a mistake that could turn around and bite you.
It is extremely kind of you to credit all your new customers with 5000 currency units in their accounts - but it might not be good business sense (even if they are Zimbabwean Third Dollars).  I recommend 0. as a more sensible default.
If the customer object is intended to be an autonomous object, it should be responsible for crediting and debiting the account, rather than setting the amount; I'd expect something more like:
void deposit(Currency amount)
{
    balance += amount;
}
void withdraw(Currency amount)
{
    balance -= amount;
}
Currency balance() const { return amount; }

(Real implementations usually involve some locking, so that concurrent operations don't interfere with each other, but that's a whole review in itself)
Why can a customer buy only one Item?  Usually, an order is composed of several items (each with a quantity) and refers to a customer (who may at a later date order more items - it's bad business to restrict them from doing that).
Something that looks really strange is this:
void print(){
    cout << Custitem.getName() << " " << Custitem.getId() << " " << Custitem.getQuantity() << " " << Custitem.getPrice() << "\n";
    Custbalance -= Custitem.getQuantity()*Custitem.getPrice();
    cout << Custbalance << "\n";
}

Why does the customer have to pay each time you print their order?
Usually, print() would look something like
std::ostream& print(std::ostream& o) const
{
    return o
      << Custitem.getName()
      << " " << Custitem.getId()
      << " " << Custitem.getQuantity()
      << " " << Custitem.getPrice() << "\n"
      << Custbalance << "\n";
}

and the debiting of the account would be a separate (non-const) operation.


Doctrine/Symfony WHERE clause for reports I'm trying to generate a report from two doctrine entities.

The fields to filter the report are optional. This is the code I've got now and it looks really bad to me. How can I improve this?

public function filter($accountNumber, $companyName, $branchName, $branchManager)
{
    $em = $this->managerRegistry->getManager();
    $whereClause = 'WHERE ';

    if (!empty($accountNumber)) {
        $whereClause .= ' u.accountNumber = :acc_number';
    }
    if (!empty($companyName)) {
        $whereClause .= ' AND um.companyName = :company_name';
    }
    if (!empty($branchName)) {
        $whereClause .= ' AND um.branchName = :branch_name';
    }
    if (!empty($branchManager)) {
        $whereClause .= ' AND um.branchAccountManager = :branch_manager';
    }

    $query = $em->createQuery(
        'SELECT u FROM CarbonUserBundle:User u
        JOIN CarbonUserBundle:UserMeta um WITh u.meta=um.id
       ' . $whereClause
    );

    if (!empty($accountNumber)) {
        $query->setParameter('acc_number', $accountNumber);
    }
    if (!empty($companyName)) {
        $query->setParameter('company_name', $companyName);
    }
    if (!empty($branchName)) {
        $query->setParameter('branch_name', $branchName);
    }
    if (!empty($branchManager)) {
        $query->setParameter('branch_manager', $branchManager);
    }

    return $query->getResult();
}

I would suggest using the QueryBuilder

$em = $this->managerRegistry->getManager();
$qb = $em->createQueryBuilder()
    ->select('u')
    ->from(User::class, 'u')
    ->join('u.meta', 'um'); // doctrine generates the join condition automatically

if (!empty($accountNumber)) {
    $qb
        ->andWhere('u.accountNumber = :acc_number')
        ->setParameter('acc_number', $accountNumber)
}
if (!empty($companyName)) {
    $qb
        ->andWhere('u.companyName = :company_name')
        ->setParameter('company_name', $companyName)
}

// and so on...

return $qb->getQuery()->getResult();


Simplification of loop in Ruby I'm still pretty new to Ruby, and am really enjoying the language. I came across this method in my code base and realized that it could be cleaned up:

def friend_all_followers(friends)
  client.followers.each do |follower|
    if not friends.include?(follower.screen_name)
      friend = Friend.new(:screen_name => follower.screen_name)
      client.friendship_create(friend.screen_name, true)
      friend.save
    end
  end
end

So I took the above and changed it to this:

def friend_all_followers(friends)
  followers = client.followers.reject { |f| friends.include?(f) }
  followers.each do |follower|
    friend = Friend.new(:screen_name => follower.screen_name)
    client.friendship_create(friend.screen_name, true)
    friend.save
  end
end

One less level of nesting, and cleaner than the first method. But I look at this method and can't help but think there's still more to be done. Any ideas?

As some background Friend is an ActiveRecord class, client is a wrapper around a Twitter API, client.followers returns an array of follower objects - the objects I believe are just hashes, but I'm not 100% certain at the moment - and friends is a string array of screen_names.

You can replace

friend = Friend.new(:screen_name => follower.screen_name)
client.friendship_create(friend.screen_name, true)
friend.save

With

friend = Friend.create(:screen_name => follower.screen_name)
client.friendship_create(friend.screen_name, true)

I'd also suggest wrapping creation of friend in separate class method:

class Friend < ActiveRecord::Base
  def create_with_follower(follower = nil)
    return unless follower
    create :screen_name => follower.screen_name
  end
end

Then code becomes like this:

friend = Friend.create_with_follower follower
client.friendship_create(friend.screen_name, true)

I'd probably hide the friendship_create method call somewhere too. Not sure what it does though. Is it separate API call?

update

Now whole code becomes like this:

def friend_all_followers(friends)
  followers = client.followers.reject { |f| friends.include?(f) }
  followers.each do |follower|
    friend = Friend.create_with_follower follower
    client.friendship_create(friend.screen_name, true)
  end
end

Now you can do some readable operation on array. Something like this:

def friend_all_followers(friends)
  (client.followers - friends).each do |follower|
    friend = Friend.create_with_follower follower
    client.friendship_create(friend.screen_name, true)
  end
end


Utility functions for processing tweets or texts I have 4 functions that process texts or tweepy.models.Status object (this object stores text information, author information, retweets & likes information of a specific tweet).

The first function is filter_unique, which is used to exclude duplicate tweets from a list of tweets. The result is a generator.

The function clean_text, is used to remove punctuations, undefined characters, and whitespaces from a string.

The function split_texts has two inputs, the list of tweets/strings and the mode of the splits (naive=True means it only use text.split(), if set to False then it will clean the text first before splitting)

The function total_rts calculates the total number of retweets. string_inclusion='word' means that it will calculate the total retweets of tweets that contain 'word'.

Question: How to make this module more efficient, and perhaps advanced?

We can use the sample tweets testfile.npy which contains objects tweepy.models.Status.

import tweepy
import string

def filter_unique(tweets):

    uniques = set()

    for tweet in tweets:

        if not isinstance(tweet, tweepy.Status):
            raise TypeError('Each element must be of tweepy.Status object')

        try:
            tweet = tweet.retweeted_status
        except:
            pass

        if tweet.id not in uniques:

            uniques.add(tweet.id)

            yield tweet

def clean_text(text):

    punct = string.punctuation
    printable = string.printable
    whitespace = string.whitespace

    table = text.maketrans({key: None for key in printable})
    undef = set(text.translate(table))

    table = text.maketrans({key: None for key in undef})
    removed_undef = text.translate(table)

    table = text.maketrans({key: None for key in punct})
    cleaned = removed_undef.translate(table)

    table = text.maketrans({key: ' ' for key in whitespace})
    cleaned = cleaned.translate(table)

    return cleaned

def split_texts(texts, naive):

    if naive:
        for text in texts:
            yield text.split()
    else:
        for text in texts:
            yield clean_text(text).split()

def total_rts(tweets, string_inclusion = False, naive = True):

    result = 0

    if not string_inclusion :

        result = sum([tweet.retweet_count for tweet in tweets]);

    else:

        if naive:
            try:
                result = sum([tweet.retweet_count for tweet in tweets if string_inclusion in tweet.full_text.split()])
            except:
                result = sum([tweet.retweet_count for tweet in tweets if string_inclusion in tweet.text.split()])
        else:
            try:
                result = sum([tweet.retweet_count for tweet in tweets if string_inclusion in clean_text(tweet.full_text).split()])
            except:
                result = sum([tweet.retweet_count for tweet in tweets if string_inclusion in clean_text(tweet.text).split()])

    return result

A few obligatory PEP-8 rules:

Imports should be grouped in the following order:

standard library imports
related third party imports
local application/library specific imports

Use blank lines in functions, sparingly, to indicate logical sections.
Two blank lines between the import statements and other code.
Two blank lines between each function.
Don't use spaces around the = sign when used to indicate a keyword argument or a default parameter value.

If this is written for python-3.x, I'd also suggest going for Type Hinting.

In the split_texts definition, I'd suggest having naive=False as the default (or naive=True) depending on the more obvious choice of the two.

In the function total_rts (could be renamed to total_retweets), you can avoid one entire level of nesting by returning early in the first if not string_inclusion clause.

The function clean_text makes several transition tables, which could be extracted out of the function and made a constant. More importantly, what I understood from the definition, I think you're (in order):

cleaning the text of all printable characters
cleaning the text of all characters leftover from step 1
cleaning all punctuation from result of step 2
replacing all kinds of whitespace characters with a single ' ' in the result of step 3.

You can define global transition tables as follows:

WHITESPACE = ' ' * len(string.whitespace)
CLEAN_TRANSLATION = str.maketrans(string.whitespace, WHITESPACE, string.punctuation)

Alternatively, you can take the CLEAN_TRANSLATION inside the clean_text function and use the undefined non-printable characters in concatenation to string.punctuation. So, the function becomes:

def clean_text(text):
    undefined_chars = text.translate(
        str.maketrans({c: None for c in string.printable}))
    cleanup_translation = str.maketrans(
        string.whitespace, WHITESPACE, string.punctuation + undefined_chars)
    return text.translate(cleanup_translation)

And, most importantly, the description for each function that you've provided in the question, could be converted to a docstring for each of them.


Celebration Party Problem - Algorithm I solved the following problem:

  Let's consider the following situation. You've invited a lot of children to a celebration party, and you want to entertain them and also teach them something in the process. You are going to hire a few teachers and divide the children into groups and assign a teacher to each of the groups. This teacher will work with this group through the whole party.

  But you know that for a teacher to work with a group of children efficiently children of that group should be of relatively the same age. More specifically age of any two children in the same group should differ by at most, one year.

  Also, you want to minimize the number of groups. Because you want to hire fewer teachers, and spend the money on presents and other kinds of entertainment for the children. So, you need to divide children into the minimum possible number of groups. Such that the age of any two children in any group differs by at most one year.

import java.io.*;
import java.util.*;

public class ChildrenGroup{

  static int getGroups(float[] children) {

    int lastChild = children.length;
    int currentChild=1;
    int startingPoint=0;
    int groups=0;

    while(currentChild<lastChild){

        if(children[currentChild]-children[startingPoint]>1){
            startingPoint=currentChild ;
            groups++;
        }

        if(currentChild==lastChild-1){
            groups++;
        }
        currentChild++;
    }

    return groups;
  }

  public static void main(String[] args) {

    Scanner in = new Scanner(System.in);

    int n = in.nextInt();
    float[] children = new float[n];

    for (int i = 0; i < n; i++) {
        children[i] = in.nextFloat();
    }

    System.out.println(getGroups(children));

  }
}

Sample input 1:

7
2.5 3.2 3.5 4.0 4.8 5.2 6.0

Output 1:

3

Sample input 2:

3
2.1 4.5 6.7

Output 2:

3

What's your thoughts on the solution?

Your algorithm is correct and will be very efficient. Note that it assumes that the array of float values is sorted ascendingly. To make sure of that, you could explicitely sort the array before entering the while loop, or document that the method must take a pre-sorted array.

The comments I have are concerning the presentation of the code itself:

Consider adding white-spaces before and after each parentheses and curly braces. For example

while(currentChild<lastChild){

could be read easier with

while (currentChild < lastChild) {

where extra spaces have been added.
You have added a lot of vertical spaces. Adding a line break with an empty line can indeed help readability but having 2 empty lines is too much: this is what you have after your while loop and between the two if statements. Consider having only a single empty line where you think it adds to clarity.
Be consistent with your usage of white-spaces. Statements like

startingPoint=currentChild ;

are a bit weird. There is a space before the semi-colon and no spaces around the = operator.

An IDE can usually reformat your code automatically. For example, taking directly your code into Eclipse and reformatting it by selecting it and hitting Ctrl+Shift+F let me to

static int getGroups(float[] children) {

    int lastChild = children.length;
    int currentChild = 1;
    int startingPoint = 0;
    int groups = 0;

    while (currentChild < lastChild) {

        if (children[currentChild] - children[startingPoint] > 1) {
            startingPoint = currentChild;
            groups++;
        }

        if (currentChild == lastChild - 1) {
            groups++;
        }
        currentChild++;
    }

    return groups;
}

Also, I noticed that you used wildcard import statement:

import java.io.*;
import java.util.*;

This is generally not a good practice. You want to import the specific classes with which you are interacting. In this case, it is actually not a lot, you just one import statement:

import java.util.Scanner;

There is no need for any class under java.io.


Binary Min Heap data structure implementation After reading about heap I tried to implement the heap. Below is my code along with test. Any feedback with respect to correctness, performance is welcome.

import java.util.Arrays;

public class BinaryHeap2 {
    private int[] heap;
    private int size;
    private int capacity;

    public BinaryHeap2(){
        capacity = 100;
        size = 0;
        heap = new int[capacity];
    }

    public BinaryHeap2(int capacity){
        this.capacity = capacity;
        size = 0;
        heap = new int[this.capacity];
    }

    public void offer(int i){

        if(size>=capacity){
            capacity = capacity*2;
            int[] tmp = new int[capacity];
            System.arraycopy(heap, 0, tmp, 0, heap.length);
            heap = tmp;
        }

        heap[size++] = i;

        heapifyUp(size-1);

    }

    private void heapifyUp(int position){
        int parent = (position-1)/2;
        while(heap[parent]>heap[position]){
            swap(parent,position);
            position = parent;
            parent = (position-1)/2;
        }
    }

    private void swap(int i, int j){
        int t = heap[i];
        heap[i] = heap[j];
        heap[j] = t;
    }

    public int peek(){
        return heap[0];
    }

    public int poll(){
        int min = heap[0];
        heap[0] = heap[size-1];
        size--;
        if(size>1)
            heapifyDown(0);
        return min;
    }

    public int getSize(){
        return size;
    }

    private void heapifyDown(int i) {
        int leftChild = 2*i+1;
        int rightChild = 2*i+2;
        int childToSwap = heap[leftChild]<heap[rightChild]?leftChild:rightChild;
        while(heap[i]> heap[childToSwap]){
            swap(i,childToSwap);
            i = childToSwap;
            leftChild = 2*i+1;
            rightChild = 2*i+2;
            if(rightChild>=size||leftChild>=size)break;
            childToSwap = heap[leftChild]<heap[rightChild]?leftChild:rightChild;
        }

    }

    public void display(){
        System.out.println(Arrays.toString(heap));
    }

}

Below is the Unit test

import static org.junit.Assert.assertEquals;

import org.junit.Before;
import org.junit.Test;

public class BinaryHeap2Test {

    BinaryHeap2 heap;
    @Before
    public void setUp(){
        heap = new BinaryHeap2(3);
    }

    @Test
    public void test() {
        heap.offer(7);
        heap.offer(6);
        heap.offer(3);
        heap.offer(2);
        heap.offer(1);
        heap.offer(5);
        heap.offer(4);
        heap.offer(3);
        heap.offer(2);
        heap.display();
        assertEquals(1, heap.peek());
        assertEquals(heap.poll(), 1);
        assertEquals(heap.poll(), 2);
        assertEquals(heap.poll(), 2);
        assertEquals(heap.poll(), 3);
        assertEquals(heap.poll(), 3);
        assertEquals(heap.poll(), 4);
        heap.offer(1);
        heap.display();
        assertEquals(heap.poll(), 1);
        assertEquals(heap.poll(), 5);
        assertEquals(heap.poll(), 6);
        assertEquals(heap.poll(), 7);
        heap.display();

    }

    @Test
    public void test2(){
        heap.offer(300);
        heap.offer(200);
        heap.offer(100);

        assertEquals(100, heap.poll());
        heap.display();
        assertEquals(200, heap.poll());
        heap.display();
        assertEquals(300, heap.poll());
        heap.display();
        heap.offer(2);
        assertEquals(2, heap.peek());
        heap.offer(100);
        heap.offer(1);
        heap.offer(5);
        assertEquals(1, heap.poll());
        assertEquals(2, heap.poll());
        assertEquals(5, heap.poll());
        assertEquals(100, heap.poll());
    }

}

You have duplicated code in your constructors, the default constructor should call the other one with capacity.
Maybe make the capacity = 100 constant and name it something like DEFAULT_INITIAL_CAPACITY.
Your tests are not named. After reading a name of a test (or anything you name in general) you should have some sort of understanding, what the test tests.
You test too many things at once. One test should test one aspect of your code. You call offer n times and assert the peek value, after that you poll and offer and assert the poll value. Better would be to split it and test the poll and offer mechanism seperately. So actually the first part could fail, while the second one would be okay, or the other way round. So you are never really sure, what really failed. You also don't have to call offer n times, it shouldn't make any difference, does it? If it would, it should be a separate test anyway.
test2() isn't meaningful, either, I mean, what's the difference between the first test, except larger numbers? I'm sure you want to test the resize of the inner array, but how does one know? I'd do something like this:

@Test
public void exceedingHeapsizeCapacityIncreaseHeapCapacity() {
    int heapCapacity = 1;
    BinaryHeap2 heap = new BinaryHeap2(1);

    heap.offer(1);
    heap.offer(1);

    // no assertion, if resize wouldn't work, 2nd call would throw Exception... maybe a method to provide the actual capacity wouldn't be _that_ bad
}

To call 'display' in a test doesn't make sense either, if you have thousands of test in an application, you just fill the console with crap and makes actual troubleshooting much harder, better to have debug or trace debugging within the class under test and activate it, when you have to troubleshoot your test or something in production.
The type has a "display" method. Usually you have an own 'View' Type. You just pass your Heap and tell the View "display your contents" (think as if you want to change the 'presentation layer', like, if you want to display it in a browser as html, the type must not write html itself)
Try to avoid naming variables like i and j. If you read the method swap by itself, you do not know, what i and j means, a method shall be as self explanatory as possible. To really understand it, you have to check, who actually calls this method.
The intention of heapifyDown is not very clear. I've read it three times and still don't understand it - goal should be, that you can read it once and understand it, shouldn't it? I think that's possible in that case. The break in the while loop hurts, can't you do that within the while condition, too?
The ordering of of public/private methods is always a discussion. It usually is public to private. But I also like to order it as how the code is called. Like you have public void offer, and you call heapifyUp, which is just under it, which I actually really like. But: The getSize() can moved beneath heapifyDown.


Abbreviation of names I have a few confusions about writing Java code, and I need some clarifications:

import java.util.Scanner;

public class NameAbbreviation {

private static String  fullName;
private static Scanner nameInput;

public NameAbbreviation(String name) {
    NameAbbreviation.fullName = name;
}

public char getInitialLetterOfFirstName() {
    char initialletterOfFirstName = fullName.charAt(0);
    //System.out.println(initialletterOfFirstName);
    return initialletterOfFirstName;
}

public String getInitialLetterOfLastName() {
    int space = fullName.lastIndexOf(" ");
    String initialletterOfLastName = fullName.substring(space + 1,
            space + 2);
    //System.out.println(initialletterOfLastName);
    return initialletterOfLastName;
}

public static void main(String[] args) {

    nameInput = new Scanner(System.in);
    String name = nameInput.nextLine();
    NameAbbreviation na = new NameAbbreviation(name);
    System.out.println(na.getInitialLetterOfFirstName() + " "
            + na.getInitialLetterOfLastName());

     }
}

I have class variables fullName and nameInput. If I make nameInput local, it shows: Resource leak: nameInput is never closed. So I just follow the Eclipse suggestion and make it a field. What should I need to follow?
I have 2 methods - getInitialLetterOfFirstName() and getInitialLetterOfLastName(), the return types of which are char and String respectively. I could eventually make the return type as void. What are the advantages or disadvantages if I have void or specific return type? As both the way of code works, what do I need to follow or does it depend on how I am writing the code?
Both the methods getInitialLetterOfFirstName()and getInitialLetterOfLastName() don't have any parameters/arguments. I could eventually create the method with argument like:

getInitialLetterOfFirstName(String name) {
        this.fullName = name;    .......}

getInitialLetterOfLastName(String name) {
        this.fullName = name;    .......}

If I create the methods with arguments, I need to pass the value during the instantiation of the object. So I avoid it here, and prefer to have only once to pass the argument value.

Is there any rule  to follow, like to make the methods with parameters or not, as here both are possible with or without argument methods?

What do I need to follow as good practice, code performance issues, etc.?

Objects
Java is, by definition, an Object-oriented language... but, that does not mean every program needs to follow those rules. This is an example program where there are no new objects that are relevant, and as a result, there's no real need to go beyond just procedural routines. You have Scanner, and String, and those are objects enough.
Consequently, you can do everything as static methods/functions, and no need to create anything using new.
Functions
Good code practices recommend a number of aspects to functions that would help here.
First up, functions should do one thing, and do that one thing well. By making functions simple, it makes it easier to reuse them, and combine them. Consider a simple function that gets the initial letter of any String:
public static String getInitial(String phrase) {
    return phrase.substring(0, 1);
}

That function has a useful name, I have made it static because it does not rely on any instance data/fields, and it is a simple stateless function.
Now, we can reuse that in the main method. All we need to do is separate the first and last names..... and a simple enough way to do that is your lastIndexOf(" ") call.
int lastspace = name.lastIndexOf(" ");
System.out.println(getInitial(name) + " " + getInitial(name.substring(lastspace + 1));

Now, there are a number of defensive problems in that code - what if the user does not input any space in their name, or the name is an empty string?
These things need to be fixed, and it makes the code more complicated. A common way to do these things is to split the data on multiple spaces, and output multiple initials, or an empty string if there are none....