texts:
I am trying to create a class that parses a JSON and selects all labels, or just a particular label that you prefer to later do a calculation with the value pair extracted off that label. This is working well for .all() This is the first function, wich selects ALL available labels. But then I want to make it flexible and be able to call names = IncomeSources(result).spa() to see the revenue results for the spa only. The code is working fine, but I will die if I have to write a function for each label separately. Is there more efficient way to do it ?

class IncomeSources(object):

    def __init__(self, result):
        self.result = result

    def all(self):
        labels_list = []
        for index in self.result:
            for key, value in index.items():
                if 'accountLabelType' in key:
                    names = value
                    labels_list.append(names)
                    collection = set(labels_list)

        return collection

    def brickyard(self):
        name = 'Brickyard'
        labels_list = []
        for index in self.result:
            for key, value in index.items():
                if 'accountLabelType' in key and value.startswith('BYD'):
                    names = value
                    labels_list.append(names)
                    collection = set(labels_list)
        return collection

    def schoolhouse(self):
        name = 'Schoolhouse'
        labels_list = []
        for index in self.result:
            for key, value in index.items():
                if 'accountLabelType' in key and value.startswith('SCH'):
                    names = value
                    labels_list.append(names)
                    collection = set(labels_list)
        return collection

    def spa(self):
        name = 'Spa'
        labels_list = []
        for index in self.result:
            for key, value in index.items():
                if 'accountLabelType' in key and value.startswith('Spa'):
                    names = value
                    labels_list.append(names)
                    collection = set(labels_list)
        return collection


texts: Laravel controller for form validation skinny

texts:
I'm trying to make controllers skinny as possible. I use repositories for accessing the database and I use Services to do other stuff. In this case, I use it to insert a new post to the database. For validation I use Jeffery Way's validation package for Laravel.

PostController.php

<?php

use Laracasts\Validation\FormValidationException;

use Dnianas\Post\PostCreationService;
use Dnianas\Post\PostRepository;

use Dnianas\Forms\PostForm;

class PostController extends BaseController
{

    /*
     * Dnianas\Services\PostCreationService
     */
    protected $post;

    /*
    * The post repository
     */
    protected $posts;

    /**
     * @param PostForm $postForm
     * @param PostCreationService $post
     * @param PostRepository $postRepo
     */
    public function __construct(PostForm $postForm, PostCreationService $post, PostRepository $postRepo)
    {
        $this->posts = $postRepo;
        $this->postForm = $postForm;
        $this->post = $post;
    }

    public function index()
    {
        $this->beforeFilter('auth');
    }

    /**
     * @return \Illuminate\Http\JsonResponse
     */
    public function create()
    {
        // Get the input
        $input = Input::all();

        // Validate it
        try {
            $this->postForm->validate($input);
        } catch(FormValidationException $e) {
            return Response::json([
                'success' => 'false',
                'message' => 'You didn\'t enter anything, Post cannot be empty.'
            ]);
        }

        // Insert it to the database
        $post = $this->post->create($input, Auth::user()->id);

        // Get the html content from the view
        $html = View::make('posts.post', ['post_id' => $post->id])->render();

        // Return a message along with the html content
        return Response::json([
            'success' => 'true',
            'message' => 'Your post has been successfuly posted!',
            'post_html' => $html
        ]);

    }

PostForm.php

<?php namespace Dnianas\Forms;

use Laracasts\Validation\FormValidator;

class PostForm extends FormValidator
{
    /**
     * Validation rules for when the user creates a post
     * @var array
     */
    protected $rules = [
        'post_content' => 'required'
    ];

}

PostCreationService.php

namespace Dnianas\Post;

class PostCreationService
{

