texts:
I am using if else statements:

public ActionResult Process(int? inventoryCheck, int? POCheck, int? PromotionCheck)
{
    //var result = db.ValidInventory(2);

    //1. When inventory is low:
    if (inventoryCheck != null && POCheck == null && PromotionCheck == null)
    {
        db.ValidInventory(inventoryCheck);
    }
    //2. When PO is not generated
    else if (POCheck != null && inventoryCheck == null && PromotionCheck == null)
    {
        db.ValidInventory(POCheck);
    }
    //3. For Promotion
    else if (POCheck == null && inventoryCheck == null && PromotionCheck != null)
    {
        db.ValidInventory(PromotionCheck);
    }
    else if (inventoryCheck != null && POCheck != null && PromotionCheck == null)
    {
        //4. When Inventory is low and PO is not generated
        inventoryCheck = 4;
        db.ValidInventory(inventoryCheck);
    }
    else if (inventoryCheck != null && POCheck == null && PromotionCheck != null)
    {
        //5.When inventory is low and Promotion Check
        inventoryCheck = 5;
        db.ValidInventory(inventoryCheck);
    }
    else if (inventoryCheck == null && POCheck != null && PromotionCheck != null)
    {
        //6. When PO is not generated and Promotion Check
        inventoryCheck = 6;
        db.ValidInventory(inventoryCheck);
    }
    else if (inventoryCheck != null && POCheck != null && PromotionCheck != null)
    {
        //7. When PO is not generated and Promotion Check   and inventory is low
        inventoryCheck = 6;
        db.ValidInventory(inventoryCheck);
    }

    return RedirectToAction("BackAnalysis");
}

Here more conditions are present, then I have to add more if else blocks.

How can I optimize it?


texts:
I'm trying to map this problem into a 4-sum problem, and I find the time complexity is always \$O(n^3)\$. Is there a way to optimize time complexity, with constant additional space complexity \$O(1)\$?

Any other advice about improvement for time complexity, code bugs or code style advice is appreciated.

  Problem

  Given an array A of unique integers, find the index of values that
  satisfy A + B =C + D, where A,B,C & D are integers values in the
  array. Find all combinations of quadruples.

def four_sum (numbers, target, start, end, exclude_index_set):
    i = start
    j = end
    result = []
    while i < j:
        if i in exclude_index_set:
            i += 1
        elif j in exclude_index_set:
            j -= 1
        elif numbers[i] + numbers[j] == target:
            result.append((numbers[i], numbers[j]))
            i += 1
            j -= 1
        elif numbers[i] + numbers[j] > target:
            j -= 1
        else:
            i += 1
    return result

if __name__ == "__main__":
    numbers = [1,2,3,4]
    result = []
    for i,v in enumerate(numbers):
        for j in range(i+1, len(numbers)):
            r = four_sum(numbers, v+numbers[j], i+1, len(numbers)-1, set([i,j]))
            if len(r) > 0:
                r.append(([numbers[i],numbers[j]]))
                result.append(r)
    print result


texts:
Here is code I wrote to dynamically choose between three country options (United States, Canada, Other). After the user selects a country it will show the related select option or an empty input (when "Other" country is chosen). Then I pass the previous value into an input called spr(state/province/region). The end result is two values are saved: country and spr.
I'm here because I think the code could be refactored, and I'm not thinking about it in an efficient way.

const country = '#country';
const province = '#province';
const region = '#region';
const state = '#state';
const spr = '#spr';
const usa = '#usa';
const canada = '#canada';
const otherCountry = '#otherCountry';

hideCountryOptions(); //initial hide

$(country).on('change', function() {
  hideCountryOptions();
  selectSPR($(country).val());
  switch ($(country).val()) {
    case "UNITED STATES":
      $(usa).show();
      break;
    case "CANADA":
      $(canada).show();
      break;
    default:
      $(otherCountry).show();
  }
})

$(state + "," + province + "," + region).on('change', function() {
  selectSPR($(country).val());
});

function hideCountryOptions() {
  $(canada).hide();
  $(usa).hide();
  $(otherCountry).hide();
}

function selectSPR(country) { //pass value into the state/province/region input
  $(spr).val("");
  switch (country) {
    case "UNITED STATES":
      $(spr).val($(state).val());
      break;
    case "CANADA":
      $(spr).val($(province).val());
      break;
    default:
      $(spr).val($(region).val());
  }
}

  *Country
  <select name="country" id="country" required>
      <option value="">CHOOSE…</option>
      <option value="UNITED STATES">UNITED STATES</option>
      <option value="CANADA">CANADA</option>
      <option value="AFGHANISTAN">AFGHANISTAN</option>
    </select>

  *State
  <select name="state" id="state">
      <option value="">CHOOSE...</option>
      <option value="ALABAMA">ALABAMA</option>
      <option value="ALASKA">ALASKA</option>
    </select>

  *Province
  <select class="custom-select" name="province" id="province">
      <option value="">CHOOSE...</option>
      <option value="ALBERTA">ALBERTA</option>
      <option value="BRITISH COLUMBIA">BRITISH COLUMBIA</option>
    </select>

  *Region
  <input type="text" name="region" id="region" placeholder="Region">

  <input type="text" name="spr" id="spr">


texts:
I wrote a primality test for UniHaskell however, it seems complicated in terms of conditionals.

Here it is, rewritten to not use Unicode and other functions in the code:

-- Primality predicate
isPrime  :: Int -> Bool
isPrime 2 = True
isPrime 3 = True
isPrime n
    | n `mod` 2 == 0 = False
    | n `mod` 3 == 0 = False
    | otherwise      = check 5 2
  where check i w
            | i * i <= n = if n `mod` i == 0
                           then False
                           else check (i + w) (6 - w)
            | otherwise = True

The algorithm is simple: return True if n is 2 or 3, False if n is a multiple of 2 or 3, and then perform trial division over numbers that are not multiples of 2 or 3.


texts:
I feel this is deeply inelegant, but I really want the option of classical inheritance in the future. How could this be written better. FYI animation here is from GSAP if you are curious.

class Modal

    angular.element(document).ready =>
        @modalElem   = document.getElementById 'modal'
        @overlayElem = document.getElementById 'overlay'

    @isOpen = false

    @getWindowDim : ->
        return dim =
            height : window.innerWidth or document.documentElement.clientWidth
            width  : window.innerHeight or document.documentElement.clientHeight

    @openModal : (attrs) ->

        unless @isOpen

            @isOpen = true

            width   = attrs.width
            height  = attrs.height
            content = attrs.content

            wDim    = @getWindowDim()

            @modalElem.style.width      = 0
            @modalElem.style.height     = 0

            @overlayElem.style.display  = 'block'

            TweenLite.to @modalElem, 0.75,
                width       : width
                height      : height
                marginTop   : (height/-2)
                marginLeft  : (width/-2)
                opacity     : 1
                ease        : Back.easeOut
        @

    @closeModal : ->

        if @isOpen

            @isOpen = false

            TweenLite.to @modalElem, 0.33,
                width       : 0
                height      : 0
                marginTop   : 0
                marginLeft  : 0
                opacity     : 0
                ease        : Back.easeOut
                onComplete  : =>
                    @overlayElem.style.display = 'none'
        @

modal   = angular.module 'modal'

modal.directive 'openmodal', ->
    return (scope, element, attrs) ->
        element.bind 'click', ->
            Modal.openModal attrs

modal.directive 'closemodal', ->
    return (scope, element, attrs) ->
        element.bind 'click', ->
            Modal.closeModal()


texts: wrote a blackjack game in python , would like you get notes on it

texts:
I started learning python online and I wrote a blackjack game as my first little project.
I would like to get some review on it if possible. (how to make it better , simpler , etc)

from random import choice
cards = ['A', 2, 3, 4, 5, 6, 7, 8 , 9,'J','Q','K']*4

def get_card(name):
    card = choice(cards)
    cards.remove(card)
    print(f'{name} got {card}')
    return card

def hand(cards):
    global dealer_total
    dealer_total = 0
    dealer_card = convert(get_card('The dealer'),dealer_total)
    dealer_total += dealer_card
    total = 0
    card = convert(get_card('You'),total)
    total += card
    card = convert(get_card('You'),total)
    total += card
    if total == 21:
        print('Blackjack! You Won!')
        another_game()
    check_total(total)

def convert(card,total):
    if card == 'A':
        if total > 10:
            card = 1
        else: card = 11
    if card in ['K','Q','J']:
        card = 10
    return card

def check_total(total):
    if total == 21:
        print(f'You stand on a total of {total}. Lets see what the dealer gets:')
        dealer_hand(total,dealer_total)
    elif total > 21:
        print(f'You stand on a total of {total}. You lost!')
        another_game()
    else:
        another_card(total)

def another_game():
    another_game = input('Would you like to play again ?').lower()
    if another_game == 'yes':
        cards = ['A', 2, 3, 4, 5, 6, 7, 8 , 9,'J','Q','K']*4
        hand(cards)
    elif another_game == 'no':
        print('Goodbye !')
        quit()
    else:
        raise ValueError('You entered the wrong value')
        another_game()

def another_card(total):
    another = input(f'You stand on a total of {total}. Would you like another card ? (Yes/No)').lower()
    if another == 'yes':
        card = convert(get_card('You'),total)
        total += card
        check_total(total)
    elif another == 'no':
        print('OK , lets see what the dealer gets')
        print(f'Before fliiping the cards , the dealer stands on a total of {dealer_total}')
        dealer_hand(total,dealer_total)
    else:
        raise ValueError('You entered the wrong value')
        another_card(total)

def dealer_hand(total,dealer_total):
    card = convert(get_card('The dealer'),dealer_total)
    dealer_total += card
    if dealer_total > 21:
        print(f"Dealer's total is {dealer_total}. You won ! ")
        another_game()
    elif dealer_total > 16:
        print(f'Dealers total is {dealer_total}.The dealer must stand.')
        who_won(total,dealer_total)
    elif dealer_total < 17:
        print(f"Dealer's total is {dealer_total}. He must take another card.")
        dealer_hand(total,dealer_total)

def who_won(my_total,dealer_total):
    print(f'Your total is {my_total} , The dealers total is {dealer_total}')
    if my_total > dealer_total:
        print('You won !')
    elif my_total < dealer_total:
        print('You lost !')
    else:
        print('Its a tie !')
    another_game()

print('Hello !')
hand(cards)

I highly appreciate it , thank you !!


texts: Functional way to handle JMSConnection open and close with Clojure

texts:
I wrote this code to automatically open and close my JMSConnection's in Clojure:

(defn with-jms
  ([provider-url context-factory factory-name fn args]
   (with-open [jndi-ctx (new InitialContext (populate-env provider-url context-factory))
               jms-conn (-> (.lookup jndi-ctx factory-name)
                            (.createConnection))]
       (apply fn (-> (sequence args)
                     (conj jms-conn)
                     (conj jndi-ctx)))))
  ([fn args]
   (let [{provider-url    "provider-url"
          context-factory "context-factory"
          factory-name    "factory-name"} jms-properties]
     (with-jms provider-url context-factory factory-name fn args))))

Note how properties are used for convenience. Please also note that populate-env is a function that returns a HashTable populated with the necessary JMS properties.

I can then define JMS functions the following way:

(defn send-text-message! [jndi-ctx jms-conn topic content]
  (with-open [session (.createSession jms-conn false Session/AUTO_ACKNOWLEDGE)
              producer (.createProducer session (.lookup jndi-ctx topic))]
    (let [message (.createTextMessage session content)]
      (.send producer message))))

I can combine both functions in the following way :

