Looking to simplify my first python Rock, paper, Scissors project I recently (Yesterday) started working with python and my goal is to not use any tutorials etc where I have to follow along and make a small project. My first project I was recommended to do was a simple game of Rock, Paper, Scissors. I made it in about thirty minutes and it works fine. It goes up to 3 points for each game etc. It's super simple, but now since I'm done with it I'm hoping to find a way to simplify the code, if there is any other way. I really stretched it out since I'm using basics with no help.

# Rock Papers Scissors
import random

option = ["Rock", "Paper", "Scissor"]
game = True

def start_game():
    point_player = 0
    point_ai = 0
    game_end = True
    while game:
        rock = False
        paper = False
        scissor = False
        if point_player == 3:
            game_end = False
        elif point_ai == 3:
            game_end = False
        if game_end:
            print("Choose an option. (R,P,S)")
            selection = input()
            if selection == 'R':
                selection = 'Rock'
                rock = True
            elif selection == 'P':
                selection = 'Paper'
                paper = True
            elif selection == 'S':
                selection = 'Scissor'
                scissor = True
            else:
                print("That's not an option")
                exit()
            print("=======================")
            print("You chose " + selection)
            ai_response = random.choice(option)
            print("The A.I chose " + ai_response)
            print("=======================")
            if ai_response == "Rock":
                while rock:
                    print("Oh! That's a tie no points.")
                    break
                while scissor:
                    print("Oh, you lost :( +1 to A.I")
                    point_ai = point_ai + 1
                    break
                while paper:
                    print("Looks like you beat the A.I! +1 Point")
                    point_player = point_player + 1
                    break
            elif ai_response == "Paper":
                while rock:
                    print("Oh, you lost :( +1 to A.I")
                    point_ai = point_ai + 1
                    break
                while scissor:
                    print("Looks like you beat the A.I! +1 Point")
                    point_player = point_player + 1
                    break
                while paper:
                    print("Oh! That's a tie no points.")
                    break
            elif ai_response == "Scissor":
                while rock:
                    print("Looks like you beat the A.I! +1 Point")
                    point_player = point_player + 1
                    break
                while scissor:
                    print("Oh! That's a tie no points.")
                    break
                while paper:
                    print("Oh, you lost :( +1 to A.I")
                    point_ai = point_ai + 1
                    break
            print("You have " + str(point_player) + " points")
            print("The A.I has " + str(point_ai) + " points.")
            print("=======================")
        else:
            if point_ai > point_player:
                print("The A.I won! RIP U")
            else:
                print("Dang! You won this time.")
            exit()

print("|=========================|")
print("|    Rock Paper Scissor   |")
print("|       (R) (P) (S)       |")
print("|=========================|")
print("Would you like to start? y/n")
answer = input()
if answer == "y":
    print("Welcome to the game of Rock Paper Scissors")
    start_game()
elif answer == "n":
    print('Well ok then.. Fine leave')
    exit()
else:
    print("That's not an option.")

game_end = True
while game:
    if point_player == 3:
        game_end = False
    elif point_ai == 3:
        game_end = False
    if game_end:

        ...

    else:
        if point_ai > point_player:
            print("The A.I won! RIP U")
        else:
            print("Dang! You won this time.")
        exit()

Could be simplified to:
while True:
    if point_player == 3 or point_ai == 3:
        break

        ...

if point_ai > point_player:
    print("The A.I won! RIP U")
else:
    print("Dang! You won this time.")

All of the
while rock:
    print("Oh! That's a tie no points.")
    break

Could be written as:
if rock:
    print("Oh! That's a tie no points.")

Instead of point_ai = point_ai + 1, you can shorten that to point_ai += 1. I would also separate out the code that decides who wins as it makes it a little bit easier to understand what is going on with the logic.
    winner = 'tie' # should be either 'player', 'tie', or 'ai'
    if ai_response == "Rock":
        if scissor:
            winner = 'ai'
        if paper:
            winner = 'player'
    elif ai_response == "Paper":
        if rock:
            winner = 'ai'
        if scissor:
            winner = 'player'
    elif ai_response == "Scissor":
        if rock:
            winner = 'player'
        if paper:
            winner = 'ai'

    if winner == 'tie':
        print("Oh! That's a tie no points.")
    if winner == 'player':
        print("Looks like you beat the A.I! +1 Point")
        player_points += 1
    if winner == 'ai':
        print("Oh, you lost :( +1 to A.I")
        ai_points += 1

It feels weird having the rock, paper, scissors Booleans to represent the choice the player made, and then having a string for the choice the ai made. I would use the same data type for both. If we stuck with using strings for both, and with some changes to some variable names, we get:
while True:
    if player_points == 3 or ai_points == 3:
        break
    print("Choose an option. (R,P,S)")
    player_choice = input()
    if player_choice == 'R':
        player_choice = 'Rock'
    elif player_choice == 'P':
        player_choice = 'Paper'
    elif player_choice == 'S':
        player_choice = 'Scissor'
    else:
        print("That's not an option")
        exit()
    print("=======================")
    print("You chose " + player_choice)
    ai_choice = random.choice(option)
    print("The A.I chose " + ai_choice)
    print("=======================")

    winner = 'tie' # should be either 'player', 'tie', or 'ai'
    if ai_choice == "Rock":
        if player_choice == 'Scissor':
            winner = 'ai'
        if player_choice == 'Paper':
            winner = 'player'
    elif ai_choice == "Paper":
        if player_choice == 'Rock':
            winner = 'ai'
        if player_choice == 'Scissor':
            winner = 'player'
    elif ai_choice == "Scissor":
        if player_choice == 'Rock':
            winner = 'player'
        if player_choice == 'Paper':
            winner = 'ai'

    if winner == 'tie':
        print("Oh! That's a tie no points.")
    if winner == 'player':
        print("Looks like you beat the A.I! +1 Point")
        player_points += 1
    if winner == 'ai':
        print("Oh, you lost :( +1 to A.I")
        ai_points += 1

    print("You have " + str(player_points) + " points")
    print("The A.I has " + str(ai_points) + " points.")
    print("=======================")

That looks worse in some ways, mostly because of the longer variable names, but everything is going to get better soon. I think now it's about time to break this game up into multiple functions. I like to have all of my print statements in a separate from the logic. In this case, I'm going to keep all of the print statements inside of the start_game function, and we'll put all of the logic outside of the start_game function. This helps us easily read through and understand what is going on, and then if we're having a problem, we can investigate the particular function whose logic is producing incorrect results. This also makes it easier to unit test the logic.
def get_players_choice():
    print("Choose an option. (R,P,S)")
    player_choice = input()
    if player_choice == 'R':
        player_choice = 'Rock'
    elif player_choice == 'P':
        player_choice = 'Paper'
    elif player_choice == 'S':
        player_choice = 'Scissor'
    else:
        player_choice = False

    return player_choice

def get_ai_choice():
    return random.choice(option)

def calculate_winner(player_choice, ai_choice):
    ''' returns either 'player', 'tie', or 'ai' '''
    winner = 'tie'
    if ai_choice == "Rock":
        if player_choice == 'Scissor':
            winner = 'ai'
        if player_choice == 'Paper':
            winner = 'player'
    elif ai_choice == "Paper":
        if player_choice == 'Rock':
            winner = 'ai'
        if player_choice == 'Scissor':
            winner = 'player'
    elif ai_choice == "Scissor":
        if player_choice == 'Rock':
            winner = 'player'
        if player_choice == 'Paper':
            winner = 'ai'
    return winner

def display_results(winner):
    if winner == 'tie':
        print("Oh! That's a tie no points.")
    elif winner == 'player':
        print("Looks like you beat the A.I! +1 Point")
    elif winner == 'ai':
        print("Oh, you lost :( +1 to A.I")

    print("You have " + str(player_points) + " points")
    print("The A.I has " + str(ai_points) + " points.")
    print("=======================")

def start_game():
    player_points = 0
    ai_points = 0
    while True:
        if player_points == 3 or ai_points == 3:
            break

        player_choice = get_players_choice()
        if player_choice is False:
            print("That's not an option")
            exit()

        print("=======================")
        print("You chose " + player_choice)
        ai_choice = get_ai_choice()
        print("The A.I chose " + ai_choice)
        print("=======================")

        winner = calculate_winner(player_choice, ai_choice)

        if winner == 'player':
            player_points += 1
        elif winner == 'ai':
            ai_points += 1

        display_results(winner)

    if ai_points > player_points:
        print("The A.I won! RIP U")
    else:
        print("Dang! You won this time.")

Now a little improvement as we refactor. This is kind of like chess, the more you do it, the more patterns just jump out at you. Let's start with the get_players_choice function. One pattern is that when asking for input from the user, instead of requiring 'R', 'P', 'S', we can grab the first character, lowercase it, and then check against that. We would then be accepting 'r', 'R', 'rock', 'Rock', or anything else that starts with the letter 'r'. Some other things:
    print("Choose an option. (R,P,S)")
    player_choice = input()

Is the same as
player_choice = input("Choose an option. (R,P,S)")

While I said I like to keep the print statements and the logic separate, display_results is a function that is obviously all about displaying text on the screen, and in the same way it would be expected that a function called get_players_choice is doing more than just logic. We're going to be using the input function, and that requires asking the user for input, and it requires telling them if the input is invalid. Anyhow, here is my revised get_players_choice function.
def get_players_choice():
    while True:
        player_choice = input("Choose an option (R,P,S), or push enter to exit")

        if not player_choice: # If they pushed enter
            return False

        first_char = player_choice[0].lower()

        if first_char == 'r':
            return 'Rock'
        elif first_char == 'p':
            return 'Paper'
        elif first_char == 's':
            return 'Scissor'

        print("That's not an option")

That display_choices and display_results can actually be combined together. And we end up with this as the final result. There are still some additional improvements that can be made, but what those are matters on what your goals are. Is it important that the code can be extended easily? Is performance important? Do you like object oriented designs? Etc.
''' A Rock Papers Scissors game '''
import random

def get_players_choice():
    while True:
        player_choice = input("Choose an option (R,P,S), or push enter to exit: ")

        if not player_choice: # If they pushed enter
            return False

        first_char = player_choice[0].lower()

        if first_char == 'r':
            return 'Rock'
        if first_char == 'p':
            return 'Paper'
        if first_char == 's':
            return 'Scissor'

        print("That's not an option")

def get_ais_choice():
    return random.choice(["Rock", "Paper", "Scissor"])

def calculate_winner(player, ai):
    ''' Takes either 'Rock', 'Paper', or 'Scissors', for both the player and the ai.
        returns either 'player', 'tie', or 'ai' '''

    if ai == "Rock":
        if player == 'Scissor': return 'ai'
        if player == 'Paper':   return 'player'

    elif ai == "Paper":
        if player == 'Rock':    return 'ai'
        if player == 'Scissor': return 'player'

    elif ai == "Scissor":
        if player == 'Rock':   return 'player'
        if player == 'Paper':  return 'ai'

    return 'tie'