    /**
     * @param $input
     * @param $user_id
     * @return \Post
     */
    public function create($input, $user_id)
    {
        // Validation passed to we insert it to our database
        $post = new \Post;
        $post->post_content = $input['post_content'];
        $post->posted_date  = \Carbon::now();
        $post->user_id      = $user_id;
        $post->save();

        return $post;
    }
}

Is this controller skinny enough? Can it get any skinnier? If so, then how?


texts:
// variables
// arr has elements to be sorted
var arr = []
// temp is to store the intermediate results after merging
var temp = []
// seen is for marking visited i.e. sorted half as green
var seen = []
// length of array
var len = 50

// canvas initialisations
var canvas = document.getElementById("myCanvas")
canvas.width = canvas.height = 1000
var canvaswidth = canvas.width
var canvasheight = canvas.height
var ctx = canvas.getContext("2d")

// random array
for (let i = 0; i < len; i++) {
    arr.push(parseInt(Math.random() * 500))
    temp.push(parseInt(0))
    seen.push(parseInt(0))
}

// initial contents of array to be sorted
// console.log(arr)

// draw the bars
draw = (s, e) => {
    ctx.clearRect(0, 0, 1000, 1000)

    // this loop will make unvisited bars in the upper half as black
    // and visited bars in the upper half as green
    for (let i = 0; i < len; i++) {
        ctx.fillStyle = "#000000"
        ctx.fillRect(15 * i, 500 - arr[i], 10, arr[i])
        if (seen[i]) {
            ctx.fillStyle = "#00ff00"
            ctx.fillRect(15 * i, 500 - arr[i], 10, arr[i])
        }
    }

    // the part that was merged is made blue in the lower half
    // also its equivalent in the uper half is made white
    for (let i = s; i <= e; i++) {
        ctx.fillStyle = "#ffffff"
        ctx.fillRect(15 * i, 500 - arr[i], 10, arr[i])
        ctx.fillStyle = "#0000ff"
        ctx.fillRect(15 * i, 500, 10, arr[i])
        seen[i] = 1
    }

}

// merge
merge = (s, e) => {

    let m = parseInt((s + e) / 2)
    let p1 = s
    let p2 = m + 1
    let n1 = m
    let n2 = e
    let idx = s

    while (p1 <= n1 && p2 <= n2) {
        if (arr[p1] <= arr[p2]) {
            temp[idx++] = arr[p1++]
        }
        else {
            temp[idx++] = arr[p2++]
        }
    }

    while (p1 <= n1) {
        temp[idx++] = arr[p1++]
    }

    while (p2 <= n2) {
        temp[idx++] = arr[p2++]
    }

    idx = s
    while (idx <= e) {
        arr[idx] = temp[idx++]
    }

}

// delay
function mytimeout(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

// mergesort
const mergesort = async (s, e) => {

    if (s < e) {
        let m = parseInt((s + e) / 2)
        await mergesort(s, m)
        await mergesort(m + 1, e)
        await merge(s, e)
        // await console.log(`merged ${s} to ${e} now draw...`)
        await draw(s, e)
        await mytimeout(500)
    }

}

// calls merge sort and at last
// makes all bars become green in upper half
const performer = async () => {
    await mergesort(0, len - 1)
    // await console.log(arr)
    await draw()
}

performer()
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <canvas id="myCanvas">
        Your browser does not support the canvas element.
    </canvas>
    <script src="testmerge.js"></script>
</body>

</html>

Now if i change the len variable in JS to above 50 i.e. 75 or 100 the code behaves oddly..why is it so?
Are there any optimisations possible??


texts: Replace text in emacs buffer with processed one

texts:
I have function that processes text and returns it in altered state. Result of the processing is a property list with following properties of interest:

:success - t if processing finished correctly
:text - complete changed text
:changedLines: list of changed lines as 2 element vectors [number-of-line line-text] (numbers are zero-based)
:cursorX - position of cursor on the current line
:error - description of the problem in case processing failed to succeed

This is a final version of the code:

(defun parinfer-mode--insert-result (result)
  "Put results of running parinfer in current buffer
If cursor is right after a newline and next character is a closing curly brace, result is ignored
All lines that were changed are replaced, then cursor is set toa new position"
  (let ((inhibit-modification-hooks t))
    (cl-macrolet ((-char-before (point) `(or (char-before ,point) -1))
                  (-char-after (point) `(or (char-after ,point) -1))
                  (sv (arg) `(symbol-value ,arg)))
      (cl-labels ((replace-line (index new-line posvar)
                                (forward-line (- index (sv posvar)))
                                (let ((beg (point))
                                      (end (progn (move-end-of-line 1) (point))))
                                  (insert new-line)
                                  (delete-region beg end))
                                (set posvar index)))
        (if (plist-get result :success)
            (if (not (and (= (-char-before (point)) 10)
                          (= (-char-after (point)) 41)))
                (let* ((old-line (line-number-at-pos))
                       (new-lines (plist-get result :changedLines))
                       (new-line-point (plist-get result :cursorX))
                       (cur-line old-line))
                  (mapc (lambda (elem)
                          (replace-line (1+ (aref elem 0))
                                        (aref elem 1)
                                        'cur-line))
                        new-lines)
                  (forward-line (- old-line cur-line))
                  (forward-char new-line-point)))
        (message "Parinfer did not succeed: %s" (plist-get result :error)))))))

This is previous version of the code:

(defun parinfer-mode--insert-result (result)
  (let ((inhibit-modification-hooks t))
    (cl-macrolet ((-char-before (point) `(or (char-before ,point) -1))
                  (-char-after (point) `(or (char-after ,point) -1)))
      (if (plist-get result :success)
          (if (not (and (= (-char-before (point)) 10)
                        (= (-char-after (point)) 41)))
              (let ((old-buffer (current-buffer))
                    (old-point (point)))
                (with-temp-buffer
                  (insert (plist-get result :text))
                  (copy-to-buffer old-buffer (point-min) (point-max)))
                (goto-char old-point)))
        (message "Parinfer did not succeed: %s" (plist-get result :error))))))

I am having doubts first approach is better then second, because it has longer and harder-to-understand code. Also, i am not clear on whether replacing code line-by-line is actually faster then switching buffer contents.


texts: I need some suggestions to speed up my array manipulation code

texts:
I have a function which from an array of days return the array of days with it's date like from array of
['Sun', 'Mon', 'Tue', 'Wed' ] my function returns the days from today if there are some past days i switch the date to next week so the array will become  ['Wed 23', 'Sun 27', 'Mon 28', 'Tue 29' ]
And here is how my function looks like (i've added all comments that specify what i'm doing on each step:
  moment.locale('it'); // setting locale to italian as API response returns it formatted days

    const days = ['lun', 'mar', 'mer', 'gio', 'ven', 'sab', 'dom']; // mapping weekdays which will be used to get index of the day to use in isoWeekday

    const momentToday = moment().isoWeekday(); // setting today date
    const arrayGiorni = giorni.map((g) => {
      const dayIndex = days.indexOf(g.giorno.toLowerCase()); // getting index of day from the object array es if g.giorno is 'mar' index will be 2
      if (momentToday <= dayIndex) { // checking if today is <= to mapping object then adding it to array
        return {
          id: g.id,
          giorno: moment().isoWeekday(dayIndex),
        };
      } else { // else skipping to next week and adding the object to array
        return {
          id: g.id,
          giorno: moment()
            .add(1, 'weeks')
            .isoWeekday(dayIndex),
        };
      }
    });

// sorting the array to get an ordered array of dates
    arrayGiorni.sort((a, b) => moment(a.giorno).valueOf() - moment(b.giorno).valueOf());

// formatting the moment object to get string formatted date
    this.giorni = arrayGiorni.map(g => g.giorno.format('ddd DD MMM'));

    console.log(this.giorni);

As asked in comments here is the model of giorni:
export class NegozioGiorni {
    constructor(
        public id: number,
        public giorno: string,
        public orari: string[] = []
    ) {}
}

That in array of objects will be [ { id: 1, giorno: 'lun', orari: ['12:00', '13:00'] }, { id: 2, giorno: 'mer', orari: ['12:00', '13:00'] }, { id: 2, giorno: 'ven', orari: ['15:00', '17:00'] } ]
I was wondering if there is something that i can reduce in this come and if there is a way to make it more performable.


texts: Template based return type from object and class method

texts:
I'm looking for a better implementation of this. The current solution looks bad to me and breaks the VC10 compiler if you call Create() with a method expecting two parameters.

Can this be reworked to be more compatible across compilers (at least VC10)?

Is there are simpler or clearer way to do this? Would it be possible to forward an arbitrary number of arguments to bind or it is necessary to write a function depending on how many parameters it can accept?

class Obj : public boost::enable_shared_from_this<Obj>
{
  public:
    Obj() {}
    bool mm(int a) { return a == 7; }
};

template<typename TOBJ, typename TMETH>
auto Create(boost::shared_ptr<TOBJ> sobj, TMETH mm) -> decltype( boost::bind(mm, sobj, _1) )
{
   return boost::bind(mm, sobj, _1);
}

...

boost::shared_ptr<Obj> o1 = boost::make_shared<Obj>();
Create(o1->shared_from_this(), &Obj::mm)(7);

It seems to work but I do not trust the code generated when the compiler breaks instead of returning an error.


texts:
I am trying to create a resume app from django. I have divided the entities for resume as Resume, Experience, Education, Qualification/Skills, Reference. I have modeled the following entities as below

class Resume(models.Model):
    applicant = models.OneToOneField(User, on_delete=models.CASCADE)
    name = models.CharField(max_length=100, blank=False, null=False, help_text="Full Name")
    slug = models.SlugField(max_length=50, unique=True)
    designation = models.CharField(max_length=200, blank=True, null=True)
    career_goal=models.CharField(max_length=500, blank=True, null=True)
    city = models.CharField(max_length=100, blank=True, null=True)
    address = models.CharField(max_length=100, blank=True, null=True)
    phone_number = models.CharField(max_length=100, blank=True, null=True)
    email=models.EmailField(blank=False, null=False)
    website=models.URLField(blank=True, null=True)
    linkedin_url=models.URLField(blank=True, null=True)
    twitter_url=models.URLField(blank=True, null=True)
    facebook_url=models.URLField(blank=True, null=True)
    summary=models.CharField(max_length=400, blank=True, null=True)

    class Meta:
        verbose_name = 'Resume'
        verbose_name_plural = 'Resume'

    def __str__(self):
        return self.first_name + self.last_name

class Education(models.Model):
    resume = models.ForeignKey(Resume, related_name='education')
    name = models.CharField(max_length=100, blank=False, null=False, help_text="Name of an institution")
    course = models.CharField(max_length=200, blank=False, null=False, help_text="Name of a course")
    description = models.CharField(max_length=400, blank=True, null=True)
    start_date = models.DateField() #only get year
    end_date = models.DateField() # only year

    class Meta:
        verbose_name = 'Education'
        verbose_name_plural = 'Education'

    def __str__(self):
        return '{0} -> {1}'.format(self.resume.name, self.name)

class Experience(models.Model):
    resume = models.ForeignKey(Resume, related_name='experience')
    designation = models.CharField(max_length=100, blank=True, null=True)
    company = models.CharField(max_length=100, blank=True, null=True)
    description=models.CharField(max_length=400, blank=True, null=True)
    start_date = models.DateField()
    end_date = models.DateField()

    class Meta:
        verbose_name='Experience'
        verbose_name_plural='Experiences'

    def __str__(self):
        return self.designation

class Skill(models.Model):
    resume=models.ForeignKey(Resume, related_name="skills")
    name = models.CharField(max_length=100, blank=True, null=True, help_text="Name of the skill")

    class Meta:
        verbose_name='Skill'
        verbose_name_plural='Skills'

    def __str__(self):
        return self.name

class Reference(models.Model):
    resume = models.ForeignKey(Resume, related_name='resume')
    name_of_refree=models.CharField(max_length=100, blank=False, null=False)
    designation_of_refree = models.CharField(max_length=100, blank=False, null=False)
    phone_number=models.CharField(max_length=50, blank=False, null=False)

I want someone to review at my model and help me on if I have designed the relation perfectly or not. I am trying for arranging the content for perfect resume so i am wanting it to be both content friendly and user friendly which will help in building convincible resume. Also please feel free to sum your expertise/idea.


texts: Reading and Storing Integer from Serial Monitor

texts:
Description

I wanted to understand how integers can be written and stored inside variables without the use of Serial.parseInt(). I couldn't find any code examples about this. Perhaps this is the right way to do it, although it doesn't detect and block letters and special characters. Please leave some feedback on ways to improve it. Thanks in advance! :)

void setup()
{
  Serial.begin(9600); // Opens serial port, sets data rate to 9600 bps
  Serial.println(F("Serial port opened!"));
}

void loop()
{
  byte received;
  static byte counter = 0;
  static uint32_t number = 0; // Store value from 0 to 4294967295

  while (Serial.available()) // Read data in serial receive buffer
  {
    received = Serial.read(); // Store received byte
    if (received != 10) // Terminate if newline char detected
    {
      if (counter != 0) // Put number in its correct position (base-10 system)
      {
        number *= 10;
        number += (received - '0');
      }
      else
      {
        number = (received - '0');
      }
      counter++;
    }
    else
    {
      Serial.println(number); // Print value inside number and reset
      counter = 0;
    }
  }
}


texts:
I'm cloning a fairly complex div/ page and changing various things in it before appending it to the DOM.  The current method seems long-winded, and I was hoping if there was a simpler way of doing it?

$.each(results.jobs, function(i, result){

var theID = result.id,
theTitle = result.title,
theDescription = result.description,
theLocation = result.location,
theType = result.type,
thePosted = posted[2]+'-'+posted[1]+'-'+posted[0],
theAgency = result.company,
theRef = result.reference,
theSalary = '',
theApps = result.number_of_applications,
hasApplied = result.applied,
theFeatured = result.featured,
theJobNo = pages*i +1;

if(result.hasOwnProperty('salary')){
    var theSalary = result.salary.information.replace(/Â/g, '');
}

var jobContainer = $('#job-container').clone(true, true).attr('data-jobno', theJobNo);

jobContainer.find('h1').text(theTitle);
jobContainer.find('#job-location').text(theLocation);
jobContainer.find('#job-type').text(theType);
jobContainer.find('#job-date').text(thePosted);
jobContainer.find('#job-agency').text(theAgency);
jobContainer.find('#job-description').html(theDescription.replace(/Â£/gi, '&pound;'));
jobContainer.find('#job-ref').text(theRef);
jobContainer.find('#job-id').text(theID);
jobContainer.find('.apply-btn, .email-btn, .save-btn').attr('id', theID);
jobContainer.find('.save-btn').text('Save Job').removeClass('job-saved');

if(localStorage["saved"]!=null && localStorage["saved"]!= '[]'){
    if(localStorage["saved"].indexOf(theID)>= 0){
        jobContainer.find('.save-btn').addClass('job-saved').text('Job Saved');
    }
}

if(theFeatured === '1'){
    jobContainer.find('#job-featured').show();
}else{
    jobContainer.find('#job-featured').hide();
}

if(localStorage["applied"]!=null && localStorage["applied"]!= '[]'){
    if(localStorage["applied"].indexOf(theID)>= 0){
        jobContainer.find('.job-alert').show();
    }
}

if(theSalary != null){
    jobContainer.find('#job-row-salary').show();
    jobContainer.find('#job-salary').text(theSalary);
}else{
    jobContainer.find('#job-row-salary').hide();
}

if(theApps === '0'){
    jobContainer.find('#job-apps').html('Be first to apply!');
}else{
    jobContainer.find('#job-apps').html(theApps);
}

viewJobList.push(jobContainer)

});

$('#slider').html('').append(viewJobList)

This is inside an Ajax success function which is made to an API. I'm cloning an existing page in the HTML and adding new information, adding it to an array/ list then appending to the DOM just the once.


texts:
I am experimenting with JavaScript ES6 import and export and wanted to achieve the following:

Use the import / export style of including JavaScript files.
Import a class file and create an instance
Import a class file that extends another class
Expose functions to the index.html scope - call from an inline onclick event
Is document. available within the module scope

Is this the correct, or recommended way of doing this, or is there a better way?

index.html

<!DOCTYPE html>

        <meta charset="UTF-8">
        <title>Javascript - Import and Export class examples</title>

Javascript Import and Export class examples

        <button onclick="window.updateScreen()">Do it</button>

main.js

import { Animal } from './animal.js';
import { Human } from './human.js';
import { Dog, Cat } from './pets.js';

const petOwner = new Human('Bob', 'Male', '21/03/19');
const pets = [ new Dog('Riley', petOwner), new Cat('Sherry', petOwner) ];

petOwner.speak();
pets[1].speak();
pets[0].speak();

function updateScreen() {
    let elem = document.getElementById('myDiv');
    elem.textContent = 'HELLO';
}

export { updateScreen };

animal.js

class Animal {
    constructor(alive, hr) {
        this.isAlive = alive;
        this.heartRate = hr;
    }
}
export { Animal };

human.js

import {Animal} from './animal.js';
class Human extends Animal {
    constructor(name, sex, dob) {
        super(true, 60);
        this.name = name;
        this.dob = dob;
        this.sex = sex;
    }
    speak() {
        console.log('Hello');
    }
    get age() {
        return now-dob;
    }
}
export { Human };

pets.js

import {Animal} from './animal.js';

class Cat extends Animal {
    constructor(name, owner) {
        super(true, 200);
        this.name = name;
        this.owner = owner;
    }
    speak() {
        console.log('Meow');
    }
}

class Dog extends Animal {
    constructor(name, owner) {
        super(true, 120);
        this.name = name;
        this.owner = owner;
    }
    speak() {
        document.getElementById('myDiv').textContent = 'Woof';
    }
}

export { Cat, Dog };


texts:
I wanted to launch a bash script (read: bash not sh script) as a root not as the user calling it, however bash ignore setuid on scripts, so I chose to write a very small script that takes a script/arguments and call it with setuid set.

This worked well and I went even further to verify that the script has setuid set on, executable and setuid() called on the owner of the file and not as root, to avoid any misuse of the program and I ended up with the program below.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>

int main(int argc, char **argv)
{
  char *command;
  int i, file_owner, size = 0;
  struct stat status_buf;
  ushort file_mode;

  // Check argc
  if (argc < 2) {
    printf("Usage: %s <script> [arguments]\n", argv[0]);
    return 1;
  }

  // Make sure the script does exist
  if(fopen(argv[1], "r") == NULL) {
    printf("The file %s does not exist.\n", argv[1]);
    return 1;
  }

  // Get the attributes of the file
  stat(argv[1], &status_buf);

  // Get the permissions of the file
  file_mode = status_buf.st_mode;

  // Make sure it's executable and it's setuid
  if(file_mode >> 6 != 567) {
    printf("The file %s should be executable and should have setuid set, please chmod it 0106755.\n", argv[1]);
    return 1;
  }

  // Get the owner of the script
  file_owner = status_buf.st_uid;

  // setuid
  setuid(file_owner);

  // Generate the command
  for (i = 1; i < argc; i++) {
    size += strlen(argv[i]);
  }
  command = (char *) malloc( (size + argc + 11) * sizeof(char) );
  sprintf(command, "/bin/bash %s", argv[1]);
  if (argc > 2) {
    for (i = 2; i < argc; i++) {
      sprintf(command, "%s %s", command, argv[i]);
    }
  }

  // Execute the command
  system(command);

  // free memory
  free(command);

  return 0;
}

The exercise was not only to solve my problem, but it was also a way to get more into C, so what do you suggest? Is there anything I should improve?


texts: Uniform random numbers in an integer interval in C

texts:
I need to generate random integers inside a range [a, b] in C. I used the normal implementation that you will see everywhere on the internet and wrote the following:

/**
 * randRange Generates random integers in range
 * @param lower Lower bound
 * @param upper Upper bound
 * @return random integer between lower and upper (inclusive)
 */
int randRange(int lower, int upper) {
    return rand() % (++upper - lower) + lower;
}

Now, this works just fine, but the distribution over the range really isn't good, and it's starting to cause secondary algorithms I have to behave badly. How can I improve that function so that it is:

Not biased
Doesn't rely on anything not on the standard library
Is suitable for a Monte Carlo algorithm
Fast


texts: KDF computation using CMAC with AES (as PRF) using Bouncy Castle C# library

texts:
Using bouncy castle .net implementation (version: 1.8.1.0), I am trying to create an encryption key from a known master key using a key derivation function. The NIST Publication 800-108 contains recommendation for key derivation using pseudorandom functions (PRF). This document has several KDF modes defined in it. I am trying to use KDF in Counter Mode (as outlined in section 5.1). This (as other KDF modes in this spec) use PRF, which according to section 4 can be HMAC or CMAC.

Can some one please take a look at the following code and comment on the correctness of this code?

    [TestMethod]
    public void CanCreateKdfWithCounterModeUsingCmacWithAesCipher()
    {
        var masterKeyHex = "5F0D130486609AEEF68A98E7793FB7EA";  //16 bytes
        Console.WriteLine($"masterKeyHex: {masterKeyHex}");

        // Ki = PRF (s, x) where s = Key, x = [i]2 || Label || Separator || Context || [L]2
        var counterParamHex = "01";
        var labelParamHex = "000000000000000000000004";
        var seperatorParamHex = "00";
        var contexParamHex = "77FA54DE8019D742E48F4682CBE55332";
        var lParamHex = "0100";

        //x = 0x01 || 0x000000000000000000000004 || 0x00 || 0x77FA54DE8019D742E48F4682CBE55332 || 0x0100
        var xHex = counterParamHex + labelParamHex + seperatorParamHex + contexParamHex + lParamHex;

        var sBytes = Utility.HexToBytes(masterKeyHex);
        var xBytes = Utility.HexToBytes(xHex);

        IBlockCipher cipher = new AesEngine();
        ICipherParameters cipherParameters = new KeyParameter(sBytes);
        IMac mac = new CMac(cipher);
        mac.Init(cipherParameters);
        mac.BlockUpdate(xBytes, 0, xBytes.Length);

        var kIBytes = new byte[16];
        var doFinalReturn = mac.DoFinal(kIBytes, 0);

        Console.WriteLine($"doFinalReturn: {doFinalReturn}");
        Assert.AreEqual(kIBytes.Length, doFinalReturn);

        var kIHex = Utility.BytesToHex(kIBytes);
        Console.WriteLine($"kIHex: {kIHex}");
    }


texts:
A simple reworking of the Bash date command to my own personal liking. Possibly a rather trivial task; I just wanted the date and time to be in the form of:

Fri Sep 2 2016
11:37 P.M.

I think this accomplishes that:

#!/bin/bash

today() {
    now="$(date | awk '{ OFS=" "; print $1,$2,$3,$6 }')"
    h="$(date "+%H")"
    m="$(date "+%M")"
    if [ $h -gt 12 ]; then
        echo -e "$now\n$(( $h - 12 )):$m P.M."
    elif [ $h = 12 ]; then
        echo -e "$now\n$h:$m P.M."
    elif [ $h = 00 ]; then
        h=12; echo -e "$now\n$h:$m A.M."
    elif [ $h -le 11 ]; then
        if [ $h -lt 10 ]; then
            h="$(echo $h | cut -c2)"
        fi
        echo -e "$now\n$h:$m A.M."
    fi
}

today

Is there anything I could do to improve this?


texts:
Task: Transform sentence to n-gram and remove all punctuation

Tests:

  Input:  ngram('Name, + other ~ name!', 1)

  Result: ['Name', 'other', 'name']

  Input: ngram('Name, + other ~ name!', 2)

  Result: ['Name other', 'other name']

  Input: ngram('Name, + other ~ name!', 10)

  Result: ['Name other name']

  Input: ngram('Мене також.', 10)

  Result: ['Мене також']

Code:

function ngram(data, order) {
    const regex = /[^A-Za-zА-ЯЄІЇа-яєії0-9_']/g
    let ngramsArray = []

    data = data
      .replace(regex, ' ')
      .split(' ')
      .filter(element => element.length > 0)

    if (order > data.length) {
      order = data.length
    }

    for (let i = 0; i < data.length - (order - 1); i++) {
      let subNgramsArray = []

      for (let j = 0; j < order; j++) {
        subNgramsArray.push(data[i + j])
      }

      ngramsArray = [...ngramsArray, subNgramsArray.join(' ')]
    }

    return ngramsArray
  }


texts: Identifying Polylines and operating on field values

texts:
I'm using Python 2.7.5 in a GIS environment (namely: QGIS 2.8.1, or PyQGIS).

  sys.version_info(major=2, minor=7, micro=5, releaselevel='final', serial=0)

The aim is to identify spatially identical Polylines (i.e. overlapping) and sum a value from a selected field. For other polylines with no matches, the code just replicates those with their original field values.

path='D:/Documents/qgis/lines_same/Lines.shp'  # Enter your SHP file path
Val='Value'                      # Enter the field name you would like to summarize
from PyQt4.QtCore import *
layer = QgsVectorLayer(path,'Lines', 'ogr')
tmp = QgsVectorLayer("LineString", "tmp_output", "memory")
dp = tmp.dataProvider()
tmp.startEditing()
dp.addAttributes ( [ QgsField("ID", QVariant.Int),
        QgsField("IDsub", QVariant.Int),
        QgsField("ValueSum", QVariant.Int) ] )
iter = layer.getFeatures()
for feature in iter:
    CreateVerify = 0
    geom = feature.geometry()
    geom = geom.asPolyline()
    ID = feature.id()
    Value = feature[Val]
    iterSub = layer.getFeatures()
    for featureSub in iterSub:
        geomSub = featureSub.geometry()
        geomSub = geomSub.asPolyline()
        IDsub = featureSub.id()
        ValueSub = featureSub[Val]
        if (geom==geomSub and ID!=IDsub):
            CheckExist = tmp.getFeatures()
            Exist = 0
            for exs in CheckExist:
                if (exs.geometry().asPolyline() == geom):
                    Exist = Exist + 1
            if (CreateVerify == 0 and Exist == 0):
                CreateVerify = 1
                New = QgsFeature()
                New.setGeometry (QgsGeometry.fromPolyline(geom))
                New.setAttributes([ID, IDsub, Value + ValueSub])
                dp.addFeatures([ New ])
                tmp.commitChanges()
            elif (Exist > 0):
                CreateVerify = 1
    if (CreateVerify == 0):
        New = QgsFeature()
        New.setGeometry (QgsGeometry.fromPolyline(geom))
        New.setAttributes([ID,-99, Value])
        dp.addFeatures([ New ])
        tmp.commitChanges()
    QgsMapLayerRegistry.instance().addMapLayer(tmp)

I used many for loops to iterate through features and it seems too brute to me. mainly those two nested for loops:

for featureSub in iterSub: # to compare geometries and search for matches

and

for exs in CheckExist: # to prevent duplicates from being created, if there is a match

I would greatly appreciate any help to make it more efficient.


texts:
I have created a sample file reading program as an exercise while learning how to implement good exception handling. I want to ask: is this a good approach or is there some other solution that I am not aware of?

import java.util.*;  // Needed for Scanner and InputMismatchException
import java.io.*;    // Needed for FileReader and FileNotFoundException

/**
 * This class reads two numbers from a file and
 * print their sum.
 */

public class ReadNum
{
   public static void main (String[] args)
   {
       Scanner inFile = null;
       try
       {
           int num1, num2;  // To hold numbers read from the file
           int sum; //To hold sum

           // Create the scanner object for file input.
           inFile = new Scanner(new FileReader("sample.txt"));

           // Read numbers from the file.
           num1 = inFile.nextInt();
           num2 = inFile.nextInt();

           // Calculate total.
           sum = num1 + num2;

           // Print total.
           System.out.println("sum " + sum);
       }
       catch (FileNotFoundException ex)
       {
           System.out.println("Error "+ ex);
       }
       catch (InputMismatchException ex)
       {
           System.out.println("Error "+ ex);
       }
       catch (Exception ex)
       {
           System.out.println("Error "+ ex);
       }
       finally
       {
           // Close the file.
           if(inFile != null)
                inFile.close();
       }
   }
}


texts:
I'm learning C and one of the questions I've been asked is converting a string to an integer. The code I've written supports converting from a string in any base up to 16/hex to an integer. There is no  over/underflow checking and it does not support lowercase hex.

int ASCIIToInteger(char *x, int base)
{
    //Each element is the ASCII for it's index.
    int ASCIICodes[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };  _Bool negative = 0;
    int count = 0, output = 0;
    if (x[0] == '-')
    {
        negative = 1;
        count = 1;
    }
    else if (x[0] == '+')
    {
        count = 1;
    }
    do
    {
        for (int i = 0; i < base; i++)
        {
            if (ASCIICodes[i] == (int)x[count])
            {
                output = output * base + i;
                break;
            }
        }
        count++;
    } while (x[count] != 0);

    if (negative == 1)
    {
        return ~output + 1;
    }
    return output;
}

Can I please get some advice regarding any possible issues or "rookie mistakes" I may have made?


texts: How can I make handling multiple {}.get('value', {}.get('foo')) pretty?

texts:
I ran into an issue where I was doing this:

dictionary1 = {}
dictionary2 = {}
foo = dictionary1.get('foo', dictionary1.get('bar', dictionary2.get('baz')))

I.e. if the value isn't supplied in one dict, it would fall back on the next and then on the next. In this case dictionary1 has a key that is deprecated that I'm getting in case the new style on isn't there, dictionary2 is completely different. It looks pretty ugly though, the alternative seem to be to break it up across multiple lines like:

foo = dictionary2.get('baz')
foo = dictionary1.get('bar', foo)
foo = dictionary1.get('foo', foo)

Which might be better, though it seems like it could be confusing to read the code in the reverse order. I wonder if there's an alternative more straight forward and prettier solution?


texts:
I want to run the timer at 2:00 a.m. and shutdown the application.
This is my code:

  var ShutdownTimer = new Timer();
  var currentTime = DateTime.Now;

  int hoursUntilShutdown;

  switch (currentTime.Hour)
  {
    case 1:
      hoursUntilShutdown = 1;
      break;

    case 2:
      hoursUntilShutdown = 0;
      break;

    default:
      hoursUntilShutdown = (24 - currentTime.Hour) + 2;
      break;
  }

  var shutdownTimeSpan = new TimeSpan(0, hoursUntilShutdown, 0, 0);
  ShutdownTimer.Interval = (int)shutdownTimeSpan.TotalMilliseconds;
  ShutdownTimer.Tick += this.OnShutdownTimer;
  ShutdownTimer.Start();

   private void OnShutdownTimer(object sender, EventArgs e)
   {
       Environment.Exit(0);
   }

Any help will be greatly appreciated!


texts:
I'm working my way through The Java Programming Language, Fourth Edition - The Java Series.  This is Exercise 7.3:

  Write a program that calculates Pascal's triangle to a depth of 12, storing each row of the triangle in an array of the appropriate length and putting each of the row arrays into an array of 12 int arrays. Design your solution so that the results are printed by a method that prints the array of arrays using the lengths of each array, not a constant 12. Now change the code to use a constant other than 12 without modifying your printing method.

Is the following an adequate solution? Is my use of exception handling reasonable for this use case?

/**
 * Defines Pascal's Triangle
 */
public class PascalsTriangle {
    private final long[][] triangle;

    /**
     * Sole constructor
     *
     * @param depth the depth of the triangle
     */
    PascalsTriangle(int depth) {
        triangle = new long[depth][];
        long upperLeft;
        long upperRight;

        for (int i = 0; i < depth; i++) {
            triangle[i] = new long[i + 1];

            for (int j = 0; j < i + 1; j++) {
                if(i == 0) {
                    triangle[i][j] = 1; //seed the triangle
                }
                else {
                    try {
                        upperLeft = triangle[i - 1][j - 1];
                    } catch (ArrayIndexOutOfBoundsException e) {
                        upperLeft = 0; //upperLeft is 0 if not found
                    }

                    try {
                        upperRight = triangle[i - 1][j];
                    } catch (ArrayIndexOutOfBoundsException e) {
                        upperRight = 0; //upperRight is 0 if not found
                    }

                    triangle[i][j] = upperLeft + upperRight;
                }
            }
        }
    }

    /**
     * Prints the triangle to System.out
     */
    public void printTriangle() {
        for (long[] iTriangle : triangle) {
            for (long jTriangle : iTriangle) {
                System.out.printf("%d ", jTriangle);
            }
            System.out.println();
        }
    }

    /**
     * Main method - create and print a triangle
     */
    public static void main(String[] arg) {
        PascalsTriangle triangle = new PascalsTriangle(10);
        triangle.printTriangle();
    }
}


texts:
I'd like to know if i respect strlcat(3) behiour with my implementation, cause i'm not really sure to understand strlcat particular behaviour

int my_strlcat(char *dest, char *src, int size)
{
  int i;
  int src_len;
  int dest_len;

  i = 0;
  dest_len = strlen(dest);
  src_len = strlen(src);
  if (size <= 0)
   return dest_len;
  while (dest_len < size)
  {
    dest[dest_len] = src[i];
    dest_len++;
    i++;
  }
  dest[dest_len] = '\0';
  return (strlen(dest));
}


texts: Implementation of a controlled job with Java

texts:
I am trying to implement a controlled job with java that initiates a new thread and provides a method to stop the execution of the thread without having to maintain the context.

The interface looks like:

public interface ControlledJob {

    void stop();

    void start();

    boolean isJobRunning();
}

And the implementation looks like:

import com.google.common.base.Preconditions;

public class SampleControlledJob implements ControlledJob {

    private static final String JOB_ALREADY_RUNNING_EXCEPTION_MESSAGE = "Job is already running.";
    private static final String JOB_ALREADY_STOPPED_EXCEPTION_MESSAGE = "Job is already stopped.";

    private final static SampleControlledJob SAMPLE_CONTROLLED_JOB = new SampleControlledJob();
    private final Process process;

    private boolean isJobRunning = false;
    private boolean toContinue = false;
    private Thread thread;
    private String threadName;

    private SampleControlledJob() {
        this.process = new Process();
    }

    public static ControlledJob getInstance() {
        return SAMPLE_CONTROLLED_JOB;
    }

    @Override
    public void start() {
        Preconditions.checkArgument(!this.isJobRunning, JOB_ALREADY_RUNNING_EXCEPTION_MESSAGE);
        this.threadName = "Thread:" + System.currentTimeMillis();
        this.thread = new Thread(this.process, threadName);
        this.toContinue = true;
        this.isJobRunning = true;
        this.thread.start();
    }

    @Override
    public void stop() {
        Preconditions.checkArgument(this.isJobRunning, JOB_ALREADY_STOPPED_EXCEPTION_MESSAGE);
        this.toContinue = false;
    }

    @Override
    public boolean isJobRunning() {
        return isJobRunning;
    }

    private class Process implements Runnable {
        public void run() {
            while (toContinue) {
                System.out.println(threadName + ", prints hello::" + System.currentTimeMillis());
            }
            isJobRunning = false;
        }
    }
}

The client can use the API like:

SampleControlledJob.getInstance().start();
SampleControlledJob.getInstance().stop();


texts: Using static final Strings for SQL Query in Spring Boot

texts:
This is regarding code quality and coding standards with respect to Spring Ecosystem. Here there are two methods:

isRecordExists is using a class level static constant String query. (Definitely suggestable for old way where we use prepared statements)
isRecordExists2 is using method level String query

Which method is better (isRecordExists or isRecordExists2) in context with  Spring Boot?

@Repository
public class SpringRepository {

    @Autowired
    private NamedParameterJdbcTemplate namedParamJdbcTemplate;

    private static final String QUERY = " select * from Dual where created_date=:date";

    public void isRecordExists(Date date){
       /**
       *  using constant for sql Query String at class level
       */
         MapSqlParameterSource parameters = new MapSqlParameterSource();
         parameters.addValue("date", date);
         namedParameterJdbcTemplate.queryForObject(QUERY, parameters, Integer.class);

    }
   public void isRecordExists2(Date date){
         String sqlQuery=" select * from Dual where created_date=:date";
       /**
       *  using  sql Query at method level
       */
         MapSqlParameterSource parameters = new MapSqlParameterSource();
         parameters.addValue("date", date);
         namedParameterJdbcTemplate.queryForObject(sqlQuery, parameters, Integer.class);

    }


texts: Handle database validation (exists, unique constraint, etc)

texts:
Let's assume you are writing a REST Api with a common structure like Controller > Service > Repository > Database.
In the database there's a table with a column with a unique constraint:
   // Examples with typeorm/typescript

   // user.entity.ts
   @Entity()
   export class User {
      @PrimaryGeneratedColumn()
      id: number;

      @Unique()
      @Column()
      email: string;

      // Other properties
   }

In the updateUser method you have to check if the user exists and if the user email is not used by another one.
Which one of the following approaches would it be better?
A) Interrogate the database to check if the user with the given id exists and do it again to make sure there's not another user with the same email:
   // users.service.ts
   @Entity()
   export class UsersService {
      async updateUser(user: UserDTO): Promise<UserDTO> {
         const userById = await this.repository.findOne(user.id);
         if (!userById) {
            throw new Error('User does not exist');
         }

         const userWithSameEmail = await this.repository.findOne({
            where: { id: Not(user.id), email: user.email }
         });
         if (userWithSameEmail) {
            throw new Error('Email already in use');
         }

         // Handle errors with some interceptor
         // Rest of the method
      }
   }

B) Database calls could lead to performance issues. The orm will anyway throw an error in case of invalid input:
   @Entity()
   export class UsersService {
      async updateUser(user: UserDTO): Promise<UserDTO> {
         try {
            const updatedUserEntity = await this.repository.update(user);

            // Rest of the method
         }
         catch (e) {
            // Handle error
         }
      }
   }

Quick bonus question
Should the service layer be aware about entities and handle operations like receive the updatedUserEntity from the repository, map it to the DTO and return it to the level above?


texts:
I have a bare-bones example of how I plan to load excel sheets into pandas data frames. However, the code runs unexpectedly slow. I'm open to suggestions on ways I can speed this up, even converting the source files to a different file format. Anything to make it snappier because I will need a loop to do this several times over multiple sheets and workbooks. Thank you.

import os
import pandas as pd

path_to_data_files = 'C:/DataArchive/'
files = sorted(os.listdir(path_to_data_files), reverse=True)

file = pd.ExcelFile(path_to_data_files + files[0])

sheet_names = file.sheet_names

df = file.parse(sheets[0])


texts: Simplified Kata of BankOCR using Shapeless

texts:
I attempted to solve a simplification of User Story 2 using shapeless:

Namely, define the implementation of:

trait IsValid[A]
object IsValid {

  def apply[L <: HList](implicit ev: IsValid[L]) = ev
}

where valid means (per my simplification):

  given 2 digits, it's valid if (A * 1 + b * 0) mod 5 == 0

So, (5, 0) is valid since (5*1) + (0*0) mod 5 == 0 is true.

But, (4, 1) is not since it does not satisfy the above equation.

Here's my full implementation:

package net

import shapeless._, ops.hlist.IsHCons
import nat._
import ops.nat.{ Mod, Prod, Sum }

trait IsValid[A]
object IsValid {

  // simplified: given 2 digits, it's valid if (A * 1 + b * 0) mod 5 == 0
  def apply[L <: HList](implicit ev: IsValid[L]) = ev

  implicit def validNumber[L <: HList, H <: HList, A <: Nat, B <: Nat,
                P1 <: Nat, P2 <: Nat, S <: Nat](
     implicit evA: IsHCons.Aux[L, A, H],
     evB: IsHCons.Aux[H, B, HNil],
     prod1: Prod.Aux[_1, A, P1],
     prod2: Prod.Aux[_0, B, P2],
     sum: Sum.Aux[P1, P2, S],
     mod: Mod.Aux[S, _5, _0]
   ): IsValid[L] = new IsValid[L] {}

}

Testing:

// (5*1) + (10*0) mod 5 === 0 (true)
scala> IsValid[_5 :: _10 :: HNil]
res4: net.IsValid[shapeless.::[shapeless.nat._5,shapeless.::[shapeless.nat._10,shapeless.HNil]]] = net.IsValid$$anon$1@160627b3

// (10*1) + (10*0) mod 5 === 0 (true)
scala> IsValid[_10 :: _10 :: HNil]
res5: net.IsValid[shapeless.::[shapeless.nat._10,shapeless.::[shapeless.nat._10,shapeless.HNil]]] = net.IsValid$$anon$1@3f3f03a3

// (3*1) + (10*0) mod 5 === 0 (false)
scala> IsValid[_3 :: _0 :: HNil]
<console>:19: error: could not find implicit value for parameter ev: net.IsValid[shapeless.::[shapeless.nat._3,shapeless.::[shapeless.nat._0,shapeless.HNil]]]
       IsValid[_3 :: _0 :: HNil]
              ^

// 3 digits are not allowed, only 2
scala> IsValid[_5 :: _0 :: _1 :: HNil]
<console>:19: error: could not find implicit value for parameter ev: net.IsValid[shapeless.::[shapeless.nat._5,shapeless.::[shapeless.nat._0,shapeless.::[shapeless.nat._1,shapeless.HNil]]]]
       IsValid[_5 :: _0 :: _1 :: HNil]
              ^

Please critique my approach.


texts: Number of files with specific file size ranges

texts:
I am trying to write a script that will traverse through my directory and sub directory and list the number of files in a specific size.

For example, 0kb-1kb: 3, 1kb-4kb:4, 4-16KB: 4, 16kb-64-kb:11. This goes on in multiples of 4.

I am able to get the list of file numbers, the size in human readable format and find the number of files in a size group. But I feel my code is very messy and not anywhere near the standard.

import os
suffixes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB']
route = raw_input('Enter a location')
def human_Readable(nbytes):
    if nbytes == 0: return '0 B'
    i = 0
    while nbytes >= 1024 and i < len(suffixes)-1:
        nbytes /= 1024.
        i += 1
    f = ('%.2f' % nbytes).rstrip('0').rstrip('.')
    return '%s %s' % (f, suffixes[i])
def file_Dist(path, start,end):
    counter = 0
    for path, subdir, files in os.walk(path):
        for r in files:
            if os.path.getsize(os.path.join(path,r)) > start and os.path.getsize(os.path.join(path,r)) < end:
                counter += 1
        print "Number of files greater than %s less than %s:" %(human_Readable(start), human_Readable(end)),  counter
file_Dist(route, 0, 1024)
file_Dist(route,1024,4095)
file_Dist(route, 4096, 16383)
file_Dist(route, 16384, 65535)
file_Dist(route, 65536, 262143)
file_Dist(route, 262144, 1048576)
file_Dist(route, 1048577, 4194304)
file_Dist(route, 4194305, 16777216)


texts: Caesar cipher using ASCII character codes

texts:
This function should take in a string and a number as parameters and 'rotate' the string to the equivalent alphabet letter that is located at the letter position + 'rotation' parameter.
E.g.: "stackoverflow" --- "fgnpxbiresybj"
def caesar(inputString, rotation = 1):
    zNum = ord('z')
    alphaLen = 26

    result = []
    for c in inputString:
        charNum = ord(c) + rotation
        if charNum > zNum:
            result.append(chr(charNum - alphaLen))
        else:
            result.append(chr(charNum))

    return ''.join(result)


texts: Simplifying `if` statements in Tic Tac Toe function

texts:
I'm currently trying to improve my coding skills, so I'm trying to code a Tic Tac Toe game. At one point a "win check" is needed.I'm using this code to check:

public void CheckWin(States state)
{
    if(fieldA1.GetState == state && fieldA2.GetState == state && fieldA3.GetState == state)
        ReportWin(currentPlayer);
    else if(fieldB1.GetState == state && fieldB2.GetState == state && fieldB3.GetState == state)
        ReportWin(currentPlayer);
    else if (fieldC1.GetState == state && fieldC2.GetState == state && fieldC3.GetState == state)
        ReportWin(currentPlayer);
    else if (fieldA1.GetState == state && fieldB1.GetState == state && fieldC1.GetState == state)
        ReportWin(currentPlayer);
    else if (fieldA2.GetState == state && fieldB2.GetState == state && fieldC2.GetState == state)
        ReportWin(currentPlayer);
    else if (fieldA2.GetState == state && fieldB2.GetState == state && fieldC2.GetState == state)
        ReportWin(currentPlayer);
    else if (fieldA3.GetState == state && fieldB3.GetState == state && fieldC3.GetState == state)
        ReportWin(currentPlayer);
    else if (fieldA1.GetState == state && fieldB2.GetState == state && fieldC3.GetState == state)
        ReportWin(currentPlayer);
    else if (fieldA3.GetState == state && fieldB2.GetState == state && fieldC1.GetState == state)
        ReportWin(currentPlayer);
    else
        PlayerSwitch();
}

This code looks very unclean to me.  Is there a better way to handle these if instructions?


texts: Search for row number of maximum value in matrix column

texts:
Background

I'm writing code that searches for the row number of the maximum value in a partial column of a matrix.  The partial column corresponds with the non-zero values of an equivalent lower triangular matrix.  That is, starting from the input row index idx through the final row. (This is my own version of subroutine for Gaussian Elimination with Partial Pivoting, for those who are interested).

Basically, the behavior of MaxLocColumnWise is the search of columnwise maximum location in the submatrices of A. Passing by reference, MaxLocColumnWise changes the value of k.

For example, for the following matrix
$$
A = \begin{bmatrix}1 & 2 & 3 \\
4 & 5 & 6 \\
7 & 8 & 9
\end{bmatrix}
$$

when k=0, MaxLocColumnWise(A,k) converts k to the index of maximum element in [1,4,7], which is 2, which is the index of 7 i.e. we get 2 as a result of

    int k = 0;
    `MaxLocColumnWise(A,k)`;
    std::cout << k <<"\n";

when k=1, MaxLocColumnWise(A,k) converts k to the index of maximum element in [5,8], which is 2, which is the index of 8. (This case is highlighted in red here)
when k=2, MaxLocColumnWise(A,k) converts k to the index of maximum element in [9], which is 2, which is the index of 9

Code

Interestingly it turns out that the following code takes quite long time.

void MaxLocColumnWise(Matrix A, int &idx){
    int n = A.size();
    int col = idx;

    double currentAbsMax = abs(A[col][col]);

    for (int i=(col+1); i<n; i++){
        double currentVal = abs(A[i][col]);
        if (currentVal > currentAbsMax){
            currentAbsMax = currentVal;
            idx = i;
        }
    }
}

I have implemented this subroutine to the following Gaussian elimination with partial pivoting routine:

void GaussElimPartialPivot(Matrix& A, Vector& b){
    int n = A.size();

    for (int j=0; j<(n-1); j++){
        int index = j;
        MaxLocColumnWise(A, index);
        SwapMatrixRows(A, j, index);
        SwapVector(b, j, index);

        // main loop
        for (int i=(j+1); i<n; i++){
            double m = A[i][j]/A[j][j];
            b[i] -= m*b[j];
            for(int k=j; k<n; k++){
                A[i][k] -= m*A[j][k];
            }
        }
    }
}

But when A gets large, the program gets slower exactly due to the subroutine MaxLocColumnWise, which was verified from excluding each subroutine in the main code.

But I'm not sure exactly where in MaxLocColumnWise() to blame. Any help will be appreciated.

(An excuse for the exclusion of the code : Matrix is just from typedef std::vector<Vector> Matrix;, and the Vector is typedef std::vector<double> Vector;)


texts: Using composition or inheritance to enhance this linked list

texts:
Problem Statement:

  A method called insertEnd() exists, but it runs in linear time, because every time it is called, it walks down the list to find the end.  Without changing the meaning of this method or any other, modify the representation of a SList and whatever methods are necessary to make insertEnd() run in constant time. Your SList class will need to continually maintain a record of the last (tail) SListNode in an SList, and all SList's methods will have to ensure that this record stays current.

SList class & SListNode class are already provided in the assignment as shown below:

SListNode

/* SListNode.java */
class SListNode {
  Object item;
  SListNode next;

  /**
   *  SListNode() (with two parameters) constructs a list node referencing the
   *  item "obj", whose next list node is to be "next".
   */

  SListNode(Object obj, SListNode node) {
    item = obj;
    this.next = node;
  }

  /**
   *  SListNode() (with one parameter) constructs a list node referencing the
   *  item "obj".
   */

  SListNode(Object obj) {
    this(obj, null);
  }
}

SList

/* SList.java */

  public class SList {

  protected SListNode head;
  protected int size;

  /**
   *  SList() constructs an empty list.
   **/

  public SList() {
    size = 0;
    head = null;
  }

  /**
   *  insertFront() inserts item "obj" at the beginning of this list.
   *  @param obj the item to be inserted.
   **/

  public void insertFront(Object obj) {
    head = new SListNode(obj, head);
    size++;
  }

  /**
   *  insertEnd() inserts item "obj" at the end of this list.
   *  @param obj the item to be inserted.
   **/

  public void insertEnd(Object obj) {
    if (head == null) {
      head = new SListNode(obj);
    } else {
      SListNode node = head;
      while (node.next != null) {
        node = node.next;
      }
      node.next = new SListNode(obj);
    }
    size++;
  }
}

Below is the solution for the given problem:

TailList

/* TailList.java */

public class TailList extends SList{
    private SListNode tail;

    public TailList(){
        tail = null;
    }

    /**
     *  insertEnd() inserts item "obj" at the end of this list.
     *  @param obj the item to be inserted.
     **/

    public void insertEnd(Object obj) {
        if(this.size > 0){
            SListNode node  = new SListNode(obj);
            this.tail.next = node;
            this.tail = node;
        }else{
            this.head = this.tail = new SListNode(obj);
        }
        this.size++;
    }

    /**
     *  insertFront() inserts item "obj" at the beginning of this list.
     *  @param obj the item to be inserted.
     **/

    public void insertFront(Object obj){
        super.insertFront(obj);
        if(size == 1){
            tail = head;
        }
    }
}

My question:

Does TailList class inheritance relation with SList implementation class looks fine(within same package)? How do I know whether SList class is specifically designed for inheritance, as mentioned below?

  It is safe to use inheritance within a package, where the subclass and the superclass implementations are under the control of the same programmers. It is also safe to use inheritance when extending classes specifically designed and documented for extension
  (Item 17). Inheriting from ordinary concrete classes across package boundaries,
  however, is dangerous. As a reminder, this book uses the word “inheritance” to mean implementation inheritance (when one class extends another). The problems discussed in this item do not apply to interface inheritance (when a class implements an interface or where one interface extends another).


texts: OOP implementation of Rock Paper Scissors game logic in Java

texts:
What is your opinion on my solution for Rock Paper Scissors game logic in Java?
Round outcome enum class
public enum Winer
{
    DRAW,
    PLAYER,
    COMPUTER;
}

Played moves enum class
public enum PlayedMove
{
    ROCK,
    PAPER,
    SCISSORS;
}

Game logic class
public class GameLogic
{
    public static Winer getWiner(PlayedMove player, PlayedMove computer)
    {
        if (player == computer)
        {
            return Winer.DRAW;
        }
        else if (isPlayerWiner(player, computer))
        {
            return Winer.PLAYER;
        }
        else
        {
            return Winer.COMPUTER;
        }
    }

    private static boolean isPlayerWiner(PlayedMove player, PlayedMove computer)
    {
        return ((player == PlayedMove.ROCK && computer == PlayedMove.SCISSORS)
             || (player == PlayedMove.SCISSORS && computer == PlayedMove.PAPER)
             || (player == PlayedMove.PAPER && computer == PlayedMove.ROCK));
    }
}


texts:
I am computing factorials as part of teaching myself C++. I am looking for feedback on efficiency, style and any bad practices I may be using.

#include <iostream>
#include <climits>

using namespace std;

int main()
{
    unsigned int number{ 0 };
    unsigned long long factorial{ 0 };
    cout << "The factorial of a non-negative integer n is denoted as n! (n factorial)...\n" <<
        "Example: 5! = 5x4x3x2x1 = 120\n\n";

    cout << "Enter a non-negative integer and we will compute the factorial: ";
    cin >> number;
    while (cin.rdstate() || number < 0 || number > LLONG_MAX)
    {
        cin.clear();
        cin.ignore(LLONG_MAX, '\n');//flush input buffer
        cout << "The data entered was invalid. Try again?\n\n" << endl;
        cout << "Enter a non-negative integer and we will compute the factorial: ";
        cin >> number;
    }
    if (number == 0 || number == 1)//since 0! and 1! = 1 there is no need to do a calculation
    {
        cout << "!" << number << " = 1" << endl;
    }
    else
    {
        factorial = number * (number - 1);
        for (size_t i = 2; i < number; ++i)
        {
            factorial *= (number - i);
        }
        cout << number << "! = " << factorial << endl;
    }
}


texts: Calculating distance and time between waypoints for large files

texts:
This is very similar to other code I've posted, however this is designed for very large CSV files, for example 35GB.

The files typically look like this:

9e77d54918dd25c3f9d2e5354ec86666,0,2015-10-01T14:14:15.000Z,45.0988,7.5811,,
9e77d54918dd25c3f9d2e5354ec86666,1,2015-10-01T14:17:15.000Z,45.0967,7.5793,,
9e77d54918dd25c3f9d2e5354ec86666,2,2015-10-01T14:20:15.000Z,45.1012,7.6144,,
9e77d54918dd25c3f9d2e5354ec86666,3,2015-10-01T14:23:15.000Z,45.0883,7.6479,,
9e77d54918dd25c3f9d2e5354ec86666,4,2015-10-01T14:26:15.000Z,45.0774,7.6444,,
9e77d5jhg35hg345hghge5354ec84751,0,2015-10-04T22:36:32.000Z,48.0723,7.6442,,
ect...

The code I've written works out the sum of the distance between each of the waypoints, as well as the time taken and total number of waypoints. Here it is in entirety:

import pandas as pd
import numpy as np

EarthRadius = 6371 #km

def distance(group): #calculate distances using Equirectangular approximation
    lat = np.radians(group.Lat)
    lon = np.radians(group.Lon)
    endLon = lon.shift(-1)
    endLat = lat.shift(-1)
    x = (endLon - lon) * np.cos(0.5 * (endLat + lat))
    y = endLat - lat
    D = EarthRadius * np.sqrt(x**2 + y**2)
    return D.sum()

def timedelt(group):  #calculate length of trip
    a = np.around((pd.to_datetime(group['Date']).max() - pd.to_datetime(group['Date']).min()).seconds/60, decimals=2)
    return a

def tripStatistics(trip):#Helper function to output distance and number of waypoints
    return pd.Series({"TripID":chunk.iloc[0,0],"Distance": distance(trip),"No. of Waypoints": len(trip),"Time Taken(Mins)": timedelt(trip)})

def iterateIDs(file): #create chunks based on tripID
    csv_reader = pd.read_csv(file, iterator=True, chunksize=1, header=None, usecols=[0, 2, 3, 4],names=['TripID', 'Date', 'Lat', 'Lon'])
    first_chunk = csv_reader.get_chunk()
    id = first_chunk.iloc[0,0]
    chunk = pd.DataFrame(first_chunk)
    for l in csv_reader:
        if id == l.iloc[0,0]:
            id = l.iloc[0,0]
            chunk = chunk.append(l)
            continue
        id = l.iloc[0,0]
        yield chunk
        chunk = pd.DataFrame(l)
    yield chunk

output = pd.DataFrame(columns=['TripID','Distance','No. of Waypoints','Time Taken(Mins)'])
chunkIterate = iterateIDs("TripRecordsReportWaypoints.csv")

for chunk in chunkIterate:
    temp = tripStatistics(chunk)
    output = output.append(temp, ignore_index=True)

output['Waypoint Frequency(Secs)'] = np.around(60*output['Time Taken(Mins)']/output['No. of Waypoints'], decimals=2)
output.reset_index().to_csv('TripDetails.csv', sep=',', index=False)

I'm wondering if there is anything in my code that might slow down processing speeds. I set it running on the previously mentioned 35GB file and it's been going for over 24 hours now. It's the first time I've used generators so I hope I've not made some simple error.

As a bit of a comparison, I had written a previous piece of code that is similar but without splitting the CSV file into chunks with the iterateIDs generator function. It processed a 200MB file in 100 seconds. A linear extrapolation of that would mean it would take only 3 hours to process a 35GB file.


texts: Count number of nodes in a binary tree the OO way

texts:
I am trying to write a simplify the algorithm of finding the number of nodes in a binary tree by using good object oriented design. I have been into good OOP style recently and found it really compelling in way that it can simplify the mental load by proper polymorphism.

Having said that, I don't know if it's a right strategy to follow in the interview since it may take some time to get to a good design.

import java.util.*;
import java.lang.*;
import java.io.*;

interface Node {
    public int count();
}

class Empty implements Node {
    public int count() {
        return 0;
    }
}

class NonEmpty<Item> implements Node {
    private final Item item;
    private final Node left;
    private final Node right;

    NonEmpty(Item item) {
        this(item, new Empty(), new Empty());
    }

    NonEmpty(Item item, Node left, Node right) {
        this.item = item;
        this.left = left;
        this.right = right;
    }

    public int count() {
        return left.count() + right.count() + 1;
    }
}

/* Name of the class has to be "Main" only if the class is public. */
class Main
{
    public static void main (String[] args) throws java.lang.Exception
    {
        Node n = new Empty();
        System.out.println(n.count()); // 0

        // Single node tree
        n = new NonEmpty(5);
        System.out.println(n.count()); // 1

        // Complete Full tree
        n = new NonEmpty(5, new NonEmpty(2), new NonEmpty(6));
        System.out.println(n.count()); // 3

        // Right skewed
        n = new NonEmpty(5, new NonEmpty(2, new NonEmpty(6), new Empty()), new Empty());
        System.out.println(n.count()); // 3
    }
}

I am thinking to write some common Tree based algorithm this way and see how far I can go.

Questions:

Is this a good strategy for interviews?
Have I divided the responsibility correctly?
Does this scale well to other tree-based algorithms?

Major Doubt:

I have seen in books such as this the author focuses on different classes like for above it could be:

class CountNodes {
  public CountNodes(Node n) {
    //...
  }
}

Which is a better strategy?


texts:
Based on the previous question, I have improved it to make it insert regular function. Also, I have implemented a new template approach to obtain the signature from any function by testing its operator().

I would like to know how I can improve it further.

#include <functional>
#include <typeindex>
#include <string>
#include <tuple>
#include <map>
#include <cassert>
#include <iostream>
#include <memory>

////////////////////////// Meta Data ////////////////////////////////
template<typename F>
struct Signature_helper;

template<typename F, typename R, typename... Ts>
struct Signature_helper<R(F::*)(Ts...) const>
{
    using type = R(Ts...);
    using result_type = R;
};

template<typename F>
#define TRAIT_CASE decltype(&std::remove_reference<F>::type::operator())
struct Signature
{
    using type = typename Signature_helper<TRAIT_CASE>::type;
    using result_type = typename Signature_helper<TRAIT_CASE>::result_type;
};

template<typename R, typename... Ts>
struct Signature<R(&)(Ts...)>
{
    using type = R(Ts...);
    using result_type = R;
};

////////////////////////// Any Class ////////////////////////////////
class AnyFunction
{
    struct placeholder
    {
        virtual ~placeholder() = default;
    };

    template <typename F>
    struct holder : placeholder
    {
        holder(F&& f) : data(std::forward<F>(f)) {}
        F data;
    };

public:
    template <typename F>
    AnyFunction(F&& f)
        : mContent(std::make_shared<holder<std::decay_t<F>>>(std::forward<F>(f)))
    {
    }

    template <typename F>
    const F& cast() const
    {
        assert(dynamic_cast<const holder<F>*>(mContent.get()) != nullptr);
        return static_cast<const holder<F>&>(*mContent).data;
    }

private:
    std::shared_ptr<placeholder> mContent = nullptr;
};

////////////////////////// Function Holder //////////////////////////
class FunctionHolder
{
public:
    template <typename F>
    void insert(F&& f)
    {
        using function = std::function<typename Signature<F>::type>;
        using type = typename Signature<F>::result_type;

        auto result = mHolder.emplace(typeid(type), function(std::forward<F>(f)));
        if (!result.second)
        {
            std::cerr << "ERROR: key "
                + std::string(typeid(typename Signature<F>::result_type).name())
                + " was already inserted\n";
        }
    }

    template <typename... Ts>
    decltype(auto) call(Ts&&... ts) const
    {
        using type = typename std::tuple_element<0, std::tuple<Ts...>>::type;
        auto it = mHolder.find(typeid(type));
        assert(it != mHolder.end());
        return it->second.cast<std::function<type(Ts...)>>()(std::forward<Ts>(ts)...);
    }

private:
    std::map<std::type_index, AnyFunction> mHolder;
};

////////////////////////// Test /////////////////////////////////////
struct Functor
{
    int operator()(int i, int j) const
    {
        return i + j;
    }
};

float function(float i, float j)
{
    return i - j;
}

int main()
{
    std::function<std::string(std::string, int)> fn = [](const std::string& s, int i)
    {
        return "Hello " + s + " " + std::to_string(i);
    };
    auto lambda = [](double i, double j) { return i * j; };
    Functor functor;

    FunctionHolder holder;

    holder.insert(fn);
    holder.insert(lambda);
    holder.insert(functor);
    holder.insert(function);

    std::cout << holder.call(std::string("World!"), 2016) << std::endl;
    std::cout << holder.call(1.5, 2.0) << std::endl;
    std::cout << holder.call(1, 2) << std::endl;
    std::cout << holder.call(6.f, 3.f) << std::endl;
}


texts: Really basic ring/circular buffer in Java

texts:
I needed a simple way to run tests on the last n bytes of data received from a socket, and a ring buffer seemed to be the most efficient way to handle it.  This is a very basic buffer that stores integers and has an accessible snapshot of its contents as a String for quick analysis.

public class RingBuffer{
    private final int size;
    private int[] buffer;
    private volatile int index = 0;

    public RingBuffer(int size){
        this.size = size;
        this.buffer = new int[size];
    }

    public int feed(int input){
        int old = buffer[index];
        buffer[index] = input;

        int nextIndex = index + 1;
        index = nextIndex % size;

        return old;
    }

    public String toString(){
        StringBuilder sb = new StringBuilder();
        for(int i=0;i<size;i++)
            sb.append((char)buffer[(index + i) % size]);
        return sb.toString();
    }
}

I'm not worried about limited features or thread safety, since this is being used by an InputStream wrapper.  I'm more concerned about possible consistency issues or any other basic oversight that would keep the result from being consistent, i.e. that the data going out isn't the same as the data going in.

My use case, for context: trim a Windows newline and period, if present, from the end of the stream.

class GopherInputStream extends InputStream{
    private static final int BUFFER_SIZE = 5;
    private final Pattern TRIM_PATTERN = Pattern.compile(".*\r\n\\.(\r\n)?");

    private final InputStream is;
    private final RingBuffer buffer = new RingBuffer(BUFFER_SIZE);

    private volatile boolean started = false, ended = false;

    GopherInputStream(InputStream is){
        this.is = is;
    }

    @Override
    public int read() throws IOException{
        if(!started){
            preload();
            started = true;
        }
        if(ended) return -1;
        int read = is.read();
        if(read == -1){
            if(TRIM_PATTERN.matcher(buffer.toString()).matches()){
                ended = true;
                return -1;
            }
        }

        int buffered = buffer.feed(read);
        if(buffered == -1)
            ended = true;
        return buffered;
    }

    private void preload() throws IOException{
        int i=0, read;
        while(i++<BUFFER_SIZE && (read = is.read()) != -1)
            buffer.feed(read);
        while(i++<BUFFER_SIZE)
            buffer.feed(-1);
    }
}


texts:
I am writing a simple script that will combine two images at a pixel level, selecting every other pixel from one image, and the other pixels from a second image.

from PIL import Image
import struct

print("Photo 1: ", end="")
photo1 = Image.open(input())  # First image, 1920 by 1080
photo1 = photo1.convert("RGB")

print("Photo 2: ", end="")
photo2 = Image.open(input()) # Second image, 1920 x 1080
photo2 = photo2.convert("RGB")

width = photo1.size[0]  # define W and H
height = photo1.size[1]

print("Output file: ", end="")
output = input()
data = str.encode("")
for y in range(0, height):  # counts to 1079
    row = ""
    for x in range(0, width):# counts to 1920
        if ((y + x) % 2) == 0: # makes every other pixel and alternates
                               # on each line, making a checker board pattern
            RGB = photo1.getpixel((x, y))
            print("Even", y) # how far am I?
        else:
            RGB = photo2.getpixel((x, y))
            print("Odd", y) # how far aim I?
        R, G, B = RGB  # now you can use the RGB value
        data += struct.pack("B", R) + struct.pack("B", G) + struct.pack("B",B)
                 # store RGB values in byte format in variable "data"

new = Image.frombytes("RGB", (1920, 1080), data)# change value if not 1920 x 1080
new.save(output, "PNG") # make new image

Sorry if the copy/paste ing messes with python indentation.
This script take a good 10 minutes to run on my laptop

Intel Core i5
8 GB ram
Running linux (Fedora 30)
Is this just going to take 10 minutes to grab all the individual pixel values, or is there any thing that is making this code inefficient?

Also, I am using python3.7 and 3 at the moment, but I also can use 2.7 if needed.

These are the two photos I am using:


texts:
I'm quite novice here so apologies for any silly mistake in advance
I've been writing a simple tic tac toe game which is a part of my course in udemy
Since this is my first project, I want to do my best in order to learn new things besides learning how to code better. Generally, I want to optimize my code as much as possible.
Can anyone help me with this?
# Tic Tac Toe
# 17 July 2020

import os

test_board = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
player_input_num = 0    # numbers of inputs entered by player
player_num = 0
won = False
marker = 'X'

def clear_screen():
    os.system("clear")

def display_board(board_cords):
    '''
    display the board
    board_cords = list(left to right from top to bottom)
    '''
    line = '-'*40
    for counter in range(0, len(board_cords), 3):
        print("\t|\t\t|")
        print(
            f"{board_cords[counter]}\t|\t{board_cords[counter+1]}\t|\t{board_cords[counter+2]}")
        print(line)
        counter += 3    # go to next row

def check_player_input(number):
    if number < 10 and number >= 0:  # checking the range
        return True
    else:
        print('Sorry the input is not in range [0-9] .')
        return False

def player_input(player_in):
    '''
    Executing codes on the previously checked input
    '''
    global player_input_num  # access to player_input_num
    if player_input_num >= 2:
        # check if the position is free to use
        if check_capacity(test_board, player_in):
            result = place_marker(test_board, 'X', player_in)
            clear_screen()
            display_board(result)

            if check_win(test_board, marker):
                print("You Won!")
                global won
                won = True
        else:
            print("The current position is occupied.")
    else:
        if check_capacity(test_board, player_in):
            result = place_marker(test_board, 'X', player_in)
            clear_screen()
            display_board(result)
            player_input_num += 1
        else:
            print("The current position is occupied.")

def check_capacity(board, position):
    '''
    Check if the current position is free to use.
    '''
    return board[position] == ' '

def place_marker(board, marker, position):
    '''
    Replace the position with a marker
    '''
    board[position] = marker
    return board

def check_win(board, marker):
    '''
    Check if the current game is finished
    '''
    if board[0] == board[1] == board[2] == marker:
        return True
    if board[0] == board[3] == board[6] == marker:
        return True
    if board[0] == board[4] == board[8] == marker:
        return True
    if board[2] == board[5] == board[8] == marker:
        return True
    if board[6] == board[7] == board[8] == marker:
        return True
    if board[2] == board[4] == board[6] == marker:
        return True
    return False

def wanna_play():
    '''
    Check whether the players wanna play again or not.
    '''
    answer = input("Wanna play again? (Y or N)")
    return answer

# Main
display_board(test_board)
while True:
    while won == False:
        try:  # checking if input is int
            player_num = int(input("Enter a position: "))   # casting into int
        except:
            print("Input is not a number")
            continue

        if check_player_input(player_num):
            player_input(player_num)

    if wanna_play() in ['y', 'Y', 'n', 'N']:
        print("something")
    else:
        print("Invalid input.")
        # print("Thanks for playing :)")

Edited.


texts: Print input lines longer than 80 characters in C

texts:
Exercise 1-17 from the book The C Programming Language: 2nd Edition, K&R

Full description: Write a program to print all input lines that are longer than 80 characters.

#include <stdio.h>

#define MAX_ARRAYCHARACTERS 1000
#define MIN_CHARACTERS 80

int main(void){

    int currchar, // current character being read
        currlinelen = 0; // how many characters in a line

    char characters[MAX_ARRAYCHARACTERS]; // holds all the characters

    while( ( currchar = getchar() ) != EOF ){
        characters[currlinelen] = currchar;
        ++currlinelen;

        if(currchar == '\n'){ // if there is a new line

            if(currlinelen >= MIN_CHARACTERS){ // if the total length of characters of this line is higher than 80
                puts("LINE WITH 80+ CHARACTERS: ");
                for(int thischar = 0; thischar < currlinelen; ++thischar) // print all the characters that were in that line
                    putchar(characters[thischar]);
            }

            currlinelen = 0;
        }
    }

    return 0;
}


texts: Extracting data for a tag cloud using Lazy.js

texts:
I've just started using Lazy.js, which is my first exposure to a "functional style" javascript library. I'm still utterly lost as to which of the hundred different functional javascript libraries to use, but so far I like Lazy.js, so I've used it to write a tag harvesting module for a blog engine project I'm working on. For anyone unfamiliar with Lazy.js (even moreso than I am) I'm under the impression its syntax is very similar to Underscore and Lodash.

getTagsWithCount: function(articles) {

  var tags = Lazy(articles).compact().pluck("attributes").pluck("tags").flatten().compact().sort().countBy()
  return tags // returns a Lazy.js Sequence
},

// Formats a Sequence of tag objects into the specific kind of JSON array for spoonfeeding to fussy baby tag-cloud.js
formatForTagCloud: function(tags) {
  var keysToJSON = tags.keys().map(function(x){return {"tagName": x, "count": tags.get(x)};}).toArray();
  var json = JSON.stringify(keysToJSON);
  return json;
}

Specific things I'm interested in/suspect I've done wrong:

Is there a better way to dodge potential nulls in both the article array and in the tags of each articles than the double compact()? What's the performance impact of compact()? If it's light, should I make a habit of using it everywhere as a general way of avoiding null/undefined values in arrays?
Is there a better way to do what I'm trying to do in formatForTagCloud? This function was purely to force my data into a format needed by a module I've actually ended up abandoning, but I'm presenting it here because writing it was a bit of a headache. Is there a different/better way of accessing both the key and the value of an ObjectLikeSequence? More to the point, I thought this would be a case where I could use either merge() or zip(), but neither of those worked, leaving me with this approach which I'm concerned would be considered a bit crude.
I'm in the habit of creating variables then returning them, but I've seen other people write it the function so that the value is just returned without a variable being created first. Which is better? Are there performance benefits to be gained by doing the latter?
Should I be putting newlines after some/all of my chained methods? Again, it's something I see, but I also sometimes find it a tiny bit confusing – but that's probably because I'm fairly new to the pattern.


texts: Linked list that support modifications during iteration

texts:
Update:

Fixed last item is not removed during iteration
Fixed clear() during iteration does nothing
Fixed addition of removed item is ignored

The lasted code can be found here. Unitest can be found here.

As part of my Signals library, I needed to create a custom Linked List with the below properties

It should allow "addition" and "removal" of items during iteration, aka when iterator() is called, like in the for loop.
It should ignore-Addition of duplicated items.
It should ignore-Removal of nonexisting items.
it should be a thread-safe

I ended up with the below implementation. Please tell me what do you think in terms of

clean code
bugs
performance

package com.gazman.signals

import java.util.*

internal class ListenersList<T> : Iterable<T?> {
    private val none = Node<T>(null)
    private var head: Node<T>? = null
    private var tail: Node<T>? = null
    private var map = IdentityHashMap<T, Node<T>>()

    fun isNotEmpty(): Boolean {
        return map.isNotEmpty()
    }

    fun add(listener: T) {
        synchronized(this) {
            if (map.containsKey(listener)) {
                return
            }
            val node = Node(listener)
            map[listener] = node

            if (tail == null) {
                head = node
                tail = node
            } else {
                node.previous = tail
                tail?.next = node
                tail = node
            }
        }
    }

    fun remove(listener: T) {
        synchronized(this) {
            val node = map[listener]
            node?.previous?.next = node?.next
            node?.next?.previous = node?.previous
        }
    }

    override fun iterator(): Iterator<T?> {
        return object : Iterator<T?> {
            var node: Node<T>? = none

            override fun hasNext() = node != null && node != tail

            override fun next(): T? {
                node = if (node == none) {
                    this@ListenersList.head
                } else {
                    node?.next
                }
                return node?.value
            }

        }
    }

    fun clear() {
        synchronized(this) {
            head = null
            tail = null
            map.clear()
        }
    }
}

Node
package com.gazman.signals

internal class Node<T>(val value: T?) {
    var previous: Node<T>? = null
    var next: Node<T>? = null
}


texts: Change example.jpg to example-color.jpg on hover

texts:
I wrote a script that would change example.jpg to example-color.jpg (.png, .gif would work too) on mouse hover and changes it back on mouse leave. I'm making a portfolio, and I have examples of my work in black and white thumbnails, on hover they switch to colored ones.

I'm just wondering if I did this in a redundant or 'wrong' way. is it poor how I have functions in variable, and to call it as such?

$(function () {
        var hoverImg = function() {
            var imgSrc = $(this).attr('src');
            var newSrc = imgSrc.slice(0, -4) + '-color.jpg';
            var isColor = imgSrc.split("-").pop();
            var notColor = (imgSrc.slice(0, - 10) +'.jpg');

            if ( isColor !== 'color.jpg' ) {
                $(this).attr('src', newSrc);
            } else {
                $(this).attr('src', notColor);
            }
         }
        var captionImg = function() {
            $(this).children('.gallery-caption').toggleClass('up');
         }

  $('.gallery').on('mouseenter mouseleave', '.gallery-item img', hoverImg);
 $('.gallery').on('mouseenter mouseleave', '.gallery-item', captionImg);

});


texts: How can I use vector for entering numbers?

texts:
I want to enter names, student numbers and student scores and display this information. I used arrays in this way:

#include "stdafx.h"
#include <iostream>
#include <string>
#define size 3
using namespace std;
class student{
public:
    void vrod();
    void dis();
    int stno,score,i,n;
};
void student::vrod(){
cout<<"name=";
cin>>name;
cout<<"stno=";
cin>>stno;
cout<<"score=";
cin>>score;
}
void student::dis(){
    cout<<"name="<<name<<"\n"<<"stno="<<stno<<"\n"<<"score="<<score<<"\n";

}

int main(){
int i, j=0,n,;
string h;

student st[size];
while (j<3){
st[j].vrod();

j++;}
j=0;
while (j<3){
st[j].dis();

j++;}
cin.get();
cin.get();
}

According to recommendation of my friends, I used vector in this way:

#include "stdafx.h"
#include<iostream>
#include<vector>
#include<sstream>
#include<string>
#define n 3
using namespace std;

int main()
{
  int input;
  string names;
  vector<int> stno,score;
  vector<string> name;
  cout<<"Enter the number of inputs: ";

  cout << "Enter your numbers to be evaluated: " << endl;
  for(int i=0;i<n;i++){
      cout<<"student No.=";
  cin >> input;
  stno.push_back(input);
  }

 for(int i=0;i<n;i++){
      cout<<"scor=";
  cin >> input;
  score.push_back(input);
  }

 for(int i=0;i<n;i++){
     cout<<"name=";
  cin >> names;
  name.push_back(names);
  }

   for(int i=0;i<stno.size();i++)
       cout<<stno[i];
    for(int i=0;i<score.size();i++)
       cout<<score[i];
    for(int i=0;i<name.size();i++)
       cout<<name[i];

  cin.get();
  cin.get();
}

Do you have any opinion to improve the second code written via vector? Can I save information from one student including student numbers and student scores in one position in vector like arrays? I mean for example if my n is 3, I enter the information of students in three positions like arrays(student st[size];)


texts: Writing a JTable to a tab delimited file

texts:
I have written this class that will write a JTable to a tab delimited file so that it can be opened in Excel. It works great, but is there any way to make it better or have it directly open in Excel without having to go through the import screens all of the time? How can I tidy up this code to work or operate more efficiently?

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import javax.swing.JTable;
import javax.swing.table.TableModel;

public class excel {
    String columnNames[] = { "Column 1", "Column 2", "Column 3" };
    String dataValues[][] =
    {
        { "12", "234", "67" },
        { "-123", "43", "853" },
        { "93", "89.2", "109" },
        { "279", "9033", "3092" }
    };

    JTable table;

    excel() {
        table = new JTable( dataValues, columnNames );
    }

    public void toExcel(JTable table, File file){
        try{
            TableModel model = table.getModel();
            FileWriter excel = new FileWriter(file);

            for(int i = 0; i < model.getColumnCount(); i++){
                excel.write(model.getColumnName(i) + "\t");
            }

            excel.write("\n");

            for(int i=0; i< model.getRowCount(); i++) {
                for(int j=0; j < model.getColumnCount(); j++) {
                    excel.write(model.getValueAt(i,j).toString()+"\t");
                }
                excel.write("\n");
            }

            excel.close();

        }catch(IOException e){ System.out.println(e); }
    }

    public static void main(String[] o) {
        excel cv = new excel();
        cv.toExcel(cv.table,new File("H:\\cs.tbv"));
    }
}


texts: ASP.NET Web API HTTP GET with optional parameters

texts:
Writing my first ASP.NET Web API web service. Still learing the power of Linq as well. I feel like there is a more ideomatic way of doing this:

public class StylesController : ApiController
{
    private Entities db = new Entities();

    // GET api/Styles
    public IEnumerable<Style> GetStyles(int division = 0, int family = 0, int model = 0, int year = 0, string market = "ANY")
    {
        market = market.ToUpper(); // make sure market is upper case

        IEnumerable<Style> q = db.Styles;

        if (division > 0) { q = q.Where(s => s.DivisionId == division); }
        if (family > 0) { q = q.Where(s => s.FamilyId == family); }
        if (model > 0) { q = q.Where(s => s.ModelId == model); }
        if (year > 0) { q = q.Where(s => s.Year == year); }
        if (market != "ANY") { q = q.Where(s => s.MarketCode == market); }

        return q.Distinct().OrderBy(s => s.Id).ToList();
    }
}


texts: Design of a remoteControl class for connecting to electronic devices

texts:
In a course that I'm taking on learning object oriented programming in java, I have completed an assignment for modeling a home entertainment system and the ability for a user to be able to use a single remote control to control multiple digital devices such as a TV or sound system etc.

I don't feel too confident about this design so I wanted to run it past the experts.
Below is my code. Any feedback you can provide on improving this design and why would be super helpful!

package user;

import remotes.RemoteControl;
import devices.Projector;
import devices.TV;

public class Person {

    public static void main (String args[]){

        //Devices in the home
        Projector niceProjector = new Projector();
        TV niceLargeScreenTV = new TV();

        // The user's control
        RemoteControl control;

        control = RemoteControl.connectWithdevice(niceProjector);
            control.clickOnButon();

        control = RemoteControl.connectWithdevice(niceLargeScreenTV);
            control.clickOffButon();

    }

}

RemoteControl class:

package remotes;

import devices.Device;

public class RemoteControl {

    private Device theDevice= null;

    private RemoteControl(){

    }

    public static RemoteControl connectWithdevice(Device aDevice){
        RemoteControl remote = new RemoteControl();
        remote.theDevice = aDevice;
        return remote;
    }

    public void clickOffButon(){
        theDevice.turnOnDevice();
    }

    public void clickOnButon(){
        theDevice.turnOnDevice();
    }

}

One of the device classes:

package devices;

public class TV implements Device{

    @Override
    public void turnOnDevice() {
        SwitchToFavoriteChannel();
        System.out.println("TV has been turned on");
    }

    @Override
    public void turnOffDevice() {
        turnOnTVAlarm();
        System.out.println("TV has been turned off");
    }

    // below are additional steps that may be required for you to operate your device
    private void SwitchToFavoriteChannel(){
        System.out.println("Switched to your favorite Channel");
    }

    private void turnOnTVAlarm(){
        System.out.println("TV Alarm set for you to wake up in the morning");
    }

}


texts:
In five minutes I made a pretty ugly looking function. Can you help before I have to commit the code into history?

  Requirements:

  I would like a function that takes an array of numbers, and returns an
  array of ranges. Ideally remove the duplicate line.

  Sample Input:

Array(1,2,3,4,5,6,10,11,12,13,20,24)

  Output:

Array
(
    [0] => 1-6
    [1] => 10-13
    [2] => 20
    [3] => 24
)

  Winning Entries:

Pseudo code
PHP

My attempt:

$myArray = array(1,2,3,4,5,6,10,11,12,13,20,24);

$rangeArray = array();
$start = $end = current($myArray);
foreach($myArray as $range){
    if($range - $end > 1){
        $rangeArray[] = ($start == $end)?$start:$start."-".$end;
        $start = $range;
    }

    $end = $range;
}
$rangeArray[] = ($start == $end)?$start:$start."-".$end;

print_r($rangeArray);


texts: Refactor nested null checking for multiple possible string values

texts:
I am parsing an XML file and trying to get the guid of a node where it has an attribute "name" and a value of "Name" like so:

<property name="Name" guid="7eca00b3-38e0-f0e8-9b72-2b822b21de6b" />

string propertyGuid = propertyList.Where(x => x.name == "Name").FirstOrDefault()?.ToString();
if (propertyGuid == (object)null)
     throw new ArgumentNullException();

So I just found out that there are nodes that don't have a "Name" value but have a "Code" value. Which lets me check for another null value again

<property name="Code" guid="8bca00b3-38e0-f0e8-9b72-2b822b21de7a" />

string propertyGuid = propertyList.Where(x => x.name == "Name").FirstOrDefault()?.ToString();
if (propertyGuid == (object)null)
{
     propertyGuid = propertyList.Where(x => x.name == "Code").FirstOrDefault()?.ToString();
     if (propertyGuid == (object)null)
          throw new ArgumentNullException();
}

How do I refactor my code such that when another criteria (e.g "ID") is introduced in the future, I don't have to make another nested null check?

EDIT:

The check should be the other way around.

if ((object)propertyGuid == null)


texts: Brainf**k to Ruby converter, written in Ruby -- v1.0

texts:
I've seen a lot of Brainf**k interpreters in various languages. I decided that actually interpreting Brainf**k is too hard, so instead of that, I wrote a 'compiler' in Ruby that directly transcribes BF to Ruby code. This is Version 1.0, and I'm looking for any tips on how to make it more efficient.

There are a few things that really bug me:

replacements feels like it's messed up somehow, but I can't put my finger on how.
$stdin.readbyte feels entirely too long, but I can't find an alternative that's shorter.
Should I be using $stdin at all?

input_file = $ARGV[0]
output_file = $ARGV[1]
start = <<-END.gsub(/[ \t]*\|/, '')
  |# Automatically generated by bf_to_ruby.rb
  |# Source available at GitHub
  |data = Hash.new(0)
  |pointer = 0
END

replacements = [
    { replacing: '+', replacement: 'data[pointer] += 1'              },
    { replacing: '-', replacement: 'data[pointer] -= 1'              },
    { replacing: '>', replacement: 'pointer += 1'                    },
    { replacing: '<', replacement: 'pointer -= 1'                    },
    { replacing: '.', replacement: 'putc data[pointer]'              },
    { replacing: ',', replacement: 'data[pointer] = $stdin.readbyte' },
    { replacing: '[', replacement: 'until data[pointer] == 0'        },
    { replacing: ']', replacement: 'end'                             },
]

output = open(output_file, File::CREAT | File::WRONLY)
output.puts(start)

open(input_file, File::RDONLY) do |input|
  input.each_char do |char|
    replacements.each do |data|
      if data[:replacing] == char
        output.puts(data[:replacement])
      end
    end
  end
end

Demo

Input:

++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.

Output:

# Automatically generated by bf_to_ruby.rb
# Source available at GitHub
data = Hash.new(0)
pointer = 0
data[pointer] += 1
data[pointer] += 1
data[pointer] += 1
data[pointer] += 1
data[pointer] += 1
data[pointer] += 1
data[pointer] += 1
data[pointer] += 1
until data[pointer] == 0
pointer += 1
data[pointer] += 1
data[pointer] += 1
data[pointer] += 1
data[pointer] += 1
until data[pointer] == 0
pointer += 1
data[pointer] += 1
data[pointer] += 1
pointer += 1
data[pointer] += 1
data[pointer] += 1
data[pointer] += 1
pointer += 1
data[pointer] += 1
data[pointer] += 1
data[pointer] += 1
pointer += 1
data[pointer] += 1
pointer -= 1
pointer -= 1
pointer -= 1
pointer -= 1
data[pointer] -= 1
end
pointer += 1
data[pointer] += 1
pointer += 1
data[pointer] += 1
pointer += 1
data[pointer] -= 1
pointer += 1
pointer += 1
data[pointer] += 1
until data[pointer] == 0
pointer -= 1
end
pointer -= 1
data[pointer] -= 1
end
pointer += 1
pointer += 1
$stdout.putc data[pointer]
pointer += 1
data[pointer] -= 1
data[pointer] -= 1
data[pointer] -= 1
$stdout.putc data[pointer]
data[pointer] += 1
data[pointer] += 1
data[pointer] += 1
data[pointer] += 1
data[pointer] += 1
data[pointer] += 1
data[pointer] += 1
$stdout.putc data[pointer]
$stdout.putc data[pointer]
data[pointer] += 1
data[pointer] += 1
data[pointer] += 1
$stdout.putc data[pointer]
pointer += 1
pointer += 1
$stdout.putc data[pointer]
pointer -= 1
data[pointer] -= 1
$stdout.putc data[pointer]
pointer -= 1
$stdout.putc data[pointer]
data[pointer] += 1
data[pointer] += 1
data[pointer] += 1
$stdout.putc data[pointer]
data[pointer] -= 1
data[pointer] -= 1
data[pointer] -= 1
data[pointer] -= 1
data[pointer] -= 1
data[pointer] -= 1
$stdout.putc data[pointer]
data[pointer] -= 1
data[pointer] -= 1
data[pointer] -= 1
data[pointer] -= 1
data[pointer] -= 1
data[pointer] -= 1
data[pointer] -= 1
data[pointer] -= 1
$stdout.putc data[pointer]
pointer += 1
pointer += 1
data[pointer] += 1
$stdout.putc data[pointer]
pointer += 1
data[pointer] += 1
data[pointer] += 1
$stdout.putc data[pointer]

Both, when run, output:

Hello World!