texts: Python program to rank based on the frequency of names that appears in text files

texts:
I've written a python program to rank the names that appear in the file(s) based on their frequency. In other words, there are multiple files and want to rank the frequency of the names that appears the most first, then the least at the end. Each name can appear only once in each file. In other words, the same name cannot be repeated in the same file.

Following is the program, that I've written, and wanted to hear your thoughts, on the style/efficiency and tips to improve the same

from pandas import DataFrame
filenames = [ 'Q1.txt', 'Q2.txt' , 'Q3.txt' , 'Q4.txt']
pathToDataFiles = "C:\\DataFiles\\"
outputHTMLFile =pathToDataFiles + "list.html"
df = DataFrame( columns = ['Name', 'Q1', 'Q2', 'Q3', 'Q4' ])

currentQtr = 1
for filename in filenames:
    entireFilename = pathToDataFiles  + filename
    # Get all the names from the file
    allNames = [line.rstrip('\n') for line in open(entireFilename)]
    # For each name from the latest .txt file
    for eachname in allNames:
        # If the name is in the dataframe then replace the current quarter with 'Y'
        if ( df['Name'].str.contains(eachname).any() ):
           rowNumber = df.loc[df['Name'] == eachname].index[0]
           df.iloc[[rowNumber],[currentQtr]] = 'Y'
        else:
            # It is a new name, thus, replace the current Qtr with 'Y'. Rest with be Nan
            emptyDataFrame =DataFrame( columns = ['Name', 'Q1', 'Q2', 'Q3', 'Q4' ])
            emptyDataFrame = emptyDataFrame.append([{'Name':eachname}])
            rowNumber = 0
            emptyDataFrame.iloc[[rowNumber], [currentQtr]] = 'Y'
            df = df.append(emptyDataFrame)
            df.index = range(len(df))

    currentQtr = currentQtr + 1
# Create a new column with 'Total' occurence of names
df['Total'] = currentQtr - df.isnull().sum(axis=1) - 1
# Sort by total
df = df.sort_values(by=['Total'], ascending=False)
df.index = range(len(df))
# Fill all Nan with 'X'
df = df.fillna('X')
df.to_html(outputHTMLFile)


texts: Toggling checkboxes based on certain conditions

texts:
I have a bunch of checkboxes that need to be toggled based on certain conditions. My function is called by multiple buttons on an onclick event. The certain condition is expressed as a string (check_all, uncheck_all, check_all_virtual). The problem that I see is that if the function would be called as toggleCheckboxes('typo'), that the error wouldn't be so easy to see as there would be no error message. Such problems should probably yield more information. How could this be done better?

    <input name="site_ids[]" data-is-virtual="0" value="1" class="checkbox"/> SG3
    <input name="site_ids[]" data-is-virtual="1" value="2" class="checkbox"/> SG1
    <input name="site_ids[]" data-is-virtual="0" value="3" class="checkbox"/> SG2

    <button onclick="toggleCheckboxes('check_all')">Check All</button>
    <button onclick="toggleCheckboxes('uncheck_all')">Uncheck All</button>
    <button onclick="toggleCheckboxes('check_all_virtual')">Check All Virtual</button>

The functionality is correct. Checking all virtual shouldn't uncheck non-virtual.


texts: Rake task to send users a reminder to post with conditions

texts:
I am implementing a feature that reminds users to make a post via email if

the user has set daily reminders to true
he has not posted yet today
and if the current hour matches when he would like to receive the daily reminder in his time zone.

I am going to write a Rake task for it and then schedule it to run every hour.

Currently, the rake tasks looks like this:

namespace :mail do
  desc "Send daily reminder to users"
  task :daily_reminder => :environment do
    User.all.each do |user|
      Time.zone = user.time_zone
      if user.reminder == true && Time.current.strftime("%H").to_i == user.reminder_time && user.reminded == false
        UserMailer.test_email(user).deliver_now
        user.update_attribute(:reminded, true)

      elsif Time.current.strftime("%H") == user.reminder_time + 1 && user.reminded == true
        user.update_attribute(:reminded, false)
        puts "Update to false"
      end
    end
  end
end

I am resetting the field reminded back to false the hour after they were reminded.

Since I am rather new to Ruby and Ruby on Rails I would appreciate feedback on the setup of this feature a lot.

Please critique away on anything you think is broken or needs improvement.

Also, right now it is not working and it's giving me back a undefined method + for nil:NilClass which tells me that the user hasn't an ActiveRecord assigned to it? Because the reminder_time column exists and is set (to 16:00).

Follow-up question:

The if clause looks kind of large and unclean. Is that the proper way to go about this?
Shall I make the whole logic more clean by putting some of the conditions in methods?


texts:
This is my third day of learning Javascript through an online class. I learned about arrays and while/for loops today, and to practice all of that stuff the challenge I'm working on is to make a function that produces \$(n)\$ terms of the Fibonacci sequence in an array.
So I'm hoping for some feedback on this code! I think it works but I would like to know how I could make it more efficient or better in any way.
function fibonacciGenerator (n) {
    var output=[];
    if (n===1) {
      output=[0];
    } else if (n===2) {
      output=[0,1];
    } else if (n>2) {
      output=[0,1];
      for (var i=3;i<=n;i++) {
        output.push(output[i-3]+output[i-2]);
      }
    }
    return output;
}


texts:
I implemented a 2D counterpart of std::array named array2d in C++17. It is an aggregate like std::array, and provides similar interface. The goal is that if you know how to use std::array, then you will find yourself at home using array2d. Any comments are welcome :) For better viewing experience with highlighting, you can refer to this GitHub page.

#include <cstddef>
#include <array>
#include <iterator>

template <typename T, std::size_t N0, std::size_t N1>
struct array2d {
  using row_t = std::array<T, N1>;
  inline static constexpr std::array sizes{ N0, N1 };

  static constexpr std::size_t size() noexcept { return N0 * N1; }
  static constexpr bool empty() noexcept { return !size(); }

  T& at(std::size_t i, std::size_t j) { return data_.at(i).at(j); }
  const T& at(std::size_t i, std::size_t j) const { return data_.at(i).at(j); }

  row_t& operator[](std::size_t i) noexcept { return data_[i]; }
  const row_t& operator[](std::size_t i) const noexcept { return data_[i]; }

  T& front() { return data_.front().front(); }
  const T& front() const { return data_.front().front(); }

  T& back() { return data_.back().back(); }
  const T& back() const { return data_.back().back(); }

  T* data() noexcept { return data_.data()->data(); }
  const T* data() const noexcept { return data_.data()->data(); }

  T* begin() noexcept { return data(); }
  const T* begin() const noexcept { return data(); }

  T* end() noexcept { return data() + size(); }
  const T* end() const noexcept { return data() + size(); }

  auto rbegin() noexcept { return std::make_reverse_iterator(end()); }
  auto rbegin() const noexcept { return std::make_reverse_iterator(end()); }

  auto rend() noexcept { return std::make_reverse_iterator(begin()); }
  auto rend() const noexcept { return std::make_reverse_iterator(begin()); }

  void fill(const T& v) {
    for (auto& row : data_) {
      row.fill(v);
    }
  }

  friend void swap(array2d& a, array2d& b) { a.data_.swap(b.data_); }

  std::array<row_t, N0> data_;
};


texts: Haskell version of HackerRank problem solution "NumberTheory/Restaurant"

texts:
Link to the challenge

  Given an input of \$T\$ rectangles, each of various dimensions \$l \times b\$, what is the minimum number of identical perfect squares that would cover each rectangle with no overlap or excess?

  Constraints

  \$1 \le T \le 1000\$
  \$1 \le l\$, \$b \le 1000\$

  Sample Input

2
2 2
6 9

  Sample Output

1
6

import System.IO (readLn, getLine)
import Control.Monad (replicateM)

main :: IO ()
main = getNumLoaves >>= getLoafDimensions >>= mapM_ (print . minNumberOfSlices)

getNumLoaves :: IO Int
getNumLoaves = readLn

parseInt :: String -> Int
parseInt = read

tuplefy :: [a] -> (a, a)
tuplefy xs = case xs of [a, b] -> (a, b)
                        _      -> error "each line of input must consist of 2 integer values."

getLoafDimensions :: Int -> IO [(Int, Int)]
getLoafDimensions =
  let rawText         = flip replicateM getLine
      parseDimensions = map $ tuplefy . map parseInt . words
  in fmap parseDimensions . rawText

squares :: [Int]
squares = map (^2) [1..1000]

squareRoot :: Int-> Int
squareRoot squaredNum = floor . sqrt $ fromIntegral squaredNum

minNumberOfSlices :: (Int, Int) -> Int
minNumberOfSlices (l, b) =
  let area                        = l * b
      isPerfectSliceDimension num = area `rem` num + b `rem` squareRoot num + l `rem` squareRoot num == 0
      largestSquare               = last $ filter isPerfectSliceDimension $ take (min l b) squares
  in if l == b
     then 1
     else area `div` largestSquare


texts: Finding the keys of map with the highest values (equality may occur)

texts:
I am currently implementing a Poker game, I have created all the logic for getting the rank of a hand, and I now have to determine the winner of a given hand.

Due to this being Poker, there may be multiple winners in a round. I, therefore, need to find all the keys (Player) that have the best hand (regardless of how many there are).

   public Map<Player, Hand> determineWinner(Map<Player, Hand> hands) {
        // Initialize worst possible hand (any hand beats this) - less verbose than
        // having to get a random element form the map
        Hand currentBestHand = new Hand(RankType.HIGH_CARD, CardRank.DEFAULT, new ArrayList<>(), new ArrayList<>());
        Map<Player, Hand> bestHands = new HashMap<>();
        for (Map.Entry<Player, Hand> playerAndHand : hands.entrySet()) {
            int comparisonValue = playerAndHand.getValue().compareTo(currentBestHand);
            if (comparisonValue > 0) {
                currentBestHand = playerAndHand.getValue();
                bestHands.clear();
                bestHands.put(playerAndHand.getKey(), playerAndHand.getValue());
            } else if (comparisonValue == 0) {
                bestHands.put(playerAndHand.getKey(), playerAndHand.getValue());
            }
        }
        return bestHands;
    }

However, I am using Java 8 and thus a lot of streams. I couldn't figure out a (pretty) way to implementing the above in streams, and therefore ended up coding it in a loop. I welcome any suggestions, especially those related to writing it succinctly and efficiently using Java 8 streams.


texts:
Is this the best way to prefix all lines written by a Bash script to standard error?

#! /bin/bash

exec 3>&2
exec 2> >(sed 's/^/ERROR: /' >&3)

echo stdout
echo stderr >&2

I am wondering, if I have to close file descriptor 3.


texts:
I have code to find images in my selections. But when nothing in selection (loop FOR) and selection is kinda big, it's kinda laggy. How can I improve my code?

  var toStageCoord = map.stageXYToCoordinates(toStage.x + selection.x1, toStage.y + selection.y1);

  var element1 = document.elementFromPoint(toStage.x + selection.x1, toStage.y + selection.y1);
  var element2 = document.elementFromPoint(toStage.x + selection.x2, toStage.y + selection.y2);
  var element3 = document.elementFromPoint(toStage.x + selection.x2, toStage.y + selection.y1);
  var element4 = document.elementFromPoint(toStage.x + selection.x1, toStage.y + selection.y2);
  var found = false;

  if(element1.localName == "image" || element2.localName == "image" || element3.localName == "image" || element4.localName == "image") {
    found = true;console.log("foundfirst");
  }

  for(var y = toStage.y + selection.y1;y < toStage.y + selection.y2 ;y++) {
    if(found){break;}

    for(var x = toStage.x + selection.x1;x < toStage.x + selection.x2;x++) {
      var element = document.elementFromPoint(x,y);

      if(element.localName === "image") {

        console.log("found");
        found = true;
        break;
      }
    }
  }