def display_round_outcome(player_choice, ai_choice, winner, player_points, ai_points):
    print("=======================")
    print("You chose " + player_choice)
    print("The A.I chose " + ai_choice)
    print("=======================")

    if winner == 'tie':
        print("Oh! That's a tie no points.")
    elif winner == 'player':
        print("Looks like you beat the A.I! +1 Point")
    elif winner == 'ai':
        print("Oh, you lost :( +1 to A.I")

    print(f"You have {player_points} points")
    print(f"The A.I has {ai_points} points.")
    print("=======================")

def start_game():
    player_points = 0
    ai_points = 0

    while True:
        if player_points >= 3 or ai_points >= 3:
            break

        player_choice = get_players_choice()
        ai_choice = get_ais_choice()

        if player_choice is False:
            break

        winner = calculate_winner(player_choice, ai_choice)

        if winner == 'player':
            player_points += 1
        elif winner == 'ai':
            ai_points += 1

        display_round_outcome(player_choice, ai_choice, winner, player_points, ai_points)

    if ai_points > player_points:
        print("The A.I won! RIP U")
    elif ai_points == player_points:
        print("It's a tie.")
    else:
        print("Dang! You won this time.")

print("|=========================|")
print("|    Rock Paper Scissor   |")
print("|       (R) (P) (S)       |")
print("|=========================|")
print("Would you like to start? y/n")
answer = input()
if answer == "y":
    print("Welcome to the game of Rock Paper Scissors")
    start_game()
elif answer == "n":
    print('Well ok then.. Fine leave')
else:
    print("That's not an option.")

Let me know what questions you have, and what I wrote to quickly and didn't do a good job in explaining me decisions with. But I hope that kind of helps seeing how I would refactor this code, and hopefully you can see how much easier it is to read and debug the final version when you have everything split chunks of code. The difference is a lot more obvious when it's complicated code that you wrote a long time ago, or that something else wrote, and you're trying to figure out what is going on.

Edit:
My brother came to a very similar conclusion for how he would refactor this code, but he found a shorter way of checking who the winner is. Here is his calculate_winner function.
what_beats_what = {
  'Paper': 'Rock',
  'Scissors': 'Paper',
  'Rock': 'Scissors',
}

def get_winner(user_weapon, ai_weapon):
    if what_beats_what[user_weapon] == ai_weapon:
        return 'USER'
    elif what_beats_what[ai_weapon] == user_weapon:
        return 'AI'
    else:
        return 'TIE'

Also, it's impossible for the game to end in a tie as whoever reaches 3 points first will always be the winner.


Pairwise distance and residual calculation I have a code for calculating the pairwise distances and the residuals of my data (X, Y, Z). Data is quite large (average of 7000 rows) and so my interest is code efficiency. My initial code is

import tkinter as tk
from tkinter import filedialog
import pandas as pd
import, numpy as np
from scipy.spatial.distance import pdist, squareform

root = tk.Tk()
root.withdraw()
file_path = filedialog.askopenfilename()

data = pd.read_excel(file_path)
data = np.array(data, dtype=np.float)
npoints, cols = data.shape

pwdistance = np.zeros((npoints, npoints))
pwresidual = np.zeros((npoints, npoints))
for i in range(npoints):
    for j in range(npoints):
        pwdistance[i][j] = np.sqrt((data[:,0][i]-data[:,0][j])**2 + (data[:,1][i]-data[:,1][j])**2)
        pwresidual[i][j] = (data[:,2][i]-data[:,2][j])**2

With the pwdistance, I changed it to the following below which works extremely good.

pwdistance = squareform(pdist(data[:,:2]))

Is there a pythonic way of calculating my pwresidual, so I do not need to use a loop and to enable my code to run faster?

Let's start by setting
col2 = data[:,2]

to avoid some repetition. (If I knew what was in the data array then maybe I could pick a better name, but all I have to go on is what was in the post.)
Now here are two possible approaches to computing pwresidual:

pwresidual[i,j] is the result of an operation on col2[i] and col2[j]. You might recognize this as being similar to an outer product in mathematics — except that the operation is subtraction rather than multiplication.
But in NumPy every universal function has an "outer" counterpart, and np.subtract is a universal function, so all we need is:
 pwresidual = np.subtract.outer(col2, col2) ** 2

Alternatively, we can use NumPy's broadcasting mechanism, combined with np.newaxis to ensure every pair of items gets operated on:
 pwresidual = (col2[:,np.newaxis] - col2[np.newaxis,:]) ** 2


Is there a better way to use SendInput? I am using an Xbox controller to send data to my computer, and am using the SendInput method to handle keys. I was wondering if there was any other, better way to do this.

INPUT Input = { 26 };
Input.type = INPUT_KEYBOARD;
Input.ki.dwFlags = VK_UP;
SendInput(1, &Input, sizeof(INPUT));
std::cout << "Up";

Are you wanting to direct this to a specific application? It's usually better to send WM_KEYDOWN and/or WM_KEYUP using the SendMessage function.

If not, then I would suggest using the keybd_event function. You can find some good examples on Code Project


Joining a product-application-customer relationship using Java 8 Streams I have three classes: product, customer and application.

The schema of these classes are as follows:

class application {
     String productID;
     String customerID;
     String applicationId;
     String name;
 ....
  // getters and setters and associated constructors
}

class product {
    String name;
    String ID;
    ...
  // constructors and getters and setters
 }

class customer {
    String name;
    String ID;
    ...
    // constructors and getters and setters
}

The only way of connection between product and customer is through the application.

The problem in hand is to retrieve all products with their associated customers (appID and customerID) in this JSON format.

 [
   {
   "product": {
         // product details
    }
   "customers": [ {
         "application": <value_appID>,
         "ID": <value_customerID> } ]
  }
]

I have done this using a nested for loop:

for (Product product : products) {
    ProductInfo prodInfo = new
    ProductInfo();
    prodInfo.setProduct(product);
    List<CustomerInfo> associatedCustomerList = new ArrayList<>();
    for (Object res : searchResults.getResult()) {
        if ((product.getId()).equals((String) ((Map) res).get("productID"))) {
            CustomerInfo associatedCustomer = new CustomerInfo();
            associatedCustomer.setCustomerID((String) ((Map) res).get("customerID"));
            associatedCustomer.setApplicationId((String) ((Map) res).get("appId"));
            associatedCustomerList.add(associatedCustomer);
        }
        prodInfo.setCustomers(associatedCustomerList);
    }
    productInfo.add(prodInfo);
}

Here, searchResults contain the result from List<? extends Object>. CustomerDetails contain appId and customerId as attributes. ProductInformationWithAssociatedCustomer is the response class.

Furthermore, I have converted this into the following which utilizes Java 8 Stream API:

 List<ProductInfo> prodList = products.stream()
    .map(product -> {
        List<CustomerInfo> customerList =searchResults.getResult().stream()
            .filter(searchResult -> (product.getId()).equals((String) ((Map) searchResult).get("productID")))
            .map(searchResult -> new CustomerInfo((String) ((Map) searchResult).get("customerID"),(String) ((Map) searchResult).get("appId")))
            .collect(Collectors.toList());
        return new ProductInfo(product, customerList);
    }).collect(Collectors.toList());

This code is working fine.

The questions I have are:

Am I making correct/ optimal use of Java 8 stream features?
Provided, I want to do it using Java 8 Stream APIs only, should I do it in any better way?
What are the factors I need to consider while optimizing this type of codes.

Using the appropriate types

Your are repeatedly casting searchResult into a Map, the first suggestion I will make is to cast it once first to make subsequent references easier to read:

// use Map<String, Object> if you want to be less strict on the value type,
// at the expense of having to do Object.toString() later
List<Map<String, String>> searchResultDetails =
                                (List<Map<String, String>>) searchResults.getResult();

Rationale: Avoid code repetition and makes the one-time cast clearer to understand

Grouping the search results into a usable Map

Instead of traversing your searchResultMap for each product, consider generating an intermediary Map that gives you the list of CustomerDetails grouped by the product ID:

Map<String, List<CustomerDetails>> customerDetailsByProduct =
    searchResultDetails.stream()
        .collect(Collectors.groupingBy(map -> map.get("productID"),
                Collectors.mapping(map -> new CustomerDetails(map.get("customerID"),
                                            map.get("appId")), Collectors.toList())));

Rationale: Consider when you have \$n\$ products and a result for each of them. Your current solution will effectively be iterating through them, and iterate through the \$n\$ results for the one matching product. Therefore, you should start with grouping your results first by the product ID, so that the retrieval later via the Map interface will potentially be more efficient.

Process the product list as the final step

With the above map, it's just a matter of looping through your products and creating an instance of ProductInformationWithAssociatedCustomer with the customer details, if present:

// BTW do you really need such long class names?
List<ProductInformationWithAssociatedCustomer> results =
    products.stream()
            .map(product -> new ProductInformationWithAssociatedCustomer(product,
                                    customerDetailsByProduct.getOrDefault(product.getId(),
                                            Collections.emptyList())))
            .collect(Collectors.toList());


Python: Print matrices as figure I have very large data files (10 to 40 GB) which I want to plot as figures. A data file contains t matrices of size n x n. A data file of t=3 matrices of size n looks like:

1 2
3 6
1 2
3 3
4 2
5 1

Here is the code that does the job:

import itertools as it
import matplotlib.pyplot as plt
import time

def printImage(M, k):
    figobj = plt.figure()
    fig = plt.imshow(M, interpolation='nearest')
    fig.set_cmap('hot')
    fig.axes.get_xaxis().set_visible(False)
    fig.axes.get_yaxis().set_visible(False)
    plt.axis('off')
    plt.tight_layout()
    plt.savefig('%05d' % k + '.png', bbox_inches='tight', pad_inches=0, dpi=300)
    plt.close(figobj)

n = 1000
t = 1000

t0 = time.clock()
with open('data', 'r') as f:
    for i in range(t):
        try:
            items = [list(map(float, i.split())) for i in it.islice(f, n)]
        except:
            raise
        else:
            printImage(items,i)
        print(str(i) + '/' + str(t))

t1 = time.clock()
print(t1-t0)

The processing speed for 1000 matrices of size 1000 x 1000 of this code is shown below:

The time is increasing and it takes about one second per image. I would like to know if I can increase the processing speed if I don't want to decrease quality?

First, a baseline timing. Using this code to generate 5 random matrices:

import numpy as np

n, t = 1000, 5

with open("data", "w") as f:
    for _ in range(t):
        np.savetxt(np.random.randint(1000, size=(n, n)))

Your code takes about 10 seconds to execute on my machine.

Second, small stylistic fixes. Your try...except...else code is literally what Python basically does for every line anyway:

It tries to execute the line.
If this fails, raise an appropriate error.
Otherwise go on with the next line.

So you can just remove that. In any case, you should never have a bar except, unless you are really sure what this means. You will not be able to abort the process using CTRL+C, for example.

