texts:
I've written a framework in MVC. I call it Midget MVC, as it's so darn small. The reason I wrote it is because I wanted a lightweight and extensible framework to use in projects. It eventually got abandoned due to it's break-ability and my lack of experience in the subject. However, I've got a bigger project I'm working on and need a framework, so I want to start re-writing MMVC. Feel free to view the entire project here.

The main piece of code I want looked over is the router class. After talking a bit on the PHP I discovered that it was indeed breakable. One of the recommendations made was for me not to use global $config. What's the best way to do this?

<?php

class Route {
    public function load(){
        global $config;
        if(isset($_SERVER['PATH_INFO'])){
            $route = explode('/', substr($_SERVER['PATH_INFO'], 1));
            $controller = ucfirst(strtolower($route[0]));
            $method = isset($route[1]) ? strtolower($route[1]) : 'index';

            $path = APPPATH . "controllers/" . $route[0] . ".php";
            if(realpath($path)){
                require $path;
                $controller = new $controller;

                if($method != 'index'){
                    $variables = array();
                    $i = 0;
                    foreach($route as $vars){
                        if ($i >= 2)
                            $variables[] = $route[$i];
                        $i++;
                    }

                    call_user_func_array(array($controller, $method), $variables);
                }else{
                    $controller->index();
                }
            }
        }else{
            $controller = $config['deafult_controller'];
            require APPPATH . "controllers/" . $controller . ".php";
            $controller = ucfirst($controller);
            $controller = new $controller;
            $method = 'index';
            $controller->$method();
        }
    }
}

The second thing I want help with is the load class. Is there a better way to load models into the controller? Loading library files was quite difficult; you have to load it in each file. If you load the library in the controller, you'll have to load it again in the model if you want to access it. What's the best way to do this?

class Load{
    function __construct($controller){
        $this->controller = $controller;
    }

    // loads a specified model
    public function model($model){
        $model = strtolower($model);
        if(file_exists(APPPATH . "models/$model.php")){
            require(APPPATH . "models/$model.php");
            $modelclass = ucfirst($model . '_Model');
            // call function to include it in the controller
            $this->controller->$model = new $modelclass;
        }
    }

    // loads a veiw
    public function view($view, $data = NULL){
        // asign filepath
        $path = APPPATH . "views/" . $view . ".php";
        // asign variables if $data is set
        if($data != NULL)
            foreach($data as $var => $value)
                $$var = $value;

        if(file_exists($path)){
            ob_start();
            require($path);
            print(ob_get_clean());
        }else
            return false;
    }

    public function library($library){
        $library = strtolower($library);
        if(file_exists(LIBRARY . "$library.php")){
            require(LIBRARY . "$library.php");
            $libraryclass = ucfirst($library);

            $this->controller->$library = new $libraryclass;
        }
    }
}

And finally, how secure is the entire thing. What security flaws can you see? Are there any major points I should improve upon.


texts:
Sometimes the best way to teach is show what you feel is a shiny approach instead of letting a student muddle through coding and potentially loose a future brilliant coder.

This is what I would show for 'Determine the largest averaged array`. Please review any and all aspects.

'use strict';
//Return the average of 1 array
function arrayAverage(array) {
  var length = array.length,
      sum = 0,
      i;
  for (i = 0; i < length; i++) {
    sum += array[i];
  }
  return sum / length;
}

//Compare 2 arrays, return the array with the largest average
//If the averages are equal, return array2
function largestAveragedArray(array1, array2) {

  return arrayAverage(array1) > arrayAverage(array2) ? array1 : array2;
}

//Figure out which array is largest, return `first` or `second` accordingly
function compare(array1, array2) {
  var largest = largestAveragedArray(array1, array2);
  return largest == array1 ? 'first' : 'second';
}

var smaller = [100, 80],
    larger = [100, 100];

document.write(compare(larger, smaller) + '<br>' + compare(smaller, larger));


texts: Checking if a single linked list is a palindrome in C++

texts:
The following is my first try at this classical interview question. It is quiet different from the solutions Gayle Laakmann provides in her book, and in another question on stackoverflow, someone initially mentioned there are better ways to do it.

I think my solution should run in O(n) time and use O(n) space. Would better Big O performance be possible? This question claims to do it in O(1) space, but edits the list in place, which in my opinion is not a valid solution (A function checking something should always leave the "something" unchanged).
Are there any other things I should change, especially concerning C++ style? I guess I could be using a stack instead of a vector to save the iterators, would that be of any advantage?

#include <forward_list>
#include <iostream>
#include <cstdlib>
#include <vector>

template<typename T>
bool isPalindrome(const std::forward_list<T>& lf)
{
  auto iter = lf.begin();
  std::vector<decltype(iter)> bv; // <-- Correct usage?

  while(iter!= lf.end())
    { bv.push_back(iter++); }

  int istop = bv.size()/2 + bv.size()%2;
  iter = lf.begin();

  for(int i = bv.size()-1; i>=istop; i--, iter++)
  { if( *iter != *(bv[i])) return false; }
  return true;
}

int main(int argc, char* argv[])
{
  std::forward_list<int> list = {0,1,2,1,0};
  std::cout << "Is palindrome: " << isPalindrome(list) << std::endl;
  return 1;
}

This should compile in any compiler using C++11 / C++14.


texts:
The program finds the first non repeating character in a character array, array contains only small case letters.

#include<iostream>
#include<cstring>
using namespace std;
int main()
{
char a2z[26]={0};//Hash

char input[100] = "abcbbbcdegh";//sample input, only small case english alphabets
int n = strlen(input);

for(int i=0; i<n; ++i)
{
    if( a2z[  input[i]-97 ]<0 )
    {
         //do nothing, this character has already repeated
    }
    else if( a2z[  input[i]-97 ]==0 )
    {
        a2z[ input[i]-97 ] = i+1; //character encoutered first time
    }
    else
    {
        a2z[ input[i]-97 ] = -(i+1); //repeating character
    }
}

int minAt=n+1;
for(int i=0; i<26; ++i) //finding first non-negative character in the Hash
{
    if( (a2z[i]>0) && (a2z[i]<minAt) )
    {
        minAt=a2z[i];
    }
}

if( minAt == n+1 )
    cout<<"\n\n no unique character";
else
    cout<<"\n\nFirst unique character is "<<input[minAt-1]<<" at position "<<minAt-1<<endl;
}

output ::

First unique character is a at position 0

here, i have taken an character array (i.e. a2z) of 26 characters initialized with zero, using it as Hash.
 if a2z[i] is zero means ith character (of English alphabet) has not encountered till now, postive value of a2z[i] denotes ith character has been encountered only once at position a2z[i]-1, and negative values shows it has repeated.
pls review this code.


texts: How to create a validation loop for multiple inputs

texts:
I wrote some code to get 3 integers from the user. The code then prints the sum of the 3 integers. The code works as expected. I want to validate all input before doing the calculation. However, the code just doesn't feel right. Is there another approach I should be taking? It seems.. redundant. I am looking into nested try/except, but so far no luck.
msg = "Invalid Input"

while True:
    try:
        a = int(input("Enter 1st number: "))
        break
    except:
        print(msg)
while True:
    try:
        b = int(input("Enter 2nd number: "))
        break
    except:
        print(msg)
while True:
    try:
        c = int(input("Enter 3rd number: "))
        break
    except:
        print(msg)

print(a + b + c)


texts: jQuery buttons to show/hide info and search

texts:
I've used multiple tutorials to get the exact look for show/hide using jQuery, but now that I've done it's too repetitive, I've tried to edit it using variables, but it didn't work. Is there a way to avoid repetitiveness here?

$(document).ready(function() {
  $(document).click(function(event) {
    if ($(event.target).is(".info-icon") || $(event.target).is(".info-tab") || ($(".info-tab").has(event.target).length == 1)) {
      if ($(".info-tab").height() != 0 && !$(event.target).is(".info-tab") && !($(".info-tab").has(event.target).length == 1)) {
        $(".info-tab").css("max-height", "0");
      } else {
        if ($(".search-tab").height() != 0) {
          $(".search-tab").css("max-height", "0");
          setTimeout(function() {
            $(".info-tab").css("max-height", "200px");
          }, 300);
        } else {
          $(".info-tab").css("max-height", "200px");
        }
      }
    } else if ($(event.target).is(".search-icon") || $(event.target).is(".search-tab") || ($(".search-tab").has(event.target).length == 1)) {
      if ($(".search-tab").height() != 0 && !$(event.target).is(".search-tab") && !($(".search-tab").has(event.target).length == 1)) {
        $(".search-tab").css("max-height", "0");
      } else {
        if ($(".info-tab").height() != 0) {
          $(".info-tab").css("max-height", "0");
          setTimeout(function() {
            $(".search-tab").css("max-height", "200px");
          }, 300);
        } else {
          $(".search-tab").css("max-height", "200px");
        }
      }
    } else {
      $(".info-tab").css("max-height", "0");
      $(".search-tab").css("max-height", "0");
    }
  });
});

JSFiddle for what it does is here: https://jsfiddle.net/msms92/L9L0tqvp/


texts: Finding travel distance between airports

texts:
I have 2 nested for loops which i want to get rid of. Any thoughts?
I am calculating distance between cities based on their longitude and latitude. There is a custom function earth.dist() that i am using in the loop.

for (i in 1:nrow(dat)) {
  #for each other airport
  for (j in 1:nrow(dat)) {
    #if both airport are different
    if (dat[i,3]!=dat[j,3]){
      k=k+1
      #airport1
      airport1[k] <- dat[i,3]
      #airport2
      airport2[k] <- dat[j,3]
      #find travel distance
      travdist[k] <- earth.dist(dat[i,5],dat[i,4],dat[j,5],dat[j,4])

    }
  }
}

function for distance calculation

earth.dist <- function (lon1, lat1, lon2, lat2){
  rad <- pi/180
  a1 <- lat1 * rad
  a2 <- lon1 * rad
  b1 <- lat2 * rad
  b2 <- lon2 * rad
  dlon <- b2 - a2
  dlat <- b1 - a1
  a <- (sin(dlat/2))^2 + cos(a1) * cos(b1) * (sin(dlon/2))^2
  c <- 2 * atan2(sqrt(a), sqrt(1 - a))
  R <- 6378.145
  d <- R * c
  return(d)
}


texts: Is there a more dynamic way to target siblings in CSS / SCSS?

texts:
The code I'm working on looks like this - All the way up to 50... (Not ideal)
There can be anywhere from 1 to 100 anchor/div combinations, but more often than not in single digits so there's almost always a lot of redundant CSS rules.
I was wondering if there was a better way to write the CSS / SCSS for this rather than code for each possible outcome manually?  Or would the only way to do this be by using JS?
.content { display: none; }
.anchor-1:hover ~ .content-1,
.anchor-2:hover ~ .content-2,
.anchor-3:hover ~ .content-3,
.anchor-4:hover ~ .content-4,
.anchor-5:hover ~ .content-5 { display: block; }

I also have the code fiddled here: https://jsfiddle.net/rn437pw8/8/


texts: Calculating a total price with group pricing

texts:
I'm evaluating a meeting_type value that determines what kind of pricing structure I should be using. Currently, if my meeting_type value is a w, we charge one price for every 10 registrants. If the meeting_type is anything else, it's a price per registrant model.