(with-jms send-text-message! ["clojureTopic" "azerty"])

However I'm not 100% satisfied with it. These are the things that puzzle me:

In with-jms, the args in with-jms is an array, because overloading and multi-varied arguments is not supported in Clojure. Is there a better alternative?
In with-jms, the (apply fn (-> (sequence args) (conj jms-conn) (conj jndi-ctx))) part feels really clunky, is there a better way to write that?
When I call with-jms function, I must remember to exclude the jndi-ctx and the jms-conn from the argument lists even if it's in the called function signature. I don't like it, I find it confusing. I tried to write a wrapper that returns a partial function but it felt unnecessary and tedious to do for every JMS function. Maybe there's a better way to write with-jms?

Any help would be appreciated !


texts:
I wrote the following class so that a single object can be shared across many threads. Is using the ReaderWriterLockSlim redundant in this case and only Interlocked.Funcs() can do the job and ensure thread safety?

using System.Threading;

public class SharedData<T> where T:class
{
T _data;
ReaderWriterLockSlim _lock;

public SharedData(T arg)
{
    Interlocked.Exchange<T>(ref _data, arg);
    _lock = new ReaderWriterLockSlim();
}

public T Value
{
    get
    {
        _lock.EnterReadLock();
        var ret = Interlocked.CompareExchange<T>(ref _data, default(T), default(T));
        _lock.ExitReadLock();

        return ret;
    }
    set
    {
        _lock.EnterWriteLock();
        Interlocked.Exchange<T>(ref _data, value);
        _lock.ExitWriteLock();
    }
}
}


texts:
I'm a student learning Python, I made this calculator that will tell you the tuition for the next 5 years at an increase of 3% per year. How can I improve on this and did I do anything that isn't best practice?
To revise my new version, Python tuition calculator 2.0

inState = 10000
outState = 24000
profGrad = 40000

years = []
tuitionIncrease = []

i = raw_input('Please input your type of residency, I for in-state, O for out-of-state, and G for graduate: ')

if i == 'I':
    costOfTuition = inState
elif i == 'O':
    costOfTuition = outState
elif i == 'G':
    costOfTuition = profGrad

x = 0
while x != 5:
    intMath = costOfTuition * 0.03
    tuitionIncrease.append(intMath)
    fnlMath = intMath + costOfTuition
    years.append(fnlMath)
    costOfTuition = fnlMath
    x += 1

academicYear1 = "${:,.2f}".format(years[0])
academicYear2 = "${:,.2f}".format(years[1])
academicYear3 = "${:,.2f}".format(years[2])
academicYear4 = "${:,.2f}".format(years[3])
academicYear5 = "${:,.2f}".format(years[4])

academicYear1Inc1 = "${:,.2f}".format(tuitionIncrease[0])
academicYear1Inc2 = "${:,.2f}".format(tuitionIncrease[1])
academicYear1Inc3 = "${:,.2f}".format(tuitionIncrease[2])
academicYear1Inc4 = "${:,.2f}".format(tuitionIncrease[3])
academicYear1Inc5 = "${:,.2f}".format(tuitionIncrease[4])

totalTuitionIncreaseSum = sum(tuitionIncrease)
totalTuitionIncrease = "${:,.2f}".format(totalTuitionIncreaseSum)
4
print('UNDERGRADUATE TUITION FOR THE NEXT FIVE YEARS ')
print('ACADEMIC YEAR          TUITION       INCREASE ')
print('-------------     ------------       -------- ')
print('2016-17             ' + academicYear1 + '        ' + academicYear1Inc1)
print('2017-18             ' + academicYear2 + '        ' + academicYear1Inc2)
print('2018-19             ' + academicYear3 + '        ' + academicYear1Inc3)
print('2019-20             ' + academicYear4 + '        ' + academicYear1Inc4)
print('2020-21             ' + academicYear5 + '        ' + academicYear1Inc5)
print('TOTAL TUITION INCREASE              '     + totalTuitionIncrease)


texts:
I wrote an itoa function yesterday, which based on feedback I am now working on improving. How does the below look? Are there any ways in which I can improve it?
#include <stdio.h>
#include <string.h>
#include <limits.h>

char* itoa(int number, size_t sz, char buffer[sz])
{
    // do error handling and edge cases
    if (buffer == NULL || sz == 0)
        return NULL;
    else if (number == 0)
        return strcpy(buffer, "0");

    char tmp[sz];
    int idx = 0;
    bool is_negative = (number < 0);
    if (!is_negative) number = -number; // so we can handle INT_MIN

    for (; number != 0; number/=10, idx++) {
        if (sz-- == 0) return NULL;
        tmp[idx] = '0' - (number % 10); // negative version of number + '0'
    }
    if (is_negative) {
        if (sz-- == 0) return NULL;
        tmp[idx++] = '-';
    }

    // reverse
    for (int i=0; i<idx; i++)
        buffer[idx-i-1] = tmp[i];
    buffer[idx] = '\0';
    return buffer;
}

int main(void)
{
    char buffer[100];
    int test[] = {123, 234, 0, 17, -4, -7, -17, -27, INT_MAX, INT_MIN};
    size_t len = sizeof(test) / sizeof(*test);

    // give it a small buffer and see how it works
    for (int i=0, num; i < len; i++) {
        num = test[i];
        char* str = itoa(num, 2, buffer);
        printf("%-10d <%s>\n", num, str);
    }

    // now give it the correctly-sized buffer
    for (int i=0, num; i < len; i++) {
        num = test[i];
        char* str = itoa(num, sizeof buffer / sizeof *buffer, buffer);
        printf("%-10d <%s>\n", num, str);
    }
}

Working code here: https://onlinegdb.com/H1xKCemNu. A few questions about this:

It seems like there are just so many edge cases to consider for the most trivial of functions to write in C. For example, the above function took me about two hours to write (and was after some very helpful feedback from @chux). Is that a common issue in writing C code? Or is this more a beginner issue that will go away with experience?
With the for loop I often find myself being bitten by an off-by-one error, for example, not realizing the idx is incremented after the previous loop but before the next loop is checked. Are there particular ways to look out for that?
Any other areas to improve here?


texts: Finding an employee from a given mother company

texts:
This method finds an employee from a given mother company which consists of group of companies. An employee can work for many child company.

$scope.getEmployee = function(subsidiary, salaryScale){ //1
  var workingDepartments = [];//2
  var findInGroupOfCompanies =  function(comGroup, salaryScale){//3
                                 var salaryIndex = subsidiary[salaryScale];//4
                                 if(salaryIndex != "SUPERIOR" && salaryIndex == comGroup.salaryIndex) {//5
                                     if(comGroup.hasSubsidiaries()) { //6
                                        findInGroupOfCompanies(comGroup, salaryScale++ ); //7
                                     } else {//8
                                        workingDepartments.push(comGroup);//8
                                       //and do some stuff
                                     }
                                 }
};

The method findInGroupOfCompanies and its function is separated by equal and intended. Is this formatting not adhering to general code styles in JS? Have I added spaces unnecessarily after line number 3?


texts:
The overall question is:  I need feedback on the security of the idea and the script.  Do I need to do more in raw code, or is this ok, taking into account my other information?

Let's assume these following first:

All images are stored on a subdomain (e.g. images.example.com)
The subdomain images.example.com does not have execute rights
The upload script is named upload.php and is located at example.com
I run a virus scanner on images.example.com every day

A simple upload script written in PHP:

$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 20000)
&& in_array($extension, $allowedExts))
  {
  if ($_FILES["file"]["error"] > 0)
    {
    echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
    }
  else
    {
    if (file_exists("upload/" . $_FILES["file"]["name"]))
      {
      echo $_FILES["file"]["name"] . " already exists. ";
      }
    else
      {
      move_uploaded_file($_FILES["file"]["tmp_name"],
      "images.example.com/" . randomName() .$_FILES["file"]["name"]);
      }
    }
  }
else
  {
  echo "Invalid file";
  }

The script is demonstrating my thoughts; nothing more.
So from what I understand now, all images uploaded cant do any harm to example.com, even if they contain injected code?
Do I not need to do a exif or Fileinfo check since I put the files on a subdomain?
I've assumed a lot of things.  Did I miss anything?


texts: Find median of two sorted arrays, with complexity of min(log(m),log(n))

texts:
I wrote a program which gets two sorted arrays a and b (with sizes m and n respectively), and calculates the median value of these arrays without merging them.

Here is my code:

#include <iostream>
using namespace std;

int findMedian(int a[], int b[], int m, int n);
int max(int a, int b);
int min(int a, int b);

void main()
{

    int m, n, *a, *b, i;

    cout << " enter the size of the first array: ";
    cin >> m;
    a = new int[m];
    cout << " \nenter the size of the second array:";
    cin >> n;
    b = new int[n];

    cout << " \nthe numbers of the first array in sorted way: ";
    for (i = 0; i < m; i++)
        cin >> a[i];

    cout << "\nplease enter your numbers of the second array in sorted way: ";
    for (i = 0; i < n; i++)
        cin >> b[i];

    cout << "\nthe median of the merged array is : " << findMedian(a, b,  m,  n)<< '\n';

    free(b);
    free(a);
}

int findMedian(int a[], int b[], int m, int n)
{

    int imin = 0, imax = m, half_len = (m + n + 1) / 2;
    int i, j, max_of_left, min_of_right;

    while (imin <= imax)
    {
        i = (imin + imax) / 2;
        j = half_len - i;

        if (i < m && b[j - 1] > a[i])
            imin = i + 1;

        else if (i > 0 && a[i - 1] > b[j])
            imax = i - 1;

        else
        {

            if (i == 0)
                max_of_left = b[j - 1];

            else if (j == 0)
                max_of_left = a[i - 1];

            else
                 max_of_left = max(a[i - 1], b[j - 1]);

            if ((m + n) % 2 == 1)
                return max_of_left;

            if (i == m)
                min_of_right = b[j];
            else if (j == n)
                min_of_right = a[i];
            else
                min_of_right = min(a[i], b[j]);

                return min(max_of_left,min_of_right);
        }
    }

}

int max(int a, int b)
{
    return a > b ? a : b;
}

int min(int a, int b)
{
    return a < b ? a : b;
}

One particular thing I'd like to improve is that although the program seems to run correctly, I get this warning; I can't understand why it happens and don't know how it should be fixed:

warning C4715: 'findMedian': not all control paths return a value


texts: SQL to list function - turning a table column into a delimited list string

texts:
I wrote this very "general use" function, because I needed that in some reporting. I was wondering if there is any suggetsion for improvement.

Function sql2List(sSql As String, Optional quote As String, Optional separ As String = ", ") As String
    Static db As DAO.Database
    Dim rs As DAO.Recordset
    Dim result As String
    'Debug.Print Now, sSql
    If db Is Nothing Then Set db = CurrentDb
    Set rs = db.OpenRecordset(sSql, dbOpenSnapshot)
    Do Until rs.EOF
        result = result & quote & rs.Fields(0).Value & quote & separ
        rs.MoveNext
    Loop
    rs.Close
    Set rs = Nothing
    'Set db = Nothing
    If Len(result) > Len(separ) Then sql2List = Left(result, Len(result) - Len(separ))
End Function

I call it from control or module or other queries like this:

strList = sql2List("select dt from planning where client = " & clientId)


texts: Conways game of life with turtle python 3

texts:
A version of CGOL made in Python using the turtle module.
Any suggestions for optimisations or improvement:

import time
import turtle
import threading
wn = turtle.Screen()
t = turtle.Turtle()
t.penup()
t.speed(0)
t.ht()
mode = int(input("What mode do you want to use to get the initial state? (1 - from a .cgol file,2 - random)"))
speed = float(input("How long is the delay between generations (seconds)"))
CellList = []
#length = 0
if mode == 1:
    file = open(input('Please input the .cgol file name: ')+'.cgol','r')
    code = file.readlines()
    for i in code:
        templist = list(i)
        while '\n' in templist:
            templist.remove('\n')
        templist2 = []
        for u in templist:
            templist2.append(int(u))
        CellList.append(templist2)
if mode == 2:
    import random
    length = int(input("How many cells across is the grid?"))
    for i in range(0,length):
        ShortList = []
        for u in range(0,length):
            ShortList.append(int(random.randrange(0,2)))
        CellList.append(ShortList)

Display = []
FriendList = []
for i in range(0, len(CellList)):
    FriendList.append([])
while True:
    wn.tracer(0,0)
    Display = []
    for y in range(0,len(CellList)):
        for x in range(0,len(CellList)):
            ymin = y - 1
            xmin = x - 1
            yplus = y + 1
            xplus = x + 1
            if yplus > len(CellList)-1:
                yplus = 0
            if ymin < 0:
                ymin = len(CellList)-1
            if xplus > len(CellList)-1:
                xplus = 0
            if xmin < 0:
                xmin = len(CellList)-1
            FriendList[y].append(CellList[xmin][ymin] + CellList[xmin][yplus] + CellList[xmin][y] + CellList[xplus][ymin] + CellList[xplus][yplus] + CellList[xplus][y] + CellList[x][ymin] + CellList[x][yplus])
    for x in range(0,len(CellList)):
        Display.append("\n")
        for y in range(0,len(CellList)):
            if CellList[x][y] == 1:
                if FriendList[y][x] > 3:
                    CellList[x][y] = 0
                if FriendList[y][x] < 2:
                    CellList[x][y] = 0
            else:
                if FriendList[y][x] == 3:
                    CellList[x][y] = 1
            Display.append(str(CellList[x][y]))
    for i in range(0,(len(CellList)**2)+len(CellList)):
        if Display[i] == '1':
            Display[i] = '||'
        if Display[i] == '0':
            Display[i] = '  '
    for y in range(0,len(CellList)):
        for x in range(0,len(CellList)):
            if CellList[y][x] == 1:
                t.goto(x*10,-y*10)
                t.dot(10)
    FriendList = []
    for i in range(0, len(CellList)):
        FriendList.append([])
    print("".join(Display))
    Display = []
    wn.update()
    t.clear()
    time.sleep(speed)

.cgol files are txt's with a custom extension. they should be made in the format of a grid with 1 being the cell is on and 0 if the cell is dead. eg

00000000000000000000
00000000000000000000
00000001000000000000
00000000000000000000
00000000001000000000
00001000000000100000
00000000000000000000
00000000010000000000
00000000000000000000
00000000000000000000
00000000000000000000
00000000000000000000
00000000000000000000
00000000000000100000
00000100000000000000
00000000010000001000
00000000000000000000
00000000000001000000
00000001000000000000
00000000000000000000


texts: Javacript/jQuery animation makes text appear/disappear as if typed

texts:
On Eric Amodio's website and JS.ORG, there is a Javascript animation which makes text appear/disappear as if it is being typed.
I tried to replicate something similar but far more basic on JSFiddle.
In my experiment, the words Code review appear typed, are hidden by toggle(200), and the words Code review appears again.
My final result was a mess of  tags and massive blocks of consequent setTimeout() JS functions.

 |

p {
  line-height: 10px;
}

setTimeout(function() {
  $("#bar").before("C");
}, 100);

setTimeout(function() {
  $("#bar").before("o");
}, 200);

setTimeout(function() {
  $("#bar").before("d");
}, 300);

setTimeout(function() {
  $("#bar").before("e");
}, 400);

setTimeout(function() {
  $("#bar").before(" ");
}, 500);

setTimeout(function() {
  $("#bar").before("R");
}, 600);

setTimeout(function() {
  $("#bar").before("e");
}, 700);

setTimeout(function() {
  $("#bar").before("v");
}, 800);

setTimeout(function() {
  $("#bar").before("i");
}, 900);

setTimeout(function() {
  $("#bar").before("e");
}, 1000);

setTimeout(function() {
  $("#bar").before("w");
}, 1100);

/* HIDE .TYPED-ANIMATION */

setTimeout(function() {
  $(".typed-letter").toggle(200);
}, 1300);

/* SECOND ITERATION */

setTimeout(function() {
  $("#bar").before("C");
}, 1600);

setTimeout(function() {
  $("#bar").before("o");
}, 1700);

setTimeout(function() {
  $("#bar").before("d");
}, 1800);

setTimeout(function() {
  $("#bar").before("e");
}, 1900);

setTimeout(function() {
  $("#bar").before(" ");
}, 2000);

setTimeout(function() {
  $("#bar").before("R");
}, 2100);

setTimeout(function() {
  $("#bar").before("e");
}, 2200);

setTimeout(function() {
  $("#bar").before("v");
}, 2300);

setTimeout(function() {
  $("#bar").before("i");
}, 2400);

setTimeout(function() {
  $("#bar").before("e");
}, 2500);

setTimeout(function() {
  $("#bar").before("w");
}, 2600);

Fiddle

How can I use functions, arrays and loops in my JS/jQuery instead of massive blocks of consequent setTimeout functions to simplify my code and make it more efficient?
How can I make it so that the text also disappears in a 'typed' way, instead of using toggle(200) to hide the text again?


texts: Cloning Distinct XML structures without data in PHP

texts:
I struggled for the last couple days on this question and finally came up with a solution. But it's got so many loops I get dizzy just looking at the code - from recursive functions with loops to loops within loops.

I really expected to find a canned function in a popular XML class to extract all the unique nodes without data, but I am surprised how non-trivial I've found this endeavor.

While this works for my piddly example data, I have performance and scalability concerns when trying to use this code in production. For example, this elegant answer uses XSLT to solve the problem, but it's limited by node depth. So is there anyway to improve efficiency by cutting out a loop, or using less objects, or even utilizing a different class or technology completely? Are there any glaring failing conditions that aren't represented in my example data?

<?php
$xml = '
<root>
  <node/>
  <node>
    more
  </node>
  <node>
    another
  </node>
  <node>value</node>
</root>
';
$doc = new DOMDocument();
$doc->loadXML($xml);

// clone without data
$empty_xml = new DOMDocument();
$empty_xml->appendChild($empty_xml->importNode($doc->documentElement));
function clone_without_data(&$orig, &$clone, &$clonedoc){
  foreach ($orig->childNodes as $child){
    if(get_class($child) === "DOMElement")
      $new_node = $clone->appendChild($clonedoc->importNode($child));
    if($child->hasChildNodes())
      clone_without_data($child,$new_node,$clonedoc);
  }
}
clone_without_data($doc->documentElement, $empty_xml->documentElement, $empty_xml);

// remove all duplicates
$distinct_structure = new DOMDocument();
$distinct_structure->appendChild($distinct_structure->importNode($doc->documentElement));
foreach ($empty_xml->documentElement->childNodes as $child){
  $match = false;
  foreach ($distinct_structure->documentElement->childNodes as $element){
    if ($distinct_structure->saveXML($element) === $empty_xml->saveXML($child)) {
      $match = true;
      break;
    }
  }
  if (!$match)
    $distinct_structure->documentElement->appendChild($distinct_structure->importNode($child,true));
}
$distinct_structure->formatOutput = true;
echo $distinct_structure->saveXML();

This results in the unique XML structures stripped of all data:

<?xml version="1.0"?>
<root>
  <node/>
  <node>

  </node>
</root>


texts: Handler for bidirectional unit conversion form

texts:
Building a form where values can be entered in either pounds or kilos.

Script is...

function onlyNumber(fld) {
     if(fld.value.match(/[^0-9.]/)) {
     fld.value=fld.value.replace(/[^0-9.]/g,'');
     }
}
function convertUnit(sense, value) {
    retValue = 0;
    if (isNaN (value)) { alert ('Non-numeric value');  return 0; }
    value = parseFloat (value);
    var factor = 0.4536;
    if (sense == 'kg2lb') {
         retValue = value/factor;
         retValue = Math.round(retValue);
    }
    else if (sense == 'lb2kg') {
         retValue = value*factor;
         retValue = Math.round(retValue);
    }
    return retValue;
}

Works fine but I have to repeat this on every input:

onblur="this.form.kg_va.value=convertUnit('lb2kg',this.value);"
onkeyup="onlyNumber(this);" onfocus="if(this.value == '0') { this.value = ''; }"

Is there some way to simplify the onblur code ?

For example, is there a way to have the function focus on the same var pairs? The var pair being lb_FOOBAR and kg_FOOBAR.

And what about the input functions that are exactly the same?

onkeyup="onlyNumber(this);" onfocus="if(this.value == '0') { this.value = ''; }"

Any way to avoid having to repeat them for each input? Form will have 12 fields.


texts: Creating a list of pairs after splitting the string containing all of the sets

texts:
I am working on asp.net/MVC and I need to read a value from my web.config file. Splitting the list into multiple keys is not an option.

<add key="DepartAssign" value="Depart1:PersonAssignTo1; Depart2:PersonAssignTo2"/>

I handled the problem by doing the following (which I am sure that there is a better approach)

public List<string> departmentList = new List<string>();
public List<string> assignedtoList = new List<string>();
public string[] pair = ConfigurationManager.AppSettings["DepartAssign"].Split(';');
foreach (string s in pair)
{
     departmentList.Add(s.Split(':').First()); //add the department to the list
     assignedtoList.Add(s.Split(':').Last()); //add the assignedto to the list
 }

and of course, I would be able to match the department with the assigned person by using the same index. Not really the cleanest approach but it works for now.

any way to make this code better?


texts:
I am using some string which contains an html. As follows

var pagerHtml = 'No.Of Records<select class="rmselect" id="records" ><option value="10">10</option><option value="20">20</option><option value="40">40</option><option value="80">80</option><option value="100">100</option></select>';

Another is with " and escape sequence \" for " in the html as follows

var pagerHtml = "No.Of Records<select class=\"rmselect\" id=\"records\" ><option value=\"10\">10</option><option value=\"20\">20</option><option value=\"40\">40</option><option value=\"80\">80</option><option value=\"100\">100</option></select>";

And I am writing this html to a div using jquery

Which one gives the better performance while parsing?

Is there any performance difference on parsing escape sequence?


texts: Generate code from full name and index number

texts:
Does this script look well-written and formulated?

'''
This is for a practice
Get the last letter from first_name, 2nd and 3rd letters from last name
First 5 numbers from index number.
And generate a a unique code.
'''

import sys

first_name = 'first_name'
last_name = 'last_name'
index_number = str('02001201525') # Converting number to str so it can concat

def from_index(index_number):
    for n in index_number.split():
        return n[0:5]

def generate_code(first_name, last_name):
    letters_from_first_name = first_name[-1]
    letters_from_last_name = last_name[0:2]
    n_from_index = from_index(index_number)
    code = letters_from_first_name + letters_from_last_name + n_from_index
    return code # To the world

 print generate_code(first_name, last_name);

 sys.exit() # Is importing the sys module important as i am not iterating


texts: Optimize this code of adapter's overriden method getItemCount()

texts:
How can I optimize this code of adapter's overriden method getItemCount()  into simpler form?

@Override
    public int getItemCount() {
        return super.getItemCount() == 0 && data != null ? 1 : super.getItemCount();
    }


texts: Merging key-value sets as specified by a command