You should also rename your function from printImage to print_image, to adhere to Python's official style-guide, PEP8.

Then, to improve the speed. This is quite tricky (as you might have discovered yourself already). These are the things I tried, but which failed to improve the time:

Create the figure only once and reuse it. This was recommended here.
Get rid of the GUI drawing completely, by using the underlying objects. This was recommended here.
Use pandas.read_csv with a hack to read an iterator, as shown here.

What did make a huge difference is using 2. from above and using the multiprocessing module:

import itertools as it
import time

from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure

import matplotlib.pyplot as plt
import multiprocessing

def timeit(func):
    def wrapper(*args, **kwargs):
        starting_time = time.clock()
        result = func(*args, **kwargs)
        ending_time = time.clock()
        print('Duration: {}'.format(ending_time - starting_time))
        return result
    return wrapper

@timeit
def print_image_multiprocessing(n, t):
    print("print_image_multiprocessing")
    p = multiprocessing.Pool(4)
    with open("data", "r") as f:
        items_gen = ([list(map(float, i.split())) for i in it.islice(f, n)]
                     for i in range(t))
        p.starmap(print_image_no_gui, zip(items_gen, it.count()))

def print_image_no_gui(items, i):
    fig = plt.Figure()
    ax = fig.add_subplot(111)
    image = ax.imshow(items, interpolation='nearest')
    image.set_cmap('hot')
    fig.tight_layout()
    plt.axis('off')
    image.axes.get_xaxis().set_visible(False)
    image.axes.get_yaxis().set_visible(False)
    canvas = FigureCanvas(fig)
    canvas.print_figure('mult%05d' % i + '.png', bbox_inches='tight',
                        pad_inches=0, dpi=300)
    print(str(i) + '/' + str(t))

if __name__ === "__main__":
    print_image_multiprocessing(1000, 5)

This takes less than 3 seconds (with the 4 workers), compared to 10 seconds, on my machine. For 10 images it needs 6 seconds, instead of 14. Not ideal, but I don't see any other obvious improvements.

Note that I removed the tight_layout, because it raises a warning per plot. According to this issue here, one can work-around it by using fig.set_tight_layout(True), but this then raises a different warning, complaining about the axes not being drawable. Since you remove the axis anyways, removing that call does no harm.


Creating new async tasks In the past, I have used AsyncTasks to perform network requests for my Android app. I recently switched to RxJava to be able to cancel the requests when the user exits an activity. I have created a system to easily create new async tasks via RxJava which all cancel when a user exits an activity. I have attached some basic code that I hope somebody could give me some pointers on.

public class BaseActivity extends AppCompatActivity{

    ArrayList<OnDestroyListener> listeners = new ArrayList<>();

    @Override
    protected void onDestroy() {

        for(OnDestroyListener listener : listeners){
            listener.onDestroy();
        }

        super.onDestroy();
    }

    public void addOnDestroyListener(OnDestroyListener listener){
        listeners.add(listener);
    }

    public interface OnDestroyListener{
        void onDestroy();
    }
}

public class Tools{
    public static <E> void observe(Callable<E> callable, SingleSubscriber<E> subscriber, BaseActivity activity){
        final Subscription sub = Single.fromCallable(callable)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(subscriber);

        if(activity == null){
            return;
        }

        activity.addOnDestroyListener(new BaseActivity.OnDestroyListener() {
            @Override
            public void onDestroy() {
                sub.unsubscribe();
            }
        });
    }
}

public class Endpoint{
    public void makeGetRequestAsync(final String url, final SingleSubscriber<String> subscriber, BaseActivity activity){
        Tools.observe(new Callable<String>() {
            @Override
            public String call() throws Exception {
                return makeGetRequestSync(url);
            }
        }, subscriber, activity);
    }
}

public class SampleActivity extends BaseActivity{

    Endpoint endpoint = new Endpoint();

    void onButtonClick(View v){
        endpoint.makeGetRequestAsync("https://someurl.com", new SingleSubscriber<String>() {
                    @Override
                    public void onSuccess(String result) {
                        //Request success
                    }

                    @Override
                    public void onError(Throwable error) {
                        //Request failure
                    }
                }, this);
    }
}

I know that I do not have a real coding problem, since this method has been working very well so far, but I just want to know if anything about this process is inherently wrong, as I am using it throughout my app.

I would start by trying to make a separate package for making the requests, something like a presenter(MVP pattern - MVP in Android).
Because, the way you have it now, it is hard to be tested and inside of the activity you have more logic, breaking a bit the SRP principle( SRP ).

Now, all it is left to do is to connect the activity and the presenter and that you can do using a callback.
Also, as a bonus, all the stuff you need, presenter, etc, you can add to a dagger module.


Storing array inside closure Is storing array values inside of a closure considered to be bad practice?  I having been trying to decide if I should just use a standard object with key value pair.  This is not the method I am using to populate arrays, but this does show how i create functions to store values.

Also, I'm wondering if this is technically a closure.

http://jsfiddle.net/canoeBoy/sn3wgs0w/

<input type="button" onclick="alert(Test1(0,0,'array'));
alert(Test2(0,0,'array'));
alert(Test3(0,0,'array'));">

function makeClosures(){
    var nameArr=["Test1","Test2","Test3","Test4","Test5","Test6","Test7"];
    for(var i=0;i<nameArr.length;i+=1){
        var nam=nameArr[i];
        window[nam]=funcsRun(nam,0,1);
    }
}

function funcsRun(nam,index,action){
    var a=nam;
    var arr=[];

    return function(value,index,action) {
        if(action=='array'){

        }
        else if(action=='copyEntireArray'){
            arr=value;
        }
        else if(action=='resetArray'){
            arr=[];
        }
        else if(action=='copyToIndex'){
            arr[index]=value;
        }

        else if(action=='indexValue'){
            return arr[index];
        }
        else if(action=='push'){
            arr.push(value);
        }
        return arr;
    };
};

makeClosures();

for(i=0;i<100;i+=1){
   Test1(Math.floor((Math.random() * 100) + 1),i,'copyToIndex');
   Test2(Math.floor((Math.random() * 100) + 1),i,'copyToIndex');
   Test3(Math.floor((Math.random() * 100) + 1),i,'copyToIndex');

}

Okay, your question is very ambiguous, but I'll give it a shot. First, is seems like you're confused about what a closure is. A closure is simply accessing a variable that was not defined inside that function.

For instance, in:

function foo () {
    var bar = 9;
    function bla () {
        return bar;
    }
}

bar can be accessed because of closure. Read this if you still have questions about that.

Now regarding your use case, it seems like what you want is a cache. You don't want to go to the server every time to get the same information, you want the user to get information that has already been requested. That's the use case of a cache.

This is how you create a cache in JavaScript:

var cache = {};

Now you need a way to index your data. Since it seems like you get it from a db, you'll have an ID available, index it by that. So your app will look something like:

$.ajax(....).done(function (data) {
    // Cache your data
    cache[data.id] = data;
});

Now before every db request you can check if the data is in the cache or not. If it is you can use the copy in the cache, if not issue the request to the server.


Simple Sudoku Solver i have made a simple sudoku solver which is a puzzle game where the player has to figure out the empty cell and checks which numbers are absent from the corresponding row, column.

how can I improve it further?

#include <iostream>

int isAvailable(int puzzle[][9], int row, int col, int num)
{
    for (int i = 0; i<9; ++i)
    {
        if (puzzle[row][i] == num) return 0;
        if (puzzle[i][col] == num) return 0;
    }
    return 1;
}

int solveSudoku(int puzzle[][9], int row, int col)
{
    if (row<9 && col<9)
    {
        if (puzzle[row][col] != 0)
        {
            if ((col + 1)<9) return solveSudoku(puzzle, row, col + 1);
            else if ((row + 1)<9) return solveSudoku(puzzle, row + 1, 0);
            else return 1;
        }
        else
        {
            for (int i = 0; i<9; ++i)
            {
                if (isAvailable(puzzle, row, col, i + 1))
                {
                    puzzle[row][col] = i + 1;
                    if ((col + 1)<9)
                    {
                        if (solveSudoku(puzzle, row, col + 1)) return 1;
                        else puzzle[row][col] = 0;
                    }
                    else if ((row + 1)<9)
                    {
                        if (solveSudoku(puzzle, row + 1, 0)) return 1;
                        else puzzle[row][col] = 0;
                    }
                    else return 1;
                }
            }
        }
        return 0;
    }
    else return 1;
}

void printSudoku(int puzzle[9][9])
{
    for (int i = 0; i<9; ++i)
    {
        for (int j = 0; j<9; ++j) {
            std::cout << puzzle[i][j] << " ";
        }
        std::cout << "\n";
    }
}

int main()
{
    int puzzle[9][9] = {
    { 3, 0, 6, 5, 0, 8, 4, 0, 0 },
    { 5, 2, 0, 0, 0, 0, 0, 0, 0 },
    { 0, 8, 7, 0, 0, 0, 0, 3, 1 },
    { 0, 0, 3, 0, 1, 0, 0, 8, 0 },
    { 9, 0, 0, 8, 6, 3, 0, 0, 5 },
    { 0, 5, 0, 0, 9, 0, 6, 0, 0 },
    { 1, 3, 0, 0, 0, 0, 2, 5, 0 },
    { 0, 0, 0, 0, 0, 0, 0, 7, 4 },
    { 0, 0, 5, 2, 0, 6, 3, 0, 0 } };

    solveSudoku(puzzle, 0, 0);
    printSudoku(puzzle);
}

Your isAvailable() is wrong.

You check if a number is within the row or col. But you also need to check if it is within the same (3*3) square.

int isAvailable(int puzzle[][9], int row, int col, int num)
{
    int sqCol = col % 3 * 3;
    int sqRow = row % 3 * 3;
    for (int i = 0; i<9; ++i)
    {
        if (puzzle[row][i] == num) return 0;
        if (puzzle[i][col] == num) return 0;

        // You need to add this test.
        if (puzzle[sqRow + (i % 3)][sqCol + (i / 3)] == num) return 0;
    }
    return 1;
}

Rather than having you loop from 0 and then using i+1 why not loop from 1?

for (int i = 0; i<9; ++i)

// I would just do
for (int i = 1; i<=9; ++i)
     Now intuitively use i

Your test for reaching the end of line and end of col is in several places. Rather than test on the call. Just increment the col and handle overflow at the top of the function (in one place). This will greately simplify the whole thing.

int solveSudoku(int puzzle[][9], int row, int col)
{
    if (col == 9) {
        col = 0;
        row++;
    }
    if (row == 9) {
        return 1;
    }

    if (puzzle[row][col] != 0) {
        return solveSudoku(puzzle, row, col + 1);
    }

    for (int i = 1; i <= 9; ++i)
    {
        if (isAvailable(puzzle, row, col, i))
        {
            puzzle[row][col] = i;
            if (solveSudoku(puzzle, row, col + 1))
                return 1;
            }
        }
    }
    puzzle[row][col] = 0;
    return 0;
}