I'm using this logic:

if($_POST['meeting_type'] != 'w'){
    $total_price = $guests * $price;
}
else{
    $webinar_count = ceil($guests / 10);
    $total_price = $webinar_count * $price;
}

Is this logic flawed?  Can it be improved upon?


texts: Counting letters program with ASCII-art graph

texts:
I am writing a program in C running on UNIX which counts the number of each letters in a input text file. For a file like this:

The cat sat on the green mat

The output would be like this:

   The letter ’a’ occurs 3 times.
   The letter ’c’ occurs 1 times.
   The letter ’e’ occurs 4 times.
   The letter ’g’ occurs 1 times.
   The letter ’h’ occurs 2 times.
   The letter ’m’ occurs 1 times.
   The letter ’n’ occurs 2 times.
   The letter ’o’ occurs 1 times.
   The letter ’r’ occurs 1 times.
   The letter ’s’ occurs 1 times.
   The letter ’t’ occurs 5 times.

  5                    *
  4     *              *
  4     *              *
  3 *   *              *
  3 *   *              *
  2 *   *  *     *     *
  2 *   *  *     *     *
  1 * * * **    ***  ***
  1 * * * **    ***  ***
  0 **************************
  0 **************************
... abcdefghijklmnopqrstuvwxyz

Where the graph represents the amount of times a letter appears. (If it is more than 10, i simply put a '+' after the 10th row). The code I've currently written to achieve this is as follows: (Haven't found a good way to test for capital letters as well as lowercase yet).

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

void drawGraph(int letters[26], char alpha[26]);
void printLetters(int letters[26], char alpha[26]);
void getLetters(FILE *fp, int letters[26], char alpha[26]);

int main(int argc, char *argv[]) {
  FILE *fp;
  int letters[26] = { 0 };
  char alpha[26] = { 'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z' };
  int indexedAlpha[256] = { 0 };
  int j = 1;

  for (i = 97; i <= 127; i++)
    {
      indexedAlpha[i] = j;
      j++;
    }

  //open file
  if ((fp = fopen(argv[1], "r")) == NULL)
    {
      perror("Cannot open file");
      exit(EXIT_FAILURE);
    }

  getLetters(fp, letters, alpha);
  printLetters(letters, alpha);
  printf("\n");
  drawGraph(letters, alpha);
  printf("\n");

  return EXIT_SUCCESS;
}

void getLetters(FILE *fp, int letters[26], char alpha[26]) {
  int c;
  for (int i = 0; (c = fgetc(fp)) != EOF; i++)
    {
      c = fgetc(fp);
      if ( isalpha(c) )
    {
      for ( int j = 0; j < 26; j++ ) //find which letter it is
        {
          if( c == alpha[j] )
        {
          letters[j]++;
          break;
        }
        }
    }
    }
}

void printLetters(int letters[26], char alpha[26]) {
  for( int i = 0; i < 26; i++ )
    {
      if(letters[i] != 0){
    printf("The letter '%c' occurs %d times.\n", alpha[i], letters[i]);
      }
    }
}

void drawGraph(int letters[26], char alpha[26]) {
  int x = 11;
  int y;
  while(x >= 0)
    {
      y = 0;
      while (y < 2)
    {
      if (x == 10)
        {
          printf(" %d ", x);
        }
      else if (x == 11)
        {
          printf("    ");
        }
      else
        {
          printf("  %d ", x);
        }

      for( int i = 0; i < 26; i++ )
        {
          if(letters[i] > 10)
        {
          printf("+");
          letters[i] = 10;
          y++; // Break out of while loop
        }
          else if(letters[i] == x)
        {
          printf("*");
        }
          else
        {
          printf(" ");
        }
          if (letters[i] == x && y == 1)
        {
          letters[i] = letters[i] - 1;
        }
        }
      printf("\n");
      y++;
    }
      x--;
    }
  printf("... ");

  for( int i = 0; i < 26; i++ )
    {
      printf("%c", alpha[i]);
    }
}

What I'm looking for is advice and tips on notation, efficiency(In amount of code written and memory usage) and any other good tips/Best practices or better methods i could use to complete this task.

Thanks!


texts: Sieve of Eratosthenes prime number finder up to n in C++

texts:
I'be been learning c++ recently and as an exercise I wanted to write a program to find numbers up to n using sieve of Eratosthenes.

I'm new to c++ and programming in general so I'm not sure if this is wildly inefficient or not. I would love some feedback for my code performance wise or better programming practices in general.

#include <iostream>
#include <vector>
#include <cmath>
using namespace std;

int square(int a){
    return a*a;
}

int main(){

    cout << "Enter a number ";
    int MAXIMUM;
    cin>> MAXIMUM;
    int sqrtMaximum = 0;

    //populate allPrimes from 1-MAXIMUM
    vector<int> allPrimes(MAXIMUM);
    for(int i = 1; i<MAXIMUM; i++){
        allPrimes[i] = i;
    }

    //get the square root closest to MAXIMUM (>=)
    if(square(sqrt(MAXIMUM)) < MAXIMUM){
        sqrtMaximum = sqrt(MAXIMUM)+1;
    }
    else{sqrtMaximum = sqrt(MAXIMUM);}

    vector<int> primesOfSqrt = {2,3};

    //adding numbers to list of prime numbers under sqrt
    bool prime = true;
    for(int i = 3; i<sqrtMaximum; i+=2){
        prime = true;
        for(int x : primesOfSqrt){
            if(i % x == 0){
                prime = false;
                break;
            }
        }
        if(prime){
            primesOfSqrt.push_back(i);
        }
    }
    for(int x:primesOfSqrt){cout<<x<<"|||||";}cout<<endl;//print prime numbers under sqrt

    //removing multiples of the prime numbers found under the sqrt
    int factor = 0;
    allPrimes[1] = 0;
    for( int j : primesOfSqrt){
        factor = MAXIMUM/j;
        for(int x = 2; x <= factor; ++x){
            allPrimes[j*x] = 0;
        }
    }
    for(int x = 1; x<MAXIMUM; x++){
        if(allPrimes[x]!=0){cout<<allPrimes[x]<<'\t';}
    }
    char ch; cin>>ch;
}

I used 2 vectors to keep track of prime numbers, one for prime numbers less than the sqrt of n and another to remove multiples of those prime numbers, which I did by setting it to 0, but for bigger numbers i would be setting certain indexes to 0 multiple times, which would only increase the bigger the number gets. I'm not sure how to go about optimizing it or if using a different container would be best so any pointers there would be appreciated as well.

lastly I'm not sure if I am actually doing sieve of eratosthenes right, I'm pretty sure I am, but if I'm not I would like to know.


texts: Using CakePHP models/controllers properly