texts:
In his Clean Code book, Robert C. Martin states that functions should do only one thing and one should not mix different levels of abstraction. So I started wondering whether the code below meets these requirements (I assume the answer is negative). Which one of the following code snippets is better?

Snippet 1

public void run() {
    isRunning = true;

    try {
        serverSocket = new ServerSocket(port);
    }
    catch (IOException | IllegalArgumentException e) {
        System.out.println("Could not bind socket to given port number.");
        System.out.println(e);
        System.exit(1);
    }

    while(isRunning) {
        Socket clientSocket = null;

        try {
            clientSocket = serverSocket.accept();
        }
        catch (IOException e) {
            logEvent("Could not accept incoming connection.");
        }

        Client client = new Client(clientSocket, this);
        connectedClients.put(client.getID(), client);
        Thread clientThread = new Thread(client);
        clientThread.start();
        logEvent("Accepted new connection from " + clientSocket.getRemoteSocketAddress().toString());
        client.send("@SERVER:HELLO");
    }
}

Snippet 2

public void run() {
    isRunning = true;

    createServerSocket();

    while(isRunning) {
        Socket clientSocket = null;
        clientSocket = acceptConnection();
        addClient(clientSocket);
    }
}

private void createServerSocket() {
    try {
        serverSocket = new ServerSocket(port);
    }
    catch (IOException | IllegalArgumentException e) {
        System.out.println("Could not bind socket to given port number.");
        System.out.println(e);
        System.exit(1);
    }
}

private Socket acceptConnection() {
    try {
        Socket clientSocket = serverSocket.accept();
    }
    catch (IOException e) {
        logEvent("Could not accept incoming connection.");
    }
    return clientSocket;
}

private void addClient(Socket clientSocket) {
    Client client = new Client(clientSocket, this);
    connectedClients.put(client.getID(), client);
    Thread clientThread = new Thread(client);
    clientThread.start();
    logEvent("Accepted new connection from " + clientSocket.getRemoteSocketAddress().toString());
    client.send("@SERVER:HELLO");
}

However, splitting such simple code into multiple fragments seems like an overkill (although it's more readable - is it?). Besides, createServerSockets has side effects (Sys.exit) and addClient does too many things at once. Any advice?


texts: RXJS queue up multiple http requests and send when x conditions happens

texts:
Just started to use rxjs few weeks ago, I think I'm getting most of it right, but my code seems to be not that efficient and prone to bugs I haven't run into yet!

I need to be able to send http requests my app is online(1) and when the user is authenticated(2) and when there's anything to send(3). I'm pretty sure there's a smart way to combine those 3 conditions the "rxjs" way :)

SuperHttpRequest

class SuperHttpRequest extends HttpRequest<any> {

  _id: string; // Used for localStorage

  constructor(method: string, url: string, body: any, _id?: string) {
    super(method, url, body);
    this._id = _id || UUID.UUID();
  }
}

HttpRequestHandler

@Injectable()
class HttpRequestHandler extends ReplaySubject<SuperHttpRequest> {

  nbItemsInQueue$: ReplaySubject<Number>; // Needed by a component (sync progress), would be better to use the combined http request time
  private requests: SuperHttpRequest[];
  private requestsSubcription: Subscription;

  constructor(
    private network: Network, // Ionic service
    private http: HttpClient,
    private localStore: LocalStore<SuperHttpRequest[]>,
    private authService: AuthenticationService) {

    super();

    this.requests = [];
    this.nbItemsInQueue$ = new ReplaySubject(this.requests.length);

    this.localStore.get('http-request')
      .then(requests => {
        if (requests) {
          requests.forEach(request => {
            this.next(new SuperHttpRequest(request.method, request.url, request.body, request._id));
          });
        }
      });

    this.nbItemsInQueue$
      .subscribe(() => this.localStore.set('http-request', this.requests));

    this.authService.currentUser$
      .subscribe(user => {
        if (!user) { if (this.requestsSubcription) { this.requestsSubcription.unsubscribe(); } }
        else {
          this.requestsSubcription = this
            .takeWhile(() => {
              if (navigator.onLine) { return true; }
              else { throw Error(); }
            })
            .retryWhen(() => this.network.onConnect())
            .subscribe(request => this.handleHttpRequest(user, request));
        }
      });
  }

  private handleHttpRequest(user: Credentials, request: SuperHttpRequest) {
    this.http.request(request.clone({ setHeaders: { Authorization: `Bearer ${user.token}` } }))
      .retryWhen(error => {
        return error
          .mergeMap((error: any) => {
            if (error.status === 503) {
              return of(error.status).delay(2000)
            }
            return Observable.throw({ error: 'No retry' });
          })
          .take(5)
          .concat(Observable.throw({ error: 'Sorry, there was an error (after 5 retries)' }));
      })
      .subscribe(res => {
        if (res instanceof HttpResponse) {
          remove(this.requests, (req) => req._id === request._id);
          this.nbItemsInQueue$.next(this.requests.length);
        }
      });
  }

  next(request: SuperHttpRequest) {
    this.requests.push(request);
    this.nbItemsInQueue$.next(this.requests.length);
    super.next(request);
  }

}


texts:
I wrote a C++ implementation of a sparse table (I wrote it for an arbitrary function) and I want so much to ask for a review. I'd like to know how I can make it better, especially the consistency of the code and the design.

Explanation:

For example, you want to solve the RMQ problem with a lot of queries. You can precompute answers for segments, which have length \$2^i\$, and then give an answer for a query with the speed \$O(1)\$ (you need to compare two precomputed answers).

template<typename T_Type, typename Function>
class SparseTable {
private:
    static vs_ log_;
    std::vector<std::vector<T_Type>> sparse_;
    Function func_;

public:
    SparseTable(const std::vector<T_Type> &mass, Function func = Function()) : sparse_(), func_(func) {
        size_t len = mass.size();
        size_t add = log_.back() + 1;
        while (static_cast<size_t> (1 << add) <= len) {
            log_.insert(log_.end(), static_cast<size_t> (1 << add), add);
            ++add;
        }
        sparse_.resize(log_[len] + 1);
        for (size_t pow = 0; pow <= log_[len]; ++pow) {
            sparse_[pow].reserve(len);
            for (size_t j = 0; j < len; ++j) {
                if (pow == 0) {
                    sparse_[pow].emplace_back(func_(mass[j], mass[j]));
                } else {
                    sparse_[pow].emplace_back(func_(sparse_[pow - 1][j],
                                                    sparse_[pow - 1][std::min(j + (1 << (pow - 1)),
                                                                              len - 1)]));
                }
            }
        }
    }

    inline T_Type get(size_t left, size_t right) const {
        return func_(sparse_[log_[right - left]][left],
                     sparse_[log_[right - left]][right - (1 << log_[right - left])]);
    }
};

template<typename T_Type, typename Function> vs_
        SparseTable<T_Type, Function>::log_ {0, 0, 1, 1};

An example:

template<typename T_Type>
struct TwoVarMax {
    inline T_Type operator()(const T_Type &lhs, const T_Type &rhs) const {
        return std::max(lhs, rhs);
    }
};

std::vector<int> vec{5, 3, 7};
SparseTable<int, TwoVarMax<int>> sparse(vec);
std::cout << sparse.get(0, 1) << std::endl;


texts: Vue.js v-if for a checkbox selection of data from a csv

texts:
I'm creating an option checkbox for an Organization data only if they have Organization data to submit from their CSV. I am creating a
 and my <select> and <option> are wrapped inside of the
.

Do I need to create an input ? I'm in Vue.js and don't see any current methods or v-if nested in the right way. I want this selection of this checkbox to be done upon upload of the CSV and prior to submit.

HTML

  <input type="checkbox" id="organization" ref="Organization" v-model="checkbox" :v-if="field in requiredOrganizationFields"

 Organization Fields

    {{field}}
    <select :id="field" :name="field" v-model="mapping[field]" required>
      <option value="">Please Select</option>
      <option v-for="columnName in columnNames" :name="columnName" :value="columnName"  value="">{{columnName}}</option>
    </select>

JavaScript

    data: null,
          columnNames: [],

  file: null,
  requiredContactFields: [
    'contact_account_name',
    'contact_first_name',
    'contact_last_name'
      ],
  optionalContactFields: [
    'contact_email',
    'contact_phone',
    'contact_address',
    'contact_city',
    'contact_region',
    'contact_postal_code'
      ],
  requiredOrganizationFields: [
      'organization_account_name',
      'organization_name'
      ],
  optionalOrganizationFields: [
      'organization_email',
      'organization_phone',
      'organization_address',
      'organization_city',
      'organization_region',
      'organization_postal_code'

      ]

}

getColumnNames() {
  let formData = new FormData();
  formData.append('file', this.file);
  let self = this;
  axios
  .post('http://localhost:8080/api/contacts/csv-column-names',
  formData,
  {
    headers: {
      'Content-Type': 'multipart/form-data'

    }
  }

  )
  .then(function(response){
    console.log('SUCCESS!!');
    console.log(response);
    //Need array of column names you get from the back-end
    self.columnNames = response.data.column_names;

  })
  .catch(function(response){
    console.log('FAILURE!!');
    console.log(response);

  })

},


texts:
I am fairly new to Assembly language programming and, for practice, I gave myself a problem: count down from 10 and right after 1, say "Blast off!".

section .text
    global _start
_start:
    mov eax, '10' ; asci 10
    mov [num], eax ; num now equals ascii 10

    mov edx, 2
    mov ecx, num
    mov ebx, 1
    mov eax, 4
    int 80h ; prints out '10' in the console

    mov eax, 9 ; numerical 9
    call subtract
subtract:
    call log ; logs the current number

    sub eax, 1 ; subract 1

    cmp eax, 0
    jne subtract ; if it doesn't equal 0, jump to subtract
    je blast_off ; if it does equal 0, jump to blast off
log:
    call to_ascii ; converts eax's value to ascii
    mov [num], eax ; num = eax
    mov edx, 1
    mov ecx, num
    mov ebx, 1
    mov eax, 4
    int 80h ; output the current number
    call to_number ; converts eax back to numerical
    ret
to_number:
    mov eax, [num] ; is this necessary? Moves num back into eax
    sub eax, '0' ; converts to numerical
    ret
to_ascii:
    add eax, '0' ; converts to ascii
    ret
blast_off:
    mov edx, len
    mov ecx, msg
    mov ebx, 1
    mov eax, 4
    int 80h ; outputs "Blast off!"

    mov eax, 1
    int 80h ; exits program
section .data
    msg db "Blast off!", 0xA ; message
    len equ $-msg ; length of message
section .bss
    num resb 1 ; this is for outputting the current number

Output:

  1098654321Blast off!

Assembled: nasm -f elf blast_off.s

Linked: ld -m elf_i386 -s -o blast_off blast_off.o

My main concerns are:

My code seems functional - is this bad, or does it not really matter, being assembly language?
Is there repetition? This was a very difficult challenge for me, and at times I lost my head - sometime during those times I might have typed something completely "off topic" in regards to the subject of the code
Aside from the first concern, does the organization need re-organizing? As in, should I reorder the different sections(.test, .data, .bss)? Or, does it not make a difference?


texts: Summations and products and factorials oh my

texts:
The proper title of this question should be "Summations and products, and factorials oh my!".

After getting quite a bit of useful feedback on this question from @mjolka, and a comment, I decided that there were many things to be improved.

