texts:
Basically I want to create a concurrent LinkedHashSet which returns proper size too.

I am mainly concerned about adding and removing iterations.  Suggestions relating to implementation of set modification during iteration are also welcomed.

import java.util.Collection;
import java.util.LinkedHashSet;

//TODO still not sure
public class ConcurrentLinkedHashSet<E> extends LinkedHashSet<E>
{
    private static final long serialVersionUID = 1L;
    private boolean isUpdating = false;

    @Override
    public int size()
    {
        while (isUpdating)
        {
            try
            {
                wait();
            } catch (InterruptedException e)
            {
                e.printStackTrace();
                return (Integer) null;
            }
        }
        return super.size();
    }

    @Override
    public synchronized boolean addAll(Collection<? extends E> arg0)
    {
        while (isUpdating)
        {
            try
            {
                wait();
            } catch (InterruptedException e)
            {
                e.printStackTrace();
                return false;
            }
        }
        isUpdating = true;
        boolean result = false;
        result = super.addAll(arg0);
        isUpdating = false;
        notify();
        return result;
    }

    @Override
    public synchronized boolean add(E arg0)
    {
        while (isUpdating)
        {
            try
            {
                wait();
            } catch (InterruptedException e)
            {
                e.printStackTrace();
                return false;
            }
        }
        isUpdating = true;
        boolean result = super.add(arg0);
        isUpdating = false;
        notify();
        return result;
    }

    @Override
    public boolean remove(Object arg0)
    {
        while (isUpdating)
        {
            try
            {
                wait();
            } catch (InterruptedException e)
            {
                e.printStackTrace();
                return false;
            }
        }
        isUpdating = true;
        boolean result = super.remove(arg0);
        isUpdating = false;
        notify();
        return result;
    }

    @Override
    public boolean removeAll(Collection<?> arg0)
    {
        while (isUpdating)
        {
            try
            {
                wait();
            } catch (InterruptedException e)
            {
                e.printStackTrace();
                return false;
            }
        }
        isUpdating = true;
        boolean result = super.removeAll(arg0);
        isUpdating = false;
        notify();
        return result;

    }
}

EDIT : Updated the code based on reviews and is available on github


texts: Removing properties and elements set to null in JavaScript

texts:
I'm looking for a review of the following code.

Is there a better way to remove all properties that evaluate to truthy for a given function?
Is there a better way to prevent a stack overflow in the recursive function?

This is the entire Node.js module:

// The removePropertiesWhereTruthy function accepts the following parameters:
//
// 1. an object or array
// 2. a function to call against each non-object or non-array to determine if it's a truthy value according to that function (e.g. _.isNull)
// 3. An optional maxRecursion value to prevent a stack-overflow when there's a circular reference or exceptionally deeply nested objects.
//
'use strict';

var _  = require('lodash');

function removePropertiesWhereTruthy(obj,func,maxRecursion) {

  maxRecursion = _.isNumber(maxRecursion) ? maxRecursion - 1 : 20;
  if(maxRecursion < 0) {
    // prevent stack overflow by allowing caller to set a max time for
    // recursion and default to 20 if not set.
    return;
  }
  if(_.isObject(obj) && !_.isArray(obj)) {
    _.forOwn(obj, function(v, k) {
      if(_.isObject(v)) { // also true for array
        return removePropertiesWhereTruthy(v,func,maxRecursion);
      } else if(func(v)) {
        delete obj[k];
      }
    });
  } else if(_.isArray(obj)) {
    _.remove(obj, function(item){
      return func(item);
    });
    _.each(obj, function(v){
      if(_.isObject(v)) { // also true for (nested) array
        return removePropertiesWhereTruthy(v,func,maxRecursion);
      }
    });
  } else {
    throw new Error('This function should only be called with objects and arrays');
  }
}

function removePropertiesWithNullValues(obj, maxRecursion) {
  return removePropertiesWhereTruthy(obj, _.isNull, maxRecursion);
}

module.exports = {
  removePropertiesWithNullValues: removePropertiesWithNullValues
};


texts: Which one should I choose for simple task: async/await or promise.then?

texts:
I made a helper function for drawing the map(OpenLayers).
Then I made another helper function for fetch(axios.get) the map URL.
So my question is should I switch from

from .then() (loadMap_before())
to async/await  (loadMap())  ?

Which way is better?
Or option3 is the best where loadMapUrl() helper is totally unnecessary?
Is there any other place where I can improve my code?
Option #1 with promise.then
export const loadMapUrl_before =  (storeMapUrl, storeMapExtent) => {
  let result = {}
  if (!storeMapUrl) {
     getNaviMap().then(res => {
    result.mapExtent = [res.data.origin_x, res.data.origin_y,
    res.data.width * res.data.resolution + res.data.origin_x,
    res.data.height * res.data.resolution + res.data.origin_y];
    result.mapUrl = res.data.image_url})
.catch(...)
  } else {
    result.mapExtent = storeMapExtent
    result.mapUrl = storeMapUrl
  }
  return result
}

Option #2 with async/await
//load map url from store or get it through axios request
export const loadMapUrl = async (storeMapUrl, storeMapExtent) => {
  let result = {}
  if (!storeMapUrl) {
    let res = await getNaviMap()
    result.mapExtent = [res.data.origin_x, res.data.origin_y,
    res.data.width * res.data.resolution + res.data.origin_x,
    res.data.height * res.data.resolution + res.data.origin_y];
    result.mapUrl = res.data.image_url
  } else {
    result.mapExtent = storeMapExtent
    result.mapUrl = storeMapUrl
  }
  return result
}

Usage
// where I call loadMapUrl()
export const loadMap = async (storeMapUrl, storeMapExtent, map, mapLayer) => {
  let mapUrl = '', mapExtent = []
  await loadMapUrl(storeMapUrl, storeMapExtent).then(result => {
    mapUrl = result.mapUrl
    mapExtent = result.mapExtent
  })

  const projection = new Projection({
    code: 'EPSG:4326',
    units: 'degrees',
    extent: mapExtent
  });

  map.setView(new View({
    center: getCenter(mapExtent),
    projection: projection,
    zoom: map.getView().getZoom(),
    minZoom: 0.1,
    maxZoom: 7
  }));

  const source = new Static({
    attributions: 'xxx',
    url: mapUrl,
    projection: projection,
    imageExtent: mapExtent
  });

  mapLayer.setSource(source);
};

Option #3 the helper for axios request might be redundant
export const loadMap = async (storeMapUrl, storeMapExtent, map, mapLayer) => {
  let mapUrl = '', mapExtent = []
 if (!storeMapUrl) {
    let res = await getNaviMap()
    mapExtent = [res.data.origin_x, res.data.origin_y,
    res.data.width * res.data.resolution + res.data.origin_x,
    res.data.height * res.data.resolution + res.data.origin_y];
    mapUrl = res.data.image_url
  } else {
    mapExtent = storeMapExtent
    mapUrl = storeMapUrl
  }
 ...
};


texts:
I'm looking for input on the code itself and formatting/style.  This script parses the output of df -h on a Linux server and emails the user if the usage percentage is above the threshold (90% in this case).

#!/usr/bin/perl

use warnings;
use strict;
use Mail::Sendmail;

my $svr = `hostname`;
my @output = `df -h`;
my $msg;
my $mailto = 'someone@foo.com';
my $threshold = 90;

sub main
{
  foreach (@output) {
    if (($_ =~ m/(\d+)% (.*)/) && ( $1 > $threshold )) {
      chomp($svr); $msg = "$svr: $2 volume  is $1 percent full\n" }
    }

    my %mail = ( To      => $mailto,
                 From    => 'Server@foo.com',
                 Subject => "$svr has a full file system",
                 Message => $msg
               );

  if ( defined $msg ) {
    sendmail(%mail) or die $Mail::Sendmail::error;
  }

}

main


texts: Print factors of number using fencepost loop

texts:
I was wondering if this code could be optimized in any way? For instance, could I use a for each loop here? Are there other ways I could write this which would make it easier for me, or the person reading it to understand?

public static void printFactors(int factorsOf) {
    for (int i = 1; i < factorsOf; i++) {
        if(factorsOf % i == 0) {
            System.out.print(i + " and ");
        }
    }
    System.out.print(factorsOf);
}


texts: Set positions in a list, keeping tied places then incrementing back to the positions

texts:
I have a list of objects which have points and I'm looping through this list to assign the object's position in the list.

If the points are tied between multiple objects they share the same position value, but then the next object with a different point value should be assigned the place as the overall ordering, not tied_value + 1.

For example, tied positions would look like:

1
2
2
4
5

My current solution is:

by_points = sorted(
    objs,
    key=lambda s: getattr(s, point_field, 0),
    reverse=True
)

# Assign the position of 1 to the first object.
position = 1
setattr(by_points[0], position_field, position)

if len(by_points) > 1:
    tied_position = 0
    for i in range(1, len(by_points)):
        previous_points = getattr(by_points[i-1], point_field, 0)
        current_points = getattr(by_points[i], point_field, 0)

        if previous_points != current_points:
            # We know objects are in the order of increasing points.
            position += 1
            if tied_position:
                position += tied_position
            # reset the tie
            tied_position = 0
        else:
            # Position tied, start a count so we know where the position needs to be after the tie is over
            tied_position += 1

        setattr(by_points[i], position_field, position)

I've verified the results are correct, but is there a better approach?


texts: Finding all neighbors of any given element in a matrix like structure

texts:
This is the code I currently have to get all neighbors of any given element in a matrix like structure:

struct Coordinates: IEquatable<Coordinates>
{
    public int Row { get; }
    public int Column { get; }

    public Coordinates(int row, int column)
    {
        Row = row;
        Column = column;
    }

    public bool Equals(Coordinates other) => Column == other.Column && Row == other.Row;

    public override bool Equals(object obj)
    {
        if (obj is Coordinates)
        {
            return Equals((Coordinates)obj);
        }

        return false;
    }

    public override int GetHashCode() => unchecked(27947 ^ Row ^ Column);

    public IEnumerable<Coordinates> GetNeighbors(int numberOfRows, int numberOfColumns)
    {
        var increasedRow = Row + 1;
        var decreasedRow = Row - 1;
        var increasedColumn = Column + 1;
        var decreasedColumn = Column - 1;
        var canIncreaseRow = increasedRow < numberOfRows;
        var canIncreaseColumn = increasedColumn < numberOfColumns;
        var canDecreaseRow = decreasedRow > -1;
        var canDecreaseColumn = decreasedColumn > -1;

        if (canDecreaseRow)
        {
            if (canDecreaseColumn)
            {
                yield return new Coordinates(decreasedRow, decreasedColumn);
            }

            yield return new Coordinates(decreasedRow, Column);

            if (canIncreaseColumn)
            {
                yield return new Coordinates(decreasedRow, increasedColumn);
            }
        }

        if (canIncreaseRow)
        {
            if (canDecreaseColumn)
            {
                yield return new Coordinates(increasedRow, decreasedColumn);
            }

            yield return new Coordinates(increasedRow, Column);

            if (canIncreaseColumn)
            {
                yield return new Coordinates(increasedRow, increasedColumn);
            }
        }

        if (canDecreaseColumn)
        {
            yield return new Coordinates(Row, decreasedColumn);
        }

        if (canIncreaseColumn)
        {
            yield return new Coordinates(Row, increasedColumn);
        }
    }
}