texts:
I'd like to know if I'm doing this properly. Basically, I have 3 models: Student, Course, StudentCourse. I'm running into problems when I'm trying to sign a student up for a course (I've removed a lot of the non-important code - auth component, view, etc).

// Courses Controller (ie: /courses/signup/6)
class CoursesController extends AppController {
        public function signup($id = null) {
            $this->Course->id = $id;
            if (!$this->Course->exists()) {
                throw new NotFoundException(__('Invalid course'));
            }

            // Let's check to see if the user can signup for the course
            if($this->Course->canSignupForCourse($this->Auth->user('id'))) {

            } else {
                $this->Session->setFlash(__('You cannot signup for that course.'), 'flash_error');
                $this->redirect(array('controller' => 'pages', 'action' => 'calendar'));
            }
    }
}

// Course Model:
class Course extends AppModel {
    // Class 'hasMany' StudentCourse
    // Class 'habtm' Student

    public function isOwnedBy($course, $user) {
        return $this->field('id', array('id' => $course, 'student_id' => $user)) === $course;
    }

    public function isApproved() {
        $course = $this->read(null);

        if($course['Course']['approved_by'] != 0) {
            return true;
        }

        return false;
    }

    public function isComplete() {
        $course = $this->read(null);

        if($course['Course']['completed'] != 0) {
            return true;
        }

        return false;
    }

    public function canSignupForCourse($studentId) {

        if(! $this->StudentCourse->isSignedUpForCourse($studentId) && $this->isApproved() && $this->isComplete()) {
            return true;
        }

        return false;
    }

}

// Student Model
class Student extends AppModel {
    // Student 'hasMany' Course
    // Student 'hasMany' StudentCourse
}

// StudentCourse Model
class StudentCourse extends AppModel {
    // StudentCourse 'belongsTo' Student
    // StudentCourse 'belongsTo' Course
    public function isSignedUpForCourse($studentId = null, $courseId = null) {
        return $this->find('count', array('conditions' => array('StudentCourse.course_id' => $courseId, 'StudentCourse.student_id' => $studentId))) != 0 ? TRUE : FALSE;
    }
}

Basically, am I going about this the right way, are my relationships correct, or, is there a better/easier way to figure out if a student can signup for a course.


texts: Test if arithmetic operation will cause undefined behavior

texts:
I've written a command line calculator as an exercise to get ready for my upcoming first programming job. The whole program source is around 450 lines of code, which I think is too long for a single question. I'll therefore post the code in parts starting with this one.

Any software needs to validate it's data. The functions below are used to test whether a basic arithmetic operation on two signed integers a and b will cause undefined behavior or not. They are checking if the result would be out of bounds and for division by zero. If they return zero the operation is then carried out and the result returned. If they return non-zero, an error message is printed out to the user. The logic of these functions is taken from this page of the SEI CERT C Coding Standard.

My main concern with this code is the is_undefined_mult function, which I don't think is very readable.

int is_undefined_add(int a, int b)
{
    return (a > 0 && b > INT_MAX - a) ||
           (a < 0 && b < INT_MAX - a);
}

int is_undefined_sub(int a, int b)
{
    return (b > 0 && a < INT_MAX + b) ||
           (b < 0 && a > INT_MAX + b);
}

int is_undefined_mult(int a, int b)
{
    if (a > 0) {
        if (b > 0) {
            if (a > INT_MAX / b) {
                return 1;
            }
        }
        else {
            if (b < INT_MIN / a) {
                return 1;
            }
        }
    }
    else {
        if (b > 0) {
            if (a < INT_MIN / b) {
                return 1;
            }
        }
        else {
            if (a != 0 && b < INT_MAX / a) {
                return 1;
            }
        }
    }

    return 0;
}

int is_undefined_div(int a, int b)
{
    return b == 0 || (a == INT_MIN && b == -1);
}


texts:
I built a small flask app and a lot of routes do need some kind of pagination system. However, in some cases I would like to just display n-2, n-1, n, n+1, n+2 where n is the current page and in some others cases, probably a bigger range. Fo example, in the following picture, the range is 2. I am probably going to merge increase() and decrease() in a single method.
I am not doing any database call here, I just want to perform pagination calculation and return values in a form of a dictionary in order to be used by different flask modules.
Would appreciate a feedback! I am quite new to this industry

import math

class Pagination():
    def __init__(self, total_items, items_per_page, page_range, current_page=0):
        self.total_items = total_items  # total number of article to display in total
        self.items_per_page = items_per_page  # maximum number of article per page
        self.page_range = page_range  # number of previous and next pages to display
        self.current_page = current_page
        self.number_of_pages = math.ceil(
            self.total_items / self.items_per_page)

        # if the current_page is 7 and page_range is 3 then self.following will be [8, 9, 10] and self.previous [4, 5 ,6]
        self.following = list(
            range(self.current_page + 1, self.current_page + self.page_range + 1))

        # empty because by default the current page is 0 so no previous
        self.previous = list()

    def increase(self, quantity):
        if self.current_page + quantity > self.number_of_pages:
            raise ValueError(
                f'The maximum number of pages is {self.number_of_pages}')
        else:
            self.current_page += quantity
            self.following = list()
            self.previous = list()
            for i in range(1, self.page_range + 1):
                new_following_page_number = i + self.current_page
                new_previous_page_number = self.current_page - i
                self.previous.insert(i, new_previous_page_number)

                # make sure the number does not exceed the number of pages
                if new_following_page_number < self.number_of_pages:
                    self.following.insert(i, new_following_page_number)

    def decrease(self, quantity):
        if self.current_page - quantity < self.number_of_pages:
            raise ValueError(f'The mimimum number of pages is 0')
        else:
            self.current_page -= quantity
            self.following = list()
            self.previous = list()
            for i in range(1, self.page_range + 1):
                new_following_page_number = i + self.current_page
                new_previous_page_number = self.current_page - i
                self.following.insert(i, new_following_page_number)
                if new_previous_page_number > 0:
                    self.previous.insert(i, new_previous_page_number)

    # method called to set the MongoDB skip amount
    def number_of_previous_items(self):
        if self.current_page == 0:
            return 0
        return self.items_per_page * self.current_page

    # method called to inject variables in the pagination HTML nav
    def dict(self):
        return {
            "current_page": self.current_page,
            "next_page": self.following,
            "previous_page": self.previous,
            "number_of_pages": self.number_of_pages
        }

tmp.py
items_pagination = Pagination(total_items=150, items_per_page=10, page_range=3)
print(render.dict())
render.increase(4)
print(render.dict())

results
{'current_page': 0, 'next_page': [1, 2, 3], 'previous_page': [], 'number_of_pages': 15}
{'current_page': 4, 'next_page': [5, 6, 7], 'previous_page': [3, 2, 1], 'number_of_pages': 15}


texts:
Problem statement

Given a node check whether the sub-tree rooted at given node is full binary tree or not.

Definition

  A full binary tree (sometimes proper binary tree or 2-tree) is a tree in which every node other than the leaves has two children.

Solution

class TreeNode(object):
  """Node of a Binary tree."""
  def __init__(self, key, left=None, right=None):
    self.key = key
    self.left = left
    self.right = right

  def __str__(self):
    return "{0}".format(self.key)

def insert_left(parent, node):
  parent.left = node
  return parent

def insert_right(parent, node):
  parent.right = node
  return parent

def is_leaf(node):
  """Checks whether given node is leaf."""
  return node.left is None and node.right is None

def is_full(node):
  """Checks if the subtree rooted at the given node is full.

  A Binary tree is full when every node other than leaves
  has two children.
  """
  if node is None:
    return True
  if is_leaf(node):
    return True
  if node.left is not None and node.right is not None:
    return is_full(node.left) and is_full(node.right)
  return False

def build_tree(inorder, preorder):
  """Builds a Binary Tree from given inorder and preorder traversal.
  Steps:
    1. Take the first element from the preorder list.
    2. Get the index of the element from inorder list.
    3. Set the element as root.
    4. Take all elements left to root from inorder list.
    5. Take all elements right to root from inorder list.
    6. Calculate preorder list for left and right subtree respectively.
    7. Repeat from step 1 for each subtree.
  """
  def recurse(node, inorder, preorder):
    if len(preorder) == 1:
      return TreeNode(preorder)
    key  = preorder[0]
    root_index    = inorder.find(key)
    inorder_left  = inorder[:root_index]
    inorder_right = inorder[root_index+1:]
    preorder_left = preorder[1:len(inorder_left)+1]
    preorder_right = preorder[root_index+1:]
    node = TreeNode(key)
    if len(inorder_left):
      insert_left(node, recurse(None, inorder_left, preorder_left))
    if len(inorder_right):
      insert_right(node, recurse(None, inorder_right, preorder_right))
    return node
  return recurse(None, inorder, preorder)

import unittest

class TestBinaryTree(unittest.TestCase):

  def test_isFull(self):
    root = build_tree('DBEAFIC', 'ABDEICF')
    self.assertTrue(is_full(root))

    root = build_tree('DBEAFC', 'ABDECF')
    self.assertFalse(is_full(root))

if __name__ == '__main__':
  unittest.main()

Time Complexity

It seems its a \$O(N)\$ where \$N\$ is the number of nodes in the given Binary Tree.

I am also interested in mathematical approach for estimating complexity of these kind of problems. So, here is my initial approach:
\$T(n) = T(n/2) + T(n/2) + 2\$

Is there more cleaner way? Also, the above solution uses a DFS approach i.e. checking every node in a tree. Can we optimize it?

Note

I have extracted away the definition of build_tree as its not important here.


texts:
I am making a Tic Tac Toe game to be played in the console either against another human or a simple AI. It is a little rough but it works. What concerns me is how well it adheres to SOLID and other design principles as this is my first time using them in practice. I would appreciate a review of how my classes are structured and any advice. I am sharing a link from GitHub because there is too much code to post everything here.

These are some of the largest classes and give me an uneasy feeling.

GameBoard.class - has the game board and holds players' markers

package board;

import java.util.ArrayList;

public class GameBoard {

    private Cell[] board;

    private ArrayList<Integer> availableSpots;

    public GameBoard(int n) {
        availableSpots = new ArrayList<Integer>();

        //the game board
        board = new Cell[n];
        for (int i = 0; i < n; i++) {
            board[i] = new Cell();
        }

        //list of initial open cells
        for (int i = 0; i < 9; i++) {
            availableSpots.add(i);
        }
    }

    public Cell[] getBoard() {
        return board;
    }

    public void addMarker(int n, String s) {
        if (availableSpots.contains(n)) {
            board[n].setMarker(s);
            removeSpotFromList(n);
            //System.out.println(availableSpots.size());
        }
        else {
                System.out.println("Cell not available");

            }
    }

    public String getCellValue(int n) {
        return board[n].getMarker();
    }

    public ArrayList<Integer> getAvailableSpots() {
        return availableSpots;
    }

    //remove number from arraylist
    public void removeSpotFromList(int n) {
        availableSpots.set(n, null);
        availableSpots.trimToSize();
        for (int i=0; i<availableSpots.size(); i++) {
            //System.out.println(availableSpots.get(i) + ", ");
        }
    }

}

Game.class - switches between players and calls each turn

import board.GameBoard;
import board.PrintBoard;
import consuleInput.InputReader;
import import players.Playable;
import players.PlayerGroup;

public class Game {

    public static void play() {
        Modes modes =  new Modes();
        InputReader ir = new InputReader();
        GameBoard bg = new GameBoard(9);
        PrintBoard pb = new PrintBoard();
        PlayerGroup pg = new PlayerGroup();
        GameStateChecker gsc = new GameStateChecker();
        System.out.println("choose a mode:");
        System.out.println("1. Player vs player");
        System.out.println("2. player v computer");
        System.out.println("3. computer vs computer");

        int mode =  ir.toIntegerReader("type below");

        modes.chooseMode(mode, pg);

        pb.print(bg);

        int counter = 9;
        Playable currentPlayer;
        boolean hasWinner = false;
        int player = 0;
        //int choice;
        do{
            currentPlayer = pg.getPlayer(player);
            //int choice = ir.toIntegerReader("pick a square (0-8):");
            bg.addMarker(currentPlayer.playerMove(bg.getAvailableSpots()), currentPlayer.getMarker());
            pb.print(bg);
            hasWinner = gsc.checkPatterns(bg, currentPlayer);
            //System.out.println("is there a winner " + hasWinner);
            counter--;
            if (player == 0) {
                player = 1;
            }
            else {
                player = 0;
            }
            /*
            currentPlayer = pg.getPlayer(1);
            choice = ir.toIntegerReader("pick a square (0-8):");
            bg.addMarker(choice, currentPlayer.getMarker());
            pb.print(bg);
            hasWinner = gsc.checkPatterns(bg, currentPlayer);
            counter--;
            */
        }
        while (!hasWinner);

    }
}


texts: Extended Euclidean algorithm and modular multiplicative inverse element

texts:
After my first exercise here is another. Again, this is exactly that: Exercise, which means that the output doesn't necessarily need to be beautifully formatted, etc. I probably have some variable naming issues around and also more general issues.

# coding=utf-8

"""Basic usage:
$ python xggt.py 3343 77
(1, -12, 521)
65
"""

import argparse

###############################################################################

def main():
    """Prints out the results of xggt().
    xggt() takes two non-optional integers as arguments.
    """

    parser = argparse.ArgumentParser()
    parser.add_argument('num_1', type=int)
    parser.add_argument('num_2', type=int)
    args = parser.parse_args()

    if (args.num_1 == 0) and (args.num_2 == 0):
        print("Please enter two positive integers.")
    else:
        print(xggt(args.num_1, args.num_2))
        print(modinv(args.num_1, args.num_2))

###############################################################################

def xggt(num_1, num_2):
    """Implements the Extended Euclidean algorithm.
    Returns the greatest common divisor of two integers > 0.
    Also returns the coefficients of Bézout’s identity.
    """

    if num_1 % num_2 == 0:
        return(num_2, 0, 1)
    else:
        gcd, lin_fact_1, lin_fact_2 = xggt(num_2, num_1 % num_2)

        lin_fact_1 = lin_fact_1 - num_1 // num_2 * lin_fact_2

        return(gcd, lin_fact_2, lin_fact_1)

###############################################################################

def modinv(num_1, num_2):
    """Returns the modular multiplicative inverse of two integers > 0
    """

    gcd, lin_fact_1, _ = xggt(num_1, num_2)

    if gcd != 1:
        return None
    else:
        return lin_fact_1 % num_2

###############################################################################

if __name__ == '__main__':
    main()


texts:
Can anyone review this?

setInterval(function() {
var days_array = [31,29,31,30,31,30,31,31,30,31,30,31];
var m = randNum(12);
var m_limit = days_array[m-1];
var d = randNum(m_limit);
$("code").html("day = "+d+"<br>month = "+m);
},1000);
function randNum(limit){var r=Math.floor(Math.random()*limit)+1;return r;}

jsFiddle


texts:
There are many if-else conditions in my code
Question 1:
I am looking for suggestions to minimize if else conditions. Also, Code in Step 1 and Step2 is almost same. Is there any way to make it neat and improve readability
Question 2:
I am looking for suggestions to improve main method and which methods can be called with an instance or class variables. That technique I will apply to all my LinkedList related questions

public class MergeTwoSortedLists {

    public Node head;
    static class Node {
        int data;
        Node next;

        Node(int d) {
            data = d;
            next = null;
        }
    }

    public void push(int data) {
        Node n = new Node(data);
        if ( head == null ) {
            head = n;
        } else {
            Node temp = head;
            while (temp.next != null ) {
                temp = temp.next;
            }
            temp.next = n;
        }
    }

    public static void printList(Node head) {
        Node temp = head;
        while ( temp != null ) {
            System.out.print(temp.data + " ");
            temp = temp.next;
        }
        System.out.println();
    }

    public static void main(String[] args) {
        MergeTwoSortedLists l1 = new MergeTwoSortedLists();
        l1.push(1);
        l1.push(2);
        l1.push(13);
        l1.push(14);
        l1.push(50);
        printList(l1.head);

        MergeTwoSortedLists l2 = new MergeTwoSortedLists();
        l2.push(10);
        l2.push(20);
        l2.push(55);
        printList(l2.head);

        Node res = sortTwoLists(l1.head, l2.head);
        printList(res);

    }

    public static Node sortTwoLists(Node headA, Node headB) {
        Node s = null;
        Node res = null;
        if ( headA == null ) return headB;
        if ( headB == null ) return headA;

        /* Step 1: Set the s with less value */
        if ( headA!= null && headB!= null ) {
            if ( headA.data < headB.data ) {
                s = headA;
                headA = s.next;
            } else {
                s = headB;
                headB = s.next;
            }
        }
        res = s;

        /* Step2: Iterate oer two lists and keep moving s accordingly */
        while ( headA!= null && headB!= null ) {
            if ( headA.data < headB.data ) {
                s.next = headA;
                s = headA;
                headA = s.next;
            } else {
                s.next = headB;
                s = headB;
                headB = s.next;
            }
        }
        if ( headA == null ) {
            s.next = headB;
        }
        if ( headB == null ) {
            s.next = headA;
        }

        return res;

    }
}


texts: HTML - single page layout - absolute positioning

texts:
I am doing web apps, mostly single page apps. So i have to give absolute and fixed positioning a lot via css.

For Example, consider this page layout:

CSS

.app-header
{
   position: fixed;
   top: 0px;
   left: 0px;
   width: 100%;
}

.main-app-area
{
   width: 100%;
   height: 100%;
}

.app-page
{
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0px;
  left: 0px;
  visibility: hidden;
}

I really don't know, Is this right way of doing single page apps? Will it cause any performance problems?


texts: Modify singly linked list such that all even numbers appear before odd numbers

texts:
I want to improve this code using STL or with better logic. I have not written code for delete function or for copy constructor or move constructor. My aim to learn to exchange even and odd elements.

#include <iostream>
#include <utility>
#include <cassert>

class LinkedList
{
  struct Node
  {
    int data;
    Node * next = nullptr;
    Node(int value)   : data(std::move(value)), next(nullptr) {}
  };
  Node *head;

public:
  LinkedList() : head(nullptr) {}
  ~LinkedList()
  {
    Node *tmp = nullptr;
    while (head)
    {
      tmp = head;
      head = head->next;
      delete tmp;
    }
    head = nullptr;
  }

  void insert(int);
  void exchangeEvenOdd();
  void printList() const;

private:
  static void advance(Node*& node)
  {
    assert (node != nullptr);
    node = node->next;
  }

  Node* getLastNode()
  {
    Node *node = head;
    while (node->next != nullptr)
           node = node->next;

    return node;
  }

  bool isOdd(int num)
  {
    if (num % 2 != 0)
        return true;
    else
        return false;
  }
};

void LinkedList::insert(int value)
{
 Node *node = new Node(std::move(value));
 Node *tmp = head;
 if (tmp == nullptr)
 {
   head = node;
 }
 else
 {
   tmp = getLastNode();
   tmp->next = node;
 }
}

void LinkedList::exchangeEvenOdd()
{
  Node *node = nullptr;
  Node *lastNodeToTest = getLastNode();
  Node *tail = lastNodeToTest;

  while (isOdd(head->data) == true)
  {
    node = head;
    advance(head);
    tail->next = node;
    advance(tail);
  }

  Node *tmp = head;
  Node *curr = head;

  while (tmp->next != lastNodeToTest)
  {
    if (isOdd(curr->next->data) == true)
    {
      node = curr->next;
      curr->next = node->next;
      tail->next = node;
      advance(tail);
    }
    else
    {
      //advance "curr" and "tmp" only when next node to it is even
      advance(curr);
      advance(tmp);
    }
  }

  if (isOdd(curr->next->data) == true && tmp->next == lastNodeToTest)
  {
    node = lastNodeToTest;
    curr->next = lastNodeToTest->next;
    tail->next = lastNodeToTest;
    advance(tail);
  }
  tail->next = nullptr;
  lastNodeToTest = nullptr;
  node = nullptr;
}

void LinkedList::printList() const
{
  if (head == nullptr)
  {
    std::cout << "Empty List \n";
    return;
  }

  Node *node = head;

  while (node != nullptr)
  {
    std::cout << node->data << " ";
    advance(node);
  }

  std::cout << "\n";
}

int main()
{
  LinkedList ll1;
  ll1.insert(1);
  ll1.insert(2);
  ll1.insert(3);
  ll1.insert(4);
  ll1.insert(5);
  ll1.insert(6);
  ll1.insert(7);
  std::cout << "Original List : ";
  ll1.printList();

  ll1.exchangeEvenOdd();
  std::cout << "New List : ";
  ll1.printList();
}


texts: Progress report for a long-running process using 'yield'

texts:
I have a function that processes a large amount of data. I call this function as part of a wider process via a command line script in which many similar but shorter jobs are conducted in sequence.

I have something like this:

import time

def initialise_foo():
    """do something quickly"""
    time.sleep(0.1)

def initialise_bar():
    """do something else quickly"""
    time.sleep(0.1)

def load_data(n_items):
    """do another thing quickly"""
    return range(n_items)

def process_datum(datum, sleep):
    """"do something with datum that takes a while"""
    time.sleep(sleep)

def cleanup():
    """do a final thing quickly"""
    time.sleep(0.1)

My problem is that I want my script to provide feedback on progress and I was considering converting my data processor into an iterator and using yield to emit progress information.

I can do this but there is a long wait with no feedback...

def process_data1(data, sleep):
    """loop over a lot of data"""
    for item in data:
        process_datum(item, sleep)

def main1(n_items, sleep):
    print("initialising foo")
    initialise_foo()
    print("initialising bar")
    initialise_bar()
    print("loading data")
    mydata = load_data(n_items)
    print("processing data")
    process_data1(mydata, sleep)
    print("cleaning up")
    cleanup()
    print("done")

So what about this?

def process_data2(data, sleep, report_frequency):
    """loop over a lot of data"""
    for i, item in enumerate(data):
        process_datum(item, sleep)
        if not (i % report_frequency):
            yield i

def main2(n_items, sleep, report_frequency):
    print("initialising foo")
    initialise_foo()
    print("initialising bar")
    initialise_bar()
    print("loading data")
    mydata = load_data(n_items)
    print("processing data")
    for i in process_data2(mydata, sleep, report_frequency):
        print("%i items processed" % i)
    print("cleaning up")
    cleanup()
    print("done")

run it like this.

if __name__ == "__main__":
    print ("\nwithout progress")
    main1(100, 0.01)
    print ("\nwith progress")
    main2(100, 0.01, 10)

Does this look like a reasonable approach? Any comments on how I have coded this?


texts: Optimal method for writing bytes to file

texts:
I'm making a method to save a byte[] to a file. It's for a Java Helper I'm writing, so it needs to be able to handle any kind of system. I saw on this example the method of FileOutputStream called write which accepts a byte[]. But I already have a method which will save an input stream to a file.

Which is best?

Alternative 1

/**
* Saves the given bytes to the output file.
*
* @param bytes
* @param outputFile
* @throws FileNotFoundException
* @throws IOException
*/
public static void saveBytesToFile(byte[] bytes, File outputFile) throws FileNotFoundException, IOException {
  ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
  saveInputStream(inputStream, outputFile);
}

/**
* Saves the given InputStream to a file at the destination. Does not check whether the destination exists.
*
* @param inputStream
* @param destination
* @throws FileNotFoundException
* @throws IOException
*/
public static void saveInputStream(InputStream inputStream, File outputFile) throws FileNotFoundException, IOException {
  try (OutputStream out = new FileOutputStream(outputFile)) {
    byte[] buffer = new byte[2097152];
    int length;
    while ((length = inputStream.read(buffer)) > 0) {
      out.write(buffer, 0, length);
    }
    inputStream.close();
  }
}

Alternative 2

/**
* Saves the given bytes to the output file.
*
* @param bytes
* @param outputFile
* @throws FileNotFoundException
* @throws IOException
*/
public static void saveBytesToFile2(byte[] bytes, File outputFile) throws FileNotFoundException, IOException {
  FileOutputStream out = new FileOutputStream(outputFile);
  out.write(bytes);
}

Obviously the second is shorter and easier, but I'm just wondering whether one's more optimal than the other. Also, as a side note, I'm wondering about the optimal size for the byte buffer.


texts:
I'm wondering if you see anything terribly wrong with this code, or if you see any areas for improvement. My objective is to make sure its simple enough for someone else taking over my job to be able to pick up fairly quickly.

My basic question has to do with the fact that in my model, I'm trying to distinguish between system errors that I want to show the end user, and ones that I don't want them to see.
Here's some code from my model:

 public function macaddresses($ip, $name)
 {
   try
     {
      //some code....
  if ( $obj->connect() )
  {
           //do something else
       return $macaddies
      }
  else
  {
      throw new Exception('Connection');
  } //end if
   }
   catch (Exception $e)
   {
   $this->error_handler($e->getMessage());
   return false;
    }//end catch
  }//end function

private function error_handler($emess)
{
    switch ($emess)
    {
        case 'Connection':
             $userfriendlyemess = "Unable to connect to device. Please contact administrator!";
             break;

       //handling unknown errors
       default:
            $userfriendlyemess = "Oops!  Something big just happened.";
            log_message('error', $emess); //write to ci logs
            break;
    }// end switch
    throw new Exception($userfriendlyemess);

} // end function

Finally, the logic in my controller is where I make the calls to show_error.
I know in CI i can use templates or something... but since I don't think there are going to be too many cases in my switch statement, i thought i'd try this approach.
any suggestions would be appreciated.


texts:
Is there anything that I could have done better in this code?

<!DOCTYPE html>

<meta charset="utf-8">
<title>Quotes</title>


texts: applicationDidBecomeActive: Am I causing a memory leak?

texts:
Using ARC, I'm calling the following function in an iOS app every time the app gets opened in the applicationDidBecomeActive function.

My concern is that it could create a memory leak because it's creating new instances of UIViewControllers every time the app gets opened from the background.

- (void)showMainWindow{
  NSLog(@"@Info @AppDelegate: Showing Main Window");
  self.leftMenuViewController = nil;
  self.rightMenuViewController = nil;
  MenuViewController *tempLeft = [[MenuViewController alloc]initWithSide:@"left"];
  MenuViewController *tempRight = [[MenuViewController alloc]initWithSide:@"right"];
  self.leftMenuViewController = tempLeft;
  self.rightMenuViewController = tempRight;
  self.viewDeckController =  [[IIViewDeckController alloc] initWithCenterViewController:self.webViewController
                                                                                leftViewController:self.leftMenuViewController
                                                                               rightViewController:self.rightMenuViewController];

  self.window.rootViewController = self.viewDeckController;
  [[NSNotificationCenter defaultCenter] postNotificationName:@"updateNavigationBar" object:nil];
}


texts:
I have code that opens a workbook and copies the sheet to the workbook running the code.  I know activating is generally bad for speed but I can't figure out how to speed this up anymore.  The data area is usually "A1:Q45000" but is different all the time.

Sub AutofillOperations()

    Dim answer As Integer, fd As FileDialog, wb1 As Workbook, wb2 As Workbook, FileName As Variant, file As Variant, location As String, filedate As Date, FileMissing As Boolean, filetime As Variant

    Set wb2 = ThisWorkbook

    With Application
        .ScreenUpdating = False
        .EnableEvents = False
        .DisplayAlerts = False
    End With

    location = Range("K7").Value
    file = UCase(Dir(location))

    FileMissing = True

    While (file <> "")

        If InStr(file, UCase("Operation")) > 0 Then
            filedate = DateValue(FileDateTime(location & file))
            If filedate = Date Then
                FileName = location & file
                Set wb1 = Workbooks.Open(FileName)
                wb1.Activate
                Cells.Copy
                wb2.Activate
                Sheet7.Activate
                Cells.Select
                ActiveSheet.Paste
                wb1.Close
                Application.CutCopyMode = False
                FileMissing = False
                GoTo EndWhile
            End If
        End If
            file = UCase(Dir)
            FileMissing = True
    Wend

EndWhile:

    If FileMissing Then
        MsgBox "File could not be found, please use dialog to verify" & vbNewLine & "modified date and select file.", vbInformation, "File not found"
        Set fd = Application.FileDialog(msoFileDialogFilePicker)

        fd.InitialView = msoFileDialogViewList
        fd.Filters.Clear
        fd.Filters.Add "Excel", "*.xls*"
        fd.Filters.Add "Excel", "*.csv"
        fd.FilterIndex = 1
        fd.AllowMultiSelect = False
        fd.InitialFileName = location
        fd.Title = "Select All file or Cancel to use pasted data"

        answer = fd.Show

        If answer = -1 Then
            FileName = fd.SelectedItems(1)
            Set wb1 = Workbooks.Open(FileName)
            wb1.Activate
            Cells.Copy
            wb2.Activate
            Sheet7.Activate
            Cells.Select
            ActiveSheet.Paste
            wb1.Close
            Application.CutCopyMode = False
        End If
    End If

    With Application
        .ScreenUpdating = True
        .EnableEvents = True
        .DisplayAlerts = True
    End With

    Sheet1.Activate
    Sheet2.Activate

    filetime = TimeValue(FileDateTime(location & file))
    Range("D11").Value = filedate
    Range("D12").Value = filetime

End Sub


texts:
I used some Java code to work out how often MPs and Senators cited their sources in tweets.  The results are at here and the GitHub for the whole project is here, and the Java code I use to download the MPs statements from Twitter is below. I'm looking for any feedback on style, possible errors, and anything else you can think of. I'm intending to be running this code quite regularly and I'd like to check I've NOT left something silly in...

import java.util.Map;

import twitter4j.Paging;
import twitter4j.RateLimitStatus;
import twitter4j.ResponseList;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.User;

public class ProcessMp {

    public static Twitter twitter;

    public static void main(String[] args) throws TwitterException, InterruptedException {
        twitter = TwitApplicationFactory.getjoereddingtonTwitter();
        String username = args[0];
        System.out.println(username);
        User user = twitter.showUser(username.replace("@", ""));
        // ht: from http://www.devmanuals.com/tutorials/java/gettingUserId.html
        checkUser(user);
    }

    private static void checkUser(User user) throws TwitterException, InterruptedException {
        int withNumberAndRef = 0;
        int tweets = 0;
        int withNumber = 0;

        for (int i = 1; i < 10; i++) {
            ResponseList<Status> temp = twitter.getUserTimeline(user.getId(), new Paging(i, 100));
            for (Status status : temp) {
                if (status.getText().startsWith("RT")) {
                    continue;
                }
                System.out.println(status.getText());
                tweets++;
                if (status.getText().matches(".* \\d+,*\\d* .*")) {
                    withNumber++;
                    if (status.getText().matches(".*http.*")) {
                        withNumberAndRef++;
                    }
                }
            }
            waitUntilICanMakeAnotherCall();
        }

        System.out.print("XX," + user.getScreenName() + ",");
        System.out.print(user.getName() + ",");
        System.out.print(tweets + ",");
        System.out.print(withNumber + ",");
        System.out.println(withNumberAndRef);

    }

    protected static void waitUntilICanMakeAnotherCall() throws TwitterException, InterruptedException {
        {
            Map<String, RateLimitStatus> temp = twitter.getRateLimitStatus();
            RateLimitStatus temp2 = temp.get("/statuses/retweets/:id");
            if (temp2.getRemaining() == 0) {
                Thread.sleep((temp2.getSecondsUntilReset() + 5) * 1000);
                return;
            }
            int secondstosleep = 1 + temp2.getSecondsUntilReset() / temp2.getRemaining();
            Thread.sleep(secondstosleep * 1000);
        }
    }

}


texts:
This is a class similar to std::pair and std::tuple inspired by Alexandresku's Expected<T>. Let me know if this class can be helpful for simple error handling.

template<class E, class T>
class CheckValue{
public:
    template<class UT>
    CheckValue(const E &e, UT &&t) : e(e), t(std::forward<UT>(t)){}

    operator E() const{
        return e;
    }

    T &get(){
        return t;
    }

    const T &get() const{
        return t;
    }

private:
    E e;
    T t;
};

... and here is some usage. I did usage with bool first, but deliberately redesign it to work with enum class to show full power.

enum class CalcError{
    OK,
    ERROR,
    DIV_BY_ZERO
};

CheckValue<CalcError, float> calc(float a, float b){
    if (b == 0)
        return { CalcError::DIV_BY_ZERO, 0 };

    return { CalcError::OK, a / b };
}

void prn(float a, float b){
    switch( auto val = calc(a, b) ){
    case CalcError::DIV_BY_ZERO:
        std::cout << "Division by zero" << std::endl;
        break;

    case CalcError::ERROR:
        std::cout << "Error"        << std::endl;
        break;

    default:
    case CalcError::OK:
        std::cout << val.get()      << std::endl;
        break;
    }
}

int main(){
    prn(5, 2);
    prn(5, 0);
}


texts: Cleaner way of returning true/false with error message

texts:
What's a concise way of returning true or false along with an error message?

Here's a concrete example - I'm building a parser that takes in a file. ParseReplayData does some validation before proceeding with the actual parsing:

public class Parser
{
    private const string SUPPORTED_FILE_EXTENSION = "w3g";
    private const string ERROR_FILE_DOES_NOT_EXIST = "Replay file does not exist: {0}";
    private const string ERROR_FILE_EXTENSION_NOT_SUPPORTED = "File extension is not a w3g replay file: {0}";
    private const string ERROR_FILE_BYTE_LENGTH_TOO_SMALL = "Replay file's byte length is too small: {0}";
    private const int REPLAY_MINIMUM_BYTE_LENGTH = 288;
    private ReplayData _replayData;
    private readonly string _replayFilePath;

    public ReplayData ReplayData
    {
        get { return _replayData; }
    }

    public Parser(string replayFilePath)
    {
        _replayFilePath = replayFilePath;
    }

    public bool ParseReplayData(out string errorReason)
    {
        errorReason = String.Empty;
        if (!File.Exists(_replayFilePath))
        {
            errorReason = String.Format(ERROR_FILE_DOES_NOT_EXIST, _replayFilePath);
            return false;
        }
        if (Path.GetExtension(_replayFilePath) != SUPPORTED_FILE_EXTENSION)
        {
            errorReason = String.Format(ERROR_FILE_EXTENSION_NOT_SUPPORTED, _replayFilePath);
            return false;
        }

        byte[] replayFileBytes = File.ReadAllBytes(_replayFilePath);
        if (replayFileBytes.Length < REPLAY_MINIMUM_BYTE_LENGTH)
        {
            errorReason = String.Format(ERROR_FILE_BYTE_LENGTH_TOO_SMALL, _replayFilePath);
            return false;
        }
        _replayData = new ReplayData();
        ..... //Parse Replay
        return true;
    }
}

I can't shake the feeling that there's a lot of code smell in this class, and I'd appreciate any other suggestions you could give me.


texts: Accelerate set of sed commands in files (recursively over full directory)

texts:
I run this to fix some hard-coded references, replacing occurrences of mywar by clientwar:

find . -type f -exec sed -i "s% '/mywar/% '/clientwar/%g" {} +
find . -type f -exec sed -i "s%,'/mywar/%,'/clientwar/%g" {} +
find . -type f -exec sed -i 's% "/mywar/% "/clientwar/%g' {} +
find . -type f -exec sed -i 's% file="/mywar/% file="/clientwar/%g' {} +
find . -type f -exec sed -i 's%<TAB>href="/mywar/%<TAB>href="/clientwar/%g' {} +
find . -type f -exec sed -i 's% href="/mywar/% href="/clientwar/%g' {} +
find . -type f -exec sed -i 's% name="/mywar/% name="/clientwar/%g' {} +
find . -type f -exec sed -i 's% relativePath="/mywar/% relativePath="/clientwar/%g' {} +
find . -type f -exec sed -i 's% requestUrl.indexOf("/mywar/")% requestUrl.indexOf("/clientwar/")%g' {} +
find . -type f -exec sed -i "s% src='/mywar/% src='/clientwar/%g" {} +
find . -type f -exec sed -i 's%<TAB>src="/mywar/%<TAB>src="/clientwar/%g' {} +
find . -type f -exec sed -i 's% src="/mywar/% src="/clientwar/%g' {} +
find . -type f -exec sed -i "s% url('/mywar/% url('/clientwar/%g" {} +
find . -type f -exec sed -i 's% url("/mywar/% url("/clientwar/%g' {} +
find . -type f -exec sed -i 's% url(/mywar/% url(/clientwar/%g' {} +
find . -type f -exec sed -i 's% url="/mywar/% url="/clientwar/%g' {} +
find . -type f -exec sed -i 's% value="/mywar/% value="/clientwar/%g' {} +
find . -type f -exec sed -i 's% webapps/mywar/core% webapps/clientwar/core%g' {} +
find . -type f -exec sed -i 's% window.open("/mywar/"% window.open("/clientwar/"%g' {} +
find . -type f -exec sed -i 's%Disallow: /mywar/%Disallow: /clientwar/%g' {} +
find . -type f -exec sed -i 's%http://localhost:8080/mywar/%http://localhost:8080/clientwar/%g' {} +
find . -type f -exec sed -i 's%http://localhost:9200/mywar/%http://localhost:9200/clientwar/%g' {} +

However, though it looks very readable, it's not compact, and many commands really look like others.

And, worst of all, it's quite slow: more or less 1 hour for the whole set of commands to run on my 2-years old laptop...

Any advice on how to make this:

more performant?
(optionally) better written (if it stays easy to read and understand)?


texts:
I've been learning Java lately and had some great feedback from the previous threads (hangman and guess a number games).
I was challenged by a user to try to get this code done, so I'm posting it here for further review.
Basically my weakeast (among many) points are exception handling and proper documentation.
What do you think about it? How would you improve it?

Code can be found also in GitHub

package app;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;

public class RandomWord {
private String fileName = "src/app/wordlist.txt";
List<String> lines = null;

public static void main(String[] args) {
    RandomWord randomWord = new RandomWord();
    randomWord.init();
}

private void init() {
    try {
        lines = Files.readAllLines(Paths.get(fileName),
                StandardCharsets.UTF_8);
    } catch (IOException e) {
        System.out.println("File can't be opened.");
    }

    int randomWordIndex = getRandomNumber(1, lines.size());
    System.out.println(lines.get(randomWordIndex));
}

/**
 * Returns a random number in the range of the specified min and max
 * parameters.
 *
 * @param min
 *            the minimum value to return
 * @param max
 *            the maximum value to return
 * @return a random number between the specified range
 */
private int getRandomNumber(int min, int max) {
    return min + (int) (Math.random() * ((max - min) + 1));
}
}


texts: Stack implementation with shared_ptr C++11

texts:
stack.hpp

#ifndef _TOP_HPP
#define _TOP_HPP

#include<memory>
#include<iostream>
#include<cstring>

    template <typename T>
    class Stack{
        private:
            struct Node{
                std::shared_ptr<Node> prev;
                T value;
            };

            int size;
            std::shared_ptr<Node> top;
            const char* name;

        public:
            Stack();
            Stack(const char* name);
            bool isEmpty()const;
            void push(T);
            const int pop();
            const int getSize()const{return size;}
            const char& getName()const{return name;}
            void clear();

            Stack<T>& operator=(const Stack<T>&);
            //don't know why but when implement this friend fun beyond
            //class then main.cpp don't compile
            friend std::ostream&  operator<<(std::ostream& os,const Stack<T>& s){
                if(strcmp(s.name,"null")) os<<"Name: "<<s.name<<"  Size "<<s.size<<std::endl;
                auto temp=s.top.get();
                while(temp){
                    os<<temp->value<<std::endl;
                    temp=temp->prev.get();
                }
                return os<<std::endl;
            }

    };

    template <typename T>
    inline Stack<T>::Stack():size(0),top(std::make_shared<Node>()),name("null"){
        top->prev=nullptr;
        top->value=0;
    }

    template <typename T>
    inline Stack<T>::Stack(const char* name):size(0),top(std::make_shared<Node>()),name(name){
        top->prev=nullptr;
        top->value=0;
    }

    template <typename T>
    inline bool Stack<T>::isEmpty()const{
        if(size==0) return true;
        return false;
    }

    template <typename T>
    void Stack<T>::push(T x){
        std::shared_ptr<Node> add =std::make_shared<Node>();
        add->value=x;
        add->prev=nullptr;
        if(isEmpty()) top=std::move(add);
        else{
            add->prev=std::move(top);
            top=std::move(add);
        }
        ++size;
    }

    template <typename T>
    const int Stack<T>::pop(){
        int p=top->value;
        if(isEmpty()){ std::cerr<<"stack is empty"<<std::endl; }
        else{
            top=top->prev; //this is good idea ?
            --size;
        }
            return p;
    }

     template <typename T>
     Stack<T>& Stack<T>::operator=(const Stack<T>& s){
         if(this!=&s){
             size=s.size;
             top=s.top;
         }
         return *this;
     }

    template <typename T>
    inline void Stack<T>::clear(){
        while(top){
            top=std::move(top->prev);i//how can i improve this ?
            --size;
        }
    }

#endif

main.cpp

#include<iostream>
#include<memory>
#include "stack.hpp"

using namespace std;

int main(){

    Stack<int> s("asd");
    Stack<int> q;
    s.push(12);
    s.push(13);
    s.push(14);
    s.push(15);

    q=s;

    cout<<s; //cout's normal display a stacks
    cout<<q;
    s.clear(); // after this fun on s

    cout<<s; // this stack is delete
    cout<<q; // this stack have only 15 (top of stack s) ;/

}


texts:
Exercise: Design a Stack

  A Stack is a data structure for storing a list of elements in a LIFO
  (last in, first out) fashion. Design a class called Stack with three
  methods.

void Push(object obj)
object Pop()
void Clear()

  The Push() method stores the given object on top of the stack. We use
  the “object” type here so we can store any objects inside the stack.
  Remember the “object” class is the base of all classes in the .NET
  Framework. So any types can be automatically upcast to the object.
  Make sure to take into account the scenario that null is passed to
  this object. We should not store null references in the stack. So if
  null is passed to this method, you should throw an
  InvalidOperationException. Remember, when coding every method, you
  should think of all possibilities and make sure the method behaves
  properly in all these edge cases. That’s what distinguishes you from
  an “average” programmer.

  The Pop() method removes the object on top of the stack and returns
  it. Make sure to take into account the scenario that we call the Pop()
  method on an empty stack. In this case, this method should throw an
  InvalidOperationException. Remember, your classes should always be in
  a valid state and used properly. When they are misused, they should
  throw exceptions. Again, thinking of all these edge cases, separates
  you from an average programmer. The code written this way will be more
  robust and with less bugs.

  The Clear() method removes all objects from the stack.

  We should be able to use this stack class as follows:

var stack = new Stack();

stack.Push(1);
stack.Push(2);
stack.Push(3);

Console.WriteLine(stack.Pop());
Console.WriteLine(stack.Pop());
Console.WriteLine(stack.Pop());

  The output of this program will be

3
2
1

This was the task assigned to me.  Following is my code.

using System;

namespace Exercise
{
    class Program
    {
        static void Main()
        {
            var stack = new Stack();

            stack.Push(1);
            stack.Push(2);
            stack.Push(3);

            Console.WriteLine(stack.Pop());
            Console.WriteLine(stack.Pop());
            Console.WriteLine(stack.Pop());
        }
    }
}

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

namespace Exercise
{
    internal class Stack : IEnumerable
    {
        private object _object;
        private List<object> list = new List<object>();

        public IEnumerator GetEnumerator()
        {
            while (list.Any())
                yield return Pop();
        }

        internal object Pop()
        {
            if (list.Count == 0)
                throw new InvalidOperationException("Cannot use .Pop() if list count equals 0.");

            _object = list.FirstOrDefault();

            list.RemoveAt(0);

            return _object;
        }

        internal void Push(object obj)
        {
            _object = obj;

            if (_object == null)
                throw new InvalidOperationException("Cannot use .Push() if object is null.");

            list.Insert(0, _object);
        }

        internal void Clear()
        {
            if (list.Count == 0)
                throw new InvalidOperationException("Cannot use .Clear() if list is empty.");

            list.Clear();
        }

        public void Print()
        {
            if (list.Count == 0)
                throw new InvalidOperationException("Stack is empty.");

            foreach (var s in list)
            {
                Console.WriteLine(s);
            }
        }
    }
}

I'm a beginner in C#.  Is there anything left to improve on with this that is within the boundaries of what the instructions expect?  Any advice or suggestions if anything to teach me something new would be great.  Thank you for all the help so far on this site.


texts:
I am building a php based mobile website that must be in both Spanish and English. This is my first bilingual site so I've been having to re-think a lot of coding practices I currently use to accommodate multiple languages.

I'm using a custom MVC pattern and currently I'm trying to use the same controller and model for both Spanish and English version of the site and just change the view for each language.

Since I'm using same model for both Spanish and English I have created an error system
in the model that supports both languages see sample below.

The error list will be different depending on the model but I have 1 model with almost 30 errors and 60 translations. Its a big Form with a lot of input field validations.

Do you think it would be better to keep it as 1 large nested array or split the array into something like $english_errorids and $spanish_errorids

Open to any ideas you guys may have, it currently works as is I'm just trying to make sure I'm doing this the right way.

 /**
 * Created by PhpStorm.
 * User: wmcgee
 * Date: 11/19/14
 * Time: 12:05 PM
 */

 class SampleModel
 {
     #region Error System
     /**
      * List of all recorded errors
      * @var array
      */
     public $errors;

     /**
      * Can be set to either ENG or SPAN
      * @var string
      */
     public $lang = "ENG";

     /**
      * List of errors with translations
      * @var array
      */
     public $errorids = array(
         10 => array('ENG'=>"Vehicle Condition Missing", 'SPAN'=>"Condicion de vehiculo falta"),
         11 => array('ENG'=>"Signature Missing",         'SPAN'=>"Falta su firma "),
     );

     /**
      * Records a translated error based on what lang is set and
      * what error id was passed into recorded errors list.
      *
      * @param $id int
      * @param bool $override if true id is treated as an
      *                       error message and is recorded
      *                       in error list.
      */
     public function recordError($id, $override = false)
     {
         //- Allow manual error messages not in translation list to be added
         if( $override ){
             $this->errors[] = $id;
             return;
         }

         $this->errors[] = $this->errorids[$id][$this->lang];
     }

    /**
     * Returns errors formatted in HTML
     * @return HTML
     */
    public function getErrors()
    {
        if( sizeof($this->errors) == 0){ return ''; }

        $msg = '
Report Errors
';

        foreach($this->errors as $error)
        {
            $msg .= "&bull; " . $error . "
";
        }

        $msg .= "
";

        return $msg;
    }
     #endregion
 }


texts:
I made this Fiddle with this code, though I'm not happy with it. Is there a better approach to achieve same result with cleaner code?

jsFiddle

var clicked = false;
var cindex = 0;
var cindex = 0;

$('.td').click(function() {
    clicked = true;
    cindex = $(this).index();
    $(this).addClass('highlight');
});

$('.td').hover(function() {
    if(clicked) {
        index = $(this).index();
        if(index >= cindex) {
        if(index >= cindex) {
            $(this).addClass('highlight');
        }
        $(this).nextAll().removeClass('highlight');
        }

      if(index <= cindex) {
      if(index <= cindex) {
            $(this).addClass('highlight');
        }
        $(this).prevAll().removeClass('highlight')
        }
    }

});

HTML:

Click it

Click it

Click it

Click it

Click it

Click it

Click it

Click it

Click it

Click it


texts: Matching file names to an array of product SKUs

texts:
The Challenges:

There are many SKUs, (around 50,000) which I'm trying to match to around the same number of image files.
SKUs contain characters that are not legal in filenames, which must be stripped or replaced.
The files we're trying to match to each SKU live on an NFS, so reads are slow.
We don't just need to match ABC to ABC.jpg, but also ABC#1.jpg and ABC#2.jpg, and need them returned in this order.

Additional Notes:

File names do not need to match the case of the SKU.

My Code:

/**
 * @param $sku
 * @return array
 */
public function findImagesBySku($sku) {
    if (empty($this->dirContents)) {
        $this->dirContents = array_diff(scandir($this->_importDir), array('..', '.'));

        if (empty($this->dirContents)) {
            return array();
        }
    }

    $sku = preg_quote($sku);
    $sku = str_replace(array('\\\\', '/'), '[-_]+', $sku);
    $pattern = "/{$sku}[[#]?[0-9]?]?\.(?:jpe?g|png|gif)$/i";

    $files = preg_grep($pattern, $this->dirContents);

    // Make sure the base-sku image comes first
    asort($files);
    uasort($files, array($this, 'strlenSort'));

    return $files;
}

...

public function strlenSort($a,$b) {
    return strlen($a)-strlen($b);
}

...

foreach ($skus as $sku) {
    $files = $this->findImagesBySku($sku);
}

Rather than repeatedly ask the file system if it has a file called ABC.jpg, I ask the file system once for a list of every file in the given directory, and store it in PHP's memory as an array. (The directory should only ever contain files which are possible matches.)

I then preg_quote the SKU in preparation for a preg_grep search of the directory contents.

I replace \\\\ (an escaped backslash) and / with '[-_]+' to match either _ or - which the client may have in the file name. (Example, ABC/DEF13 becomes abc_def13.jpg and I need to make that match.)

Finally, I build my regex pattern and run preg_grep to find the matching files.

I then asort them and then uasort them by a string length comparison method to make sure that they are in numerical order like so: ABC.jpg, ABC#1.jpg, ABC#2.jpg

I welcome ideas on how this code can be improved and made to run faster. The NFS presents real speed limitations and can't be helped.


texts:
I recently answered a question that had me wondering if I could simplify this below code without creating an extra function:

for object in objects {
    if let type = object["type"] where !type.isEmpty, let name = object["name"] {

        print(pokemonTypeDefenseChart[type])
        for weakness in pokemonTypeDefenseChart[type]! {
            if pokemonWeaknessChart[weakness] == nil {
                pokemonWeaknessChart[weakness] = []
            }
            pokemonWeaknessChart[weakness]?.append(name)
        }
    }

    if let typeTwo = object["typeTwo"] where !typeTwo.isEmpty, let name = object["name"] {
        for weakness in pokemonTypeDefenseChart[typeTwo]! {
            if pokemonWeaknessChart[weakness] == nil {
                pokemonWeaknessChart[weakness] = []
            }
            pokemonWeaknessChart[weakness]?.append(name)
        }
    }
}

Essentially the code loops through objects (list of pokemon) and is designed to add all of the pokemon weak to type (and optionally typeTwo).

I ended up just refactoring the for statements inside the if let statements into a function, but I was wondering if it was possible to compress these without an extra function. The only difference is the type.

I know I could simplify it a bit by using a map instead of for loops but I wanted to keep it more understandable for the question.

Any ideas?


texts:
Requirement:

If the bookshop manager field changes from A to B, I need to email the person B saying that the new Bookshop has been allotted to him and he has to do certain activities.

private void SendEmailToAllottedManager()
{
   EmailExpress mEmailExpress = new EmailExpress();
   mEmailExpress.SendEmail(Shop.Bookstore.BookstoreName, Subject);
}

In the method where I am calling SendEmailToAllottedManager, I am checking if the Manager has indeed changed or not as below:

if (OriginalManager != CurrentManager)
{
    SendEmailToAllottedManager();
}

During code review, a colleague suggested that I move the check from outside the function SendEmailToAllottedManager() to inside it:

Proposed Code

private void SendEmailToAllottedManager()
{
    if (OriginalManager != CurrentManager)
    {
          EmailExpress mEmailExpress = new EmailExpress();
          mEmailExpress.SendEmail(Shop.Bookstore.BookstoreName, Subject);
    }

}

I maintain my stand that the function SendEmailToAllottedManager is only about emailing and not about performing the checks, etc.

What do you think?


texts:
In my company's code, they use double.tryParse() which is quite good but sets too much security for our needs. As we sometimes have to parse a few billion strings, I came up with this code which is a little bit faster (10%) but I have the feeling that it's not at its best... Unfortunately, this kind of stuff require more knowledge than I have.

private static double GetDoubleValue(string input)
{
    double n = 0;
    int decimalPosition = input.Length;
    bool separatorFound = false;
    bool negative = input[0] == '-';
    for (int k = (negative ? 1 : 0); k < input.Length; k++)
    {
        char c = input[k];

        if (c == '.' || c == ',')
        {
            if (separatorFound)
                return Double.NaN;
            decimalPosition = k + 1;
            separatorFound = true;
        }
        else
        {
            if (!char.IsDigit(c))
                return Double.NaN;
            n = (n * 10) + (c - '0');
        }
    }
    return ((negative ? -1 : 1) * n) / CustomPow(10, input.Length - decimalPosition);
}

private static double CustomPow(int num, int exp)
{
    double result = 1.0;
    while (exp > 0)
    {
        if (exp%2 == 1)
            result *= num;
        exp >>= 1;
        num *= num;
    }
    return result;
}


texts:
I'm writing a log table which contains the summary of the claims. The log table logs the data whenever there is an upload.

I have written the following SQL query. Though it serves the purpose, I'm trying to learn whether there is any way to simplify the UPDATEs.

CREATE TABLE #1
  (
     id                         INT IDENTITY(1, 1),
     [total no claims]          INT,
     [total claims inserted]    INT,
     [total claims errored out] INT,
     [erroed claims]            VARCHAR(max)
  )

INSERT INTO #1
            ([total no claims])
SELECT Count(DISTINCT [claimnumber])
FROM   [Operations Productivity Tool].[dbo].[test_importedauditdata] ta
WHERE  claimnumber IN (SELECT DISTINCT claimnumber
                       FROM   [dbo].[opcod audit information] ts
                       WHERE  [final status] IN ( 'Finding', 'No Finding' ))
       AND id = Scope_identity()

UPDATE #1
SET    [total claims inserted] = (SELECT Count(DISTINCT [claimnumber])
                                  FROM
              [Operations Productivity Tool].[dbo].[test_importedauditdata] ta
                                  WHERE  claimnumber NOT IN
                                         (SELECT DISTINCT claimnumber
                                          FROM   [dbo].[opcod audit information]
                                                 ts
                                          WHERE  [final status] IN (
                                                 'Finding', 'No Finding' )
                                         ))
WHERE  id = Scope_identity()

UPDATE #1
SET    [total claims errored out] = (SELECT
       [total no claims] - [total claims inserted]
                                     FROM   #1)
WHERE  id = Scope_identity()

UPDATE #1
SET    [erroed claims] = (SELECT
                                Stuff ((SELECT DISTINCT ',' + claimnumber
                                         FROM
       [Operations Productivity Tool].[dbo].[test_importedauditdata]
                WHERE  claimnumber NOT IN
                       (SELECT DISTINCT claimnumber
                        FROM   [dbo].[opcod audit information] ts
                        WHERE  [final status] NOT IN (
                               'Finding', 'No Finding' ))
                FOR xml
       path(''), type).value('text()[1]', 'varchar(max)'), 1, 2, ''))
WHERE  id = Scope_identity()


texts: Computation of concordant and discordant pairs

texts:
I would like to compute the number of concordant and discordant pairs of two large vectors. This function is a nice try, and works quite efficiently.

pairs <- function(x,y){
    n <- length(x)
    ix <- order(x)
    x <- x[ix]
    y <- y[ix]
    Nc <- sum(sapply(1:(n-1),function(i) sum(x[i]<x[(i+1):n] & y[i]<y[(i+1):n])))
    Nd <- sum(sapply(1:(n-1),function(i) sum(x[i]<x[(i+1):n] & y[i]>y[(i+1):n])))
    return(list(Nc=Nc,Nd=Nd))
}

x <- runif(10000)
y <- runif(10000)
system.time(pairs(x,y))

Do you have any idea on how it would be possible to boost the function?


texts:
CODE:
applicationData = [td.text
                   for td in webBrowser.find_elements_by_xpath('//td[@class="wpsTableNrmRow" and text()!=" "]')]

applicationHeader = [re.sub('[^A-Za-z0-9]+', '', td.text)
                     for td in webBrowser.find_elements_by_xpath('//td[@class="wpsTableShdRow" and text()!=" "]')]

record = {'TitleOfInvention': (webBrowser.find_element_by_xpath('//*[@id="bibviewTitle"]/tbody/tr/td[2]')).text}

for i in range(len(applicationHeader)):
    record[applicationHeader[i]] = applicationData[i]

return record

I am returning scraped data in the dictionary type. But I DON'T WANT to use 3 LOOPS for scraping and storing it in a record(dictionary).
I can't find any other solution other than is.
Any suggestion will be helpful to learn.


texts: Recursively parsing JSON response using GSON

texts:
I have a URL which I am executing it and it is returning the below string as a JSON response. I am using GSON to parse JSON.

In the below JSON, "resourceId" contains an IP address.

{
   "status":{
      "code":"200",
      "msg":"ok",
   },
   "hasmore":true,
   "count":1000,
   "result":[
      {
         "_type":"Calculate",
         "resourceId":"1.2.3.4",
         "_oid":"522b216"
      },
      {
         "_type":"Calculate",
         "resourceId":"5.6.7.8",
         "_oid":"53cea4ad1"
      },
      {
         "_type":"Calculate",
         "resourceId":"9.10.11.12",
         "_oid":"51f98cce1c12c6"
      }
   ],
   "pagination":{
      "cursor":[
         "",
         "545b3bba43a2",
         ""
      ],
      "limit":[
         10000,
         1000,
         1000
      ],
      "skipEmptyPage":false
   },
   "next":{
      "method":"GET",
      "url":"/urlB"
   }
}

Now from the above JSON response, I need to extract all the resourceId values and populate it into a List<String>.

In my above JSON string, there is a property called "hasmore" and in all the JSON response this field will be there always so if "hasmore" is true, then it means there are more IP Address which will be there in another URL and that URL is present in "next" JSON object in the same JSON response at the bottom so I need to execute that URL and get the JSON response back and that response will be similar to what I have above so populate the IP address into the same list and keep on doing this until you see "hasmore" is false.

In general, I will have original URLA which I will execute it and get the JSON response back which will look like as shown above, parse that JSON populate all the resourceId into a List and then check if "hasmore" is true, then it means there will be another URL at the bottom which is URLB so now execute this URL again, get the JSON response back which will be similar to what I have above and then keep on populating resourceId into the same list
and again check if "hasmore" is true or not. Keep on doing this until you see "hasmore" is false.

In short, ips list should have all the IP Address in it since JSON response is coming back as paginated.

I have got the below code working fine:

public static List<String> getListOfIps(String alias) {
    List<String> ips = new ArrayList<String>();
    String url = null;
    boolean hasMore = true;
    try {
        // original url
        url = getURL(alias);
        while (hasMore) {
            String response = getJsonResponse(url);

            // parse response
            if (response != null) {
                JsonElement jelement = new JsonParser().parse(response);
                JsonObject jobject = jelement.getAsJsonObject();

                hasMore = jobject.get("hasmore").getAsBoolean();

                JsonArray jarray = jobject.getAsJsonArray("result");
                if (hasMore) {
                    url = "http://machine.vip.domain.com/ppt" + jobject.getAsJsonObject("next").get("url").getAsString();
                }

                for (JsonElement type : jarray) {
                    ips.add(type.getAsJsonObject().get("resourceId").getAsString());
                }
            }
        }
    } catch (Exception e) {
        // log an exception using logger
    }
    return ips;
}

I am opting for code review for this method to see whether there is any better way of doing this.


texts: C++ template Partial Specialization Member Function; Am I doing right?

texts:
I'm trying to improve my C++ template metaprogramming skills. From my understanding, I can't partially specialize a function(either member function or not). So, I need to define another class that can be used as template class, which enables us partially specialize template argument.
So, In order to check my understanding, I've wrote a simple code. It uses general template class and partially specialized template class to deal with various types. (I've tested this code using gcc 4.8 / clang 3.4 / MSVC 2015) It would give a result as follows:

Generic
Specialization for std::string
Specialization for bool
Specialization for integral type

Am I doing write using class templates? I need a review for this. Any comment would be helpful.
// a.hpp
#ifndef A_HPP
#define A_HPP
#include <iostream>
#include <string>
#include <type_traits>

// declaration & implementation for bar_impl::bar
template <typename T, typename T1, typename T2, typename T3>
struct bar_impl
{
    static void bar(const T& input)
     {
        (void)input;
        std::cout << "Generic" << std::endl;
    }
};

template <typename T>
struct bar_impl<T, std::false_type, std::true_type, std::false_type>
{
    static void bar(const T& input)
    {
        (void)input;
        std::cout << "Specialization for integral type" << std::endl;
    }
};

template <typename T>
struct bar_impl<T, std::false_type, std::true_type, std::true_type>
{
    static void bar(const T& input)
    {
        (void)input;
        std::cout << "Specialization for bool" << std::endl;
    }
};

template <typename T, typename T1, typename T2>
struct bar_impl<T, std::true_type, T1, T2>
{
    static void bar(const T& input)
    {
        (void)input;
        std::cout << "Specialization for std::string" << std::endl;
    }
};

struct Foo
{
    template <typename T>
    void bar(const T& input);
};

template <typename T>
void Foo::bar(const T& input)
{
    bar_impl<
        T,
        typename std::is_same<T, std::string>::type,
        typename std::is_integral<T>::type,
        typename std::is_same<T, bool>::type
    >::bar(input);
}

#endif // A_HPP

// b.cpp
#include "a.hpp"

int main()
{
  Foo foo;

  foo.bar(Foo());
  foo.bar(std::string());
  foo.bar(bool());
  foo.bar(int());
  return 0;
}


texts:
I have a table containing URLs as they should appear in English and equivalent translations of them into other languages.  Originally, I was told that there would always be an English translation, so when listing them in the application that updates them I just searched for the ones where iso = 'GB'.  However, it turns out that it's entirely possible for there not to be an English translation.

I needed to update my query for generating the list displayed in the application so that it would select the English translation in preference to any other translations that might exist, but if there is no English translation, then use a single example of which other translations there are present (doesn't matter which, just as long as there's a single entry presented to the user).

The query I came up with is as follows.  I'd appreciate it if you could give it a sanity check so I can be confident that it's returning correct results. (It appears to do so with the current data set, but it's currently quite a small set).

SELECT `t`.*
FROM (
    SELECT `translations_urls`.*
    FROM `translations_urls`
    ORDER BY iso = 'GB' DESC,
    `order` ASC,
    `url_gb` ASC
) AS `t`
GROUP BY `url_gb`

The table schems is as follows:

CREATE TABLE `translations_urls` (
    `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
    `order` INT(10) NOT NULL COMMENT 'Sort order',
    `iso` CHAR(2) NOT NULL COMMENT 'ISO country code',
    `url_gb` VARCHAR(127) NOT NULL COMMENT 'Original URL',
    `url_trans` VARCHAR(127) NOT NULL COMMENT 'Translated URL',
    `controller` VARCHAR(127) NOT NULL COMMENT 'Controller the URL refers to',
    `action` VARCHAR(127) NOT NULL COMMENT 'Action the URL refers to',
    PRIMARY KEY (`id`),
    UNIQUE INDEX `iso_url_gb` (`iso`, `url_gb`),
    INDEX `url_trans` (`url_trans`),
    CONSTRAINT `fk_translations_urls_translations_countries_iso` FOREIGN KEY (`iso`) REFERENCES `translations_countries` (`iso`)
)
COMMENT='URL translations'
COLLATE='utf8_general_ci'
ENGINE=InnoDB
AUTO_INCREMENT=303;


texts:
Today I had to write a small tool to help me send HTTP requests in bulk. Rabbit was overloading my server, so I decided to change my consumers to buffer the contents of the request, before sending. After changing my API, I did this:

#include <amqpcpp.h>
#include <amqpcpp/libev.h>
#include <ev.h>
#include <cpr/cpr.h>

typedef std::unordered_map<std::string, std::ostringstream> HttpBuffer;
const char* RabbitQueue = getenv("RABBIT_NAME");
char QueueAddress[128];

int main()
{
    sprintf(QueueAddress, "amqp://%s:%s", getenv("RABBIT_HOST"), getenv("RABBIT_PORT"));

    int MaxThreads = std::thread::hardware_concurrency();
    std::vector<std::thread> threads;

    for (int i = 0; i < MaxThreads; i++) {
        threads.push_back(std::thread(RabbitThread));
    }

    for (std::thread &thread : threads) {
        thread.join();
    }

    threads.clear();
}

void RabbitThread()
{
    struct ev_loop *loop = ev_loop_new(0);
    AMQP::LibEvHandler handler(loop);
    AMQP::TcpConnection connection(&handler, AMQP::Address(QueueAddress));
    AMQP::TcpChannel channel(&connection);

    AMQP::MessageCallback onMessage = [&channel](const AMQP::Message &message, uint64_t deliveryTag, bool redelivered) {
        HttpBuffer[message.replyTo()] << message.message().c_str() << ",";
        if (HttpBuffer[message.replyTo()].tellp() < 300000) {
            channel.ack(deliveryTag);
            return;
        }

        cpr::PostCallback(handle_response, cpr::Url{"http://localhost:8888"}, cpr::Body{HttpBuffer[message.replyTo()].str()});
        HttpBuffer[message.replyTo()].str("");

        channel.ack(deliveryTag);
    };

    channel.declareQueue(RabbitQueue);
    channel.bindQueue("default", RabbitQueue, "default");
    channel.consume(RabbitQueue).onReceived(onMessage);

    ev_run(loop);
    ev_loop_destroy(loop);
}

What do you guys think? How can I improve this one?


texts:
I have two different data inputs for the same value, I want to use the non empty one if one of them is, to return the empty string if both are empty, and to flag an error if both are not empty but differ and return one of them.

Empty for my criteria matches the meaning of string.IsNullOrEmpty().

And it's okay that it's written as a property (don't worry about that part.)

This works but feels overly verbose. Can you think of any alternatives?

    public string Callkey
    {
        get
        {
            if (string.IsNullOrEmpty(AS_CALL_KEY) && !string.IsNullOrEmpty(CALLKEY))
            {
                return CALLKEY.Trim();
            }
            if (!string.IsNullOrEmpty(AS_CALL_KEY) && string.IsNullOrEmpty(CALLKEY))
            {
                return AS_CALL_KEY.Trim();
            }
            if (!string.IsNullOrEmpty(AS_CALL_KEY) && !string.IsNullOrEmpty(CALLKEY))
            {
                if (!AS_CALL_KEY.Trim().Equals(CALLKEY.Trim()))
                {
                    _error = true;
                }
                return AS_CALL_KEY.Trim();
            }
            if (string.IsNullOrEmpty(AS_CALL_KEY) && string.IsNullOrEmpty(CALLKEY))
            {
                return "";
            }
            _error = true;
            return "THISNEVERHAPPENS";
        }
    }


texts:
How can I improve this code and avoid crutch? Can I use a case operator?

public bool Crutch;

public void Resize(SizeChangedEventArgs input)
    {
        if (input.NewSize.Width < 450 && Crutch)
        {
            if (!ServiceLocator.Current.GetInstance<MultiViewModel>().EightBoxesCommandIsEnabled)
            {
                ChangeToSmall(2, 2);
            }
        }

        if (input.NewSize.Width < 550 && !Crutch)
        {
            if (!ServiceLocator.Current.GetInstance<MultiViewModel>().EightBoxesCommandIsEnabled)
            {
                ChangeToSmall(3, 2);
            }
            Crutch = true;
        }

        if (input.NewSize.Width > 450 && Crutch)
        {
            if (!ServiceLocator.Current.GetInstance<MultiViewModel>().EightBoxesCommandIsEnabled)
            {
                ChangeToBig(3, 2);
            }
            Crutch = false;
        }

        if (input.NewSize.Width > 550 && !Crutch)
        {
            if (!ServiceLocator.Current.GetInstance<MultiViewModel>().EightBoxesCommandIsEnabled)
            {
                ChangeToBig(4, 2);
            }
        }
    }


texts:
I think understanding basic data compression and pattern finding / entropy reduction primitives is really important. Mostly the basic algorithms (before the many tweaks and optimizations are made) are really elegant and inspiring. What's even more impressive is how widespread they are, but perhaps also how little they are really understood except outside of people working in compression directly. So I want to understand.

I understand and have implemented the naive implementations of LZ77 (just find the maximal prefix that existed before the current factor) and LZ78 (just see if we can extend a factor that occurred before at least twice, or we make a new record and start a new factor). I also understand the naive version of Burrows-Wheeler Transform (maintain the invariant that the first column is sorted, and keep adding that column and resorting until the matrix is square).

I also understand why all these (parts of) compression algorithms work:

LZ77 asymptotically optimal since in the long term and with an infinite window all factors that exist are composed of prefixes earlier in the input which LZ77 can find.
LZ78 is also pretty good since if a factor occurs at least once before it can be compressed the second time, so long as it is not a suffix of another factor found earlier.
BWT, by grouping same letters on the left hand side (of the matrix), and finding patterns in the preceding letters in the right hand side, can exploit bigram repetitions, recursively.

The BWT code below works, but the inverse is not efficient. What are the optimizations, and how can I understand why they work?

BWT

def rot(v):
        return v[-1] + v[:-1]

def bwt_matrix(s):
        return sorted(reduce(lambda m,s : m + [rot(m[-1])],xrange(len(s)-1),[s]))

def last_column(m):
        return ''.join(zip(*m)[-1])

def bwt(s):
        bwtm = bwt_matrix(s)
        print 'BWT matrix : ', bwtm
        return bwtm.index(s), ''.join(last_column(bwtm))

def transpose(m):
        return [''.join(i) for i in zip(*m)]

def ibwt(s):
        return reduce(lambda m, s: transpose(sorted(transpose([s]+m))),[s]*len(s),[])

s = 'sixtysix'
index, bwts = bwt(s)
print 'BWT, index : ', bwts, index
print 'iBWT : ', ibwt(bwts)

BWT output

BWT matrix :
ixsixtys
ixtysixs
sixsixty
sixtysix
tysixsix
xsixtysi
xtysixsi
ysixsixt
BWT, index :  ssyxxiit 3
iBWT :
ixsixtys
ixtysixs
sixsixty
sixtysix
tysixsix
xsixtysi
xtysixsi
ysixsixt

Which is correct.

LZ77

def lz77(s):
        lens = len(s)
        factors = []
        i = 0
        while i < lens:
                max_match_len = 0
                current_word = i
                j = 0
                while j < lens-1:
                        if current_word >= lens or s[current_word] != s[j]:
                                j -= (current_word - i)
                                if current_word - i >= max_match_len:
                                        max_match_len = current_word - i
                                if current_word >= lens:
                                        break
                                current_word = i
                        else:
                                current_word += 1
                        j += 1
                if max_match_len > 1:
                        factors.append(s[i:i+max_match_len])
                        i += max_match_len
                else:
                        factors.append(s[i])
                        i += 1
        return ','.join(factors)

LZ78

def lz78(s):
        empty = ''
        factors = []
        word = empty
        for c in s:
                word += c
                if word not in factors:
                        factors.append(word)
                        word = empty
        if word is not empty:
                factors.append(word)
        return ','.join(factors)

Correct outputs against 7th Fibonacci word:

LZ77( abaababaabaab ): a,b,a,aba,baaba,ab
LZ78( abaababaabaab ): a,b,aa,ba,baa,baab