These are the following things that I've added/changed:

A factorial function which uses the product function.
Support for getting the sum, and product of sequences with no elements.
Strongly typed anonymous function parameters.

Again, for those who don't know, a summation is defined as follows:

  $$\sum_{n=a}^{b}f(n)$$

And a product is defined as follows:

  $$\prod_{n=a}^{b}f(n)$$

I'd like to know the following things, which are more or less mostly the same as the ones in the last question:

Am I writing this in a proper functional way?
How can I reduce the repetitiveness in my code?
Is there a way to improve performance? It already runs pretty fast, at approximately \$0.025\$ seconds for inputs of \$10\$).
Anything else?

Here's the code:

let inline summation (f: (double -> double)) low high =
    match (low, high) with
    | (low, high) when low <> high ->
        { low .. high }
        |> Seq.map f
        |> Seq.sum
    | (low, high) when low = high -> 0.0
    | _ -> -1.0

let inline product (f: (double -> double)) low high =
    match (low, high) with
    | (low, high) when low <> high ->
        { low .. high }
        |> Seq.map f
        |> Seq.fold Checked.op_Multiply 1.0
    | (low, high) when low = high -> 1.0
    | _ -> -1.0

let inline factorial n =
    product (fun x -> x) 1.0 n

Here's a few small tests to ensure that the code works:

[<EntryPoint>]
let main argv =
    System.Console.WriteLine(summation (fun x -> x) 1.0 10.0)
    System.Console.WriteLine(product (fun x -> x) 1.0 10.0)
    System.Console.WriteLine(factorial 10.0)
    0

And here's expected output of the above tests:

55
3628800
3628800


texts:
I am trying to implement a "find nearest location" from a given latitude and longitude using MySql. I have 8000 locations stored in my WordPress website.

I managed to write this:

SELECT
   b.ID,
   SQRT( POW(69.1 * (b.latitude - 51.5073509), 2) + POW(69.1 * (-0.1277583 - b.longitude) * COS(b.latitude / 57.3), 2)) AS distance
FROM
   wp_posts a
LEFT JOIN
(
   SELECT
      post_id AS ID,
      MAX(CASE WHEN meta_key = 'theme_directory_map_latitude' THEN meta_value ELSE NULL END) AS latitude,
      MAX(CASE WHEN meta_key = 'theme_directory_map_longitude' THEN meta_value ELSE NULL END) AS longitude
   FROM
      wp_postmeta
   WHERE
      meta_key = 'theme_directory_map_latitude' OR meta_key = 'theme_directory_map_longitude'
   GROUP BY
      post_id
) b ON a.ID = b.ID
WHERE
   a.post_type = 'directory'
HAVING
   distance < 30
ORDER BY
   distance

The script above does what I need but it takes too long for it to process on my WordPress site, sometimes I even get a time out error.

Is there a way where I can optimise the above code so it runs a lot quicker?


texts:
I am trying to keep the progression of the Review Queue Notifier moving forward.  My next big move is to turn it into an extension for Chrome and FireFox and eventually Edge.

I would like the Javascript for the code reviewed again to get me back into the groove of coding this extension/script.

Here are the guts:

$( document ).ready(function() {
    //Public Key
    var publicKey = '?key=hyEwZ8*W*OF7tQ3KYgNjzg((';
    var sites;
    var ACTIVESITES;// = chrome.storage.sync.get(activeSites);

    GetSelectedSites();
    getAllTehSitez();

    function getAllTehSitez() {
        console.log("getAllTehSitez has been called");
        $.getJSON('http://api.stackexchange.com/2.2/sites' + publicKey + '&pagesize=100', function(data) {
            sites = data.items;
            isActiveSite();
        });
    }

    function isActiveSite() {
        console.log("isActiveSite has been called");
        chrome.runtime.sendMessage("getUrl", function(response) {
            var tabUrl = response.url;
            for (var site in sites) {
                if ((tabUrl == sites[site].site_url + '/review')
                    && (ACTIVESITES.indexOf(sites[site].name.toLowerCase()) > -1)) {
                        runRQN();
                        return;
                }
            }
        });
    }

    function GetSelectedSites () {
        console.log("GetSelectedSites has been called");
        chrome.storage.sync.get({
            activeSites: "Code Review"
        }, function(item) {
            ACTIVESITES = item.activeSites;
        });
    }

    function runRQN () {
        console.log("runRQN has been called")
        Notification.requestPermission();
        var DELAY =  300 * 1000; //120,000 milliseconds = 2 Minutes
        function getDelayAmount() {
            chrome.storage.sync.get({
                refreshRate: 300000
            }, function(item){
                DELAY = item.refreshRate;
            });
        }
        getDelayAmount();

        setTimeout(function(){
            window.location.reload();
        }, DELAY);

        console.log(DELAY);
        var notificationTitle = (document.title.split(' - ')[1] + ' Review Queue').replace(' Stack Exchange', '.SE');
        var reviewCount = 0;
        var reviewItems = document.getElementsByClassName('dashboard-num');

        for (var i = 0; i < reviewItems.length; i++){
            if (reviewItems[i].parentNode.className != 'dashboard-count dashboard-faded'){
                reviewCount += parseInt((reviewItems[i].getAttribute("title")).replace(',', ''), 10);
                console.log(reviewItems[i]);
            }
        }
        console.log(reviewCount);
        var image = chrome.extension.getURL('Icon2.jpg');
        if (reviewCount > 0) {
            var details = {
                body: reviewCount + ' Review Items',
                icon: image
            }
            var n = new Notification(notificationTitle, details );
            setTimeout(n.close.bind(n), 100000); // Magic number is time to notification disappear
        }
    }
});

Stack Apps Question

GitHub Repository

This is a follow-up to the following questions, kind of...

First Question

Second Question


texts:
I've written a simple Java class to encrypt and decrypt files using AES. The code works and I'm able to encrypt and decrypt files.

However, I understand this is an easy way of implementing AES and far from the most secure (my usage of ECB mode for example).

I'm looking to improve the strength of encryption this code provides.

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.security.Key;

class Crypto {

    // Process a file (Encrypts or decrypts depending on cipherMode)
    private void processFile(boolean encrypt, File inputFile, String inputKey, File outputFile) throws Exception {
        // Convert key into bytes
        Key key = new SecretKeySpec(inputKey.getBytes(),"AES");

        // Get cipher instance
        Cipher cipher = Cipher.getInstance("AES");

        if(encrypt) {
            cipher.init(Cipher.ENCRYPT_MODE,key);
        }
        else {
            cipher.init(Cipher.DECRYPT_MODE,key);
        }

        // Read input file into byte array
        FileInputStream fileInputStream = new FileInputStream(inputFile);
        byte[] inputBytes = new byte[(int)inputFile.length()];
        fileInputStream.read(inputBytes);

        // Process the byte array from the input file
        byte[] outputBytes = cipher.doFinal(inputBytes);

        // Write the output byte array to the output file
        FileOutputStream fileOutputStream = new FileOutputStream(outputFile);
        fileOutputStream.write(outputBytes);

        // Close file streams
        fileInputStream.close();
        fileOutputStream.close();
    }

    // Encrypts a file
    void encrypt(File inputFile, String inputKey, File outputFile) throws Exception {
        processFile(true,inputFile,inputKey,outputFile);
    }

    // Decrypts a file
    void decrypt(File inputFile, String inputKey, File outputFile) throws Exception {
        processFile(false,inputFile,inputKey,outputFile);
    }

}

The encrypt() and decrypt() methods are there purely for easy of use and readability when using the code.


texts: Split Collection to two list depend on criteria

texts:
Let's say I have a List contains numbers:

1,2,3,4,5,6,7,8,9

and I would like to split this to two lists:

odd numbers
even numbers

So I can do this two ways:

Solution 1:

Create two methods:

List<Integer> filterOdd(List<Integer> numbers){
    List<Integer> result  = new ArrayList<Integer>();
    for(Integer n : numbers){
        if(n % 2 != 0){
            result.add(n);
        }
    }
    return result;
}

List<Integer> filterEven(List<Integer> numbers){
    List<Integer> result  = new ArrayList<Integer>();
    for(Integer n : numbers){
        if(n % 2 == 0){
            result.add(n);
        }
    }
    return result;
 }

and in the code I will call:

List<Integer> numbers = Arrays.asList(new Integer[] { 1,2,3,4,5,6,7,8,9 });

List<Integer> oddNumbers = filterOdd(numbers);
List<Integer> evenNumbers = filterEven(numbers);

and do something with these lists.

Disadvantage:

I do two loops over one collection.

Solution 2:

Create one method:

public void filter(List<Integer> numbers, List<Integer> oddNumbers, List<Integer> evenNumbers){
    for(Integer n : numbers){
        if(n % 2 != 0){
            oddNumbers.add(n);
        }else{
            evenNumbers.add(n);
        }
    }
}

and in the code I will call:

List<Integer> numbers = Arrays.asList(new Integer[] { 1,2,3,4,5,6,7,8,9 });
List<Integer> oddNumbers  = new ArrayList<Integer>();
List<Integer> evenNumbers = new ArrayList<Integer>();
filter(numbers, oddNumbers, evenNumbers);

Disadvantage:

I hear that assigning results for parameters is bad practice.

Which solution is better?