This works but it seems kind of clunky and I can't help thinking there is a more elegant, concise and obvious way of doing this.

Considerations to take into account:

By elegant I mean more concise but readable and mantainable even if performance is slightly worse.
I don't want dependencies on System.Drawing.Point or similar because I don't want to use mutable structs and I don't like using types that conceptually represent unrelated things even though they happen to provide usable functionality to solve the problem at hand.
There is no bound checking in the arguments. This is simply because the code where I'm using this algorithm already ensures that the current coordinates instance is a valid location. As per comments, the current implementation will give erroneous results if you happen to enter matrix bounds that makes the current coordinates invalid. This is not an issue that concerns me.


texts: Refining an ASP.Net MVC VeiwModel for a Table to display worked hours

texts:
I am writing an ASP.Net MVC app which has a page that will display a standard table which will contain a person's hours for the week. The basic structure of the table would be a 7 column, muti-row table. The Header of each column would display the Day of the Week with the total hours worked that week. There would then be rows for the time of the day starting at 8AM going to 5:30 PM in 15m increments. In the table for each day would be a listing of what projects where worked on that day with an indication of when it started and stopped being worked on. (Please see image below for visual aid).

I have built a ViewModel to hold the data for this table and pass it up but I am not sure if I built it in a manor that makes it efficient to work though and have it's data displayed so I would love to have some feedback on ways I might be able to improve it or even alternate ways of building such a ViewModel.

If this is off topic here please let me know where is on topic and I will delete and post there.

My ViewModel Code:

{
    public class TimesheetHoursTableVM
    {
        public int TimesheetHeaderID { get; set; }
        public DateTime WeekEndingDate { get; set; }
        public decimal TotalWeekHours { get; set; }
        public decimal SundayHours { get; set; }
        public decimal MondayHours { get; set; }
        public decimal TuesdayHours { get; set; }
        public decimal WednesdayHours { get; set; }
        public decimal ThursdayHours { get; set; }
        public decimal FridayHours { get; set; }
        public decimal SaturdayHours { get; set; }
        public IEnumerable<TimesheetDailyHoursVM> SundayTimesheet { get; set; }
        public IEnumerable<TimesheetDailyHoursVM> MondayTimesheet { get; set; }
        public IEnumerable<TimesheetDailyHoursVM> TuesdayTimesheet { get; set; }
        public IEnumerable<TimesheetDailyHoursVM> WednesdayTimesheet { get; set; }
        public IEnumerable<TimesheetDailyHoursVM> ThrusdayTimesheet { get; set; }
        public IEnumerable<TimesheetDailyHoursVM> FrodauTimesheet { get; set; }
        public IEnumerable<TimesheetDailyHoursVM> SaturdayTimesheet { get; set; }
    }

    public class TimesheetDailyHoursVM
    {
        public int TimesheetID { get; set; }
        public DateTime StartDateTime { get; set; }
        public DateTime EndDateTime { get; set; }
        public string ProjectCode { get; set; }
        public string TaskCode { get; set; }
        public string ProjectDescription { get; set; }
        public string TaskDescription { get; set; }
    }
}

Table the data goes into:


texts:
I am working on a program that would generate swift classes/ structures for JSON file contents.

The link to the application is Json2Model in case you want to contribute directly.

I do not know a lot of Swift but this is what I came up with. These classes most likely will not hold any logic they are just data.

input.json

{
    "customer":{
        "firstName": "John",
        "lastName": "Doe"
    },
    "addresses": [
        {
            "street": "Faraway Creek",
            "number": 1234,
            "city": "Never-land"
        }
    ],
    "balance": 23234.23,
    "active": true
}

I want the following generated code to be reviewed.

Input.swift

struct Input {
    var addresses: [Address]
    let balance: Double
    let active: Bool
    let customer: Customer

    init(addresses: [Address], balance: Double, active: Bool, customer: Customer) {
        self.addresses = addresses;
        self.balance = balance;
        self.active = active;
        self.customer = customer;
    }

    static func load() {
        //TODO: Needs to be implemented.
    }

}

Address.swift

struct Address {
    let number: Int
    let city: String
    let street: String

    init(number: Int, city: String, street: String) {
        self.number = number;
        self.city = city;
        self.street = street;
    }

}

Customer.swift

struct Customer {
    let firstName: String
    let lastName: String

    init(firstName: String, lastName: String) {
        self.firstName = firstName;
        self.lastName = lastName;
    }

}


texts: Inputs equality check using jQuery without plugins

texts:
I tried creating a function to check for a match between two email fields, let's say EMAIL and CONFIRM email. I absolutely try to avoid jQuery validate. It is not worth it for a single field. For the rest I use HTML5 properties like required, pattern, etc. and it works well. This is why I want to deliver seamless experience with setCustomValidity.

Here's my working code, which of course, may be improved by someone with more experience in JS and jQuery.

HTML

<input type="email" name="addr1" id="addr1" required>
<input type="email" name="addr2" data-equal-to="addr1" data-msg-error="Emails do not match." required>

jQuery

$('[data-equal-to]').on('blur', function() {
    var to_confirm = $(this),
        to_equal = $('#' + to_confirm.data('equal-to'));
    if (to_confirm.val() != to_equal.val()) {
        this.setCustomValidity(to_confirm.data('msg-error'));
    }
    else {
        this.setCustomValidity('');
    }
    to_equal.one('blur', function() {
        to_confirm.trigger('blur');
    });
});

Here are the problems I encountered:

