texts:
This is a program to generate prime numbers for a given range. The sieve of Eratosthenes algorithm was implemented, but still the SPOJ says time limit exceeded. Where can some optimizations be made?

The input begins with the number t of test cases in a single line (t<=10). In each of the next t lines there are two numbers m and n (1 <= m <= n <= 1000000000, n-m<=100000) separated by a space.

import java.util.*;
import java.lang.*;
class Main
{
    public static void prime(int m, int n)
    {
    boolean arr[] = new boolean[n+1];
    for(int i = 0; i < arr.length; i++)
        arr[i] = true;
    for(int p = 2; p*p <= n; p++)
    {
        if(arr[p] == true)
        {
            for(int j = p*2; j <= n; j += p)
                arr[j] = false;
        }
    }
    for(int i = m; i <= n; i++)
    {
        if(arr[i] == true)
            System.out.print(i + " ");
    }
}
public static void main (String[] args) throws java.lang.Exception
{
    Scanner in = new Scanner(System.in);
    int test = in.nextInt();
    int m = 0,n = 0,flag = 0;
    while(test > 0)
    {
        m = in.nextInt();
        n = in.nextInt();
        prime(m,n);
        test--;
    }
}
}


texts: Delete all instances of "b" or "ac" from a string

texts:
A recent question, inspired me to think about how far we've come, and how much easier tasks are in current, modern languages like C# and Java, compared to the low-level languages we were stuck with years ago.