texts:
I came across a situation where I'd like to improve my code, but don't really have a clue about what I could do... It's for a game I'm making, I want to get a perimeter surrounding a unit, but I don't want tiles inside the perimeter. I'm pretty sure there is a better way to do this. (@x and @y are the unit's coordinates)

r = 4
radius = []
for x in @x-r..@x+r
  for y in @y-r..@y+r
    radius.push([x, y]) if $game_map.passable?(x, y)
  end
end
radius.delete_if {|a|
  radius.include?([a[0] + 1, a[1]]) &&
  radius.include?([a[0] - 1, a[1]]) &&
  radius.include?([a[0], a[1] + 1]) &&
  radius.include?([a[0], a[1] - 1])
}

There are some things that I simplified here to focus on the problem, like the local variable 'r' that would not be constantly 4. What matters is how to handle radius so it gives the same result without having to add the coordinates that will be removed.

Performance is important as this function is called frequently by many units.


texts: Merging two lists from dictionary. How to do this in a better way?

texts:
I have the following code:

print o
# {'actor_name': [u'Keanu Reeves', u'Laurence Fishburne', u'Carrie-Anne Moss', u'Hugo Weaving', u'Glor
# ia Foster', u'Joe Pantoliano', u'Marcus Chong', u'Julian Arahanga', u'Belinda McClory', u'Matt Doran
# '], 'played': [u'Neo (Thomas Anderson)', u'Morfeusz', u'Trinity', u'Agent Smith', u'Wyrocznia', u'Cy
# pher', u'Tank', u'Apoc', u'Switch', u'Mouse']}
li = list(o.itervalues())
for index, value in enumerate(li[0]):
    print [value, li[1][index]]
# [u'Keanu Reeves', u'Neo (Thomas Anderson)']
# [u'Laurence Fishburne', u'Morfeusz']
# [u'Carrie-Anne Moss', u'Trinity']
# [u'Hugo Weaving', u'Agent Smith']
# [u'Gloria Foster', u'Wyrocznia']
# [u'Joe Pantoliano', u'Cypher']
# [u'Marcus Chong', u'Tank']
# [u'Julian Arahanga', u'Apoc']
# [u'Belinda McClory', u'Switch']
# [u'Matt Doran', u'Mouse']

I'm curious how I could write this thing in a more Pythonic way without losing its readability.


texts:
This code solves the problem of FizzBuzz. Is it possible in any way to improve it?

main = main' 1 where
main' n = do
    (putStrLn . choose) (show n, "Fizz", "Buzz", "FizzBuzz", n)
    if n < 100 then main' (succ n) else putStrLn "End!"
    where
        choose (n0, n3, n5, n15, n)
            | mod n 3 == 0 && mod n 5 == 0 = n15
            | mod n 5 == 0 = n5
            | mod n 3 == 0 = n3
            | True = n0


texts: Implementation of the Minimum Stop Algorithm in Javascript

texts:
I started taking the Algorithm design class from Coursera. So into the third week they talk about Greedy algorithms and walks through a sample problem.

This is the Problem Statement that I could find which was close.

  Professor Midas drives an automobile from Newark to Reno along
  Interstate 80. His car’s gas tank, when full, holds enough gas to
  travel ‘d’ miles, and his map gives the distances between gas stations
  on his route. The professor wishes to make as few stops as possible
  along the way. The problem is to find an efficient method by which
  Professor Midas can determine at which gas stations he should stop,
  and prove that the strategy adopted yields an optimal solution.

The INPUT: an Array containing the Distance of each gas station from the Starting Point , and an integer that contains the maximum distance that the car can go with full tank of gas.

OUTPUT: The Minimum Number of Stops that the Car must make at each gas station to make a successful trip.

Here's the Code

   /*
    * Week 3 , Algorythm Design Course Coursera
    *
    * Design an algorythm that computes the minimum Number of Refills that a car must make to reach
    * the destination .
    *
    * INPUT :
    *       An Integer Array giving the distance of the GasStations from the Starting point ,
    *       An Integer that gives the maximum distance that the car can travel on a full refill
    *
    *  OUTPUT:
    *      The Minimum Number of refills , that the car must make.
    */

   var getLeastRefills = function(stationDist, maxDistance) {
     var curPos = 1;
     var minRefill = 0;
     var curDistance = maxDistance;
     var numRefillStations = (stationDist.length - 1);

     while (curPos <= (numRefillStations)) {
       for (; stationDist[curPos] <= curDistance; curPos += 1);

       if (curPos > numRefillStations) return minRefill;

       curPos -= 1;
       minRefill += 1;
       curDistance = stationDist[curPos] + maxDistance;
     }

     if (stationDist[curPos] < curDistance)
       minRefill += 1;

     return minRefill;
   };

    // Test Cases
   console.log(getLeastRefills([0, 200, 375, 550, 750, 950], 400));


texts: Returning a new object reference when mutation happens

texts:
i attempted to create a way (not sure if already implemented by someone) by which when i update a property of an object. it returns a new reference of the object with the new value.
i have a usecase in my mind for that purpose you can say i want to use it.

for some example reference you can consider redux reducer where you have to return a new reference everytime store is updated.

here is my small code which attempts to do it.

kindly ignore the setIn implementation its the first attempt.

function NewRef(jsObj) {
  Object.keys(jsObj).forEach((key) => {
    this[key] = jsObj[key];
  });
}

NewRef.prototype.set = function set(key, value) {
  let copyValue = null;
  if (Array.isArray(value)) copyValue = [...value];
  else if (typeof value === 'object') copyValue = { ...value };
  else copyValue = value;
  if (this[key] || ['object', 'boolean', 'number'].includes(typeof this[key])) {
    return Object.assign(Object.create(Object.getPrototypeOf(this)), {
      ...this,
      [key]: copyValue,
    });
  }
  throw new Error(`invalide key ${key} in object`);
};

NewRef.prototype.setIn = function set(nested, value) {
  let copyValue = null;
  if (Array.isArray(value)) copyValue = [...value];
  else if (typeof value === 'object') copyValue = { ...value };
  else copyValue = value;
  if (!Array.isArray(nested)) {
    throw new Error('setIn requires array of strings as first argument');
  } else {
    if (this[nested[0]] || ['object', 'boolean', 'number'].includes(typeof this[nested[0]])) {
      if (this[nested[0]][nested[1]] || ['object', 'boolean', 'number'].includes(typeof this[nested[0]][nested[1]])) {
        return Object.assign(Object.create(Object.getPrototypeOf(this)), {
          ...this,
          [nested[0]]: {
            ...this[nested[0]],
            [nested[1]]: copyValue,
          },
        });
      }
    }
    throw new Error(`invalid properties maybe ${nested.join(',')}`);
  }
};

NewRef.prototype.get = function get(key) {
  return this[key];
};

export default function NObject(jsObj) {
  const store = new NewRef(jsObj);
  return store;
}

with this piece of code i am able to do this.

const d1 = NObject({
   type: 'bool',
   data: {key:'value'}
   meta: {
      user: 'john doe'
   }
  })
const n1 = d1.set('type','mutated').set('data',[1,2])
const n2 = n1.setIn(['meta','user'],'foo bar');

both n1,n2 and d1 have different references. it works and is tested well.

please feel free to review it and give your suggestions. i am open to everything


texts:
I have the following code that takes input of Line arrays and attempts to find the intersections on the end points between them. The value _nConrerTolerance is an int of a value of around 10% of the average Line length to allow the lines to not need to be exactly on each other. Now obvisouly this code will be quite slow, especially as I have similar methods for top left, bottom left and bottom right corners. Can anyone suggest a way to improve this?

Also if you have any tips on how I can improve my coding style, if needed, that would be great.

private Point[] FindTopRightCorners(Line[] horizontalLines, Line[] verticalLines)
{
    List<Point> TopRightCorners = new List<Point>();

    Line[] laHorizontalLines = horizontalLines.OrderByDescending(l => l.EndPoint.X).ThenBy(l => l.EndPoint.Y).ToArray();
    Line[] laVerticalLines = verticalLines.OrderByDescending(l => l.StartPoint.X).ThenBy(l => l.StartPoint.Y).ToArray();

    foreach (Line verticalLine in laVerticalLines)
    {
        foreach (Line horizontalLine in laHorizontalLines)
        {
            if (verticalLine.StartPoint.X >= (horizontalLine.EndPoint.X - _nCornerTolerance) && verticalLine.StartPoint.X <= (horizontalLine.EndPoint.X + _nCornerTolerance))
            {
                if (horizontalLine.EndPoint.Y <= (verticalLine.StartPoint.Y + _nCornerTolerance) && horizontalLine.EndPoint.Y >= (verticalLine.StartPoint.Y - _nCornerTolerance))
                {
                    int nX = Math.Abs((verticalLine.StartPoint.X + horizontalLine.EndPoint.X) / 2);
                    int nY = Math.Abs((verticalLine.StartPoint.Y + horizontalLine.EndPoint.Y) / 2);

                    TopRightCorners.Add(new Point(nX, nY));
                    break;
                }
            }
        }
    }

    return TopRightCorners.Distinct().ToArray();
}

And the Line class is defined as follows:

public class Line
{
    public Point StartPoint { get; private set; }

    public Point EndPoint { get; private set; }

    public Line(Point startPoint, Point endPoint)
    {
        this.StartPoint = startPoint;
        this.EndPoint = endPoint;
    }
}


texts: Calculating calendar year for a student based on DOB

texts:
I've written this brief function for calculating which calendar year a student would be in Year 1 based on their DOB (date of birth). In 1998 there was a change in the DOB cut points for starting Year 1, hence the need for a function.

year1 <- function(x){
    if(x <= as.Date("1996-12-31")) {out <- as.numeric(format(x, "%Y")) +6}
    if(x >= as.Date("1997-07-01")) {ifelse(as.numeric(format(x, "%m")) >=07 , out <- as.numeric(format(as.Date(x), "%Y")) + 7, out <- as.numeric(format(x, "%Y")) + 6)}
    if(x >= as.Date("1997-01-01") & x <= as.Date("1997-06-30")) {out <- 2003}
    return(out)
}

An example of the results:

> year1(as.Date("1996-02-15"))
[1] 2002
> year1(as.Date("1999-02-15"))
[1] 2006

I plan to run it like this:

> test <- c(as.Date("1985-09-15"),as.Date("1999-02-15"),as.Date("2004-08-15"))
> sapply(test,year1)
[1] 1991 2006 2011

I have a lot of data to run this over, and the use of so many ifs and assigning the result to out just to write it seems pretty redundant, but I couldn't think of a better way to do it.


texts: Conversion Helper with support for enumerations and Nullable - The Remix

texts:
I recently wrote this code as a more versatile stand-in for Convert.ChangeType. I very recently posted an earlier version, for which I received some good feedback. I've incorporated that feedback and further refactored in an attempt to streamline the flow of the method.

    /// <summary>
    ///     Returns an object of type <typeparamref name="T"/> whose value is equivalent to that of the specified
    ///     object.
    /// </summary>
    /// <param name="value">
    ///     An object that implements <see cref="IConvertible"/> or is <see cref="Nullable{T}"/> where the underlying
    ///     type implements <see cref="IConvertible"/>.
    /// </param>
    /// Other XML comments removed for brevity's sake.
    internal static T ChangeType<T>(object value) {

        Type originalType = typeof(T);
        Type nullableType = Nullable.GetUnderlyingType(originalType);

        if (value != null && value.GetType() == originalType)
        {
            return (T)value;
        }

        if (value == null || DBNull.Value.Equals(value))
        {
            if (nullableType != null || !originalType.IsValueType)
            {
                return default(T);
            }

            throw new InvalidCastException(string.Format("Cannot convert null to {0} because it is a non-nullable value type.", originalType.Name));
        }

        Type conversionType = nullableType ?? originalType;

        if (!conversionType.IsEnum)
        {
            return (T)Convert.ChangeType(value, conversionType);
        }

        object result = (value is string) ? Enum.Parse(conversionType, (string)value) : Enum.ToObject(conversionType, value);

        if (!Enum.IsDefined(conversionType, result))
        {
            throw new ArgumentException("The specified value is not defined by the enumeration.", "value");
        }

        return (T)result;
    }


texts: Monty Hall simulation with any number of doors

texts:
After answering Monty hall python simulation I wondered what the outcome were to be if there were more than three doors, say four or seven. And so I decided to modify the problem slightly to adjust for this.

There are \$x\$ amount of doors. Behind one door is a car, the others are goats. You pick a door, and the host reveals a goat in a different door. You're then given the choice to change from the selected door to any door except the open door, or the already selected door.

And so I decided to find out how many times a person is likely to win if they always pick a random door when asked if they want to switch door. And so programmed the following:

import random

def monty_hall(amount, doors=3):
    if doors < 3:
        raise ValueError(f'doors must be greater than three, not {doors}')

    wins = 0
    for _ in range(amount):
        player_choice = random.randrange(doors)
        car_placement = random.randrange(doors)
        other_doors = set(range(doors)) - {player_choice, car_placement}

        shown_door = random.choice(list(other_doors))
        swap_doors = set(range(doors)) - {player_choice, shown_door}
        final_choice = random.choice(list(swap_doors))

        wins += final_choice == car_placement
    return wins

print(monty_hall(1000000, 3))
print(monty_hall(1000000, 4))
print(monty_hall(1000000, 5))

I then decided to optimize the above code, and came up with the following ways to do this:

Change player_choice to doors - 1. The first player choice doesn't have to be random.
Change other_doors and swap_doors to account for (1). Rather than removing an item that will always be in the set, remove it from the range and the second set. And so other_doors becomes: set(range(doors - 1)) - {car_placement}.
Remove player_choice as it's no longer used.
Change shown_door to always be the first door. However if the car is the first door, show the second. shown_door = car_placement == 0.
Remove other_doors as it's no longer used.
Change swap_doors to be a list, rather then a set with an item being removed. This requires the use of an if else to manually split the list if the car is in the first door. And so can become:

if car_placment == 0:
    swap_doors = [0] + list(range(2, doors - 1))
else:
    swap_doors = list(range(1, doors - 1))
final_choice = random.choice(swap_doors)

Rather than making my code WET, as I did in (6), we can instead move the car to the second door if it's in the first, and use the else whatever the case.
Finally we can merge all the code into a sum and a generator comprehension.

This resulted in the following code:

import random

def monty_hall(amount, doors=3):
    if doors < 3:
        raise ValueError(f'doors must be greater than three, not {doors}')

    rand = random.randrange
    return sum(
        max(rand(doors), 1) == rand(1, doors - 1)
        for _ in range(amount)
    )

print(monty_hall(1000000, 3))
print(monty_hall(1000000, 4))
print(monty_hall(1000000, 5))

Are there any improvements that I can make on either the optimized or non-optimized solutions? Also are there any issues with the optimized solution, as my method for optimization weren't exactly scientific. As far as I know it looks good.

Code is only runnable in Python 3.6+


texts: Balanced smileys check algorithm (part 4)

texts:
This is a follow-up for here, for bug fixes and applied advice.

  Problem

  Your friend John uses a lot of emoticons when you talk to him on
  Messenger. In addition to being a person who likes to express himself
  through emoticons, he hates unbalanced parenthesis so much that it
  makes him go :(

  Sometimes he puts emoticons within parentheses, and you find it hard
  to tell if a parenthesis really is a parenthesis or part of an
  emoticon.

  A message has balanced parentheses if it consists of one of the
  following:

  An empty string ""
  One or more of the following characters: 'a' to 'z', ' ' (a space) or ':' (a colon)
  An open parenthesis '(', followed by a message with balanced parentheses, followed by a close parenthesis ')'.
  A message with balanced parentheses followed by another message with balanced parentheses.
  A smiley face ":)" or a frowny face ":("
  Write a program that determines if there is a way to interpret his message while leaving the parentheses balanced.

I'm working on this balanced smileys checking algorithm, and my current solution is very naive, with just two rules:

Do a forward scan, at any point, the number of ) (close) should be less than or equal to the number of ( (open) + number of :( (frown)
Do a backward scan, at any point, the number of ( (open) should be less than or equal to the number of ) (close) and :) (smile)

I'm wondering if there are any bugs in my checking logic. Any advice on algorithm time complexity improvement or code style advice is highly appreciated as well.

def check_balance(source):
    pre = ''
    left = 0
    right = 0
    frown = 0 # :(
    smile = 0 # :)
    # forward scan
    for c in source:
        if c == ')':
            if pre == ':':
                smile += 1
            else:
                right += 1
                if right > left + frown:
                    return False
        elif c == '(':
            if pre == ':':
                frown += 1
            else:
                left += 1
        pre = c
    # reverse scan
    for i in range(len(source)-1, -1, -1):
        if source[i] == ')':
            if i > 0 and source[i-1] == ':':
                smile += 1
            else:
                right += 1
        elif source[i] == '(':
            if i > 0 and source[i-1] == ":":
                frown += 1
            else:
                left += 1
                if right + smile < left:
                    return False
    return True

def verify(test_input, expected_result):
    actual_result = check_balance(test_input)
    assert actual_result == expected_result, "{} expected {} failed".format(test_input, expected_result)
    print(test_input, actual_result)

if __name__ == "__main__":
    verify(':)(', False)
    verify(':()', True)
    verify('abc(b:)cdef(:()', True)
    verify('a)', False)
    verify(')(' , False)


texts: Angular 2 service to upload a batch job and poll for results

texts:
I have to write a web interface for one of my homebrew projects. Since I'm not familiar with HTML and CSS I've decided to take heavy duty framework such as Angular 2. This is my first experiment - I'm uploading a batch job to a remote servlet with POST request, get tracking ID and start polling this id with 100 ms interval. When remote batch completes its job, user of this service will be able to get result via Promise. Since I've written this without any systemic learning of any underlying technologies, I'm not sure if my approach is correct at all.

import { Injectable } from '@angular/core';
import {Http, Response} from '@angular/http';
import 'rxjs/add/operator/toPromise';
import 'rxjs/add/operator/map';

enum Status { SUCCESS, FAIL }

export class Upload {
  constructor(public readonly status: Status,
    public readonly message: string,
    public readonly timestamp: Date)
  {}
}

@Injectable()
export class EmeraldBackendStorageService {

  constructor(private http: Http) { }

  upload(fileToUpload: any): Promise<Upload> {
    let input = new FormData();
    input.append("file", fileToUpload);
    return this.http.post("/emerald/storage/submit-content", input)
      .map((response: Response) => JSON.parse(response.text()))
      .toPromise().then((serverAnswer: any) => {
        if (serverAnswer['success']) {
          return this.subscribeSubmitStatusTracker(serverAnswer['trackingId'] as number);
        } else {
          throw new Error('POST request failed');
        }
      }).catch((err) => {
        return new Upload(Status.FAIL, err, new Date())
      });
  }

  private subscribeSubmitStatusTracker(trackingId: number) : Promise<Upload>  {
    return this.http.get("/emerald/storage/submit-status/" + trackingId)
      .map((response: Response) => JSON.parse(response.text()))
      .toPromise().then((serverAnswer: any) => {
        if (serverAnswer['status'] == 'PENDING') {
          return new Promise<Upload>((resolve) => {
            setTimeout(() => resolve(this.subscribeSubmitStatusTracker(trackingId)), 5000);
          });
        } else if (serverAnswer['status'] == 'SUCCESS') {
          let ts = serverAnswer['timestamp'] as number;
          return new Upload(Status.SUCCESS, null, new Date(ts));
        } else {
          throw new Error('Server can\'t process uploaded file');
        }
      }).catch((err) => {
        return new Upload(Status.FAIL, err, new Date())
      })
  }
}


texts:
This is an example of the Java Swing application I've wrote. I'm trying to follow the first Effective Java items. I wrote some classes similar so I've posted only this class for the review.

package com.ELSE.view;

import java.awt.BorderLayout;
import java.awt.Color;

import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;

class Bar {

    private static JPanel parent, left, right;

    private Bar() {
        parent = new JPanel();
        parent.setBackground(Color.decode("#cbc4a7"));
        parent.setBorder(new EmptyBorder(10, 10, 10, 10));
        parent.setLayout(new BorderLayout());

        left = JInvisiblePanel.getInstance(parent);
        right = JInvisiblePanel.getInstance(parent);

        parent.add(left, BorderLayout.WEST);
        parent.add(right, BorderLayout.EAST);
    }

    static Bar getInstance() {
        return new Bar();
    }

    public JPanel getParent() {
        return parent;
    }

    public JPanel getLeft() {
        return left;
    }

    public JPanel getRight() {
        return right;
    }

}

I add the JInvisiblePanel just for showing (no need to review) as it's similar to Bar.java:

package com.ELSE.view;

import java.awt.Component;

import javax.swing.JPanel;

class JInvisiblePanel {

  private JInvisiblePanel() {
      throw new AssertionError();
  }

  public static JPanel getInstance(Component component) {
      JPanel panel = new JPanel();
      panel.setBackground(component.getBackground());
      return panel;
  }

}

And some code that uses the class as example (neither to review):

Bar panel = Bar.getInstance();

JButton settings = new Button(MenuBar.class.getResource("/settings.png"));
panel.getLeft().add(settings);
SearchBar searchBar = new SearchBar(); panel.getRight().add(searchBar);


texts:
I'm trying the write a threadpool that can safely be added inside a signal handler or in code forked by multithreaded code. Are there any corner cases that would cause this code to fail? What could be done to improve this code?

#include <pthread.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <semaphore.h>
#include <stdatomic.h>
#include <unistd.h>
#define MAX_WORKERS 16

struct threadpool
{
    _Atomic(int) idle;
    void *(*func)(void*);
    sem_t sem;
    void * arg;
    int id;
    pthread_t thread;
};

struct threadpool threads[MAX_WORKERS] = {0};

void *Worker(void *arg)
{
    int * t = (int*)arg;
x:
    sem_wait(&threads[*t].sem);
    __sync_synchronize();
    threads[*t].func(threads[*t].arg);
    threads[*t].idle = false;
    goto x;
}

bool ThreadPoolNew()
{
    for (int i = 0; i < MAX_WORKERS; i++) {
        threads[i].id = i;
        sem_init(&threads[i].sem, 0, 0);
        pthread_create(&threads[i].thread, NULL, Worker, &threads[i].id);
    }
    return true;
}

bool ThreadPoolAddTask(void *(*entry)(void*), void * arg, bool retry)
{
    _Atomic(bool) found = false;
x:
    for (size_t i = 0; i < MAX_WORKERS; i++) {
        if (__sync_val_compare_and_swap(&threads[i].idle, 0, 1) == 0) {
            threads[i].func = entry;
            threads[i].arg = arg;
            __sync_synchronize();
            sem_post(&threads[threads[i].id].sem);
            found = true;
            break;
        }
    }

    if (found == false && retry == true) {
        goto x;
    }

    return found;
}

void * t1(void *a)
{
    int i = 0;
    while (true) {
        i += 2;
        printf("%i\n", i);
        sleep(5);
    }
}

void * t2(void *a)
{
    int i = 0;
    while (true) {
        i += 3;
        printf("%i\n", i);
        sleep(5);
    }
}

//TESTER CODE
//gcc -pthread list.c

int main(void)
{
    ThreadPoolNew();
    ThreadPoolAddTask(t2, NULL, 1);
    ThreadPoolAddTask(t1, NULL, 1);
    sleep(60);
}


texts: Zip Code to City, State for registration form

texts:
Took me a couple of days (in between working on other projects) to get the code working, but now that I do have it working I would like to know if there is a way that I could make it work better, or clean up my act JavaScript/jQuery surrounding my JSON utilization skills.

I am using ASP.NET if that means anything to the JavaScript.

Here is the code, ASPX pertinent to the JavaScript only:

        <asp:Label runat="server" ID="lblCity" Text="City:"></asp:Label>

        <asp:TextBox runat="server" ID="txtCity" CssClass="textbox" Enabled="False" BackColor="#CCCCCC" ></asp:TextBox>

        <asp:Label runat="server" ID="lblState" Text="State:"></asp:Label>

        <asp:TextBox runat="server" ID="txtState" CssClass="textbox" Enabled="False" BackColor="#CCCCCC"></asp:TextBox>

        <asp:Label runat="server" ID="lblZip" Text="Zip Code:"></asp:Label>

        <asp:TextBox runat="server" ID="txtZip" CssClass="textbox" TabIndex="6"></asp:TextBox>

...

I got the idea from SO and various places on the net, but I have hacked the code into this usable piece of script, but is it good code?


texts:
Reading Jeff Atwood's "Why Can't Programmers.. Program?" led me to think that almost all of the solutions would not be something I would want in my own code-base.  The Fizz Buzz program specification from Imran is here which says:

  Write a program that prints the numbers from 1 to 100. But for
  multiples of three print “Fizz” instead of the number and for the
  multiples of five print “Buzz”. For numbers which are multiples of
  both three and five print “FizzBuzz”.

Implementing my solution differently than almost everyone else - I would like to put my solution up for review (as everyone doing it differently must think that my solution is not the best).

Could you please review my approach.  Is it overkill to suggest such a solution?  Under what conditions would you split it into a Model and Views?  Are there any issues with the code?

For a start, I don't think a language agnostic definition of the problem can fully describe the best solution.  In an interview I would find out by asking questions what was expected of the Fizz Bang code.  Probable questions and my assumed answers are:

Whether any changes were likely to be made in the future? (such as
new words, different rules other than 'Fizz' on multiples of 3 and 'Bang' on 5).    Yes
Whether the existing code-base was procedural or OO?    OO

I have decided to split the model and view components so that different output formats could be easily implemented.

Model:

class Model_Fizz_Buzz
{
   private $fizzBuzz;

   /** Construct the Fizz Buzz game model.
    *  @param fizzBuzz \Array The list of period => text for the game.  If the
    *  number is a multiple of the period then the text should be used.
    */
   public function __construct(Array $fizzBuzz=array())
   {
      $this->fizzBuzz = $fizzBuzz;
   }

   /** Get the Fizz_Buzz game numbers.
    *  @param start \int The number to start from (defaults to 1).
    *  @param end   \int The number to finish with (defaults to 100).
    */
   public function get($start=1, $end=100)
   {
      $data = array();

      for ($num = $start; $num <= $end; $num++)
      {
         $data[$num] = '';

         foreach ($this->fizzBuzz as $period => $text)
         {
            if ($num % $period === 0)
            {
               $data[$num] .= $text;
            }
         }

         if (empty($data[$num]))
         {
            $data[$num] = $num;
         }
      }

      return $data;
   }
}

View:

class View_Text_Lines
{
   /** Write the data values separated by newlines.
    *  @param data \array The data to be written.
    */
   public function write(Array $data)
   {
      foreach ($data as $val)
      {
         echo $val . PHP_EOL;
      }
   }
}

Usage would be:

$fizzView = new View_Text_Lines();

echo PHP_EOL . '-- Standard Fizz Buzz' . PHP_EOL;
$fizzBuzz = new Model_Fizz_Buzz(array(3 => 'Fizz',
                                      5 => 'Buzz'));
$fizzView->write($fizzBuzz->get());

echo PHP_EOL . '-- Three Buzz Bang' . PHP_EOL;
$threeBuzz = new Model_Fizz_Buzz(array(3 => 'Three',
                                       4 => 'Buzz',
                                       5 => 'Bang'));
$fizzView->write($threeBuzz->get(30, 61));


texts:
I have a program that prints the star pattern.

Starr Pattern is:

          *
          *
          *
          *
  * * * * * * * * *
          *
          *
          *
          *

My code is:

$n=5;

for($i=0; $i<$n; $i++){

  for($k=$n-$i; $k>0; $k--){
      echo ' '.' ';
  }
  for($j=0; $j< ($tot = $i+1); $j++){

      if($i==$j && $tot<$n){
        echo '* ';
      }else{
          if($tot<$n){
            echo ' '.' ';
          }else{
             echo '* ';
          }
      }

  }

  if($i == ($n-1)){
      for($l=$n-1; $l>0;$l--){
         echo '* ';
       }
     }
  echo '
';

}

for($i=0;$i<$n;$i++){
  for($k=$n-$i; $k>0; $k--){
      echo ' '.' ';
  }

  for($j=0; $j< ($tot = $i+1); $j++){

      if($i==$j && $tot<$n){
        echo '* ';
            }else{
              echo ' '.' ';
            }
    }
  echo '
';
}

My question is that how can I calculate the complexity of this code?

And also Is there a good way to reduce loops?


texts:
This is an accounting program (and my first attempt at a web app of any kind) where users need to get and retrieve objects from different JSON URLs and at different levels. Rails is used for the back.

I'd like to know if the following process is the best to use:

User clicks button to toggle some boolean value
Local JS boolean value is updated
PUT request is sent to JSON URL
Success or failure response is sent to browser

On success, "all changes saved" is sent to the view
On failure, a get request is sent to the SAME URL as the put request
On success of that get request, the local variable is updated

I also had the idea that I could use one function (putValue in the code below) for all put requests if I make the local javascript object use the same structure as the JSON I am retrieving. Is this a good idea?

After this, I will need to do the same thing for text inputs which I want to write to the server after each keystroke. Can I go about that in the same way as the code above?

This gives the current users account data:

www.example.com/accData.json:
{"deleteWarning":true,"displayHiddenFields":true,"groups":[{"id":2,"text":"My Company"}]}

A user has many microposts, which each have one template:

www.example.com/microposts/9/template.json
{"id":9,"name":"template","templateIndex":0,"shared":true,"micropost_id":9}

Users can get and put to these URLs.

A function in an Angular factory is used to put to these addresses.

//Put a single objValue into the parentKey  SQL table
var putValue = function(objValue, objKey, parentKey) {

  var putURL = '';
  var obj = {};

  //create the obj to be put
  var accObj = {};

  //tell the notification variable what's happening
  viewed.current.status = "saving...";

  //update local variable and define save location
  if (typeof parentKey === 'string') {
    putURL = '/microposts/' + viewed.sig.id + '/' + parentKey + '.json';
    viewed.sig[parentKey][objKey] = objValue;
    obj[parentKey] = accObj;
  } else {
    putURL = '/accData.json';
    viewed.accData[objKey] = objValue;
    obj = {acc_datum:accObj};
  }

  accObj[objKey] = objValue;

  //tell the console what's happening
  console.log("object sent to acc_datum is:");
  console.dir(obj);

  //do the put request
  return $http.put(putURL, obj).then(
    //on success do nothing
    function(response){},
    //on failure, get the data again
    function(response){

      //CHANGE BELOW - need this to update the correct local
      //variable not just viewed.accData

      //getData from putURL and put it into the local js object
      viewed.accData = getData(putURL, 'accData');
    }
  );
};


texts: XOR linked list implementation - Follow Up

texts:
This question is a follow up question to the XOR linked list implementation.
I am posting a new code here with taking into consideration the suggestions of Toby Speight and Deduplicator. Please advise how the code efficiency can be improved.
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

struct StNode {
    int value;
    uintptr_t both;
};
typedef struct StNode StHexNode;

StHexNode *add(StHexNode *lastNode, int value)
{
    StHexNode *newNode = malloc(sizeof(struct StNode));
    newNode->value = value;

    //latest node's [both]=pointer value pointing previous node:
    newNode->both = (uintptr_t)lastNode;
    //calculating previous node [both]:
    lastNode->both = (uintptr_t)newNode ^ lastNode->both;
    return newNode;
}

StHexNode *get(StHexNode *headNode, unsigned int index)
{

    StHexNode *prevNode;
    StHexNode *currNode;
    uintptr_t tmp;

    //cur=1, prev=0
    currNode = (struct StNode *) ((headNode->both) ^ 0);
    prevNode = headNode;

    for(int i=2; i<=index; i++)
    {
        tmp = (uintptr_t)prevNode;
        prevNode = currNode;
        currNode = (struct StNode *) (currNode->both ^ tmp);
    }
    return currNode;
}

int free_list(StHexNode *headNode)
{
    StHexNode *prevNode;
    StHexNode *currNode;
    uintptr_t tmp;
    int ctr=0;

    //case: there is a only head node in the list
    if(headNode->both == 0)
    {
        free(headNode);
        return ++ctr;
    }

    //prev=head, curr=second_node
    currNode = (struct StNode *) ((headNode->both) ^ 0);
    prevNode = headNode;

    while(currNode->both != (uintptr_t)prevNode)
    {
        tmp = (uintptr_t)prevNode;
        free(prevNode);
        ctr++;
        prevNode = currNode;
        currNode = (struct StNode *) (currNode->both ^ tmp);
    }
    //last node
    free(currNode);
    ctr++;

    return ctr;
}

int main(void)
{
    unsigned int i;

    //I named first node as headNode, and last node as tailNode
    //create head node with both=0 since there is no previous node to it
    StHexNode *headNode = malloc(sizeof(struct StNode));
    StHexNode *tailNode = headNode; //last node pointer in the list

    //lets add 100 nodes after head
    //special handling of both value at head node
    for(headNode->both = 0, i=100; i<200; i++)
    {
        tailNode = add(tailNode, i);
        //printf("last node value:%d\n", tailNode->value);
    }

     //get index=50 node value
     StHexNode *iNode = get(headNode, 50);
     printf( "result: %d\n",  iNode->value);

     //free memory
     printf("we released %d list\n", free_list(headNode));

    }


texts: Data set generation with Python and Matplotlib

texts:
I want to use Python and Matplotlib to create a data set of images. I want to do this by transforming the plot to a numpy matrix. At the moment it takes about 0.1 second to generate 100 images of size 50x50 pixels:

Question: How can I speed up things a lot?

This is my code:

import matplotlib.pyplot as plt
import numpy as np
import time
import cv2

fig = plt.figure(frameon=False)
ax = fig.add_axes([0., 0., 1., 1.])
fig.set_size_inches((0.5,0.5))
fig_size = fig.canvas.get_width_height() + (3,)
points, = ax.plot([],[])
ax.set_xlim(0.,1.)
ax.set_ylim(0.,1.)
ax.set_axis_off()
ax.set_frame_on(False)
ax.grid(False)

def plot2mat():
    data = np.random.rand(20,2)
    points.set_xdata(data[:,0])
    points.set_ydata(data[:,1])
    fig.canvas.draw()
    fig.canvas.flush_events()
    M = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep="")
    M = M.reshape(fig_size)
    M = cv2.cvtColor(M, cv2.COLOR_BGR2GRAY)
    return M

I = []
t0 = time.time()
runs = 1000
for k in range(runs):
    I.append(plot2mat())
print(time.time()-t0)

plt.close(fig)

for k in range(100):
    plt.subplot(10,10,k+1)
    plt.imshow(I[k])
    plt.axis("off")
plt.savefig("plot.png", dpi=400)


texts: Search Android contacts more efficiently

texts:
Is there is better way to do that more efficiently?

onCreate():

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    layout = new Layout();
    Event event = new Event(layout);
}