I was using '.bind'. It turns out its deprecated. Then I started using
'.on'
I forgot the last 3 lines. There was no event listener for the
first email input, so I was only checking the CONFIRM input. This
got fixed.
I was using 'input' instead of 'blur'. 'input' provided
real-time validation (as you type) which is good, but consumed too
much in my opinion. Also it showed errors while you are still typing
(and haven't finished), so some users may find it confusing. The only
drawback of 'blur' I find is that feedback on validity comes after
you click another element (unfocus).
Binding on every input a new listener to 'to_equal' turned out to be a bad idea. I ended up with multiple listeners, causing the browser to crash. I found out that '.one' exists, which should do the same as .off before .on (or maybe after?)

My question is - can this little script be improved in terms of speed, or using less event listeners? Is there a case I haven't thought of? I searched a lot to find a good no plugin solution, but with no luck. Also I insist on using data- attributes to provide the matching id + the error message (as the website is multi-lingual and its easier to modify HTML than JS on the fly).

I think that having the 'perfect' version of this script will help a lot of people, especially in confirm email/password (for passwords case sensitivity must be in mind!) aspect.


texts: Direction array to support multiple keydowns in 4-directional movement

texts:
To get a simple, responsive, 4-directional movement in a 2D game, I've implemented the following. When a key is pressed, the add method adds the direction to the keys array. When the key is released, the remove method removes the direction from the keys array. In my Update method, I call getLast to get the last direction and move the player in that direction.

I want to restrict movement to one direction, but when I press multiple keys, I want the last key's direction to be used. Basically, if I'm going left and press up, but then release up while still holding down left, I want the character to go left, up, and continue going left.

I'm rather inexperienced when it comes to this kind of Javascript, so I'm hoping anyone has some tips / best practices recommendations for this small code snippet. I know naming is a bit iffy - I wanted to name it 'stack', but it's hardly a stack implementation.

function Keys() {
    this.keys = [];
}

// Only add the direction if it doesn't exist yet
Keys.prototype.add = function (dir) {
    for (var i = 0; i < this.keys.length; i++) {
        if (this.keys[i] == dir) {
            return;
        }
    }

    this.keys[this.keys.length] = dir;
};

// Find the index of the first occurrence and splice the array there without it
Keys.prototype.remove = function (dir) {
    for (var i = 0; i < this.keys.length; i++) {
        if (this.keys[i] == dir) {
            this.keys.splice(i, 1);
        }
    }
};

Keys.prototype.getLast = function () {
    if (this.keys.length > 0) {
        return this.keys[this.keys.length - 1];
    }
};

In my main file, I use it as: var keys = new Keys();


texts:
I am working on a small app to help my kids study their multiplication and addition.  And I have various preferences I want to be persisted between visits.  What do you think of the below to get the settings out of local storage?  I know I could do it even more simply by simply stringifying the whole object at once, but I want the preferences to contain the answers and I don't want to save all of the answers every time the preferences change...although as I write this that seems like less of an issue...this is for my kids so I don't care about supporting older browsers.

function getPrefs() {
        "use strict";

        getPrefs.prefs = getPrefs.prefs || new Object();
        var prefs = getPrefs.prefs;

        if (prefs.populated) return prefs;

        var localStorage = window['localStorage'];

        prefs.addAnswer = function (answer, correct) {
            this.answers.unshift(answer);
            if (correct) {
                this.correctAnswers++;
                localStorage.setItem("correctAnswers", this.correctAnswers.toString());
                if (this.correctAnswers % 12 === 0) {
                    this.level++;
                    localStorage.setItem("level", this.level.toString());
                }
            } else {
                this.wrongAnswers++;
                localStorage.setItem("wrongAnswers", this.wrongAnswers.toString());
            }
            localStorage.setItem("answers", JSON.stringify(this.answers.slice(0, 100)));
            this.answeredAdded();
        }

        prefs.answeredAdded = function () { };

        prefs.answers = JSON.parse(localStorage.getItem("answers") || '[]');

        prefs.topValue = Number(localStorage.getItem("topValue"));
        prefs.bottomValue = Number(localStorage.getItem("bottomValue"));

        prefs.showHistory = localStorage.getItem("showHistory") === "false";
        prefs.operator = localStorage.getItem("operator") || "x";

        prefs.correctAnswers = Number(localStorage.getItem("correctAnswers") || 0);
        prefs.wrongAnswers = Number(localStorage.getItem("wrongAnswers") || 0);
        prefs.level = Number(localStorage.getItem("level") || "1");

        prefs.populated = true;

        return prefs;
    }


texts:
I have two small structs (might change to classes later) that get loaded into Generic lists. The loading of the lists is what I'm asking about. Can it be done better or more object-oriented?

You'll notice I'm using MS Enterprise library for data access to a SqlCe database.

I'm just looking for some opinions on this code. Is there a more efficient way to do what I've written so far? My goal is to make the code as efficient and small as possible while still being maintainable and expandable.

 public class ConversionUtility
{

    private List<ComicBook> _books;
    private List<ComicPublisher> _publishers;

    private void Load()
    {
        try
        {
            _books = GetBooks();
            _publishers = GetPublishers();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }

    public void PerformConversion()
    {
        Load();

       //still working on this

    }

    private List<ComicPublisher> GetPublishers()
    {
        List<ComicPublisher> tmp = new List<ComicPublisher>();

        Database db = EnterpriseLibraryContainer.Current.GetInstance<Database>("CeConnectionString");

        IDataReader rdr = db.ExecuteReader(CommandType.Text, "SELECT * FROM Publisher");

        while (rdr.Read())
        {
            tmp.Add(new ComicPublisher { Id = (int)rdr["PublisherId"], Name = rdr["PublisherName"].ToString() });
        }
        return tmp;

    }

    private List<ComicBook> GetBooks()
    {
        List<ComicBook> tmp = new List<ComicBook>();

        Database db = EnterpriseLibraryContainer.Current.GetInstance<Database>("CeConnectionString");

        IDataReader rdr = db.ExecuteReader(CommandType.Text, "SELECT * FROM Book");

        while (rdr.Read())
        {
            tmp.Add(new ComicBook { Id = (int)rdr["BookId"], Title = rdr["Title"].ToString(), Company = rdr["Company"].ToString() });
        }

        return tmp;

    }

}

public struct ComicPublisher
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public struct ComicBook
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Company { get; set; }
}


texts:
I'm currently working with the LLVM JIT framework. There is some graph I had to implement for internal cost bench-marking. It has cyclic node dependencies, so I have to use std::weak_ptr pointers for nodes' children instead of their std::shared_ptr counterparts. When it came to implementing child iterators for the graph's external interface, I've adapted llvm::iterator_base.

template
<
  typename WrappedIteratorT,
  typename T = typename std::remove_reference < decltype(*(std::declval<WrappedIteratorT>()->lock())) >::type
>
struct weak_pointee_iterator
  : public llvm::iterator_adaptor_base
  <
    weak_pointee_iterator<WrappedIteratorT>, WrappedIteratorT,
    typename std::iterator_traits<WrappedIteratorT>::iterator_category,
    T
  >
{
  using strong_counterpart = decltype(std::declval<WrappedIteratorT>()->lock());

  weak_pointee_iterator() = default;
  template <typename U>
  weak_pointee_iterator(U &&u)
    : weak_pointee_iterator::iterator_adaptor_base(std::forward<U &&>(u))
  {}

  bool tryLock() const
  {
    strongPointer_ = (*this->I).lock();
    return strongPointer_ != nullptr;
  }

  T& operator*() const
  {
    if (tryLock()) {
      return *strongPointer_;
    } else {
      llvm_unreachable("Weak pointer expired");
    }
  }
private:
  mutable strong_counterpart strongPointer_;
};


texts:
from random import randint
from time import sleep
from sys import (exit, argv)
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import (QToolTip, QPushButton, QApplication, QWidget, QLabel)
from PyQt5.QtGui import (QIcon, QPixmap, QFont)

#Creates the main widget which will contain everything else
class coinflipsimulator(QWidget):

    def __init__(self):
        super().__init__()

        self.initUI()

    def initUI(self):
        #Creates the QLabel 'coin' which will contain the image of the coin
        self.coin = QLabel(self)
        #Uses QPixmap to place a random coin image (head or tail) into the QLabel 'coin'
        self.coin.setPixmap(QPixmap('coin_' + str(randint(1, 2)) + '.png').scaled(162, 302, Qt.KeepAspectRatio, Qt.FastTransformation))
        self.coin.move(0.5, 0.5)

        #Creates the button that will activate the simulated coin flip when clicked and labels it 'Flip' using QPushButton
        self.btn = QPushButton('Flip', self)
        #Selects the font/font size for the label on the QPushButton 'btn' using QFont
        self.btn.setFont(QFont('SansSerif', 20))
        #Creates a tooltip when user hovers over the QPushButton 'btn' using QToolTip
        self.btn.setToolTip('Click to Flip Coin')
        #Selects the font/font size for the QToolTip above on the QPushButton 'btn' using QFont
        QToolTip.setFont(QFont('SansSerif', 10))
        #Connects the QPushButton 'btn' to the function 'flipcoin' to activate when the button is clicked
        self.btn.clicked.connect(self.flipcoin)
        self.btn.resize(166, 43)
        self.btn.move(-2, 161)

        #Sets where on the screen the window will open and the size of the window respectively using x and y coordinates
        self.setGeometry(1427, 30, 162, 201)
        #Locks the size of the window and make it impossible for the user to change it
        self.setFixedSize(self.size())
        self.setWindowTitle('Coin Flip Simulator')
        #Sets the window icon to the image file 'icon.png' located in the same folder as the source file
        self.setWindowIcon(QIcon('icon.png'))
        self.show()

    def flipcoin(self):
        #Sets the image inside the Qlabel 'coin' to a coin flipping animation...aspect ratio is ignored to get the animation to fit inside the window correctly
        self.coin.setPixmap(QPixmap('coin_flipping_animation.png').scaled(162, 302, Qt.KeepAspectRatio, Qt.FastTransformation))
        #Processes any change made to the program/window in this case the change of the image in the Qlabel 'coin'
        QApplication.processEvents()
        #Pauses the execution of any more code for 0.5 seconds
        sleep(0.5)
        #Sets the image inside the QLabel 'coin' to a random coin image (head or tail) into the QLabel 'coin'
        self.coin.setPixmap(QPixmap('coin_' + str(randint(1, 2)) + '.png').scaled(162, 302, Qt.KeepAspectRatio, Qt.FastTransformation))
        #Processes the second change to the QLabel 'dice'
        QApplication.processEvents()

if __name__ == '__main__':

    #Begins the execution of the QApplication

    app = QApplication(argv)
    ex = coinflipsimulator()
    ex.show()
    exit(app.exec_())

This is the first GUI I have completed since I started learning to code. It is a simple program which simulates a die roll when the user clicks a button. I am quite proud of myself even though I know it's nothing great still I am always open to advice and suggestions.


texts: Printing a K-ary tree stored in level-order in an array

texts:
I am given an array that represents a k-ary tree (I am also given the branching factor "k") that is stored in level order. My task was to print the tree in level order.

For example a trinary tree stored as {0,1,2,3,null,null,null,7,8,9,10,11,12} (It doesn't have to be full or complete) would print out as:

0
1 2 3
null null null 7 8 9 10 11 12

My solution currently works fine but it is very messy and not as elegant as I would prefer. The runtime complexity is also very bad (I don't know if Math.pow is O(1) or O(n) but if it's O(1), my code is still O(n) which is not ideal. If Math.pow is O(n) then my code is O(n2) which is garbage.

Is there another approach I am not seeing or can my existing code be optimized at all?

public static void main(String[] args) {
  int k = 3;
  Integer[] arrInt = {0,1,2,3,null,null,null,7,8,9,10,11,12};

  String ans = arrInt[0] + "\n";
  int currLvl = 1;
  int prevLvl = 0;
  //Print all values
  for(int i = 1; i < arrInt.length-1; ++i){
    //Add a line if we reach a new level
    if(i == (Math.pow(k, currLvl)+Math.pow(k, prevLvl))){
      currLvl++;
      prevLvl++;
      ans+= "\n";
    }
    ans+= " " + arrInt[i];
  }
  //EDGE CASE TO HANDLE LAST ELEMENT
  ans+= " " + arrInt[arrInt.length-1];
  System.out.println(ans);
}


texts:
I am writing an object oriented shape detector, first time in Python. I come from a Java background. Can you provide any coding advice?
https://www.pyimagesearch.com/2016/02/08/opencv-shape-detection/
@dataclass
class Coordinate:
    x_value: int
    y_value: int

@dataclass
class Rectangle:
    coordinate_upper_left: Coordinate
    width: float
    height: float

from cv2 import cv2
from numpy.random import randint

import constants.shape_constants as shape_constants
from models.coordinate import Coordinate
from models.rectangle import Rectangle

class ShapeItem():

    def __init__(self, curve_data):
        # these items must run in sequence to be set correctly
        self.curve_data = curve_data
        self.drawing_item_id = uuid.uuid4()
        self.approx_poly_dp = self.get_approx_poly()
        self.vertices = self.get_vertices()
        self.bounded_rectangle = self.get_bounded_rectangle()
        self.center_coordinate = self.get_center_coordinate()
        self.shape = self.get_shape()

    def get_approx_poly(self):
        perimeter_value = cv2.arcLength(self.curve_data, True)
        return cv2.approxPolyDP(self.curve_data, 0.04 * perimeter_value, True)

    def get_vertices(self):
        vertices_list : list[Coordinate] = []
        vertices_data_curve = self.approx_poly_dp.tolist()
        for vertices_in_shape in [vertices_data_curve]:
            for vertices_shape_two_brackets in vertices_in_shape:
                for vertices_shape_one_bracket in vertices_shape_two_brackets:
                    vertices_item = Coordinate(vertices_shape_one_bracket[0], vertices_shape_one_bracket[1])
                    vertices_list.append(vertices_item)

        return vertices_list

    def get_bounded_rectangle(self):
        (x_cv, y_cv, width_cv, height_cv) = cv2.boundingRect(self.approx_poly_dp)
        bounded_rectangle = Rectangle(
            coordinate_upper_left=Coordinate(x_cv, y_cv),
            width=width_cv,
            height=height_cv
        )
        return bounded_rectangle

    def get_shape(self):
        shape_value: str
        if len(self.vertices) == 3:
            shape_value = shape_constants.TRIANGLE
        elif len(self.vertices) == 4:
            shape_value = shape_constants.RECTANGLE
        elif len(self.vertices) == 5:
            shape_value = shape_constants.PENTAGON
        else:
            shape_value = shape_constants.ELLIPSE
        return shape_value

    def get_secondary_shape(self):
        if self.shape == shape_constants.RECTANGLE and \
            0.95 <= (self.bounded_rectangle.width / float(self.bounded_rectangle.height) <= 1.05):
            return shape_constants.SQUARE
        else:
            return shape_constants.RECTANGLE

    def get_center_coordinate(self):
        moment_data = cv2.moments(self.curve_data)
        center_x = int((moment_data["m10"] / moment_data["m00"]))
        center_y = int((moment_data["m01"] / moment_data["m00"]))
        center_coordinate = Coordinate(center_x, center_y)
        return center_coordinate

    def set_background_color(self):
        random_color_index = randint(1, 10)
        return random_color_index


texts:
This is how I solved the binary gap problem: Find longest sequence of zeros, bounded by ones, in binary representation of an integer

I wonder how does it fare against solutions such as ones appeared here?  Codility binary gap solution using regex

function solution(N) {
    const bin = N.toString(2);

    let currentGap = 0;
    let gaps = [];

    for (i=0; i<bin.length; i++){

      if (bin[i]==="0"){
        currentGap++;

        if (bin[i+1]==="1"){
          gaps.push(currentGap);
          currentGap = 0;
        }
      }
    }

    if (gaps.length===1){
      return gaps[0];
    } else if (gaps.length>1){
      return Math.max(...gaps)
    } else {
      return 0
    }
}


texts: Analog clock in React.js, rendered using CSS rotation

texts:
I am new to ReactJS and I am trying to write a component which emulates an analog clock. The second, minutes and hour div elements are transformed every second using an interval function. However, I am wondering if there is a better way of transforming the styles for them in the setDate() function?

It seems that what I have written directly modifies the DOM rather than using the Virtual DOM that React provides.

import React from 'react';

class Clock extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            timer: setInterval(this.setDate, 1000)
        }
    }

    componentWillUnmount() {
        clearInterval(this.state.timer);
    }

    setDate() {
        const secondHand = document.querySelector('.second-hand');
        const minutesHand = document.querySelector('.min-hand');
        const hourHand = document.querySelector('.hour-hand');

        const now = new Date();
        const second = now.getSeconds();
        const minute = now.getMinutes();
        const hour = now.getHours();

        const secondDegrees = (second/60) * 360 + 90;
        const minutesDegrees = (minute/60) * 360 + 90;
        const hourDegrees = (hour/12) * 360 + 90;

        secondHand.style.transform = `rotate(${secondDegrees}deg)`;
        minutesHand.style.transform = `rotate(${minutesDegrees}deg)`;
        hourHand.style.transform = `rotate(${hourDegrees}deg)`;
    }

    render() {
        return (

        )
    }
}

export default Clock;


