C++ Shared_Ptr implementation I reinvented a c++ smart pointer, shared_ptr to be precise. It is meant for practice purpose and does not attempt to replace the standard implementation. To the best of my knowledge, the code works as expected. I decided to skip the custom deleter because I want to keep things simple for now. I would love feedbacks and constructive criticism.
Here is the implementation
shared.hpp
#ifndef SHARED_PTR_H_
#define SHARED_PTR_H_

#include <cstddef>

namespace smp
{
    template<typename T>
    class shared_ptr
    {
        public:
            explicit shared_ptr(T* ptr = nullptr);
            ~shared_ptr();
            shared_ptr(shared_ptr& ptr);
            shared_ptr operator=(shared_ptr& ptr);
            shared_ptr(shared_ptr&& ptr) noexcept;
            shared_ptr operator=(shared_ptr&& ptr) noexcept;

            T operator*();
            T* operator->() const;

            size_t use_count() const;
            void reset();
            T* get();
            bool unique() const;
            operator bool() const;

        private:
            T* obj_ptr;
            struct RefCount {
                size_t use_count_;
                T* object_;
            }* ref_cnt;

    };

    template<typename T>
    shared_ptr<T> make_shared(T object);
}

#endif /* SHARED_PTR_H_ */

shared.cpp
#include "shared.hpp"

#include <algorithm>
#include <iostream>

namespace smp
{
    template<typename T>
    shared_ptr<T>::shared_ptr(T* ptr)
        : obj_ptr{ptr}, ref_cnt{new RefCount()}
    {
        ref_cnt->object_ = ptr;
        if(ptr)
            ++ref_cnt->use_count_;
    }

    template<typename T>
    shared_ptr<T>::shared_ptr(shared_ptr& ptr)
        : ref_cnt{new RefCount()}
    {
        obj_ptr = ptr.obj_ptr;
        ref_cnt = ptr.ref_cnt;

        ++ref_cnt->use_count_;
    }

    template<typename T>
    shared_ptr<T> shared_ptr<T>::operator=(shared_ptr& ptr)
    {
        obj_ptr = ptr.obj_ptr;
        ref_cnt = ptr.ref_cnt;
        ++ref_cnt->use_count_;

        return *this;
    }

    template<typename T>
    shared_ptr<T>::shared_ptr(shared_ptr&& ptr) noexcept
        : obj_ptr{nullptr}, ref_cnt{new RefCount()}
    {
        obj_ptr = std::move(ptr.obj_ptr);
        ref_cnt = std::move(ptr.ref_cnt);

        ptr.reset();
    }

    template<typename T>
    shared_ptr<T> shared_ptr<T>::operator=(shared_ptr&& ptr) noexcept
    {
        if(obj_ptr)
            reset();
        obj_ptr = std::move(ptr.obj_ptr);
        ref_cnt = std::move(ptr.ref_cnt);

        ptr.obj_ptr = nullptr;

        return *this;
    }

    template<typename T>
    shared_ptr<T> make_shared(T object)
    {
        return shared_ptr<T>(new T{object});
    }

    template<typename T>
    T shared_ptr<T>::operator*()
    {
        return *obj_ptr;
    }

    template<typename T>
    T* shared_ptr<T>::operator->() const
    {
        return &*obj_ptr;
    }

    template<typename T>
    size_t shared_ptr<T>::use_count() const
    {
        return ref_cnt->use_count_;
    }

    template<typename T>
    void shared_ptr<T>::reset()
    {
        obj_ptr = nullptr;

        if(ref_cnt)
            --ref_cnt->use_count_;

        if(ref_cnt->use_count_ == 0)
            ref_cnt->object_->~T();
    }

    template<typename T>
    T* shared_ptr<T>::get()
    {
        return obj_ptr;
    }

    template<typename T>
    bool shared_ptr<T>::unique() const
    {
        return (ref_cnt->use_count_ == 1);
    }

    template<typename T>
    shared_ptr<T>::operator bool() const
    {
        return (obj_ptr != nullptr);
    }

    template<typename T>
    shared_ptr<T>::~shared_ptr()
    {
        if(obj_ptr)
            reset();
    }
}

Overview
Templated classes "normally" should provide all the code at the point of usage. As a result you should probably not have a separate shared.cpp. Though some people put the definitions in a separate shared.tpp file that is included by the header file.
Code Review:
You are missing a constructor for nullptr.
Though nullptr can be converted to any other type the compiler can not know what type you want in this situation so you would need to be explicit. But it would be nice to allow auto conversion from nullptr to the correct shared pointer type.
 void myFunc(smp::shared_ptr<int>&& ptr) { /* Stuff */}

 int main()
 {
     myFunc(nullptr); // This fails.
                      // as you defined an explicit constructor.
                      // But this is totaly safe so it would be nice if it
                      // simply worked rather than forcing the long hand.
 }

So I would add a constructor for this situation.
 smp::shared_ptr::shared_ptr(std::nullptr_t);

Non standard copy constructor and move constructor:
            shared_ptr(shared_ptr& ptr);           // Would expect const ref
            shared_ptr operator=(shared_ptr& ptr); //

In the current state these can not catch temporary values.

Most people forget the noexcept. So well done.
            shared_ptr(shared_ptr&& ptr) noexcept;
            shared_ptr operator=(shared_ptr&& ptr) noexcept;

You should probably return a reference here:
            T operator*();

Otherwise you are going to force a copy of the internal object as it is returned. Just like the operator-> this does not affect the state of the shared pointer so this is const.
In std::shared_ptr this is a noexcept operation. I could personally argue over that. But smarter people than me wrote the standard so I would go with them.
            T&       operator*() const noexcept;

Good.
T* operator->() const;
But like the operator* can be noexcept.
            T* operator->() const noexcept;

You don't want this accidentally converting in non boolean contexts.
            operator bool() const;

In this situation:
      smp::shared_ptr<int>   x(new int{6});
      smp::shared_ptr<float> y(new float{5});

      if (x == y) {
          // Because of your bool operator
          // they are converted to bool (for both this is true)
          // resulting in this code saying they are equal.
          std::cout << "Equal\n";
      }

Use the explicit here:
      explicit operator bool() const;

The issue I have hear is that if the new fails (for RefCount) then you leak the pointer.
Once you had the pointer to the constructor of a shared pointer you are seeding all responsibility of the pointer. That mean if the object fails to correctly construct you need to make sure the passed pointer is deleted. So in the situation of new failing you need to call delete on the pointer.
template<typename T>
shared_ptr<T>::shared_ptr(T* ptr)
    : obj_ptr{ptr}, ref_cnt{new RefCount()}
{
    ref_cnt->object_ = ptr;
    if(ptr)
        ++ref_cnt->use_count_;
}

Add a try catch block to the initializer list:
template<typename T>
shared_ptr<T>::shared_ptr(T* ptr)
try
    : obj_ptr{ptr}
    , ref_cnt{new RefCount()}
{
    ref_cnt->object_ = ptr;
    if(ptr)
        ++ref_cnt->use_count_;
}
catch(...)
{
    delete ptr;
}

If you are copying a shared_ptr then you should be using the same ref_cnt not a brand new one.
You should prefer to do as much work in the initializer list as possible to prevent multiple initializations.
    shared_ptr<T>::shared_ptr(shared_ptr& ptr)
        : ref_cnt{new RefCount()}
    {
        obj_ptr = ptr.obj_ptr;
        ref_cnt = ptr.ref_cnt;

        ++ref_cnt->use_count_;
    }

// Fixed:
    shared_ptr<T>::shared_ptr(shared_ptr& ptr)
        : obj_ptr(ptr.obj_ptr)
        , ref_cnt{ptr.ref_cnt}
    {
        if (obj_ptr) {
            ++ref_cnt->use_count_;
        }
    }

Here you forget to decrement the ref_counter of the previous object (so potentially allowing a leak). I would use the copy and swap idiom to provide the strong exception guarantee (it also covers self assignment).
    template<typename T>
    shared_ptr<T> shared_ptr<T>::operator=(shared_ptr& ptr)
    {
        obj_ptr = ptr.obj_ptr;  // Old object potentially leaked.
        ref_cnt = ptr.ref_cnt;  // Old ref count potentially leaked.
        ++ref_cnt->use_count_;

        return *this;
    }

Again incorrectly increment the counter.
    template<typename T>
    shared_ptr<T>::shared_ptr(shared_ptr&& ptr) noexcept
        : obj_ptr{nullptr}, ref_cnt{new RefCount()}
    {
        obj_ptr = std::move(ptr.obj_ptr);
        ref_cnt = std::move(ptr.ref_cnt);

        ptr.reset();
    }

The reset will decrement the counter. Since you have moved the object there has been no decrement.
Simpler to simply set this one up as null and then swap.