Layout and Event:

class Layout
{
    public Layout()
    {
         txtName = (EditText)findViewById(R.id.txtName);
         btnSerch = (Button)findViewById(R.id.btnSerch);
        group1 = (RadioGroup)findViewById(R.id.group1);
    }
    RadioGroup group1;
    EditText txtName;
    Button btnSerch;
}

class Event
{
    public Event(Layout layout)
    {
        layout.btnSerch.setOnClickListener(new start_Serch());
    }
}

class start_Serch implements OnClickListener
{
    @Override
    public void onClick(View view)
    {
        Serch(view, layout);
    }
    Layout layout;
}

Main goal: (the main commands of the application)

void Serch(View v, Layout layout)
{
    Uri Contacts = android.provider.ContactsContract.Contacts.CONTENT_URI;

    Cursor C = getContentResolver().query(Contacts, null, null, null, null);

    if(C != null)
    {
        if(C.moveToFirst())
        {
            do
            {
                String display_ContactsName = getValue(C, android.provider.ContactsContract.Contacts.DISPLAY_NAME);

                if (Check(display_ContactsName, C) == true)
                {
                    break;
                }

            }while (C.moveToNext());
        }
    }
}

getValue() and Check():

private String getValue(Cursor cursor, String name)
{
    return cursor.getString(cursor.getColumnIndex(name));
}
private boolean Check(String Name, Cursor C)
{
    boolean Found = false;
    int id = layout.group1.getCheckedRadioButtonId();
    switch (id)
    {
        case -1:
            break;
        case R.id.fullName:
            if (layout.txtName.getText().toString().equals(Name))
            {
                AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);

                alert.setTitle("Hey This Contact Is in the LIST!!! yay you are the best lasy man EVER SO G***");

                alert.setMessage("The contact "+Name+" was found in this phone... oh ya");

                alert.setPositiveButton("ok",new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialogInterface, int i)
                    {
                    }
                });
                alert.show();
                Found = true;
            }
            break;
        case R.id.Contane:
            if ( Name.toLowerCase().contains ( layout.txtName.getText ().toString ().toLowerCase()))
            {
                AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);

                alert.setTitle("this is the first result for the name that you typed");

                alert.setMessage("The contact "+Name+" was found in this phone... oh ya");

                alert.setPositiveButton("ok",new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialogInterface, int i)
                    {
                    }
                });
                alert.show();
                Found = true;
                break;
            }
    }

     if (C.isLast() == true&&layout.txtName.getText().toString().equals(Name) == false&& Name.toLowerCase().contains ( layout.txtName.getText ().toString ().toLowerCase()) == false)
    {
        AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);

        alert.setTitle("Hey This Contact Is NOT in the LIST!!!");

        alert.setMessage("The contact/part of "+layout.txtName.getText().toString()+" was not found in this phone...");

        alert.setPositiveButton("ok",new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialogInterface, int i)
            {
            }
        });
        alert.show();
    }
    return Found;
}