texts:
My question is really simple. Does this code cause memoryleaks? If so, where/how/why?

HDC hDC, memDC = 0;
HBITMAP hBMP = 0;
HBITMAP hOldBMP = 0;
PAINTSTRUCT PS;
HBRUSH hb212121, hb141414, hb070707, hb000, hbF7F7F7, hb989898, hb707070, hb494949, hb984921 = 0;
HPEN hp353535 = 0;

case WM_PAINT:
        hDC = BeginPaint(hWnd, &PS);
        memDC = CreateCompatibleDC(hDC);
        hBMP = CreateCompatibleBitmap(hDC, 450, 450);
        SelectObject(memDC, hBMP);

        hb212121 = CreateSolidBrush(RGB(33, 33, 33));
        FillRect(memDC, &rMainClntNoBorder, hb212121);

        hb494949 = CreateSolidBrush(RGB(73, 73, 73));
        hb984921 = CreateSolidBrush(RGB(152, 73, 33));
        hb000 = CreateSolidBrush(RGB(0, 0, 0));
        switch(tiles)
        {
            setTileRect();
            case 1:
                FillRect(memDC, &rTile, hb494949);
                break;
            case 2:
                FillRect(memDC, &rTile, hb984921);
                break;
            case 7:
                FillRect(memDC, &rTile, hb000);
                break;
        }
        SelectObject(memDC, hOldBMP);
        DeleteObject(hBMP);
        DeleteObject(hb984921);
        DeleteObject(hb494949);
        DeleteObject(hb212121);
        DeleteObject(hb000);

        hp353535 = CreatePen(PS_SOLID, 1, RGB(53, 53, 53));
        SelectObject(memDC, hp353535);
        GetClientRect(hWnd, &rClnt);
        MoveToEx(memDC, rClnt.left, rClnt.bottom - 1, 0);
        LineTo(memDC, rClnt.left, rClnt.top);
        LineTo(memDC, rClnt.right, rClnt.top);
        DeleteObject(hp353535);

        BitBlt(hDC, 0, 0, rMainClntNoBorder.right, rMainClntNoBorder.bottom, memDC, 0, 0, SRCCOPY);
        DeleteDC(memDC);

        EndPaint(hWnd, &PS);
        break;


texts:
import ssl
from socket import socket

class testsock(socket):
    def __init__(self, tls=True):
        super(testsock, self).__init__()
        self.connect(('192.168.0.1', 443))
        if tls:
            self = ssl.wrap_socket(self) # Ugly "handover"

testsock(tls=True)

This code works, it's the second ugliest bodge I've done as of today.
But it works with the behavior I desire, that .send() and .close() etc are "intact".

However, if I ever try to add any other values to my custom class testsock those will effectively be gone, since I replace self with whatever wrap_socket spits out.

I could use something that looks like this:

class testsock():
    def __init__(self, tls=True):
        self.s = socket()
        ...
        self.s = ssl.wrap_socket(self.s)

    def send(self, data):
        self.s.send(data)

But that goes against the elegance of inheriting the socket object and not having to create all the functions you'd expect out of a ordinary socket. (I know, lazy programming, but it looks cleaner without all the definitions).

I could probably iterate over all the .__dict__ or inspect.getmembers() functions and replace them with the matching available items from wrap_socket, but that would also cause for concerns later on, but it would look something like:

for name, obj in inspect.getmembers(self):
    print(name, obj)

It would yield something like:

close <bound method socket.close of <__main__.testsock fd=...>>

I'm not sure how I'd get socket from this, obj.__class__.__name__ doesn't yield this. If I could some how get socket from the object I would know that it's a socket() bound method, and replace the corresponding method from wrap_socket() return.

I've heard of metaclass programming, and I'm having a go at it.
But my question is, out of all the options - Which would be the best according to the community?

Would it be possible to inline-replace the inherited socket object with whatever ssl.wrap_socket returns?


texts:
def user_not_authorized(exception)
    message = t('flash.access_denied')
    if exception.policy.class.to_s.underscore == 'group_policy' && current_user.students.size != 0
        current_user.students.each do |student|
          student.memberships.each do |membership|
            if membership.group_id == exception.record.id
              message = t('flash.pending_acceptance')
              break # and I would like to break from the outer loop too
            end
          end
        end
    end
    flash[:alert] = message
    redirect_to request.referrer || root_path
  end

This looks ugly to me. Is there a way to somehow compress those two each loops, where one should break both of them conditionally?


texts: Calculating the area of various 2D shapes

texts:
I've made a simple program that can calculate the area of various 2D shapes. I'd like your expereanced eyes to asses my code. Be as harsh as you want but please be specific and offer me ways in which I can improve my coding.

shape = ("triangle","square","rectangle","circle")                  # This is a tuple containing the string names of all the supported shapes so far.
constants = (3.14)                                                  # An object containing the value of pi. I will add more constants in future and turn this into a tuple.
start_up = input("Do you want to calculate a shape's area?: ")      # Fairly self explainatory

if start_up != "yes" or "no":                                       # This is to prevent the program failing if the user answers the start_up question
   print("Sorry but I don't understand what your saying")           # with an answer outside of the simple yes/no that it requires
   start_up = input("Do you want to calculate a shape's area?: ")   # re-iterates the start up question.

   while start_up == "yes":                                            # This is the condition that obviously contains the bulk of the program.
      target_shape = input("Choose your shape: ")                       # Once again, self explainatory.

      if target_shape == shape[0]:                                      # Uses the shape tuple to bring forth the case for the first shape, the triangle.
         h = float(input("give the height: "))                          # These Two lines allow the user to input the required values to calculate the area of the triangle.
         b = float(input("give the base length: "))                     # They are using the float funtion to increase the accuracy of the answer.
         area_triangle = h * 1/2 * b                                    # The formula we all learned in school.
         print("the area of the %s is %.2f" % (shape[0],area_triangle)) # This generates a format string which uses both the shape tuple and the area_triangle object
                                                                # to display the answer. note the %.2f operand used to specify how many decimal places for the answer.

      if target_shape == shape[1]:                                      # Square
         l = float(input("give the length: "))
         area_square = l ** 2
         print("the area of the %s is %.2f" % (shape[1],area_square))

      if target_shape == shape[2]:                                     # Rectangle
         l = float(input("give the length: "))
         w = float(input("give the width: "))
         area_rectangle = l * w
         print("the area of the %s is %.2f" % (shape[2],area_rectangle))

      if target_shape == shape[3]:                                     # Circle
         r = float(input("give the radius: "))
         pi = constants                                                # In this line we are calling forth the constants object to use the value of pi.
         area_circle = 2 * pi * r
         print("the area of the %s is %.2f" %(shape[3],area_circle))

         start_up = input("Do you want to calculate another shape's area?: ") # This line allows the user the chance to do just what it says in the brackets.

      else:                                                                   # This is to safegaurd against failure in the event of the user
        print("That shape's not in my database")                             # inputing a shape non-existant in the shape tuple.
        start_up = input("Do you want to calculate another shape's area?: ")

        if start_up == "no":                                                      #This is for when the user no longer wants to use the program.
           print("Goodbye then!")
           input("Press any key to close")


texts:
I have a function that produce an array with values that are Gaussian (normal) distribution. If you plot the values on a graph, it would look something like this:

Is there any way to improve on the code?

private static IComparable[] NonUniformDistributionsGaussian(int startNumber,int arraySize)
    {
        IComparable [] arr = new IComparable[arraySize];
        Double[] intervals = { ((1.00 / 6.00) * arraySize), ((2.00 / 6.00) * arraySize),
                                 ((3.00 / 6.00) * arraySize),((4.00 / 6.00) * arraySize),
                                 ((5.00 / 6.00) * arraySize), ((6.00 / 6.00) * arraySize) };

        for (var i = 0; i < arraySize; i++)
        {

            if (i <= (int)intervals[0])
            {
                startNumber = startNumber + 1;
            }

            else if ( i <= (int)intervals[1])
            {
                 startNumber = startNumber  + 2;
            }
            else if (i <= (int)intervals[2])
            {
                startNumber = startNumber + 3;
            }
            else if (i <= (int)intervals[3])
            {
                startNumber = startNumber - 3;
            }
            else if (i <= (int)intervals[4])
            {
                startNumber = startNumber - 3;
            }
            else
            {
                 startNumber = startNumber  - 2;
            }
            arr[i] = startNumber;
        }
        return arr;
    }


texts: C# - Linq - Techniques for avoiding repeating same pieces of code

texts:
I am writing a piece of code for C# Web Api, letting the clients to pass a column name and sort direction as parameter.
Although there are, like, 30-ish properties, so the following code (despite it works) gets ugly after a while.
What are my options to avoid repeating this seemingly same pieces of code?
if (column == nameof(MyModel.ColumnA).ToLower())
{
    if (parameters.IsOrderByAsc)
    {
        return queryResult.OrderBy(q => q.ColumnA);
    }

    return queryResult.OrderByDescending(q => q.ColumnA);
}

if (column == nameof(MyModel.ColumnB).ToLower())
{
    if (parameters.IsOrderByAsc)
    {
        return queryResult.OrderBy(q => q.ColumnB);
    }

    return queryResult.OrderByDescending(q => q.ColumnB);
}

if (column == nameof(MyModel.ColumnC).ToLower())
{
    if (parameters.IsOrderByAsc)
    {
         return queryResult.OrderBy(q => q.ColumnC);
    }

    return queryResult.OrderByDescending(q => q.ColumnC);
}

....