texts:
private void merge(ArrayList<String> operations, ArrayList<LinkedHashSet<String>> setOfStrings) {
        String toMerge = operations.get(1);
        String fromMerge = operations.get(2);
        boolean enteredFirstToMerge = false;
        boolean enteredFirstForMerge = false;
        // references that points one on toMerge and the other on fromMerge
        LinkedHashSet<String> toMergeAndAfterDelete = null;
        LinkedHashSet<String> addOnFromMerge = null;
        for (LinkedHashSet<String> subSet : setOfStrings) {
        if (subSet.contains(toMerge) && subSet.contains(fromMerge))
            break;
        else {
            if (subSet.contains(toMerge) && !enteredFirstToMerge) {
            toMergeAndAfterDelete = subSet;
            enteredFirstToMerge = true;
            }
            if (subSet.contains(fromMerge) && !enteredFirstForMerge) {
            addOnFromMerge = subSet;
            enteredFirstForMerge = true;
            }
            if ((enteredFirstForMerge && enteredFirstToMerge)) {
            break;
            }
          }
        }
        /***********************************************/
        //outside Loop i call the remove on the arraylist
        //that are very expensive
        /*************************************************/
        if (enteredFirstForMerge && enteredFirstToMerge) {
        // first i delete from the array the linkedHashSet toMerge and
        // fromMerge and after i add a
        // new linkedHashSet with the subSets merged
        setOfStrings.remove(toMergeAndAfterDelete);
        setOfStrings.remove(addToMergeOnFromMerge);
        addOnFromMerge.addAll(toMergeAndAfterDelete);
        setOfStrings.add(addOnFromMerge);
        }
}

This function takes as parameter an arrayList of operations, and an ArrayList<LinkedHashSet<String>>:

For the arrayList of operations, I always get a specific position, so I don't iterate.    It is always \$O(1)\$.

For example, if I have as operation move foo bar, I have to do these steps:

First of all, I have to find where are located foo and bar:

Inside setOfStrings, I can have this situation:

    position x : {bar tree hotel}
    ...
    position y : {foo lemon coffee}

When I find them, I have to  concat the foo string into bar string  in this way:

            position x : {bar tree hotel foo lemon coffee}
            ...
            position y : {}

How can I improve the efficiency of this function?


texts:
This question is a followup to the last one.

I followed RobH's advice and his edge case bug found in my code with this solution:

private Line CreateParallelLine(Line target, int offset)
{
    var parallelLine = new Line();
    var xDifference = target.point1.x - target.point2.x;
    var yDifference = target.point1.y - target.point2.y;
    var length = Math.Sqrt(Math.Pow(xDifference, 2) + Math.Pow(yDifference, 2));

    parallelLine.point1.x = (float)(target.point1.x - offset * yDifference/length);
    parallelLine.point2.x = (float)(target.point2.x - offset * yDifference/length);
    parallelLine.point1.y = (float)(target.point1.y + offset * xDifference/length);
    parallelLine.point2.y = (float)(target.point2.y + offset * xDifference/length);

    return parallelLine;
}

Now, since his solution only provided a means of creating one parallel line, even though I need to draw several lines, I have this method that draws the parallel lines (it works) but it is long and there is repeat code:

private void DrawParallelLines(object sender, LineDrawingEventArgs e)
    {
        Line referenceLine = CameraObject.GetComponent<DrawLines>().GetLineParams(ViewType + StickLocationEnum.ToString() + linename);
        Line ParallelLine1 = CameraObject.GetComponent<DrawLines>().CreateParallelLine(referenceLine, 50);
        Line ParallelLine2 = CameraObject.GetComponent<DrawLines>().CreateParallelLine(referenceLine, -50);
        Line ParallelLine3 = CameraObject.GetComponent<DrawLines>().CreateParallelLine(referenceLine, 100);
        Line ParallelLine4 = CameraObject.GetComponent<DrawLines>().CreateParallelLine(referenceLine, -100);

        LineParams paramForParallelLine = new LineParams(ViewType + "ParallelLine", Color.green, Color.green, EndPointType.Circle, EndPointType.Circle, lineThickness, endPointThickness);
        Line parallellineWithParams1 = new Line(ParallelLine1.point1, ParallelLine1.point2, paramForParallelLine, ElementType.Line);
        Line parallellineWithParams2 = new Line(ParallelLine2.point1, ParallelLine2.point2, paramForParallelLine, ElementType.Line);
        Line parallellineWithParams3 = new Line(ParallelLine3.point1, ParallelLine3.point2, paramForParallelLine, ElementType.Line);
        Line parallellineWithParams4 = new Line(ParallelLine4.point1, ParallelLine4.point2, paramForParallelLine, ElementType.Line);

        CameraObject.GetComponent<DrawLines>().AddNewLine(parallellineWithParams1);
        CameraObject.GetComponent<DrawLines>().AddNewLine(parallellineWithParams2);
        CameraObject.GetComponent<DrawLines>().AddNewLine(parallellineWithParams3);
        CameraObject.GetComponent<DrawLines>().AddNewLine(parallellineWithParams4);
        CameraObject.GetComponent<DrawLines>().UpdateAllLabels();
    }

What is the best way to refactor this method to remove redundant code?


texts: Getting the miliseconds from now to the next midday

texts:
I need to get the total milliseconds to the next mid-day (12:00:00) to signal a timer that will run once a day.

Assuming the application can be shut down and started anytime, is this code to get the milliseconds left to midday (used to set the timer) correct? (It doesn't need to be exact; it can be off by a few seconds.)

TimeSpan now = DateTime.Now.TimeOfDay;
TimeSpan target = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 12, 0, 0).TimeOfDay;

double r = target.TotalMilliseconds - now.TotalMilliseconds;

if (r > 0) // It's before noon
    ;
else // It's after noon
    r = TimeSpan.FromTicks(TimeSpan.TicksPerDay).TotalMilliseconds + r;

t = new Timer(DoWork, null, r, TimeSpan.FromTicks(TimeSpan.TicksPerDay));

Can it be done more efficiently or in fewer lines of code?


texts: Splitting Hashmap by converting to TreeMap

texts:
I have a project requirement where I have to split a HashMap of around 60-70 entries into multiple HashMaps. The critical number of the split is 30 due to performance reasons because eventually this HashMap is going to be wrapped in a customer Request object and sent in an API call. The receiving end during performance testing found that 30 is the only number they can take for good performance.

So, I have to split the HashMap of 70 subscribers into sub-HashMaps of - 30, 30, 10.

Since HashMaps do not have methods like - subMap() or tailMap() - I am thinking of converting the HashMap into TreeMap. Here's my implementation:

checkAndSplitSubscribers(Map<String, Type> originalMap) throws Exception {
      List<Map<String, Type>> listOfSplitMaps = new ArrayList<Map<String, Type>>();
      int criticalNumber = 30; (Although this will be configurable)

      try {
           TreepMap<String, Type> treeMap = new TreeMap<String, Type> (originalMap);
           List<String> keys = new ArrayList<String> (originalMap.keySet());

           final int originalMapSize = treeMap.size();

           for (int i = 0; i < originalMapSize; i += criticalNumber) {
               if (i + criticalNumber < originalMapSize) {
                    listOfSplitMaps.add(treeMap.subMap(keys.get(i), keys.get(i + criticalNumber));
               } else {
                    listOfSplitMaps.add(treeMap.tailMap(keys.get(i));
               }
           }
      } catch (Exception e) {
           throw e;
      }

      return listOfSplitMaps;
  }

I want to ask if there is anything wrong with this implementation? Is converting HashMap to TreeMap mid way of the code really a bad programming practice? Or if there's any better way to achieve the above, please suggest (I have searched and gone through almost all splitting hashmap questions on SO but I did not find any answer to my satisfaction).


texts: Saving temporary file for plotting audio waveform

texts:
I am developing a web application in Flask - Python.

My goal is to let the user upload an mp3/wav file. This file will (for the scope of this question) get processed by the server and a picture showing the waveform of the audio file will be shown to the user.

My concern is that I am not experienced with neither Flask nor web applications. I would like this audio file to be saved somewhere temporarily, then get deleted. Similarly, I would like the picture of the waveform to just be shown without being saved after the user sees it. This is because I expect all the mp3/wav files to be different - there is no point in saving them.

Right now I have this method that gets called when a user uploads file:

def handle_file(file):
  filename = secure_filename(file.filename)
  filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
  file.save(filepath)
  mir.save_plot(filepath)
  os.remove(filepath)
  plot_filepath = PLOT_FOLDER + 'audio.png'
  return plot_filepath

As you can see, I first save the audio file to a directory in the server, then process it (mir.save_plot does that), then I remove it, and then I return the plot_filepath which will be used in the template to show the final plot picture.

The mir.py file is the following:

import librosa
import plot as plt

def save_plot(filename):
    y, sr = librosa.load(filename)
    plt.plot(y, 'audio', 'time', 'amplitude')

The plot.py file:

import matplotlib.pylab as plt

def plot(vector, name, xlabel=None, ylabel=None):
    plt.figure()
    plt.plot(vector)
    plt.xlabel(xlabel)
    plt.ylabel(ylabel)
    plt.plot()
    plt.savefig('static/plots/' + name)

I feel like my design is poor and there is a better way to do this. Am I right?

The rest of the code:

def allowed_file(filename):
  return '.' in filename and \
    filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@app.route('/', methods=['GET', 'POST'])
def index():
  if request.method == "GET":
    return render_template('index.html', request="GET")
  else:
    if 'file' not in request.files:
      flash('No file part')
      return redirect(request.url)
    file = request.files['file']
    if file.filename == '':
      flash('No selected file')
      return redirect(request.url)
    if file and allowed_file(file.filename):
      plot_filepath = handle_file(file)
    return render_template('index.html', request="POST", filepath=plot_filepath)

The allowed_file() and majority of index() code are from the Flask docs.


texts:
Follow up of - Dynamically-sized stack - follow up

I've took the tips given to me, and what I did now is:

changing the function names to have a prefix
making the pop() function only popping and not returning the value as well
checking for OOM exception / scenario that 0 is passed to capacityIncrement variable when initializing the stack (in those cases, if trying to push values to the stack, just ignore)
added a decrement mechanism, when popping values a check will be made to see if there are (capacityIncrement / 2 + capacityIncrement) elements in the stack that are not in use, and if so, decrement the stack size by capacityIncrement

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

typedef struct
{
    int *elementData;
    unsigned int stackSize;
    unsigned int capacityIncrement;
    unsigned int elementCount;
} Stack;

void stack_initialize(Stack*, unsigned int);
void stack_push(Stack*, int);
void stack_pop(Stack*);
int stack_peek(const Stack*);
void stack_destroy(Stack*);
bool stack_isEmpty(const Stack*);
void stack_setCapacityIncrement(Stack*, unsigned int);
unsigned int stack_getCapacityIncrement(const Stack*);
unsigned int stack_getNumberOfElements(const Stack*);
unsigned int stack_getSize(const Stack*);

int main()
{
    Stack s1;
    stack_initialize(&s1, 4);
    for(int i = 0; i < 25; i++)
    {
        stack_push(&s1, i + 1);
    }
    stack_pop(&s1);
    stack_push(&s1, 88);
    stack_push(&s1, 25);
    printf("The top of the stack is %d.\n", stack_peek(&s1));
    while(!stack_isEmpty(&s1))
    {
        int top = stack_peek(&s1);
        stack_pop(&s1);
        printf("Popping %d from the top of the stack.\n", top);
        printf("Size of stack is %d.\n", s1.stackSize);
    }
    return 0;
}

void stack_initialize(Stack *p, unsigned int capacityIncrement)
{
    p->elementData = NULL;
    p->stackSize = 0;
    p->capacityIncrement = capacityIncrement;
    p->elementCount = 0;
}

void stack_push(Stack *p, int value)
{
    if (p->elementCount == p->stackSize)
    {
        int newStackSize = p->stackSize + p->capacityIncrement;
        void *temp = realloc(p->elementData, sizeof(*p->elementData) * newStackSize);
        if (temp == NULL || newStackSize == 0)
        {
            return;
        }
        p->stackSize = newStackSize;
        p->elementData = temp;
    }
    p->elementData[p->elementCount] = value;
    p->elementCount++;
}

void stack_pop(Stack *p)
{
    if (!stack_isEmpty(p))
    {
        p->elementCount--;
        if(p->stackSize - p->elementCount == p->capacityIncrement / 2 + p->capacityIncrement)
        {
            int newStackSize = p->stackSize - p->capacityIncrement;
            p->elementData = realloc(p->elementData, sizeof(*p->elementData) * newStackSize);
            p->stackSize = newStackSize;
        }
    }
}

int stack_peek(const Stack *p)
{
    if (!stack_isEmpty(p))
    {
        return p->elementData[p->elementCount - 1];
    }
    return 0;
}

void stack_destroy(Stack *p)
{
    free(p);
}

bool stack_isEmpty(const Stack *p)
{
    return p->elementCount == 0;
}

void stack_setCapacityIncrement(Stack *p, unsigned int capacityIncrement)
{
    p->capacityIncrement = capacityIncrement;
}

unsigned int stack_getCapacityIncrement(const Stack *p)
{
    return p->capacityIncrement;
}

unsigned int stack_getNumberOfElements(const Stack *p)
{
    return p->elementCount;
}

unsigned int stack_getSize(const Stack *p)
{
    return p->stackSize;
}


texts:
I have been trying to write a BrainF*** program that prints the Fibonacci sequence numbers repeatedly. I was wondering whether this is the most efficient way to do it. I basically repeatedly duplicate two cells into a third cell, and shift one cell forward and repeat.

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


texts:
I was in need of a function that could check a string against a certain pattern at compile-time. The pattern can contain any of the commonly known wildcards: ?, * and +.

? - match any character.
* - match any sequence of characters, including the empty string.
+ - equal to ?*

I'm not sure how to test my code for errors, is there a set of patterns and strings that will determine (with 100% certainty) nothing is wrong with my code? If not, could any of you spare a moment and check my code for errors?

I've tested this code and it seems to work fine. Also, is this a good way of implementing compile-time functionality?

Compiled with: clang++ -std=c++11

Just as a help to more easily get into this code, I've tried to write the syntax in such a way to represent an if-elseif chain. The indentation shows the level of nesting.

constexpr int MatchPattern_Rec(const char* pattern, const char* text) {
    return *pattern == '\0' || *text == '\0' ? *pattern == *text :
            *pattern == '?' ? MatchPattern_Rec(pattern+1, text+1) :
            *pattern == '*' ?
                MatchPattern_Rec(pattern+1, text) ? 1 :
                MatchPattern_Rec(pattern, text+1) ? 1 :
                0 :
            *pattern == '+' ?
                MatchPattern_Rec(pattern+1, text+1) ? 1 :
                MatchPattern_Rec(pattern, text+1) ? 1 :
                0 :
            *pattern == *text ? MatchPattern_Rec(pattern+1, text+1) :
            0;
}

constexpr int MatchPattern(const char* pattern, const char* text) {
    return *pattern == '\0' ? 0 :
            *pattern == '*' && *(pattern+1) == '\0' && *text == '\0' ? 1 :
            MatchPattern_Rec(pattern, text);
}

Some side notes:

The code will only be run when compiling debug builds. Performance is the least of my worries.
The strings and patterns will be limited in size (max. 50 characters) and the patterns will have 5 wildcards at most. The stack should be big enough to handle that level of recursion.


texts:
I have designed a logger class to log messages to a file. It uses an independent thread to log the messages save to a queue previously using the main thread. I want to receive reviews about it.
#include <iostream>
#include <queue>
#include <mutex>
#include <condition_variable>
#include <fstream>
#include <atomic>
#include <string>
using namespace std::chrono_literals;

class Logger
{
    std::mutex queueMutex;
    std::condition_variable condVar;
    std::queue<std::string> messagesQueue;
    std::thread loggingThread;//background process launcher
    std::atomic_bool exit = false;//safety condition
    void processEntries()//the background process
    {
        // Open log file.
        std::ofstream logFile("log.txt");
        if (logFile.fail()) {
            std::cerr << "Failed to open logfile." << std::endl;
            return;
        }

        // Start processing loop. It process only one message for each iteration
        // to gain more performance
        while (!exit) {
            std::unique_lock lock(queueMutex);

            // Wait for a notification and don't wakeup unless the queue isn't empty.
            condVar.wait(lock, [this]{return !messagesQueue.empty();});

            //log to the file
            logFile << messagesQueue.front() << std::endl;
            messagesQueue.pop();
        }

        //At the end, if the queue has some messages. here you don't need mutexes
        // because you have reached the destructor i.e you won't enqueue any messages anymore
        while(exit && !messagesQueue.empty()){

            //log to the file
            logFile << messagesQueue.front() << std::endl;
            messagesQueue.pop();
        }

    }

public:
    Logger()
    {
        //the default ctor launches the background process task
        loggingThread = std::thread{ &Logger::processEntries, this };
    }
    Logger(const Logger& src) = delete;
    Logger& operator=(const Logger& rhs) = delete;

    //logs the messages to the queue
    void log(std::string_view entry)
    {
        std::unique_lock lock(queueMutex);
        messagesQueue.push(std::string(entry));
        condVar.notify_all();
    }

    ~Logger()
    {
        exit = true;
        loggingThread.join();
    }

};

int main(){

    Logger lg;
    for(int i = 1;i < 10000;i++){
        lg.log("This is the message number " + std::to_string(i));
    }

    std::this_thread::sleep_for(10ms);

    for(int i = 10000;i < 20001;i++){
        lg.log("This is the message number " + std::to_string(i));
    }

}


texts: How to have  elements with different links on each image?

texts:
Time ago I had a header implemented with a Bootstrap carousel: You know, something like this:

Pay attention to that link on "pic2.jpg", this will be fun...
Recently, I have been asked to use <picture> elements, so now it is posible to display images for mobile devices:

    <picture>
        <source media="(max-width: 576px)" srcset="pic1-small.jpg">

     </picture>

    <picture>
        <source media="(max-width: 576px)" srcset="pic2-small.jpg">

     </picture>

And here is the tricky question: I need to add a link only in the mobile image (pic2-small.jpg).
(Well, in fact could be links on every image, or none at all, only in the mobile image, only in the desktop image... This is managed by the administrator user)
So, I can't do this because the link should be only for pic2-small, not pic2:

        <picture>
            <source media="(max-width: 576px)" srcset="pic2-small.jpg">

         </picture>

What I did is this:

    <picture>
        <source media="(max-width: 576px)" srcset="pic2-small.jpg?target=pic2-small-link">

     </picture>

An onclick event in the carousel item and a javascript function.
A target value in the URL of the image.
A hidden  with the destination URL.

The magic is in this line:
var current_src = carousel_item.querySelector("img").currentSrc;

currentSrc has the URL of the image that the browser is currently showing according to the screen size. So, from that URL I take the target parameter and use it to get the corresponding link and then execute it.
All this is working, but I feel it too hacky for my taste. I'm not very experienced with the <picture> element, so my question is: this could be resolved in a better way?


texts:
Is there anything I can do to this code to optimize it to use less resources?

write-host (get-date -format s) " Beginning script..."
Add-Type -AssemblyName System.Windows.Forms
do{
    $len = [System.Windows.Forms.Screen]::AllScreens.Length;
    if($len-eq1){
        $ie = Get-Process -Name iexplore -ErrorAction SilentlyContinue
        if ($ie -ne $null){
            Write-Host (get-date -format s) "Stopping IE..."
            $ie | Stop-Process
        }
    }elseif($len-eq2){
        $ie = Get-Process -Name iexplore -ErrorAction SilentlyContinue
        if ($ie -eq $null){
            write-Host (get-date -format s) " Starting IE..."
            Start-Sleep -s 5 #5
            $ie = Open-InternetExplorer -Url http://localhost/ -Left 1366 -FullScreen -InForeground #This is an external function that works well.
            write-Host (get-date -format s) " IE Started"
        }
    }
    start-sleep -s 10
}while(1-eq1)


texts: Feynmann lifeguard riddle graphical representation

texts:
Physicist Richard Feynman though of a very interesting riddle:

Imagine you are a lifeguard at the side of the beach and there is a child drowning in the water. (You must cross both sand and water to get to him)
Which route would you take to go to the child and save him?

Not a straight line1 because in the sand you move faster than in the water so the advantage of staying a larger percentage of the trip on the sand outweighs the disadvantage of having a longer trip (straight line is shortest) up to a certain point.
How to get an intuition about the shape of such route?
I wrote a simple visualization with modifiable parameters to get an intuitive feeling for different start positions and sand/sea speed ratios, here is an example (yellow is sand, blue is sea):

I am interested in all kinds of suggestions, here is the code:
from tkinter import *

LIFEGUARD_Y = 100
CHILD_Y = 350
SAND_SPEED = 3 # SEA_SPEED = 1
WIDTH = 500
HEIGHT = 500

def distance(a, b):
    return ((a[0] - b[0])**2 + (a[1]-b[1])**2)**0.5

def total_time(lifeguard_y, child_y, midpoint_y,sand_speed=SAND_SPEED):
    sand_len = distance( (lifeguard_y, 0), (midpoint_y, WIDTH//2) )
    sea_len = distance( (midpoint_y, WIDTH//2), (child_y, WIDTH) )
    sand_time = sand_len / sand_speed
    sea_time  = sea_len / 1
    return sand_time + sea_time

def find_optimal_midpoint_y(lifeguard_y, child_y,sand_speed=SAND_SPEED):
    return min(range(0, 500), key=lambda y: total_time(lifeguard_y, child_y, y, sand_speed))

def show_situation():
    master = Tk()

    master.title("Feymann lifeguard route problem")
    w = Canvas(master, width=WIDTH, height=HEIGHT)
    w.pack()

    l = Label(master, text="Lifeguard Y")
    l.pack()

    lifeguard_y_w = Scale(master, from_=0, to=HEIGHT, orient=HORIZONTAL)
    lifeguard_y_w.pack()

    l = Label(master, text="Child Y")
    l.pack()

    child_y_w = Scale(master, from_=0, to=HEIGHT, orient=HORIZONTAL)
    child_y_w.pack()

    l = Label(master, text="Sand Speed / Sea Speed ratio")
    l.pack()

    sand_speed_w = Scale(master, from_=1, to=3, resolution=0.1, orient=HORIZONTAL)
    sand_speed_w.pack()

    w.create_rectangle(0, 0, WIDTH//2, HEIGHT, fill="yellow")
    w.create_rectangle(WIDTH//2, HEIGHT, WIDTH, 0, fill="blue")

    def draw_optimal_route():
        w.create_rectangle(0, 0, WIDTH//2, HEIGHT, fill="yellow")
        w.create_rectangle(WIDTH//2, HEIGHT, WIDTH, 0, fill="blue")

        midpoint_y = find_optimal_midpoint_y(lifeguard_y_w.get(), child_y_w.get(), sand_speed=sand_speed_w.get())

        w.create_line(0, lifeguard_y_w.get(), WIDTH//2, midpoint_y)
        w.create_line(WIDTH//2, midpoint_y, WIDTH, child_y_w.get())

    b = Button(master, text="GO", command=draw_optimal_route)
    b.pack()

    mainloop()

if __name__ == "__main__":
    show_situation()

1 A straight line only in the trivial and non-realistical case where sand-speed = sea-speed such as for a bird.
Bonus Physics Note: Light behaves the same way as this perfect lifeguard because it always chooses the fastest path.


texts: Which is better for checking previous object in list?

texts:
I have a for loop which loops through a list and builds and object, I needed to check the previous object with the one i'm building...which way is better?

This way?:

    String lastDirection= "";
    List<Stages> stages = new ArrayList();
    for (Object object : results) {
        Vector result = (Vector) object;
        Stages stage = new Stages();
        stage.setStage(result.get(0).toString());
        stage.setDirection((String) result.get(1));
        stage.setStageName((String) result.get(2));
        if(!stage.getDirection.equals(lastDirection))
            stages.add(stage);
        lastAtco = stage.getDirection();
    }
    return stages;

Or This way?:

    List<Stages> stages = new ArrayList();
    for (Object object : results) {
        Vector result = (Vector) object;
        Stages stage = new Stages();
        stage.setStage(result.get(0).toString());
        stage.setDirection((String) result.get(1));
        stage.setStageName((String) result.get(2));
        if (stages.size() >= 1 && stages.get(stages.size() - 1).getDirection().equals(stage.getDirection())) {
        } else {
            stages.add(stage);
        }

    }
    return stages;

I can see how one looks better than the other...but which one would be more efficient?


texts:
I have made a Point2D.Double wrapper so I can add my own functionality (like a dominate method) and alter some (like toString) and control some (like not having public access to x and y).

Point class:

public class Point implements Serializable {

    private final Point2D.Double point2D;

    public Point(double x, double y) {
        this.point2D = new Point2D.Double(x, y);
    }

    public Point(String line, String delimiter) {
        line = line.trim();
        String[] lineArray = line.split(delimiter);
        double x = Double.parseDouble(lineArray[0]);
        double y = Double.parseDouble(lineArray[1]);
        this.point2D = new Point2D.Double(x, y);
    }

    public boolean dominates(Point point) {
        return (this.getX() <= point.getX() && this.getY() < point.getY())
                || (this.getY() <= point.getY() && this.getX() < point.getX());
    }

    public double getX() {
        return point2D.getX();
    }

    public double getY() {
        return point2D.getY();
    }

    @Override
    public boolean equals(Object o) {
        return point2D.equals(o);
    }

    @Override
    public int hashCode() {
        return point2D.hashCode();
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append('(').append(point2D.getX()).append(", ").append(point2D.getY()).append(')');
        return builder.toString();
    }
}


texts: Making lists symmetrical by merging elements

texts:
My code is based around the following problem:

http://orac.amt.edu.au/cgi-bin/train/problem.pl?set=aio16int&problemid=903

It's about making a series of plots of land symmetrical by knocking down fences, but out of context of this problem, the code: Takes a list, makes it symmetrical by adding elements together, and prints / writes the number of changes needed to achieve this.

My main concern is speed: the code works fine but it is taking too long to solve cases with long lists. (up to 100,000 elements, where each element is an integer up to 10,000) Any feedback welcomed!

infile = open("farmin.txt", "r")
outfile = open("farmout.txt", "w")
n = int(infile.readline())
plots = infile.readline().split()
infile.close()
plots = [int(i) for i in plots]
fencescut = 0
leftpos = 0
rightpos = 0

def mergeplots (direc, n1, n2):
    global plots
    if direc == "l":
        plots[n1] = plots[n1] + plots.pop(n2)
    else:
        plots[len(plots) - 1 - n1] = plots[len(plots) - 1 - n1] + plots.pop(len(plots) - 1 - n2)

while leftpos <= len(plots)/2 and rightpos <= len(plots)/2:
    if plots[len(plots) - 1 - rightpos] - plots[leftpos] > 0: # left fence needs to be cut
        fencescut += 1
        mergeplots("l",leftpos, leftpos + 1)
    elif plots[len(plots) - 1 - rightpos] - plots[leftpos] < 0: #right fence needs to be cut
        fencescut += 1
        mergeplots('r', rightpos, rightpos + 1)
    else: # no fence needs to be cut
        leftpos += 1
        rightpos += 1
outfile.write(str(fencescut))
outfile.close()


texts: Audio processing with normalized [0.0, 1.0] domain

texts:
I've a code that process buffers of samples/audio data. Here's the code:

#include <iostream>
#include <math.h>
#include <cstring>
#include <algorithm>

#define PI 3.141592653589793238
#define TWOPI 6.283185307179586476

const int blockSize = 256;
const double mSampleRate = 44100.0;
const double mHostPitch = 2.0;
const double mRadiansPerSample = TWOPI / mSampleRate;

double mGainNormalizedValues[blockSize];
double mPitchNormalizedValues[blockSize];
double mOffsetNormalizedValues[blockSize];

class Oscillator
{
public:
    double mPhase = 0.0;
    double minPitch = -48.0;
    double maxPitch = 48.0;
    double rangePitch = maxPitch - minPitch;
    double pitchPd = log(2.0) / 12.0;
    double minOffset = -900.0;
    double maxOffset = 900.0;
    double rangeOffset = maxOffset - minOffset;

    Oscillator() { }

    void ProcessBuffer(double voiceFrequency, int blockSize, double *left, double *right) {
        // precomputed data
        double bp0 = voiceFrequency * mHostPitch;

        // process block
        for (int sampleIndex = 0; sampleIndex < blockSize; sampleIndex++) {
            double output = (sin(mPhase)) * mGainNormalizedValues[sampleIndex];

            *left++ += output;
            *right++ += output;

            // next phase
            mPhase += std::clamp(mRadiansPerSample * (bp0 * WarpPitch(mPitchNormalizedValues[sampleIndex])) + WarpOffset(mOffsetNormalizedValues[sampleIndex]), 0.0, PI);
            while (mPhase >= TWOPI) { mPhase -= TWOPI; }
        }
    }

    inline double WarpPitch(double normalizedValue) { return exp((minPitch + normalizedValue * rangePitch) * pitchPd); }
    inline double WarpOffset(double normalizedValue) { return minOffset + normalizedValue * rangeOffset; }
};

int main(int argc, const char *argv[]) {
    int numBuffer = 1024;
    int counterBuffer = 0;

    Oscillator oscillator;

    // I fill the buffer often
    while (counterBuffer < numBuffer) {
        // init buffer
        double bufferLeft[blockSize];
        double bufferRight[blockSize];
        memset(&bufferLeft, 0, blockSize * sizeof(double));
        memset(&bufferRight, 0, blockSize * sizeof(double));

        // emulate params values for this buffer
        for(int i = 0; i < blockSize; i++) {
            mGainNormalizedValues[i] = i / (double)blockSize;
            mPitchNormalizedValues[i] = i / (double)blockSize;
            mOffsetNormalizedValues[i] = i / (double)blockSize;
        }

        // process osc buffer
        oscillator.ProcessBuffer(130.81278, blockSize, &bufferLeft[0], &bufferRight[0]);

        // do somethings with buffer

        counterBuffer++;
    }
}

Basically:

init a Oscillator object
for each buffer, fill some param arrays with values (gain, pitch, offset); gain remain normalized [0.0, 1.0], while pitch and offset range in -48/48 and -900/900
then I iterate the buffer, calculating the Oscillator's sine due to pitch and offset, and I apply a gain; later, I move the phase, incrementing it

The whole domain of operations are normalized [0.0, 1.0]. But when I need to manage pitch and offset, I need to switch domain and use different values (i.e. the Warp functions).

This required lots of computations and process. I'd like to avoid it, so I can improve the code and performances.

How would you do it? Can I keep into [0.0, 1.0]? Could I improve the performance?


texts: Sudoku solving algorithm - Revision needed

texts:
I was preparing myself for an interview at a well known .com firm. One of the question that they often ask is an algorithm to solve sudokus (that have one solution). Here is what came to my mind. Any hints criticisms or suggestions to tune it up?

import itertools
sudoku_str="""003020600
900305001
001806400
008102900
700000008
006708200
002609500
800203009
005010300"""

sudoku=[[int(i) for i in j] for j in sudoku_str.splitlines()]
while not any([0 in line for line in sudoku]):
    for x,y in itertools.ifilter(lambda x: sudoku[x[1]][x[0]]==False, itertools.product(*[range(9)]*2)):
        #Find the elements in the line
        line=set([i for i in sudoku[y] if i])
        #Find the elements in the column
        column=set([xline[x] for xline in sudoku if xline[x]])
        #Create some shifts to get the start (x,y) position for the area computation e.g. for 1,1 => 0,0 and for 3,8=>1,3
        shifts=dict(zip(range(9),[0]*3+[3]*3+[6]*3))
        #Find the elements in the area
        area=filter(None,reduce(lambda x,y: x.add(y), sudoku[shifts[y]:shifts[y]+3], set()))
        #What could be in that position?
        outcomes=set(range(1,10))-line-column-area
        if len(outcomes)==1:
            #One outcome? replace the zero
            sudoku[y][x]=outcomes.pop()

print "\n".join([" | ".join(str(k) for k in i) for i in sudoku])


texts:
I have developed some free standing functions to provide hex dumps for buffer (std::string) contents.

You can see it working in action here.

The purpose is for debugging diagnostics to print buffer contents to a (logging) stream, in a format similar as wireshark does.

Any proposals for improvements are welcome.

Here's the code:

#include <iostream>
#include <iomanip>
#include <cctype>

std::ostream& render_printable_chars(std::ostream& os, const char* buffer, size_t bufsize) {
    os << " | ";
    for (size_t i = 0; i < bufsize; ++i)
    {
        if (std::isprint(buffer[i]))
        {
            os << buffer[i];
        }
        else
        {
            os << ".";
        }
    }
    return os;
}

std::ostream& hex_dump(std::ostream& os, const uint8_t* buffer, size_t bufsize, bool showPrintableChars = true)
{
    auto oldFormat = os.flags();
    auto oldFillChar = os.fill();

    os << std::hex;
    os.fill('0');
    bool printBlank = false;
    size_t i = 0;
    for (; i < bufsize; ++i)
    {
        if (i % 8 == 0)
        {
            if (i != 0 && showPrintableChars)
            {
                render_printable_chars(os, reinterpret_cast<const char*>(&buffer[i] - 8), 8);
            }
            os << std::endl;
            printBlank = false;
        }
        if (printBlank)
        {
            os << ' ';
        }
        os << std::setw(2) << std::right << unsigned(buffer[i]);
        if (!printBlank)
        {
            printBlank = true;
        }
    }
    if (i % 8 != 0 && showPrintableChars)
    {
        for (size_t j = 0; j < 8 - (i % 8); ++j)
        {
            os << "   ";
        }
        render_printable_chars(os, reinterpret_cast<const char*>(&buffer[i] - (i % 8)), (i % 8));
    }

    os << std::endl;

    os.fill(oldFillChar);
    os.flags(oldFormat);

    return os;
}

std::ostream& hex_dump(std::ostream& os, const std::string& buffer, bool showPrintableChars = true)
{
    return hex_dump(os,reinterpret_cast<const uint8_t*>(buffer.data()), buffer.length(),showPrintableChars);
}

Here's the test case:

int main()
{
    const char test[] = "abcdef123456\0zyxwvu987654";
    std::string s(test,sizeof(test));

    hex_dump(std::cout, s);

    return 0;
}

The output looks like expected:

61 62 63 64 65 66 31 32 | abcdef12
33 34 35 36 00 7a 79 78 | 3456.zyx
77 76 75 39 38 37 36 35 | wvu98765
34 00                   | 4.


texts: jQuery plugin to cycle through text and "typewrite" it out

texts:
I have written a jQuery plugin (my first for a long time) that simply cycles through strings of text in a data attribute and uses setInterval to type it out - it's a common effect you've probably seen hundreds of times.

I'm looking for a code review of the JavaScript/jQuery portion of the code mainly because a lot of the literature on building a jQuery plugin is quite old and I want to be sure I'm doing things the "modern" way.

CodePen

$(document).ready(function() {
  $().typeText();
});

(function($) {

  $.fn.typeText = function(options) {

    var settings = $.extend({
      loopSpeed: 5000,
      typeSpeed: 100,
      selector: '.words'
    }, options);

    var typeIntervals = [];

    load();

    function load() {

      $(settings.selector).each(function() {
        var wordsArray = $(this).data('words').split(',');
        var length = wordsArray.length - 1;
        var index = 0;
        var thisWordGroup = $(this);;
        if (typeof $(this).data('index') == 'undefined') {
          $(thisWordGroup).data('index', 0);
        }
        $(this).html(wordsArray[0]);
      });

      setIntervals();

    }

    function setIntervals() {

      setInterval(function() {
        clearTypeIntervals();
        $(settings.selector).each(function() {
          var thisWordGroup = $(this);
          var wordsArray = thisWordGroup.data('words').split(',');
          var length = wordsArray.length - 1;
          var index = thisWordGroup.data('index');
          index++;
          if (index > length) {
            index = 0;
          }
          thisWordGroup.data('index', index);
          type(thisWordGroup, wordsArray[index]);
        });
      }, settings.loopSpeed);

    }

    function type($selector, word) {
      $selector.html('');
      var index = 0;
      var splitWord = word.split('');
      var splitWordLength = splitWord.length - 1;
      var intervalName = 'typeWordInterval' + Math.ceil(Math.random() * 99999);
      typeIntervals[intervalName] = setInterval(function() {
        var currentText = $selector.html();
        $selector.html(currentText + splitWord[index]);
        if (index < splitWordLength) {
          index++
        } else {
          clearInterval(typeIntervals[intervalName])
        }
      }, settings.typeSpeed);
    }

    function clearTypeIntervals() {
      for (var element in typeIntervals) {
        clearInterval(typeIntervals[element]);
      }
    }

  }

}(jQuery));


texts: Simple PHP inheritance using an abstract class

texts:
I have created simple class inheritance of an abstract class Pet which is basically the skeleton of all other children classes.

abstract class Pet {

    private static $relations = array(
        'Cat',
        'Dog'
    );

    public static final function getClassById($id){
        return self::$relations[$id];
    }

    protected static $foods = array(

    );

    public static function getEdibleFoods(){
        $class = get_called_class();
        return $class::$foods;
    }

    abstract public function play();
    abstract public function eat();
    abstract public function sleep();

}

Then I have the Dog and Cat classes

class Dog extends Pet {

    protected static $foods = array(
        'bones'
    );

    public function eat() { }

    public function play() { }

    public function sleep() { }

}

class Cat extends Pet {

    protected static $foods = array(
        'fish'
    );

    public function eat() { }

    public function play() { }

    public function sleep() { }

}

As you see, the only difference between them is the foods that they like. My concern about this code is the getEdibleFoods static method in the parent class.

public static function getEdibleFoods(){
    $class = get_called_class();
    return $class::$foods;
}

In order to not have to implement it in all children classes, I figured I can use get_called_class() instead of self to return the foods static variable. Notice that every child class has its own foods array and they are not all the same.

My problem is that this does not look like clean code. I'd like to ask if this is good practice and if not, how is it done the right way?


texts: Optimizing matrix multiplication algorithm

texts:
I have implemented my own version of algorithm to multiply two matrices together and I need someone who know what they are doing to see if there is anything that can be done in a more optimal way. I am also keen on understanding how I can make it robust such that it doesn't crash when non-rectangular matrices are passed as argument i.e. matrix that has uneven number of elements in different Vds it holds.
I am particularly interested in function matrixDot in the code bellow, everything else is only to show how I am using it in my project).
#include "iostream"
#include <vector>

#define LOG(m) std::cout << m << std::endl

struct Vd
{
    std::vector<double> v;
};

struct Md
{
    std::vector<Vd> m;

    //fill matrix with num
    void fill(unsigned const int rows, unsigned const int cols, const double num)
    {
        m.clear();
        for (unsigned int i = 0; i < rows; i++)
        {
            Vd tempVec;
            for (unsigned int j = 0; j < cols; j++)
            {
                tempVec.v.push_back(num);
            }
            m.push_back(tempVec);
        }
    }

    friend std::ostream& operator << (std::ostream& out, const Md& mat)
    {
        out << "[" << std::endl << std::endl;
        for (unsigned int i = 0; i < mat.m.size(); i++)
        {
            out << "[";
            for (unsigned int j = 0; j < mat.m[i].v.size(); j++)
            {
                if (j % mat.m[i].v.size() == mat.m[i].v.size() - 1)
                    out << mat.m[i].v[j] << "]" << std::endl << std::endl;
                else
                    out << mat.m[i].v[j] << ", ";
            }
        }
        out << "]" << std::endl;
        return out;
    }
};

inline void matrixDot(const Md& m1, const Md& m2, Md& outm)
{
    if (m1.m[0].v.size() && m2.m.size())
        if (m1.m[0].v.size() != m2.m.size())
        {
            LOG("Shape mismatch: " << "matrix1 columns: " << m1.m[0].v.size() << ", " << "matrix2 rows: " << m2.m.size());
            throw std::exception();
        }

    unsigned int m1x = 0; unsigned int m1y = 0; unsigned int m2y = 0; //m2x = m1y

    while (outm.m.size() < m1.m.size())
    {
        Vd tempv;
        while (tempv.v.size() < m2.m[0].v.size())
        {
            double total = 0.0;
            while (m1x < m1.m[0].v.size())
            {
                total += m1.m[m1y].v[m1x] * m2.m[m1x].v[m2y];
                m1x++;
            }
            tempv.v.push_back(total);
            m1x = 0;
            m2y < m2.m[0].v.size() - 1 ? m2y++ : m2y = 0;
        }
        m1y < m1.m.size() - 1 ? m1y++ : m1y = 0;
        outm.m.push_back(tempv);
    }
}

int main()
{
    Md mat1;
    mat1.fill(5, 2, 1.0);
    Md mat2;
    mat2.fill(2, 6, 2.0);
    Md mat3;
    matrixDot(mat1, mat2, mat3);
    std::cout << mat3;
}


texts:
I'm in the process of creating a program that can model points, vectors, lines and segments. I have the classes built and confirmed to be working correctly. The classes are built to handle multiple dimensions, so as an example, the same point class is used for R1, R2, R3, ... Rn.

The issue that I am dealing with is how to handle operations between classes if the dimensions are different. For example, you can add two vectors that are in R2 but you cannot add a vector that is in R2 and another in R3.

My original plan was to create an exception class that I would throw if the dimensions between the two objects was different. This would work but would entail needing to wrap a lot of operations in try/catch blocks. Is this the best course of action to take or is there a better method that i could impliment?

Below is my point class:

public class Point
{
    private List<double> values;

    public List<double> VALUES
    {
        get { return values; }
        set { values = value; }
    }
    public int DIMENSION
    {
        get { return VALUES.Count; }
    }

    public Point(List<double> args)
    {
        values = new List<double>();
        this.VALUES = args;
    }
    public override string ToString()
    {
        string temp = "( ";

        for (int i = 0; i < DIMENSION; i++)
        {
            temp += VALUES[i];

            if(i != DIMENSION - 1)
                temp += ", ";
        }

        temp += ");";

        return temp;
    }

    public static double Distance(Point point1, Point point2)
    {
        if (!SameDimension(point1, point2))
        {
            //add exception
        }

        double temp = 0;

        for (int i = 0; i < point1.DIMENSION; i++)
        {
            temp += Math.Pow(point2.VALUES[i] - point1.VALUES[i], 2);
        }

        return Math.Sqrt(temp);
    }
    public static Point Midpoint(Point point1, Point point2)
    {
        if (!SameDimension(point1, point2))
        {
            //add exception
        }

        List<double> temp = new List<double>();

        for (int i = 0; i < point1.DIMENSION; i++)
        {
            temp.Add((point2.VALUES[i] + point1.VALUES[i]) / 2);
        }

        return new Point(temp);
    }
    //This is the method used to check dimensions
    public static bool SameDimension(Point point1, Point point2)
    {
        if (point1.DIMENSION != point2.DIMENSION)
            return false;
        else
            return true;
    }
}//working, needs exceptions added

This is the most simple class but all check the dimension by using this meathod.

EDIT:
The reason for needing to encase operations in try/catch blocks is say I have:

Point p1 = new Point(new List<double> { 0, 0});
Point p2 = new Point(new List<double> { 3, 3});
Point p3 = new Point(new List<double> { 4, 4, 4});

double distance = Point.Distance(p1, p2);

This would work completely fine, giving the distance of 3sqrt(3). But if this was tried:

distance = Point.Distance(p1,p3);

An error should occur because you are trying to compare a point in 2-Dimensions to a point in 3-Dimensions. Code will be written to reduce the risk of this happening, but I want a safe-guard in place in case this situation arises. If I go with the exception route, try/catch blocks will be needed. This is more apparent in the Vector class where when you add two vectors a new vector is returned. In that case, if a dimension error is encountered, the return value would be null, causing the possibility of other errors. Using exceptions, in my opinion, would mitigate potential errors as well as give me a capacity to track when they occur during run-time.


texts: Picking a random neighbouring cell, but only picking previously-visited ones if there aren't any unvisited

texts:
I'm creating mazes, and have a Cell class (only relevant code shown)...

public class Cell {
  public int Row { get; }
  public int Col { get; }

  public List<Cell> Links { get; }

  public Cell North { get; set; }
  public Cell South { get; set; }
  public Cell East { get; set; }
  public Cell West { get; set; }

  public Cell(int row, int col) {
    Row = row;
    Col = col;
    Links = new List<Cell>();
  }

  public bool Linked(Cell cell) =>
    Links.Contains(cell);

  public bool DeadEnd =>
    Links.Count == 1;

  public IEnumerable<Cell> Neighbours =>
    new List<Cell> { North, South, East, West }.Where(c => c != null);

}

The mazes are all (currently) rectangular, so a Cell starts off with 2, 3 or 4 neighbours (depending on where it is in the maze, eg corner cells only have two neighbours, other edge cells have three, internal cells have four). These are set during the maze initialisation code (In Maze class which is not shown as it's not relevant here), and the Neighbours property gives the resulting neighbouring cells.

Given a grid of cells, the maze-generation algorithm links cells together using Link() and Unlink() methods (not shown as they aren't relevant here).

The Linked method then allows you to check if a cell is linked to the current one.

As I often need to pick a random cell from a collection, I have the following extension method defined...

public static Cell Rand<Cell>(this IEnumerable<Cell> items, Random r) =>
  items.OrderBy(n => r.Next()).First();

I create one Random object at the start, and pass it around, hence the second parameter.

Some of the maze-generation algorithms work by taking a random walk around the grid. When on a cell, they pick a neighbouring cell to be the next in the walk.

One specific algorithm will try and avoid previously visited cells. This means that if there are any neighbours that don't yet have any links, then it will pick one of those. If all neighbouring cells have links, it picks one of those instead.

My current code for this is shown below. This is on the maze-generating class, and current is the cell we're currently visiting in our random walk. We pick the next by...

Cell next = current.Neighbours.Any(c => c.Links.Count == 0)
  ? current.Neighbours.Where(c => c.Links.Count == 0).Rand(r)
  : current.Neighbours.Rand(r);

This works fine, but I can't help feeling that there is a way to combine this into one Linq query instead of the three required for the ?: operator.

Any suggestions? Thanks.


texts:
Here's a class I made in java. It's pretty simple, the description of what it does is in the comment. I'd appreciate any feedback.

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * An unordered, duplicate-allowing collection of items that are added with a
 * time-to-live, and will automatically be considered not a part of the
 * collection when that time expires. Has 0 thread overhead, and is not thread safe.
 */
public class TTLBag<E> implements Iterable<E> {

    private class Element {

        E item;
        long expires;

        Element(E item, long expires) {
            this.item = item;
            this.expires = expires;
        }

    }

    private List<Element> contents = new ArrayList<>();

    public void add(E item, long timeToLive) {
        contents.add(new Element(item, System.currentTimeMillis() + timeToLive));
    }

    @Override
    public Iterator<E> iterator() {
        long time = System.currentTimeMillis();
        contents.removeIf(element -> element.expires > time);
        return contents.stream().map(element -> element.item).iterator();
    }

}


texts:
I'm learning C#, I programmed some things in java, and I would like to have a feedback on my C# code. The exercise is from codility.

  The goal is to rotate array A K times; that is, each element of A will
  be shifted to the right K times.

  Write a function:

  class Solution { public int[] solution(int[] A, int K); }

  that, given an array A consisting of N integers and an integer K,
  returns the array A rotated K times.

  For example, given

A = [3, 8, 9, 7, 6]
K = 3 the function should return [9, 7, 6, 3, 8]. Three rotations were made:

[3, 8, 9, 7, 6] -> [6, 3, 8, 9, 7]
[6, 3, 8, 9, 7] -> [7, 6, 3, 8, 9]
[7, 6, 3, 8, 9] -> [9, 7, 6, 3, 8] For another example, given

A = [0, 0, 0]
K = 1 the function should return [0, 0, 0]

  Given

A = [1, 2, 3, 4]
K = 4 the function should return [1, 2, 3, 4]

And this is my code. It gives 100% but maybe something can be improved.Thanks in advice.

using System;
// you can also use other imports, for example:
// using System.Collections.Generic;

// you can write to stdout for debugging purposes, e.g.
// Console.WriteLine("this is a debug message");

class Solution {
    public int[] solution(int[] A, int K) {
        int len = A.Length;
        int[] B = new int[len];
        if(len > 0 && K % len != 0 )
        {
            for ( int i = 0; i < len; i++)
            {
                B[(K + i) % len] = A[i];
            }
        }
        else
        {
            return A;
        }
        return B;
    }
}


texts: TCP server in Android to continuously listen to an RFID reader

texts:
I have created a TCP server thread which I want to keep running and listening to the IOT device (an RFID reader).
I have only one client.

Please review my code and provide your feedback. Are there any edge cases that would make this TCP server fail?

import android.util.Log;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class TcpServerThread extends Thread {

    private static final String TAG = "TcpServerThread";

    private boolean run_ = true;
    DataInputStream stream;
    ServerSocket serverSocket;
    Socket clientSocket;

    public TcpServerThread() {
        super();
        start(); //start the thread
    }

    @Override
    public void run() {

        byte[] inBytes = new byte[200];
        int mPort = 1025;

        //creating a socket to listen on a given port
        Log.d(TAG, "PORT OPENED SUCESSFULLY in " + mPort);
        try {
            serverSocket = new ServerSocket(mPort);

        } catch (IOException e) {
            Log.d(TAG, "run: [exception occured in creating the socket]" + e.getLocalizedMessage());
        }

        while (run_) {

            Log.d(TAG, "run() :started");

            try {
                while (serverSocket != null) {
                    Log.d(TAG, "run() : running ");
                    try {
                        //accepting the incoming socket connection request
                        long started = System.currentTimeMillis();
                        clientSocket = serverSocket.accept();
                        clientSocket.setKeepAlive(true);

                        if (clientSocket != null) {
                            long established = (System.currentTimeMillis() - started);
                            Log.d(TAG, "[Connection made at]:" + clientSocket.getRemoteSocketAddress() + "in mills :" + established);

                            DataInputStream stream = new DataInputStream(clientSocket.getInputStream());
                            DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());

                            while ((input = stream.read(inBytes)) != -1) {
                                Log.d(TAG, "Size read is " + input);
                                Log.d(TAG, "Data is " + (inBytes));
                                outToServer.writeByte(10);

                            }

                        }

                    } catch (IOException e) {
                        Log.d(TAG, "IOexception occured: " + e.getLocalizedMessage());
                        continue;

                    } catch (Exception e) {
                        Log.d(TAG, "EXCEPTION occured: " + e.getLocalizedMessage());
                        continue;
                    }

                }

            } catch (Exception e) {
                //we need to watch out for IllegalStateException cases
                Log.d(TAG, "[Exception occured] :" + e.getLocalizedMessage());

                continue;

            }

        }
        try {
            throw new RuntimeException(TAG + " Crashed!!");
        } catch (RuntimeException e) {
                      Log.d(TAG, "RuntimeException: " + e.getLocalizedMessage());

        }
    }

    public void abort() {
        run_ = false;
        closeServer();
        interrupt();
    }

    public void closeServer() {

        try {
            serverSocket.close();
            clientSocket.close();
            stream.close();
        } catch (Exception e) {
            Log.d(TAG, "closeServer: " + e.getLocalizedMessage());
        } finally {
            start();
        }
    }


texts:
// ConsoleApplication1.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <cstdlib>
#include <iostream>
#include <cmath>

using namespace std;

int main() {
    system("cls");
    system("color 5");

    float a;
    float b;
    float c;
    float Sector1Arithmetic;
    float Sector2Arithmetic;
    float Sector3Arithmetic;
    float Sector4Arithmetic;
    float Sector5Arithmetic;
    float X1;
    float X2;

    cout << endl;
    cout << "            Quadratic Equation Solver";
    cout << endl;
    cout << endl;
    cout << "       Enter the value of the a co-efficient ---> ";
    cin >> a;
    cout << endl;
    cout << endl;
    cout << "       Enter the value of the b co-efficient ---> ";
    cin >> b;
    cout << endl;
    cout << endl;
    cout << "       Enter the value of the c co-efficient ---> ";
    cin >> c;
    cout << endl;

    Sector1Arithmetic = b * -1;
    Sector2Arithmetic = b * b - 4 * a * c;
    Sector3Arithmetic = sqrt(Sector2Arithmetic);
    Sector4Arithmetic = Sector1Arithmetic + Sector3Arithmetic;
    Sector5Arithmetic = Sector1Arithmetic - Sector3Arithmetic;
    X1 = Sector4Arithmetic / 2 * a;
    X2 = Sector5Arithmetic / 2 * a;

    cout << "  For the equation " << a << "x^2 + " << b << "x + " << c <<     endl;
    cout << endl;
    cout << "  X=" << X1 << " OR " << "X=" << X2 << endl;

    if ((-4 * a * c) >= (b * b) || (a == 0) || (b == 0) || (c == 0)) {
    cout << endl;
    cout << "An error might have occurred due to impractical math calculations" << endl;
    cout << "OR due to invalid values inputted such as 0" << endl;
    cout << endl;
    }

    cout << endl;
    system("pause");
    main();
    return 0;

}

As you may remember I also posted a quadratic equation solver in Python as well. The main reason I post this simple program is to get critical feedback and perhaps look for alternative ways of coding such simple program applying it to my future projects.


texts: PHP, would this class pass the single responsibility principle?

texts:
I have a user class comprised of the code below. It has functions to insert a user, update a user, delete a user, look up a user, and search for users. What I'm wondering is if I this class would pass the Single Responsibility Principle as stated here (http://en.wikipedia.org/wiki/Single_responsibility_principle).

class user{
    $first_name = "";
    $last_name = "";
    $physical_address1 = "";
    $physical_address2 = "";
    $physical_city = "";
    $physical_state = "";
    $physical_zip = "";
    $mailing_address1 = "";
    $mailing_address2 = "";
    $mailing_city = "";
    $mailing_state = "";
    $mailing_zip = "";
    function __construct($array){
        if(!isset($array['first_name']) && !empty($array['first_name'])){
            $this->first_name = "";
        }
        if(!isset($array['last_name']) && !empty($array['last_name'])){
            $this->last_name = "";
        }
        if(!isset($array['physical_address1']) && !empty($array['physical_address1'])){
            $this->set_physicalAddress(array(
                "address_1"=>$array['physical_address1'],
                "address_2=>$array['physical_address2']",
                "city"=>$array['physical_city'],
                "state"=>$array['physical_state'],
                "zip"=>$array['physical_zip']
            ));
        }
        if(!isset($array['mailing_address1']) && !empty($array['mailing_address1'])){
            $this->set_mailingAddress(array(
                "address_1"=>$array['mailing_address1'],
                "address_2=>$array['mailing_address2']",
                "city"=>$array['mailing_city'],
                "state"=>$array['mailing_state'],
                "zip"=>$array['mailing_zip']
            ));
        }
    }
    function set_physicalAddress($array){}
    function get_physicalAddress(){}
    function set_mailingAddress($array){}
    function get_mailingAddress(){}
    static function insert($array){}
    static function update($array){}
    static function delete($int){}
    static function lookup($array){}
    static function search($array){}
}

$obj = new user(array(
"first_name"=>"John",
"last_name"=>"Smith"
));

The purpose of having the constructor parameter value be an array is that I feed it only the values I want without having to deal with errors caused by not setting a parameter. Instead of setting the parameters to null it's easier to just not put them in the array.


texts:
I am using an AlertDialog in Android, asking the user for some input. I would like do run some code when the user has finished entering her input.

Since an AlertDialog is asynchronous, my code is not waiting for it. Therefore, I decided to use a callback, as in the following sample code:

This is the interface: AlertDialogCallback

public interface AlertDialogCallback<T>
{
    public void alertDialogCallback(T ret);
}

The main activity implements the interface and calls the function creating the alert dialog:

public class MainActivity extends Activity implements AlertDialogCallback<String>

...

public void alertDialogCallback(String ret)
{
    ...
}

...

askForInput(this, this);

And the function creating the dialog has a final reference to the class that implements AlertDialogCallback (here MainActivity). It has to be final because of the nested anonymous class.

public static void askForInput(Context context, final AlertDialogCallback<String> callback)
{
    AlertDialog.Builder alert = new AlertDialog.Builder(context);

    alert.setTitle("Enter input");
    alert.setMessage("Please enter some input");

    // Set an EditText view to get user input
    final EditText input = new EditText(context);
    alert.setView(input);

    alert.setPositiveButton("Ok", new DialogInterface.OnClickListener()
    {
        public void onClick(DialogInterface dialog, int whichButton)
        {
            String value = input.getText().toString();

            callback.alertDialogCallback(value);
        }
    });

    alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener()
    {
        public void onClick(DialogInterface dialog, int whichButton)
        {
            // Canceled.
        }
    });

    alert.show();
}

I would like to know if this is a bad design (and why), and also if there is some kind of design pattern that is commonly used for this purpose in Android(/Java?).