texts:
Say, there is a class with some methods, that have try catch blocks. I need to accumulate messages from all inner exceptions of generated exception and use throw new Exception(exceptionMessages).
I came up with two possible solutions:

Create a private method, concatenate inner exception messages, return a string and raise an exception in a caller method. (SomeMethod1 below);
Create a private method, concatenate inner exception messages and raise exception inside it. (SomeMethod2 below);

Code snippet:

class SomeClass
{
    private void _raiseException(Exception ex)
    {
        var exceptionMessages = new StringBuilder();
        do
        {
            exceptionMessages.Append(ex.Message);
            ex = ex.InnerException;
        }
        while (ex != null);
        throw new Exception(exceptionMessages.ToString());
    }

    private string _getInnerExceptions(Exception ex)
    {
        var exceptionMessages = new StringBuilder();
        do
        {
            exceptionMessages.Append(ex.Message);
            ex = ex.InnerException;
        }
        while (ex != null);
        return exceptionMessages.ToString();
    }

    public void SomeMethod1()
    {
        try
        {
            //some code to try
        }
        catch (Exception e)
        {
            throw new Exception(this._getInnerExceptions(e));
        }
    }

    public void SomeMethod2()
    {
        try
        {
            //some code to try
        }
        catch (Exception e)
        {
            this._raiseException(e);
        }
    }
}