```


texts:
Just recently started learning ML, first I've gone through the notes of Ng's Coursera stuff. While I have nothing against Octave, I'm trying to solve exercises in Python. It's my beginning with that kind of algorithms, though I got mathematical background, so sorry for a bit messy code. My questions:
Is there a way to make it more readable, and where to find datasets with solutions to test? Also is that conversion to float in gradient descent main loop unavoidable?

import numpy as np

def scaling(X):
    """mean normalization"""
    l = []
    for k in range(X.shape[1]):
        x = X[:, k]

        def f(e):
            tmp0 = sum(x) / len(x)
            tmp1 = max(x) - min(x)
            return (e - tmp0) / tmp1

        m = list(map(float, (list(map(f, x[:, 0])))))
        l.append(m)
    return np.matrix(l).transpose()

l_cost_function = []  # lists to record data for debugging
l_iterations = []

def multivariate_g_d(A, y, alfa):
    """computes gradient descent"""
    X = np.c_[np.ones(len(A), A]
    tmp = np.matrix([0, 0, 0], dtype=np.float64)
    theta = np.matrix([0, 0, 0], dtype=np.float64)
    cnt = 0
    m = len(X)
    ma = alfa * (1 / m)
    delta = J_m(X, y, theta)
    while delta > 0.00001:
        beg = J_m(X, y, theta)
        for j in range(X.shape[1]):
            tmp[:, j] = theta[:, j] - ma * float((((X *   theta.transpose()) - y.transpose()).transpose()) * X[:, j])
        theta = tmp
        end = J_m(X, y, theta)
        l_cost_function.append(end)
        l_iterations.append(cnt)
        delta = abs(end - beg)
        cnt += 1
    return (theta, cnt)

def J_m(A, y, theta):
    """computes cost function """
    n = len(A)
   return (1 / (2 * n)) * float(sum([x * x for x in A * theta.transpose() - y.transpose()]))


texts:
I have been following along the book 'The C Programming Language' 2nd edition by Kernighan and Ritchie. The below code is an exercise from the book. What I am confused about in this code is the Character array 'line'. It is a local variable so I don't understand how the value is changing when it is used as an argument in the 'get_line' function.

/*******************************
 * Author:                     *
 * Date: 4/22/2019             *
 * Purpose: Book exercise      *
 *******************************/

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

#define MAX_LINE 1000

int get_line(char line[], int maxline);
void copy(char to[], char from[]);

/*Print longest input line*/
int main()
{
    int len;    //Current line length
    int max;    //Maximum length seen so far

    char line[MAX_LINE];        //Current input line
    char longest[MAX_LINE];     //Longest line saved here

    max = 0;

    //While input length is greater than 0
    while((len = get_line(line, MAX_LINE)) > 0)
    {
        //If current string is longer than max
        if (len > max)
        {
            max = len;              //Assign new max value
            copy(longest, line);    //Replace longest string value with current string
        }
    }

    if (max > 0)
    {
        printf("%s", longest);
    }
    return 0;
}

int get_line(char s[], int lim)
{
    int c, i;

    /*i = 0; i less than limit - 1 *and* input is not EOF *and* input is not enter key */
    for (i=0; i<lim - 1 && (c=getchar())!=EOF && c!='\n'; i++)
    {
        s[i] = c; // input array position i is = input
    }

    //Once enter key is hit
    if (c == '\n')
    {
        s[i] = c;   //Add enter key '\n' onto array
        i++;        //Incr i so that last char can be '\0' later
    }

    s[i] = '\0';    //The last spot on char array is '\0'
    return i;
}

void copy(char to[], char from[])
{
    int i;

    i = 0;

    //Assign from[i] to to[i] until null terminator
    while((to[i] = from[i]) != '\0')
    {
        i++;
    }
}

For example if I had a variable in the main routine

int add_num(int num1);
main()
{
    int x = 5;
    add_num(x);
    printf("%d", x);
}

int add_num(int num1)
{
    num1 += 5;
    return num1;
}

x would still remain equal to 5 unless I did:

x = add_num(x);

then x would equal 10.

So how does the line character array change when the function that it's used in returns 'i'?
Where I is the length of the string entered.

Sorry if this was a little long, but I wanted to explain myself clearly.


texts: Adjusting the height of a div to match that of another column

texts:
This code checks whether an image whose parent is .papers.left has completely loaded into DOM and if yes then the background of its right content's height has to be same as the background of this images parent. So below is html to understand the structure

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages." Jogn De, Birthday Event

So to set same height I have written below js code which will set the height of div.papers.right same as div.papers.left but only when the image is loaded completely

$('img').each(function () {
    if ($(this).closest('.papers.left').length)
    {
        $(this).on('load', function () {
            $(this).closest('.row').find('.papers.right').height($(this).closest('.papers.left').height());
        })
    }
})

Can the above piece of jQuery code be optimized? I am not sure whether the above code can be optimized to some simple one.

Update
I just realized one more requirement so that whichever's height is greater assign that height to other one and I've made below changes to code and I would like to know if there is any improvement that can be done to the below code. Extremely sorry for the inconvenience.

$('img').each(function () {
    if ($(this).closest('.papers.left').length)
    {
        $(this).on('load', function () {
            if ($(this).closest('.papers.left').height() > $(this).closest('.row').find('.papers.right').height())
             //if left side has greater height assign it to right side
                $(this).closest('.row').find('.papers.right').height($(this).closest('.papers.left').height());
            else
            //vice versa
            $(this).closest('.papers.left').height($(this).closest('.row').find('.papers.right').height());
        })
    }
})


texts:
I am a newbie in std::thread and std::condition_variable.
I would like to use 2 threads: one for display (void showCalibration()) and the other for processing (void CaptureFrame()). These threads access a global variable (temp_pupil).
The display thread will clear the variable after a specific time to get the data (pupil) from processing thread (during that time).
I used loops to "simulate" capture loop from a high speed camera (void CaptureFrame()) and 9 calibration points displayed on the screen (void showCalibration()
#include <opencv2/core/core.hpp>
#include <iostream>
#include <thread>
#include <mutex>
std::vector<cv::Point2d> temp_pupil;
std::mutex mu;
std::condition_variable cond;

void showCalibration()
{
    for (int i = 0; i <= 9; i++)//plot 9 points sequentially
    {

        std::unique_lock<std::mutex> lk(mu);
        {
            temp_pupil.clear();//prepare for get new data
        }
        lk.unlock();
        cond.notify_one();//signal CaptureFrame() to capture data
        std::this_thread::sleep_for(std::chrono::milliseconds(100));//specific time

        lk.lock();
        {
            while (temp_pupil.empty())
            {
                cond.wait(lk);//wait CaptureFrame() to end current point
            }
            std::string cal = std::to_string(temp_pupil.size()) + "Cali" + std::to_string(i) + "\n";
            std::cout << cal;//print
        }
        lk.unlock();
    }
}

void CaptureFrame()
{
    cv::Point2d pupil;
    for (int i = 0; i <= 500; i++)
    {
        std::unique_lock<std::mutex> lk(mu);
        {
            pupil = cv::Point2d(i, i);//create data
            temp_pupil.push_back(pupil);//get data
            std::string cap = std::to_string(temp_pupil.size()) + "Captue" + std::to_string(i) + "\n";
            std::cout << cap;//print
        }
        lk.unlock();
        cond.notify_one();//signal showCalibration() to end current point
    }
}

int main()
{
    std::thread cal_thread(showCalibration);//display thread
    std::thread cap_thread(CaptureFrame);//process thread
    cal_thread.join();
    cap_thread.join();
}

Could anyone help me review above code ?


texts: Project Euler 78: Coin Partitions in Python

texts:
I was trying to solve Project Euler Problem 78: Coin Partitions.

  Let p(n) represent the number of different ways in which n coins can be separated into piles. For example, five coins can be separated into piles in exactly seven different ways, so p(5)=7. Find the least value of n for which p(n) is divisible by one million.

My solution is in Python. It uses the formula described here in the Wikipedia article, a simple formula really. It takes around 12 seconds, but ideally I'd get it around two or three seconds if not quicker.

Here's my code. I would appreciate any comments or help people could offer.

from timeit import default_timer as timer

start = timer()
partitions = [1, 1, 2, 3, 5, 7, 11, 15, 22, 30, 42]
n = 11
partition = 42
pentagonals = []

for k in range(1, 2000):
    pentagonals.append(k*(3*k-1)/2)
    k *= -1
    pentagonals.append(k*(3*k-1)/2)

while partition != 0:
    partition = 0
    pentagonal = 0
    index = 0
    temp = 0
    is_positive = False
    while pentagonal <= n:
       if is_positive: partition += temp
       else: partition -= temp
       pentagonal = pentagonals[index]
       temp = partitions[n - pentagonal]
       if index % 2 == 0: is_positive = not is_positive
       index += 1
    partition %= 1000000
    partitions.append(partition)
    n += 1

ans = n - 1
elapsed_time = (timer() - start) * 1000
print "Found %d as the answer in %d ms." % (ans, elapsed_time)


texts:
I have a working function that may be optimizable.

Currently processing 4 objects gives me 0.0459822 for the elapsed time in seconds - used for testing purposes. Once implemented into the app I will be checking > 1000 objects at a time and would like to speed this up if possible. The format of the fd.dataTime and the other TimeSpans are from a database and I have no control over the format. The reason for adding a day to some Dates is due to the time going over midnight and would yield an incorrect minimum timespan as a result.

Required: manually adding a day to the date if the time is less than the date - only case is presented below(before midnight date - after midnight timespans). Only store valid timespans. nullField is a String that = 0:00:00 an empty TimeSpan found in DB.

Here is the Function:

Private Function GetMinTimeSpan(fds As List(Of Field)) As String
 Dim result As New List(Of Date)
 For Each fd In fds
  Dim dt As Date = fd.dateTime
  Dim s1 As TimeSpan = TimeSpan.Parse(dt.ToString("HH:mm:ss"))
  Dim s2 As TimeSpan = TimeSpan.Parse(fd.sg)
  Dim s3 As TimeSpan = TimeSpan.Parse(fd.os)
  If Not fd.sg = nullField Then
    If s1 > s2 Then
      result.Add(Date.Parse(dt.AddDays(1).ToShortDateString & " " & fd.sg))
    Else
      result.Add(Date.Parse(dt.ToShortDateString & " " & fd.sg))
    End If
  End If
  If s1 > s3 Then
    result.Add(Date.Parse(dt.AddDays(1).ToShortDateString & " " & fd.os))
  Else
    result.Add(Date.Parse(dt.ToShortDateString & " " & fd.os))
  End If
 Next
 Return result.Min.ToString("HH:mm:ss")
End Function

Here is a sample testing:

Dim sw As New Stopwatch
sw.Start()
Dim fd1 As New Field With {.dateTime = Date.Now, .sg = "23:59:00", .os = "00:03:00"}
Dim fd2 As New Field With {.dateTime = Date.Now, .sg = "00:01:00", .os = "00:03:00"}
Dim fd3 As New Field With {.dateTime = Date.Now, .sg = "0:00:00", .os = "00:04:00"}
Dim fd4 As New Field With {.dateTime = Date.Now, .sg = "00:12:00", .os = "00:05:00"}
Dim fds As New List(Of Field) From {fd1, fd2, fd3, fd4}
Dim m = GetMinTimeSpan(fds)
Debug.WriteLine(sw.Elapsed.ToString)


texts: PostgreSQL simple query with repeated function calls

texts:
I have PostgreSQL 9.1.1 running in a shared hosting environment and I'm running this query:

SELECT a.id,
CASE WHEN a.idpai IS NULL THEN a.nome
ELSE concat(a.nome, ' (', b.nome, ')')
END AS nome, a.idpai
FROM localidade a
LEFT OUTER JOIN localidade b ON a.idpai = b.id
WHERE a.idcidade = :idcidade AND normalizar(
    CASE WHEN a.idpai IS NULL THEN a.nome
    ELSE concat(a.nome, ' (', b.nome, ')')
    END
) LIKE normalizar(:nome)
ORDER BY CASE WHEN normalizar(
    CASE WHEN a.idpai IS NULL THEN a.nome
    ELSE concat(a.nome, ' (', b.nome, ')')
    END
) LIKE substring(normalizar(:nome) from 2) THEN 1
ELSE 2
END, a.nome, b.nome
LIMIT 15

The performance is pretty good, the query returns in less than 50ms. Though, I'm repeating this part 3 times inside the query:

CASE WHEN a.idpai IS NULL THEN a.nome
ELSE concat(a.nome, ' (', b.nome, ')')
END

I believe this reduces the maintainability of the query and is not DRY at all. What is the recommended way to handle that? Should I create a function in my schema solely for this query? Or just store it in a variable and concatenate into the query in my back end before sending it over to the db server? Or is there any better way around?

I believe what this query does isn't the main point here, but just to give some background:

The localidade table may or may not have a relation with itself  through the idpai which references a "parent" register. Assuming this table format:

id | nome | idpai
 1 | foo  |
 2 | bar  |   1

So if the query placeholder :nome contains %foo%, it will return:

id | nome       | idpai
 1 | foo        |
 2 | bar (foo)  |   1

The ORDER BY clause is just to display results which the query parameter matches the beginning of the returned row's name before those who don't - SUBSTRING('%foo%' FROM 2) returns foo% -, and then the matching and not matching groups are ordered by a.nome and b.nome ASC as the SQL shows.

normalizar is a STABLE function that takes a string as parameter and calls LOWER() and removes accentuation returning the new string, so I can perform case-insensitive and accent-insensitive string comparison. Similar to unaccent which I couldn't properly apply on my use case due to some encoding problems (page is UTF8 and DB is latin1, if I convert the UTF8 to latin1 solely on the back end I'll have broken UTF8 pages; well this has been solved with the function above and is off-topic).

idcidade is just a foreign key which I use to reduce the result set to less than 0.1% of the table. Hence performance isn't really an issue in this specific case.

My real question is, does calling CASE multiple times passing the exact same parameters have an impact on performance? I assume the result from CASE should be STABLE and the query will be optimized automatically then. If that's the case, I can store part of the query into a variable on my back end and build the query string using that. Otherwise, if calling CASE multiple times in the same query with the same arguments affects performance, should I create a STABLE function for it then or what's the correct approach to this? Any pointers are appreciated.


texts: Loading information about a competition every time the page is loaded

texts:
I am using KeystoneJS to manage data and my APIs (which includes Node.js, MongoDB, and Express.js). It uses Mongoose to connect with MongoDB; Keystone queries are essentially the same as Mongoose queries, just prefixed with keystone.list('listname').model instead of mongoose.model('name').

My use case is loading information about a competition when a relevant page is being visited by a user. I'm using Express.js to identify the competition we're looking for (stored on the key path of my Competition model, and identified in Express as req.params.cid (Competition ID). Other Express.js routes will use the information from the res.locals.competition path (name, date, location, etc.)

What I am currently doing is running one query to get information about the current competition every time the page is visited. This is stored as a middleware function, loadCompetition, which is called for every Express route that matches /competition/cid*.

app.all('/competition/:cid*', middleware.loadCompetition);

My code looks like this:

exports.loadCompetition = function (req, res, next) {
    keystone.list('Competition').model.findOne({key: req.params.cid}).exec(function (err, competition) {
        if (competition && !err) {
            res.locals.competition = competition;
            return next();
        }
        else {
            if (!competition) {
                req.flash("error", "No competition could be found at this page.");
                return res.redirect("/");
            }
            else  {
                req.flash("error", "An unexpected error occurred. Please try again! If this error persists, email admin@ezratech.us");
                return res.redirect("/");
            }
        }
    });
};

Is this the most effective way of loading a competition like this? Is it feasible to load information about the competition once, and only need to reload it if something changes? Or is what I'm doing the only realistic way of loading information on a competition? I think I would need to query the competition anyway to see if datum has changed (Keystone can track the date a document was modified at, on the updatedAt path), and that would make this entirely redundant. But I don't know if I am missing something. If anything else looks awry, please let me know as well.


texts: Implementation of Permutation Algorithm B from Topor, 1982

texts:
This is Algorithm B from Functional Programs for Generating Permutations (Topor, 1982).

We have implemented Algorithm B in an F# recursive module as follows.

module rec Permutations.Permute2

let removeFirst (list: List<'t>) (item: 't): List<'t> =
    match list with
    | [] -> []
    | head::tail when head = item -> tail
    | head::tail -> head :: (removeFirst tail item)

let mapcons (a: 't) (ps: List<List<'t>>) (qs: List<List<'t>>): List<List<'t>> =
    match ps with
    | [] -> qs
    | head::tail -> (a :: head) :: mapcons a tail qs

let mapperm (x: List<'t>) (y: List<'t>): List<List<'t>> =
    match y with
    | [] -> []
    | head::tail ->
        let permuteNext = permute (removeFirst x head)
        let mappermNext = mapperm x tail
        mapcons head permuteNext mappermNext

let permute (x: List<'t>) : List<List<'t>> =
    match x with
    | [] -> [ [] ]
    | _ -> mapperm x x

We would like a review to make our F# more canonical. That is, we would like to adjust our code to be in keeping with common F# styles and techniques.

Alternatively, we would like a reviewer to show alternative techniques (if not better ones) for implementing Algorithm B in F#.


texts:
The following is my tree coloring realisation attempted to get a feel of Elixir (simple, but slow coloring algorithm from Principles of Distributed Computing). Coloring runs from the root, using alternative colors 0 and 1.

defmodule Graph do
  def add_v g, v, label do
    :digraph.add_vertex(g, v, label)
    g
  end

  def add_e g, v1, v2 do
    :digraph.add_edge(g, v1, v2)
    g
  end
end

defmodule GraphNode do
  import :digraph
  def worker parent, v, children do
    receive do
      {_, {parent_, :color, x}} when parent == parent_ ->
        (
        IO.puts "result: #{elem(v, 1)} color #{x}"
        Enum.map children,
          fn (child) ->
            send child, {self, {elem(v, 0), :color, 1 - x}}
          end
         )
      _ -> IO.puts "???"
    end
    worker(parent, v, children)
  end
end

defmodule ProcessGraph do
  import :digraph
  def start g, current, parent \\ nil do
    children = Enum.map out_neighbours(g, current),
       fn (v) -> ProcessGraph.start(g, v, current) end
    p = spawn(GraphNode, :worker, [parent, vertex(g, current), children])
    if is_nil parent do
      send p, {nil, {nil, :color, 0}}
    end
    p
  end
end

defmodule Graph.Examples do
  import Graph
  def example do
    :digraph.new([:acyclic])
    |> add_v(:root, "Root")
    |> add_v(:a1, "A1")
    |> add_e(:root, :a1)
  end

  def example2 do
    :digraph.new([:acyclic])
    |> add_v(:root, "Root")
    |> add_v(:a1, "A1")
    |> add_v(:a2, "A2")
    |> add_v(:a1b1, "B1")
    |> add_v(:a1b2, "B2")
    |> add_v(:a2b1, "B3")
    |> add_v(:a1b1c1, "C1")
    |> add_e(:root, :a1)
    |> add_e(:root, :a2)
    |> add_e(:a1, :a1b1)
    |> add_e(:a1, :a1b2)
    |> add_e(:a2, :a2b1)
    |> add_e(:a1b1, :a1b1c1)
  end
end

The idea is to have true "no sharing" between processes, so global graph structure is not available to "workers" (one worker per tree node).

As this is the longest of my first programs in Elixir, I am not sure if it is the best way

to use recursion to start workers
to have this format for message contents

Also, the way to add vertices and edges (in examples) seems to me quite Elixirish (if we do not use macros for making DSL).

After this I plan to implement more effective graph coloring algorithms.


texts:
I used the std::chrono library for computing the timing of a function and need some review on it.

Here is the code:

namespace gstd
{

#ifdef GTIME
    inline namespace gtime
    {
        template<typename type, typename period>
        using duration = std::chrono::duration<type, period>;
        std::function<std::chrono::time_point<std::chrono::steady_clock>( )>current_time = std::chrono::high_resolution_clock::now;

        template<typename RetType>
        std::optional<double> getFunctionTime(std::function<RetType(void)>function) {
            try {
                auto start_time = current_time( );
                function( );
                auto end_time = current_time( );
                duration<double, std::milli> dur = end_time - start_time;
                return dur.count( );
            }
            catch ( ... ) {
                return {};
            }
        }
        template <typename RetType, typename arg>
        std::optional<double> getFunctionTime1(std::function<RetType(arg)> function, arg value) {
            try {
                auto start_time = current_time( );
                function(value);
                auto end_time = current_time( );
                duration<double, std::milli> dur = end_time - start_time;
                return dur.count( );
            }
            catch ( ... ) {
                return {};
            }
        }
        template<typename RetType, typename arg1, typename arg2>
        std::optional<double> getFunction2(std::function<RetType(arg1, arg2)>function, arg1 firstparam, arg2 secondparam) {
            try {
                auto start_time = current_time( );
                function(firstparam, secondparam);
                auto end_time = current_time( );
                duration<double, std::milli> dur = end_time - start_time;
                return dur.count( );
            }
            catch ( ... ) {
                return {};
            }
        }
    }

#endif // GTIME
}

This is the code in the header file. Now how i am using it is here:

#define GTIME

#include "GStandard.h"
#include <iostream>

int number_crunching( ) {
    int sum { 0 };
    for ( int i = 0; i < 10000000; i++ )
        sum += 1;
    return sum;
}
int multiplier(int number) {
    for ( int i = 0; i < 10000000; i++ ) {
        number *= ( i + 1 );
    }
    return number;
}
int sum( int a, int b) {
    return a + b;
}
int main( ) {
    auto ftime = gstd::getFunctionTime<int>(number_crunching);
    auto f1time = gstd::getFunctionTime1<int, int>(multiplier, 5);
    auto f2time = gstd::getFunction2<int, int,  int>(sum, 4, 5);

    std::cout << ftime.value( ) << '\n';
    std::cout << f1time.value( ) << '\n';
    std::cout << f2time.value( ) << '\n';

    std::cin.get( );
    return 0;
}

Some suggestions were previously made on making it variadic but I am not doing it so that the students at my college can make improvement to this code. I am looking forward to removing the try catch block and if there are any more changes that you guys could suggest that would be very nice.


texts:
I'm building an example REST API in PHP in my local environment to learn how they work.  The starting point was an online tutorial.  The example is working fine; however, I have a hunch that there is room for improvement in the logic that handles the endpoints which is stored in a script called RestController.php.

Currently, I have the example working both via a UI and, separately, using Postman.  The pertinent lines in .htaccess file are:

RewriteRule ^mobile/?$ controllers/RestController.php [nc,L]
RewriteRule ^mobile/([0-9]+)/?$ controllers/RestController.php?id=$1 [nc,qsa,L]

Here is an example of a Postman test for the GET one mobile API endpoint:

The code that follows is RestController.php.  I'm wondering if there is a way to refactor this into a class but still have the ability to use Postman for testing the endpoints.  If so, how would one go about doing that?

<?php
require_once("../classes/MobileRestHandler.php");

# read raw data from request body and stuff it into $_POST
$_POST = json_decode(file_get_contents('php://input'), true);

# get parameter values according to the method
$method = $_SERVER['REQUEST_METHOD'];

# initialize and populate $parameters_* variables
if (in_array($method, ['GET', 'PUT', 'DELETE'])) {
    $id = isset($_GET["id"]) ? $_GET["id"] : "";
    $parameters_id_only = ['id' => $id];
}

if (in_array($method, ['POST', 'PUT'])) {
    $name = isset($_POST["name"]) ? $_POST["name"] : "";
    $model = isset($_POST["model"]) ? $_POST["model"] : "";
    $color = isset($_POST["color"]) ? $_POST["color"] : "";
    $parameters_no_id = ['name' => $name, 'model' => $model, 'color' => $color];
}

if ($method == 'PUT') {
    $parameters_all = array_merge($parameters_id_only, $parameters_no_id);
}

# this logic controls the RESTful services URL mapping
$mobileRestHandler = new MobileRestHandler();

if (!in_array($method, ['GET', 'POST', 'PUT', 'DELETE'])) {
    $statusCode = 404;
    $statusMessage = $mobileRestHandler->getHttpStatusMessage($statusCode);
    exit($statusCode . ' - ' . $statusMessage);
} else {
    if ($method == 'GET' && strlen($id) == 0) {
        $result = $mobileRestHandler->getAllMobiles();                      // handles method GET + REST URL /mobile/
    } else if ($method == 'GET') {
        $result = $mobileRestHandler->getMobile($parameters_id_only);       // handles method GET + REST URL /mobile/<id>/
    } else if ($method == 'POST') {
        $result = $mobileRestHandler->addMobile($parameters_no_id);         // handles method POST + REST URL /mobile/
    } else if ($method == 'PUT') {
        $result = $mobileRestHandler->editMobile($parameters_all);          // handles method PUT + REST URL /mobile/<id>/
    } else if ($method == 'DELETE') {
        $result = $mobileRestHandler->deleteMobile($parameters_id_only);    // handles method DELETE + REST URL /mobile/<id>/
    }

    echo $result;

}
?>


texts:
Could somebody help me out with trying to clean up this big list of if / else if statements please? I've found that switch statements won't work because it won't handle a TextBox as the parameter. I've seen many answers involving the Dictionary, but those won't work either in my case.

    private void SelectNextTextBox()
    {
        TextBox newTextBox = null;

        if (_currentTextBox == keyText1)
        {
            newTextBox = keyText2;
        }
        else if (this._currentTextBox == keyText2)
        {
            newTextBox = keyText3;
        }
        else if (this._currentTextBox == keyText3)
        {
            newTextBox = keyText4;
        }
        else if (this._currentTextBox == keyText4)
        {
            newTextBox = keyText5;
        }
        else if (this._currentTextBox == this.keyText5)
        {
            newTextBox = regText1;
        }
        else if (this._currentTextBox == regText1)
        {
            newTextBox = regText2;
        }
        else if (this._currentTextBox == regText2)
        {
            newTextBox = regText3;
        }
        else if (this._currentTextBox == regText3)
        {
            newTextBox = regText4;
        }
        else if (this._currentTextBox == regText4)
        {
            newTextBox = regText5;
        }
        else
        {
            return;
        }
        newTextBox.SelectAll();
        newTextBox.Focus();
    }

There's 10 total text boxes and when one is full it changes to the next. This is the method that tells it which text box is next in the list.


texts: Largest palindrome made from the product of two 3-digit numbers

texts:
I am working on an interview question in which I need to find the largest palindrome made from the product of two 3-digit numbers. Here is the question.

public class PalindromeThreeDigits {

    public static void main(String[] args) {
        int value = 0;
        for(int i = 100;i <=999;i++) {
            for(int j = i;j <=999;j++) {
                int value1 = i * j;
                StringBuilder sb1 = new StringBuilder(""+value1);
                String sb2 = ""+value1;
                sb1.reverse();
                if(sb2.equals(sb1.toString()) && value<value1) {
                    value = value1;
                }
            }
        }

        System.out.println(value);
    }
}

Are there any optimizations/simplifications that we can do in this program?


texts: Static variable in method vs private class property

texts:
I have a class with a method that will be called multiple times over an object's lifetime to perform some processing steps. This method operates on a mixture of immutable (does not change over the lifetime of the process) data and data that is passed as an argument. The immutable data is comparatively expensive to calculate, so I would like to cache it.

class Sample
{
    public function process($data)
    {
        $immutable = $this->getImmutable();
        $this->processImplementation($immutable, $data); // not interesting
    }
}

How should getImmutable be implemented?

Option #1 would be

public function getImmutable()
{
    static $cache;
    if ($cache === null) {
        $cache = "not interesting";
    }

    return $cache;
}

Option #2 would be

private $_cache;

public function getImmutable()
{
    if ($this->_cache === null) {
        $this->_cache = "not interesting";
    }

    return $this->_cache;
}

Option #2 is of course better OOP, but what I like about option #1 is that the "implementation detail" $cache is physically close to the only place where it is used. This means that it doesn't increase the mental load of someone reading the code unless that someone decides to read the body of getImmutable, in which case the implementation detail has become important.

In my mind, this purely practical argument is stronger than theoretical purisms.

I am also aware that the static version shares the cache across all instances of the class, which option #2 does not (and that's a good thing). However this is not an issue because

no more than one instance of the class will be created per process
PHP is not multithreaded so the shared cache will not be a problem even when unit testing

Is there some other argument for option #2 that could tip the scales?


texts: Last element pivot Quicksort exercise in TypeScript

texts:
Never being good in "algorithming", I'm now trying to improve the situation a bit.

An algorithm below is the attempt to home brew yet another quicksort. This time, specifically with a "last-element" pivot selection strategy. Is there anything, I can improve better here?

Priorities

Readability first. If it's not readable, it's broken.
Performance. Yes, it's compiled into JavaScript. Yes, JavaScript is "slow". Point is, this code is just an exercise and will never get into production. Said that, I don't want it to be unnecessary inefficient.

Code

I really don't like sorting an array of primitive type element. Instead, I use Element<TKey> which is a key-value object, where the key is used to sort the array by it. Please assume the code is correct (as CR requires it). At least, the tests are green on 52 data inputs ranging from 0 to 99 elements.

import { Compare, SortableArray, swap } from '../sorting-env';

export function quicksort<T>(data: SortableArray<T>, lowIndex: number, highIndex: number, compare: Compare<T>): void {
  if (lowIndex < highIndex) {
    const pivotIndex = partition(data, lowIndex, highIndex, compare);
    quicksort(data, lowIndex, pivotIndex - 1, compare);
    quicksort(data, pivotIndex + 1, highIndex, compare);
  }
}

export function partition<T>(data: SortableArray<T>, lowIndex: number, highIndex: number, compare: Compare<T>): number {
  const originalPivotIndex = highIndex;
  const pivotValue = data[originalPivotIndex];
  let insertionIndex = lowIndex - 1;
  for (let index = lowIndex; index < highIndex; index++) {
    if (compare(data[index], pivotValue) < 0) {
      insertionIndex++;
      swap(data, index, insertionIndex);
    }
  }
  const newPivotIndex = insertionIndex + 1;
  swap(data, originalPivotIndex, newPivotIndex);
  return newPivotIndex;
}

The "helpers" are defined as following:

/** Function to compare two keys.
 * @returns A negative number if first operand is "less" than the second;
 * 0 if operands are "equal";
 * or a positive number otherwise.
 */
export type Compare<TKey> = (a: Element<TKey>, b: Element<TKey>) => number;

/** Represents an element in a sortable collection. */
export class Element<TKey> {
  /** The key to sort by. */
  key: TKey;
  /** Some value held by the element, related to the key. */
  value: any;
}

/** Represents an array which elements can be sorted by key. */
export type SortableArray<TKey> = Element<TKey>[];

/**
 * Swaps two elements in an array by indices (swapping happens in-place).
 * @param array Array which elements are being swapped.
 * @param index1 Index of first element to swap.
 * @param index2 Index of second element to swap.
 */
export function swap<T>(array: SortableArray<T>, index1: number, index2: number): void {
  const temporary = array[index1];
  array[index1] = array[index2];
  array[index2] = temporary;
}


texts:
This is a recursive algorithm implementation of Eulerian tour search.

I guess there is no way to make it more efficient (except rewriting with loops instead of recursion). Any advice on style?

def sub(visited, _cur, graph):
    if not graph:
        return visited + [_cur]
    for i, edge in enumerate(graph):
        cur, nex = edge
        if _cur not in edge:
            continue
        _graph = graph[:]
        del _graph[i]
        if _cur == cur:
            res = sub(visited + [cur], nex, _graph)
        else:
            res = sub(visited + [nex], cur, _graph)
        if res:
            return res

def find_eulerian_tour(graph):
    head, tail = graph[0], graph[1:]
    prev, nex = head
    return sub([prev], nex, tail)

assert find_eulerian_tour([(1, 2), (2, 3), (3, 4), (4, 1)]) == [1, 2, 3, 4, 1]
assert find_eulerian_tour([
    (0, 1), (1, 5), (1, 7), (4, 5),
    (4, 8), (1, 6), (3, 7), (5, 9),
    (2, 4), (0, 4), (2, 5), (3, 6),
    (8, 9)
]) == [0, 1, 7, 3, 6, 1, 5, 4, 8, 9, 5, 2, 4, 0]


texts:
I am trying to make a text-based RPG in Python and Pygame.  I need a way to manage my inventory slots. Currently, I have no way to find out what is currently equipped.  I can only overwrite it, even though I can display the current armor value and what it would be.

Here is the code for the only item I have "finished," a leather tunic:

leatherTunicItem = False
if leatherTunicItem == True and itemSlotArmorChest == False:
    itemSlotArmorChest = True
    chestArmorValue = 2
    print("The leather tunic is now equipped")
elif leatherTunicItem == True and itemSlotArmorChest == True:
    print("Your armor value is currently: ", totalArmorValue, "Equipping a Leather Tunic will make this value: ", totalArmorValue - chestArmorValue + 2)
    print("Would you still like to equip this item? (Yes or No)")
    lti = input("")
    if lti == "y" or lti == "Y" or lti == "yes" or lti == "Yes":
        itemSlotArmorChest = True
        chestArmorValue = 2
        print("Your armor value is now ", totalArmorValue)
    else:
        print("This Leather Tunic will be discarded.")
        leatherTunicItem = False

I have the whole Pastebin code here.

Note: the inventory is all that I am working on for now.


texts:
Here is my problem.  Do I need to give a new identifier to each delegate I write of the following delegate type? like so: or could i use one delegate that accounts for any Datatype I need to use so i don't have to keep repeating the code?

Something that may or may not be relevant: I'm calling these functions to prompt user's input for new fields to add for records in a database.  So database field types are the data types I'm dealing with, but I'm using this approach for learning purposes to try and minimize redundancy.

public static class stcHelper  // helper class
{
    public delegate T DelReturnType<T>();
    static public DelReturnType<int> UserInt = () =>
    {
        Console.Write("Enter integer: ");
        return int.Parse(Console.ReadLine());
    };
    static public DelReturnType<string> UserString = () =>
    {
        Console.Write("Enter string: ");
        return Console.ReadLine();
    };
    static public DelReturnType<AnotherDataType> UserAnotherDataType = () =>
    {
        Console.Write("Enter AnotherDataType: ");
        return SomeKindOfConversionFunction(Console.ReadLine());
    };
    // and so on for what could be 15 other data types ..
}

or is there a better way to reduce redundant code?

The code below is also part of the same class.

public static class stcHelper
{
    static public T InsistValidInput<T>(DelTypeReturn<T> MyInputAction)
    {
        bool bSuccess = true;
        do
        {
            try
            {
                return MyInputAction();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Invalid input!" + ex.ToString());
                bSuccess = false;
            }
        } while (!bSuccess);
        return default(T);
    }
}


texts: Calling individual classes for navigation items

texts:
I have navigation items that are created dynamically with PHP. I wrote this because I need to add individual classes and fire them individually. My code works, but I want a way of refining it no matter how many items are added to the navigation via the backend. Is there a way of doing this so I don't have to add 20 .slideToggle lines of code?

//Adds a CSS Selector to items we need to target individually
jQuery('#sidr ul li').has('ul').each(function(i){
    jQuery(this).addClass('has-sub-'+(i+1));
});
jQuery('#sidr ul li ul').has('li').each(function(i){
    jQuery(this).addClass('sub-'+(i+1));
});

//Toggles a 'clicked' CSS Selector and reveals the Sub-Menus
jQuery('li.has-sub-1').click(function(){
    jQuery('#sidr ul li ul.sub-1').slideToggle(200);
});
jQuery('li.has-sub-2').click(function(){
    jQuery('#sidr ul li ul.sub-2').slideToggle(200);
});
jQuery('li.has-sub-3').click(function(){
    jQuery('#sidr ul li ul.sub-3').slideToggle(200);
});

jQuery('li.has-sub-1, li.has-sub-2, li.has-sub-3, li.has-sub-4, li.has-sub-5, li.has-sub-6').click(function(){
    jQuery(this).toggleClass('clicked');
});


texts:
I'm trying to discover useful command line tools in Arch Linux, and it seems one good way of going about that is to look through all of the man pages related to programs (that is, section 1, as in man 1 bash) in local alphabetic order (that is, not overriding the sorting locale with LC_COLLATE=C or similar). This is the simplest (in terms of number of tokens) I've been able to do so far:

man $(man -s 1 -k . | cut -d' ' -f 1 | sort | tr '\n' ' ')

Questions:

Are there any POSIX incompatibilities here? Or any simple way to make this much more cross-platform?
Is there a simpler way to do this? For example, is there a magic man switch to actually show the pages found with -k, rather than printing their summary, or to sort the output?

This question came about because of a suggestion to use

cd /usr/bin
man

to show all the man pages. First, this just responds

  What manual page do you want?

with exit code 1. Second, amending to man * works for some executables, but several of them do not have man pages. Third, this doesn't necessarily give a complete list of section 1, especially in other distros where some tools are only installed in /usr/sbin or /bin.


texts:
I have built a simple JS class with functional methods that create a Rock, Paper, Scissors game.

I would be happy to get a non-opinionated review in terms of code being optimal.

class Rps{
  constructor(){
    this.signs = {1:'rock',2:'paper',3:'scissors'};
    this.winMatrix = [
      {1:3},
      {2:1},
      {3:2}
    ];
  }
  randomizePlay(){
    const keys = Object.keys(this.signs);
    return 1 + Math.floor(keys.length * Math.random());
  }

  play(){
    return this.roundResult([this.randomizePlay(),this.randomizePlay()]);
  }

  roundResult(resultArray) {
    let victorious = {};

    if (resultArray[0] === resultArray[1]) {
      return 'rematch';
    }

    this.winMatrix.forEach((value, index) => {
      const p1Result = resultArray[0];
      const p2Result = resultArray[1];
      const p1WinMatrix = parseInt(Object.keys(this.winMatrix[index]));
      const p2WinMatrix =  parseInt(Object.values(this.winMatrix[index]));

      if (p1Result === p1WinMatrix && p2Result === p2WinMatrix){
        return victorious = {1:p1Result}
      }else{
        return victorious = {2:p2Result}
      }
    });
    return victorious;
  }
}

const theRpsArray = [];
const theRpsAverage = 0;

let rps = new Rps;
rps.play()


texts:
I'm trying to find the greatest integer of four integers and its ties.  I used the following code.  Is there anyway to simplify this?

int winner = MAX(self.playerOneScore, MAX(self.playerTwoScore, MAX(self.playerThreeScore, self.playerFourScore)));

if (winner == self.playerOneScore && winner != self.playerTwoScore && winner != self.playerThreeScore  && winner != self.playerFourScore) {
    NSLog(@"1");
} else if (winner == self.playerTwoScore && winner != self.playerOneScore && winner != self.playerThreeScore && winner != self.playerFourScore) {
    NSLog(@"2");
} else if (winner == self.playerThreeScore && winner != self.playerOneScore && winner != self.playerTwoScore && winner != self.playerFourScore) {
    NSLog(@"3");
} else if (winner == self.playerFourScore && winner != self.playerOneScore && winner != self.playerTwoScore && winner != self.playerThreeScore) {
    NSLog(@"4");
} else if (self.playerOneScore == self.playerTwoScore || self.playerOneScore ==  self.playerThreeScore || self.playerOneScore == self.playerFourScore || self.playerTwoScore == self.playerThreeScore || self.playerTwoScore == self.playerFourScore || self.playerThreeScore == self.playerFourScore) {
    NSLog(@"Tie");
}


texts: Importing text into PANDAS and counting certain words

texts:
Aim: To improve the speed of the following code. Current timing is about 80~ hours :0

Purpose: The code imports a dataset which contains 1.9 million rows and two columns. One of these columns contain text posts of var length. I then loop through each of these rows and query the post against an imported function that returns a specific counter of variable length. The counter tells me about the presence of certain words in the text. On average the func takes less than  1 ms to return this counter. (Timer for the "Func" inserted at the end to prove this)

Overheads: The code i'm looking to improve is the loop. I accept a certain level of overhead with the "func" which can't be improved at this minute. I have considered looking at Spark or Dask to parallelize the loop and speed up the process. Suggestions are welcome

#Import data
import pandas as pd
from func import func
data = pd.read_csv('Dataset.csv')

print(len(data))
>> 1900000

print(data.columns)
>> Index(['type', 'body'], dtype='object')

#Create new DF
data2 = pd.Dataframe()

for post in data['post']:
    post = str(post)
    scores = func.countWords(posts)
    data2 = data2.append(scores,ignore_index=True)

print(scores)
>> Counter({0: 306,
     1: 185,
     2: 61,
     45: 31,
     87: 23,
     92: 5,
     94: 3,
     102: 30,})

 import time
 start = time.time()
 score = func.countWords("Slow down Sir, you're going to give yourself skin faliure!")
 end = time.time()
 print(end - start)
 >> 0.0019948482513427734


texts: c# Factory Pattern Generic Exception Handler using dot net core

texts:
My task was to create exception handler on some system that has multiple types of database and big business behavior.

At first, I had done a switch/case that handled the exceptions by type using the Object.GetType() method. After some additional thought, I realized that the types of exceptions are endless --- which meant that, every time a new error is thrown, I would have to add more logic to the switch/case. That will make the switch/case so ugly.

So, I have done it by this way. I need your help if i can improve it more or do I need to change the implementation? Also, where are the weaknesses of this implementation?

IExceptionHandlerFactory

private readonly IHttpContextAccessor HttpContext;
private readonly ILogManager LogManager;
private Dictionary<ExceptionsType, Func<ExceptionHandler>> EntityTypeMapper =
    new Dictionary<ExceptionsType, Func<ExceptionHandler>>();

public ExceptionHandlerFactory(IHttpContextAccessor httpContext, ILogManager logManager)
{
    HttpContext = httpContext;
    LogManager = logManager;
    EntityTypeMapper.Add(ExceptionsType.EFException, () =>
        { return new EFExceptionHandler(HttpContext, LogManager); });
    EntityTypeMapper.Add(ExceptionsType.Exception, () =>
        { return new GenericExceptionHandler(HttpContext, LogManager); });
    EntityTypeMapper.Add(ExceptionsType.OracleException, () =>
        { return new OracleExceptionHandler(HttpContext, LogManager); });
}

public ExceptionHandler GetExceptionHandlerBasedOnType(ExceptionsType type)
{
    return EntityTypeMapper[type]();
}

ExceptionHandler

public abstract class ExceptionHandler : Exception
{
    private readonly ILogManager LogManager;

    public ExceptionsType ExceptionsType { get; set; }

    public abstract void Handle(Exception exception);

    public ExceptionHandler(ILogManager logManager)
    {
        LogManager = logManager;
    }

    public void AddLogForException<T>(
        T exception,
        IHttpContextAccessor httpContext,
        string description)
        where T : Exception
    {

        LogManager.AddLog()
    }

}

GenericExceptionHandler

public class GenericExceptionHandler : ExceptionHandler
{
    private readonly IHttpContextAccessor httpContext;

    public ILogManager LogManager { get; }

    public GenericExceptionHandler(
        IHttpContextAccessor httpContext,
        ILogManager logManager) : base(logManager)
    {
        this.httpContext = httpContext;
    }

    public override void Handle(Exception exception)
    {
        AddLogForException(exception, httpContext, string.Empty);
    }
}


texts:
I've just written a palindrome generator and would like to know what you think about it.

Especially:

code style
Is it possible to get the same result without making a special case for 1-digit palindromes?
efficiency

#!/usr/bin/env python

def getPalindrome():
    """
        Generator for palindromes.
        Generates palindromes, starting with 0.
        A palindrome is a number which reads the same in both directions.
    """
    # First print all one-digit palindromes
    for i in range(10):
        yield i

    length = 2
    while True:
        # Do the symmetric part
        for i in range(10**(length//2-1), 10**(length//2)):
            a = str(i)
            r = a + a[::-1]
            yield int(r)
        length += 1

        # Do the unsymmetric part
        exponent = (length-1)//2
        for prefix in range(10**(exponent-1), 10**exponent):
            prefix = str(prefix)
            for i in range(10):
                result = prefix + str(i) + prefix[::-1]
                yield int(result)
        length += 1

if __name__ == "__main__":
    palindromGenerator = getPalindrome()
    for i, palindromeNumber in enumerate(palindromGenerator):
        print("%i-th palindrome: %i" % (i, palindromeNumber))
        if i >= 500:
            break


texts:
This program counts down from 100 to 1 and:

If the current number is a multiple of 3 it prints "Fizz" instead of the number
If it is a multiple of 5 it prints "Buzz" instead of the number
If it is a multiple of 3 and 5 it prints "FizzBuzz" instead of the number

format PE console
entry main

include 'macro/import32.inc'

section '.rdata' data readable
msg db '%d',13,10, 0
fizz db 'Fizz', 13, 10, 0
buzz db 'Buzz', 13, 10, 0
p db 'pause>nul', 0
fizzbuzz db 'FizzBuzz', 13, 10, 0
section '.data' data readable writeable
vdiv_by_3 dd 0
vdiv_by_5 dd 0

main:
push ebp
mov ebp, esp

mov ecx, 100

load_3:
mov eax, ecx
mov ebx, 3
xor edx, edx
div ebx
mov ebx, edx
mov [vdiv_by_3], ebx ; Store the remainder in div_by_3

load_5: ; Now check if its divisible by 5
mov eax, ecx
mov ebx, 5
xor edx, edx
div ebx
mov [vdiv_by_5], edx ; Remainder in div_by_5

cmp edx, 0 ; Checking 5
jne check_3_not_5

check_3:
mov eax, [vdiv_by_3]
cmp eax, 0
je print_fizzbuzz

check_3_not_5:
mov eax, [vdiv_by_3]
cmp eax, 0
je print_fizz

check_5_not_3:
mov eax, [vdiv_by_5]
cmp eax, 0
je print_buzz

print_num: ; Problem: This is printing 101 first, we need to start at 1
push ecx
push msg
call [printf] ; This call will mess with ecx so we have to store it
add esp, 4
pop ecx ; Get the counter back into ecx
jmp endme

print_fizz:
push ecx
push fizz
call [printf]
add esp, 4
pop ecx
jmp endme

print_buzz:
push ecx
push buzz
call [printf]
add esp, 4
pop ecx
jmp endme

print_fizzbuzz:
push ecx
push fizzbuzz
call [printf]
add esp, 4
pop ecx
jmp endme

print_number:
push ecx
push msg
call [printf]
add esp, 4
pop ecx

endme:
dec ecx
cmp ecx, 0
jne load_3
push p
call [system]
add esp, 4
push 0
call [exit]

section '.idata' import data readable
library msvcrt, 'msvcrt.dll'
import msvcrt, \
printf, 'printf', \
system, 'system', \
exit, 'exit'