Using [ChildActionOnly] for generating links I have a view which displays a list of items, in each row I'm going to have a link, a link in each row points to different location So base upon a property called CertificationType I have to generate an address, for example if the type equals to 'BirthCertificate' I need to fetch the address from a table called BirthCertificates. So I decided to use a ChildActionOnly action method because in my controller I can easily access to context and fetch the result, That why I didn't use HTML helpers.

View:

foreach(var item in Model)
{
   //...

}

Controller:

public class MainController : Controller
{
    //...
    private readonly IUserCertificateService _certificateService;
    public MainController(IUserCertificateService certificateService)
    {
        _certificateService = certificateService;
        //...
    }
    [ChildActionOnly]
    public ContentResult GetFilePath(CertificateType type, Guid certificateFkId)
    {
        var fileName = "";
        switch (type)
        {
            case CertificateType.Shenasnameh:
            {
                var result = _birthCertificateService.GetBirthCertificateById(certificateFkId);
                fileName = string.Format("/Content/Files/UserDocs/{0}/{1}", result.User.UserName, result.ShenasNamehFileName);
            }
            break;
            //....
        }
        return Content(fileName);
    }
}

It works like a charm. But I wanted to know Is there a better solution?

Any idea?

This would appear to be an abuse of child actions. Child Actions are meant to compose smaller items of your interface that you would need to re-use and load up part (albeit a small part) of the MVC pipeline to provide this functionality.

Furthermore, it is giving your Controller responsibility for a unit of work that you may eventually want to reuse elsewhere. Can you really not see a need to work out a full path to a file in the future?

You mention this:

  in my controller I can easily access to context and fetch the result, That why I didn't use HTML helpers.

I can understand you not wanting to use HTML Helpers for this, as you need to make a request to a service to find out information about the user and the filename. Fine, but your reference to requiring access to a context, what context? Your service? This doesn't seem to warrant, at least in my eyes, a full controller action.

In my opinion, and this is an opinion-based "how is best to do this" question rather than code review, this method is best suited on your model. Extending your model to have a method that would return a path to the file that you can subsequently output seems like a much more logical place for this type of method. That way, should you need to get a path again in a different controller, you do not need to duplicate code and/or refactor the method into another location at a later date.

Another option would be to construct a ViewModel for each item in your (current) Model, which contains this URL for output. That way you can have a normal method on your controller, and call it whilst constructing the VM in the main Action.

Finally, have your models where the filename is sourced from a different column implement an interface that allows you to get a filename, and fallback to using URL Helpers.

Something as simple as below would suffice:

interface IFileNameProvider
{
    GetFileName();
}

Each implementation would return the filename from its appropriate property as an attempt at model-level (not DB-level) normalisation (of course you could normalise the filename at DB level). That way you can use standard URL helpers after getting your filename from this method, and your username through a similar method.


Get AD Users' Latest Last Logon Dates across Multiple DCs I was recently asked to help our Spanish BU to audit their AD for inactive accounts.

Grabbing a script from online I gave them this: https://gallery.technet.microsoft.com/scriptcenter/Get-Active-Directory-User-bbcdd771

However that doesn't scale well when there's multiple users; as this takes one account then manually searches for the maximum last logon on any domain controller, rather than pulling back the values from all DCs then performing an aggregate function (which can then work the same way for 1 or many accounts).

As such I wrote this:

[string]$DCNameFilter = "ES*" #only get Spanish DCs (i.e. our company's naming convention prefixes server names with 2 char country iso code)
[string]$SearchBase = 'OU=es,DC=eu,DC=myCompany,DC=com' #only look within the Spanish OU; our OUs are under their collective region's domain (i.e. EU) within the company

#filter down to just the ES domain controllers
$DCs = Get-ADDomainController -Filter {Name -like $DCNameFilter} | Select -expand Name