Which one of them would be better, or is there another way of doing it, or maybe this approach is not good at all?


texts: Custom exit with only some exceptions in Python

texts:
I want to define an exit code for some exceptions and some exceptions only. I want that the only input is that dictionary with the definition.

import sys

exit_codes = { ValueError:'10', KeyError:'25' }

try:
    raise Some_Exception
except Exception as exit_err:
    if any([isinstance(exit_err, exceptions) for exceptions in exit_codes.keys()]):
        exit_code = int(exit_codes[type(exit_err)])
        sys.exit(exit_code)
    else:
        raise exit_err

except Exception is the only part that troubles me, however this seems approach seems safe.


texts:
I've recently solved the LeetCode's "Same Tree" problem:

  Given two binary trees, write a function to check if they are equal or
  not.

  Two binary trees are considered equal if they are structurally
  identical and the nodes have the same value.

The problem itself and the idea is simple: traverse the tree in a way that preserves the structure - returning None for non-existing left or right sub-tree.

Here is the complete working code:

from itertools import izip

def traverse(node):
    if not node:
        yield None
    else:
        yield node.val
        if node.left:
            for val in traverse(node.left):
                yield val
        else:
            yield None
        if node.right:
            for val in traverse(node.right):
                yield val
        else:
            yield None

class Solution(object):
    def isSameTree(self, p, q):
        """
        :type p: TreeNode
        :type q: TreeNode
        :rtype: bool
        """
        try:
            for node_p, node_q in izip(traverse(p), traverse(q)):
                if node_p != node_q:
                    return False
        except StopIteration:
            return True

        return True

It was accepted by the Online Judge, but the code looks a bit lengthy. Is there a way to further simplify or improve the solution? Also, is it the most optimal way to solve the problem?

Note that I cannot use yield from since the OJ is Python 2.7 only.

FYI, here is what LeetCode uses as a Tree/Node:

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


texts: Check if a list of ints is pairwise sorted

texts:
In class we created our own ArrayList class; the code I wrote is meant to interact with the ArrayIntList class. I'm looking for general feedback to help with the next time I write code. I'm also wondering if it's "safe" to change the value of the size variable in my method (size represents the current size of the ArrayIntList.)

  Write a method isPairwiseSorted that returns whether or not a list of integers is pairwise sorted (true if it is, false otherwise). A list is considered pairwise sorted if each successive pair of numbers is in sorted (non-decreasing) order. For example, if a variable called list stores the following sequence of values:

[3, 8, 2, 5, 19, 24, -3, 0, 4, 4, 8, 205, 42]

  Then the call of list.isPairwiseSorted() should return true because the successive pairs of this list are all sorted: (3, 8), (2, 5), (19, 24), (-3, 0), (4, 4), (8, 205). Notice that the extra value 42 at the end had no effect on the result because it is not part of a pair. If the list had instead stored the following:

[1, 9, 3, 17, 4, 28, -5, -3, 0, 42, 308, 409, 19, 17, 2, 4]

  Then the method should return false because the pair (19, 17) is not in sorted order. If a list is so short that it has no pairs, then it is considered to be pairwise sorted. If a list is of odd length, the final element should be ignored since it has no pair. In other words, if the rest of the list is pairwise sorted until that last unpaired element, your method should return true.

  Assume you are adding to the ArrayIntList class with following fields:

public class ArrayIntList {
    private int[] elementData;
    private int size;

   // your code goes here
}

And here's my code:

public boolean isPairwiseSorted() {
    if (size <= 1) {
        // Pairwise sorted for lists smaller than two elements
        return true;
    }
    boolean reIncrementSize = false;
    if (size % 2 != 0) {
        reIncrementSize = true;
        size--;
    }
    for(int i = 0; i < size; i+=2) {
        // Pairwise sorted if elements are in increasing order
        if (elementData[i] > elementData[i + 1]) {
            return false;
        }
    }
    if (reIncrementSize) {
        size++;
    }
    return true;
}


texts:
I'm solving a knapsack problem here. It works, but gives time limit exceeds on a certain test case.

Problem statement
There are N
items, numbered 1,2,…,N. For each i (1≤i≤N), Item i has a weight of wi and a value of vi
Taro has decided to choose some of the N
items and carry them home in a knapsack. The capacity of the knapsack is W, which means that the sum of the weights of items taken must be at most W
Find the maximum possible sum of the values of items that Taro takes home.

The input is in the following form:
N W
w1 v1
w2 v2
:
wN vN

N: Number of items.
W: Max weight I can have.
wi: ith weight.
vi: ith value.
Here is my solution to it:
using System;
using System.Collections.Generic;

public static class Solution
{
  // Both s_weights and s_values will have the same length.
  private static int[] s_weights; // array holding the weights of the items.
  private static int[] s_values; // array holding the values of the items.
  private static Dictionary<(int, int), long> s_memo; // memoization dictionary.

  // NOTE: I cannot use an array instead of a dictionary here, cause it
  // will be a very large 2d array and will give OutOfMemoryException.

  public static void Main()
  {
    // Read the first line, which contains number of items and max weight.
    string[] nw = Console.ReadLine().Split(' ');
    // Parse n.
    int n = int.Parse(nw[0]);
    // Parse the max weight.
    int maxWeight = int.Parse(nw[1]);

    s_weights = new int[n];
    s_values = new int[n];
    // arbitrary high capacity dictionary to avoid resizing which is O(n).
    s_memo = new Dictionary<(int, int), long>(10000000);

    // Read each line from the input.
    for (int i = 0; i < n; i++)
    {
      string[] wv = Console.ReadLine().Split(' ');
      s_weights[i] = int.Parse(wv[0]);
      s_values[i] = int.Parse(wv[1]);
    }
    // Start the recursion with the maximum weight and all the items.
    Console.WriteLine(Solve(maxWeight, n));
  }

