texts:
An app I'm building professionally includes rudimentary text messaging. It allows users to send from the phone, and it polls for new messages (I know, yikes. Push notifications are a future task) with variable frequency for new messages from other users.

Part of its functionality is of course keeping messages in date-sorted order, and each message has a timestamp on it. I came up with two sorting implementations and I was curious as to which one would be more efficient.

Implementation 1:

for (Message* message in messages) {
    [self.backingMessages addObject:message];
}
NSSortDescriptor* sortingDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"fullTimestamp" ascending:YES];
[self.backingMessages sortUsingDescriptors:@[sortingDescriptor]];

Implementation 2:

for (Message* message in messages) {
    NSInteger insertionPoint = [self.backingMessages indexOfObject:message inSortedRange:NSMakeRange(0, self.backingMessages.count) options:NSBinarySearchingInsertionIndex usingComparator:^NSComparisonResult(Message*  _Nonnull obj1, Message*  _Nonnull obj2) {
        return [obj1.fullTimestamp compare:obj2.fullTimestamp];
    }];
    self.backingMessages[insertionPoint] = message;
}

Some observations:

The new messages being added are known to be sorted
The messages being added to are initially sorted, and so will also be sorted every time new messages are added.

Doing some back-of-the-napkin analysis...

n = length of existing message array
m = length of new message array
implementation 1: O(m) + O((n+m)log(n+m))
implementation 2: O(mlog(n+m)) + O(m) <- for the shifting that I assume happens upon insertion

My gut says that implementation 2 would be faster by a hair, depending on how the shifting works. All of this being said, I'm assuming that Apple ends up doing some crazy polymorphic implementation for sorting depending on the data, so implementation 1 might end up being faster. I'm probably overthinking this since the amount of data I'm expecting is so small, but I'm still curious about what might theoretically be faster.


texts:
For this equation, I need to count possible solutions:

$$ a + b^2 + c^3 + d^4 \le S  $$

$$0\le a,b,c,d \le S$$

I tried the following approach:

       Integer S=Integer.parseInt(br.readLine());
      // get maximum possible value of a,b,c,d which satisfy equation
         int a=S;
        int b=(int) Math.sqrt(a);
        int d=(int) Math.sqrt(b);
        int c=(int) Math.cbrt(a);
        int count=0;
        for (int i = 0; i <= a; i++) {
            for (int j = 0; j <= b; j++) {
                for (int k = 0; k <= c; k++) {
                    for (int l = 0; l <= d; l++) {
                       int total=i+j*j+(int)Math.pow(k, 3)+
  (int)Math.pow(l,4);
                        if(total<=a) {
                            count++;
                        }
                    }
                }
            }
        }
          System.out.println(count);

Time complexity: \$O(n \times \sqrt{n} \times \sqrt[3]{n} \times \sqrt[4]{n})\$ (Not sure)

For large value, this takes time. Can someone please help me with better solution with time complexity?


texts:
I solved this stack problem in Swift. Looking for any feedback on my code:

import Foundation
/// Returns an integer read from one line of standard input.
func readInteger() -> Int {
    guard let line = readLine() else {
        fatalError("Unexpected end of input")
    }
    guard let i = Int(line) else {
        fatalError("Invalid integer in input")
    }
    return i
}

/// Returns an array of Characters
func readStrings() -> [Character] {
    guard let line = readLine() else {
        fatalError("Unexpected end of input")
    }
    return line.characters.map{ $0 }
}

// checks if all brackets are balanced
func balancedBrackets() {
    let sequences = readInteger()
    // outloop loops through each sequence line
    outerLoop: for _ in 0..<sequences {
        // create a stack (array in this case)
        var stack = [Character]()
        // each line of sequence
        let sequence = readStrings()
        // edgeCase is when there are only opening brackets in stack and didn't reach case } ] )
        var edgeCase = false
        // inner loop loops through each bracket character
        innerLoop: for bracket in sequence {
            switch bracket {
            // if opening brackets, append and set edgeCase
            case "{", "[", "(":
                stack.append(bracket)
            // case closing brackets
            case "}", "]", ")":
                // checks for empty stack or if the bracket pairs arent matching
                if stack.isEmpty || (bracket == "}" && stack.last != "{") || (bracket == "]" && stack.last != "[") || (bracket == ")" && stack.last != "(")  {
                    edgeCase = true
                    print("NO")
                    // append closing bracket so YES doesn't print when breaking
                    stack.append(bracket)
                    // break out of checking anymore brackets
                    break innerLoop
                }
                stack.removeLast()
            default:
                fatalError("unknown bracket found")
            }
        }
        // if empty
        if stack.isEmpty {
            print("YES")
        } else if !edgeCase { // stack has opening brackets and hasn't reach if statement in case } ] )
            print("NO")
        }
    }
}

balancedBrackets()


texts:
Is this code good practice? What kind of design pattern should I use for this specific situation?

The following function creates a new marker on a map. It sets a new image for it, except when the marker references the user location.

$scope.addMarker = function (lat, lng, isUserLocation) {

    if (typeof(isUserLocation) === undefined || isUserLocation === false)
        var icon = "img/marker-map.png";

    $scope.markers.push({
        latitude: parseFloat(lat),
        longitude: parseFloat(lng),
        icon: icon
    });
}

Maybe just (!isUserLocation) is more readable - is it error prone?

Here's a call to the function to create the "user location" marker:

$scope.addMarker(position.coords.latitude, position.coords.longitude, true);

If someone reads that, he/she wouldn't be able to say what that true is for and would have to look for the addMarker() function, for example. But maybe that's no big deal or is it?

Here's the function that creates all other markers:

$scope.populateMarkers = function(locations) {
    for (var i = 0; i < locations.length; i++) {
        $scope.addMarker(locations[i].Latitude, locations[i].Longitude);
    }
}

This is the HTML / Angular directives that references the markers inside the map:

  <markers>
    <marker ng-repeat="marker in markers" coords="marker" icon="marker.icon">
    </marker>
  </markers>

It works, but since I'm very new to AngularJS and I also thought about many different ways to do just that, I'd like to know how people would do it and/or whether there is a recommended design pattern for it.


texts: Merging every two objects into single single object making group by a property C# LINQ

texts:
I have a object list like below. I want to join every two rows into single row based on column B. It is sure that only two rows would be there for every single column B value.
Input

Output

However, my solution works. but I am looking for more better solution. I am not much happy with my solution.
My solution:
var groupByItems = items.GroupBy(x => x.ColumnB).Select(x => new MappingClass
    {
        ColumnA= x.FirstOrDefault().ColumnA,
        ColumnB= x.FirstOrDefault().ColumnB,
        ColumnC= x.Where(r=> !string.IsNullOrEmpty(r.ColumnC)).Select(r=>r.ColumnC).FirstOrDefault(),
        ColumnD= x.Where(r => !string.IsNullOrEmpty(r.ColumnD)).Select(r => r.ColumnD).FirstOrDefault(),
    }).ToList();

Now groupByItems object returns me two rows as expected.


texts:
After finding a piece of code on StackOverflow that drew the Koch snowflake fractal, I made a ton of modifications to it and used it to produce an animation divided in two parts:

Constant size, recursion depth increasing.
Constant recursion depth, size increasing.

You can see the animation here.

I am interested mainly in:

Have I got too many constants? I like them because they make the program easy to customize, but 12 constants looks like a lot.
Any idea to avoid repetition in these blocks of code?

write_as_title(\
    "Constant size, recursion depth increasing.", font=FONT)
time.sleep(WRITING_SLEEPING_INTERVAL)

for deepness in range(MAX_DEPTH):
    costum_reset()
    snowflake(deepness, SIZE_WHEN_CONSTANT_DEPTH)
    time.sleep(DRAWING_SLEEPING_INTERVAL)

costum_reset()
write_as_title(\
    "Constant recursion depth, size increasing.", font=FONT)
time.sleep(WRITING_SLEEPING_INTERVAL)
for size in RANGE_OF_SIZES:
    costum_reset()
    snowflake(DEPTH_WHEN_CONSTANT_SIZE, size)

They are similar but I cannot quite abstract the similarity out.

from __future__ import division

import turtle
import time

WIDTH, HEIGHT = 800, 600
FONT = ("Arial", 25, "normal")
DRAWING_SLEEPING_INTERVAL = 0.5
WRITING_SLEEPING_INTERVAL = 2.5
MAX_DEPTH = 5
SIZE_WHEN_CONSTANT_DEPTH = 300
DEPTH_WHEN_CONSTANT_SIZE = 4
RANGE_OF_SIZES = range(0, 5000, 5)
SIDES_OF_AN_EQUILATERAL_TRIANGLE = 3
EQUILATERAL_TRIANGLE_INTERNAL_ANGLE = 120
DRAWING_START_X = - 200
DRAWING_START_Y = 150

def snowflake(n, size=300):

    for _ in range(SIDES_OF_AN_EQUILATERAL_TRIANGLE):
        snowflake_edge(n, size)
        turtle.right(EQUILATERAL_TRIANGLE_INTERNAL_ANGLE)

    turtle.update()