Based on that, I decided to post some code for doing the same task, but in a language that (at least in most people's estimation) has been obsolete for decades. In this case, I chose an ancient language named SNOBOL 4 for the implementation.

Warning: this really is an old language (this year is its 50th anniversary), so try not to be terribly surprised at the length and complexity of the code compared to modern languages like C# and Java.

    * read a string from standard input
    input_string = input

* find "b" or "ac" in s, replace with nothing, and repeat if successful:
del_loop input_string ("b" | "ac") =     : s(del_loop)

    * write out resulting string
    output = input_string

I don't think anybody's posted any SNOBOL 4 here before, so please be gentle...


texts: Rails conditional sorting based on params

texts:
The following code sorts the current users bid model items based on a param condition :bid_status. It starts to get messy when checking if the project space (:real_property_sale_project) :failed_date is .present? or .nil? to exclude certain items from the returned results. How can I improve this?

def index
  @bids = current_user.bids.select { |bid| bid.real_property_sale.try(:real_property_sale_project).try(:failed_date).nil? }

  if params[:bid_status] == 'in_progress'
    @bids = @bids.select { |bid| bid.real_property_sale.status == 'published' }
  elsif params[:bid_status] == 'awarded'
    @bids = @bids.select { |bid| bid.status == 'accepted' && bid.real_property_sale.try(:real_property_sale_project).try(:failed_date).nil? }
  elsif params[:bid_status] == 'lost'
    @bids = @bids.select { |bid| bid.status == 'rejected' }
  elsif params[:bid_status] == 'history'
    @bids = current_user.bids.select { |bid| bid.status == 'accepted' && bid.real_property_sale.try(:real_property_sale_project).try(:failed_date).present? }
  end

  @bids = @bids.paginate(:page => params[:page], :per_page => 9)
end


texts: Recyclerview Adapter for weather app - Makes API calls for each item

texts:
I have a weather app that allows the user to save Cities (with nickname and zip) into a room database.  I'm using mvvm and livedata to observe the list of cities and update the recyclerview accordingly. I then perform an API call for each item in the recyclerview, which to me seems wrong.  It works but seems wrong.

I'd appreciate any reviews on things I could do to improve.

public class RecyclerAdapter extends ListAdapter<MyCity, RecyclerAdapter.ViewHolder> {

    private static final DiffUtil.ItemCallback<MyCity> DIFF_CALLBACK = new DiffUtil.ItemCallback<MyCity>() {
        @Override
        public boolean areItemsTheSame(@NonNull MyCity oldItem, @NonNull MyCity newItem) {
            return oldItem.getId() == newItem.getId();
        }

        @Override
        public boolean areContentsTheSame(@NonNull MyCity oldItem, @NonNull MyCity newItem) {
            return oldItem.getZipCode() == newItem.getZipCode();
        }
    };

    public RecyclerAdapter() {
        super(DIFF_CALLBACK);
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_item_list, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {

        MyCity city = getItem(position);

        WeatherApi weatherApi = RetrofitService.createService(WeatherApi.class);

        weatherApi.getWeatherWithZip(city.getZipCode(), Constants.API_KEY).enqueue(new Callback<WeatherResponse>() {
            @Override
            public void onResponse(Call<WeatherResponse> call, Response<WeatherResponse> response) {
                if (response.isSuccessful()) {
                    String zip = String.valueOf(city.getZipCode());
                    holder.zip.setText(zip);
                    holder.city.setText(response.body().getName());
                    holder.weather.setText(Conversions.kelvinToFahrenheit(response.body().getMain().getTemp()) + "°C");
                }
            }

            @Override
            public void onFailure(Call<WeatherResponse> call, Throwable t) {

            }
        });
    }

    public MyCity getCityAt(int position) {
        return getItem(position);
    }

    class ViewHolder extends RecyclerView.ViewHolder {

        private TextView zip, city, weather;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            zip = itemView.findViewById(R.id.tv_zip);
            city = itemView.findViewById(R.id.tv_city);
            weather = itemView.findViewById(R.id.tv_weather);
        }
    }
}

EDIT:
I just got an email from openweatherapi... I made 11791 calls in a minute. This is definitely not ideal.


texts:
I wrote the following code using jQuery to create a WebAlert instead of using the alert() function from jQuery:

(function($){
    $.fn.WebAlert = function(msg) {
        // If WebAlert is Availble -> First Remove  this-> callback = Yes -> Now Create New WebAlert
        if ($('.WebAlert_Area').length) {
            $(this).Remove_WebAlert(msg , 'Yes')
            return false;
        //If WebAlert Not Availble
        } else {
            $(this).Create_WebAlert(msg)
            return false;
        }
    }

    //Function For Create WebAlert
    $.fn.Create_WebAlert = function(msg) {
        $('body').append('

');
        $('.WebAlert_Area .Text_Area').html(msg)
    };

    //Function For Remove WebAlert
    $.fn.Remove_WebAlert = function(msg , callback) {
        $('.WebAlert_Area').hide(1000 , function() {
            $(this).remove();
            if (callback == 'Yes') {
                $(this).Create_WebAlert(msg)
            }
        })
    };
})(jQuery);

$(document).ready(function() {
    $('body').WebAlert('Welcome To My Web')
}};

But I think that it's too complex and non-standard, is that true?


texts: Draw crosshairs on the screen - ZedGraph

texts:
Here's some part of my code is use to draw objects on the screen :

Class members:

private double cursorX = 0;
private double cursorY = 0;
private LineObj cursorOldY = new LineObj();
private LineObj cursorOldX = new LineObj();
private int index1 = 0;

private double cursor2X = 0;
private double cursor2Y = 0;
private LineObj cursor2OldY = new LineObj();
private LineObj cursor2OldX = new LineObj();
private int index2 = -1;

ZedGraph.CurveItem curve = null;

Drawing function :

private void drawCursors(bool first, bool second, bool fromKeyboard = false, Point mousePoint = new Point())
{
    GraphPane p = lineGraphControl1.GraphPane;
    if (p.CurveList.Count == 0 || curve == null)
        return;

    ZedGraph.Axis axis = curve.IsY2Axis ? (Axis)p.Y2AxisList[curve.YAxisIndex] : (Axis)p.YAxisList[curve.YAxisIndex];
    ZedGraph.PointPair point = new PointPair(0.0, 0.0);
    if (first)
    {
        p.GraphObjList.Remove(cursorOldY);
        p.GraphObjList.Remove(cursorOldX);
        if (fromKeyboard)
           point = curve.Points[index1];
        else if (lineGraphControl1.Graph.XAxis.Mode == XAxisMode.Parameter)
        {
            ZedGraph.CurveItem outputCurve;
            p.FindNearestPoint(mousePoint, curve, out outputCurve, out index1);
            if (index1 >= 0)
               point = curve.Points[index1];
        }
        else
        {
           if (!mousePoint.IsEmpty)
               p.ReverseTransform(mousePoint, out cursorX, out cursorY);
           point = findPoint(curve, cursorX);
        }
        cursorX = point.X;
        cursorY = transform(point.Y, axis);
        cursorOldY = new LineObj(cursorX, p.YAxis.Scale.Min, cursorX, p.YAxis.Scale.Max);
        cursorOldX = new LineObj(p.XAxis.Scale.Max, cursorY, p.XAxis.Scale.Min, cursorY);

       if (cursorX > p.XAxis.Scale.Min && cursorX < p.XAxis.Scale.Max)
           p.GraphObjList.Add(cursorOldY);

       if (cursorY > p.YAxis.Scale.Min && cursorY < p.YAxis.Scale.Max)
           p.GraphObjList.Add(cursorOldX);
   }
   if (second)
   {
       p.GraphObjList.Remove(cursor2OldY);
       p.GraphObjList.Remove(cursor2OldX);
       if (fromKeyboard)
           point = curve.Points[index2];
       else if (lineGraphControl1.Graph.XAxis.Mode == XAxisMode.Parameter)
       {
           ZedGraph.CurveItem outputCurve;
           p.FindNearestPoint(mousePoint, curve, out outputCurve, out index2);
           if (index2 >= 0)
               point = curve.Points[index2];
       }
       else
       {
           if (!mousePoint.IsEmpty)
               p.ReverseTransform(mousePoint, out cursor2X, out cursor2Y);
           point = findPoint(curve, cursor2X);
           if (index2 == -1)
           {
               index2 = (int) Math.Round(curve.NPts * 0.75, 0);
               point = curve.Points[index2];
           }
       }

       cursor2X = point.X;
       cursor2Y = transform(point.Y, axis);
       cursor2OldY = new LineObj(cursor2X, p.YAxis.Scale.Min, cursor2X, p.YAxis.Scale.Max);
       cursor2OldX = new LineObj(p.XAxis.Scale.Max, cursor2Y, p.XAxis.Scale.Min, cursor2Y);

       if (cursor2X > p.XAxis.Scale.Min && cursor2X < p.XAxis.Scale.Max)
           p.GraphObjList.Add(cursor2OldY);
       if (cursor2Y > p.YAxis.Scale.Min && cursor2Y < p.YAxis.Scale.Max)
           p.GraphObjList.Add(cursor2OldX);
    }
}

Is (structurally speaking) there some optimizations I missed ?


texts: Backtracking all the words in the English alphabet that have 5 letters, where no 2 consecutive letters can be consonants or vowels

texts:
I have the following problem in my algorithms textbook:

  Write a computer program that generates and counts how many words of 5 letters of the English alphabet can be formed, with the condition that no 2 consecutive letters can be consonants or vowels.

From the statement, I understand that the output should have this form cvcvc or vcvcv, where c means consonant and v means vowel.

The way I approached this problem was to write a function that generates all the words with 5 letters given a permutation of the sets (since there are 2 available sets, consonants and vowels). There are only 2 permutations of the sets available: cvcvc or vcvcv. And I call the function generate_words for every permutation of the sets.

My question is: Is it a good practice to hardcode the permutation of the sets? Would have been a better solution to write a function that generates this information?

# We use this variable just o track the number of generated solutions.
counter = 1

def _print_solution(set_master, solution):
    result = [set_master[set_index][element]
        for set_index, element in enumerate(solution)]

    global counter
    # ljust(6) because, in our case, the maximum number of words is 21 66 00
    # which has 6 digits.
    print str(counter).ljust(6), ', '.join(map(str, result))
    counter += 1

def _generate_words(set_master, solution, set_counter):
    if set_counter == len(set_master):
        _print_solution(set_master, solution)
        return

    for i in range(0, len(set_master[set_counter])):
        solution.append(i)
        _generate_words(set_master, solution, set_counter + 1)
        solution.pop()

def generate_words(set_master):
    solution = []
    _generate_words(set_master, solution, 0)

if __name__ == "__main__":

    vowels = ['a', 'e', 'i', 'o', 'u']
    consonants = ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p',
        'q', 'r', 's', 't', 'v', 'x', 'z']

    generate_words([vowels, consonants, vowels, consonants, vowels])
    generate_words([consonants, vowels, consonants, vowels, consonants])


texts: An entire file size retriever using a recursive os function in python

texts:
I'm a beginner and i just started with automate the boring stuff with python course and reached his first os lesson, so i decided to make a recursive directory size finder since apparently os.path.getsize doesn't get the size of folders.
Need a way to improve my code or advice on coding tricks, to make it more efficient

import os
class FileSizeFinder:

    def calculate_directory_size_in_bytes(self, directory: str, totalsize=0):
        for filename in tuple(os.listdir(directory)):
            current_directory = os.path.join(directory, filename)
            if os.path.isdir(current_directory):
                totalsize += FileSizeFinder.calculate_directory_size_in_bytes("self", current_directory)
            if not os.path.isfile(current_directory):
                continue
            totalsize += os.path.getsize(current_directory)
        return totalsize

    def get_file_size(self, directory: str, totalsize=0):
        total_size_in_bytes = FileSizeFinder.calculate_directory_size_in_bytes("self", directory)
        if total_size_in_bytes > 1024000000:
            totalsize = "Size in GB: " + str(round(total_size_in_bytes / 1024000000, 3))
        elif total_size_in_bytes > 1024000:
            totalsize = "Size in MB: " + str(round(total_size_in_bytes/ 1024000, 3))
        elif total_size_in_bytes > 1024:
            totalsize = "Size in KB: " + str(round(total_size_in_bytes / 1024, 3))
        return totalsize

print(FileSizeFinder.get_file_size("self", r"E:\Utilities_and_Apps\Python"))


texts:
I am doing a Pandas project on alcohol consumption. For your information, the dataset has the following columns:

| Continent | Country | Beer | Spirit | Wine |

The following is my code:

# Separating data by continent
# ----------------------------
data_asia   = data[data['Continent'] == 'Asia']
data_africa = data[data['Continent'] == 'Africa']
data_europe = data[data['Continent'] == 'Europe']
data_north  = data[data['Continent'] == 'North America']
data_south  = data[data['Continent'] == 'South America']
data_ocean  = data[data['Continent'] == 'Oceania']

top_5_asia_beer = data_asia.nlargest(5, ['Beer Servings'])[['Country', 'Beer Servings']]
top_5_asia_spir = data_asia.nlargest(5, ['Spirit Servings'])[['Country', 'Spirit Servings']]
top_5_asia_wine = data_asia.nlargest(5, ['Wine Servings'])[['Country', 'Wine Servings']]
top_5_asia_pure = data_asia.nlargest(5, ['Total Litres of Pure Alcohol'])[['Country', 'Total Litres of Pure Alcohol']]

top_5_africa_beer = data_africa.nlargest(5, ['Beer Servings'])[['Country', 'Beer Servings']]
top_5_africa_spir = data_africa.nlargest(5, ['Spirit Servings'])[['Country', 'Spirit Servings']]
top_5_africa_wine = data_africa.nlargest(5, ['Wine Servings'])[['Country', 'Wine Servings']]
top_5_africa_pure = data_africa.nlargest(5, ['Total Litres of Pure Alcohol'])[['Country', 'Total Litres of Pure Alcohol']]

top_5_europe_beer = data_europe.nlargest(5, ['Beer Servings'])[['Country', 'Beer Servings']]
top_5_europe_spir = data_europe.nlargest(5, ['Spirit Servings'])[['Country', 'Spirit Servings']]
top_5_europe_wine = data_europe.nlargest(5, ['Wine Servings'])[['Country', 'Wine Servings']]
top_5_europe_pure = data_europe.nlargest(5, ['Total Litres of Pure Alcohol'])[['Country', 'Total Litres of Pure Alcohol']]

top_5_north_beer = data_north.nlargest(5, ['Beer Servings'])[['Country', 'Beer Servings']]
top_5_north_spir = data_north.nlargest(5, ['Spirit Servings'])[['Country', 'Spirit Servings']]
top_5_north_wine = data_north.nlargest(5, ['Wine Servings'])[['Country', 'Wine Servings']]
top_5_north_pure = data_north.nlargest(5, ['Total Litres of Pure Alcohol'])[['Country', 'Total Litres of Pure Alcohol']]

top_5_south_beer = data_south.nlargest(5, ['Beer Servings'])[['Country', 'Beer Servings']]
top_5_south_spir = data_south.nlargest(5, ['Spirit Servings'])[['Country', 'Spirit Servings']]
top_5_south_wine = data_south.nlargest(5, ['Wine Servings'])[['Country', 'Wine Servings']]
top_5_south_pure = data_south.nlargest(5, ['Total Litres of Pure Alcohol'])[['Country', 'Total Litres of Pure Alcohol']]

top_5_ocean_beer = data_ocean.nlargest(5, ['Beer Servings'])[['Country', 'Beer Servings']]
top_5_ocean_spir = data_ocean.nlargest(5, ['Spirit Servings'])[['Country', 'Spirit Servings']]
top_5_ocean_wine = data_ocean.nlargest(5, ['Wine Servings'])[['Country', 'Wine Servings']]
top_5_ocean_pure = data_ocean.nlargest(5, ['Total Litres of Pure Alcohol'])[['Country', 'Total Litres of Pure Alcohol']]

I understand the ridiculousness of my code in terms of duplicity and repetitiveness. Can anyone please share tips and tricks to refactor the code?


texts: Single MySQL Query one-to-many efficiency

texts:
I am fairly inexperienced with the ramifications of doing a single select where joining several tables and there are several one-to-many relationships while also running some built in MySQL functions using column values between tables.

The tables will be fairly large: 10,000 records in the accounts table, 70,0000 records in the locations table, 350,000 in the email_sequences table.

The select I am performing: (from Laravel's query builder)

$interval = $getSheduleInterval($current);

$sql = "SELECT seq.id FROM locations AS loc
        JOIN accounts as acc ON acc.id=loc.account_id
        JOIN email_sequence AS seq ON loc.id=seq.location_id
        WHERE acc.suspended = 0
        AND acc.deleted_at IS NULL
        AND loc.active = 1
        AND seq.immediate = 0
        AND TIME(CONVERT_TZ(seq.schedule_time, 'UTC', loc.timezone)) >= {$interval->start}
        AND TIME(CONVERT_TZ(seq.schedule_time, 'UTC', loc.timezone)) < {$interval->end}";

$sequents = DB::select($sql);

I have seen (read) where in some instances it is more efficient to perform several queries and process the result of each in between rather than a complex SELECT query where several one-to-many or many-to-one relationships are involved.

Are there going to be any major issues with this single select as I have it currently constructed?

Edit: As requested here is the $getScheduleInterval() code;

// @param  object [Takes a instance of Carbon::now()]
public function getScheduleInterval($carbonObj){
    $interval = (object)[];

    // round time down to quarter hour
    $carbonObj->minute = $carbonObj->minute - ($carbonObj->minute % 15);
    $carbonObj->second = 00;

    //set start / end
    $interval->start = "'{$carbonObj->toTimeString()}'";
    $interval->end =   "'{$carbonObj->addMinutes(15)->toTimeString()}'";

    return $interval;

}


texts: Listing Docker Images without registry URI

texts:
I have a private container registry behind a firewall that will need some Google registry images. To make sure things are updated sanely, I'm writing a mirror script in Bash. I have one line that lists the images without their registry URIs, but it's overly complicated and I am piping through 3 awk statements.

docker images | awk '{printf("%s\:%s\n", $1, $2)}' | awk 'NR>1' | awk -F '/' '{print $3}'

First awk statement:

$ docker images | awk '{printf("%s\:%s\n", $1, $2)}'
REPOSITORY:TAG
gcr.io/google_containers/skydns:2015-10-13-8c72f8c

Second awk statement:

$ docker images | awk '{printf("%s\:%s\n", $1, $2)}' | awk 'NR>1'
gcr.io/google_containers/skydns:2015-10-13-8c72f8c

Third awk statement:

$ docker images | awk '{printf("%s\:%s\n", $1, $2)}' | awk 'NR>1' | awk -F '/' '{print $3}'
skydns:2015-10-13-8c72f8c

How can I reduce this to one awk statement?


texts:
In the process of learning F#, I wrote this code that reads lines of input from the console and stores them in a list.

As far as I can tell the code works correctly, but since I'm new to functional programming, I'm not sure if it is written as well as it could have been.

Should I have read characters iteratively instead of recursively?
Is there a better alternative to using a StringBuilder object?
Does my code follow proper functional style?

open System

/// Appends a character to the string builder and returns the new builder.
/// Characters 10 and 13 (newline and carriage return) are ignored.
/// Returns the updated StringBuilder.
let appendChar char (builder : Text.StringBuilder) =
    match char with
    | 10 | 13 -> builder
    | n ->
        let c = Convert.ToChar(n)
        builder.Append(c)

/// Finishes building a string by clearing the StringBuilder
/// and appending the string to the end of the list of strings.
/// Empty strings are ignored.
/// Returns a tuple containing the lines and the new StringBuilder.
let finishString lines (builder : Text.StringBuilder) =
    let s = builder.ToString()
    let l = builder.Length
    let newBuilder = builder.Clear()
    match l with
    | 0 -> (lines, newBuilder)
    | _ -> (lines @ [s], newBuilder)

/// Handles a character by appending it to the builder and taking an appropriate action.
/// If char is a newline, finish the string.
/// Returns a tuple containing lines and the new builder.
let handleChar char lines builder =
    let newBuilder = appendChar char builder
    match char with
    | 10 -> finishString lines newBuilder
    | c -> (lines, newBuilder)

/// Gets all the lines from standard input until end of input (Ctrl-Z).
/// Empty lines are ignored.
/// Returns a list of strings read.
let rec getLines lines builder =
    match Console.Read() with
    | -1 -> lines
    | c ->
        let tuple = handleChar c lines builder
        let newLines = fst tuple
        let newbuilder = snd tuple
        getLines newLines newbuilder

[<EntryPoint>]
let main argv =
    Text.StringBuilder()
    |> getLines []
    |> ... and so on


texts:
I'm just starting to experiment with F# (from a C# background).  I think I'm starting to get into the right way of thinking, but this code still seems pretty awkward.  Is there a better (more terse) way to accoAny comments appreciated.  (BTW, this is supposed to sum all even fibonacci numbers up to 4,000,000)

let rec fib x y max acc =
    let z = x + y
    if z < max then
        if z%2=0 then
            fib y z max (z + acc)
        else
            fib y z max acc
    else
        acc

let result = fib 1 2 4000000 2

printfn "%d" result


texts:
I'm new to Haskell, so I wrote a program to crack Caesar Ciphered text for practice. The program calculates the frequency of each letter in the input, and then checks to see which shift minimizes the Euclidean norm of the element-wise difference between the text's frequencies and pre-measured frequencies in the English language. The program prints the shift to stdio and writes the decrypted text to {input file name}_DECRYPTED.

While this isn't actually a great (let alone mediocre) decryption method, I'd appreciate any input about how to improve my code to make it more "Haskell-like" or idiomatic. Syntax and readability suggestions are also more than welcome.

Thank you!

import System.Environment (getArgs)
import System.IO
import Data.List (elemIndex)
import Data.Char (ord, chr, isUpper, isAlpha, toLower)
import Data.Bool (bool)
import Data.Map (fromListWith, toList)

-- English letter frequencies from A to Z
frequencies :: (Fractional a) => [a]
frequencies = [0.0812,
               0.0149,
               0.0271,
               0.0432,
               0.1202,
               0.023,
               0.0203,
               0.0592,
               0.0731,
               0.001,
               0.0069,
               0.0398,
               0.0261,
               0.0695,
               0.0768,
               0.0182,
               0.0011,
               0.0602,
               0.0628,
               0.091,
               0.0288,
               0.0111,
               0.0209,
               0.0017,
               0.0211,
               0.0007]

main :: IO()
main = do
  (filename: _) <- getArgs
  handle <- openFile filename ReadMode
  encrypted <- hGetContents handle
  let shift_size = decrypt (map toLower $ filter isAlpha encrypted) in
    do
    print shift_size
    writeFile (filename ++ "_DECRYPTED") (shift (negate shift_size) encrypted)
  hClose handle

shift :: Int -> String -> String
shift s input = map (shiftLetter s) input

shiftLetter :: Int -> Char -> Char
shiftLetter offset c
  | isAlpha c =
    let i = ord $ bool 'a' 'A' (isUpper c)
    in chr $ i + mod ((ord c - i) + offset) 26
  | otherwise = c

decrypt :: String -> Int
decrypt text = let len = fromIntegral $ length text
                   (_, freq) = unzip $ toList $ fromListWith (+) [(c, 1.0) | c <- text]
                   in minShift frequencies $ map (flip (/) len) freq

minShift :: (Fractional a) => (Ord a) => [a] -> [a] -> Int
minShift freq1 freq2 = let norms = map (\x -> norm freq1 (shiftList freq2 x)) [0..25]
                           (Just num) = elemIndex (minimum norms) norms in num

shiftList :: (Fractional a) => [a] -> Int -> [a]
shiftList freq x = iterate oneCycle freq !! x

oneCycle :: (Fractional a) => [a] -> [a]
oneCycle (x:xs) = xs ++ [x]

norm :: (Fractional a) => [a] -> [a] -> a
norm xs ys = foldl (\acc -> \(x, y) -> acc + (x - y)^2) 0 $ zip xs ys


texts: Displaying number of unread posts for a message board

texts:
I am working on a Rails 3.2.6 app for a friend which implements some message board functionality. Users can post messages into a categories. Each user also has a list of other users they have friended.

I got a feature request recently to display the number of unread posts made by the current user's friends next to each category. This is tracked on a category basis, not a per post basis, since the posts are displayed on a main newsfeed and you can't read a single post. So the feature request states that when a user clicks a category, which filters posts by that category, it will reset the unread count for that category.

I've implemented the unread counter by adding a database table that tracks the last time a user "read" all the messages. The table contains user_id, category_id, and last_read_time.

Now I am trying to implement the unread counters. I set up some scopes in my Post model (some of these are used in different places, which is why they are separate scopes):

scope :by_users, lambda { |users| where("user_id IN (?)", users) unless users.nil? }
scope :by_categories, lambda { |categories| where("category_id IN (?)", categories) unless categories.nil? }
scope :since, lambda { |date| where("updated_at > ?", date) unless date.nil? }

Here is my first crack at an unread method (also in the Post model):

def self.unread_count(user, category)
  read_time = ReadStatus.where("user_id = ? AND category_id = ?", user.id, category.id).first

  if read_time.nil?
    #handle it
  end

  #if user has no friends, there will be no unread posts displayed
  if user.friends.count == 0
    return
  else
    friends = user.friends
  end

  unread = by_users(friends).since(read_time.last_read_time).by_categories(category.id).count

  unless unread == 0
    "(" + unread.to_s + " new)"
  end
end

This works fine, but I would like to make this more efficient. Right now, there are 81 categories users can post in. This means when the homepage loads there are 81 count queries firing off, and this is repeated anytime the homepage is re-loaded. I can't think of any way to cache this value or eliminate these queries, since the unread count can change at any given moment and needs to be refreshed when the page is reloaded.

Any tips/tricks/Rails pixie dust to make this better? Every solution I think of either results in stale counter values or a large DB hit (for what I feel is a fairly trivial "feature").


texts:
I need to expand logical patterns to list of strings.

For example I have the following definition:

(expand-pattern '(and "xy"
                      (or "1" "2")
                      (or (and "ab0"
                               (or "1" "2" "3"))
                          "cd01")))

Which evaluates to the following list of strings:

("xy1ab01" "xy2ab01" "xy1ab02" "xy2ab02" "xy1ab03" "xy2ab03" "xy1cd01" "xy2cd01")

I wrote the following code:

(defun expand-pattern (pattern)
  (defun expat (parents expr)
    (pcase expr
      ((or (pred stringp)
           (pred numberp))   (mapcar (lambda (parent)
                                     (cons expr parent))
                                     parents))
      (`(and ,first)         (expat parents first))
      (`(and ,first . ,rest) (expat (expat parents first)
                                    (cons 'and rest)))
      (`(or . ,args)         (apply #'append
                                    (mapcar (lambda (arg)
                                              (expat parents arg))
                                            args)))
      (_                     (error "unknown %S" expr))))
  (mapcar (lambda (tokens)
            (mapconcat (lambda (token)
                         (format "%s" token))
                       (reverse tokens)
                       ""))
          (expat '(()) pattern)))

I am new to Emacs Lisp and would like to know, if this is a reasonable way to solve the problem in Elisp or if it can be optimized, to simplify the code.


texts: In n circle size removing k th person every time until 1 remains

texts:
In one site there was one practice question which ask you to make one program:

  Tapas and Meghana are appointed as the one responsible for interviews
  of AXIS Core committee '17 ! In order to decide upon the order in
  which to call the aspirants for the interview, they have come up with
  a brilliant game. It goes like: the core game is divided into \$N\$
  phases; and \$N\$ aspirants, successively numbered from \$1\$ to \$N\$, are moving
  round a circle one after another, i.e. the first follows the second,
  the second follows the third, ..., the \$(N-1)\$th follows the \$N\$th, and
  the \$N\$th follows the first. At each phase, a single aspirant is made
  to leave the circle and is taken up for interview. While the others
  continue to move. At some phase, the circle is left by an aspirant,
  who is marching \$K\$ positions before the one, who left the circle at the
  previous phase. An aspirant, whose number is \$K\$, leaves the circle at
  the first phase.

  Input The only line contains the integer numbers \$N\$, and \$K\$.

  Output You should output the order in which in the aspirants give
  their interviews. The numbers should be separated by single spaces.

  Constraints \$1\le N\le 100000\$; \$1\le K\le N\$.

According to my understanding this question is related to queue.

My program:

a,b = raw_input().split()
a = int(a)
b = int(b)
c = []
d = []
for i in range(a, 0, -1):
    c.append(i)
while len(c) != 0:
    for i in range(1, b):
        f = c.pop()
        c.insert(0, f)
    print c.pop(),

This code was working fine but on some input cases it was showing time limit exceed. So I was wondering that if there is any algorithm which can work better than this or is there any problem with my code which I don't know ?


texts: Helper Method for Generating Stubbed ICommand in Rhino Mocks

texts:
This helper method is designed to make stubbing ICommands simpler.

Do you see any problems with this implementation?

public static ICommand GenerateCommandStub(
    Action<object> executeAction = null,
    Func<object, bool> canExecuteFunc = null)
{
    var commandStub = MockRepository.GenerateStub<ICommand>();
    commandStub.Stub(command => command.Execute(Arg<object>.Is.Anything))
        .Do(executeAction ?? (_ => { }));
    commandStub.Stub(command => command.CanExecute(Arg<object>.Is.Anything))
        .Do(canExecuteFunc ?? (_ => true));
    return commandStub;
}


texts: Password Checker using Pwnedpasswords API in Rust

texts:
This takes a user password, hashes password to SHA1 and does a check against the Pwnedpasswords database.

I know I need to use unwrap less and do more real checking to improve the clarity of errors. In what other places is my code lacking and what should I learn or look at to improve in the future.

The current resources I am using are the Rust by Example. The documentation for the crates I used and in general looking at rust code on GitHub.

$ cargo run --bin checker -- check
Password: *********
Password is (not) compromised

#[macro_use] extern crate clap;
extern crate crypto;
extern crate reqwest;
extern crate regex;
extern crate rpassword;

use crypto::digest::Digest;
use crypto::sha1::Sha1;
use clap::App;
use regex::Regex;

/* loads clap cli config
 * if the check subcommand is used, run check
 */
fn main () {
    let yaml = load_yaml!("config/clap_cli.yml");
    let matches = App::from_yaml(yaml).get_matches();

    if let Some(_m_check) = matches.subcommand_matches("check") {
        check();
    }

}

/* get password from user
 * hash the password
 * check against pwned database
 * tell user if the password is bad
 */
fn check () {
    let value = &rpassword::prompt_password_stdout("Password: ")
        .unwrap();
    let mut hasher = Sha1::new();

    hasher.input_str(value);
    let pass_hash = hasher.result_str().to_uppercase();
    let pass_hash_slice = pass_hash.get(0..5).unwrap();
    let pass_hash_end = pass_hash.get(5..).unwrap();

    let body = reqwest::get(
        &format!("https://api.pwnedpasswords.com/range/{}", pass_hash_slice)
        ).unwrap().text().unwrap();

    let re_pass = Regex::new(&pass_hash_end).unwrap();

    if re_pass.is_match(&body) {
        println!("Password is compromised.");
    } else {
        println!("Password is not compromised.");
    }
}


texts: Implementation of MVC pattern for single and multiple objects

texts:
I've implemented a student administration with MVC pattern (Tutorial: Link). I've decided to divid the students in "SingleStudentModel" and "MultipleStudentModel", but I'm not sure if that make sense in my case. In general, I'm not satisfied with my solution. Is it possible to handle single student and multiple students with one controller?
Is it ok if a model import into a view class (see StudentsView.java)?

How can I improve this project?

Thanks in advance.

Student.java (Model, data class (?))

public class Student {

    private String name;
    private int nr;

    public Student(String _name, int _nr){
        this.name = _name;
        this.nr = _nr;
    }

    // get set
}

SingleStudentModel.java (Model)

public class SingleStudentModel {
    private Student student;

    // get set
}

StudentController.java (Controller -> SingleStudentModel)

public class StudentController {
    private SingleStudentModel model;
    private StudentView view;

    public StudentController(SingleStudentModel _model, StudentView _view){
        this.model = _model;
        this.view = _view;
    }

   // set get

    public void updateView(){
        view.printStudentDetails(model.getStudent().getName(), model.getStudent().getNr());
    }
}

MultipleStudentModel.java (Model)

public class MultipleStudentModel {
    private Collection<Student> students = new ArrayList<Student>();

    public Collection<Student> getStudents() {
        return students;
    }

    public void setStudents(Student student){
        this.students.add(student);
    }
}

StudentsController.java (Controller -> StudentsModel)

public class StudentsController {
    private MultipleStudentModel model;
    private StudentsView view;

    public StudentsController(MultipleStudentModel _model, StudentsView _view){
        this.model = _model;
        this.view = _view;
    }

    public void updateView(){
        view.printStudentList(model.getStudents());
    }
}

StudentView.java

public class StudentView {
    public void printStudentDetails(String _name, int _nr){
        System.out.println("Student: ");
        System.out.println("name: " + _name);
        System.out.println("nr: " + _nr);
    }
}

StudentsView.java

import com.mvc.model.Student;

import java.util.Collection;

public class StudentsView {

    public void printStudentList(Collection<Student> students){

        System.out.println("\nStudent list");

        for(Student item : students){
            System.out.println("name: " + item.getName());
            System.out.println("nr: " + item.getNr());
        }
    }
}

Main.java

 public class Main {

       public static void main(String [] args){

            //Single student
            SingleStudentModel model = new SingleStudentModel();
            StudentView view = new StudentView();
            StudentController controller = new StudentController(model, view);

            model.setStudent(new Student("John", 1));

            controller.updateView();

            //Multiple student
            MultipleStudentModel model2 = new MultipleStudentModel();
            StudentsView view2 = new StudentsView();
            StudentsController controller2 = new StudentsController(model2, view2);

            model2.setStudents(new Student("Zelda", 2));
            model2.setStudents(new Student("Link", 3));

            controller2.updateView();

            }
      }


texts: Stacking frames of a video file horizontally into a single image

texts:
I stumbled upon a post on Reddit a few days ago and I thought I make my own! It's a program to extract from a movie file (.mkv, .mp4, etc.) and stack them horizontally next to each other and make one picture of all the frames available in the movie file. how can I make it more pythonic, readable, and sufficient?
Also, THIS is the GitHub link, pull requests are welcome.
Also, the default frame rate (the number of frames to extract one from, to stack up in the output image) is 5.
from natsort import natsorted
from ffprobe import FFProbe
from time import sleep
from tqdm import tqdm
from PIL import Image
import cv2
import os

# get and format file path
path = input('All modules loaded, press enter to proceed...\nEnter file path to the file(w/ filename, w/out the last backslash):\n')

if not os.path.exists(path):
    print("Path is incorrect, quitting")
    exit(0)
if path[0] == "~":
    os.path.expanduser(path)  # replace ~ with literal home address
meta = FFProbe(path)
# get metadata
video_duration = meta.metadata["Duration"][:-3]
rate = meta.video[0].framerate
height = int(meta.video[0].width)
# one shot per 5 seconds
freq = int(rate) * 5

# info for the process bar
hours = int(video_duration[1]) * 3600
minutes = int(video_duration[3:5]) * 60
seconds = int(video_duration[-2:])
duration_seconds = hours + minutes + seconds
frames = rate * duration_seconds
output_images = frames // freq  # number of extracted images

(directory, video_name) = os.path.split(path)

dst_path = directory + "/images/"
os.system("mkdir " + dst_path)
os.system("mkdir " + dst_path + "resized")
print("Destination folder created.\n")

print("Extracting frames...")
cap = cv2.VideoCapture(path)
i = 1  # current captured frame, how many 24's has already been iterated
os.system('clear')
with tqdm(total=frames) as pbar:
    while cap.isOpened():
        frame_id = cap.get(1)  # first frame in the current stream
        ret, frame = cap.read()
        if ret != True:  # if run out of frames, video finished
            break
        if frame_id % freq == 0:  # if frame# is a multiplicand of freq=24
            filename = dst_path + str(i) + ".jpg"
            i += 1
            cv2.imwrite(filename, frame)  # create the image
        pbar.update(1)
print(str(output_images) + " images extracted successfully.")
cap.release()
del pbar

src_path = directory + "/images/"
dst_path = src_path + "resized/"

images = natsorted(os.listdir(src_path))

os.system("clear")
i = 1
max_counter = len(images) - 1  # all images count
with tqdm(total=output_images) as pbar:
    for image in images:
        if i <= max_counter:  # process until all images are done
            read_path = src_path + image
            img = cv2.imread(read_path, cv2.IMREAD_UNCHANGED)
            w = 2  # convert to 2px
            h = img.shape[1]  # unchanged
            dim = (w, h)
            resized = cv2.resize(img, dim)
            filename = dst_path + str(i) + "_re.jpg"
            cv2.imwrite(filename, resized)  # create the image
            if i == 1:  # do only once
                print(str(img.shape) + " convert to " + str(dim))
            i += 1
            pbar.update(1)
        else:
            print("Finished " + str(len(images) - 1) + " pictures.")

images_list = natsorted(os.listdir(dst_path))

images_list = [Image.open(dst_path + x) for x in images_list]

# we have the height, user input #3
width = len(images_list) * 2  # number of small pictures, each 2px
out = Image.new("RGB", (width, height))  # create an empty image

x_offset = 0
for im in images_list:
    out.paste(im, (x_offset, 0))
    x_offset += im.size[0]

out.save(directory + "/" + video_name[:-4] + ".jpg")
print("Cleaning Up...")
os.system("rm -rf " + src_path)

print("All set, finishing now.")


texts:
I am wondering, how can I improve this simple MissingResource exception class? I am using it in my simple game.
template <typename Resource>
class MissingResource : public std::exception {
    std::string_view fileName{};
    std::string_view msg{};

public:
    MissingResource() = default;
    MissingResource(std::string_view fileName)
    : fileName{fileName}
    {
        initMsg<Resource>();
    }

    template <typename T>
    void initMsg() {
        msg = "Failed loading resource: "
              "{ Type: "    + std::string(typeid(Resource).name()) + ", "
              "File name: " + fileName.data()                      + " }";
    }

    virtual const char* what() const noexcept override {
        return msg.data();
    }
};

Throw usage:
template <typename Key, typename Resource>
#if (__cplusplus == 202002L)
  requires Mappable<Key>
#endif
class ResourceHolder {
    std::unordered_map<Key, std::unique_ptr<Resource>> resources;
    std::string resourcesDir;

public:

    explicit ResourceHolder(std::string_view resourcesDir = "../resources/")
            : resourcesDir{std::move(resourcesDir)}
    {}

    template <typename... Args>
    void insert(const Key& key, std::string_view fileName, Args&&... args) {
        auto resPtr = std::make_unique<Resource>();

        bool loaded{};
        if constexpr (std::is_same<Resource, sf::Music>()) {
            loaded = resPtr->openFromFile(resourcesDir + fileName.data(), std::forward<Args>(args)...);
        } else {
            loaded = resPtr->loadFromFile(resourcesDir + fileName.data(), std::forward<Args>(args)...);
        }

        /** Called here */
        if (!loaded) {
            throw MissingResource<Resource>(fileName);
        }
        resources.emplace(key, std::move(resPtr));
}

Try-Catch usage:
ResourceManager::ResourceManager() {
    try {
        loadResources();
    } catch (const std::exception& e) {
        std::cerr << e.what() << std::endl;
        std::exit(EXIT_FAILURE);
    }
}

Exemplary error message:
what():  Failed loading resource: { Type: N2sf11SoundBufferE, File name: Death.wav }

P.S: If you see some smelly code or have doubts or found any kind of other mistakes, I would be looking forward to knowing them. Thanks!


texts:
Looking for review, good practices, optimizations, clean code tips etc.

/**
 * Flip the columns.
 *
 * Complexity:
 * O(row * col)
 *
 */
public final class Mirror {

    private Mirror () { }

    /**
     * Given a matrix create a mirror image,
     *
     * @param m     the input matrix
     * @throws      NPE if exception occurs.
     */
    public static void mirrorPatch(int[][] m) {
        // for each row.
        for (int i = 0; i < m.length; i++) {
            // for each column
            flipRow(m[i]);
        }
    }

    private static void flipRow(int[] row) {
        int length = row.length;
        // simple swap of each element.
        for (int i = 0; i < length/2; i++) {
            int x = row[i];
            row[i] = row[length -1 - i];
            row[length -1 - i] = x;
        }
    }

    public static void main(String[] args) {
        // even number of columns.
        int[][] m = { {1, 2, 3, 4} , {10, 20, 30, 40}};
        mirrorPatch(m);

        /*
         * Informally verifying that output is:
         * 4   3   2   1
         * 40  30  20  10
         *
         */
        for (int i = 0; i < m.length; i++) {
            for (int j = 0; j < m[0].length; j++) {
                System.out.print(m[i][j] + " ");
            }
            System.out.println();
        }

        System.out.println("-----------------------------------");

        // odd number of columns.

        /*
         * Informally verifying that output is:
         *  5   4   3   2   1
         *  50  40  30  20  10
         */
        int[][] m1 = { {1, 2, 3, 4, 5} , {10, 20, 30, 40, 50}};
        mirrorPatch(m1);

        for (int i = 0; i < m1.length; i++) {
            for (int j = 0; j < m1[0].length; j++) {
                System.out.print(m1[i][j] + " ");
            }
            System.out.println();
        }

        System.out.println("-----------------------------------");
    }
}


texts:
I'm posting my code for a LeetCode problem copied here. If you would like to review, please do so. Thank you for your time!
Problem

In a network of nodes, each node i is directly connected to another
node j if and only if graph[i][j] = 1.
Some nodes initial are initially infected by malware.  Whenever two
nodes are directly connected and at least one of those two nodes is
infected by malware, both nodes will be infected by malware.  This
spread of malware will continue until no more nodes can be infected in
this manner.
Suppose M(initial) is the final number of nodes infected with
malware in the entire network, after the spread of malware stops.
We will remove one node from the initial list.  Return the node that
if removed, would minimize M(initial).  If multiple nodes could be
removed to minimize M(initial), return such a node with the smallest
index.
Note that if a node was removed from the initial list of infected
nodes, it may still be infected later as a result of the malware
spread.

Inputs
[[1,1,0],[1,1,0],[0,0,1]]
[0,1]

[[1,0,0,0],[0,1,0,0],[0,0,1,1],[0,0,1,1]]
[3,1]

[[1,0,0],[0,1,0],[0,0,1]]
[0,2]

[[1,1,1],[1,1,1],[1,1,1]]
[1,2]

Outputs
0

3

0

1

Code
#include <vector>
#include <algorithm>

struct Solution {
    std::vector<int> parents;
    inline int minMalwareSpread(const std::vector<std::vector<int>> &graph, const std::vector<int> &initial) {
        size_t length = graph.size();

        for (size_t index = 0; index < length; index++) {
            parents.push_back(index);
        }

        for (size_t row = 0; row < length; row++) {
            for (size_t col = row + 1; col < length; col++) {
                if (graph[row][col]) {
                    union_uf(row, col);
                }
            }
        }

        std::vector<int> areas(length, 0);
        std::vector<int> malwares(length, 0);

        for (size_t area = 0; area < length; area++) {
            areas[find(area)]++;
        }

        for (size_t init : initial) {
            malwares[find(init)]++;
        }

        std::vector<int> min_spread = {1, 0};

        for (int init : initial) {
            min_spread = std::min(min_spread, {(malwares[find(init)] == 1) * (-areas[find(init)]), init});
        }

        return min_spread[1];
    }

private:
    const inline size_t find(const size_t x) {
        if (x != parents[x]) {
            parents[x] = find(parents[x]);
        }

        return parents[x];
    }

    const inline void union_uf(const size_t x, const size_t y) {
        parents[find(x)] = find(y);
    }
};

Algorithm
You can read about various algorithms here in this link:

We'd first map the graph using Disjoint Set Union (DSU).
We'd count all areas as well as all infected sets.
If there'd be only one malware set, we would return the largest. Otherwise, we'd return the set with lowest index using the last loop.

References

Problem

Solution

Discuss

Union Find


texts:
I have the follow function:

Download.prototype.fundamentals = function(exchanges, cb){

    if (!(exchange = exchanges.pop())) return

    var that = this;

    this.login(function(err){

        if (err) return cb(true, exchange.code)

        var path = util.format(that.eoddata.fundamentals['path'], that.token, exchange.code)

        that.get(that.eoddata.fundamentals['host'], path, function(err, data){
            if (err) return cb(true, exchange.code)

            that.xml(data, function(err, data){
                if (err || data['@'].Message != 'Success') return cb(true, exchange.code)

                var stocks = data['FUNDAMENTALS']['FUNDAMENTAL']

                that.insert(stocks, exchange, function(){
                    cb(false, exchange.code)
                })

                that.fundamentals(exchanges, cb)
            })

        })

    })
}

I think it easy to understand, I pop() an element to a list and then do other operations, and then recall the function to pop() another element.

I have a doubt regarding the writing of the function, now it works, but it does not seem very optimized. Example: I do not like var that = this.

How could I rewrite it better?


texts: Bash function to find contents of a file with a certain extension

texts:
I have to read a lot of code and search through many code bases. I frequently find myself using something like grep -r --include=.C "test string" . to find files containing a certain string or regular expression. However, to simplify this and expedite the process, I want to create a function that allows me to specify what I am looking for, what are acceptable file extensions and what are inacceptable file extensions.

The function I have written is below. I am not sure if this follows best practices. Also, the hack using the brace expansion with the .\? is bad. I really appreciate any feedback that you have.

findInFile() {
  # Function to be placed in bash profile
  # Allows user to specify what contents of a file they are looking for
  # in what file types and in what NOT file types
  # Iterate over the number of scripts arugments
  # TODO: How can I create documentation for this function outside of code comments?
  while [[ "$#" -gt 0 ]]
  do
    case $1 in
      -ft|--fileTypes)
        local fileTypes=$2
        ;;
      -et|--excludeTypes)
        local excludeTypes=$2
        ;;
      *) # Catch the case where user does not specify
         # these arguments
        local searchTerm=$1
        ;;
    esac
    shift
  done

  echo "fileTypes: $fileTypes"
  echo "excludeTypes: $excludeTypes"
  echo "searchTerm: $searchTerm"

  # TODO: Should probably clean up with case statement
  # TODO: I am using this \? in the include and exclude as a hack
  # to catch the case where only one file type is provided.
  if [ -n "$fileTypes" ] && [ -n "$excludeTypes" ]
  then
    #searchString="grep -r --include=\*{$fileTypes} --exclude=\*{$excludeTypes} "$searchTerm" ."
    searchString="grep -r --include=\*{$fileTypes,.\?} --exclude=\*{$excludeTypes,.\?} "$searchTerm" ."

  elif [ -n "$fileTypes" ]
    then
      #searchString="grep -r --include=\*{$fileTypes} "$searchTerm" ."
      searchString="grep -r --include=\*{$fileTypes,.\?} "$searchTerm" ."
  elif [ -n "$excludeTypes" ]
    then
      #searchString="grep -r --exclude=\*{$excludeTypes} "$searchTerm" ."
      searchString="grep -r --exclude=\*{$excludeTypes,.\?} "$searchTerm" ."
  else
      searchString="grep -r "$searchTerm" ."
  fi

  #searchString="grep -r --include=\*{$fileTypes} "$searchTerm" ."
  echo "searchString: $searchString"
  eval $searchString

  # TODO: Allow the user to type a number to then programmatically jump to that
  # file in the text editor of their choice

}


texts:
I've been playing around with Python off and on for about the past year and recently came up with the following 68 (was 62) lines. I think I'll try making a calculator out of it. I'd really like to know what readers here think of its attributes such as coding style, readability, and feasible purposefulness.

# notes: separate addresses from data lest the loop of doom cometh

class Interpreter:

  def __init__(self):
    self.memory = { }
    self.dictionary = {"mov" : self.mov,
                       "put" : self.put,
                       "add" : self.add,
                       "sub" : self.sub,
                       "clr" : self.clr,
                       "cpy" : self.cpy,
                       "ref" : self.ref }
    self.hooks = {self.val("0") : self.out }

  def interpret(self, line):
    x = line.split(" ")
    vals = tuple(self.val(y) for y in x[1:])
    dereferenced = []
    keys_only = tuple(key for key in self.memory)
    for val in vals:
      while val in self.memory: val = self.memory[val]
      dereferenced.append(val)
    vals = tuple(y for y in dereferenced)
    self.dictionary[x[0]](vals)

  def val(self, x):
    return tuple(int(y) for y in str(x).split("."))

  def mov(self, value):
    self.ptr = value[0]

  def put(self, value):
    self.memory[self.ptr] = value[0]

  def clr(self, value):
    if self.ptr in self.hooks and self.ptr in self.memory:
      x = self.hooks[self.ptr]
      y = self.memory[self.ptr]
      for z in y: x(z)
    del self.memory[self.ptr]

  def add(self, values):
    self.put(self.mat(values, lambda x, y: x + y))

  def sub(self, values):
    self.put(self.mat(values, lambda x, y: x - y))

  def mat(self, values, op):
    a, b = self.memory[values[0]], self.memory[values[1]]
    if len(a) > len(b): a, b = b, a
    c = [op(a[x], b[x]) for x in xrange(len(b))] + [x for x in a[len(a):]]
    return [tuple(x for x in c)]

  def cpy(self, value):
    self.put(value)

  def out(self, x):
    print chr(x),

  def ref(self, x):
    self.put(x)

interp = Interpreter()
for x in file(__file__.split('/')[-1].split(".")[-2] + ".why"):
  interp.interpret(x.strip())


texts: Animating the opacity of certain page elements

texts:
I wrote this jQuery code to animate the opacity (sort of Fadein) of certain elements on my page in consecutive order. It feels very inelegant, though.

(function($) {
     function animateFadin($delayedElement, delayTime) {
        $delayedElement.delay(delayTime).animate({
            opacity: 1
        }, 700);
    }
    $(document).ready(function(){
        animateFadin($('#zone-branding-wrapper'),100);
        animateFadin($('#zone-menu-wrapper'),500);
        animateFadin($('#zone-content-wrapper'),600);
        $(".view-nodequeue-1 a[href]").delay(600).each(function(index) {
            $(this).delay(200*index).animate({
            opacity: 1
        }, 100);
        });
    });
}) (jQuery);

Is there a way to reuse the named function animateFadin inside the each?


texts:
Is this a good compromise between readability and verbosity? Are there any bugs, additional error checking, or extraneous code as well?

// Generate permutations of array of n..n+x
// n must have no repetitions, sorted smallest to largest
// Steinhaus-Johnson-Trotter algorithm
// Results are not in lexicographical order

// Switch to using a generator when n! becomes too large. ~12 or 13 probably.

#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

enum directions { LEFT, RIGHT };

int **permute(int array[], int n);
bool mobile(int array[], int dir[], int count, int n);
void swap(int array[], int a, int b);

void printArray(int *array, int n, char c);
long long factorial(int n);

int **permute(int array[], int n) {
  if (n < 1) {
    return NULL;
  }

  int bigInd;    // index of largest mobile num
  int bigNum;    // largest mobile num
  bool ismobile; // If there is still a mobile number
  int counter = 0;

  int fact = factorial(n);

  int *dir;
  int **res;
  if ((dir = malloc(n * sizeof(int))) == NULL) {
    fprintf(stderr, "Error allocating memory\n");
    exit(EXIT_FAILURE);
  }
  for (int i = 0; i < n; i++) {
    dir[i] = LEFT;
  }

  if ((res = malloc(fact * sizeof(int *))) == NULL) {
    fprintf(stderr, "Error allocating memory\n");
    exit(EXIT_FAILURE);
  }
  for (int i = 0; i < fact; i++) {
    if ((res[i] = malloc(n * sizeof(int))) == NULL) {
      fprintf(stderr, "Error allocating memory\n");
      exit(EXIT_FAILURE);
    }
  }

  while (1) {
    memcpy(res[counter], array, n * sizeof(int));
    counter++;
    bigInd = 0;
    bigNum = 0;
    ismobile = false;
    for (int i = 0; i < n; i++) {
      if (mobile(array, dir, n, i)) {
        ismobile = true;
        if (array[i] > bigNum) {
          bigInd = i;
          bigNum = array[i];
        }
      }
    }
    if (!ismobile) {
      break;
    }
    if (dir[bigInd] == LEFT) {
      swap(array, bigInd, bigInd - 1);
      swap(dir, bigInd, bigInd - 1);
    } else {
      swap(array, bigInd, bigInd + 1);
      swap(dir, bigInd, bigInd + 1);
    }

    for (int i = 0; i < n; i++) {
      if (array[i] > bigNum) {
        dir[i] = !(dir[i]);
      }
    }
  }

  free(dir);
  return res;
}

void swap(int array[], int a, int b) {
  int temp = array[a];
  array[a] = array[b];
  array[b] = temp;
}

bool mobile(int array[], int dir[], int count, int n) {
  if ((n == 0 && dir[n] == LEFT) || (n + 1 == count && dir[n] == RIGHT) ||
      (dir[n] == RIGHT && array[n + 1] > array[n]) ||
      (dir[n] == LEFT && array[n - 1] > array[n])) {
    return false;
  }
  return true;
}

void printArray(int array[], int n, char c) {
  if (!array || n < 1) {
    return;
  }
  for (int i = 0; i < n; i++) {
    printf("%d", array[i]);
  }
  printf("%c", c);
}

long long factorial(int n) {
  long long result = 1;
  for (long long i = n; i > 1; i--) {
    result *= i;
  }
  return result;
}

int main(void) {
  int a[] = {1, 2, 3, 4, 5};
  int length = sizeof(a) / sizeof(a[0]);
  int fact = factorial(length);
  int **r = permute(a, length);
  for (long long i = 0; i < fact; i++) {
    printf("%*lld: ", 3, i + 1);
    printArray(r[i], length, '\n');
  }
  for (long long i = 0; i < fact; i++) {
    free(r[i]);
  }
  free(r);
}


texts: High performance primitive dynamic array

texts:
Unfortunately Java does not support generic programming with primitive types. Using collections classes with boxed types may increase memory usage by a factor of 3-4 (e.g. int being 32-bit and Integer 128-bit). Throughput may be lower, with some tests demonstrating boxed types being at least 10 times slower. This seems consistent with my own measurements. I have not found any official (Oracle) or otherwise reputable implementations of primitive arrays, so here I go.

The goal is to write a fast and simple linear container for primitives. It is intended to be as similar as possible to ArrayList. It will at least implement the common array operations size(), add(int value), add(int index, int value), set(int index, int value), get(int index), remove(), remove(int index) and clear(). A few operations, like contains(Object obj) and indexOf(Object obj) will be left out, because they rely on reference types, not value types.

I'm interested in performance optimizations. Hopefully someone better knows how this code can be optimized further. Below is the implementation of int-vector, iVector. The name is only a preliminary placeholder, and vectors for other primitives can be created by changing the classname and the int-types in the implementation.

public class iVector {
    private int[] data;
    private int length = 0;

    //Constructors
    public iVector(){
        data = new int[10];
    }
    public iVector(int initialCapacity){
        if(initialCapacity < 10)
            initialCapacity = 10;
        data = new int[initialCapacity];
    }

    //Methods
    public int size(){
        return length;
    }

    public void ensureCapacity(final int capacity){
        if(capacity <= data.length) return;
        int[] newData = new int[capacity];
        System.arraycopy(data, 0, newData, 0, data.length);
        data = newData;
    }

    public void add(final int value){
        if(length == data.length)
            ensureCapacity(data.length + data.length/2); // Grow by approx. 1.5x
        data[length] = value;
        ++length;
    }

    public void add(final int index, final int value){
        if (index >= length || index < 0)
            throw new ArrayIndexOutOfBoundsException(index);
        if (length == data.length)
            ensureCapacity(data.length + data.length / 2); // Grow by approx. 1.5x
        for (int i = length; i > index; --i)
            data[i] = data[i - 1];
        data[index] = value;
        ++length;
    }

    public void set(final int index, final int value){
        if(index >= length)
            throw new ArrayIndexOutOfBoundsException(index);
        data[index] = value; //if (index<0) or (index>data.length), IndexOutOf. is thrown
    }

    public int get(final int index){
        if(index >= length)
            throw new ArrayIndexOutOfBoundsException(index);
        return data[index]; //if (index<0) or (index > data.length), IndexOutOf. is thrown
    }

    public void remove(){ // Remove last element
        if(length == 0) return;
        --length;
    }

    public int remove(int index){ // Removes and returns the removed value
        final int result = get(index);
        --length;
        for(; index < length; ++index)
            data[index] = data[index + 1];
        return result;
    }

    public void clear(){ // Make empty
        length = 0;
    }
}


texts:
Given two input arrays [-1, 8, 3] and [3, 7, 2] your function will return true if any two of the numbers in the first array add up to the any numbers in the second array.

\$-1 + 3 = 2 \therefore \text{True}\$

My algorithm simply takes all the pairs from the first input and check if they exist in second array set which the complexity of set lookup is \$O(1)\$. Overall complexity is \$O(n^2)\$ I'm pretty sure there should be a better algorithm leveraging hash tables or sorting and doing a binary search. Is there a way to make time complexity more efficient?

My code:

def arraySum(inputs, tests):
    # iterating through all possible sums and check if it exists in test by using a test set which
    #makes the complexity better with O(1) lookup in set.
    my_set=set(tests)
    for i in range(len(inputs)-1):
        for j in range(i+1,len(inputs)):
            my_sum=inputs[i]+inputs[j]
            if my_sum in my_set:
                return True
    return False #this will take care of an edge case when there is one input from each arr


texts: Copying data to a .txt, but making it look nice?

texts:
This is probably horribly sloppy, but here it is! This is a section from a large (imo) GUI program I am making. The below code is what triggers when a specific button is pressed.

 def calc_platenumber(self):
    customer_firstname = str(self.customer2_entry.get())
    customer_lastname = str(self.customer3_entry.get())

    infile = open('license_numbers.txt', 'r')

    license_numbers = infile.readlines()

    infile.close()

    self.platenmb = random.choice(license_numbers)

    self.platenumber.set(self.platenmb)

    license_numbers.remove(self.platenmb)

    outfile = open('license_numbers.txt', 'w')

    for item in license_numbers:
        outfile.write(item)

    outfile.close()

    infile = open('used_license_numbers.txt', 'r')
    used_license_numbers = infile.readlines()
    infile.close()

    used_license_numbers.append(self.platenmb)
    used_license_numbers.append(customer_firstname)
    used_license_numbers.append(customer_lastname)

    outfile = open('used_license_numbers.txt', 'w')

    for item in used_license_numbers:
        outfile.write(item)

    outfile.close()

So, I have a GUI that asks for the first name and last name of the person. There is a generate button below that. The generate button will take a random license number from a large list of available numbers, remove it from that list, and then add it to a list of "used" license numbers. That is the function you see here. When it adds it to this second list, I want it to also take their name and add it as well. I have made it do that.

Problem is, whenever it adds it, it looks sloppy. No spaces or anything. I would rather it add on like...

Tim Bob C565213

And then whenever the next person uses the program, the file is updated to say...

Tim Bob C565213
Jim Bean 1234F324

...And so on. Currently it just looks sloppy, and even if sloppy won't matter (this is just a school project), it is going to bother me.


texts:
Provided Object.prototype hasn't been modified, will the following snippet work in major browsers?

var obj = {length:0};
var push = Array.prototype.push;
push.call(obj,'1st value')
push.call(obj,'2nd value');

Many have responded that the above code is bad practice, but what makes code like this any better?

Array.prototype.slice(arguments,0)

Both are calling Array.prototypes on non Arrays.


texts: Find highly composite number using Python 3

texts:
A highly composite number (HCN) is a positive integer with more divisors than any smaller positive integer ha according to Wikipedia. Here is a YouTube video about it.

def get_divisors(number_range):
  divisor_list = []
  divisor_list2 = []
  for number in range(1,number_range+1):
    for e in range(1,number_range+1):
      if number % e == 0:
        divisor_list2.append(e)
    divisor_list.append(divisor_list2)
    divisor_list2 = []
  return divisor_list

def get_highly_composite_number(number_range):
  divisor_list = get_divisors(number_range)
  highly_composite_number_list = []
  number_of_divisor_list = []
  number_of_divisor_list2 = []
  number_of_divisor_list3 = []
  tracker = 0
  for e in divisor_list:
    number_of_divisor_list.append(len(e))
    number_of_divisor_list2.append(max(number_of_divisor_list))
  for e in number_of_divisor_list2:
    number_of_divisor_list3.append(e)
    if number_of_divisor_list3[tracker] == max(number_of_divisor_list3) and number_of_divisor_list3.count(number_of_divisor_list3[tracker]) == 1:
      highly_composite_number_list.append(tracker+1)
      tracker += 1
    else:
      tracker += 1
  return highly_composite_number_list

I know the naming is horrible, but I did not know any better ways. Also, I know this can probably be condensed, but I did not want to touch it.


texts: C++ class to compute similarity coefficients

texts:
I'm a complete beginner in C++. I wrote a class to compute similarity coefficients using Euclidean distance and Pearson coefficients on map data structure. I would like to know if it is possible to improve the code to make it more efficient in terms of memory and time it takes to execute the code.

Header:

#include <map>
#include <string>

extern "C" class DATAANALYTICS_API Similarity
{
    std::map<std::string, std::map<std::string, double>> data_;

public:
    Similarity(std::map<std::string, std::map<std::string, double>> &data);
    double EuclideanSimilarity(std::string a, std::string b);
    double PearsonSimilarity(std::string a, std::string b);
};

Implementation:

#include <iostream>
#include <map>
#include <string>
#include <cmath>
#include <vector>
#include "DataAnalytics.h"

Similarity::Similarity(std::map<std::string, std::map<std::string, double>> &data)
{
    data_ = data;
}

double Similarity::EuclideanSimilarity(std::string a, std::string b)
{
    double distance_squared = 0, aVal, bVal;
    for (auto const &entry : data_[a])
    {
        if (data_[b].count(entry.first) > 0)
        {
            aVal = entry.second;
            bVal = data_[b][entry.first];
            distance_squared += (aVal - bVal) * (aVal - bVal);
        }
    }
    return (1 / (1 + distance_squared));
}

double Similarity::PearsonSimilarity(std::string a, std::string b)
{
    double aVal, bVal, aExpectedValue = 0, bExpectedValue = 0, aSquaredExpectedValue = 0, bSquaredExpectedValue = 0, abExpectedValue = 0;
    std::vector<double> aValues, bValues, abValues;
    int commonItemCounter = 0;

    for (auto const &entry : data_[a])
    {
        if (data_[b].count(entry.first) > 0)
        {
            commonItemCounter++;
            aVal = entry.second;
            bVal = data_[b][entry.first];
            aValues.push_back(aVal);
            bValues.push_back(bVal);
            abValues.push_back(aVal * bVal);
        }
    }

    if (aValues.size() == 0)
    {
        return 0;
    }
    else
    {
        for (int i = 0; i < aValues.size(); i++)
        {
            aExpectedValue += aValues[i] / commonItemCounter;
            bExpectedValue += bValues[i] / commonItemCounter;
            aSquaredExpectedValue += pow(aValues[i], 2) / commonItemCounter;
            bSquaredExpectedValue += pow(bValues[i], 2) / commonItemCounter;
            abExpectedValue += abValues[i] / commonItemCounter;
        }
        double denominator = sqrt(aSquaredExpectedValue - pow(aExpectedValue, 2)) * sqrt(bSquaredExpectedValue - pow(bExpectedValue, 2));
        if (denominator != 0)
        {
            return (abExpectedValue - (aExpectedValue * bExpectedValue)) / denominator;
        }
        else
        {
            return 0;
        }
    }
}

When I run unit tests on the two methods EuclideanSimilarity and PearsonSimilarity, they both take about 130ms to complete which is a bit strange because I'm doing a lot more in PearsonSimilarity than in EuclideanSimilarity.


texts: How can I better the readability of inline test data?

texts:
[TestCase(new[] { 1, 2 }, 1, Result = 2)]
[TestCase(new[] { 1, 2 }, 2, Result = 1)]
[TestCase(new[] { 1, 2, 3 }, 2, Result = 2)]
[TestCase(new[] { 1, 2, 3, 4 }, 2, Result = 2)]
[TestCase(new[] { 1, 2, 3, 4 }, 10, Result = 1)]
public int TotalPageCountIsAccurate(int[] testSequence, int pageSize)
{
    var pagedList = new PagedList<int>(testSequence, 0, pageSize);
    return pagedList.TotalPageCount;
}

I wrote this test about five minutes ago and I can barely understand it - I dread to think how hard it will be to read in a few weeks. How can I refactor the TestCase attribute to improve readability?

I thought about using named arguments or (maybe) introducing a some well-named fields, but neither of these ideas appear to be feasible.


texts: Extract version string from text file with Powershell

texts:
I need to pull the version # out of a Vim script that might look something like:

 " some header blah blah
 " Version: 0.1
 [a bunch of code]
 " Version: fake--use only the first version

The expected output is 0.1. If a Version # doesn't exist, it should return the empty string or something like that.

I'm new to Powershell, so this is what I have so far:

Get-Content somescript.vim -ErrorAction SilentlyContinue |
    Select-String '^" Version: (.*)' |
    select -First 1 -ExpandProperty Matches |
    select -ExpandProperty Groups |
    select -Index 1 |
    select -ExpandProperty Value

It's just that it feels... kind of verbose. For comparison, here's my *nix version:

perl -ne '/^" Version: (.*)/ && do { print "$1\n"; exit }' somescript.vim 2>/dev/null

Or you could write a similarly concise awk script

Is there any hope for my Windows version being as concise?


texts: Fill missing dates into array of np.datetime

texts:
Here is the problem:

Given an array of a non-continuous sequence of dates. Make it a
continuous sequence of dates, by filling in the missing dates.

# Input

dates = np.arange(np.datetime64('2018-02-01'), np.datetime64('2018-02-25'), 2)

print(dates)
#> ['2018-02-01' '2018-02-03' '2018-02-05' '2018-02-07' '2018-02-09'
#>  '2018-02-11' '2018-02-13' '2018-02-15' '2018-02-17' '2018-02-19'
#>  '2018-02-21' '2018-02-23']

And here is my solution:
import numpy as n
dates = np.arange(np.datetime64('2018-02-01'), np.datetime64('2018-02-25'), 2)
stride = (dates[1] - dates[0])
result = np.arange(np.datetime64(dates[0]), np.datetime64(dates[-1] + stride))
print(dates)
print(result)

Is there a better way to do this task?


texts:
Which option is better?

In the first case, I use a universal repository that can work with any entities. The methods of this repository have many parameters, such as string queries, table names, entity mappers, etc. Another option is to use for each entity separate repository (which is probably a good practice).

Advantages of the first option

One class/service for all entities
You can send any query string and
perform a complex query

Minuses

Domain layer knows many details about the repository, for example
Cursor (Android SDK)
For each request would have to actually write the method in the repository

What do you think?

Option 1

Local Service

public interface LocalService {
    <T> Observable<List<T>> get(String table, String sql, Func1<Cursor, T> mapper);
    void removeAll(String table, String sql);
    <T> long save(T item, String table, Func1<T, ContentValues> mapper);
    <T> int update(T item, String table, String where, String[] args, Func1<T, ContentValues> mapper);
}

LocalServiceImpl

public class LocalServiceImpl  implements LocalService {

    BriteDatabase briteDatabase;

    public LocalServiceImpl(BriteDatabase briteDatabase) {
        this.briteDatabase = briteDatabase;
    }

        @Override
        public <T> Observable<List<T>> get(String table, String sql, Func1<Cursor, T> mapper) {
            return briteDatabase.createQuery(table, sql)
                    .mapToList(mapper)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread());
        }

        @Override
        public void removeAll(String table, String sql) {
            briteDatabase.createQuery(table, sql)
                    .subscribe();
        }

        @Override
        public <T> long save(T item, String table, Func1<T, ContentValues> mapper) {
            return briteDatabase.insert(EventItem.TABLE, mapper.call(item));
        }

        @Override
        public <T> int update(T item, String table, String where, String[] args, Func1<T, ContentValues> mapper) {
            return briteDatabase.update(table,
                    mapper.call(item),
                    SQLiteDatabase.CONFLICT_IGNORE,
                    where,
                    args);
        }
    }

Option 2

UserRepository

public interface UserRepository {
           Observable<List<User>> users();
           Observable<User> user(int userId);
    }

UserRepositoryImpl

    public class UserRepositoryImpl implements UserRepository {

        BriteDatabase briteDatabase;

        public UserRepositoryImpl(BriteDatabase briteDatabase) {
            this.briteDatabase = briteDatabase;
        }

        @Override
        public Observable<List<User>> users() {
            return briteDatabase.createQuery(User.TABLE, "SELECT * FROM " + User.TABLE)
                    .mapToList(User.MAPPER)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread());
        }

        @Override
        public Observable<User> user(int userId) {
            return briteDatabase.createQuery(User.TABLE, "SELECT * FROM " + User.TABLE + "WHERE userId = " + userId )
                    .mapToList(User.MAPPER)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread());
        }

   }


texts:
I have a piece of code where I compare two arrays for similar values, then remove the similar values from one of the arrays. Is there a better way of writing this piece of code?

UpdateAddedTasksAfterDelete() {
    var tasksToRemove = [];
    var updatedTasks = [];

    for (var i = 0; i < this.deletedTasks.length; i++) {
        if (this.addedTasks.indexOf(this.deletedTasks[i]) > -1) { tasksToRemove.push(this.deletedTasks[i]); }
    }

    for (var i = 0; i < this.addedTasks.length; i++) {
        if (this.addedTasks.indexOf(tasksToRemove[i]) == -1) { updatedTasks.push(this.addedTasks[i]); }
    }

    this.addedTasks = updatedTasks;
}


texts:
I am working on a socket HTTP post request.  Here is one method that I come up with.  It looks dirty and is in C instead of C++.

bool SendBasicInfo(USER* user, SOCKET sock)
{
    char FormBuffer[1024];

    char DataType1[] = "a=";
    char DataType2[] = "&b=";
    char DataType3[] = "&c=";

    char FormAction[] = "/g/g.php";

    // get: length of the actual content
    int ContentLength = (int)strlen(user->user_id) + (int)strlen(user->pcname) + (int)strlen(user->username) + strlen(DataType1) + strlen(DataType2) + strlen(DataType3);
    char ContentLengthBuffer[sizeof(ContentLength)];
    sprintf_s(ContentLengthBuffer, "%d", ContentLength);

    // header
    strcpy_s(FormBuffer, "POST ");
    strcat_s(FormBuffer, FormAction);
    strcat_s(FormBuffer, " HTTP/1.1\n");
    strcat_s(FormBuffer, "Content-Type: application/x-www-form-urlencoded\n");
    strcat_s(FormBuffer, "Host: \n");
    strcat_s(FormBuffer, "Content-Length: ");
    strcat_s(FormBuffer, ContentLengthBuffer); // size of actual content
    strcat_s(FormBuffer, "\n\n");

    // actual content
    strcat_s(FormBuffer, DataType1);
    strcat_s(FormBuffer, user->user_id);
    strcat_s(FormBuffer, DataType2);
    strcat_s(FormBuffer, user->pcname);
    strcat_s(FormBuffer, DataType3);
    strcat_s(FormBuffer, user->username);

    std::cout << FormBuffer << std::endl;

    return ( send(sock, FormBuffer, strlen(FormBuffer), NULL) >= (int)strlen(FormBuffer) );
}

The idea here is to send a message like this one:

POST /g/g.php HTTP/1.1
Content-Type: application/x-www-form-urlencoded
Host:
Content-Length: 31

a=123&b=computername&c=username

This was working fine, but it just seems hard-coded and wrong.  How can I make the size of FormBuffer to be dynamic instead of 1024?


texts: Achieving a never-ending loop of game tasks

texts:
The following is a basic implementation of a loop which is intended to launch a series of games in a loop (generic ones that can be overridden, but that have always have finite durations).  The intention would be that a game can broadcast events to clients and would always broadcast its completion.  When there are no clients listening it can Shutdown, and restart again when some clients begin listening again

Is it a good way to approach this?  Does it matter that I do not await the _gameScheduler.Start(this) call? Am I dealing with the task loop correctly?  Is the timer used correctly?

public class Table
{
    private readonly GameScheduler _gameScheduler;
    public Game Game { get; set; }
    public Table()
    {
        _gameScheduler = new GameScheduler();
        Task schedulerTask = _gameScheduler.Start(this);
    }
    public void Close()
    {
        _gameScheduler.Shutdown();
    }
}

public class GameScheduler
{
    private bool _running = true;
    public async Task Start(Table t)
    {
        while (_running)
        {
            await RunGame(t);
        }
    }

    async Task RunGame(Table table)
    {
        var game = new Game();
        table.Game = game;
        table.Game.Start();
        await table.Game.GameCompletionSource.Task;
    }
    public void Shutdown() { _running = false; }
}

public class Game
{
    System.Threading.Timer _countdownTimer;
    private int _timeLeft = 15000;
    private int _countdownInterval = 1000;
    public TaskCompletionSource<bool> GameCompletionSource;
    public void Start()
    {
        _countdownTimer = new System.Threading.Timer(GameCountdown, null, 0, _countdownInterval);
    }
    public void GameCountdown(object state)
    {
        if (_timeLeft <= 0)
        {
            _countdownTimer.Dispose();
            Finish();
        }
        else
        {
            _timeLeft -= _countdownInterval;
        }
    }
    private void Finish()
    {
        GameCompletionSource.SetResult(true);
    }
}


texts: Resize iframe & textarea in reverse directions

texts:
I have a textarea and iframe whose sizes should change dynamically and in reverse directions. I'd like to achive this effect without using a frameset or jQuery plugin. Here's the result of my attempt:

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>Resize</title>
    <style>
        textarea,
        iframe {
            display: block;
            width: 300px;
            height: 200px;
            margin: 0;
            border: 0;
            padding: 0;
        }
        textarea {
            background: green;
            resize: none;
        }
        iframe {
            background: blue;
        }
    </style>
</head>

<body>
    <input id="slide" oninput="resize();" onchange="resize();" type="range" min="0" max="400" value="200">
    <textarea id="textarea"></textarea>
    <iframe id="iframe"></iframe>
    <script>
        var slide = document.getElementById("slide");
        var textarea = document.getElementById("textarea");
        var iframe = document.getElementById("iframe");

        function resize() {
            var slideValue = slide.value;
            textarea.style.height = slideValue + "px";
            iframe.style.height = 400 - slideValue + "px";
        }
    </script>
</body>

</html>

Demo

I wonder if you could review my code and let me know what you think.


texts: Serialization/Unserialization of a list of strings - C++

texts:
Are there any issues with below implementation?
Input: from STDIN, a list of strings
Output: serialize to a file called "out.txt" and then unserialize into a list of strings, and output to STDOUT

Goal is not here too much about code organization, but I would like to know if this code can fail for certain types of inputs

#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <cstdlib>

using namespace std;

int main()
{
    std::vector<std::string> input;

    std::string tmp;
    while (std::cin >> tmp)
    {
        input.push_back(tmp);
    }

    std::ofstream out("out.txt", std::ios::out);
    for (std::vector<std::string>::const_iterator iter = input.begin();
         iter != input.end();
         ++iter)
    {
        out << (*iter).size() << "|" << *iter;
    }
    out.close();

    std::vector<std::string> output;
    std::ifstream in("out.txt", std::ios::in);
    if (in.is_open())
    {
        std::string tmp;
        if (!in.eof())
        {
            getline(in, tmp);
            size_t pos;
            int length = 0;
            std::string str;

            while (!tmp.empty())
            {
                pos = tmp.find('|');
                if (pos != std::string::npos)
                {
                    length = atoi(tmp.substr(0, pos).c_str());
                    str = tmp.substr(pos+1, length);
                    tmp = tmp.substr(pos+str.size() + 1);

                    output.push_back(str);
                }
            }
        }

        in.close();
    }

    for (std::vector<std::string>::const_iterator iter = output.begin();
         iter != output.end();
         ++iter)
    {
        std::cout << *iter << "\n";
    }

    return 0;
}


texts: MonoAlphabetic and PolyAlphabetic ciphers in Haskell

texts:
This code defines functions to cipher text with both mono-alphetic (Caesar) ciphers and poly-alphabetic ciphers. I also define a shortcut for rot13. I like this code and I think it is easy to read, but code is never perfect so I ask you for improvements.

import Data.Char (toLower)

alphabet :: String
alphabet = ['a'..'z']

generalShift :: String -> Int -> Char -> Char
generalShift alphabet 0 letter = letter
generalShift alphabet positions letter
  | letter == last alphabet = generalShift alphabet (positions - 1) (head alphabet)
  | otherwise = generalShift alphabet (positions - 1) (succ letter)

shift :: Int -> Char -> Char
shift = generalShift alphabet

clean :: String -> String
clean = filter (`elem` alphabet) . (map toLower)

monoAlphabeticCipher :: Int -> String -> String
monoAlphabeticCipher key = map (shift key) . clean

rot13 :: String -> String
rot13 = monoAlphabeticCipher 13

poliAlphabeticCipher :: [Int] -> String -> String
poliAlphabeticCipher keys text = zipWith shift keys (clean text)

main :: IO()
main = print $ poliAlphabeticCipher [3, 2, 1] "abc"


texts: Custom MySQLi statement function for binding variables

texts:
I have the following functions:

function db ($query, $parameters = false, $results = false, $fetch = false, $error_reporting = true) {

    global $db;
    global $db_query;

    if(!isset($db)) {

        $db = new mysqli("localhost", "username", "password", "db");

    }

    if ($db->connect_error == NULL) {

        $db->set_charset("utf8");

        if(is_array($parameters)) {

            $db_query = $db->prepare($query);

            if($db_query) {

                foreach($parameters as $key => $value) {
                    $parameters_reference[$key] = &$parameters[$key];
                }

                $ReflectionMethod = new ReflectionMethod ('mysqli_stmt', 'bind_param');
                @$ReflectionMethod -> invokeArgs($db_query, $parameters_reference);

                $execute = $db_query->execute();

                if($execute) {

                    if($results === false && $fetch === false) {

                        $return = $db_query;

                    } else {

                        if($results === true) {
                            $return = $db_query->get_result();
                        }

                        if($results === true && $fetch === true) {
                            $return = $return->fetch_array(MYSQLI_ASSOC);
                        }
                    }

                } else {
                    $db_error = "Execution error.";
                }

            } else {
                $db_error = "Preparation error.";
            }

        } else {

            $return = $db->query($query);

            if($parameters === true) {
                $return = $return->fetch_array(MYSQLI_ASSOC);;
            }

        }

    } else {
        $db_error = "Connection error.";
    }

    if(!isset($db_error)) {

        return $return;

    } else {

        if($error_reporting === true) {

            die("Database Error: ".$db_error);

        } else {

            return false;
        }
    }
}

function db_fetch($query) {
    return $query->fetch_array(MYSQLI_ASSOC);
}

Their main purpose is to save me time when executing queries to the database. The usage is as follows:

$query = db("SELECT * FROM `table`");

When I need to execute a simple query:

$query = db("SELECT * FROM `table` WHERE `var` = ?", ['i', $var], true);

When I need to add some variables to the query. Then I use $row = db_fetch($query) to get the results. It's possible to skip the db_fetch function if i set 4th parameter of the db function to true.

How can I make the functions better? I mean, is it written well or can I change something to make it better?


texts: Pointer handle - only allocates in stack

texts:
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?


texts: String manipulation with std::adjacent_find

texts:
For the given strings (not containing numbers), print their shortened
  versions,  where each adjacent sequence of the same characters longer
  than 2, change to an expression consisting of a sign and a number of
  repetitions.

Sample input:

4
AAA
ABCDEF
CCCCCCDDDDDDD
ZZAACCCDDDDEEEEEE

Sample output:

A3
ABCDEF
C6D7
ZZAAC3D4E6

My code:

#include <algorithm>
#include <cstddef>
#include <functional>
#include <iostream>
#include <iterator>
#include <string>

std::string reduce(std::string const& word) {
    std::string result;
    for (auto it = word.cbegin(); true;) {
        auto curr = std::adjacent_find(it, word.cend(), std::not_equal_to<int>());
        auto dist = std::distance(it, curr) + (curr != word.cend());

        if (dist < 3) {
            result += std::string(dist, *it);
        } else {
            result += *it + std::to_string(dist);
        }

        if (curr == word.cend()) {
            break;
        }
        it = 1 + curr;
    }
    return result;
}

int main() {
    std::size_t tests;
    std::cin >> tests;
    while (tests--) {
        std::string word;
        std::cin >> word;
        std::cout << reduce(word) << "\n";
    }
}

How could I simplify or improve this code?


texts:
This is my first Scala game.  I would love some feedback on my coding style, or your brief input on how you would do it.

object tictactoe extends App {
  def tttFormat(board: Array[Char]): String =
    "|" + board(0) + "|" + board(1) + "|" + board(2) + "|\n" +
    "|" + board(3) + "|" + board(4) + "|" + board(5) + "|\n" +
    "|" + board(6) + "|" + board(7) + "|" + board(8) + "|\n"
  println("Enter the number of the square you want to occupy!\n"+
      tttFormat(GameObj.board))
  while(GameObj.atPlay) {
    println(tttFormat(GameObj.updatedStateArray))
  }
  GameObj.nextTurn
  println("game over! " + GameObj.nextTurn + "'s win!")
}

object GameObj {
  val board: Array[Char] = Array('1','2','3',
                                 '6','5','4',
                                 '7','8','9')
  var whosTurn = false

  def nextTurn: Char = {
    whosTurn = !whosTurn;
    if (whosTurn) 'X' else 'O'
  }

  def atPlay: Boolean =
    !(board(0) == 'X' && board(1) == 'X' && board(2) == 'X') &&
    !(board(3) == 'X' && board(4) == 'X' && board(5) == 'X') &&
    !(board(6) == 'X' && board(7) == 'X' && board(8) == 'X') &&
    !(board(0) == 'X' && board(4) == 'X' && board(8) == 'X') &&
    !(board(6) == 'X' && board(4) == 'X' && board(2) == 'X') &&
    !(board(0) == 'X' && board(3) == 'X' && board(6) == 'X') &&
    !(board(1) == 'X' && board(4) == 'X' && board(7) == 'X') &&
    !(board(2) == 'X' && board(5) == 'X' && board(8) == 'X') &&
    !(board(0) == 'O' && board(1) == 'O' && board(2) == 'O') &&
    !(board(3) == 'O' && board(4) == 'O' && board(5) == 'O') &&
    !(board(6) == 'O' && board(7) == 'O' && board(8) == 'O') &&
    !(board(0) == 'O' && board(4) == 'O' && board(8) == 'O') &&
    !(board(6) == 'O' && board(4) == 'O' && board(2) == 'O') &&
    !(board(0) == 'O' && board(3) == 'O' && board(6) == 'O') &&
    !(board(1) == 'O' && board(4) == 'O' && board(7) == 'O') &&
    !(board(2) == 'O' && board(5) == 'O' && board(8) == 'O')

  def updatedStateArray: Array[Char] = {
    val in: Int = Integer.parseInt(readLine()) - 1
    board.update(in, nextTurn)
    board
  }
}


texts:
This is supposed to be efficient code, but it's taking much longer than what a normal insertion sort would take. I can't identify what's the problem with this insertion sort. Is there an implementation problem?

// function to sort a singly linked list using insertion sort
    void insertionSort(element_t **head_ref)
{
    // Initialize sorted linked list
    element_t *sorted = NULL;

    // Traverse the given linked list and insert every
    // node to sorted
    element_t *current = *head_ref;
    while (current != NULL)
    {
        // Store next for next iteration
        element_t *next = current->next;

        // insert current in sorted linked list
        sortedInsert(&sorted, current);

        // Update current
        current = next;
    }

    // Update head_ref to point to sorted linked list
    *head_ref = sorted;
}

/* function to insert a new_node in a list. Note that this
  function expects a pointer to head_ref as this can modify the
  head of the input linked list (similar to push())*/
void sortedInsert(element_t** head_ref, element_t* new_node)
{
    element_t* current;
    /* Special case for the head end */
    if (*head_ref == NULL || (*head_ref)->val >= new_node->val)
    {
        new_node->next = *head_ref;
        *head_ref = new_node;
    }
    else
    {
        /* Locate the node before the point of insertion */
        current = *head_ref;
        while (current->next!=NULL &&
               current->next->val < new_node->val)
        {
            current = current->next;
        }
        new_node->next = current->next;

current->next = new_node;
    }
}


texts:
When you click open - a div slides out. If you click on the new div, an additional div slides out from under it. This is working great, but I need two things that I cant figure out!

How can I condense the jQuery so I don't have to add a class to it every time I want a new slider? Is it possible to do a .sibling kind of thing, or something like this?
I've tried making a close button, but I cannot get it to work the way I want. When you click close, I want the bottom div to close first, then the slide out div to close. And this button would need to work even if only one div is open.

jsFiddle

$(document).ready(function() {
   $('.cambridge').hide();
   $("#test").click(function () {
      $(".cambridge").toggle("slide", { direction: "right" }, 1000);
   });
   $('.shopping').hide();
   $("#test2").click(function () {
      $(".shopping").toggle("slide", { direction: "up" }, 1000);
   });
});


texts: Deciding whether an anchor should be updated

texts:
A colleague and I were discussing the following code today and had a disagreement over the return false in the catch (MalformedURLException e) block.

For some background information this method is in a class which is going through legacy data to be migrated into a new system, parsing the text, finding all of the <a> tags and re-writing some of those links depending on what the link is to. This method is determining if the link should be updated or not based on some criteria.

private boolean shouldUpdateAnchor(final String link, String replaceFrom, String replaceInto) {
    if (link == null) {
        return false;
    }

    if (!link.contains(URL_NODEREF_QUERY_PARAM)) {
        return false;
    }

    if (!link.contains(replaceFrom) && !link.contains(replaceInto)) {
        return false;
    }

    final URL url;
    try {
        url = new URL(link);
    } catch (MalformedURLException e) {
        return false;
    }

    final String query = url.getQuery();
    final NodeRef documentNodeRef = getNodeRefFromQueryString(query);
    final QName type = nodeService.getType(documentNodeRef);
    if (type == null) {
        return false;
    }

    if (!type.equals(ContentModel.KnowledgeCentreDocument.QNAME)) {
        return false;
    }

    return true;
}

One of us said that using exceptions for control flow is an anti-pattern and the exception should be thrown/allowed to propagate up and handled elsewhere, while the other said that the error being thrown is a by-product of the API (this is Java code which doesn't have any of the tryParse() methods of C#) which needn't be thrown any further as it can be handled here.

I've read these related questions but I'm not entirely sure they're applicable here as they're quite general.

https://stackoverflow.com/questions/729379/why-not-use-exceptions-as-regular-flow-of-control
https://softwareengineering.stackexchange.com/questions/189222/are-exceptions-as-control-flow-considered-a-serious-antipattern-if-so-why

To provide some context, here are the two methods which are called immediately before this one:

public final String transformLinks(final String contentString, String replaceFrom, String replaceInto) {
    if (StringUtils.isBlank(contentString))
        return contentString;

    final Document document = Jsoup.parse(contentString);
    final Elements anchors = document.getElementsByTag("a");
    for (final Element anchor : anchors) {
        handleAnchor(anchor, replaceFrom, replaceInto);
    }
    return document.body().toString();
}

private void handleAnchor(final Element anchor, String replaceFrom, String replaceInto) {
    final String linkHref = anchor.attr("href");
    if (!shouldUpdateAnchor(linkHref, replaceFrom, replaceInto)) {
        return;
    }

    final String newHref = linkHref.replace(replaceFrom, replaceInto);
    anchor.attr("href", newHref);
}


texts:
I was trying to solve this problem.  I thought of any possible relation between the number of matches among subsequent substrings, but could not find one. So, the probably naive solution that I drafted was:

#include <iostream>
#include <cstring>

using namespace std;

int n;
char str[1000000];

int sim(int i, int len)
{
    int j=0;
    for(; i<len; i++, j++)
    {
        if(str[i]!=str[j])
            return j;
    }
    return j;
}

void solve()
{
    int len=strlen(str);
    int count=len;

    for(int i=1; i<len; i++)
    {
        count+=sim(i, len);
    }
    cout<<count<<endl;
}

int main()
{
    cin>>n;
    for(int i=0; i<n; i++)
    {
        cin>>str;
        solve();
    }

    return 0;
}

Now submission to online judge at interviewstreet says that I did pass 7/10 testcases but the time limit exceeded for the 8th testcase! It means that my solution isn't even that naive, but it also indicates a need for some optimization. Can you people please suggest any way to optimize it?