  private static long Solve(int weightLeft, int numberOfItemsToConsider)
  {
    // simple base case.
    if (weightLeft == 0 || numberOfItemsToConsider == 0) return 0;

    // If already calculated, get it from the dictionary.
    if (s_memo.TryGetValue((weightLeft, numberOfItemsToConsider), out var cachedValue))
    {
      return cachedValue;
    }

    // Recursive call calculating the solution if we don't take the current item.
    long dontTakeCurrent = Solve(weightLeft, numberOfItemsToConsider - 1);
    long result;

    // Can we take the current item? If yes, calculate the solution.
    if (weightLeft >= s_weights[numberOfItemsToConsider - 1])
    {
      long takeCurrent = s_values[numberOfItemsToConsider - 1] + Solve(weightLeft - s_weights[numberOfItemsToConsider - 1], numberOfItemsToConsider - 1);
      // Maximize the value between the two cases, taking or not taking the item.
      result = Math.Max(takeCurrent, dontTakeCurrent);
      // Add the result to the memo dictionary.
      s_memo.Add((weightLeft, numberOfItemsToConsider), result);
      return result;
    }
    // Here, we don't have another choice other than not taking the item.
    result = dontTakeCurrent;
    s_memo.Add((weightLeft, numberOfItemsToConsider), result);
    return result;
  }
}
```


texts: Comparing two simple distance calculating algorithms

texts:
Is the single method printMaxDistance_a or the two methods printMaxDistance_b AND printMaxDistance_c better or respectively "more readable"? Thanks.

public static void printMaxDistance_a(String s) {
    int first = 0;
    int second = 0;
    int max = 0;
    for (int i = 0; i < s.length(); i++) {
        for (int j = i + 1; j < s.length(); j++) {
            if (s.charAt(i) == s.charAt(j)) {
                if ((j - i) > max) {
                    first = i;
                    second = j;
                    max = j - i;
                }
                break;
            }
        }
    }
    System.out.println(first + " " + second + " " + max);
}

public static void printMaxDistance_b(String s) {
    int first = 0;
    int second = 0;
    int max = 0;
    for (int i = 0; i < s.length(); i++) {
        int cur = printMaxDistance_c(s, s.charAt(i), i + 1);
        if (cur > max) {
            first = i;
            second = i + cur;
            max = cur;
        }
    }
    System.out.println(first + " " + second + " " + max);
}

public static int printMaxDistance_c(String s, char c, int j) {
    for (int i = j; i < s.length(); i++) {
        if (c == s.charAt(i)) {
            return i - (j - 1);
        }
    }
    return 0;
}

@SuppressWarnings("resource")
public static void main(String[] args) {
    String s = new Scanner(System.in).nextLine();
    printMaxDistance_a(s);
    printMaxDistance_b(s);
}


texts:
I've got this own made grid system made in SASS:

@import "../mixins/cross-browser-elements/box";

$columns: 12 !default;
$gutter-width-px: 20px !default;

@function calculate-column-width($index) {
  @return percentage($index / $columns);
}

.row {
  overflow: hidden;
  max-width: 100%;

  .column {
    float: left;
    min-height: 1px;
    padding-left: ($gutter-width-px / 2);
    padding-right: ($gutter-width-px / 2);
    @include box-sizing(border-box);

    &:first-child {
      padding-left: 0;
    }

    &:last-child {
      padding-right: 0;
    }

    @for $index from 1 through $columns {
      &.size-#{$index} {
        width: calculate-column-width($index);
      }
    }
  }

}

It looks pretty good in my opinion, it works and has a working padding on each element.

The thing I worry about is when I want to make it responsive. Do I have to go in my stylesheet and give every column a width of 100% when it's below a certain screen size with the @media selector?

My HTML markup looks like this:

column-size-10

column-size-2

column-size-1

column-size-1

column-size-1

column-size-1

column-size-1

column-size-1

column-size-1

column-size-1

column-size-1

column-size-1

column-size-1

column-size-1


texts: CRC function duplication – differ only in pointer vs iterator signature

texts:
This is a CRC function generated by pyCRC and changed by me:

static inline crc_t crc_update(crc_t          crc,
                               char const *   data,
                               long long      data_len)
{
    while (data_len--)
    {
        crc = (crc_table[(crc ^ *data) & 0xff] ^ (crc >> 8));
        ++data;
    }
    return crc;
}

I made an iterator version of it:

static inline crc_t crc_update(crc_t                          crc,
                               std::istreambuf_iterator<char> data,
                               long long                      data_len)
{
   /* body identical to the above */
}

Is there a way I can avoid duplication? (The main purpose of the code is to be fast.)


texts: How to refactor the boolean logic of this F# function?

texts:
I have a list of path I want to filter out. I want to keep only paths matching a specific pattern and remove all paths matching another specific pattern.
To achieve this I pattern matched on each pattern. Here is the code:
let stringToSpan (s: string) =
    System.ReadOnlySpan<char>(s.ToCharArray())

let matchWildcard pattern text =
    System.IO.Enumeration.FileSystemName.MatchesSimpleExpression(stringToSpan pattern, stringToSpan text)

let filterByPattern (includePattern: string Option) (excludePattern: string Option) (paths: string seq) :string seq =
    paths
    |> Seq.filter
        (fun path ->
            let shouldKeep =
                match includePattern with
                | Some pattern -> matchWildcard pattern path
                | None -> true

            if not shouldKeep then
                false
            else
                match excludePattern with
                | Some pattern -> matchWildcard pattern path |> not
                | None -> true)

You can try this snippet with:
seq {"test"; "foo/bar"; "foo/toto"}
|> filterByPattern (Some "foo/*") (Some "*toto*")
|> printfn "%A"

// output: foo/bar

If it matters, this snippet is used inside a dotnet tool to clone multiple git repositories. You can find this tool on GitHub.
I think that we could improve this snippet a bit. Can we?


texts:
class Redirect {

    public function __construct() {
    }

    public function to($key, $page) {
        if(isset($page) && !empty($page)) {
            header('Location: ?' . $key . '=' . $page);
            exit();
        }
    }

}

With this class I can use this:

$foo->redirect('page', 'home');

instead of this:

header('Location: ?page=home);


texts: Efficiency and correctness of my randomized selection algorithm

texts:
Instead of picking a random pivot I'm shuffling the array beforehand. Does it count as randomization and is it efficient to shuffle or pick a random pivot and is my implementation pythonic?

Problem

Algorithm

from random import shuffle

def _partition(arr, lo, hi, pivot):
    p = arr[pivot]
    arr[hi - 1], arr[pivot] = arr[pivot], arr[hi - 1]
    i = lo - 1
    for j in xrange(lo, hi):
        if arr[j] <= p:
            i += 1
            arr[i], arr[j] = arr[j], arr[i]
    return i

def select(arr, lo, hi, spos):
    assert lo <= spos < hi
    shuffle(arr)  # here's your randomization.
    while True:
        pos = _partition(arr, lo, hi, lo)
        if pos == spos:
            return arr[pos]
        elif pos < spos:
            lo = pos + 1
        else:
            hi = pos


texts:
I have written a simple snippet of code that implements a function that returns a list of primes up to a certain integer n. Assuming that this function could be called several times in the script for different values of n, I wanted to make it as "lazy" as possible—that is, able to reuse previously-calculated variables.

Here is the code (assume isPrime(n) returns True if n is prime and False otherwise):

primes = []

def pi(n):
    global primes

    if len(primes) == 0:
        # Full
        for i in range(2, n + 1):
            if isPrime(i):
                primes.append(i)
        return primes

    elif n <= primes[-1]:
        # Lazy
        return list(filter(lambda m: m <= n, primes))

    else:
        # Semi-lazy
        for i in range(primes[-1] + 1, n + 1):
            if isPrime(i):
                primes.append(i)
        return primes

The problem is, as you may have spotted, that I'm using a global variable (primes) to store the list of primes, and later modifying it inside the pi function. I've heard that relying on mutable global variables is a bad design choice. What are better ways to implement this?

This question should actually be generalized to the following: what's the best design pattern to implement a 'lazy' function (i.e. a function that reuses previously calculated values)?


texts: Dijkstra algorithm implementation with adjacency list

texts:
I've implemented the Dijkstra Algorithm to obtain the minimum paths between a source node and every other.

#include <bits/stdc++.h>

typedef std::vector<std::list<int>> AdjacencyList;
typedef std::vector<std::vector<int>> Weights;

std::vector<int> dijkstra(AdjacencyList &adj, Weights weights, int src) {
    int n = adj.size();

    std::vector<int> prev(n, -1);
    std::vector<int> dist (n, INT_MAX);
    std::vector<bool> visited(n, false);

    auto comp = [&dist](const int& lhs, const int& rhs) -> bool { return dist[lhs] > dist[rhs]; };
    std::priority_queue<int, std::vector<int>, decltype(comp)> candidates(comp);

    candidates.push(src);
    dist[src] = 0;
    for (int j = 0; j < n - 1; ++j) {
        int next = candidates.top();
        candidates.pop();
        visited[next] = true;
        for(std::list<int>::const_iterator it = adj[next].begin(); it != adj[next].end(); it++) {
            int neighbor = *it;
            if (!visited[neighbor] && (dist[next] + weights[next][neighbor] < dist[neighbor])) {
                dist[neighbor] = dist[next] + weights[next][neighbor];
                prev[neighbor] = next;
                candidates.push(neighbor);
            }
        }
    }
    return prev;
}

I wrote this code to practice but also to be used at competition contests. So, i want this to be simple, clear and efficient at the same time (without losing so much readability). Any advices?


texts:
Here is a simple client for Wwitter that I wrote based on the twitter library in Python. The aim is to be able to read the feeds from different twitter accounts from the same place in a light way.

I should mention that the code does what I want it to do. Nevertheless, how could I improve it?

(It is available on GitHub.)

#!/usr/bin/python

import sys
import os
import getopt
from twitter import *

# Default values
def_counts = 10
users = []
dir_creds = "./data/oauth/"

# input parameters
def usage():
  print "Run: " + sys.argv[0] + " [OPTIONS]"
  print "Where OPTIONS is one the following: "
  print " -h --help"
  print " -c N --counts=N"
  print " -u \"name\" --user=\"name\""
  print " -a --all"
  print " -l --list"

def main(argv):
  global def_counts, users
  try:
    opts, args = getopt.getopt(argv,"hc:u:al",["help","counts=","user=","all","list"])
  except getopt.GetoptError:
    usage()
    exit(2)
  for opt,arg in opts:
    if opt in ["-h","--help"]:
      usage()
      exit(1)
    elif opt in ["-c","--counts"]:
      print "Retrieving "+str(arg)+" tweets."
      def_counts = arg
    elif opt in ["-u","--user"]:
      print "User: "+arg
      users.append(arg)
    elif opt in ["-a","--all"]:
      print "all users"
      if os.path.exists(os.path.expanduser(dir_creds)):
        token_files = filter(lambda x: x.endswith('.token'), os.listdir(os.path.expanduser(dir_creds)))
        for file in token_files:
          usr = file[:file.index(".token")]
          users.append(usr)
      else:
        print "No user to be added, path undefined"
        exit(2)
    elif opt in ["-l","--list"]:
      if os.path.exists(os.path.expanduser(dir_creds)):
        token_files = filter(lambda x: x.endswith('.token'), os.listdir(os.path.expanduser(dir_creds)))
        for file in token_files:
          usr = file[:file.index(".token")]
          print usr
    else:
      print "Got the following and I don't know what to do with it:"
      print opt + " " + arg
      usage()
      exit(2)

if __name__ == "__main__":
  main(sys.argv[1:])

if len(users) < 1:
  users.append("bilbo_pingouin")

col_bgred   = '\033[41m'
col_bold    = '\033[1m'
col_fgblue  = '\033[34m'
col_fggreen = '\033[32m'
col_fggrey  = '\033[90m'
col_end     = '\033[0m'

for user in users:
  print "\n" + col_bgred + col_bold + user + col_end
  # Retrieve the credentials for a given account
  if not os.path.exists(dir_creds):
    os.makedirs(dir_creds) # I just assume there is not race issue here!

  file_creds = dir_creds + user + ".token"
  MY_TWITTER_CREDS = os.path.expanduser(file_creds)

  api_token_file = "data/api_token.dat"
  if os.path.exists(api_token_file):
    cust_token, cust_secret =     read_token_file(os.path.expanduser(api_token_file))
  else:
    print "ERROR: The app is not identified!"

  if not os.path.exists(MY_TWITTER_CREDS):
    oauth_dance("Twit on CLI",cust_token,cust_secret,
            MY_TWITTER_CREDS)

  oauth_token, oauth_secret = read_token_file(MY_TWITTER_CREDS)

  # OAuth idnetification
  t = Twitter(auth=OAuth(oauth_token,oauth_secret,cust_token,cust_secret))

  # Get status
  data = t.statuses.home_timeline(count=def_counts)

  # Print lines
  for c in range(len(data)):
    print "* " + col_fggreen+col_bold+data[c]['user']['name']+col_end + ' (' + col_fgblue+data[c]['user']['screen_name']+col_end + ')' + " - " + data[c]['text'] + col_fggrey+" ## "+data[c]['created_at']+col_end


texts:
I had to implement an auditing system where the user have to provide a reason he needs to perform a certain operation. When he provides the reason, he can perform freely it for a certain amount of time. Each execution of the operation needs to be logged somewhere.

I implemented it using a Continuation Passing Style, which allows me to cleanly handle atomically permission checking and operation logging.

public class AuditLogger
{
   private readonly TimeSpan permissionDuration;
   private readonly IAuditDatabase auditDatabase;

   private DateTime permissionExpiry = DateTime.MinValue;
   private string accessReason;

   public AuditLogger(TimeSpan permissionDuration, IAuditDatabase auditDatabase)
   {
       this.permissionDuration = permissionDuration;
       this.auditDatabase = auditDatabase;
   }

   private bool CheckPermission()
   {
       return DateTime.UTCNow < permissionExpiry;
   }

   public void SetAccessReason(string reason)
   {
       reason = reason;
       permissionExpiry = DateTime.UTCNow.Add(permissionDuration);
   }

   public void LogAccessAndExecuteOperation(Action operation, Action onPermissionExpired, Action<Exception> onError)
   {
       if(CheckPermission())
           onPermissionExpired();
       try
       {
           auditDatabase.Log(reason);
           operation();
       }
       catch(Exception exception)
       {
           onError(exception);
       }
   }
}

What do you think about it?

Here it is some client code to show how it is supposed to be used.

public static void Main(string[] args)
{
    var auditLogger = new AuditLogger(TimeSpan.FromMinutes(15), new AuditingDatabase);
    var reason = args[0]; // Let's assume the user tells us what he needs to do at startup
    auditLogger.SetAccessReason(reason);

    // Now the user keeps doing lots of things
    while(1)
    {
        auditLogger.LogAccessAndExecuteOperation(
            () => { /* doing nothing here */ Thread.Sleep(1000); },
            () => {
                Console.WriteLine("Time's up. Can you please tell us again what you need to do?");
                reason = Console.ReadLine();
                auditLogger.SetAccessReason(reason);
            },
            exeption => Console.WriteLine(exception)
            );
    }
}