def snowflake_edge(n, size=300):
    if n == 0:
        turtle.forward(size)
        return

    for movement in (lambda: turtle.left(EQUILATERAL_TRIANGLE_INTERNAL_ANGLE // 2),
                   lambda: turtle.right(EQUILATERAL_TRIANGLE_INTERNAL_ANGLE),
                   lambda: turtle.left(EQUILATERAL_TRIANGLE_INTERNAL_ANGLE // 2)):
        snowflake_edge(n - 1, size / SIDES_OF_AN_EQUILATERAL_TRIANGLE)
        movement()

    snowflake_edge(n - 1, size / SIDES_OF_AN_EQUILATERAL_TRIANGLE)

def costum_reset():
    turtle.reset()
    turtle.penup()
    turtle.setx( DRAWING_START_X )
    turtle.sety( DRAWING_START_Y )
    turtle.pendown()

def write_as_title(title, font=FONT):
    turtle.setx(- (WIDTH // 2.5) )
    turtle.sety(HEIGHT // 3)
    turtle.write(title, font=font)

if __name__ == "__main__":
    turtle.setup(width=WIDTH, height=HEIGHT)
    turtle.hideturtle()
    turtle.tracer(0, 0)

    write_as_title(\
        "Constant size, recursion depth increasing.", font=FONT)
    time.sleep(WRITING_SLEEPING_INTERVAL)

    for deepness in range(MAX_DEPTH):
        costum_reset()
        snowflake(deepness, SIZE_WHEN_CONSTANT_DEPTH)
        time.sleep(DRAWING_SLEEPING_INTERVAL)

    costum_reset()
    write_as_title(\
        "Constant recursion depth, size increasing.", font=FONT)
    time.sleep(WRITING_SLEEPING_INTERVAL)
    for size in RANGE_OF_SIZES:
        costum_reset()
        snowflake(DEPTH_WHEN_CONSTANT_SIZE, size)


texts: Summing values in a vector using threads

texts:
This is my very first program that using threads. I use C++11 standard threads and I run it on Linux.

The program creates two threads that sums all the elements in a vector together. The first created thread sums the left half of the vector and the other thread sums the right part of the vector.

The main thread runs until both are done, adds the two sums together and then print the sum.

#include <iostream>
#include <vector>
#include <thread>

void
adder( const std::vector<int> & v, int begin, int end, int & result)
{
  for( ; begin < end; ++begin )
    {
      result = result + v.at( begin );
    }
}

int
main()
{
  int sum_left  = 0;
  int sum_right = 0;

  std::vector<int> v( 100000000,1); //100 millions
  int v_size = v.size();

  std::thread t1( adder, v, 0,v_size/2 , std::ref(sum_left) );
  std::thread t2( adder, v, v_size/2, v_size, std::ref(sum_right) );

  t1.join();
  t2.join();

  int sum_total = sum_left + sum_right;

  std::cout << sum_total << '\n';

  return 0;
}


texts:
pwgen is a nice password generator utility.
When you run it, it fills the terminal with a bunch of random passwords,
giving you many options to choose from and pick something you like,
for example:

lvk3U7cKJYkl pLBJ007977Qx b9xhj8NWPfWQ
pMgUJBUuXwpG OAAqf6Y9TXqc fJOyxoGYCRSQ
bpbwp6f2MxEH fUYTJUqg0ZMB GjVVEQxuer0k
oqTEvV1LmdJu si47MkHNRpAw 3GKV8NdGMvwf

Although there are ports of pwgen in multiple systems,
it's not so easy to find in Windows.
So I put together a simple Python script that's more portable,
as it can run in any system with Python.

I added some extra features I often want:

Skip characters that may be ambiguous, such as l1ioO0Z2I
Avoid doubled characters (slow down typing)

Here it goes:

#!/usr/bin/env python

from __future__ import print_function

import random
import string
import re

from argparse import ArgumentParser

terminal_width = 80
terminal_height = 25

default_length = 12

alphabet_default = string.ascii_letters + string.digits
alphabet_complex = alphabet_default + '`~!@#$%^&*()_+-={}[];:<>?,./'
alphabet_easy = re.sub(r'[l1ioO0Z2I]', '', alphabet_default)

double_letter = re.compile(r'(.)\1')

def randomstring(alphabet, length=16):
    return ''.join(random.choice(alphabet) for _ in range(length))

def has_double_letter(word):
    return double_letter.search(word) is not None

def easy_to_type_randomstring(alphabet, length=16):
    while True:
        word = randomstring(alphabet, length)
        if not has_double_letter(word):
            return word

def pwgen(alphabet, easy, length=16):
    for _ in range(terminal_height - 3):
        for _ in range(terminal_width // (length + 1)):
            if easy:
                print(easy_to_type_randomstring(alphabet, length), end=' ')
            else:
                print(randomstring(alphabet, length), end=' ')
        print()

def main():
    parser = ArgumentParser(description='Generate random passwords')
    parser.add_argument('-a', '--alphabet',
                        help='override the default alphabet')
    parser.add_argument('--complex', action='store_true', default=False,
                        help='use a very complex default alphabet', dest='complex_')
    parser.add_argument('--easy', action='store_true', default=False,
                        help='use a simple default alphabet, without ambiguous or doubled characters')
    parser.add_argument('-l', '--length', type=int, default=default_length)
    args = parser.parse_args()

    alphabet = args.alphabet
    complex_ = args.complex_
    easy = args.easy
    length = args.length

    if alphabet is None:
        if complex_:
            alphabet = alphabet_complex
        elif easy:
            alphabet = alphabet_easy
        else:
            alphabet = alphabet_default
    elif len(alphabet) < length:
        length = len(alphabet)

    pwgen(alphabet, easy, length)

if __name__ == '__main__':
    main()

How would you improve this? I'm looking for comments about all aspects of this code.

I know that the terminal_width = 80 and terminal_height = 25 variables don't really reflect what their names imply. It's not terribly important, and good enough for my purposes, but if there's a way to make the script detect the real terminal width and height without importing dependencies that reduce portability, that would be pretty awesome.


texts: Sending a string from anonymous thread to UI with PostMessage

texts:
I am sending a string from an anonymous thread to the UI with PostMessage in the following code:

unit Unit2;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;

const
  WM_SETCAPTION = WM_USER;

type
  TForm2 = class(TForm)
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
    procedure WMSetCaption(var msg: TMessage); message WM_SETCAPTION;
  end;

var
  Form2: TForm2;

implementation

{$R *.dfm}

procedure TForm2.WMSetCaption(var msg: TMessage);
begin
  Self.Caption := PChar(msg.LParam);
end;

procedure TForm2.Button1Click(Sender: TObject);
begin
  System.Classes.TThread.CreateAnonymousThread(
    procedure
    begin
      PostMessage(Handle, WM_SETCAPTION, 0, LParam(PChar('My new caption')));
    end).Start;
end;

end.

This works seemingly well, but could this potentially create memory leaks? Or is there a better way to accomplish this?


texts: React hook "select all" checkbox implementation

texts:
This is a select-all checkbox (and checkboxes that it controls), that's usually found in tables/lists.

Two things I'm concerned about:

I'm returning elements from a React Hook - is that OK to do? As opposed to create a Component (probably a render prop)
I'm calculating master.indeterminate in a useEffect, as opposed to doing it when the checkboxes are clicked.

I'm planning on using it in a table that will have 1000s of entries, filtered/paginated upto 100.

I realize #2 could be a performance issue since I'm essentially checking all checkboxes to determine whether to set master.indeterminate, but since the table will be filtered I want this to be "reactive" as well.

Any other issues I might be overlooking?

Fiddle

const h = (...args) => React.createElement(...args)

function useSelectAll(existingStateOrSize = []) {
  const [state, update] = React.useState(existingStateOrSize)
  const master = React.useRef(null)
  const children = React.useRef(state.map(() => null))

  function setIndeterminate () {
    /* Calculate master.indeterminate */
    let allChecked
    for (const child of children.current) {
      if (!child) continue
      const checked = Boolean(child.checked)
      if (allChecked === undefined) {
        allChecked = checked
      } else if (allChecked !== checked) {
        allChecked = null
        break
      }
    }
    if (typeof allChecked === 'boolean') {
      master.current.checked = allChecked
      master.current.indeterminate = false
    } else {
      master.current.indeterminate = true
    }
  }

  function onChangeMaster() {
    children.current.forEach(child => child.checked = master.current.checked)
  }

  function onChangeChild(e) {
    const i = children.current.indexOf(e.target)
    const newState = Array.from(state)
    newState[i] = e.target.checked
    update(newState)
  }

  React.useEffect(setIndeterminate)

  return [
    state,
    h('input', { type: 'checkbox', ref: master, onChange: onChangeMaster }),
    state.map((x, i) => h('input', { type: 'checkbox', ref: r => children.current[i] = r, checked: existingStateOrSize[i], onChange: onChangeChild }))
  ]
}

function Table() {
  const [state, master, children] = useSelectAll([null,null,null])
  return h('table', {}, [
    h('tr', {}, h('th', {}, master), h('th', {}, 'Select all')),
    h('tr', {}, h('td', {}, children[0]), h('td', {}, 'First')),
    h('tr', {}, h('td', {}, children[1]), h('td', {}, 'Second')),
    h('tr', {}, h('td', {}, children[2]), h('td', {}, 'Third')),
  ])
}

ReactDOM.render(h(Table), document.getElementById('container'))


texts: script that imports only data that is not in the database yet

texts:
I want to write a script that imports data into a database (in django). The database has a Company class with a name (CharField) instance. Additionally, it has a Person class with name (CharField), email address (CharField) and a company which is a reference to the Company class (ForeginKey).

The database already has entries.

The script is importing the data from a csv file with the following format:

Company Name | Email Address | First Name | Last Name

While importing the data I want the script to go through the database and check if the same people only exist once (no duplicates) and also make sure that the email address is unique. So one email address can only belong to one person not multiple. Incorrections that are already in the database can be ignored.

def handle(self, *args, **options):
        with open('/path/to/myFile.csv') as f:
            reader = csv.reader(f)
            next(f)
            for row in reader:
                company_in_list = row[0].strip()        ###reading the company name from the file
                visitor_company = ''
                company_in_db = Company.objects.filter(name=company_in_list)        ###searching for this company name in the db
                time.sleep(0.05)
                if len(company_in_db) == 1:
                    visitor_company = company_in_db[0]
                    print "company already created", visitor_company
                elif len(company_in_db) == 0:                                       ###if the company doens't exist it will create one
                    print "created a new company"
                    visitor_company = Company.objects.create(name=company_in_list)
                else:
                    raise NameError("Multiple Companies with the same name, please fix the database")
                visitor_name = row[2].strip() + ' ' + row[3].strip()                ###reading the name of the person from the file
                email = row[1].strip()                                              ###reading the email address from the file
                person_in_db = Person.objects.filter(email=email)                   ###searching for this email address in the db
                if len(person_in_db) == 0 :
                    Person.objects.create(company=visitor_company,name=visitor_name,email=email)    ###if email doesn't exist, create the person
                    print "new Person created", visitor_name
                if len(person_in_db) > 0 :
                    for p in person_in_db:
                        if p.name == visitor_name and p.company == visitor_company:                 ###if the person does exist, if it's not the same one (different name or company) stop and raise an error
                            print "Person already created"
                            pass
                        else:
                            raise NameError('multiple people with the same email address, please fix this. Row:', row, p)
        print 'done commands'

My script opens the file, ignores the header row next(f), then for each row it searches the name of the company in the database. If it already exists, it will take that instance. If not, it will create that company. If there are multiple companies with the same name, the script throws an error.

Then it reads the email address and name from the file. It searches for the email address in the database. If it doesn't exist it creates an this person with the previously gathered infos (name and company). If it exists, it checks if the person in the database has the same name and company. If the info matches it will pass as the person is already in the database, if not it will raise an error saying there are multiple persons in the database.

The time.sleep() are in there so that the database won't get locked.

Is there any way to make this faster or write this better?


texts: Is catching 'expected' exceptions that bad?

texts:
I had to find the corresponding process for a windows service the other day, and I kept on getting this one exception. I've spent some time researching the exception only to find that this exception will occur if the process is terminating, Hence my question, is it really that bad to catch expected exceptions ?

Sample Code:

try
{
  if (proc.MainModule.FileName == controller.ImagePath)
    {
             //Logic goes here
    }
 }
 catch (System.ComponentModel.Win32Exception ex)
 {
      // Thrown if process is already terminating,
      // the process is a Win16 exe or the process
      // could not be accessed.
      MyLogger.Debug(
                   "The following Win32Exception occurred while trying to access the MainModule information: " + ex.ToString());
}


texts: Codewars: Reduce strings to one character

texts:
I am trying to solve a puzzle in a performant way. This is the puzzle.

Simply explained: you have a String and you must reduce it to one character with the given rules. This is the solution to the simple variant.

COLORS = set("RGB")
def triangle(row):
    while len(row) > 1:
       row = ''.join(a if a == b else (COLORS-{a, b}).pop() for a, b in zip(row, row[1:]))
    return row

In the harder variant the task is to do the same, but performance is asked.
I thought adding a dictionary and "remembering" already solved words would boost the performance. But actualy it is not performing faster than the simple variation. Is there a way to boost one of my codes? Do I have an efficiency lack in my code? Is there maybe a efficiency lack in the algorithm?

COLORS = set("RGB")
mapping_simple = {}
def triangle_simple(row):
    result = ['']
    while True:
        if len(row) == 1:
            result[0] = row
            return result[0]
        if row in mapping_simple:
            result[0] = mapping_simple[row][0]
            return result[0]
        mapping_simple[row] = result
        row = ''.join(a if a == b else (COLORS-{a, b}).pop() for a, b in zip(row, row[1:]))
    return result[0]


texts:
I implemented the following mergesort algorithm in JavaScript, but I want to know your opinion about if is possible to do better than this.

function mergesort(list){
    if(list.length < 2){
        return list
    }else if(list.length > 1){
        let n = list.length
        let middle = n/2
        return merge(mergesort(list.slice(0, middle)), mergesort(list.slice(middle, n)))
    }
}

function merge(listA, listB){
    let list = []

    listA.push(Infinity)
    listB.push(Infinity)

    let i = 0
    let j = 0

    while(i < listA.length-1 || j < listB.length-1){
        if(listA[i] < listB[j]){
            list.push(listA[i])
            i++
        }else{
            list.push(listB[j])
            j++
        }
    }

    return list

}

Do you have any idea of how can I improve this?


texts: Auto move files to a sub folder with Ruby

texts:
I started writing a script to handle my file downloads in osx because they quickly pile up and it gets time consuming to do this manually by drag and drop. I am looking forward to get some feedback.

require 'filewatcher'
require 'pathname'
require 'fileutils'

class FileAction

  def initialize(filename, event)
    @filename = filename
    @event = event
    @path = Pathname.new(@filename)
    @basename = @path.basename.to_s
    @base_path = "/Users/digerati"
    @dl_path = "#{@base_path}/Downloads"
    @dl_docs_path = "#{@base_path}/Downloads/Documents"
    create_folder_if_not_exist
    move_file
  end

  def create_folder_if_not_exist
    Dir.mkdir(@dl_docs_path) unless File.exists?(@dl_docs_path)
  end

  def move_file
    if(@event == :new)
      puts "Downloaded a document:" + @filename
      puts "Basename: " + @basename
      begin
        FileUtils.mv("#{@dl_path}/#{@basename}", "#{@dl_docs_path}/#{@basename}")
      rescue => e
        puts "+ Error: #{e.message}"
      end
    end
  end
end

@doc_files = ["pdf", "docx"].collect { |f| "~/Downloads/*.#{f}" }
FileWatcher.new(@doc_files).watch do |filename, event|
  FileAction.new(filename, event)
end


texts: Traversing un-ordered list and appending attibute values to the list item

texts:
I have written this jQuery code to traverse the HTML markup. Basically, I am selecting data-icount attribute of each anchor tag and appending it to anchor text as (28) e.g. the ALL becomes ALL (38) in the example. 38 here is the sum of all the data-icounts under that li. Similarly, summers become summers (2) because it has two data-icount 0 and 2 so 0+2 =2.

Working example here.

I am sure there must be an improved process to do this - any comments/suggestions would be appreciated.

HTML

        ALL

                Fruits

                        Summers

Mango

Water melon

                        Winters

Tangerines

Pomegranate

Others

                Furniture

Home

Garden

Games

Playstation

Clothes


texts: Cleaning up nested promises in Cloud function

texts:
I am writing the Cloud function for Parse whose purpose is to update my database with a provided array of data objects.  The main problem are the nested promises, which doesn't look right.  Any help to refactor this code or any other critiques?

/**
 * Updating multiple object arrays:
 * Look for object with the same idKey and update with supplied data or create new if none is found
 * Expect Data {schema: <schema_name>, idKey: <name_of_id_key>, data: <object_array>}
 */

Parse.Cloud.define("updater", function(request, response) {
    var _ = require('underscore');

    var schema          = request.params.schema,
            idKey       = request.params.idKey,
            objectArray = request.params.data;

    var Class           = Parse.Object.extend(schema),
            parseObject,
            id,
            query;

    _.each(objectArray, function(dataObject){
            id = dataObject[idKey];
            if (!id) return response.error("Supplied Object " + dataObject + " has no id Key '" + idKey + "' set!");

            // now query for the same idKey
            query           = new Parse.Query(Class);
            query.equalTo(idKey, id);
            query.find().then(
                function(array){
                    if(array) {
                        // found at least one object - take the first
                        parseObject = array[0];

                        // use the new dataObject to update parseObject
                        parseObject.set(dataObject);
                        parseObject.save().then(

                            /*
                             * should this go outside the promise?
                             */

                            function(object){
                                // success
                            },
                            function(error){
                                return response.error(error);
                            });
                    } else {
                        // nothing found - create new
                        parseObject = new Class(dataObject);
                        parseObject.save().then(
                            function(object){
                                // success
                            },
                            function(error){
                                return response.error(error);
                            });
                    }
                }
            );

            parseObject = new Class(dataObject);

            parseObject.save().then(
            function(object){
                // success
            },
            function(error){
                response.error(error);
            });
    });

    response.success("Success!");

});


texts:
I've created a simple User Login page. Here User is authenticated [username, password] and if it is a valid user, values like username, name and role of the user is stored in the Session.

And according to the role of the user, the user is redirected to different pages. This is simple code, but please help me to make my login page more secure and add more functionality.

using System;
using System.Data;

namespace PROJECT.view.User
{
    public partial class LoginUser : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                Session.Clear();
                Session.Abandon();
            }
            catch (Exception)
            {

                throw;
            }
        }

        protected void btnSignIn_Click(object sender, EventArgs e)
        {
            try
            {
                DataTable dt = new DataTable();
                dt = new C_User().Get_LoginUser(inputUserName.Value, inputPwd.Value);
                if(dt != null && dt.Rows.Count > 0)
                {
                    DataRow dr = dt.Rows[0];
                    Session["username"] = dr["USERNAME"].ToString();
                    Session["name"] = dr["NAME"].ToString();
                    Session["role"] = dr["ROLE"].ToString();

                    #region affiliated user pages
                    Int16 userRole = 0;
                    userRole = Convert.ToInt16(Session["role"]);
                    switch (userRole)
                    {
                        case 1:
                            Response.Redirect("Registration.aspx", false);
                            break;
                        case 2:
                            Response.Redirect("Medicine_1.aspx", false);
                            break;
                        case 3:
                            Response.Redirect("PortalRegister.aspx", false);
                            break;
                        case 4:
                            Response.Redirect("Billing.aspx", false);
                            break;
                    }

                    #endregion
                }
                else
                {

                    Response.Redirect("LoginUser.aspx", false);
                    return;
                }
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}


texts: Returning the last segment of a split string

texts:
I recently reviewed a PR and saw the following.
const parts = someString.split('.');
return parts[parts.length - 1];

was changed to
const [last] = someString.split('.').reverse();
return last;

I commented that I am against the change for the reasons that it is harder to read and not performant.
The answer was that it is only hard to read, because I am not used to it and that performance does not matter if you use big frameworks like React for example.
Who is right and why?


texts:
I'm sure there is a better way to implement this feature. I am making an app that allows a user "upvote" or "downvote" a post. Right now, the code works and disables the upvote button if pressed and vice versa with the downvote button (the idea is that a user can only upvote or downvote once).

post.js

import React, { Component } from 'react';
import { Card, CardText, CardHeader } from 'material-ui/Card';
import FlatButton from 'material-ui/FlatButton';

class Post extends Component {

  constructor(props) {
    super(props);

    this.state = {
      disabledUpvote: false,
      disabledDownvote: false
    }

  }

  handleUpvoteClicked() {
    const downvoteDisabled = this.state.disabledDownvote;

    if (downvoteDisabled == false) {
      this.setState({
        disabledUpvote: true,
        disabledDownvote: false
      });
    } else {
      this.setState({
        disabledUpvote: true,
        disabledDownvote: false
      });
    }
  }

  handleDownvoteClicked() {
    const upvoteDisabled = this.state.disabledUpvote;

    if (upvoteDisabled == false) {
      this.setState({
        disabledDownvote: true,
        disabledUpvote: false
      });
    } else {
      this.setState({
        disabledDownvote: true,
        disabledUpvote: false
      });
    }
  }

  render() {
    const { content, createdAt, votes } = this.props.post;

    return (

        <Card>
          <CardText>

              {moment(createdAt).fromNow()}

            {content}

              <FlatButton
                label="Upvote"
                primary={true}
                disabled={this.state.disabledUpvote}
                onClick={this.handleUpvoteClicked.bind(this)} />
              <FlatButton
                label="Downvote"
                secondary={true}
                disabled={this.state.disabledDownvote}
                onClick={this.handleDownvoteClicked.bind(this)} />

          </CardText>
        </Card>

    );
  }
}

export default Post;

I am specifically looking for help with the handleUpvoteClicked() and handleDownvoteClicked() functions as they both appear to be somewhat redundant.


texts:
I made a function about random backgrounds

And those images will unique as possible. (Shuffle again after all gone)

My steps is :

Setup the array
Shuffle it
Do function (check if isset() so run on)

PHP :

$rand_image_ids = [1048,1049,1061,1064,983,972,964];
shuffle($rand_image_ids);
$rand_images_i = 0;

function rand_image($width,$height){
    global $rand_image_ids,$rand_images_i;
    if( !isset($rand_image_ids[$rand_images_i]) ) {
        shuffle($rand_image_ids);
        $rand_images_i = 0;
    }
    $id = $rand_image_ids[$rand_images_i];
    $rand_images_i++;
    return 'https://unsplash.it/'.$width.'/'.$height.'?image='.$id;
}

So I am looking for :

Bugs ?
Any better way to do ?
Shorter codes if possible

Possible with PHP 5.6


texts: Iterator and Generator versions of Python's range()

texts:
I have created iterator and generator versions of Python's range():

Generator version

def irange(*args):
 if len(args) > 3:
     raise TypeError('irange() expected at most 3 arguments, got %s' % (len(args)))
 elif len(args) == 1:
     start_element = 0
     end_element = args[0]
     step = 1
 else:
     start_element = args[0]
     end_element = args[1]
     if len(args) == 2:
         step = 1
     elif (args[2] % 1 == 0 and args[2] != 0):
         step = args[2]
     else:
         raise ValueError('irange() step argument must not be zero')

 if((type(start_element) is str) or (type(end_element) is str)
    or (type(step) is str)):
     raise TypeError('irange() integer expected, got str')

 count = 0
 while (( start_element + step < end_element )
        if 0 < step else
        ( end_element < start_element + step )) :
     if count == 0:
         item = start_element
     else:
         item = start_element + step
     start_element = item
     count +=1
     yield item

Iterator version

class Irange:
 def __init__(self, start_element, end_element=None, step=1):
     if step == 0:
         raise ValueError('Irange() step argument must not be zero')
     if((type(start_element) is str) or (type(end_element) is str)
        or (type(step) is str)):
         raise TypeError('Irange() integer expected, got str')

     self.start_element = start_element
     self.end_element = end_element
     self.step = step
     self.index = 0

     if end_element is None:
        self.start_element = 0
        self.end_element = start_element

 def __iter__(self):
     return self

 def next(self):
     if self.index == 0:
         self.item = self.start_element
     else:
         self.item = self.start_element + self.step
     if self.step > 0:
         if self.item >= self.end_element:
                raise StopIteration
     elif self.step < 0:
         if self.item <= self.end_element:
             raise StopIteration

     self.start_element = self.item
     self.index += 1
     return self.item

Usage

 >>> for i in irange(2,5):
 ...  print i,
 2 3 4
 >>> for i in irange(2,-3,-1):
 ...  print i,
 2 1 0 -1 -2
 >>> for i in Irange(3):
 ...  print i,
 0 1 2

I would like to know if the approach is correct.


texts:
This is what I wrote to validate JSON to the given schema.

public void validateJsonSchema(ObjectNode jsonSchema, ObjectNode json) throws InvalidRequestException {

    String errorMessage = null;

    if (json != null) {

        if(jsonSchema == null) {
            errorMessage = "json exist in request but there is no schema to validate it against";
        }
        else {
            try {
                JsonSchema jsonSchema = JsonSchemaFactory.byDefault().getJsonSchema(jsonSchema);
                ProcessingReport processingReport = jsonSchema.validate(json);

                if (!processingReport.isSuccess()) {

                    StringBuilder sb = new StringBuilder();
                    processingReport.forEach(jsonError -> sb.append(String.format("[%s] ", jsonError)));

                    errorMessage = String.format("json validation failed. Errors: %s", sb.toString());
                }

            } catch (ProcessingException e) {
                errorMessage = String.format("json validation threw ProcessingException. Error Message: %s", e.getMessage());
            }
        }
    }

    if (errorMessage != null) {
        throw new InvalidRequestException(errorMessage);
    }

}

Here are few things that I had in my mind while writing this code:

I don't want to return anything from the method. Schema is either valid or invalid. In case of invalid, I just throw an exception. Since it's part of a Helper class, I think it's okay to put some business logic (throwing exception) with in this code.
I like 1 point of return or 1 point of exception throwing. Thats why I am using errorMessage to capture any error and if it exists, throw it at the end. By this approach, the code readability is much better.
The jsonSchema and json both are optional. In case if json doesn't exist, there is no point of getting into validation.


texts: Partitioning strings into substrings of fixed length

texts:
I've got a Clojure function here that's meant to parse a string of form:

  "DDXXXYYY"

where DD is meant to be discarded, and XXX and YYY are string representations of integers.

(defn split-id [tileid]
  (map #(Integer/parseInt %)
       (map (partial apply str)
            (partition 3 (drop 2 tileid)))))

Or, written with the threading macro:

(defn split-id [tileid]
  (map #(Integer/parseInt %)
       (map (partial apply str)
            (->> tileid (drop 2) (partition 3)))))

Does anyone have any recommendations for a simple way to do this? It feels like clojure.contrib.string should have a partition function that takes a string and an integer.

I think I've come up with a fairly good block of code for the above function, which I had to extend a bit. I'd love comments and suggestions on the final block.

(defn parse-ints
  "Converts all strings in the supplied collection to their integer
  representation."
  [coll]
  (map #(Integer/parseInt %) coll))

(def res-map
  ^{:doc "Map between the second digit in a MODIS TileID
metadata value and the corresponding resolution."}
  {:1 "1000"
   :2 "500"
   :4 "250"})

(defn tileid->res
  "Returns a string representation of the resolution referenced by the
supplied MODIS TileID."
  [tileid]
  (res-map (keyword (subs tileid 1 2))))

(defn tileid->xy
  "Extracts integer representations of the MODIS X and Y coordinates
referenced by the supplied MODIS TileID."
  [tileid]
  (parse-ints
   (map (partial apply str)
        (partition 3 (subs tileid 2)))))

(defn split-id
  "Returns a sequence containing the resolution, X and Y
  coordinates (on the MODIS grid) referenced by the supplied MODIS
  TileID."
  [tileid]
  (flatten
   ((juxt tileid->res
          tileid->xy) tileid)))


texts:
I created a code that import the data regularly into a selected workbook. The code run well, it takes less than 20 seconds before the data is imported successfully.

How does it work?

I get a monthly data with Excel format. I want the data to be imported into my workbook to be analysed further.

Step by step

The first part of my code run to copy the data from monthly workbook to analysis workbook.

The second part is a macro that will copy the content from the new data imported into a template table analysis based on the header. The code will only copy the content of columns if the header between 2 tables match.

Finally, I decided to add in the middle of the body of code, only for client's name column, before the macro copies all the rows at that column. I asked it to change the case of the value for each row to be UPPERCASE.

After adding this one line of code, my code run for 20 minutes.

Can someone help me to give another solution for the code to change the case to be "UPPERCASE" and also to reduce the runtime?

Option Explicit

    Dim lastRow As Long, LastTemp As Long 'lasttemp is "last row for table template
    Const StartRowTemp As Byte = 1
    Dim c As Byte 'number of columns
    Dim GetHeader As Range 'find

    Call Entry_Point 'to prevent screen updating and display alert, the value is False

'    On Error GoTo Handle

    'pick files to import - allow multiselect
    FiletoOpen = Application.GetOpenFilename _
    (FileFilter:="Excel Files (*.xlsx), *.xlsx", Title:="Select Workbook to Import", MultiSelect:=True)

    If IsArray(FiletoOpen) Then
        For FileCnt = 1 To UBound(FiletoOpen)
        Set SelectedBook = Workbooks.Open(Filename:=FiletoOpen(FileCnt))
        ShDataN.Cells.Clear
        SelectedBook.Worksheets("Client").Cells.Copy
        ShDataN.Range("A1").PasteSpecial xlPasteValuesAndNumberFormats
        SelectedBook.Close

        'locate last empty row in Monthly Table
        lastRow = ShMN.Cells(Rows.Count, 1).End(xlUp).Row + 1

        'locate last row in the new data
        LastTemp = ShDataN.Cells(Rows.Count, 1).End(xlUp).Row

       'delete the content from Analysis table

        ShMN.Rows("2:" & ShMN.Rows.Count).ClearContents

        'do while to find matching headers before copy paste
        c = 1
        Do While ShMN.Cells(1, c) <> ""

        Set GetHeader = ShDataN.Rows(StartRowTemp).Find _
        (What:=ShMN.Cells(1, c).Value, LookIn:=xlValues, MatchCase:=False, lookat:=xlWhole)
        If Not GetHeader Is Nothing Then
            ShDataN.Range(ShDataN.Cells(StartRowTemp + 1, GetHeader.Column), ShDataN.Cells(LastTemp, GetHeader.Column)).Copy
            ShMN.Cells(2, c).PasteSpecial
            ShMN.Rows("2:" & ShMN.Rows.Count).ClearFormats
            Call Range_Case
             'to change the case on column Client's name after copying
'
'                Set myrange = ShMN.Range("B2", "B" & Cells(Rows.Count, 1).Row)
'
'                For Each cell In myrange
'
'                cell.Value = UCase(cell)
'
'                Next cell

        End If 'get Header
        c = c + 1
       Loop

        Next FileCnt
        MsgBox "Data imported sucessfully", vbInformation, "General Information"

    End If 'isArray
    ShDataN.Cells.Clear

    With ShNote
        .Select
        .Range("A1").Select
    End With

    Call Exit_Point

'Handle:
'    If Err.Number = 9 Then
'    Else
'    MsgBox "An error has occured"
'    End If

Call Exit_Point

End Sub


texts: Compare directory entries (sort by access date)

texts:
I have a comparison function for use in scandir or qsort to sort an array of struct dirent *s by access date. S is the directory path of the directory whose files are being sorted, and SavesLen is strlen(S).
static int Q(const struct dirent **const First, const struct dirent **const Second) {
    const char *const FirstName = (*First)->d_name, *const SecondName = (*Second)->d_name, *const Name[] = {FirstName, SecondName};
    const unsigned short FirstLen = (unsigned short)strlen(FirstName), SecondLen = (unsigned short)strlen(SecondName), Len[] = {FirstLen, SecondLen};
    char File[SavesLen+Len[FirstLen < SecondLen]+2], *CurrPtr = memcpy(File, S, SavesLen)+SavesLen;
    *CurrPtr++ = '/';
    time_t Time[2];
    for (unsigned char I = 0; I < 2; I++) {
        memcpy(CurrPtr, Name[I], Len[I]);
        struct stat Stat;
        if (stat(File, &Stat)){
            return 0;
        }
        Time[I] = Stat.st_atimespec.tv_sec;
    }
    return Time[1]-(*Time);
}

Sorry for being obsessed with microoptimizations, but I'm looking to improve this.
S and SavesLen are both global variables defined and declared and initialized elsewhere.  Is there a way to take advantage of local scopes to delete some of the memory earlier?  Are there other improvements to be made? Thanks ahead of time.
An answerer pointed out that char File[SavesLen+Len[FirstLen > SecondLen]+2] is extremely hard to read. So here's why I do it that way. There are 2 files, and I need to check the access time of both of them. Rather than creating a path for each one, I'm reusing the same path, to minimize the number of VLA declarations and the number of memcpy() calls. Now let's break it down for you. char File[...] is a VLA declaration. The size is SavesLen plus the larger size of the 2 files, plus 2, for the / and null character. So what the heck is Len[FirstLen > SecondLen]? The reason why it's confusing is because I'm treating booleans like integers, and being weakly typed, C lets me do that. Len is an array so it will either be indexed by 0 or 1 (the 2 boolean values) depending on which one is bigger, because FirstLen > SecondLen will either evaluate to 0 or 1.
It seems the answerer understands, but in case there are others confused. I do agree that there was a bug, and that's because it used to be a ternary and I forgot to switch the values.


texts:
I wrote a Python script that, given a literary work in text file format, takes it apart, makes a word list, counts how many times each words appears in the literary work, and then checks if it follows Zipf's Law by performing the chi-square test.

For those of you who don't know Zipf's Law, put simply, it is a law that states that in literary works, the frequency of a word is inversely proportional to its rank in the frequency table. So, the second most common word will appear half as much as the most common words, the third most common word will appear a third as often, and so on.

Also, for those who don't know the Chi-Square Test, it is a test that looks for statistical significance.

It commonly takes the form of:

$$x^2 = \sum \frac{(\text{observed} - \text{expected})^2}{\text{expected}}$$

I made this script because I had recently learned to code Python and I wanted some small project to occupy my mind. However, as I am rather new, I figured that my code was not exactly "Pythonic", so I was hoping that some kind souls could help me to tell me what I'm doing wrong and provide other helpful shortcuts.

from string import maketrans
from operator import itemgetter, attrgetter, methodcaller
import math

punct = [".", ",", "!", "?", "<", ">", "\n", "'", '"', "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "_"]

f_open = open('C:\Python27\Pride and Prejudice.txt', 'r')
lines = f_open.readlines()
f_open.close()
lines = filter(lambda name: name.strip(), lines)

def cleanup(text):
    counter = 0
    new_text = []
    while counter < len(text):
        if text[counter] in punct:
            counter += 1
        elif text[counter] == " " or text[counter] == "-":
            new_text.append(" ")
            counter += 1
        else:
            new_text.insert(counter, text[counter].lower())
            counter += 1
    words = "".join(new_text)
    return words.split()

def make_list(line):
    words = []
    for x in line:
        words = words + cleanup(x)
    return words

def count_words(words):
    word_count = []
    counter = 0
    for x in words:
        for sublist in word_count:
            if x == sublist[0]:
                sublist[1] += 1
        if all(sublist[0] != x for sublist in word_count):
                word_count.append([x, 1, 0, 0])
    return sorted(word_count, key = itemgetter(1), reverse = True)

def get_numbers(lists):
    numbers = []
    for x in lists:
        numbers.append(x[1])
    return numbers

def check_zipf(counted_words):
    counter = float(1)
    standard = counted_words[0][1]
    new_list = counted_words
    for x in counted_words:
        new_list[counted_words.index(x)][2] = float(standard) / counter
        new_list[counted_words.index(x)][3] =((float(new_list[counted_words.index(x)][1]) - float(new_list[counted_words.index(x)][2]))**2) / float(new_list[counted_words.index(x)][2])
        counter += 1
    return new_list

words = make_list(lines)
counted = count_words(words)


texts:
I've implemented a SortedList which takes in streams of floats and returns a median at any point.

public class SortedList {

        float[] list;
        int pos;
        int capacity;

        public SortedList(){
            this.pos = 0;
            this.capacity = 2;
            list = new float[capacity];
        }

        public void offer(int item){
            if(pos == 0){
                list[pos] = item;
                pos++;
                return;
            }
            if(pos == 1){
                if(item > list[0]){
                    list[1] = item;
                }else{
                    float temp = list[0];
                    list[0] = item;
                    list[1] = temp;

                }
                pos++;
                return;
            }
            if(pos - list.length <= 1) resize();
            int index = -1;
            for(int i=0; i< pos -1; i++){
                if(item < list[i]){
                    index = i;
                    break;

                }else if((item > list[i] && item < list[i+1])){
                    index = i+1;
                    break;
                }
            }
            if(index > -1){
                for(int i= pos; i > index; i--){
                    list[i] = list[i -1];
                }
                list[index] = item;

            }else{
                list[pos] = item;
            }
            pos++;
        }
        public float median(){
            float median = -1;
            if(pos%2 == 0){
                median = (list[pos/2 -1] + list[(pos/2)])/2;
            }else{
                median = list[(pos/2)];
            }
            return median;
        }
        private void resize(){

            capacity = capacity*2;
            float[] arr = new float[capacity];
            for(int i=0; i< pos; i++){
                arr[i] = list[i];
            }
            list = arr;
        }

        public void trace(){
            for(int i=0; i< pos; i++){
                System.out.print(list[i] + " ");
            }
            System.out.println();
        }
}

Invite comments on efficiency and accuracy. In the test case that I've used it works fine.


texts: Rails app that scrapes forum using Nokogiri gem

texts:
I've built a website that scrapes a guitar forum's pages and populates Rails model. I'm using rake task along with heroku scheduler to run background scrapes every hour.
On the homepage, the forum ads (in the form of a Post Model) are displayed using a dataTables (jQuery plugin), so user can search from the front-end.

Questions

I had a few questions to see if there's a better way to do things.  If the questions require too much effort, then any general feedback or pointer to online resources would be appreciated.

1. Best Caching Strategy?

I'm currently implementing fragment caching, but I'm not sure if this is best practice.

First I cache all posts:

//app/views/posts/index.html
<% cache(cache_key_for_posts) do %>
<% @posts.each do |p| %>
    ....
    <%= p.replies %>
    <%= p.views %>

<% end %>
<% end %>

...using a helper method to set cache key:

def cache_key_for_posts
  last_updated_at = Post.last.updated_at.to_i
  "/all-#{last_updated_at}"
end

My understanding is that @posts = Post.all is gets cached. And when I re-scrape, memcache is sets new key-value pair, which is then being used to read current data.

The caching seems to be working at the moment, but I'm curious if there's a better way to implement caching.

2. Scraping / Exception Handling

I put all the scrape logic inside the Post Model:

  //app/models/post.rb
  class Post < ActiveRecord::Base
  default_scope { order(:id) }

  URL = "http://www.acousticguitarforum.com/forums/forumdisplay.php"\
        "?f=17&pp=200&sort=lastpost&order=desc&daysprune=200"

  # scrape guitar forum pages and create records in posts table
  def self.scrape_create
    require 'open-uri'
    begin
      data = Nokogiri::HTML(open(URL))
      test_page_scrape(data)
      numPages = data.css('td.vbmenu_control').text.split(' ').last.to_i
    rescue StandardError=>e
      puts "Error: #{e}"
      puts "Test scrape failed."
    else
      destroy_all             # delete old records
      reset_pk_sequence       # reset primary key to 0
      scrape_pages(numPages)
    end
  end

And then run the scrape using rake task:

//app/lib/tasks/scrape.rake
namespace :scrape do
  desc "Scrape AGF For Sale forum"
  task agf: :environment do
      puts "scraping AGF pages..."
      # Post.delay.scrape_create
      # no moneny for heroku workers :(
      Post.scrape_create
      puts "scraping complete."
  end
end

Again, I'm not sure if this is best practice, or if I'm missing anything.  Would appreciate a second pair of eyes to skim over and let me know if something looks off.

Notes

I received a-okay from forum owner.

Demo
Source Code


texts: Improving the running time of finding the count of pairs satisfying a symmetric relation

texts:
I had an online coding test yesterday. The question is not hard to solve, but I could not achieve the required running time. The question is as follow:

Given \$1 <= M\$, \$N <= 10^5\$ find the count of pairs A, B:

1 <= A <= M and 1 <= B <= N
\$(A^{1/3} + B^{1/3})^3\$ is an integer
Here was my solution:

I notice that this relationship is symmetric, so if assuming M >= N, and imagining we are searching valid points on a M*N matrix, I only need to search the following three parts of the matrix:

Items above the diagonal: (i, j) where 1 <= i < j <= N. Increase the counter by 2 if a valid pair has found. (Symmetric relation)
Diagonal elements.
Items int (i, j) where N+1 <= i <= M, and 1<= j <= N

My java solution is as the following

        static int cubeNumbers(int M, int N) {
            int count = 0;
            if (N > M) {
                int temp = N;
                N = M;
                M = temp;
            }
            for (int i = 1; i <= N; i ++) {
                for (int j = i + 1; j <= N; j ++) {
                    if (isValid(i, j)) {count += 2;}
                }
                if (isValid(i, i)) {count += 1;}
            }
            for (int i = N + 1; i <= M; i ++) {
                for (int j = 1; j <= N; j ++) {
                    if (isValid(i, j)) {count += 1;}
                }
            }
            return count;
        }

        private static boolean isValid(int A, int B) {
            double result = Math.pow(Math.pow(A, 1.0/3) + Math.pow(B, 1.0/3), 3);
            return (result % 1) == 0;
        }


texts: Responsive horizontal scroll on mouse position

texts:
I am making a responsive horizontal scroll UI. The horizontal scroll position is calculated according to the mouse horizontal position:

$(document).ready(function() {
  var docWidth = $('body').width(),
    slidesWidth = $('#imgs').width(),
    rangeX = slidesWidth - docWidth,
    $images = $('#imgs');

  $(window).on('resize', function() {
    var docWidth = $('body').width(),
      slidesWidth = $('#imgs').width(),
      rangeX = slidesWidth - docWidth;
  })

  $(document).on('mousemove', function(e) {
    var mouseX = e.pageX,
      percentMouse = mouseX * 100 / docWidth,
      offset = percentMouse / 100 * slidesWidth - percentMouse / 200 * docWidth;

    $images.css({
      '-webkit-transform': 'translate3d(' + -offset + 'px,0,0)',
      'transform': 'translate3d(' + -offset + 'px,0,0)'
    });
  });
})
body,html {
  margin: 0;
  overflow: hidden;
  height: 100%;
}
#imgs {
  position: absolute;
  top: 0; left: 0;
  width: 150%; height: 100%;
  display: flex;
  justify-content: space-around;
  align-items: center;
  margin: 0 25%;
  /* transition: transform .1s; */
}
#imgs > div {
  max-width: 9%;
  perspective: 500px;
  z-index: 1;
}
#imgs img {
  display: block;
  max-width: 100%;
  height: auto;
}

This works pretty well in the browsers I tested. And other than general performance enhancement I am concerned about this issue:
When the mouse comes out of the window and back in, the images snap to the new position. I tried to make that snap smoother  with transition:transform .1s on the #imgs element (commented out in the CSS) but:

in chrome, it is a little janky
in Firefox and edge it is very janky even on small mouse moves


texts: LeetCode #1120 Maximum Average Subtree (Python)

texts:
This code snippet shows 2 common patterns I see a lot in Python that I don't really like:

Arbitrarily-named, narrowly-scoped recursive function
Inappropriate data type (in this case, an array ans to store 1 float) used purely for its mutability and scope, to store side-effects from some other scope

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def maximumAverageSubtree(self, root: TreeNode) -> float:
        ans = [0]
        def helper(node):
            if not node:
                return 0, 0
            left_sum, left_count = helper(node.left)
            right_sum, right_count = helper(node.right)
            ans[0] = max(ans[0], (left_sum + right_sum + node.val) / (left_count + right_count + 1))
            return left_sum + right_sum + node.val, left_count + right_count + 1
        helper(root)
        return ans[0]

ans has to be an array, even though we just want to store one scalar value, because if we tried to use a float it would not be visible inside helper. This seems like an ugly shortcut to me.

And the other pattern I don't like is defining helper just so we can do recursion with additional return values for logic, then return helper's side effects. Is it normal to define short, sort of "throwaway" functions like this?


texts: leetcode 987. Vertical Order Traversal of a Binary Tree

texts:
anyone can provide some suggestion about my answer for the questions
987. Vertical Order Traversal of a Binary Tree

  Given a binary tree, return the vertical order traversal of its nodes values.  For each node at position (X, Y), its left and right children respectively will be at positions (X-1, Y-1) and (X+1, Y-1). Running a vertical line from X = -infinity to X = +infinity, whenever the vertical line touches some nodes, we report the values of the nodes in order from top to bottom (decreasing Y coordinates). If two nodes have the same position, then the value of the node that is reported first is the value that is smaller.

  Return an list of non-empty reports in order of X coordinate.  Every report will have a list of values of nodes.

  Input: [3,9,20,null,null,15,7]

  Given binary tree [1, 2, 3, 4, 6, 5, 7]

      1
    /   \
   2     3
  / \   / \
 4   6 5   7

  return its vertical order traversal as

  Output:  [[4], [2], [1, 5, 6], [3], [7]]

class Solution:
    def verticalOrder(self, root: TreeNode) -> List[List]:
        stack = [(root, 0)]
        node_map = dict()
        while stack:
            tmp = dict()
            for _ in range(len(stack)):
                node, index = stack.pop(0)
                if node:
                    tmp[index] = tmp.get(index, []) + [node.val]
                if node.left: stack.append((node.left, index - 1))
                if node.right: stack.append((node.right, index + 1))

            tmp = {k: sorted(i) for k, i in tmp.items()}
            node_map = {k: node_map.get(k, []) + tmp.get(k, []) for k in list(tmp.keys()) + list(node_map.keys())}
        res = sorted([(index, val) for index, val in node_map.items()], key=lambda x: x[0])
        return [i for _, i in res]


texts: Chaining multiple async calls and data manipulation within promises

texts:
Is there a better way to do this (clean, efficient, good practices)?

import aws from 'aws-sdk'

aws.config.setPromisesDependency(require('bluebird'))

ebs.describeApplications().promise()
  .then(({ Applications }) => Applications.map(app => { return { ...app, Environments: [] }}))
  .each(app => {
    return ebs.describeEnvironments({ ApplicationName: app.ApplicationName }).promise()
      .then(({ Environments }) => app.Environments = Environments)
      .catch(error => { throw error })
  })
  .then(applications => {
    console.log(applications)
  })
  .catch(error => console.error(error))

It works but it feels wrong to me.

Here is a sample of a return from each calls:

describeApplications:

{
    "Applications": [
        {
            "ApplicationName": "test-application",
            "Versions": [
                "Sample Application"
            ],
            "DateCreated": "2017-02-05T03:39:41.144Z",
            "ConfigurationTemplates": [],
            "DateUpdated": "2017-02-05T03:39:41.144Z",
            "ResourceLifecycleConfig": {
                "VersionLifecycleConfig": {
                    "MaxCountRule": {
                        "DeleteSourceFromS3": false,
                        "Enabled": false,
                        "MaxCount": 200
                    },
                    "MaxAgeRule": {
                        "DeleteSourceFromS3": false,
                        "Enabled": false,
                        "MaxAgeInDays": 180
                    }
                }
            }
        }
    ]
}

describeEnvironments:

{
    "Environments": [
        {
            "ApplicationName": "test-application",
            "EnvironmentName": "Sample-env",
            "VersionLabel": "Sample Application",
            "Status": "Ready",
            "EnvironmentLinks": [],
            "EnvironmentId": "********",
            "EndpointURL": "********",
            "SolutionStackName": "64bit Amazon Linux 2016.09 v2.5.0 running Docker 1.12.6",
            "CNAME": "********",
            "Health": "Green",
            "AbortableOperationInProgress": false,
            "Tier": {
                "Version": " ",
                "Type": "Standard",
                "Name": "WebServer"
            },
            "HealthStatus": "Ok",
            "DateUpdated": "2017-02-05T03:46:17.325Z",
            "DateCreated": "2017-02-05T03:39:46.072Z"
        }
    ]
}

And the results of my code:

[{
    ApplicationName: 'test-application',
    DateCreated: 2017 - 02 - 05 T03: 39: 41.144 Z,
    DateUpdated: 2017 - 02 - 05 T03: 39: 41.144 Z,
    Versions: ['Sample Application'],
    ConfigurationTemplates: [],
    ResourceLifecycleConfig: {
        VersionLifecycleConfig: {
            MaxCountRule: {
                Enabled: false,
                MaxCount: 200,
                DeleteSourceFromS3: false
            },
            MaxAgeRule: {
                Enabled: false,
                MaxAgeInDays: 180,
                DeleteSourceFromS3: false
            }
        }
    },
    Environments: [{
        EnvironmentName: 'Sample-env',
        EnvironmentId: '********',
        ApplicationName: 'test-application',
        VersionLabel: 'Sample Application',
        SolutionStackName: '64bit Amazon Linux 2016.09 v2.5.0 running Docker 1.12.6',
        EndpointURL: '********',
        CNAME: '********',
        DateCreated: 2017 - 02 - 05 T03: 39: 46.072 Z,
        DateUpdated: 2017 - 02 - 05 T03: 46: 17.325 Z,
        Status: 'Ready',
        AbortableOperationInProgress: false,
        Health: 'Green',
        HealthStatus: 'Ok',
        Tier: {
            Name: 'WebServer',
            Type: 'Standard',
            Version: ''
        },
        EnvironmentLinks: []
    }]
}]


texts:
The function im2col in MATLAB is very useful to vectorize Patch based Image Processing algorithms. The problem is the function isn't optimized and doesn't use C Code. I'm trying to build efficient C code for that.

This is the code I created:

function [ mColumnImage ] = ImageToColumns( mInputImage, blockRadius )
% ----------------------------------------------------------------------------------------------- %
% [ mColumnImage ] = ImageToColumns( mInputImage, blockRadius )
%   Creates an column image from the sliding neighborhood in mInpuImage
% Input:
%   - mInputImage           -   Input image.
%                               Matrix, 1 Channels, Floating Point
%   - blockRadius        -      Local Window Radius.
%                               Scalar, Floating Point, {1, 2, ..., inf}.
% Output:
%   - mColumnImage          -   Input image.
%                               Matrix, 1 Channels, Floating Point, [0, 1]
% Remarks:
%   1.  Prefixes:
%       -   'm' - Matrix.
%       -   'v' - Vector.
%   2.  C
% TODO:
%   1.  I
%   Release Notes:
%   -   1.0.000     22/08/2014  R
%       *   First release version.
% ----------------------------------------------------------------------------------------------- %

numRows = size(mInputImage, 1);
numCols = size(mInputImage, 2);

blockSize = (2 * blockRadius) + 1;

numPixelsToProcess = (numRows - blockSize + 1) * (numCols - blockSize + 1);

mColumnImage = zeros((blockSize * blockSize), numPixelsToProcess);

colImageColIdx = 0;

for iColIdx = (blockRadius + 1):(numCols - blockRadius)
    for jRowIdx = (blockRadius + 1):(numRows - blockRadius)
        colImageColIdx = colImageColIdx + 1;
        colImageRowIdx = 0;
        for kPixelColIdx = -blockRadius:blockRadius
            for lPixelRowIdx = -blockRadius:blockRadius
                colImageRowIdx = colImageRowIdx + 1;
                mColumnImage(colImageRowIdx, colImageColIdx) = mInputImage((jRowIdx + lPixelRowIdx), (iColIdx + kPixelColIdx));
            end
        end
    end
end

end

It is MATLAB code written in C style. Imagine it was C code: what would you do make it faster? What would you do to allow compiler optimizations (loop unrolling, vectorization, parallelization, etc...)?

I posted vanilla C code I created and have a few questions about it:

How can I make the memory access more efficient (hence make the code faster)?
Any place to utilize vectorization?
How can I assist the compiler and tell it no aliasing will happen?
What would be the right way to utilize OpenMP?


texts:
index.php,general message.php, logout.php, site life.php (this page for session and put it in the other pages by required)

Database:

connection.php

<?php
$dsn = "mysql:host=localhost;dbname=mg";
$username = "root";
$password = "";
$options = array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
);

try{
$conn = new PDO($dsn,$username,$password,$options);
} catch (PDOException $e){
echo "Error!".$e->getMessage();
}

?>

index.php:

<?php
session_start();
if(isset($_SESSION['user'])){
header("location: general message.php");
}
require "connection.php";

if(isset($_POST['login'])){
$user = $_POST['username'];
$pass = md5($_POST['password']);
$messeg = "";

if(empty($user) || empty($pass)) {
    $messeg = "Username/Password con't be empty";
} else {
    $sql = "SELECT username, password FROM users WHERE username=? AND
  password=? ";
    $query = $conn->prepare($sql);
    $query->execute(array($user,$pass));

    if($query->rowCount() >= 1) {
        $_SESSION['user'] = $user;
        $_SESSION['time_start_login'] = time();
        header("location: general message.php");
    } else {
        $messeg = "Username/Password is wrong";
    }
}
}

?>

Site life.php (and I will put it in the the other pages by require "site life.php")

//The lives of session is one hour 60*60=3600

<?php
session_start();

if(isset($_SESSION['user'])){
if((time() - $_SESSION['time_start_login']) > 3600){
    header("location: logout.php");
} else {
    $_SESSION['time_start_login'] = time();
}
} else {
header("location: logout.php");
}
 ?>

logout.php

<?php
session_start();
session_destroy();
header("location: index.php");
?>

General message.php

I put this in the header (to make a refresh every hour):

// 60*60=3600 one hour

<meta http-equiv="Refresh" content="3600" >

<?php
require ('site life.php');
?>


texts: Concatenating 2 array variable names to create a new variable name

texts:
I'm developing a room booking system using PHP for a school project.

I'm trying to create a variable name by concatenating values from two arrays together.
here are the two arrays:

$day = array('Mon', 'Tue', 'Wed', 'Thu', 'Fri');
$B = array('P1B', 'P2B', 'P3B', 'P4B', 'P5B', 'P6B');

and then here is the code I'm currently using to try concatenate them:

// getting all the values from the table using $_POST. There are 120 different values so it is best to create these variables using a procedure

for ($l = 0; $l < count($day); ++$l) {
    for ($k = 0; $k < count($B); ++$k) {
        $days = $day[$l];
        $week = $B[$k];
        ${$days . $week} = $_POST["'" . $days.$week . "'"];
    };
};

Is the syntax of the concatenated variable correct? Is there a better way of doing this?

The final variable names of the concatenated variable should look something like:

$MonP1B
$MonP2B
$MonP3B
$MonP4B
$MonP5B
$MonP6B
$TueP1B

etc.


texts:
This is a rags-to-riches attempt from this question, based on the popular 99 Bottles of Beer, by (lightly) using Java 8's stream-based processing.

Any room for improvement in terms of readability? I can only think of two concerns:

It's not immediately obvious what the placeholders for each Line value are expecting.
I need to skip() by HEADER_COUNT to trim away the... header.

public final class Bottles {

    enum Line {
        BOTTLES("%s bottle%s of beer"),
        ON_WALL_PREFIX("%s on the wall, %s."),
        ON_WALL_SUFFIX("%s, %s on the wall.");

        private final String pattern;

        private Line(String pattern) {
            this.pattern = pattern;
        }

        public String with(Object first, Object second) {
            return String.format(pattern, first, second);
        }
    }

    private static final int HEADER_COUNT = 2;
    private static final long ALCOLISM_LEVEL = 99;
    private static final String PASS_AROUND = "Take one down and pass it around";
    private static final String BUY_MORE = "Go to the store and buy some more";

    private Bottles() {
        // empty
    }

    public static void main(String[] args) {
        getLyrics(ALCOLISM_LEVEL).forEach(System.out::println);
    }

    public static List<String> getLyrics(long target) {
        return Stream.concat(LongStream.rangeClosed(0, target)
                        .map(i -> target - i)
                        .mapToObj(Bottles::toWord)
                        .flatMap(Bottles::getVerse)
                        .skip(HEADER_COUNT),
                    Stream.of(Line.ON_WALL_SUFFIX.with(BUY_MORE, toWord(target))))
                .collect(Collectors.toList());
    }

    private static String toWord(long i) {
        return Line.BOTTLES.with(i == 0 ? "no more" : i, i == 1 ? "" : "s");
    }

    private static Stream<String> getVerse(String value) {
        String last = Line.ON_WALL_PREFIX.with(value, value);
        return Stream.of(Line.ON_WALL_SUFFIX.with(PASS_AROUND, value), "",
                Character.toUpperCase(last.charAt(0)) + last.substring(1));
    }
}


texts:
I recently started learning and programming Java based on a series of beginner videos created by a Youtuber (TheNewBoston), who had a tutorial on a calculator. So based on everything else I've previously learned, I have tried to mix it in to create a bit more advanced one.  If you are able to minimize and clean up the code, please give a brief explanation.  I'd like some tips as well.

import java.util.Scanner;

class apples{
    public static void main(String args[]){
        Scanner checker = new Scanner(System.in);
        int selection = 0;
        double fnum, snum, answer;

        System.out.println("Calculator Program Initialized");
        System.out.println("Please select your math operator");
        System.out.println("Enter 1 for Addition");
        System.out.println("Enter 2 for Subraction");

        selection = checker.nextInt();

        if (selection == 1){
            System.out.println("Enter your first number here");
            fnum = checker.nextDouble();
            System.out.println("Enter your second number here");
            snum = checker.nextDouble();
            answer = fnum+snum;
            System.out.println("Answer: " + answer);
            System.out.println("Thank you for using my calculator");
        }else{
            System.out.println("Enter your first number here");
            fnum = checker.nextDouble();
            System.out.println("Enter your second number here");
            snum = checker.nextDouble();
            answer = fnum-snum;
            System.out.println("Answer: " + answer);
            System.out.println("Thank you for using my calculator");
        }
    }
}


texts: Sorting a list in ascending/descending order with a button toggle

texts:
I have this piece of code written as a function to handle a button-toggle for sorting a list in ascending and descending order. Below is the code which is working as expected, but I would appreciate if someone knows a better, shorter and cleaner way of writing it.

  // method called every time the button is clicked
  // it will change the sorting order
  //(ASCENDING => DESCENDING => ASCENDING => DESCENDING) in that order

  onSortChange = () => {
      this.setState({
        users: this.state.order
          ? this.state.users.sort((a, b) => {
          if (a.name < b.name) return -1;
          if (a.name > b.name) return 1;
          return 0;
      })
          : this.state.users.reverse((a, b) => {
          if (a.name < b.name) return 1;
          if (a.name > b.name) return -1;
          return 0;
      }),
        order: !this.state.order,
      });
  }
```


texts:
I have this array of objects:
const dataset = [
  {name: 'Paul', age: 10},
  {name: 'Marcus', age: 5},
  {name: 'Jennifer', age: 1},
  {name: 'Linda', age: 53},
  {name: 'Mary', age: 4},
  {name: 'Rose', age: 40},
  {name: 'Peter', age: 2},
]

and an array of ranges:
const buckets = [[0, 10], [10, 20], [20, 30], [30, 60]]

This is what I would like to get:
const result = {
  "0-10": {
    res: [{name: 'Marcus', age: 5}, {name: 'Jennifer', age: 1}, {name: 'Mary', age: 4}, {name: 'Peter', age: 2}],
    count: 4
  },
  "10-20": {res: [{name: 'Paul', age: 10}], count: 1},
  "20-30": {res: [], count: 0},
  "30-60": {res: [{name: 'Linda', age: 53}, {name: 'Rose', age: 40}], count: 2},
}

So I would like to get an object where each key is the bucket range (as string) and each value is an object that contains two info: res should be an array of people whose age is inside that bucket (min <= age < max) and count is the lenght of that array.
Here is my code:
const res = buckets.reduce((acc, bucketExtent) => {
        const keyBucket = `${bucketExtent[0]}-${bucketExtent[1]}`
        const people = dataset.filter(
          (s) => s['age'] >= bucketExtent[0] && s['age'] < bucketExtent[1]
        )
        acc[keyBucket] = {
          res: people,
          count: people.length,
        }
        return acc
      }, {})

It works but there is a smarter way? I prefer not to loop everytime the dataset array because it will be very large


texts: Validating and saving a user profile, using fat model vs. view code

texts:
I heard that fat models are good idea and I should avoid operations on database in my views so I do something like this below. Can you tell me if it's good idea and which version is better? Please also review the rest of the code by the way.

views.py

class CandidateCreateProfileView(AnonymousRequiredMixin, FormView):
    form_class = CandidateCreateProfileForm
    template_name = 'users/candidate_create_profile.html'
    success_url = reverse_lazy('account_login')

    def dispatch(self, request, *args, **kwargs):
        activation_key = self.kwargs['activation_key']
        self.user = get_object_or_404(User, activation_key=activation_key)

        if self.user.key_expires < timezone.now():
            return render_to_response('users/candidate_confirm_expired.html')
        if self.user.is_active:
            return HttpResponseRedirect(reverse_lazy('account_login'))

        return super(CandidateCreateProfileView, self).dispatch(
            request, *args, **kwargs)

    def get_initial(self):
        initial = super(CandidateCreateProfileView, self).get_initial()
        initial['name'] = self.user.name
        initial['mobile_phone'] = self.user.mobile_phone
        return initial

    def form_valid(self, form):
        self.user.name = form.cleaned_data['name']
        self.user.mobile_phone = form.cleaned_data['mobile_phone']
        self.user.notification_type = form.cleaned_data['notification_type']
        self.user.set_password(form.cleaned_data['password'])
        self.user.is_active = True
        self.user.save()

        return super(CandidateCreateProfileView, self).form_valid(form)

vs.

models.py

class User(models.Model):
    name = models.CharField(max_length=50)
    ...
    def create_candidate_profile(self, name, mobile_phone, notification_type, password):
        self.name = name
        self.mobile_phone= mobile_phone
        self.notification_type=notification_type
        self.set_password(password)
        self.is_active = True
        self.save()

and then in my CandidateCreateProfileView view:

def form_valid(self, form):
    self.user.create_candidate_profile(
        name = form.cleaned_data['name'],
        mobile_phone = form.cleaned_data['mobile_phone'],
        notification_type = form.cleaned_data['notification_type'],
        password = form.cleaned_data['password']
    )
    return super(CandidateCreateProfileView, self).form_valid(form)


texts: 99 Haskell problems, problem 9: Pack function

texts:
Today I started to tackle the 99 Haskell problems (http://www.haskell.org/haskellwiki/99_questions). I had to struggle with problem 9 which requires to Pack consecutive duplicates of list elements into sublists. If a list contains repeated elements they should be placed in separate sublists..

For example the input:

pack ['a', 'a', 'a', 'a', 'b', 'c', 'c', 'a', 'a', 'd', 'e', 'e', 'e', 'e']
["aaaa","b","cc","aa","d","eeee"]

I managed to create a pack function. However, my solution feels kind of
overcomplicated:

pack :: [[Char]] -> [[Char]]
pack xs = foldl (\acc x -> if not(null acc) && x `Data.List.isPrefixOf` (last acc)
                           then (init acc) ++ [(last acc) ++ x]
                           else acc ++ [x]) [] xs

A test of my pack function:

pack ["a", "a", "b", "b", "b", "c", "a", "a", "c"]
["aa","bbb","c","aa","c"]

Can you give me a code review?
How can I simplify it? What could I improve to make this function more idiomatic?


texts: Is there a way to avoid repetitive code in the following switch statement?

texts:
I have the following method, which is called every time the user clicks a checkbox within a Datagrid. Each column within this Datagrid has a box in its header, which checks/unchecks all child checkboxes in the respective column. This header checkbox will be updated according to the child checkboxes by the method.

My problem is that there is a lot of repetitive code in it since we do the same operation for each property (column) based on the checkbox that was clicked.

Here is the code:

    /// <summary>
    /// Sets the Columnsheadercheckbox based on the individual checkbox values of the respective filter
    /// </summary>
    private void SetHeaderCheckbox(string filterProperty = null)
    {
        if (GridData.Count == 0) return;
        var filter = GridData[0];
        DataGridDropdownProperty found;
        if (filterProperty == null) filterProperty = "all";
        switch (filterProperty)
        {
            case "SuperImpose":
                found = GridData.FirstOrDefault(f => f.SplitOver != filter.SplitOver);
                if (found == null)
                {
                    SuperimposeHeaderCheckbox = filter.SplitOver;
                }
                else
                {
                    SuperimposeHeaderCheckbox = null;
                }
                break;
            case "Normalize":
                found = GridData.FirstOrDefault(f => f.ToNormalize != filter.ToNormalize);
                if (found == null)
                {
                    NormalizeByHeaderCheckbox = filter.ToNormalize;
                }
                else
                {
                    NormalizeByHeaderCheckbox = null;
                }
                break;
            case "Legend":
                found = GridData.FirstOrDefault(f => f.ToLegend != filter.ToLegend);
                if (found == null)
                {
                    LegendHeaderCheckbox = filter.ToLegend;
                }
                else
                {
                    LegendHeaderCheckbox = null;
                }
                break;
            case "all":
                // Superimpose
                found = GridData.FirstOrDefault(f => f.SplitOver != filter.SplitOver);
                if (found == null)
                {
                    SuperimposeHeaderCheckbox = filter.SplitOver;
                }
                else
                {
                    SuperimposeHeaderCheckbox = null;
                }
                // Normalize
                found = GridData.FirstOrDefault(f => f.ToNormalize != filter.ToNormalize);
                if (found == null)
                {
                    NormalizeByHeaderCheckbox = filter.ToNormalize;
                }
                else
                {
                    NormalizeByHeaderCheckbox = null;
                }
                // Legend
                found = GridData.FirstOrDefault(f => f.ToLegend != filter.ToLegend);
                if (found == null)
                {
                    LegendHeaderCheckbox = filter.ToLegend;
                }
                else
                {
                    LegendHeaderCheckbox = null;
                }
                break;
        }
    }

My question is, if this kind of code is 'OK' or if it is, this is terrible practice, and there should be a more elegant way around it. (btw. Ignore the hardcoded strings. This is to illustrate the example)


texts: Sieve of Eratosthenes using Java 8 streams

texts:
I am learning streams and lambdas in Java 8.

I wanted to implement the classic Sieve of Eratosthenes using lambdas and streams. This is my implementation.

 /**
 * @author Sanjay
 */
class Sieve {
    /**
     * Implementation of Sieve of eratosthenes algorithm using streams and lambdas
     * It's much slower than the version with traditional for loops
     * It consumes much memory than the version with traditional for loops
     * It computes all primes upto 100_000_000 in 2 secs (approx)
     */
    public static List<Integer> sieveOfEratosthenes(int _n) {
        // if _n is empty return an empty list
        if (_n <= 1) return Arrays.asList();
        // create a boolean array each index representing index number itself
        boolean[] prime = new boolean[_n + 1];

        // set all the values in prime as true
        IntStream.rangeClosed(0, _n).forEach(x -> prime[x] = true);
        // make all composite numbers false in prime array
        IntStream.rangeClosed(2, (int) Math.sqrt(_n))
                .filter(x -> prime[x])
                .forEach(x -> unsetFactors(x, prime, _n));
        // create a list containing primes upto _n
        List<Integer> primeList = new ArrayList<>((_n < 20) ? _n : (_n < 100) ? 30 : _n / 3);
        // add all the indexes that represent true in prime array to primeList
        IntStream.rangeClosed(2, _n).filter(x -> prime[x]).forEach(primeList::add);
        // return prime list
        return primeList;
    }

    /*
     * makes all the factors of x in prime array to false
     * as primes don't have any factors
     * here x is a prime and this makes all factors of x as false
     */
    private static void unsetFactors(int x, boolean[] prime, int _n) {
        IntStream.iterate(x * 2, factor -> factor + x)
                .limit(_n / x - 1)
                .forEach(factor -> prime[factor] = false);
    }
}

What is its efficiency compared to normal for-loops?
Are there any imporvements to be made?


texts:
I would like to find a more efficienct way to use jQuery for my question and answer page.

Here is the code which I want to change. If a .q_container is clicked, I want its corresponding answer div will slide down.

$(document).ready(function() {
    $('#qc1').hover(
        function () {
            $('#a1').slideDown('fast');
        },
        function () {
            $('#a1').slideUp('fast');
        }
    );
    $("#qc2").hover(
        function () {
            $('#a2').slideDown('fast');
        },
        function () {
            $('#a2').slideUp('fast');
        }
    );
    $("#qc3").hover(
        function () {
            $('#a3').slideDown('fast');
        },
        function () {
            $('#a3').slideUp('fast');
        }
    );
});

All of my Code:

            What is a question?

            It is a way to discover something.

            What is a question2?

            It is a way to discover something2.

            What is a question3?

            It is a way to discover something3.


texts:
I wrote a simple card game in JavaScript and I wonder if anyone could give me some advice and make some improvements on my code.

Here is the demo that I build:
https://codesandbox.io/s/cardgame-his95?file=/src/index.js

So it is a 2 person card game. Every card has a number and also has a pattern.
The game goes like this: we have a set of pre-defined rules, and these rules have a ranking. The player that satisfies the highest-ranked rule will win. And there could be tie if they end up with the same ranking. The goal here is not just to make the game work, also I wanted to account for maintainability. For example, we can easily add new rules and swap the ranking and re-define the rule if possible.

There are mainly a couple of classes.
First is the Game class

class Game {
  constructor({ play1, play2, rules, messages }) {
    this.play1 = play1;
    this.play2 = play2;
    this.rules = rules;
    this.messages = messages;
  }
  play() {
    let rankOfP1 = Infinity;
    let rankOfP2 = Infinity;
    for (const rule of this.rules) {
      if (rule.validator(this.play1)) {
        rankOfP1 = rule.rank;
        break;
      }
    }
    for (const rule of this.rules) {
      if (rule.validator(this.play2)) {
        rankOfP2 = rule.rank;
        break;
      }
    }

    return rankOfP1 === rankOfP2
      ? this.messages.tie
      : rankOfP1 < rankOfP2
      ? this.messages.win.player1
      : this.messages.win.player2;
  }
}

Here the rules are an array of rule object where every object looks like this

{
    description: "Six Cards of the same pattern",
    rank: 1,
    validator: cards => {
      return hasSamePattern(cards, 6);
    }

The lower the rank gets, the more important this rule is. So If player1 satisfies a rule with rank 1, and player1 satisfies a rule with rank 2, then we say player1 won.
And validator is the function that takes an array of card object and returns a boolean to determine if the set of cards satisfy the rule.

And lastly we have a Card class which is pretty simple

class Card {
  constructor({ pattern, number }) {
    this.pattern = pattern;
    this.number = number;
  }
}

Please take a look and feel free to make some improvements on it. Also please suggest some better naming for variables if possible, I am not a native English speaker so some of the names of the variables would be a bit weird.

Finally I wrote this game in a OOP style. I know that JavaScript is not the best language out there when it comes to OOP. Also I am not really good at Object Oriented Design. I wonder if anyone knows how to rewrite the game in functional programming style. That would be super cool!


texts: Evaluating a Definite Integral, kindly check

texts:
The code below does not deal with any numerical-integration or anything related to it — just the basic rule in evaluating a definite integral of the form Ax^2 + Bx + C. I would love to hear from you guys since I'm relatively new and still learning.

This coding exercise is meant to test what we learned for the past few weeks, so anything more sophisticated than the keywords below is probably discouraged, as well as other standard library functions.

Also, under under evaluateIntegral() function, does the initialization value of lower and upper matter? I mean they do matter, but is it better to initialize it to 0 in this situation instead of 1? They give same result. Which is better?

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

void inputDegree(int *deg) {
    printf("Enter the degree of the polynomial: ");
    scanf("%d", deg);
}

void inputCoeffs(int deg, double *coeffs) {
    printf("\nEnter the coefficients of the polynomial: \n\n");
    for(int i = 0; i <= deg; i++) {
        printf("Coefficient of degree %d: ", deg - i);
        scanf("%lf", &coeffs[i]);
    }
}

void inputLimits(double *lowerL, double *upperL) {
    printf("\nEnter the lower limit of integration: ");
    scanf("%lf", lowerL);
    printf("\nEnter the upper limit of integration: ");
    scanf("%lf", upperL);
}

void computeIntegralCoeffs(int deg, double *coeffs, double *integCoeffs) {
    for(int i = 0; i <= deg; i++) {
        integCoeffs[i] = coeffs[i] / (deg + 1 - i);
    }
}

double evaluateIntegral(int degree, double *integCoeffs, double lowerLimit, double upperLimit) {
    double lower = 0, upper = 0;
    for(int i = 0; i <= degree; i++) {
        lower += integCoeffs[i] * pow(lowerLimit, (degree + 1 - i));
    }
    for(int i = 0; i <= degree; i++) {
        upper += integCoeffs[i] * pow(upperLimit, (degree + 1 - i));
    }
    return upper - lower;
}

int main() {
    int degree;
    double lowerLimit;
    double upperLimit;
    double integral;
    double *coefficients = NULL;
    double *integralCoefficients = NULL;

    inputDegree(&degree);

    coefficients = (double *)malloc((degree + 1) * sizeof(double));
    integralCoefficients = (double *)malloc((degree + 1) * sizeof(double));

    inputCoeffs(degree, coefficients);

    inputLimits(&lowerLimit, &upperLimit);

    computeIntegralCoeffs(degree, coefficients, integralCoefficients);

    integral = evaluateIntegral(degree, integralCoefficients, lowerLimit, upperLimit);

    printf("\n\nEvaluating the definite integral gives us the following area: \t%lf\n", integral);

    free(coefficients);
    free(integralCoefficients);

    return 0;
}
```


texts: Print numbers in a concentric square pattern

texts:
I am trying to solve a programming problem on a coding platform. When I execute it on my PC, it works perfectly, but when I submit the code on the coding platform, it throws a "Time Limit Exceeded" error. Can someone check my solution and help optimize it?

Given a number N, the program must print the pattern as described below.
Input Format:The first line contains the value of the N which represent the number N.
Output Format:The pattern as described below in the Example.

> Input: 4

> Output:
4444444
4333334
4322234
4321234
4322234
4333334
4444444

My Approach
Print Upper rectangle and then print the lower rectangle.
The problem statement and my code can also be found here.

import java.util.Scanner;

public class Test004_3 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int N = sc.nextInt();
        /*  PRINT UPPER PART
            4444444
            4333334
            4322234
            4321234
        */
        for(int i = N; i>(1); i--)
        {
            for(int j = N; j >i; j--)
                System.out.print(j);
            for(int j = 0; j<(i*2)-1; j++)
               System.out.print(i);
            for(int j = i+1; j<=N; j++)
                System.out.print(j);
            System.out.println("");
        }
        /*
            PRINT LOWER PART
            4322234
            4333334
            4444444
        */
        for(int i = 1; i<=(N); i++)
        {
            for(int j = N; j>i; j--)
                System.out.print(j);
            for(int j = 0; j<(i*2)-1; j++)
                System.out.print(i);
            for(int j = i+1; j <=N; j++)
                System.out.print(j);
            System.out.println("");
        }
    }
}


texts: Correct use of Serializable with lambda functions

texts:
I'm practicing saving and reading serializable objects when a friend told me serializable objects have no use in real life, that I'd better focus on JSON or XML to serialize my objects when I came across this situation:
I want to preload some FileFilters to use them in a JFileChooser dialog and I want these Filefilters to have more complicated behaviour than just file extension.
The code works fine but I've read there could be some security issues saving executable code and reading it later. Is it true? Can they be avoided?
I had to implement my own interface of Predicate due to the fact that Predicate is not Serializable.
import java.io.File;
import java.io.Serializable;

public interface MyPredicate extends Serializable {
  boolean isValid(File file);
}

This is the class that defines how the filters are going to be set (It's called List despite the fact that uses internally a Map just in case implementation changes).
import java.io.Serializable;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class FileFilterList implements Serializable {
  private Map<String, MyPredicate> filters;

  public FileFilterList() {
    this.filters = new HashMap<>();
  }

  public FileFilterList addFilter(String string, MyPredicate predicate) {
    this.filters.put(string, predicate);
    return this;
  }

  public Iterator<Map.Entry<String, MyPredicate>> getIterator() {
    return this.filters.entrySet().iterator();
  }
}

In this little program I save a list of filters in a file
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

public class SaveFileFilter {
  public static void main(String[] args) throws IOException {
    FileFilterList filterList = new FileFilterList();
    filterList
            .addFilter("txt, Text files", f -> f.isDirectory() || f.getName().endsWith(".txt"))
            .addFilter("Big txt, Big txt files (>1Kb)", f -> f.isDirectory() || (f.getName().endsWith(".txt") || f.length() > 1024))
            .addFilter("Small txt, Small txt file (<=1Kb)", f -> f.isDirectory() || (f.getName().endsWith(".txt") || f.length() <= 1024));
    try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("filters.obj"))) {
      oos.writeObject(filterList);
    } catch (IOException ioe) {
      System.err.println("Sorry, there wa a problem saving filters");
      ioe.printStackTrace();
      throw ioe;
    }
  }
}

And this would be the main program that get the preset file filter list:
import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import java.io.*;

public class FileFilterUse {
  public static void main(String[] args) throws IOException, ClassNotFoundException {
    JFileChooser fileChooser = new JFileChooser();
    try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("filters.obj"))) {
      FileFilterList filterList = (FileFilterList) ois.readObject();
      filterList.getIterator().forEachRemaining(
              (entry) -> fileChooser.addChoosableFileFilter(new FileFilter() {
                @Override
                public boolean accept(File f) {
                  return entry.getValue().isValid(f);
                }

                @Override
                public String getDescription() {
                  return entry.getKey();
                }
              }));
      fileChooser.showOpenDialog(null);
    } catch (IOException ioe) {
      System.err.println("There was a problem reading filters file");
      ioe.printStackTrace();
      throw ioe;
    } catch (ClassNotFoundException cnf) {
      System.err.println("File format is not correct");
      cnf.printStackTrace();
      throw cnf;
    }
  }
}

Every java file has a package line.
I guess it is not possible to achive this serializing objects to JSON or XML, is it?
By the way, any comment about the code would be very appreciated.