#for each of the above domain controllers
$DCs | %{
    #get a list of enabled users & their last logon dates
    Get-AdUser -SearchBase $SearchBase -Filter {Enabled -eq $true} -Properties LastLogonDate -Server $_ `
    | Select-Object samAccountName, Name, LastLogonDate #filter to only the columns we're interested in
} | Group-Object -Property samAccountName | %{ #group results by account name
    #return the account name, full name, & their latest logon date
    $_ | select Name, @{Name='Full Name';Expression={$_.Group | select -ExpandProperty Name -first 1}}, @{Name='LastLogonDate';Expression={$_.Group | Measure-Object -Property LastLogonDate -Maximum | select -ExpandProperty Maximum}}
} | sort Name #nb: name is sAmAccountName; column name changed as result of earlier group-object statement.

I've seen lots of examples similar to the technet script above used before, but have never seen someone using the aggregate/group-object approach, so wondered if there was a reason for this (e.g. some inefficiency I'd not considered); hence posting here.

NB: I'm also aware of the Search-ADAccount -AccountInactive option, which would show inactive accounts; but the request was to return the last logon dates rather than simply what's inactive; so I provided both options so the local team could determine which was more suited to their requirements.

Aliases

You're used to my reviews by now so you're probably tired of me saying this, but avoid aliases and abbreviations (% vs ForEach-Object, Select vs Select-Object, -expand vs -ExpandProperty, sort vs Sort-Object, etc.).

Backticks ` as line continuation

Try to avoid shortening lines with backtick where possible. The backticks are hard to see / easy to miss.

Note that you can end a line with a pipe | or an operator and continue on the next line without the backtick, which I think is a much more flexible solution:

Get-ADObject -Filter { whatever } |
Sort-Object BySomething |
Select-Object Thing1,Thing2,Thing3 |
Where-Object {
    $_.A -eq 5 -and
    $_.Z -like '*what*' -and
    $_.BoolProp
} |
Format-Table

As an added bonus, it doesn't confuse the syntax highlighting on these sites!

Domain Controller Discovery

When finding a domain controller in a certain region, you might consider filtering on Site. Nothing wrong with going by your naming convention, although it's more likely for that to change, or for a short pattern like ES* to match something else; I'm sure you've considered that and your pattern is fine, just offering another suggestion.

I also like to add -Discover, -ForceDiscover, and -Service ADWS to ensure that you are finding DCs that are available and usable with PowerShell. Combined:

$DCs = Get-ADDomainController -Discover -ForceDiscover -SiteName Spain -Service ADWS | Select-Object -Expand Name

Logon Dates

You're probably already familiar with the logon date attributes in AD, but I'll summarize:

LastLogon — Updated every time a user logs on, but only on the domain controller that authenticated the user. This value is not replicated.
LastLogonTimestamp — This value is replicated, but to avoid heavy replication traffic it's not updated every time, so you sacrifice accuracy (it could be as much as 2 weeks off by default), but you only have to query a single DC to get the value. This value is also annoying to turn into an actual date.
LastLogonDate — This is not actually in AD. It's provided by the PowerShell cmdlets, and it's a real [DateTime] object that has the same value as LastLogonTimestamp, which makes it really convenient to use and filter on.

So, depending on how accurate you really need this process to be, you might avoid querying all the DCs in the first place and just take LastLogonDate as being "Close Enough" for your purposes. It would simplify things greatly if that's acceptable.

The thing is, this also reveals a problem in your script. You are already using LastLogonDate, you're just querying it from every DC instead of using LastLogon. As long as replication is working correctly, that value will always be the same, so querying multiple DCs is unnecessary.

If you want the precision, you need to use LogonDate (and do the appropriate conversions like in the technet script you linked to). This is probably why Group-Object is not often used. Because it's not so trivial to treat this attribute directly as a [DateTime].

Search-ADAccount

I'm not sure I understand the aversion to using Search-ADAccount. The object returned is still an AD account object, and it includes the LastLogonDate property so you can return that.

After re-reading it I understand; you're not filtering on any specific date in this script. So you're returning all users and their dates.

Simplification

Based on what I wrote above, I might suggest a more simple solution (I know this isn't SO but, it's basically a one-liner...):

$DC = Get-ADDomainController -Discover -ForceDiscover -SiteName Spain -Service ADWS | Select-Object -Expand Name -First 1
Get-ADUser -SearchBase $SearchBase -Filter { Enabled -eq $true } -Properties LastLogonDate -Server $DC |
Sort-Object SamAccountName |
Select-Object SamAccountName,Name,LastLogonDate

I would even add that because the attribute is replicated, there's no need to query a Spanish DC; you can leave out the whole discovery part and just let Get-ADUser use the logon server, or use discovery but don't limit it to a site. It should in theory be more efficient to simply query the closest DC to where the script is running.


Gallery of employees with dynamic filtering I'm trying to learn how to write better, more efficient JavaScript code and wanted to run this function I'd written by you and see if people can suggest an improved method.

It's basically a people filter based upon two variables.

Demo.

It works fine, but if additional categories come in (so far there are three) then the code would become redundant.

var family = 'director';
var expertise = 'asset';

function showConsultant(){
   $('.profile').stop(true,true).fadeOut(100);
   $('.profile[data-family="'+family+'"][data-expertise="'+expertise+'"]').delay(101).fadeIn();
}

showConsultant();

$('.top-level li').on('click', function() {

  $('.top-level li').removeClass('selected');
  $(this).addClass('selected');

  if( $(this).index() === 0 ){
     family = 'director';
     showConsultant();
  } else if( $(this).index() === 1 ){
      family = 'consultant';
      showConsultant();
  } else if( $(this).index() === 2 ){
      family = 'support';
      showConsultant();
  }

});

$('.second-level li').on('click', function() {

  $('.second-level li').removeClass('selected');
  $(this).addClass('selected');

  if( $(this).index() === 0 ){
     expertise = 'asset';
     showConsultant();
  } else if( $(this).index() === 1 ){
      expertise = 'insurance';
     showConsultant();
  } else if( $(this).index() === 2 ){
      expertise = 'wealth';
     showConsultant();
  }

});

Make a lookup table. Then access by index:

var expertises = ["asset", "insurance", "wealth"];
expertise = expertises[$(this).index()];
showConsultant();

If you're worried about going out of bounds, add a range check:

var expertises = ["asset", "insurance", "wealth"];
var index = $(this).index();
if (0 <= index && index < expertises.length) {
    expertise = expertises[index];
    showConsultant();
}

You could even globally define these lists somewhere, so you could write enums.getExpertise(index).


Django API Implementation I am building a backend to a mobile application that will be hosted on a Django site connected to a PostgreSQL database.

I have never built anything to accomplish this before and this is my first go at it. I have not studied this type of application before so please let me know if the below code follows best practices for this task, is secure, and doesn't have any obvious problems.  If there is an industry standard for this that is very different, please let me know what it is and why it is preferred.

My client connects via the view readJSON:

@csrf_exempt
def readJSON(request):
    if request.method == 'POST':
        try:
            c = connections['postgres_db'].cursor()
            json_data = json.loads(request.body)
            if json_data['tag'] == 'register':
                return HttpResponse(cc().register(c, json_data))
            elif json_data['tag'] == 'syncprofile':
                return HttpResponse(cc().syncProfile(c, json_data))
################ A long list of other possible tags
            else:
                raise Http404
        finally:
            c.close()
    else:
        raise Http404

I have a separate class that holds all the code to handle the incoming JSON requests. This is one such function.

    def register(self, c, json_data):
    import bcrypt as bc
    salt = bc.gensalt()
    pwrd = json_data['data']['password']
    hash = bc.hashpw(pwrd, salt)
    try:
        c.execute("INSERT INTO profiles VALUES (DEFAULT, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)",
            (json_data['data']['email'], hash, salt, json_data['data']['date_created'],
            json_data['data']['state_lvl'], True,
            json_data['data']['first_name'], json_data['data']['last_name'],
            json_data['data']['sex'], json_data['data']['age'],
            json_data['data']['state'], json_data['data']['country'],
            json_data['data']['language'], json_data['data']['device_type'],
            json_data['data']['device'], json_data['data']['device_width'],
            json_data['data']['device_height'], json_data['data']['device_screen_density']
        ))
        json_response = json.dumps({"success": 1, "errors": 0})
        return HttpResponse(json_response, mimetype="application/json")
    except Exception,e:
        json_response = json.dumps({"success": 0, "errors": 1, "msg": str(e)})
        return HttpResponse(json_response, mimetype="application/json")

And here is the JSON structure for the above function.

    {
   "tag":"register",
   "data":{
      "email":"email@email.com",
      "password":"app123",
      "date_created":"07/10/1967",
      "state_lvl":"1",
      "first_name":"John",
      "last_name":"Smith",
      "sex":"m",
      "age":23,
      "state":"CA",
      "country":"USA",
      "language":"english",
      "device_type":"phone",
      "device":"Nexus-5",
      "device_width":400,
      "device_height":800,
      "device_screen_density":331
   }
}

readJSON()

Returning HTTP 404 ("Not Found") is improper, unless you are deliberately sending obfuscatory responses as a kind of security-by-obscurity measure.  If you require a POST, and the client sends anything but a POST, the proper response should HTTP 405 ("Method Not Allowed").  For a body that does not have an appropriate JSON tag, I think that the appropriate response would be a non-specific HTTP 400 ("Bad Request").

In if-else branches, prefer to put the branch with less code first, to get it out of the way and reduce mental load.  Usually, that means putting the error handler first.  As a bonus, you can eliminate one level of indentation.

Instead of the try-finally construct, use a with block for the database cursor.

Assuming that there is an exact correspondence between the JSON tags and the method names of cc(), you could dispatch dynamically.  (Your syncProfile() method doesn't match 'syncprofile', but you could rename your methods accordingly.)

@csrf_exempt
def readJSON(request):
    if request.method != 'POST':
        raise Http405
    json_data = json.loads(request.body)

    # Whitelist allowable function calls for security
    if json_data['tag'] not in ['register', 'syncprofile', … ]:
        raise Http400

    cc_method = getattr(cc(), json_data['tag'])
    with connections['postgres_db'].cursor() as c:
        return HttpResponse(cc_method(c, json_data))

register()

Imports should be listed at the top of the file.  I wouldn't alias bcrypt as bc, as the latter sacrifices clarity just to save a few characters.

There are a lot of columns to be inserted, and a long parameter list.  I think it would be less error prone if you used named placeholders.

import bcrypt

def register(self, c, json_data):
    attr = dict(json_data['data'])
    attr['salt'] = bcrypt.gensalt()
    password = attr['password']
    attr['hash'] = bcrypt.hashpw(password, attr['salt'])
    attr['true'] = True
    try:
        c.execute("""INSERT INTO profiles VALUES (DEFAULT
                         , %(email)s
                         , %(hash)s
                         , %(salt)s
                         , %(date_created)s
                         , %(state_lvl)s
                         , %(true)s
                         , %(first_name)s
                         , %(last_name)s
                         , %(sex)s
                         , %(age)s
                         , %(state)s
                         , %(country)s
                         , %(language)s
                         , %(device_type)s
                         , %(device)s
                         , %(device_width)s
                         , %(device_height)s
                         , %(device_screen_density)s
                     )""", attr);
        json_response = json.dumps({"success": 1, "errors": 0})
    except Exception, e:
        json_response = json.dumps({"success": 0, "errors": 1, "msg": str(e)})
    return HttpResponse(json_response, mimetype="application/json")

It's a bit odd that you let the client specify the profile creation date.  I would just let the database issue a timestamp.

I think that the long parameter list is indicative of a problematic database schema.  If you ever want to add another attribute to the user profile, that would require a schema alteration.  The profiles table should probably be split into an accounts table containing the essentials and an account_attributes table that stores arbitrary key-value pairs.

CREATE TABLE accounts
( id SERIAL PRIMARY KEY
, email TEXT NOT NULL
, hash TEXT NOT NULL
, salt TEXT NOT NULL
, date_created DATE NOT NULL DEFAULT statement_timestamp()
);

CREATE TABLE account_attributes
( account_id INTEGER NOT NULL
, attribute TEXT NOT NULL
, value TEXT NOT NULL
, PRIMARY KEY (account_id, attribute)
, FOREIGN KEY (account_id) REFERENCES accounts (id)
);


Transform a Japanese word to furigana I developed a script to transform a Japanese word in Furigana thanks to the jisho website. But the code is very ugly, especially the extractHiraganaFromHTML and filterBetween functions. What kind of improvements are possible?

module Main
where

import Network.HTTP
import Network.URI
import Text.HTML.TagSoup
import Data.Text (unpack)
import Data.Text.Encoding (decodeUtf8)
import Data.ByteString.Char8 (pack)
import System.Environment (getArgs)

jishoUrlFor :: String -> String
jishoUrlFor word = (escapeURIString isUnescapedInURI) $ "http://jisho.org/word/"++word

getJishoHTML :: String -> IO String
getJishoHTML w  = simpleHTTP (getRequest $ jishoUrlFor w) >>=  getResponseBody

extractHiraganaFromHTML :: String -> String
extractHiraganaFromHTML = unicodeToString . strip . innerText . filter(~== TagText "") . filterBetween . head . partitions  (~== "<span class=\"furigana\">") . parseTags

convertWordToHiragana :: String -> IO String
convertWordToHiragana w = do
    html <- getJishoHTML w
    return $ extractHiraganaFromHTML html

filterBetween :: [Tag String] -> [Tag String]
filterBetween p = fst $ sfoldl step ([],0) $  p
where step (x,a) tag | tag ~== "<span>" = (tag:x,a+1)
      step (x,a) tag | tag ~== TagClose "span" = (tag:x,a-1)
      step (x,a) tag = (tag:x,a)

      sfoldl step (a,1) (TagClose "span":xs) = (reverse (TagClose "span":a),0) -- stop condition
      sfoldl step (a,b) (x:xs) = sfoldl step (step (a,b) x) xs
      sfoldl step (a,b) [] = (a,b)

wchars = " \t\r\n"

strip :: String -> String
strip = lstrip . rstrip

lstrip :: String -> String
lstrip = dropWhile (`elem` wchars)

rstrip :: String -> String
rstrip = reverse . lstrip . reverse

unicodeToString = Data.Text.unpack . Data.Text.Encoding.decodeUtf8 . Data.ByteString.Char8.pack

main = do
    (word:_) <- getArgs
    a <- convertWordToHiragana word
    putStrLn a

Let's inline stuff that's only used once and replace recursion with library combinators.

import Control.Monad.State (evalState, modify, gets)
import Control.Monad.Loops (takeWhileM)
import Control.Applicative ((*>))
import Data.Char (isSpace)

filterBetween :: [Tag String] -> [Tag String]
filterBetween = (`evalState` 1) . takeWhileM step where
  step tag = modify (+ bracket tag) *> gets (>0)
  bracket tag
    | tag ~== "<span>" = 1
    | tag ~== TagClose "span" = -1
    | otherwise = 0

main = do
  [word] <- getArgs
  http <- simpleHTTP $ getRequest $ escapeURIString isUnescapedInURI $ "http://jisho.org/word/" ++ word
  html <- getResponseBody http
  putStrLn
    $ Data.Text.unpack $ Data.Text.Encoding.decodeUtf8 $ Data.ByteString.Char8.pack
    $ dropWhile isSpace $ reverse $ dropWhile isSpace $ reverse
    $ innerText $ filter (~== TagText "")
    $ filterBetween
    $ tail $ head $ partitions (~== "<span class=\"furigana\">") $ parseTags html

I left the <span> and </span> tags themselves out of what is printed, that's easier to code up so might be the correct way.

Edit: More existing combinators :D

{-# LANGUAGE OverloadedStrings #-}
import Text.HTML.TagSoup.Match (getTagContent)
import Data.Text (strip)
import Data.Text.Encoding (decodeUtf8)
import qualified Data.Text.IO as T

main = do
  [word] <- getArgs
  http <- simpleHTTP $ getRequest $ escapeURIString isUnescapedInURI
    $ "http://jisho.org/word/" ++ word
  html <- getResponseBody http
  T.putStrLn $ strip $ decodeUtf8 $ innerText
    $ getTagContent "span" (== [("class","furigana")]) $ parseTags html


Finding the number of inversions in an Array I am doing a college assignment where I have to count the number of inversions in an array/list. An inversion is defined as a tuple where i<j and a[i]>a[j]. For example in this array

val arr = Array(3, 1, 2, 4)

The inversions are (3,1), (3,2). So total count of inversions is 2.

I wrote a divide and conquer algorithm to find this. it works for small arrays. but for large inputs like this one

https://github.com/abhsrivastava/ArrayInversions/blob/master/src/main/resources/inversions.txt

there is always an out of memory error. My code is below

import scala.io.Source
import Sort._

object CountInversions extends App {
  val data = Source.fromResource("inversions.txt").getLines.map(_.toInt).toList
  val inversions = countInversions(data)
  println(s"number of inversions ${inversions}")

  def countInversions(input: List[Int]): Int = {
    input match {
      case Nil => 0
      case List(a) => 0
      case _ =>
        val mid = input.size / 2
        val left = input.slice(0, mid)
        val right = input.slice(mid, input.size)
        val l1 = countInversions(left)
        val l2 = countInversions(right)
        val l3 = splitInversions(left, right)
        l1 + l2 + l3
    }
  }

  // assuming l1 and l2 are almost of same size.
  // total complexity 2(nlogn + n)
  def splitInversions(l1: List[Int], l2: List[Int]): Int = {
    val sortedL1 = mergeSort(l1) // nlogn
    val sortedL2 = mergeSort(l2) // nlogn
    (sortedL1, sortedL2) match {
      case (Nil, Nil) => 0
      case (Nil, _) => 0
      case (_, Nil) => 0
      case (_, _) if sortedL1.head > sortedL2.head =>
        val result = splitInversions(sortedL1, sortedL2.tail)
        sortedL1.size + result
      case (_, _) =>
        splitInversions(sortedL1.tail, sortedL2)
    }
  }
}

I am not posting the code for mergeSort here. it is just a simple merge sort.

My objective is to be able to determine the inversions in O(nlogn) time and be able to process the large file. I also want to keep my code functional.

How can I optimize my code?

A few things I've noticed.

You use List to represent the input data. Lists are inefficient (linear) for things like input.size (which you do twice on the same input) and input.slice().
Both countInversions() and splitInversions() are recursive but they're not tail recursive, so that's going to eat up stack space.
splitInversions() sends its passed parameters to mergeSort() which means that every time it calls itself (recurses) it re-sorts already sorted data.
Your calculations return an Int, which is going to be too small for a large data set such as the inversions.txt you've linked to.

But generally I find the whole thing rather too complicated.

Here's an alternative algorithm that is smaller, faster, and more memory efficient.

def countInversions(input :Vector[Int]) :Long = {
  val idxBuf = input.indices.sortBy(input).toBuffer
  input.indices.foldLeft(0L){ case (sum,x) =>
    val idx = idxBuf.indexOf(x)
    idxBuf.remove(idx)  //side effect
    sum + idx
  }
}


Basic Calculator in Java 8 I was reading this post and saw quite few improvements. So I tried to rewrite it using Java 8 features. Any improvements you can spot, please feel free to mention.

public static void main(String[] args) {

    boolean runAgain = false;
    Double result = .0;
    List<Double> inputs = new ArrayList<Double>();
    Scanner scanner = new Scanner(System.in);
    do {
        System.out.print("Enter the first number : ");
        inputs.add(scanner.nextDouble());
        System.out.print("Enter the second number : ");
        inputs.add(scanner.nextDouble());
        System.out.print("Enter the operator : ");
        String op = scanner.next();

        result = calculateAnswer(inputs, op);
        System.out.println("Answer : "+result);

        System.out.print("Do you want to try again?[Y/N] : ");
        runAgain = scanner.next().equals("Y")?true : false;

    } while (runAgain);

    System.out.println("Program finished!");
    scanner.close();
}

static Double calculateAnswer(List<Double> inputs, String operator){

    Operations[] ops = Operations.values();
    Operations correctOp = Arrays.asList(ops).stream()
            .filter(op -> op.getSymbol().equals(operator))
            .findFirst().get();

    return correctOp.getResult(inputs.get(0), inputs.get(1));
}

enum Operations{
    ADD(){
        @Override
        String getSymbol() {
            return "+";
        }
        @Override
        Double getResult(Double d1, Double d2) {
            return d1 + d2;
        }
    },SUB{
        @Override
        String getSymbol() {
            return "-";
        }
        @Override
        Double getResult(Double d1, Double d2) {
            return d1 - d2;
        }
    },MUL{
        @Override
        String getSymbol() {
            return "*";
        }
        @Override
        Double getResult(Double d1, Double d2) {
            return d1 * d2;
        }
    },DIV{
        @Override
        String getSymbol() {
            return "/";
        }
        @Override
        Double getResult(Double d1, Double d2) {
            return d1 / d2;
        }
    };

    abstract Double getResult(Double d1, Double d2);

    abstract String getSymbol();
}

Embrace lambda expressions!
Your Operations is a lot more complicated that it needs to be. First of all, I would rename it Operation instead of Operations: the class does not represent multiple operations but a single one.
An Operation has 2 members: the symbol and the concrete operation it is performing. As such, consider adding 2 fields to your class symbol and operation. They will be initialized using a custom constructor. For the operation, all of them will be taking as input 2 double values, and returning a double that is the result of the calculation. This can be represented with the DoubleBinaryOperator class. Consider this:
enum Operation {

    ADD("+", (d1, d2) -> d1 + d2), // or Double::sum
    SUB("-", (d1, d2) -> d1 - d2),
    MUL("*", (d1, d2) -> d1 * d2),
    DIV("/", (d1, d2) -> d1 / d2);

    private final String symbol;
    private final DoubleBinaryOperator operator;

    private Operation(String symbol, DoubleBinaryOperator operator) {
        this.symbol = symbol;
        this.operator = operator;
    }

    public double getResult(double d1, double d2) {
        return operator.applyAsDouble(d1, d2);
    }

    public String getSymbol() {
        return symbol;
    }

}

The great advantage is that the code is now a lot shorter, and more readable. Instances of the concrete operations are created using a lambda expression.
Prefer primitives when possible
Your code is working on Double objects. In fact, you could just work with the primitive type double: simpler, no auto-boxing that may impact performance is performed. You should avoid to create unnecessary objects when possible.
Careful with Optional.get()
To retrieve the operation from its symbol, the code is looping over all the possible operations, filtering the one having the correct symbol and returning it. However, if there are no operations with this symbol, it will fail with a NoSuchElementException from Optional#get().
The issue is that it is "hidden" in the code. When reading it, you can easily not spot this fact. Instead of relying on this behaviour, you should express in your code what you want to happen when no operations were found. You could default to another operation with orElse, but most likely you will want to fail with an exception. And for that you can use orElseThrow. The advantage is that it documents clearly in the code what is expected to happen when no operations are found.
Operation correctOp =
    Arrays.stream(Operation.values())
          .filter(op -> op.getSymbol().equals(operator))
          .findFirst()
          .orElseThrow(() -> new IllegalArgumentException("No operation found for operator " + operator));

The end result is the same: an exception will be thrown. But in this example, the reader and the maintainer of the code clearly sees that this case was thought of. Also, it provides a more meaningful exception message for the user.
Note that I replaced the creation of the Stream with Arrays.stream(array): there is no need to first convert to a list to create a Stream, you can do it directly on an array.
Clear parameters to functions
The method calculateAnswer currently takes as parameter a List<Double> inputs for the inputs by the user. Why? This is awkward: it would imply the function could be called with an empty list, or a list with 1 element... and the code will fail trying to access an out of bounds index since it expects at least 2 elements in the list.
In fact, the method only takes 2 inputs, so instead of wrapping them in a list, pass them as 2 parameters:
double calculateAnswer(double firstInput, double secondInput, String operator)

This also means you need to refactor a bit the main code: don't use a List<Double> but store each number given by the user in 2 separate local variables.
Boolean arithmetic
Don't do
runAgain = scanner.next().equals("Y")?true : false;

It is both clearer and shorter to just have
runAgain = scanner.next().equals("Y");


Tail-recursive factorial Is there anything what could be improved on this code?

def factorial(n: Int, offset: Int = 1): Int = {
    if(n == 0) offset else factorial(n - 1, (offset * n))
}

The idea is to have tail-recursive version of factorial in Scala, without need to define internal function or alias.

This one is callable like this:

factorial(4)

So final solution looks like this:

import scala.annotation._

@tailrec
def factorial(n: Int, accumulator: Long = 1): Long = {
    if(n == 0) accumulator else factorial(n - 1, (accumulator * n))
}

Looks ok in its basic form, but here are some points to consider:

You may want to consider using at least Long, as factorials tend to get large quickly.
Whenever you write a function that you believe to be tail-recursive, then do add @tailrec (from scala.annotations) to it. This has two major advantages: First, it corrects your thoughts and tells you immediately, if it isn't tail-recursive although you thought so, and second, it tells everyone else and stops them from making a "fix" that causes the function to no longer be tail-recursive. May not be a big deal for such a small one, but in general tail-recursive functions can be more complex and then it's much harder to see at a glance that the function is tail-recursive if you do not annotate it as such.
Naming convention: The semantics of what you labelled offset is not really an offset as we would usually think about it. If you say offset most people have a certain meaning in mind that they associate with this term. The traditional meaning that resembles your semantics would be given by the term accumulator. Especially, when writing recursive functions we run into this intermediate-result-variable-thing very often and you will almost always see it referred to as an accumulator, so for clarity's sake you should just name the variable as such.


Efficiently checking if a number is divisible by 3 I'm looking for code review, best practices and optimizations.

public final class DivThreeEfficiently {

    private DivThreeEfficiently() {}

    /**
     * Returns true if the input number is divisible by three.
     * Else returns false.
     *
     * @param n     the input number
     * @return      true if input number is divisible by three
     */
    public static boolean isMultipleOfThree(int n) {
        if(n < 0) n = -n;

        int evenCtr = 0;
        int oddCtr = 0;

        while (n != 0) {
            if ((n & 1) == 1) {
                oddCtr++;
            }
            n = n>>1;
            if ((n & 1) == 1) {
                evenCtr++;
            }
            n = n>>1;
        }

        return evenCtr == oddCtr;
    }
}

public class DivThreeEfficientlyTest {

    @Test
    public void testEvenNegative() {
        assertTrue(DivThreeEfficiently.isMultipleOfThree(-3));
        assertTrue(DivThreeEfficiently.isMultipleOfThree(-6));
        assertTrue(DivThreeEfficiently.isMultipleOfThree(-12));
    }

    @Test
    public void testEvenPositive() {
        assertTrue(DivThreeEfficiently.isMultipleOfThree(0));
        assertTrue(DivThreeEfficiently.isMultipleOfThree(3));
        assertTrue(DivThreeEfficiently.isMultipleOfThree(6));
    }

    @Test
    public void testOddNegative() {
        assertFalse(DivThreeEfficiently.isMultipleOfThree(-1));
        assertFalse(DivThreeEfficiently.isMultipleOfThree(-4));
        assertFalse(DivThreeEfficiently.isMultipleOfThree(-11));
    }

    @Test
    public void testOddPositive() {
        assertFalse(DivThreeEfficiently.isMultipleOfThree(1));
        assertFalse(DivThreeEfficiently.isMultipleOfThree(4));
        assertFalse(DivThreeEfficiently.isMultipleOfThree(11));
    }
}

Computers aren't humans.  A human might find it easiest to apply a divisibility rule.  A computer, though, doesn't care.

The simplest code would be to check n % 3 == 0.  The modulo operator uses the JVM opcode irem, which is about as efficient as you can get.

On an Intel CPU, irem is probably implemented using the IDIV (signed divide) instruction.  On most modern x86-compatible processors, IDIV with a 32-bit operand uses 10 to 30 micro-operations and has a latency of 20 to 61 clock cycles.  More importantly, the trend on newer and more powerful hardware is for IDIV to take fewer clock cycles.  In other words, writing the program as if it were a RISC processor is a counterproductive "optimization" — it would be better to let the hardware perform the division operation to its full potential.

For comparison…

javap -c DivThreeEfficiently

public final class DivThreeEfficiently {
  public static boolean isMultipleOfThree(int);
    Code:
       0: iload_0
       1: ifge          7
       4: iload_0
       5: ineg
       6: istore_0
       7: iconst_0
       8: istore_1
       9: iconst_0
      10: istore_2
      11: iload_0
      12: ifeq          46
      15: iload_0
      16: iconst_1
      17: iand
      18: iconst_1
      19: if_icmpne     25
      22: iinc          2, 1
      25: iload_0
      26: iconst_1
      27: ishr
      28: istore_0
      29: iload_0
      30: iconst_1
      31: iand
      32: iconst_1
      33: if_icmpne     39
      36: iinc          1, 1
      39: iload_0
      40: iconst_1
      41: ishr
      42: istore_0
      43: goto          11
      46: iload_1
      47: iload_2
      48: if_icmpne     55
      51: iconst_1
      52: goto          56
      55: iconst_0
      56: ireturn
}

Div3MoreEfficiently.java

public class Div3MoreEfficiently {
    private Div3MoreEfficiently() {}

    public static boolean isMultipleOfThree(int n) {
        return n % 3 == 0;
    }
}

javap -c Div3MoreEfficiently

public class Div3MoreEfficiently {
  public static boolean isMultipleOfThree(int);
    Code:
       0: iload_0
       1: iconst_3
       2: irem
       3: ifne          10
       6: iconst_1
       7: goto          11
      10: iconst_0
      11: ireturn
}


Pointer handle - only allocates in stack This is a pointer class of mine that I would like to have reviewed. Right now it only allocates in the stack and has no copy or move operations.

template<typename T>
class Ptr {
public:
    Ptr(T* t, int s = 1) :p{t},sz{s} { }
    T& operator*() {
        check_range();
        return *p;
    }
    T& operator[](int i) {
        check_range(i);
        return p[i];
    }
    Ptr& operator+(int i) {
        index += i;
        check_range(index);
        p+= i;
        return *this;
    }
    Ptr& operator-(int i) {
        index -= i;
        check_range(index);
        p -= i;
        return *this;
    }
    Ptr& operator++() {
        *this = *this+1;
        return *this;
    }
    Ptr operator++(int) {
        Ptr<T> old{p};
        ++(*this);
        return old;
    }
    Ptr& operator--() {
        *this = *this-1;
        return *this;
    }
    Ptr operator--(int) {
        Ptr<T> old{p};
        --(*this);
        return old;
    }
private:
    T* p;
    int sz;
    int index = 0;
    void check_range(int i) {
        if (i < 0 || i > sz-1) {
            throw std::out_of_range("out of range");
        }
    }
    void check_range() {
        if (p == nullptr) {
            throw std::out_of_range("null pointer");
        }
    }
};

How can I make this shorter and less ugly? Is there a better solution than what I did?

I would expect operator+ and operator- to return a new object (leaving the current one intact.

    Ptr& operator+(int i) {
        index += i;
        check_range(index);
        p+= i;
        return *this;
    }
    Ptr& operator-(int i) {
        index -= i;
        check_range(index);
        p -= i;
        return *this;
    }

If I was using normal pointers.

 T* x  = getAT();
 x + 1;           // Does not change x
 T* y = x + 1;    // Does not change x (but y has the value of x+1).

Usually you see operator+ defined in terms of operator+=

Ptr& operator+(int i) {
   Ptr result(*this);
   return result+=1;
}

The *this = *this+1; look very strange.

    Ptr& operator++() {
        *this = *this+1;
        return *this;
    }

I would have just called the operator+=

    Ptr& operator++() {
        return operator+=(1);
    }

Again don't like ++(*this);

    Ptr operator++(int) {
        Ptr<T> old{p};
        ++(*this);
        return old;
    }

I would have used:

    Ptr operator++(int) {
        Ptr<T> old{p};
        operator++();
        return old;
    }

You should strive for the strong exception guarantee (also known as transaction exception guarantee).

    void check_range(int i) {
        if (i < 0 || i > sz-1) {
            throw std::out_of_range("out of range");
        }
    }

Though this code looks like it does that. It is usually called in a way that prevents it.

    index -= i;
    check_range(index);  // If this throws your object is now in the new state
                         // with index out of range. I would have tried to make sure
                         // that if an exception is thrown then the state of the object
                         // remains unchanged.

    // Change to this:

    check_range(index - i); // If it throws then the object is still
                            // in a consistent unchanged state.
    index -= 1;             // If we get here then change the state.


Getting the frequency of letters in each position I have a text file like this example:

>chr12:86512-86521
CGGCCAAAG
>chr16:96990-96999
CTTTCATTT
>chr16:97016-97025
TTTTGATTA
>chr16:97068-97077
ATTTAGGGA

This file is divided into different parts, and every part has 2 lines. The line which starts with > is ID and the 2nd line is a sequence of letters and the letters are A, T, C or G and also the length of each sequence is 9 so, for every sequence of letters there are 9 positions. I want to get the frequency of the 4 mentioned letters in every position (we have 9 positions).

Here is the expected output for the small example:

one = {'T': 1, 'A': 1, 'C': 2, 'G': 0}
two = {'T': 3, 'A': 0, 'C': 0, 'G': 1}
three = {'T': 3, 'A': 0, 'C': 0, 'G': 1}
four = {'T': 3, 'A': 0, 'C': 1, 'G': 0}
five = {'T': 0, 'A': 1, 'C': 2, 'G': 1}
six  = {'T': 0, 'A': 3, 'C': 0, 'G': 1}
seven = {'T': 2, 'A': 1, 'C': 0, 'G': 1}
eight = {'T': 2, 'A': 1, 'C': 0, 'G': 1}
nine = {'T': 1, 'A': 2, 'C': 0, 'G': 1}

I am doing that in Python using the following command. This command has 3 steps. Steps 1 and 2 work fine, but would you help me to improve step 3, which made this pipeline so slow for big files?

Step 1: to parse the file into a comma-separated file

def fasta_to_textfile(filename, outfile):
    with open(filename) as f, open(outfile, 'w') as outfile:
        header = sequence = None
        out = csv.writer(outfile, delimiter=',')
        for line in f:
            if line.startswith('>'):
                if header:
                    entry = header + [''.join(sequence)]
                    out.writerow(entry)
                header = line.strip('>\n').split('|')
                sequence = []
            else:
                sequence.append(line.strip())
        if header:
            entry = header + [''.join(sequence)]
            out.writerow(entry)

Step 2: comma-separated file to a Python dictionary

def file_to_dict(filename):
    f = open(filename, 'r')
    answer = {}
    for line in f:
        k, v = line.strip().split(',')
        answer[k.strip()] = v.strip()
    return answer

To print functions from steps 1 and 2:

a = fasta_to_textfile('infile.txt', 'out.txt')
d = file_to_dict('out.txt')

Step 3: to get the frequency

one=[]
two=[]
three=[]
four=[]
five=[]
six=[]
seven=[]
eight=[]
nine=[]
mylist = d.values()
for seq in mylist:
    one.append(seq[0])
    two.append(seq[1])
    se.append(seq[2])
    four.append(seq[3])
    five.append(seq[4])
    six.append(seq[5])
    seven.append(seq[6])
    eight.append(seq[7])
    nine.append(seq[8])

from collections import Counter
one=Counter(one)
two=Counter(two)
three=Counter(three)
four=Counter(four)
five=Counter(five)

That's a crazy amount of code for such a simple task.  There's no need to generate any intermediate files.  There's no need to create nine separate variables for the nine columns.

To process an input file (whether from sys.stdin or as a named argument on the command line), use fileinput.  That way, you don't have to hard-code 'infile.txt'.  Then, simply ignore the lines that start with > and strip off the newlines.

To work on columns rather than rows, use zip().

Suggested solution

These seven lines could replace your entire code.

import fileinput
from collections import Counter

def nucleotide_lines(f):
    for line in f:
        if not line.startswith('>'):
            yield line.rstrip()

print([Counter(col) for col in zip(*nucleotide_lines(fileinput.input()))])


Sort by year and day descending, yet time ascending I recently discovered a hugely inefficient portion of code in my program, and have gone about rewriting it. I am however, not quite sure if the rewritten program actually does exactly what I want, due to its (relative) mathematical complexity. I am especially uncertain about how this new code will handle changes of the day (so 24:00 -> 00:00).

Here are the old and the new piece of code, in said order:

Collections.sort(listEntries, new Comparator<LogEntry>() {
            @Override
            public int compare(LogEntry lhs, LogEntry rhs) {
                Calendar lhsCreatedAt = Calendar.getInstance();
                Calendar rhsCreatedAt = Calendar.getInstance();
                lhsCreatedAt.setTimeInMillis(lhs.getCreatedAt());
                rhsCreatedAt.setTimeInMillis(rhs.getCreatedAt());
                if (lhsCreatedAt.get(Calendar.YEAR) != rhsCreatedAt.get(Calendar.YEAR)) {
                    return rhsCreatedAt.get(Calendar.YEAR) - lhsCreatedAt.get(Calendar.YEAR);
                }
                if (lhsCreatedAt.get(Calendar.DAY_OF_YEAR) != rhsCreatedAt.get(Calendar.DAY_OF_YEAR)) {
                    return rhsCreatedAt.get(Calendar.DAY_OF_YEAR) - lhsCreatedAt.get(Calendar.DAY_OF_YEAR);
                }
                return (int) (lhs.getCreatedAt() - rhs.getCreatedAt());
            }
        });

versus

Collections.sort(listEntries, new Comparator<LogEntry>() {
            @Override
            public int compare(LogEntry lhs, LogEntry rhs) {
                long lhsCreatedAt = lhs.getCreatedAt();
                long rhsCreatedAt = rhs.getCreatedAt();
                long millisecondsPerDay = 86400000;

                if (Math.floor(lhsCreatedAt/millisecondsPerDay) != Math.floor(rhsCreatedAt/millisecondsPerDay)){
                    return (int) (rhsCreatedAt - lhsCreatedAt);
                }
                return (int) (lhsCreatedAt - rhsCreatedAt);
            }
        });

If there are any flaws in this new code, or any other performance increases to be gained, I would love to know.

Main problem that I see, is cast to int, as it will overflow in
   23 days!!!

Regarding 24:00 correctness, that depends is that ticks in local timezone or UTC and if you care, but I'd suggest to write Unit Test that validates this algorithm on some set of events, for whole year, and lot of events per day, to verify every case.

Additionally make millisecondsPerDay a constant inside Comparator, but upper then method

new Comparator<LogEntry>() {
        static final long MILLISECONDS_PER_DAY = 86400000;
        @Override
        public int compare(LogEntry lhs, LogEntry rhs) { ...}
}

EDIT

You don't need Math.floor, as this is integral numbers, so dividing gives number of days as integral number.

I'd suggest following code:

Collections.sort(listEntries, new Comparator<LogEntry>() {

        static final long MILLISECONDS_PER_DAY = 86400000;

        @Override
        public int compare(LogEntry lhs, LogEntry rhs) {
            long lhsCreatedAt = lhs.getCreatedAt();
            long rhsCreatedAt = rhs.getCreatedAt();

            long lhsDays = lhsCreatedAt/MILLISECONDS_PER_DAY;
            long rhsDays = rhsCreatedAt/MILLISECONDS_PER_DAY;
            if(lhsDays == rhsDays){
                 return (int)(lhsCreatedAt%MILLISECONDS_PER_DAY - rhsCreatedAt%MILLISECONDS_PER_DAY)
            }
            return (int)(rhsDays-lhsDays);
        }
    });

Well, if block can be following, as long as we are in the same day, no need to divide additional time:

            if(lhsDays == rhsDays){
                 return (int)(lhsCreatedAt - rhsCreatedAt)
            }


I think your current code is working- it seems like it’s getting the same answer as other people who say they solved it (i.e. 23514624000). So I think it belongs here.
Right now, if you wanted to use this for any string of digits and any length of consecutive numbers, it would be \$O(n^2)\$ time complexity because you would have to multiply at most (length-of-series / 2) * (length-of-series / 2) numbers. Something you could use to fix that is a deque from the collections module. You could use it to know what to divide and what to multiply to get the current product, and you could also use it to track how many zeros are in the current sequence of consecutive numbers. If you do this then you only need to multiply or divide at most (length-of-series * 2) - 1 numbers, so it’s \$O(n)\$.
import collections

def find_max_prod(n, series):

    if len(series) < n:
        return 0

    current_nums = collections.deque(maxlen=n)
    zero_count = 0
    max_prod = 1
    my_iter = iter(series)

    for _ in range(n):
        next_n = int(next(my_iter))
        max_prod *= next_n
        current_nums.append(next_n)
        if next_n == 0:
            zero_count += 1

    current_prod = max_prod if max_prod > 0 else 1

    for str_n in my_iter:
        n_out = current_nums.popleft()
        n_in = int(str_n)
        current_nums.append(n_in)
        if n_in == 0:
            zero_count += 1
        if n_out == 0:
            zero_count -= 1
        else:
            current_prod //= n_out
        if n_in != 0:
            current_prod *= n_in
            if current_prod > max_prod and zero_count == 0:
                max_prod = current_prod

    return max_prod

or with Toby Speight‘s suggestion:
import collections

def max_of_substr(n, substr):
    current_nums = collections.deque(maxlen=n)
    my_iter = iter(substr)
    max_prod = 1

    for _ in range(n):
        next_n = int(next(my_iter))
        max_prod *= next_n
        current_nums.append(next_n)

    current_prod = max_prod

    for str_n in my_iter:
        n_out = current_nums.popleft()
        n_in = int(str_n)
        current_nums.append(n_in)
        current_prod //= n_out
        current_prod *= n_in
        if current_prod > max_prod:
            max_prod = current_prod

    return max_prod

def find_max_prod(n, series):
    max_substr_generator = (
        max_of_substr(n, substr)
        for substr in series.split('0')
        if len(substr) >= n
        )
    return max(max_substr_generator, default=0)


Sort Characters By Frequency I solved this problem.

  Problem Statement

  Given a string, sort it in decreasing order based on the frequency of
  characters.

  Example 1

  Input: "tree"

  Output: "eert"

  Explanation: 'e' appears twice while 'r' and 't' both appear once. So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a
  valid answer.

  Example 2:

  Input: "cccaaa"

  Output: "cccaaa"

  Explanation: Both 'c' and 'a' appear three times, so "aaaccc" is also
  a valid answer. Note that "cacaca" is incorrect, as the same
  characters must be together. Example 3:

  Input: "Aabb"

  Output: "bbAa"

  Explanation: "bbaA" is also a valid answer, but "Aabb" is incorrect.
  Note that 'A' and 'a' are treated as two different characters.

I solved this problem using heaps(since it was tagged under this category). I feel my solution is a bit verbose which includes building a vector from a map and so on.

Can you think of any redundancies that can be removed from this solution or any better way of doing it.

class CompareHeap
    {
        public:
            bool operator()(const std::pair< char, int> &A, const std::pair< char , int > &B )
            {
                return (A.second < B.second);
            }
    };
    class Solution {
    public:
        string frequencySort(string input) {
        std::string answer = "";
        std::map<char, int> freq;
        for(auto it = input.begin(); it!= input.end(); ++it)
        {
            if(freq.find(*it) != freq.end())
            {
                freq[*it] += 1;
            }
            else
            {
                freq[*it] = 1;
            }
        }
        std::vector<std::pair<char, int >> v;
        std::transform(freq.begin(), freq.end(), std::back_inserter(v), [](std::pair<char , int > kv) {return kv;});
        std::make_heap(v.begin(), v.end(), CompareHeap());
        while(v.size() > 0)
        {
            std::pop_heap(v.begin(), v.end(), CompareHeap());
            answer += std::string(v.back().second,v.back().first);
            v.pop_back();
        }
        return answer;
        }
    };

Shorter:

There are possibilities to make the code shorted without making it less correct/clear.

for(auto it = input.begin(); it!= input.end(); ++it)

Range loop could be used for this purpose.

        if(freq.find(*it) != freq.end())
        {
            freq[*it] += 1;
        }
        else
        {
            freq[*it] = 1;
        }

map zero initializes built in types when it creates the key-value pair. Source. So the check can be removed, and ++ used instead of +1. The change may also improve performance, but I don't think it will be much of a deal.

    std::vector<std::pair<char, int >> v;
    std::transform(freq.begin(), freq.end(), std::back_inserter(v), [](std::pair<char , int > kv) {return kv;});

std::vector has a constructor which takes iterator pair and constructs the container from that.

    std::make_heap(v.begin(), v.end(), CompareHeap());
    while(v.size() > 0)
    {
        std::pop_heap(v.begin(), v.end(), CompareHeap());
        answer += std::string(v.back().second,v.back().first);
        v.pop_back();
    }

In my opinion sort would be a better fit (making a heap is sorting too, but I think std::sort have potential to perform better), then do range for loop with the last 2 lines of the code inside of it. Currently intentions are less clear, though still good.

Style:

I think that having operator() in the outside class is confusing. If the clarity is really wanted, named lambda could be made, then passed to std::sort() or make_heap().

Theoretically input.length() can be bigger than maximum value of int, so std::size_t should be used, just to be nerd that cares about standard compliance.

Usage of map:

I think that map is the most clear solution for this problem. It lifts a lot of burden from the programmer. There are also possibilities that compiler vendor did some small map optimization (so everything will be in the automatic storage).

Copying the map into vector will probably cost nothing, since everything is POD, so it will decay into std::memset() or something similar (in case the map is small map, it will be even faster).

Sorting a vector should be fast as well, since char on the platform has theoretical maximum of 256 values.

The only thing that could be slightly sped up is putting the data into the result. reserve(input.length()) can be called on the result string so that it won't perform any additional memory allocations.

Performance:

The algorithm should be fast enough for most of the systems, unless insane blazing performance is needed (e.g. Facebook or similar).


Simple Morse Code Converter (Python) I created a simple text to morse code converter in python, and was wondering if there was an easier/shorter way to do this. Is there a way to generate the dictionary without having to hard-code every single option?
def main():

    print("This program translates words to morse code\n")

    words = input("Enter a word or phrase to be encoded: ")
    words = words.upper()

    codeDict = createDict()

    i = 0

    try:
        while (i < len(words)):
            if (words[i] != " "):
                print(codeDict[words[i]], end = " ")
            else:
                print("/", end = " ")
            i += 1
    except:
        print("\nInvalid characters found - refer to morse code alphabet")

def createDict():
    code = {'A': '.-',
            'B': '-...',
            'C': '-.-.',
            'D': '-..',
            'E': '.',
            'F': '..-.',
            'G': '--.',
            'H': '....',
            'I': '..',
            'J': '.---',
            'K': '-.-',
            'L': '.-..',
            'M': '--',
            'N': '-.',
            'O': '---',
            'P': '.--.',
            'Q': '--.-',
            'R': '.-.',
            'S': '...',
            'T': '-',
            'U': '..-',
            'V': '...-',
            'W': '.--',
            'X': '-..-',
            'Y': '-.--',
            'Z': '--..',
            '1': '.----',
            '2': '..---',
            '3': '...--',
            '4': '....-',
            '5': '.....',
            '6': '-....',
            '7': '--...',
            '8': '---..',
            '9': '----.',
            '0': '-----'}

    return code

main()

As already mentioned in the comments, I don't think there's a strictly better way to create the morse code mapping. There is however a lot we can do to make this code more concise and more pythonic. This looks like Java code that was directly translated into Python and doesn't utilise some of Python's key features.

Morse Code dict
See the comments on your question: We don't need function createDict, which should be called create_dict (PEP 8), we only need a top-level variable:
CHAR_TO_MORSE = {'A': '.-',
                 ...
                 '0': '-----'}

Never iterate over indices in python
In Python this pattern is generally not recommended:
i = 0
while (i < len(words)):
    print(words[i])

You almost never need to iterate over and access elements by their indices. Instead you should directly iterate over the elements of the iterable:
for word in words:
    print(word)

If you do need the index as well you can use built-in enumerate:
for index, word in enumerate(words):
    print(f"{index}: {word}")

words is not a descriptive variable name for a string. If I iterate over a variable named words, I expect to receive words, not single characters. I'd change it to text or message and then change the loop to:
for char in text:
    ...

This makes it immediately clear what is happening.

Exception handling
Do not use bare except. Doing so can make it harder to interrupt programs and it can disguise other problems, since it catches all errors, not just the ones you're expecting. Instead you should only catch KeyError, since that's the only error you're explicitly handling.

words[i] != " "
You perform this check in every loop iteration, although it's not really a special case. This basically only translates " " to "/", the rest of the logic is the same. So you can simply add it to your char to morse mapping:
CHAR_TO_MORSE = {'A': '.-',
                 ...
                 '0': '-----',
                 ' ': '/'}

Calling main()
For most use cases, you should wrap a call to main() from within the script in a if __name__ == “__main__”: condition.
if __name__ == "__main__":
    main()

What does if name == “main”: do?

Complete code
I also applied .upper() directly to the return value of input(...) and moved the Exception clause into the loop to allow for a better error statement to the user.
CHAR_TO_MORSE = {'A': '.-',
                 ...
                 '0': '-----',
                 ' ': '/'}

def main():
    print("This program translates words to morse code", end="\n\n")

    text = input("Enter a word or phrase to be encoded: ").upper()

    for char in text:
        try:
            print(CHAR_TO_MORSE[char], end=" ")
        except KeyError:
            print(f"\nInvalid character found: '{char}' - refer to morse code alphabet")
            break

if __name__ == "__main__":
    main()

join and list comprehensions / generator expressions
If you're not set on printing the morse code up until the invalid character, this is a perfect use case for join together with a list comprehension:
try:
    print(" ".join(CHAR_TO_MORSE[char] for char in text))
except KeyError:
    print(f"\nInvalid character found - refer to morse code alphabet")

What we're using here is actually not a list comprehension, but a generator expression. If you're interested you can read more about Generator Expressions vs List Comprehensions.