This can fail.
    template<typename T>
    shared_ptr<T> shared_ptr<T>::operator=(shared_ptr&& ptr) noexcept
    {
        if(obj_ptr)
            reset();

If ptr is the only copy. Then calling reset is going to free the object. Thus any other code is going to now manipulate a freeed object.
        obj_ptr = std::move(ptr.obj_ptr);
        ref_cnt = std::move(ptr.ref_cnt);

        ptr.obj_ptr = nullptr;
        // If you don't reset the ref count object then
        // eventually `ptr` is going to go out of scope and
        // its destructor is going to mess with the ref count object.

Simpler to simply set this one up as null and then swap.

Why does the shared object have to be copied constructed?
    template<typename T>
    shared_ptr<T> make_shared(T object)
    {
        return shared_ptr<T>(new T{object});
    }

Would be nive to allow the type T to be constructed using any of its normal constructors that take parameters.
    template<typename T, typename... Args>
    shared_ptr<T> make_shared(Args...&& args)
    {
        // Though this is the simplist way to do it.
        // The standard version tries to make the whole thing more efficient.
        // by allocating the space for the object T and the ref-count
        // in a single allocation (thus removing the need for an extra
        // call to new).
        return shared_ptr<T>(new T{std::forward<Args>(args)...});
    }

    template<typename T>
    T* shared_ptr<T>::operator->() const
    {
        return &*obj_ptr; // Not sure why that is rewquired.
    }

This implies you don't keep a reference count object for nullptr. But your object always has a reference counter and you will need to make sure it is updated correctly.
template<typename T>
shared_ptr<T>::~shared_ptr()
{
    if(obj_ptr) // Always call reset.
                // Otherwise you are potentially leaking
                // the reference count object.
        reset();
}

Which leads us to the reference count object handling. In reset you need to call delete on the object managed and the reference count object if the count reaches zero.
template<typename T>
void shared_ptr<T>::reset()
{
    obj_ptr = nullptr;

    if(ref_cnt)
        --ref_cnt->use_count_;

    if(ref_cnt->use_count_ == 0)
        // This is not correct.
        // You have called the destructor but leaked the object space.
        ref_cnt->object_->~T();

        // You need to delete the object and the memory used by the
        // reference count object
        // delete ref_cnt->object_;
        // delete ref_cnt;
}

Self Plug: Wrote a lot about shared pointers here:
https://lokiastari.com/series/
Read three articles on shared pointers.


Import "izip" for different versions of Python A common idiom that I use for Python2-Python3 compatibility is:

try:
    from itertools import izip
except ImportError:  #python3.x
    izip = zip

However, a comment on one of my Stack Overflow answers implies that there may be a better way.  Is there a more clean way to accomplish this?

Not sure this is really an answer, or I should elaborate on my comment, and in hindsight probably not even a very good comment anyway, but:

Firstly, you can just simplify it to:

try:
    from itertools import izip as zip
except ImportError: # will be 3.x series
    pass

What I was thinking about was:

From 2.6 you can use as per the docs:

from future_builtins import map # or zip or filter

You do however then have the same problem of ImportError - so:

try:
    from future_builtins import zip
except ImportError: # not 2.6+ or is 3.x
    try:
        from itertools import izip as zip # < 2.5 or 3.x
    except ImportError:
        pass

The advantage of using future_builtin is that it's in effect a bit more "explicit" as to intended behaviour of the module, supported by the language syntax, and possibly recognised by tools. For instance, I'm not 100% sure, but believe that the 2to3 tool will re-write zip correctly as list(zip(... in this case, while a plain zip = izip may not be... But that's something that needs looking in to.

Updated - also in the docs:

  The 2to3 tool that ports Python 2 code to Python 3 will recognize this usage and leave the new builtins alone.


Optimizing a linked list I wrote a linked list class and don't know how to optimize it, please suggest some ideas for optimizing and fixing possible memory leaks.
#define indexTooLarge -1
template <typename T>
class LincedList
{
public:
    LincedList(){}
    template<typename... Types>
    LincedList(T value,Types... values) :  LincedList(values...)
    {
        push_front(value);
    }
    LincedList(T value)
    {
        push_front(value);
    }
    ~LincedList()
    {
        clear();
    }
    void push_back(T value_a)
    {
        if(tail == nullptr)
        {
            tail = new Node(nullptr,value_a);
            head = tail;
            m_size++;
            return;
        }
        tail->next = new Node(nullptr,value_a);
        tail = tail->next;
        m_size++;
    }
    void push_front(T value_a)
    {
        if(head == nullptr)
        {
            head = new Node(nullptr,value_a);
            tail = head;
            m_size++;
            return;
        }
        head = new Node(head,value_a);
        m_size++;
    }
    void clear()
    {
        Node *buffer;
        for(int i = 0;i<m_size;i++)
        {
            buffer = head;
            head = head->next;
            delete buffer;
        }
        m_size = 0;
    }
    void remove(unsigned int index)
    {
        if(index >= m_size)
            throw indexTooLarge;
        Node *currectNode = head;
        for(int i = 0; i < index-1;i++)
            currectNode = currectNode->next;
        Node* buffer = currectNode->next;
        currectNode->next = currectNode->next->next;
        delete buffer;
        m_size--;
    }
    void remove(unsigned int index,unsigned int lenght)
    {
        if(index+lenght >= m_size)
            throw indexTooLarge;
        Node *currectNode = head;
        for(int i = 0; i < index-1; i++)
            currectNode = currectNode->next;
        Node* buffer = currectNode;
        currectNode = currectNode->next;
        for(int i = 0; i < lenght; i++ )
        {
            Node* buffer2 = currectNode;
            currectNode = currectNode->next;
            delete buffer2;
        }
        buffer->next = currectNode;
        m_size -= lenght;
    }
    T& operator[](unsigned const int &index)
    {
        if(index >= m_size)
            throw indexTooLarge;
        if(index == m_size-1)
            return tail->value;
        Node *currectNode = head;
        for(unsigned int i = 0; i < index;i++)
            currectNode = currectNode->next;
        return currectNode->value;
    }
    void operator=(const LincedList &C1)
    {
        head->value = C1.head->value;
        Node *currectNode = new Node(nullptr,C1[1]);
        Node *C1CurrectNode = C1[1];
        head->next = currectNode;
        for(int i = 2; i < m_size; i++)
        {
            C1CurrectNode = C1CurrectNode->next;
            currectNode->next = new Node(nullptr,C1CurrectNode->value);
            currectNode = currectNode->next;
        }
        tail->value = C1.tail->value;
    }
    unsigned int size()
    {
        return m_size;
    }
private:
    struct Node
    {
         Node* next;
         T value;
         Node(Node* next_a, T value_a) : next(next_a) , value(value_a)
         {}
    };
    unsigned int m_size = 0;
    Node* head = nullptr;
    Node* tail = nullptr;
};

#include <iostream>
int main()
{
    LincedList<int> ll(0,1,2,3);
    std::cout << ll[1] << std::endl; //writes to console 1
    ll.remove(1); //removes the element at index 1
    std::cout << ll[1] << std::endl; //writes to console 2
    ll.push_back(4);//adds to the end 4
    ll.push_front(5);//adds 5 to the beginning
    std::cout << ll.size() << std::endl; //writes to console 5
    ll.remove(1,2); //remove all 2 to 3 elements
    std::cout << ll[1] << std::endl ; //writes to console 3
    return  0;
}

In addition to what Reinderien posted:
Look at std::forward_list
Your linked list is a single-linked list, the closes equivalent in the standard library is std::forward_list. You will notice from the documentation of std::forward_list that it doesn't implement a push_back(), and its erase() function only takes iterators, not indices. All this is to keep this data structure light and focused only on the properties that a single-linked list has: inserting and removing at the head is fast, and you can iterate over it in one direction. There is no operator[] overload.
Slower operations, like finding the node at a given index, are left to other functions such as std::advance(). And this makes it clear that if you want to do something like access random elements, you are better off using a different data structure, such as a std::vector.
Spelling
There are some spelling errors in your code:

LincedList -> LinkedList
currectNode -> currentNode (and some variants)

Maybe English is not your native language, that's fine. There are some tools that can help you find and fix common spelling errors in source code, like codespell. Consider running them on your code from time to time.
Don't do bounds checking
Well, you asked how to improve performance.
In C++ it is normal for standard containers to not do any bounds checking. The burden of bounds checking is placed on the caller. This avoids some overhead every time your functions are called.
Not throwing exceptions also allows code using your class to be compiled without exceptions enabled, which can have various benefits.


query optimization and indexing database relations can be found here  http://www.tpc.org/tpc_documents_current_versions/pdf/tpc-h_v2.18.0.pdf

SELECT l_orderkey, sum(l_extendedpriced * (1 - l_discount)) as revenue, o_orderdate, o_shippriority
FROM customer, orders, lineitem
WHERE c_mktsegment = 'BUILDING' -- '[SEGMENT]'
    and c_custkey = o_custkey
    and l_orderkey = o_orderkey
    and o_orderdate < "1995-03-15" -- '[DATE]'
    and l_shipdate > "1995-03-15" -- '[DATE]'
GROUP BY l_orderkey, o_orderdate, o_shippriority
ORDER BY revenue desc, o_orderdate;

I was planning on optimizing this query by using joins like so

SELECT l_orderkey, sum(l_extendedpriced * (1 - l_discount)) as revenue, o_orderdate, o_shippriority
FROM customer
JOIN orders ON c_custkey = o_custkey
JOIN lineitem ON o_orderkey = l_orderkey
WHERE c_mktsegment = 'BUILDING' --'[SEGMENT]'
AND o_orderdate < "1995-03-15" -- '[DATE]'
AND l_shipdate > "1995-03-15" -- '[DATE]'
GROUP BY l_orderkey, o_orderdate, o_shippriority
ORDER BY revenue desc, o_orderdate;

Now all I have to do is create indexes for the tables. For this problem, a maximum of 3 indexes per table can be created with its primary key being 1 of them.

The indexes that I came up with are (these are the columns used in the GROUP BY and ORDER BY clauses)

CREATE INDEX idx_l_orderkey ON lineitem(l_orderkey);
CREATE INDEX idx_o_orderdate_shippriority ON orders(o_orderdate, o_shippriority);

Are there any more indexes that I can put in to further optimize this query? I feel like I need to make another index for the customer table for the c_mktsegment.  Also, if there's any other strategies that I forgot, could you please enlighten me. Thank you.

You can ask SQL Server to recommend the indexes that might improve performance of your query by selecting the query and clicking on this Display Estimated Execution Plan button on the taskbar (or simply Ctrl+L):

This will analyze the query and it will show you the query cost of the operations required to retrieve the data, and eventually propose which indexes might be useful.

Btw, using the joins (as on your 2nd example) should be more efficient indeed.


Command pattern implementation Recently, I have get familiar with Command Pattern implementation. I have a problem where I need to get a choice for user to select what kind of method to execute typing method name or number, which concerns to this concrete method execution. Everything will be OK if I don't need to create separate class for each method as it describes below:

public interface Order {
    void execute ();
}

// Receiver class.
class StockTrade {
    public void buy() {
        System.out.println("You want to buy stocks");
    }
    public void sell() {
        System.out.println("You want to sell stocks ");
    }
}

// Invoker.
class Agent {

    void placeOrder(Order order) {
        order.execute();
    }
}

//ConcreteCommand Class.
class BuyStockOrder implements Order {

    private StockTrade stock;

    public BuyStockOrder(StockTrade st) {
        stock = st;
    }
    public void execute() {
        stock.buy();
    }
}

//ConcreteCommand Class.
class SellStockOrder implements Order {
    private StockTrade stock;
    public SellStockOrder (StockTrade st) {
        stock = st;
    }
    public void execute() {
        stock.sell();
    }
}

// Client
public class Client {
    public static void main(String[] args) {
        StockTrade stock = new StockTrade();
        BuyStockOrder buyStockOrder = new BuyStockOrder(stock);
        SellStockOrder sellStockOrder = new SellStockOrder(stock);
        Agent agent = new Agent();

        agent.placeOrder(buyStockOrder ); // Buy Shares
        agent.placeOrder(sellStockOrder ); // Sell Shares
    }
}

How can I avoid too much class creation for each method that it will be also correct and flexible?

I may not be able to review the point you specifically ask for, but I'll go for a general review:

Omit public and abstract keyword from interfaces, it is implicit.
Be consistent with spacing out your syntax. You for example have public abstract void execute ( );, whereas it should be void execute();, some strings in your program also could have spacing fixed.
Don't start instance variables with m_, perhaps this is common practice from another background, but not in Java. You seem to adhere camelCasing elsewhere though.
Make parameters final where possible. It gives compiler errors if you accidentally change the primitive or the reference to an object.
Use generics, in Agent you specify m_ordersQueue as new ArrayList(), you want to use generics. If all types of objects can be stored, then use new ArrayList<Object>(). I see that you have forgotten to declare the type of the variable, using Java 7's Diamond Operator, it would be private final List<Object> ordersQueue = new ArrayList<>();, also notice that I define only List<Object> as type, as you always want to use interfaces to declare types if possible.
Give variables descrptive names, bsc and ssc are not descriptive.
Lastly, I would consider using a Queue<Object> for the ordersQueue in Agent, the name implies that you want a queue implementation, yet you are using a list implemention.

The good news is that you seem to be following quite some paradigms correctly and you understand OOP quite reasonably, yet you do need to improve on some points.


Remove Duplicates from Array in Swift 3.0 I ran the following code through a Leetcode.com challenge and it says the runtime for the test cases is 119ms, which puts it at the back of the pack performance wise.

The goal is to remove duplicates from a sorted array of Ints and return the count of the array without dups.

func removeDuplicates(_ nums: inout [Int]) -> Int {
    nums = Array(Set(nums)).sorted()
    return nums.count
}

I thought my solution was pretty simple, but 119ms isn't so hot compared with the average of ~60-70ms. Is there a better way to do this?

Your code works correctly, as far as I can see. A small simplification
would be

func removeDuplicates(_ nums: inout [Int]) -> Int {
    nums = Set(nums).sorted()
    return nums.count
}

because sorted() can directly be applied to any collection of
comparable elements and returns an array.

However, your code does not take advantage of the fact that the
given array is already sorted. Two intermediate collections (a set
and an array) are created, and the new array is sorted.
That can be improved.

Since the array elements are sorted, you can traverse through all
elements and only keep those which are different to the previous
one. This leads to the following implementation:

func removeDuplicates(_ nums: inout [Int]) -> Int {

    guard let first = nums.first else {
        return 0 // Empty array
    }
    var current = first
    var uniqueNums = [current] // Keep first element

    for elem in nums.dropFirst() {
        if elem != current {
            uniqueNums.append(current) // Found a different element
            current = elem
        }
    }
    nums = uniqueNums
    return uniqueNums.count
}

In addition, you can save memory by overwriting the elements
in the given array directly. If a different element is found then it
is copied directly to its new position. At the end of the loop,
surplus elements are removed:

func removeDuplicates(_ nums: inout [Int]) -> Int {

    guard let first = nums.first else {
        return 0 // Empty array
    }
    var current = first
    var count = 1

    for elem in nums.dropFirst() {
        if elem != current {
            nums[count] = elem
            current = elem
            count += 1
        }
    }

    nums.removeLast(nums.count - count)
    return count
}

In my tests, the last two methods were about a factor 10 faster
than yours.


Converting integers into Unary Notation I have written a python script that has tallies representing digits 1-9 (0 is just ":" ) Unlike true Unary languages that are in the form 1^k. I represent values for n as per their decimal digits. The integer 121 is 1_11_1 Overall every k digit out of n "integer" is in Tally notation, and the amount of tallies is the sum of all the digits in a given n "integer" such as 121 = 4, 1_11_1 = 4.

Its called a many-one reduction. If you can transform Instance A(9,33,4) into Instance B(1111_1111 1, 111----111, 1111) in poly-time, then its NP-complete

Transformation rules is to just to enter each integer sequentially when asked in the while loop. Also, when your integer is a negative you do not give a "-" symbol for input. It will ask for input if its a negative integer.

Input

(9,33,4) "9, and then 33 and then 4. One at a time for each input."

Output

'111_1111 1' = 9

    111
33>>
    111

    11 11    =4

Algorithm for the Reduction

# This algorithm is very simple and inconsequential.
# It converts integers into a unary like language
# in poly time. All tallies are represented vertically.

print('If your integer is a negative, the script will ask.')
print("DO NOT GIVE -X integers for input!!!")
print('Script will output multiple - symbols for a negative integer transformation')

while 0 == 0:
  ask = input('Enter an integer from a subset-sum instance sequentially.')
  askStr = str(ask)
  res = list(map(int, str(askStr)))
  x = (res)
  asktwo = input('Is your integer a negative integer? y or n: ')
  if asktwo == str("y"):
     twinkle = str('-')
  else:
     twinkle = str(" ")
  for n in x:
      if n == 0:
       tallyone = ":"
       print(twinkle, tallyone)
      if n == 1:
       print(twinkle, "1")
      if n == 2:
       print(twinkle, "11")
      if n == 3:
       print(twinkle, "111")
      if n == 4:
       print(twinkle, "11 11")
      if n == 5:
       print(twinkle, "111 11")
      if n == 6:
       print(twinkle, "111 111")
      if n == 7:
       print(twinkle, "111_111 1")
      if n == 8:
       print(twinkle, "1111 1111")
      if n == 9:
       print(twinkle, "1111_1111 1")

 Question

In what way, is this code sloppy? Am I using while loops and variable names in an ugly way? Is my tallies in the print statements hard to read? What is the ugliest parts of my code and how would I improve them?

The code works. But, I don't know enough about python so what mistakes are you seeing in my code?

This is a very interesting task. Good work on doing it. Here are some criticism.

print('If your integer is a negative, the script will ask.')
print("DO NOT GIVE -X integers for input!!!")
print('Script will output multiple - symbols for a negative integer transformation')

Do not use both double quote
("") and single quote ('') strings. Pick one. I personally prefer "".

while 0 == 0:
  ask = input('Enter an integer from a subset-sum instance sequentially.')

It's considered a best practice to indent using 4 spaces instead of 2.
Also it would be better to move actual transform functionality to a new function.
Also it's better to use while True instead of while 0 == 0 to indicate a endless loop.

Reason: This is more readable.

  askStr = str(ask)
  res = list(map(int, str(askStr))

You are converting ask twice to a string. This is redundant.
Since input() returns a string you don't need to convert this at all.
It is also a better to use python conventions for names. Ex: ask_str or value

  x = (res)

You don't need parenthesis here.
There is also no need to assign to x you can directly use res.

  if asktwo == str("y"):
     twinkle = str('-')
  else:
     twinkle = str(" ")

You don't need to convert a string literal to a string again.
You can directly use "y" as a string.
twinkle is not a good name. Use something like sign.


Minimum sub-array challenge Below is my solution to finding the minimum product sub-interval. It passed 8/12 or so test cases, but the other test cases timed out if they hadn't finished within 2 seconds. When I compile this code as Release, optimized, and to target x64, it takes about 7.6 seconds to finish on large input sizes, such as  this testcase. (I'm running this on Windows 8.1 with CPU: AMD FX-8320 3.49 GHz).

using System;
using System.Collections.Generic;
using System.Linq;

class SubInterval : IComparable<SubInterval> {
    public int start;
    public int end;

    public int Length { get { return start == 0 && end == 0? 0 : end - start + 1; } }

    public int CompareTo(SubInterval other) {
        if (this.Length > other.Length)
            return 1;
        else if (this.Length < other.Length)
            return -1;
        else if (this.Length == other.Length)
            return this.start < other.start ? 1 : -1;
        else
            return 0;
    }
}

class Solution {
    static void Main(string[] args) {
        int N, Q;
        int[] a, q;
        int[][] linesQ;

        //read from STDIN, initialize variables...

        System.Diagnostics.Stopwatch watch = System.Diagnostics.Stopwatch.StartNew();
        for (int j = 0; j < Q; j++) {
            q = linesQ[j];
            if (q[0] == 2)
                a[q[1]] = q[2];
            else
                getMinSubInterval(a, q[1], q[2]);
        }
        watch.Stop();
        long ms = watch.ElapsedMilliseconds;
}

static void getMinSubInterval(int[] a, int i, int j) {

    int min = a[i];
    List<int> lookup = new List<int>() { i };
    for (int k = i; k <= j; k++) {
        if (a[k] == 0) {
            min = 0;
            break;
        }
        if (a[k] < min) {
            min = a[k];
            lookup = new List<int>() { k };
        }
        else if (a[k] == min && k > i) {
            lookup.Add(k);
        }
    }

    if (min == 0) {
        SubInterval zero = new SubInterval { start = i, end = j };
        Console.WriteLine("0 {0} {1}", zero.start, zero.end);
    }
    else if (min == 1 && lookup.Count > 1) {
        SubInterval longest = getLongestSubInterval1s(lookup, a);
        Console.WriteLine("1 {0} {1}", longest.start, longest.end);
    }
    else  {
        int idxMin = lookup[0];
        SubInterval sub = new SubInterval { start = idxMin, end = idxMin };
        Console.WriteLine("{2} {0} {1}", sub.start, sub.end, a[idxMin]);
    }

}

static SubInterval getLongestSubInterval1s(List<int> samesLookup, int[] a) {
    List<SubInterval> list = new List<SubInterval>();
    SubInterval sub;
    for (int k = 0, ikj = 0; k < samesLookup.Count; k++, ikj++) {

        if (k == 0 || !(a[samesLookup[k]] == a[ikj])) {
            sub = new SubInterval { start = samesLookup[k], end = samesLookup[k] };
            ikj = sub.start;
            list.Add(sub);
            continue;
        }
        (list[list.Count - 1]).end = samesLookup[k];
    }

    return list.Max<SubInterval>();
}

How can this code be improved upon so that it runs in \$ O(n \log(n)) \$ time, or what constant-time improvements can be made?

This review won't help much with your time limit exceeded problem,
but there are some poor practices in your code that I'd like to point out.

The else statement is dead code, and the last else if can be changed to else here:

if (this.Length > other.Length)
    return 1;
else if (this.Length < other.Length)
    return -1;
else if (this.Length == other.Length)
    return this.start < other.start ? 1 : -1;
else
    return 0;

Actually, since all the if-else branches return,
you can simplify to:

if (this.Length > other.Length)
    return 1;
if (this.Length < other.Length)
    return -1;
return this.start < other.start ? 1 : -1;

Method names that start with the word "get" normally return something.
getMinSubInterval is void, and it prints stuff.
So it would be better to rename it accordingly.


How can I improve this PHP MySQL rank query? In my db MySQL, I have a table ranks with many fields, one for each page I want limit access for the user in the menu application with PHP control:

  <?php if ($row_ranks['padric'] == '1' ) {
    echo ('
Ricerca
');
        }
        else  {
        echo ('
Ricerca
');
        }
  ?>

In the admin panel, I have a page for seting the privileges to single page with relative checkbox.

The checkbox as a name equal at field name in table like this example:

<input type="checkbox" name="padric" value="1"
<?php if ($row_user_ranks['padric'] == 1) { echo "checked"; } ?>
>Ricerca

For set the privileges I make this PHP code:

    mysql_select_db($database_geomo, $geomo);
    $query_RSfields = sprintf("SHOW COLUMNS FROM ranks WHERE Field NOT IN ('ID', 'userID', 'gruppo')");
    $RSfields = mysql_query($query_RSfields, $geomo) or die(mysql_error());
    $row_RSfields = mysql_fetch_assoc($RSfields);
    $totalRows_RSfields = mysql_num_rows($RSfields);
    do {
     $field = $row_RSfields['Field'] ;

     if (!isset($_POST[$field])) { // set value = 0 for checkbox not checked
         $_POST[$field] = '0' ;
        }

    $updateSQL = sprintf("UPDATE ranks SET $field='".$_POST[$field]."' WHERE userID='".$_POST['ID']."'"); // set privileges for user
    mysql_select_db($database_geomo, $geomo);
    $Result1 = mysql_query($updateSQL, $geomo) or die(mysql_error());

    } while ($row_RSfields = mysql_fetch_assoc($RSfields));

I've made this code in this way because if the checkbox is not checked, it shouldn't return a value and should generate an error "unknown column" for the update SQL.

So, there is another more simply way for doing this job?

DO NOT USE THE mysql_* FUNCTIONS!
They are DEPRECATED.

<?php if ($row_ranks['padric'] == '1' ) {
  echo ('
Ricerca
');
      }
      else  {
      echo ('
Ricerca
');
      }
?>

Your indentation style is a mess, decide what indentation style to use and if to use tabs or spaces (and if yes how many) and then stick to it:
<?php
    if ($row_ranks['padric'] == '1' ) {
        echo '
Ricerca
';
    } else  {
        echo '
Ricerca
';
    }
?>

Normally there's also no space between the line and the closing semicolon.
Additionally the echo function does not need any parentheses.

if ($row_ranks['padric'] == '1' )

If your code is in your native language, please always convert it to English before posting it here for review. It makes things easier for us.
Now what you use here is called a magic string or magic number, it's a fixed value that has some meaning but does not provide any explanation what's-o-ever what that meaning is or why it is that way. Use named constants instead.
const SOME_CONDITION = "1"; // Change the name to something meaningful.

if ($row['padric'] == SOME_CONDITION) {

Also do you now the difference between the equality and identity operator? The equality operator == will perform casting as needed which can yield interesting effects, the identity operator === on the other hand will also compare the types.
Some examples:
0 == 0     -->  true
0 == "0"   -->  true
0 == ""    -->  true
0 == NULL  -->  true

0 === 0     -->  true
0 === "0"   -->  false
0 === ""    -->  false
0 === NULL  -->  false

So always sue === unless you have a compelling reason not to.

$_POST[$field] = '0' ;

First of all, global variables are bad. And after that, writing into the Super-Globals is a bad idea for many reasons. Nobody expects that super globals are modified in any way and that can lead to funny errors which you'll be looking for for days.
Extract the values from the super globals and work with that variable.

$updateSQL = sprintf("UPDATE ranks SET $field='".$_POST[$field]."' WHERE userID='".$_POST['ID']."'"); // set privileges for user

One word (okay, it's two): SQL Injection. There is no, absolutely no (and I mean no) excuse to allow SQL injection. Imagine somebody would manipulate the POST request to contain the value '; DROP TABLE ranks; -- which will yield the query:
UPDATE ranks SET field='field' WHERE userID=''; DROP TABLE ranks; --'

...any questions?
Why are you using sprintf here?

$row_RSfields = mysql_fetch_assoc($RSfields);
do {
    // code
} while ($row_RSfields = mysql_fetch_assoc($RSfields));

Traditionally it's a while loop:
$result = getResult();
while ($row = fetchRow($result)) {

}

Now let's get to the core problem: You are using the mysql_* functions. You should either use mysqli_* or PDO.
Personally I prefer PDO over mysqli_* because it has an object oriented interface and support multi-statements. So here's an example on how to use PDO:
/**
 *
 * @var PDO
 */
$pdo = new PDO($dsn, $user, $password, $options);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); // See footnote!

/**
 *
 * @var PDOStatement
 */
$statement = $pdo->prepare("SELECT field FROM table WHERE id = :id;");
$statement->bindValue(":id", $id, PDO::PARAM_INT);

$statement->execute();

while ($row = $statement->fetch()) {
    echo $row['field'];
}

$statement->closeCursor();

Question on Stack Overflow about when to turn off emulated prepares.

Are you aware of the difference between strings?
'A simple string'
"A string with automatic $variable expansion"


Detecting change of a name or a part We have a fair amount of code which looks like this:

private boolean isThingChanged(String newName, Thing thing) {
    final Part part = thing.getPart();
    if (part == null && newName == null) {
        return false;
    }
    if (part == null || newName == null) {
        return true;
    }
    return !part.getName().equals(newName);
}

That is, if the thing's current part is null and we're trying to set its name to null, that's not a change.  If the part is null or the name is null, but not both, that is a change.  And if neither is null, we have to look at it a little closer.

Thing and Part represent different entities for different such methods, so the first and final lines have the same general form but different specifics.

As written, this generates a SimplifiableIfStatement warning in Intellij, which would prefer to see it as:

private boolean isThingChanged(String newName, Thing thing) {
    final Part part = thing.getPart();
    return !(part == null && newName == null) && (part == null || newName == null || !part.getName().equals(newName));
}

Which is arguably simpler, but certainly not easier for me to read.  I can of course suppress the warning with @SuppressWarnings("SimplifiableIfStatement") but prefer to avoid that if possible.

I would like to find a way to extract this bit:

if (part == null && newName == null) {
    return false;
}
if (part == null || newName == null) {
    return true;
}

which is duplicated in all the instances of this code, because (a) it triggers the SimplifiableIfStatement warning and (b) it just seems too wordy to have it everywhere.  So far I've come up with this:

private Boolean changedFromNull(Object a, Object b) {
    // if both are null, nothing has changed.
    if (a == null && b == null) {
        return false;
    }
    // if only one is null, something has changed
    if (a == null || b == null) {
        return true;
    }
    // if neither is null, further analysis is required
    return null;
}

but that's arguably even worse, because now the calling code has to null-check the result of this method in addition to all the other null checking already going on.

private boolean isThingChanged(String newName, Thing thing) {
    final Part part = thing.getPart();
    final Boolean changedFromNull = changedFromNull(part, newName);
    return changedFromNull != null ? changedFromNull : !part.getName().equals(newName);
}

What's a good approach to this?

A good option is to use the Objects utility class (available since Java 7)

Note also, that instead of doing if-conditions and returning true, or false, you can do a direct return of the condition... For example, the part == null is common to these two expressions:

if (part == null && newName == null) {
    return false;
}
if (part == null || newName == null) {
    return true;
}

And those can be simplified to just:

if (part == null) {
    return newName != null;
}

Note also, that your code runs the risk of a NullPointerException if part.getName() returns null. Is that possible?

Your code:

private boolean isThingChanged(String newName, Thing thing) {
    final Part part = thing.getPart();
    if (part == null && newName == null) {
        return false;
    }
    if (part == null || newName == null) {
        return true;
    }
    return !part.getName().equals(newName);
}

Could be:

private boolean isThingChanged(String newName, Thing thing) {
    if (thing.getPart() == null) {
        return newName != null;
    }
    return !Objects.equal(thing.getPart().getName(), newName);
}

Writing that as a ternary is an option:

private boolean isThingChanged(String newName, Thing thing) {
    return thing.getPart() == null ? newName != null : !Objects.equal(thing.getPart().getName(), newName);
}


BFS and DFS tree traversal I posted some code as part of an answer to another question and I thought it would be a good idea to get that code reviewed also.

Any comments are welcomed, but I am mostly annoyed by terminalNode.  It is basically a slightly convenient factory method, but I think it should either be renamed to something more enlightening, or something entirely different should be done.

object TreeTraversal extends App {

  case class Node[+T](value: T, left: Option[Node[T]], right: Option[Node[T]]) {
    def map[V](f: T => V): Node[V] =
      Node(f(value), left.map(l => l.map(f)), right.map(r => r.map(f)))
    def childrenLeftRight: List[Node[T]] = List(left, right).flatten
  }
  def terminalNode[T](value: T) = Node(value, None, None)

  def dfs[T](tree: Node[T]): List[T] = {
    var output = List[T]()
    tree.map(t => (output = t :: output))
    output.reverse
  }

  def bfs[T](tree: Node[T]): List[T] = {
    @tailrec
    def bfsLoop(accum: List[List[T]], nextLayer: List[Node[T]]): List[T] = nextLayer match {
      case Nil => accum.reverse.flatten
      case _ => bfsLoop(nextLayer.map(_.value) :: accum, nextLayer.flatMap(_.childrenLeftRight))
    }
    bfsLoop(List[List[T]](), List(tree))
  }

  val tree1 = Node[Int](6, Some(Node(13, Some(terminalNode(101)), None)), Some(Node(42, Some(terminalNode(666)), Some(terminalNode(65)))))
  println("map: " + tree1.map(i => s"Hello$i"))
  println("dfs: " + dfs(tree1))
  println("bfs: " + bfs(tree1))
}

Node looks like a monad.  Could I get all other operations such as flatMap and foldLeft for free somehow?

Any comments are welcomed, but I am mostly annoyed by terminalNode

From my opinion, it's more natural to provide default values for case classes:

case class Node[+T](value: T, left: Option[Node[T]] = None, right: Option[Node[T]] = None) {//...

Then you can simply use Node(42) anywhere in your code.

  Node looks like a monad. Could I get all other operations such as flatMap and foldLeft for free somehow?

Typically, any methods in Monads are based on flatMap and unit methods. Therefore you need to implement flatMap method, as unit method you already have (Node.apply).

flatMap needs to accept a method, which returns new instance of Node, e.g. def flatMap[V](f: T => Node[V]): Node[V]. Then it should look like the following:

def flatMap[V](f: T => Node[V]): Node[V] = {
    f(value).copy(
      left = left.map(_.flatMap(f)),
      right = right.map(_.flatMap(f))
    )
}

And it you create a new test, it produce the same output, as for map:

println("map: " + tree1.map(i => s"Hello$i"))
println("fmap: " + tree1.flatMap(i => Node(s"Hello$i"))) //will be the same outputs

But, you should handle cases, when f(value) may return new node with existing left and/or right values, otherwise the implementation above may override the result. You need to consider this in your final implementation.

Then, according to the rule of map, it can be present as map(f) = fmap unit f, so you can create method map2 with flatMap:

def map2[V](f: T => V): Node[V] =
  flatMap(t => Node(f(t)))

Then you will have the same outputs:

println("map: " + tree1.map(i => s"Hello$i"))
println("map2: " + tree1.map2(i => s"Hello$i")) //will be the same outputs

Regarding foldLeft: typically you can almost everything implement with foldLeft, but not otherwise. So we need to understand, what foldLeft should do (DSF?), and then we can express other methods with this.

Also couple notes, I'd change (it's arguable, of course, but worth considering):

Instead of left.map(l => l.map(f) I'd use left.map(_.map(f))
tree.map(t => (output = t :: output)) this can be replaced with mutable ArrayBuffer for 2 reasons: it should be slightly faster and slightly more well-looking.

Consider this code:

 def dfs2[T](tree: Node[T]): List[T] = {
   val output = ArrayBuffer[T]()
   tree.map(output += _)
   output.toList
 }

And outputs again will be the same:

println("dfs: " + dfs(tree1))
println("dfs2: " + dfs2(tree1)) //will be the same outputs

Hope that helps.


VBA Excel - Conditional Formatting Colour Grab This code gets the cell's colour regardless of whether it's set from conditional formatting or not. It currently works on 2010 and unsure about older versions of excel.

My question is is there a way to make this code more efficient?

Such as being able to highlight an area for the code to search rather than setting For stantments
Getting it to search for a specific colour you set rather than red or whatever has been set
Anything else anyone can think of

Sub myCFtest()

For q = 1 To 26

sCol = Split(ActiveCell.Address, "$")(1)
sColNum = sCol & 1
Range(sColNum).Select

For i = 1 To 100

sColNum = ActiveCell.Address

    If Range(sColNum).DisplayFormat.Interior.Color = 255 Then
        Y = ActiveCell.Address
        MsgBox ("Red Cell Found At " & Y)
    End If

ActiveCell.Offset(1, 0).Select

Next i

ActiveCell.Offset(0, 1).Select

Next q

MsgBox ("No Red Cell Found")

End Sub

I can't test this code to see if it works because I have 2007 on this computer. But, I do have some things to add.

First things first, I have no idea what the variables are for - there is no description. You also don't have Option Explicit on and none of the variables are dimed. That's the first thing to address.

What is q? It iterates 1 to 26, but I don't see it being used anywhere. You're just doing the entire thing 26 times? Why? Oh, because you're using .Select - I'll get to that.

The same thing goes to i.

You use sCol = Split(ActiveCell.address,"$")(1) to get the column letter? Why not just get the column with ActivecCell.Columns?

Speaking of ActiveCell - why are you using it? Why not get a variable like Dim RangeToTest and set it to Sheets(1).Range("A1:A26") or whatever? At least Set RangeToTest = Selection - but using selection and activecell is generally bad form.

Instead this entire thing could be (using whatever numbers you need to use)-

  Dim RowNumber As Long
  Dim ColumnNumber As Long

  For RowNumber = 1 To 100
    For ColumnNumber = 1 To 26
        'do stuff to Cells(RowNumber, ColumnNumber)
    Next ColumnNumber
  Next RowNumber

If you're not sure you can do something like this to get what you need -

  Dim RowNumber As Long
  Dim ColumnNumber As Long
  Dim LastRow As Long
  LastRow = Cells(Rows.Count, "A").End(xlUp).Row
  Dim LastColumn As Long
  LastColumn = Cells(1, Columns.Count).End(xlToLeft).Column

  For RowNumber = 1 To LastRow
    For ColumnNumber = 1 To LastColumn
        'do stuff to Cells(RowNumber, ColumnNumber)
    Next ColumnNumber
  Next RowNumber

I can't tell what you're doing here -

sCol = Split(ActiveCell.Address, "$")(1)
sColNum = sCol & 1
Range(sColNum).Select

For i = 1 To 100

sColNum = ActiveCell.Address

From what I can tell you get the column, set sColNum (is that a string? A range?) to the first cell in the column, then you select the Range of the SColNum (string?). And then you set the sColNum that was selected to its own .address? What are you accomplishing here? Seems like it has something to do with your i loop - which can be eliminated and you can just use the example I gave, or something similar.

Now you check for .Interior.Color = 255 and if it's found, you msgbox where it was found with Y as activecell.address when sColNum is already the activecell.address. You don't need Y to say the least.

Instead you could do something like this -

Dim FindInteriorColor As Long

  FindInteriorColor = 255

  If Cells(RowNumber, ColumnNumber).DisplayFormat.Interior.Color = FindInteriorColor Then
    MsgBox ("Red Cell Found at " & Cells(RowNumber, ColumnNumber))
  End If

Now all you need to do is change the variable FindInteriorColor to whatever the value is of the color you want to find. You'd still need to change your msgbox to say the color, but that could be avoided with an input box or variable or something.

Again, I can't test the actual function of the code, but these are improvements you could make at least, if you want to run through cell by cell looking for something and saying each time it's found. If you want to only find the first one, just put an Exit Sub in the if loop.

In response to your comment - a simple way to get the letter of a column number (in case you need it in the future) is something like -

Sub test()
Dim RowBegin As Long
RowBegin = InStr(2, Cells(1, 200).Address, "$")
Dim ColumnLetter As String
ColumnLetter = Mid(Cells(1, 200).Address, 2, RowBegin - 2)
MsgBox ColumnLetter
End Sub


overload c++ enum class operators and enable check value set I use c++ 11 enum class usually instead of the old enums because many enums can contain the same value
but as known they don't have the bitwise operators out of the box so we should define them manually

in windows it's already done for us with this macro in windows.h header :

DEFINE_ENUM_FLAG_OPERATORS

but I then encountered another problem

if I use these enum as flags I can put many values in the falg using bitwise operator | , but to test if the flag contains a value I can't check with bitwise operator & like this :

if (flags & value) {...}

I could however write a template function like this to test :

template <class T>
constexpr bool has_value(T flags, T value)
{
    return (std::underlying_type_t<T>)flags & (std::underlying_type_t<T>)value;
}

but I really would like to use the old format to test for values in the flags
I already found a solution on github which wrapped all chosen emums in a class called flags and it was used like the old ones but with the type safety of enum classes

As I don't want to use templates for this purpose and I want only operator & to give me a bool value in if expressions , I used another class that holds the enum value and can be converted to bool and this is what I wrote

#define OVERLOAD_ENUM_OPERATORS(x) \
class EnumBool##x \
{ \
    x enum_value; \
public: \
    constexpr EnumBool##x(const x e_val) : enum_value(e_val) {} \
    constexpr operator x() const { return enum_value; } \
    explicit operator bool() const { return (std::underlying_type_t<x>)enum_value != 0; } \
}; \
inline constexpr EnumBool##x operator&(const x lhs, const x rhs) \
{ \
    return EnumBool##x((x)((std::underlying_type_t<x>)lhs & (std::underlying_type_t<x>)rhs)); \
} \
inline constexpr x operator|(const x lhs, const x rhs) \
{ \
    return (x)((std::underlying_type_t<x>)lhs | (std::underlying_type_t<x>)rhs); \
} \
inline constexpr x operator^(const x lhs, const x rhs) \
{ \
    return (x)((std::underlying_type_t<x>)lhs ^ (std::underlying_type_t<x>)rhs);\
} \
inline constexpr x operator~(const x lhs) \
{ \
    return (x)(~(std::underlying_type_t<x>)lhs);\
} \
inline constexpr x& operator|=(x& lhs, const x rhs) \
{ \
    lhs = (x)((std::underlying_type_t<x>)lhs | (std::underlying_type_t<x>)rhs); \
    return lhs; \
} \
inline constexpr x& operator&=(x& lhs, const x rhs) \
{ \
    lhs = (x)((std::underlying_type_t<x>)lhs & (std::underlying_type_t<x>)rhs); \
    return lhs; \
} \
inline constexpr x& operator^=(x& lhs, const x rhs) \
{ \
    lhs = (x)((std::underlying_type_t<x>)lhs ^ (std::underlying_type_t<x>)rhs); \
    return lhs; \
} \
inline constexpr bool operator==(const x lhs, const x rhs) \
{ \
    return (std::underlying_type_t<x>)lhs == (std::underlying_type_t<x>)rhs; \
} \
inline constexpr bool operator!=(const x lhs, const x rhs) \
{ \
    return (std::underlying_type_t<x>)lhs != (std::underlying_type_t<x>)rhs; \
} \
inline constexpr bool operator>(const x lhs, const x rhs) \
{ \
    return (std::underlying_type_t<x>)lhs > (std::underlying_type_t<x>)rhs; \
} \
inline constexpr bool operator<(const x lhs, const x rhs) \
{ \
    return (std::underlying_type_t<x>)lhs < (std::underlying_type_t<x>)rhs; \
} \
inline constexpr bool operator>=(const x lhs, const x rhs) \
{ \
    return (std::underlying_type_t<x>)lhs >= (std::underlying_type_t<x>)rhs; \
} \
inline constexpr bool operator<=(const x lhs, const x rhs) \
{ \
    return (std::underlying_type_t<x>)lhs <= (std::underlying_type_t<x>)rhs; \
}

A few things that might be improved:

Use static_cast<type>(value) instead of (type)(value).
I'm missing an bool operator!(const x lhs).
You could also define operator&& and operator||.
You can make enum_value const.


Conditional joining Pandas dataframes I'm looking for an optimum way to join two Dataframes where the same record exists in both. Examples would be:

dat1 = pd.DataFrame({"id": [1,2,3,4,5], "dat1": [34,56,57,45,23]})
dat2 = pd.DataFrame({"id": [2,3,4], "dat2": [19,19,20]})

dat1
   id  dat1
0   1    34
1   2    56
2   3    57
3   4    45
4   5    23

dat2
   id  dat2
0   2    19
1   3    19
2   4    20

With the aim being to create overall_data:

overall_data
   id  dat1  dat2
0   2    56    19
1   3    57    19
2   4    45    20

At the moment my method is:

dat3 = dat1['id'].isin(dat2['id'])
dat3 = pd.Dataframe(dat3)
dat3.columns = ['bool']
dat4 = dat1.join(dat3)
overall_data = dat4(dat4['bool'] == True)

Though this feels very messy. Is there a nicer way to do this?

This is the textbook example of an inner join. The most canonical way to have your id columns being used for the matching, set them as an index first (here using inplace operations to save on extra variable names; depending on your use, you might prefer new copies instead):

dat1.set_index('id', inplace=True)
dat2.set_index('id', inplace=True)

Then, the whole operation becomes this simple join on index:

>>> overall_data = dat1.join(dat2, how='inner')
>>> overall_data

    dat1  dat2
id
2     56    19
3     57    19
4     45    20

If you do not want to modify the original DataFrames, you can use utility function merge instead, which performs the same operation, but needs the common column name specified explicitely:

>>>  pd.merge(dat1, dat2, how='inner', on='id')

   id  dat1  dat2
0   2    56    19
1   3    57    19
2   4    45    20


Candy splitting - lower memory usage needed I just did CodeChief's candy splitting task here and my code is working even with a lot of test cases and big numbers, but it uses way too much memory. When I checked my submission, it was 1342M, which is a lot.

import java.util.ArrayList;
import java.util.Scanner;

class Candies {

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int candieStuds;
    int candieT;

    int testCases = in.nextInt();
    ArrayList<String> answ = new ArrayList<String>();
    for(int tCase = 0; tCase < testCases; tCase++){
        int candies = in.nextInt();
        int studs = in.nextInt();
            candieStuds = candies/studs;
        candieT  = candies%studs;
        StringBuilder str = new StringBuilder();
        str.append(candieStuds);
        str.append(" ");
        str.append(candieT);
        answ.add(str.toString());

    }
   for(int listInd = 0; listInd < answ.size(); listInd++){
       System.out.println(answ.get(listInd));
   }
   in.close();
}}

Can someone point out what I should use so I can have the same performance but use less memory?

Your code is a bit messy, and buggy, and you have a significant memory problem in the event of there being a lot of test cases.

Buggy

The problem specifies that the number of candies (N) and children (K) is a value \$0 \le N,K \le 2^{33} - 1\$ The telling part is \$2^{33} - 1\$. That number is larger than a Java int value. You need to use long in order to support the specified input values.

Messy

You declare the variables:

int candieStuds;
int candieT;

outside the loop they are used in. You should declare variables in their scope. It is more readable, and less error prone.

On the other hand, you declare the StringBuilder inside the loop, but that is a system which can be reused, so you should. Declare it outside the loop, then call str.setLength(0) to reset it.

Memory

You declare an array, and store the results of all tests in that array. Once all tests are complete, you report on all the results. In one sense, this is good, because lots of println operations will slow things down. On the other hand, this is bad, because lots of tests cases will fill up memory.....

A compromise is to wrap the System.out in a BufferedWriter, and then write to the buffer for each test, and then let the buffer occasionally flush when it's full (and at the end).

Buffering the System.in is also a good idea.

Performance

Loading all your logic in to a method that is only called once is not a great plan for either readability, or performance.

Java performance is heavily dependent on the JIT compiler. In essence, the basic unit of compilation in Java is a method. You only have one method, and it only gets called once, so it is not likely to be compiled down very well. By giving the compiler more methods, called more often, you give it more to work with in terms of ways to compile things. More is good.

In your case, I would recommend a method for parsing the input lines in to numbers, a method for doing the computations, and another method for preparing the output...

I hacked together the following, which I think will do better (not sure how much better though...). Use it to see what I mean when I talk about the functions, and the buffering.

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class CCCandy {

    public static void main(String[] args) throws IOException {
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));
            try {
                String line = reader.readLine();

                if (line == null) {
                    throw new IllegalStateException("Expecting test count input");
                }

                while ((line = reader.readLine()) != null) {
                    processCandySplit(line, writer);
                }
            } finally {
                writer.flush();
            }
        }
    }

    private static void processCandySplit(String line, BufferedWriter writer)
            throws IOException {
        line = line.trim();
        String[] inputs = line.split("\\s+");
        long candies = Long.parseLong(inputs[0]);
        long kids = Long.parseLong(inputs[1]);

        computeSplit(candies, kids, writer);

    }

    private static void computeSplit(long candies, long kids, BufferedWriter writer)
            throws IOException {
        if (kids == 0) {
            writer.write(String.format("%d %d\n", 0, candies));
        } else {
            writer.write(String.format("%d %d\n", candies / kids, candies % kids));
        }
    }

}


Python insert line in the middle of the file I will be inserting a new text line in a setup.py file, this new line will contain text, and is part of the REQUIRED_PACKAGES. I parsed the
file and look for REQUIRED_PACKAGES pattern (REQUIRED_PACKAGES = [ ... ]). Looking for alternatives during file insertion.

A sample setup.py file looks like this:

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import fnmatch
import os
import re
import sys

from setuptools import Command
from setuptools import find_packages
from setuptools import setup
from setuptools.command.install import install as InstallCommandBase
from setuptools.dist import Distribution

DOCLINES = __doc__.split('\n')

_VERSION = '1.0.0'

REQUIRED_PACKAGES = [
    'absl-py >= 0.7.0',
    'astunparse == 1.6.3',
    'backports.weakref >= 1.0rc1;python_version<"3.4"',
    'enum34 >= 1.1.6;python_version<"3.4"',
    'gast == 0.3.3',
    'scipy == 1.2.2;python_version<"3"',
]

if sys.byteorder == 'little':
  # grpcio does not build correctly on big-endian machines due to lack of
  # BoringSSL support.
  REQUIRED_PACKAGES.append('io >= 1.0.0')

...

After conversion it will look like this (adding a new line):

...
REQUIRED_PACKAGES = [
    'absl-py >= 0.7.0',
    'astunparse == 1.6.3',
    'backports.weakref >= 1.0rc1;python_version<"3.4"',
    'enum34 >= 1.1.6;python_version<"3.4"',
    'gast == 0.3.3',
    'scipy == 1.2.2;python_version<"3"',
    'test==1.0.0',
]
...

Python code

import re

SEARCH_DICT = {
    'required_packages': re.compile(
        r'REQUIRED_PACKAGES = (?P<required_packages>.*)\n')
}

TEST_LIBRARY = '\t\t\'test==1.0.0\'\n'

def _parse_line(line):
    """
    Do a regex search against all defined regexes and
    return the key and match result of the first matching regex

    """

    for key, rx in SEARCH_DICT.items():
        match = rx.search(line)
        if match:
            return key, match
    # if there are no matches
    return None, None

def parse_file(filepath):
    """
    Parse text at given filepath

    Parameters
    ----------
    filepath : str
        Filepath for file_object to be parsed

    Returns
    -------
    data : file contents

    while True:
        last_pos = fp.tell()
        line = fp.readline()
        new_line = line.upper()
        fp.seek(last_pos)
        fp.write(new_line)
        print "Read %s, Wrote %s" % (line, new_line)

    """

    data = []  # create an empty list to collect the data
    line_index = -1
    # open the file and read through it line by line

    with open(filepath, 'r+') as file_object:
        line = file_object.readline()
        line_index+=1
        while line:
            # at each line check for a match with a regex
            key, match = _parse_line(line)
            if key == 'required_packages':
                required_packages_start = match.group('required_packages')
                if required_packages_start == '[':
                    print('Found REQUIRED_PACKAGES')
                    while line.strip():
                        library = line.rstrip()
                        if library == ']': # End of required packages
                            return line_index
                        line = file_object.readline()
                        line_index+=1

            line = file_object.readline()
            line_index+=1
        file_object.readline()
        line_index+=1

    return line_index

line_index = parse_file('setup.py')
lines = None
if line_index != -1:
    with open('setup.py', 'r+') as fd:
        contents = fd.readlines()
        contents.insert(line_index, TEST_LIBRARY)  # new_string should end in a newline
        fd.seek(0)  # readlines consumes the iterator, so we need to start over
        fd.writelines(contents)  # No need to truncate as we are increasing filesize

Your code goes through the file twice - once to find the index where your new line is to be inserted, and again to actually perform the change.

My approach to this problem would be to create a class that contains three variables:

The lines in setup.py before "REQUIRED_PACKAGES = ["
The contents of the REQUIRED_PACKAGES list
The lines in setup.py after the REQUIRED_PACKAGES list

Your problem then splits nicely into three distinct sub-problems:

Parsing setup.py and returning an instance of the class above
Adding an element to the required packages list in your custom class (trivial)
Writing a new setup.py file

Looking at your code specifically, your docstring for parse_file does not match what the code is doing. It says that data is returned, but the code actually returns line_index, and the data member you initialise is unused.

Your code comments in general could be improved. You comment some obvious things such as"open the file and read through it line by line" and "if there are no matches". These operations are immediately apparent from looking at the code, and do not require comments.


Plotting a 2D iso-probability curve I have a library function that returns a pair of two numbers like this

def library_function(x0, x1):
    return x0**2 + x1**2, 10*x0*x1 + 1

(Actually, it is a function that returns predicted probabilities of two classes for some object, but it doesn't matter, so I created an artificial one.) I want to draw contours where the difference between two numbers returned by library_function is zero. To do so, I have to create a two-dimensional list (or array) with the differences.

I have the following possibilities:

X0 = np.linspace(-10, 10, 200)
X1 = np.linspace(-10, 10, 200)

results = [[(lambda u: u[0]-u[1])(library_function(x0, x1))
            for x0 in X0] for x1 in X1]
plt.contour(X0, X1, results, [0])

This approach is concise but I have to introduce lambda which seem to be considered not so Pythonic.

Another way:

values = [[library_function(x0, x1) for x0 in X0] for x1 in X1]
results = [[a-b for a, b in row] for row in values]

I have to introduce temporary two-dimensional list and this approach is longer.

Are there any ideas how to do it better (more concise and readable)?

Since you are using NumPy, you should deal with grids the NumPy way instead of performing list comprehensions.

def probability_diff(x0, x1):
    probs = library_function(x0, x1)
    return probs[0] - probs[1]

results = np.vectorize(probability_diff)(X0[:, np.newaxis], X1)

I wouldn't try to get too clever with the lambdas.

Also, since the grid happens to be a square, you could use X0 again instead of defining X1.


Java CSV to XML converter I'm relatively new to programming and I was trying to work a project.
I would like recommendations of how to annotate or comment my project and any improvement I could make to it, any suggestion is welcome,
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.ArrayList;

public class Util {

    /*/
    DOC Generation -> XML with ArrayList String elements
     */
    public Document docBuilder(ArrayList<String[]> elements) throws ParserConfigurationException {
        DocumentBuilderFactory xmlFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder xmlBuilder = xmlFactory.newDocumentBuilder();
        Document xmlDoc = xmlBuilder.newDocument();

        Element rootElement = xmlDoc.createElement("root");
        xmlDoc.appendChild(rootElement);

        Element mainElement = xmlDoc.createElement("elements");
        rootElement.appendChild(mainElement);

        boolean headerDefined = false; //First while will be to define header
        String[] header = new String[elements.size()]; //Header initialization

        /*/
        DOC Generation -> XML Generation of every ELEMENT
        */
        for (String[] node : elements) { //FOR every ArrayString
            if (headerDefined) {
                Element nodesElements = xmlDoc.createElement("element");
                mainElement.appendChild(nodesElements);

                for (int j = 0; j < node.length; j++) {
                    node[j] = node[j].replaceAll("\"", "").trim();
                    Element nodesValues = xmlDoc.createElement(header[j]);
                    nodesElements.appendChild(nodesValues);
                    Text nodeTxt = xmlDoc.createTextNode(node[j]);
                    nodesValues.appendChild(nodeTxt);
                }
            }
            /*/
            DOC Generation -> Array Generation of every COL Name for NODES
            */
            else {
                header = node;
                for (int k = 0; k < node.length; k++) {
                    header[k] = header[k].replaceAll("[^a-zA-Z0-9]", "");
                    //We want to make sure NODE isn't NUMERIC. If it is, we make a patch
                    try {
                        Integer.parseInt(header[k]);
                        header[k] = "node" + header[k];
                    } catch (NumberFormatException e) {
                    }
                }
                headerDefined = true;
            }
        }
        return (xmlDoc);
    }

    /*/
    XML Generation -> Transform DOC Data to XML Format
     */
    public static void transformDocToFile(Document xmlDoc, String xmlFile) throws TransformerException {
        TransformerFactory xmlTransformerFactory = TransformerFactory.newInstance();
        Transformer xmlTransformer = xmlTransformerFactory.newTransformer();
        xmlTransformer.setOutputProperty(OutputKeys.INDENT, "yes");
        xmlTransformer.setOutputProperty(OutputKeys.METHOD, "xml");
        xmlTransformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        xmlTransformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
        FileOutputStream outputStream = null;
        try {
            outputStream = new FileOutputStream((new File(xmlFile)));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        xmlTransformer.transform(new DOMSource(xmlDoc), new StreamResult(outputStream));
    }

}

https://github.com/codepressed/JAVACSVtoXMLConverter

Line by line analysis
public class Util {

Util is not a good class name. It does not describe what the responsibility or function of the class is. If it did, it would describe the top desktop drawer of code, where all random code snippets are dumped because the authors could not be bothered to think of a proper place. Suffice to say, those kinds of classes don't exist in well maintained code bases. Use something like TabularToXmlConverter instead.
/*/
DOC Generation -> XML with ArrayList String elements
 */

You should have an extremely good reason for creating your own specialized format for documenting your classes and methods. Java platform comes with JavaDoc which is a standardized way of formatting documentation. Programmers know how to read it and expect to see it. When encountered with your style they literally get angry because they have to learn a new (and most likely inferior) format.
DocumentBuilderFactory xmlFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder xmlBuilder = xmlFactory.newDocumentBuilder();

Because your method created the DocumentBuilderFactory, it became responsible for managing it's own dependencies. If you wanted to use the converter to create a bit different kind of XML document, you couldn't do it without changing the class and breaking all code that already uses it. You might want to pass a DocumentBuilder reference to the class and thus employ dependency injection.
Document xmlDoc = xmlBuilder.newDocument();

What is the reason why you build the document in memory? Most often when I have worked with XML, the biggest problem has been memory consumption caused by handling large XML documents that have been loaded into memory. Since you also provided a transformDocToFile it might make more sense to just write the document directly to an OutputStream using the Streaming API for XML (StAX).
boolean headerDefined = false; //First while will be to define header

Do not use end-of-line comments. They are difficult to read, hard to maintain and force you to compress your thoughts into fewer words that make sense. I, for example, have no idea what this comment means. And you should strive to use variable names that describe the purpose of the variable. From the variable name alone I already guessed it's a flag that tells if the header row has been generated. So there isn't any need for a comment here at all. The other end-of-line comments also just tell what the preceding code does adding no additional value. Comments should desribe why something is being done, not repeat what the code already tells. If the code isn't clear, first priority should be making it clearer instead of duplicating it in free verse.
public static void transformDocToFile(Document xmlDoc, String xmlFile) throws TransformerException {

One of your methods is static and the other is not, requiring the caller to create an unnecessary instance of the Util-class.
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

You catch one of the possible exceptions and continue happily even though in this particular case you cannot even write to the file.


Python 3 - Get n greatest elements in dictionary Given an dictionary with lists as values this piece of code is dedicated to find the n keys with the longest lists as values. It works, but there has to be a more elegant solution.

def get_n_longest_values(dictionary, n):
    result = []

    for key, value in dictionary.items():
        if len(result) < n:
            result.append((key, len(value)))
        else:
            # (index, length) of smallest element
            smallest = (10e10, 10e10)
            for index in range(0, n):
                if result[index][1] < smallest[1]:
                    smallest = (index, result[index][1])

            if len(value) > smallest[1]:
                result[smallest[0]] = (key, len(value))

    return result

Using the following test case, your code takes about 1 ms on my machine:

In [1]: import itertools
In [2]: import string

In [3]: d = dict(zip(itertools.product(string.ascii_lowercase, repeat=10),
             ([0] * i for i in range(1000))))
In [4]: %timeit get_n_longest_values(d, 3))
1000 loops, best of 3: 1.06 ms per loop

First, a short style comment: In Python, range has an implicit 0 as its first argument, so range(0, n) is the same as range(n).

You are doing this very manually, while it can be a bit faster when using built-in functions. I would first sort the items of the dictionary by the length of the values. (You cannot avoid going over the dictionary once. However this wastes some cycles, because it is a full sort, instead of a partial sort). Then you can just slice the sorted list and return the length of the values:

def get_n_longest_values_g(dictionary, n):
    longest_entries = sorted(
        dictionary.items(), key=lambda t: len(t[1]), reverse=True)[:n]
    return [(key, len(value)) for key, value in longest_entries]

This is much more readable and for the given test case performs better than your code by about a factor of 2:

In [5]: %timeit get_n_longest_values_g(d, 3)
1000 loops, best of 3: 514 µs per loop

Note that for this function, the output is actually sorted (descending), whereas yours is not.

Even for larger dictionaries, my function outperforms yours:

In [12]: import random
In [13]: d = dict(zip(itertools.product(string.ascii_lowercase, repeat=10), ([0] * random.randrange(10000) for i in range(10000))))
In [14]: %timeit get_n_longest_values(d, 3)
100 loops, best of 3: 10.2 ms per loop

In [15]: %timeit get_n_longest_values_g(d, 3)
100 loops, best of 3: 6.61 ms per loop

When n grows, your code becomes ever slower, because you iterate over the whole result in the worst case, whereas my code always sorts the whole dictionary anyways (same d as in the previous case):

In [18]: %timeit get_n_longest_values(d, 100)
10 loops, best of 3: 109 ms per loop

In [19]: %timeit get_n_longest_values_g(d, 100)
100 loops, best of 3: 6.27 ms per loop

There are a few possible routes of improvements left for this code. One could already at the beginning generate pairs of len(values), key, which can then be naturally sorted by Python, which should be slightly faster, as noted by @Peilonrayz in the comments. So, something like this:

def get_n_longest_values_g2(dictionary, n):
    return sorted([(len(value), key) for key, value in dictionary.items()],
                  reverse=True)[:n]

It is slightly slower than my previous function:

In [32]: %timeit get_n_longest_values_g2(d, 100)
100 loops, best of 3: 11.7 ms per loop

It has also a changed output (len(values), key, instead of key, len(values)).

Another possibility is to use your basic code and maintain a sorted result, so we can use binary search to insert the newest value and pop the smallest pair if needed, using the bisect module:

import bisect

def get_n_longest_values_gb(dictionary, n):
    result = []

    for key, value in dictionary.items():
        bisect.insort(result, (len(value), key))
        if len(result) > n:
            result.pop(0)

    return result

This performs somewhere between the other two approaches:

In [42]: %timeit get_n_longest_values_gb(d, 100)
100 loops, best of 3: 9.42 ms per loop

Note that its output is also reversed. It is limited by list.insert (which bisect.insort calls internally) being \$\mathcal{O}(n)\$ (as is list.pop(0), which we could get around by using a collections.deque, but a deque also has \$\mathcal{O}(n)\$ insert).

Lastly, one could use the heapq module, which has a nlargest function:

import heapq

def get_n_longest_values_gh(dictionary, n):
    return heapq.nlargest(n, ((len(value), key) for key, value in dictionary.items()))

This is the fastest for this particular test case, outperforming the sorted approach:

In [32]: %timeit get_n_longest_values_gh(d, 100)
100 loops, best of 3: 3.16 ms per loop

Note that its output is also reversed.

As stated in an answer to a similar question:

  The latter two functions perform best for smaller values of n. For
  larger values, it is more efficient to use the sorted() function.
  Also, when n==1, it is more efficient to use the built-in min() and
  max() functions. If repeated usage of these functions is required,
  consider turning the iterable into an actual heap.


Caesar Cypher guessing game Caeser's cipher code where there are a converter and a game part with user input. The code includes keys (settable and not settable).

import random

def change_letter(original, new_message, key_number, alpha):
    for letter in original:
        if letter in alpha.lower():
            new_message += alpha[(alpha.lower().index(letter) + key_number) % 26].lower()
        elif letter in alpha:
            new_message += alpha[(alpha.index(letter) + key_number) % 26]
        else:
            new_message += letter

    return new_message

def encipher(the_key, message, inp=True):
    alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    output_message = ""

    if inp:
        try:
            the_key = int(input('Key?  ・  '))
        except ValueError:
            the_key = input('\nNot valid input  ・  ')
            while not the_key.isnumeric():
                the_key = input('Not valid input  ・  ')

    output_message = change_letter(message, output_message, int(the_key), alphabet)

    return output_message

def convert():
    while True:
        key = None
        type_word = input('\nType your word  ・  ')
        print('\n{}  ::  {}'.format(type_word, encipher(key, type_word)))
        convert_again = input('\nWould you like to convert again? | Y/N  ・  ').upper()

        if convert_again == 'Y' or convert_again == 'YES':
            continue
        break

def play():
    while True:
        key = random.randint(1, 25)
        words = ('WWE', 'Javascript', 'Pythonista', 'Computer Science', 'Eighty-three', 'Event Log', '5K Freestyle')
        word = random.choice(words)
        question = input('\nWhat is {} of key {}  ・  '.format(word, key)).lower()
        changed_word = encipher(key, word, inp=False)

        if question == changed_word.lower():
            print(f'Congratulations! You guessed {changed_word} from {word}')
        else:
            print(f'Oops! Wrong answer. The word is {changed_word} from {word}')

        play_again = input('\nWould you like to play again? | Y/N  ・  ')

        if play_again.upper() == 'YES' or play_again.upper() == 'Y':
            continue
        break

def main():
    while True:
        convert_or_play = input('C to convert, P to play  ・  ')
        if convert_or_play.upper() == 'C':
            convert()
        elif convert_or_play.upper() == 'P':
            play()
        else:
            break
        print()

if __name__ == '__main__':
    main()

def change_letter(original, new_message, key_number, alpha):

docstrings: Python documentation strings (or docstrings) provide a convenient way of associating documentation with Python modules, functions, classes, and methods.It’s specified in source code that is used, like a comment, to document a specific segment of code.

You should include a docstring indicating what the parameters are and what the function does:

def change_letter(original, new_message, key_number, alpha):
    """
    Encode message.
    original: a string (word)
    new_message: empty string
    key_number: int
    alpha: a string containing lowercase alphabet
    """

unecessary function parameter: new_message

There is no need to bother user with entering an empty string.

string immutability::

new_message += alpha[(alpha.lower().index(letter) + key_number) % 26].lower()

A string is immutable in Python therefore each time you're adding to a string, you're creating another string instance and this is pretty inefficient, use list comprehension syntax instead.

list comprehension syntax:

You can use list comprehensions to replace this whole function in the following way:

def encode(message: str, shift: int):
   """Encode and return message."""
return ''.join([chr(ord(char) + shift) for char in message.lower()])

the use of ord and chr is very useful in this case since both do not care about whether a character is uppercase, lowercase or digit, they convert everything and they are much more efficient than alpha.lower().index(letter) + key_number) % 26 which call .lower() and .index() for each letter in the word.

def encipher(the_key, message, inp=True):
    alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

same comments regarding docstrings.
you can use string.ascii_uppercase instead of manually writing the letters with possibility of a slip of hand and the creation of a bug in the case of a missed letter.
if inp: I did not find a single case where inp might be set to False so there is no need for this parameter.

This whole encipher() can be shortened to the following:

def encipher(message, encryption_key=input('Enter key: ')):
    """Encipher according to a user given key, return an error if key is not digit."""
    while not encryption_key.isdigit():
        encryption_key = input('Invalid input, enter a number: ')
    return encode(message, int(encryption_key))

f-strings: since you're using Python 3, in Python source code, an f-string is a literal string, prefixed with 'f', which contains expressions inside braces. The expressions are replaced with their values.

print('\n{}  ::  {}'.format(type_word, encipher(key, type_word)))

expression can be written using f-strings in the following way:

print(f"\n{type_word} : {encipher(key, type_word)}")

same goes for question = input('\nWhat is {} of key {}  ・  '.format(word, key)).lower()

can be written:

question = input(f'What is the translation of {word} using {key} as key? ').lower()

Here's a refactored version of the code:

import random

def encode(message: str, shift: int):
    """Encode and return message."""
    return ''.join([chr(ord(char) + shift) for char in message.lower()])

def encipher():
    """Encode message interactively."""
    message = input('Enter word/message: ')
    encryption_key = input('Enter key: ')
    while not encryption_key.isdigit():
        key = input('Invalid input, enter a number: ')
    encoded_message = encode(message, int(encryption_key))
    print(f'{message} has been encoded to {encoded_message}')
    re_encode = input(f'Would you like to convert {encoded_message} again? y/n: ').lower()
    while re_encode.lower() not in 'yesno':
        print(f'Invalid input {re_encode}')
        re_encode = input(f'Would you like to convert another word? y/n: ').lower()
    if re_encode in 'no':
        print('Thank you for using Cesar cipher.')
        exit(0)
    if re_encode in 'yes':
        encipher()

def play():
    """Play a cipher game."""
    key = random.randint(1, 25)
    words = ('WWE', 'Javascript', 'Pythonista', 'Computer Science', 'Eighty-three', 'Event Log', '5K Freestyle')
    word = random.choice(words)
    answer = input(f'What is the translation of {word} using {key} as key? ')
    encoded_word = encode(word, key)
    if answer == encoded_word:
        print(f'Correct guess {encoded_word}')
    if answer != encoded_word:
        print(f'Oops! wrong guess {answer} the correct answer is {encoded_word}')
    replay = input('Would you like to play again? y/n: ')
    while replay not in 'yesno':
        print(f'Invalid input {replay}')
        replay = input('Would you like to play again? y/n: ')
    if replay in 'no':
        print('Thank you for using Cesar cipher.')
        exit(0)
    if replay in 'yes':
        play()

if __name__ == '__main__':
    while True:
        game_or_encode = input('Enter e to encode or p to play e/p: ').lower()
        while game_or_encode not in 'ep':
            print(f'Invalid entry {game_or_encode}')
            game_or_encode = input('Enter e to encode or p to play e/p: ').lower()
        if game_or_encode == 'e':
            encipher()
        if game_or_encode == 'p':
            play()


Functional K-way merge (Merge k sorted sequences) I've implemented a functional k way-merge algorithm to merge k sorted sequences of any type T. I used scalaz's Heap since the Scala standard library does not provide an immutable heap. Any suggestions to make this more performant/concise/idiomatic are welcome :-

import scala.annotation.tailrec
import scalaz.Heap
import scalaz.Order.fromScalaOrdering

def kWayMerge[T: Ordering](allSequences: IndexedSeq[IndexedSeq[T]]): IndexedSeq[T] = {
    case class PQNode(elem: T, indexInList: Int, indexOfList: Int)

    implicit val pqOrdering = fromScalaOrdering(Ordering.by[PQNode, T](_.elem))
    val pqNodes = allSequences.zipWithIndex.map {
      case (list, indexOfList) =>
        list.zipWithIndex.map { case (a, b) => PQNode(a, b, indexOfList) }
    }

    @tailrec
    def loop(priorityQueue: Heap[PQNode], sortedList: IndexedSeq[T]): IndexedSeq[T] = {
      if (priorityQueue.isEmpty) sortedList
      else {
        val minNode = priorityQueue.minimum
        val newPq = priorityQueue.deleteMin
        val finalPQ = pqNodes(minNode.indexOfList).lift(minNode.indexInList + 1).fold(newPq)(newPq.insert(_))
        loop(finalPQ, sortedList :+ minNode.elem)
      }
    }

    val priorityQueue = pqNodes.foldLeft(Heap.Empty[PQNode])((heap, list) => heap.insert(list(0)))
    loop(priorityQueue, IndexedSeq.empty[T])
  }

I've been thinking about this question literally for weeks.

It always seemed like this implementation suffers from "hammer syndrome" - if you have a really good hammer, you want to think every problem is a nail. Functional coding is a great tool for many things, but in this case, it has a problem.

The reason why algorithms use mutable rather than immutable heaps is asymptotic performance. In a heap sort, a mutable heap gives you log n time per element, but an immutable heap would have n time per element (because you have to copy the entire heap of size n in addition to doing the re-heap with time log n).

Similarly, a k-way merge implemented with immutable heaps will run in nk time, rather than n log k time. That's fine if k is small but even with modest sized k, will become a significant performance hit.

It would have been helpful if test cases had been included so that reviewers could take a look at performance numbers with various possible changes.

The code itself looks fine to me. The fact that nobody wrote a review could mean that most people who read the question came to the same conclusion. As an academic exercise, I say, good job. In the long run, I doubt such an algorithm is genuinely useful except in truly unusual circumstances