texts:
I am going to make this code below into the second release of my library, but I want to make sure I haven't missed anything. If there are improvements that can be made, I'd like to implement them.
This code is also on GitHub.
import random
import secrets
import string
import urllib.request

class Simple():
    def __init__(self, length: int, characters = None):
        '''A simple password'''
        self.length = length
        self.characters = characters
        self.output = []

    def generate(self, num_of_passwords: int):
        '''
        Generates a password depending on the num_of_passwords
        and the arugments provided in the simple class
        '''
        characters = ''
        if self.characters is None:
            characters = string.ascii_letters + string.digits
        else:
            characters = self.characters

        for i in range(num_of_passwords):
            password = ''
            for c in range(self.length):
                password += secrets.choice(characters)
            self.output.append(password)
        return self.output

    def return_result(self, index: int):
        '''
        Returns the password which is at the specified index
        in the output list.
        '''
        try:
            return self.output[index]
        except IndexError:
            print(f'Incorrect index specified. Please provide an index relevant to the number of passwords generated')

    def clear_results(self):
        '''Clears the output list if you want to make way for new passwords'''
        self.output.clear()

class Complex(Simple):
    def __init__(self, length, string_method, numbers=True, special_chars=False):
        '''
        Creates a customisable password depending on length,
        string_method, numbers and special_chars
        '''
        characters = ''
        self.output = []

        methods: dict = {
            "upper": string.ascii_uppercase,
            "lower": string.ascii_lowercase,
            "both": string.ascii_letters,
        }

        characters += methods[string_method]

        if numbers:
            characters += string.digits
        if special_chars:
            characters += string.punctuation

        super().__init__(length=length, characters=characters)

class Memorable(Simple):
    def __init__(self, numbers=True):
        '''A memorable password'''
        self.numbers = numbers
        self.output = []

    def generate(self, num_of_passwords: int):
        '''Gets some random words'''
        word_url = "http://svnweb.freebsd.org/csrg/share/dict/words?view=co&content-type=text/plain"
        headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64)'}
        req = urllib.request.Request(word_url, headers=headers)
        response = response = urllib.request.urlopen(req)
        long_txt = response.read().decode()
        words = long_txt.splitlines()

        '''
        Generates the password containing 2 words
        and numbers if self.numbers == True
        '''
        for i in range(num_of_passwords):
            password = ''
            two_words = ''
            for i in range(2):
                two_words += secrets.choice(words).title()
            password = two_words
            if self.numbers == True:
                for i in range(random.randint(3, 4)):
                    password += secrets.choice(string.digits)
            self.output.append(password)
        return self.output

# Test Scenarios

if __name__ == "__main__":
    var = Memorable()
    print(var.generate(3))


texts:
I have a class which updates an object. The class takes a String id in its constructor and returns the appropriate class based on the id. I think these two methods should be separated into their own classes as returning an object based on a String id will probably have uses elsewhere in the code base.

I've considered adding the functionality which returns the object to update into its own static method:

ObjectToUpdate = Utils.getObjectToUpdate(id)

Is there a better way or a design pattern?

UpdateContestantObj c = new UpdateContestantObj(childWithParentRatingsObject.getCoupleId());
c.getContestantObj().setSortVal(singleScoringFM.getScore());
c.persistContestant();

public class UpdateContestantObj {

    private String id;
    private ContestantObj contestantToSave = null;

    public ContestantObj getContestantObj(){
        return this.contestantToSave;
    }

    public UpdateContestantObj(String id){
        this.id = id;

        SimpleSortingVector simpleSortingVector = (SimpleSortingVector)FutureContent.future.getContent(Constants.CONTESTANTS_DATA);
        Enumeration contestantsEnumeration = simpleSortingVector.elements();

        while(contestantsEnumeration.hasMoreElements()){
            final ContestantButtonField contestantButtonField = (ContestantButtonField)contestantsEnumeration.nextElement();
            if(contestantButtonField.getContestant().getId().equalsIgnoreCase(this.id)){
                contestantToSave = contestantButtonField.getContestant();
            }
        }
    }

    public void persistContestant(){

        contestantsStore.setContents(contestantToSave);
        contestantsStore.commit();

    }
}


texts: Given an array of integers, find and print its number of negative subarrays on a new line

texts:
Given an array of N integers, find and print its number of negative subarrays (i.e sub arrays having negative summation) on a new line.

My code is taking \$\mathcal{O}(n^2)\$ time. How can I improve this?

import java.util.Scanner;

public class Solution {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        int numberOfInts = sc.nextInt();
        int[] arr = new int[numberOfInts];

        for (int i = 0; i < numberOfInts; i++) {
            arr[i] = sc.nextInt();
        }
        int count = 0;
        for (int i = 0; i < numberOfInts - 2; i++) {
            int sum = arr[i];
            if (arr[i] < 0) {
                count++;
            }
            for (int j = i + 1; j < numberOfInts; j++) {
                sum = sum + arr[j];
                if (sum < 0) {
                    count++;
                }
            }
        }
        if (arr[numberOfInts - 1] < 0) {
            count++;
        }
        System.out.println(count);
    }
}


texts:
KMP algorithm is for searching and matching string with a given pattern. The most important part is to build a table for the pattern then move a proper step rather than just one step increment.

In my code I created the table correctly but something is wrong for moving steps.
It stuck in the for loop as variable was always equal to 2.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace KMP
{
    class Program
    {
        const string pattern = "abcdabd";
        const string s = "aadabcdabedxdfabcdabddsa";
        static int[] x = new int[7];
        static void Main(string[] args)
        {
            x = BuildTable(pattern);
            var y = Match(x, s);
            Console.WriteLine(y);
            Console.Read();
        }

        private static int Match(int[] x, string s)
        {
            int n = s.Length;
            int l = x.Length;
            int find = 0;
            Char[] charPattern = pattern.ToCharArray();
            for (int i = 0; i < n; )
            {
                string a = s.Substring(i, l);
                if (a.CompareTo(pattern).Equals(0))
                {
                    return i; // Found match, return match position of the first letter
                }
                // move position by BuildTable
                Char[] charSubstring = a.ToCharArray();
                int count = 0;
                for (int j = 0; j < l; j++)
                {
                    if (charPattern[j] == charSubstring[j])
                    {
                        count++;// count of matched chars
                        continue;
                    }
                    else
                    {
                        i += count - x[j]; // move forward steps = matched count - table value
                        break;
                    }
                }
            }
            return -999; // not found
        }

        public static int[] BuildTable(string p)
        {
            int[] result = new int[p.Length];
            result[0] = 0;
            for (int i = 1; i < p.Length - 1; i++)
            {
                // The substring from p[1] to p[i]
                string s = p.Substring(0, i + 1);

                var prefixes = Enumerable.Range(1, s.Length - 1)
                     .Select(a => s.Substring(0, a)).ToList();
                var suffixes = Enumerable.Range(1, s.Length - 1)
                     .Select(a => s.Substring(a, s.Length - a)).ToList();
                var common = prefixes.Intersect(suffixes).FirstOrDefault();
                result[i] = (common == null) ? 0 : common.Length;
            }
            return result;
        }
    }
}


texts:
I made this two player TicTacToe game as a challenge i was given in class. The game starts where the first player chooses where their X will be placed. Each area in the array has been given a number starting from 1 and ending at 9. After X chooses their area, the game will let the user know who's turn it is, and they will keep playing until one of them wins.

As of right now, the game doesn't let you know that nobody won, but that's another update i have to make.

Please do review the code and let me know how i can make it more efficient and i am also open for suggestions, so please be honest as much as possible as this is the first time i write in Javascript using Nodejs, and i would love to get better.

 //user input and format
let input = process.stdin;
input.setEncoding("utf-8");

console.log("You will start with X");
console.log("Please choose a box number from 1 to 9 to place your X");

//initializing an array of 9 fields where each one contains * as a start
let gameboard = []; // = ["*", "*", "*", "*", "*", "*", "*", "*", "*"];
let symbol = "*";

for (let i = 0; i < 9; i++) {
  gameboard[i] = symbol;
}

//determining who's turn it is and the players' symbols
let player1isplaying = true;
let player1 = "X";
let player2 = "O";

//Game loop
input.on("data", function(data) {
  console.clear();

  //bad input
  if (parseInt(data) > 9 || parseInt(data) < 1 || isNaN(data)) {
    console.log("Please enter a number between 1 and 9");
  } else if (gameboard[parseInt(data) - 1] != symbol) {
    console.log("The spot you're trying to fill is already taken.");
  }
  //which player's turn
  else if (player1isplaying) {
    gameboard[parseInt(data) - 1] = player1;
    player1isplaying = false;
  } else if (!player1isplaying) {
    gameboard[parseInt(data) - 1] = player2;
    player1isplaying = true;
  }

  showboard(gameboard);
  checkforXwin(gameboard);
  checkforOwin(gameboard);

  if (player1isplaying) {
    console.log(player1 + "'s turn");
  } else {
    console.log(player2 + "'s turn");
  }
});

//winner validation
function checkforXwin(array) {
  if (
    (array[0] == player1 && array[1] == player1 && array[2] == player1) ||
    (array[3] == player1 && array[4] == player1 && array[5] == player1) ||
    (array[6] == player1 && array[7] == player1 && array[8] == player1) ||
    (array[0] == player1 && array[4] == player1 && array[8] == player1) ||
    (array[2] == player1 && array[4] == player1 && array[6] == player1) ||
    (array[0] == player1 && array[3] == player1 && array[6] == player1) ||
    (array[1] == player1 && array[4] == player1 && array[7] == player1) ||
    (array[2] == player1 && array[5] == player1 && array[8] == player1)
  ) {
    console.log(player1 + " wins");
    process.exit();
  }
}

//winner validation
function checkforOwin(array) {
  if (
    (array[0] == player2 && array[1] == player2 && array[2] == player2) ||
    (array[3] == player2 && array[4] == player2 && array[5] == player2) ||
    (array[6] == player2 && array[7] == player2 && array[8] == player2) ||
    (array[0] == player2 && array[4] == player2 && array[8] == player2) ||
    (array[2] == player2 && array[4] == player2 && array[6] == player2) ||
    (array[0] == player2 && array[3] == player2 && array[6] == player2) ||
    (array[1] == player2 && array[4] == player2 && array[7] == player2) ||
    (array[2] == player2 && array[5] == player2 && array[8] == player2)
  ) {
    console.log(player2 + " wins");
    process.exit();
  }
}

//showing the board in 3 rows and 3 columns
function showboard(array) {
  console.log("---------");
  console.log(array.slice(0, 3).join("   "));
  console.log("");
  console.log(array.slice(3, 6).join("   "));
  console.log("");
  console.log(array.slice(6, 9).join("   "));
  console.log("---------");
}


texts: Unique everlasting session with low collision rate and is set across sub-domains

texts:
The goal is to try and make an everlasting SESSION without too much or unnecessary scripting for updating of sessions. And at the same time to avoid session collision as session collisions could lead to 2 users trying to make use of the same session. That would not look pretty! And it does happen. Also for websites that use different language sub-domains, it would be useful if session did not change so that you can easily go from one sub-domain to another without requiring new sessions.

STEP 0:

function getUserIP(){
    $client  = @$_SERVER['HTTP_CLIENT_IP'];
    $forward = @$_SERVER['HTTP_X_FORWARDED_FOR'];
    $remote  = $_SERVER['REMOTE_ADDR'];

    if(filter_var($client, FILTER_VALIDATE_IP)){
        $ip = $client;
    }else
    if(filter_var($forward, FILTER_VALIDATE_IP)){
        $ip = $forward;
    }else{
        $ip = $remote;
    }
    return $ip;
}
$ip = getUserIP();

STEP 1:

ini_set('session.gc_probability', 0);// 0% probability of purging session log files, in this case on startup we preventing sessions from ever being deleted!
session_set_cookie_params(0, '/', '.website.com');// allow same session to be set across sub-domains!
session_name('session');// now make sure that the same session will not be regenerated across sub-domains and stay the same!
session_save_path($_SERVER['DOCUMENT_ROOT'].'/SESSION');//finally sessions are stored in a folder of choice in say public_html folder..
session_start();// we allow sessions to be read or changed..

STEP 2:

if(isset($_SESSION['ip'])){// if IP session in session log exist, do..
    if($ip!=$_SESSION['ip']){// if the current IP is not in the session log, then user privileges hasn't been confirmed!
        session_regenerate_id();// make sure that current visitor will be forced to use a different session_id! // new session copy is generated!
        session_destroy();// new session copy will be cleansed from previous data to be ready for use!
        header('Location: .');// reload the current page and to begin using a new session algorithm!
    }// SESSION collision has now been avoided and replaced with SESSION+IP collision where chances of that are pretty much ZERO!!!
    // IP is checked first, even if collision does occur, it will not allow to use it because of the missing IP..
    // that means someone must be in a public place that uses same IP for all PC's and within that amount of PCs a collision can occur!
}else{// if session doesn't exist, start new log!
    $_SESSION['ip']=$ip;// visitor session log file has been updated!
    echo 'NEW SESSION!<br>';
}

Is this a good solution? Is it a great solution? Is it the best solution? What do you guys think? :)
Note, that I didn't include the cleaning up process in this scenario, so you should use your imagination! But with this script you shouldn't even be needing a script to clean up sessions. All you'll need is to go to FileZilla, enter SESSION folder, select 1 file, press ctrl+a to select all session log files and then delete them all once a month or even once a year or so!? Also the storage directory for SESSIONS is just an example that you can put them in some nearby location closer to your development folder. But public_html is kinda PUBLIC and therefore you should use it along with .htaccess file and restrict access to the SESSIONS folder to secure it.


texts: Comparing two objects having two nullable date fields

texts:
ExpiryDates has two properties PSL_ExpiryDate and MNL_ExpiryDate of type nullable date. I am trying to compare two objects for having same or different values.

Is there a cleaner way to do the same as the code below?

private bool SameValues(ExpiryDates ExpiryDates1, ExpiryDates ExpiryDates2)
    {
        //Assume they are the same value and the look for differences
        bool result = true;

        if (ExpiryDates1.PSL_ExpiryDate.HasValue != ExpiryDates2.PSL_ExpiryDate.HasValue)
        {
            result = false;
        }

        if (ExpiryDates1.MNL_ExpiryDate.HasValue != ExpiryDates2.MNL_ExpiryDate.HasValue)
        {
            result = false;
        }

        if ((ExpiryDates1.MNL_ExpiryDate != null) && (ExpiryDates2.MNL_ExpiryDate != null))
            if (ExpiryDates1.MNL_ExpiryDate.Value != ExpiryDates2.MNL_ExpiryDate.Value)
                result = false;

        if ((ExpiryDates1.PSL_ExpiryDate != null) && (ExpiryDates2.PSL_ExpiryDate != null))
            if (ExpiryDates1.PSL_ExpiryDate.Value != ExpiryDates2.PSL_ExpiryDate.Value)
                result = false;

        return result;
    }

The ExpiryDate class looks like this:

public class ExpiryDates
{
    public DateTime? MNL_ExpiryDate { get; set; }
    public DateTime? PSL_ExpiryDate { get; set; }
}


texts: Should I write my fadeTo function differently?

texts:
fadeTo = function(obj, time, to, cChange ){
    if ( typeof( time ) == "undefined" )
        time = 1000;
    if ( typeof( to ) == "undefined" )
        to = 1;

    if ( time <= 0 )
        return true;

    objSt = obj.style;
    objOpac = parseFloat(objSt.opacity) + 0;

    if ( typeof( cChange ) == "undefined" )
    {
        cChange = (to - objOpac)/(time/10);
    }

    objSt.opacity = objOpac + cChange;

    setTimeout( function(){
            fadeTo( obj, time - 10, to, cChange);
        }, 10);
};

This code was written as a replacement for fadeIn and fadeOut. I made this for learning purposes and it works fine.

I'm just not sure if I could write it better, and if it could cause problems in the future. I feel that I should use two functions instead: one as an init function, and one to finish the process without asking all the extra ifs and simple variable settings.


texts:
This is a continuation of previous questions. I just started using react and I've managed to fetch a xml file, convert it to json and then loop through the data. But I think there should be a better way to go through what I've done as I'm using a function I found on another SO answer and then used a map() within it.

Anyways here's the breakdown of my code.

Fetching the xml and converting to json:

componentDidMount() {
    axios.get('https://gist.githubusercontent.com/eMatsiyana/e315b60a2930bb79e869b37a6ddf8ef1/raw/10c057b39a4dccbe39d3151be78c686dcd1101aa/guestlist.xml')
    .then(res => {
      const xml = XMLMapping.load(res.data);
      var guests  = XMLMapping.tojson(xml);
      this.setState({guests: guests});
    });
  }

The results of the json in console:

Object{
  dataset{
   record{
    0{
      company{
        $t: "Skippad"
      }
      first_name{
        $t: "Keith"
      }
      last_name{
        $t: "Cook"
      }
    }
    1{
      company{
        $t: "Skippad"
      }
      first_name{
        $t: "Keith"
      }
      last_name{
        $t: "Cook"
      }
    }
   }
  }
}

I'm using this function to map the object and then using a map() within it:

function mapObject(object, callback) {
  return Object.keys(object).map(function (key) {
    return callback(key, object[key]);
  });
}

This is what the final mapping of the data looks like:

{mapObject(this.state.guests, (key, value) => {
  return

    {value.record
    .filter(
      (item,index) => {
        return (
          item.first_name.$t.toLowerCase().includes(this.state.search.toLowerCase())
          //item.last_name.$t.toLowerCase().includes(this.state.search.toLowerCase())
          //item.company.$t.toLowerCase().includes(this.state.search.toLowerCase())
        )
      }
    )
    .map((item,index) => {
      return

{item.first_name.$t} {item.last_name.$t}
{item.company.$t}

{item.company.$t}

          <EmailFormdisplay guestid={index} />

          <PhoneFormdisplay guestid={index} />

          <Dropdown>
            <DropdownTrigger></DropdownTrigger>
              <DropdownContent>

                    <EmailFormdisplay guestid={index} />

                    <PhoneFormdisplay guestid={index} />

              </DropdownContent>
          </Dropdown>

;
    })}

  })}

Is there a better way of doing this without using mapObject() and a map() within it?

Any kind of feedback or advice would be greatly appreciated!


texts:
I was able to pull the records I wanted but I have a feeling it could be written better for these particular MySQL query strings.

SELECT ID,XAxis,YAxis,Player,Castle,Alliance FROM SC75
WHERE Snap = (SELECT MAX(SavedSnap) FROM DataSnap WHERE Server = 75)
AND hex(Player) IN (hex('Vandiel'))
UNION
SELECT SC.ID,XAxis,YAxis,SC.Player,Castle,Alliance FROM SC75 AS SC
INNER JOIN AltFiller AS AF ON hex(AF.Player) IN (hex('Vandiel'))
WHERE SC.Player = AF.Alts
AND Snap = (SELECT MAX(SavedSnap) FROM DataSnap WHERE Server = 75)
ORDER BY Player,Castle


texts: Fine-grained synchronization to serve a file

texts:
I'm writing a proxy server that serves cached resources. If resource is not cached, it's retrieved and put into filesystem. Server is multi-threaded and I want to avoid any kind of global locking. If there are several requests for the same resource that is not cached at the same time, one request should retrieve resource, put it into filesystem and other requests should be blocked and then serve cached resource.

My first approach was to synchronize on interned string:

void serveFile(Path file) {
    if (!Files.exists(file)) {
        synchronized (file.toString().intern()) {
            if (!Files.exists(file)) {
                retrieveResource(file);
            }
        }
    }
    serveResource(file);
}

But there are many discussions about why this approach is not the best, so I rewrote is as follows:

private final ConcurrentMap<Path, Object> downloadLocks = new ConcurrentHashMap<>();

void serveFile(Path file) {
    if (!Files.exists(file)) {
        Object lock = downloadLocks.get(file);
        if (lock == null) {
            Object newLock = new Object();
            Object existingLock = downloadLocks.putIfAbsent(file, newLock);
            lock = existingLock == null ? newLock : existingLock;
        }
        try {
            synchronized (lock) {
                if (!Files.exists(file)) {
                    retrieveResource(file);
                }
            }
        } finally {
            downloadLocks.remove(file, lock);
        }
    }
    serveResource(file);
}

retrieveResource method retrieves resource into a temporary file and then performs atomical move into the final destination, so I assume that it's safe to use.

My question is if it's a correct multithreaded code and if there are better suited primitives for this fine-grained synchronization. I'm using Java 7.


texts:
var s = player.getSurrounding();
    if (vY > 0) {
        if ((s[0] || (s[7] && xLocal < LOCAL_LEFT) || (s[4] && xLocal > LOCAL_RIGHT)) && (yLocal + vY * dt) > LOCAL_RIGHT) {
            vY = (LOCAL_RIGHT - yLocal) / dt;
        }
    } else if (vY < 0) {
        if ((s[2] || (s[6] && xLocal < LOCAL_LEFT) || (s[5] && xLocal > LOCAL_RIGHT)) && (yLocal + vY * dt) < LOCAL_LEFT) {
            vY = (LOCAL_LEFT - yLocal) / dt;
        }
    }
    if (vX < 0) {
        if ((s[3] || (s[7] && yLocal > LOCAL_RIGHT) || (s[6] && yLocal < LOCAL_LEFT)) && (xLocal + vX * dt) < LOCAL_LEFT) {
            vX = (LOCAL_LEFT - xLocal) / dt;
        }
    } else if (vX > 0) {
        if ((s[1] || (s[4] && yLocal > LOCAL_RIGHT) || (s[5] && yLocal < LOCAL_LEFT)) && (xLocal + vX * dt) > LOCAL_RIGHT) {
            vX = (LOCAL_RIGHT - xLocal) / dt;
        }
    }

This might be a long shot, but I threw this together. It seems very inefficient and repetitive. It might be hard to explain, but here I go.

The world is made up of a grid of blocks that is saved in a 40x600 boolean array (true if filled, false if not).

The red block represents the player, a simple block that can fly in all directions. The position is defined by it's center point (orange).

The numbers represent the index of the boolean array s, true if the block is filled and false if not. Filled blocks should be interacted with.

xLocal and yLocal represents the position of the player in it's current grid position.
If the player is all the way to the left: xLocal = (playersize / 2) AKA LOCAL_LEFT.
If the player is all the way to the right: xLocal = blocksize - (playersize / 2) AKA LOCAL_RIGHT.
Same applies for yLocal but for up and down.

dt represents the game's delta time.

If the if-statements go through, the velocity is set so that xLocal will equal LOCAL_LEFT or LOCAL_RIGHT by the next time the position is updated.


texts:
The following method will add two strings of any length as binary numbers assuming the characters 1 and 0. I made this for fun in my spare time.  Improvements are not critical but I would like to hear them. I would also like to know if there is a more efficient algorithm to simulate a ALU.

static string BinAdd(string a, string b)
{
    if (a.Length < b.Length)
    {
        string c = a;
        a = b;
        b = c;
    }

    StringBuilder sb = new StringBuilder(a.Length);

    bool addLeft = false;

    for (int i = a.Length - 1, j = b.Length - 1; i >= 0; i--, j--)
    {
        char c = '1';
        bool add = addLeft;
        addLeft = false;

        if (j >= 0)
        {
            if (a[i] == '1' && b[j] == '1')
            {
                c = '0';
                addLeft = true;
            }
            else if (a[i] == '0' && b[j] == '0')
            {
                c = '0';
            }
            else if (add)
            {
                addLeft = true;
            }
        }
        else
        {
            if (a[i] == '0')
            {
                c = '0';
            }
            else if (add)
            {
                addLeft = true;
            }
        }

        sb.Append(add ? (c == '1' ? '0' : '1') : c);
    }

    if (addLeft)
    {
        sb.Append('1');
    }

    char[] cx = new char[sb.Length];
    sb.CopyTo(0, cx, 0, sb.Length);
    Array.Reverse(cx);

    return new string(cx);
}

I'm aware that no validation is done, but I didn't intend to.


texts:
I would like some help on making my solution more functional. At present, I rely heavily on using indexes in my map functions. I am also seeking general feedback and advice, thanks.

export const getMatrixColumns = (a: number[][]) => {
  return a[0].length;
};

export const getMatrixRows = (a: number[][]) => {
  return a.length;
};

export const matricesAreValid = (a: number[][], b: number[][]) => {
  return getMatrixColumns(a) === getMatrixRows(b);
};

export const generateEmptyMatrix = (rows: number, cols: number) => {
  return [...Array(rows)].fill(0).map(() => [...Array(cols)].fill(0));
};

export const dotProduct = (a: number[], b: number[]) => {
  return a.map((value, i) => value * b[i]).reduce((acc, val) => acc + val, 0);
};
export const multiplyMatrices = (a: number[][], b: number[][]) => {
  if (matricesAreValid(a, b)) {
    const rows = getMatrixRows(a);
    const cols = getMatrixColumns(b);
    return generateEmptyMatrix(rows, cols).map((resultRow, i) =>
      resultRow.map((element: number, j: number) => {
        const column = b.map(row => row[j]);
        const row = a[i];
        return dotProduct(row, column);
      })
    );
  }
};


texts:
I'm no ace when it comes to mathematical problems, so I've decided to go over some old college coursework and put it to code. The function works just fine and the returned values are spot on, but I'm wondering if there's a better way to solve this problem, perhaps more readable.

Problem:

  Restaurant 'A' has recently opened a 'drive through' service for its customers. The checkout has a mean arrival time of 20 per hour, with a service rate of 29 per hour. Due to the success of the new service, a second checkout has been opened.

  Rival restaurant, 'B', has launched an identical 'drive through' service, consisting of two checkout windows. This restaurant's mean arrival time is 19 per hour and the mean service rate is 17 per hour.

  In restaurant 'A', what is the probability that there will be exactly 2 customers in the queue?

  In restaurant 'B', what is the probability that the queue will be empty.

Formulas used

$$idle = P_0 = \frac{2\mu - \lambda}{2\mu + \lambda}$$
$$n\ state\ probability = P_n = \frac{1}{2^{n-1}}.\frac{\lambda}{\mu}^n.P_0$$

Where \$\lambda\$ is the arrival time, and \$\mu\$ is the service rate.

Code:

def n_state_probability(arrival_time, service_rate, n):
    """Return a value representing the probability an M/M/2 queue is in state n.

    To calculate the probability that the queue is empty, let n = 2.

    Arguments:
        arrival_time: mean arrival time per hour
        service_rate: mean service rate per hour
        n: amount of customers in the queue

    """
    idle = ((2 * service_rate) - arrival_time) / ((2 * service_rate) + arrival_time)
    probability = (1 / 2 ** (n - 1)) * ((arrival_time / service_rate) ** n) * idle
    if n == 2:
        return idle + probability + ((arrival_time / service_rate) * idle)
    return probability

if __name__ == '__main__':
    n_state_probability(19, 17, 2)
    # => 0.7760984526996147
    n_state_probability(20, 29, 4)
    # => 0.01377612256456733


texts:
I wrote a text adventure game a while back and today I looked at it to see how I did the word wrapping (to use in a new project); I'm curious if I went about it the right way. I realize I could use an array instead of a list and remove 2 dependencies from the class but wanted some other feedback as I may have missed something obvious.

    public static string GetBorderedText(string Input, int AbsoluteLength, bool splitLines = true, int Offset = -4)
    {
        string outputString = "";

        if(Input.Length > AbsoluteLength + Offset && splitLines)
        {
            List<string> words = Input.Split(' ').ToList();
            string lineConstruction = "";

            foreach (string s in words)
            {
                if (lineConstruction.Length + s.Length + 1 >= AbsoluteLength + Offset)
                {
                    outputString += "+ " + GetPaddedSubstring(lineConstruction, AbsoluteLength, Offset) + " +" + Environment.NewLine;
                    lineConstruction = "";
                    lineConstruction += s + " ";
                }
                else
                {
                    lineConstruction += s + " ";
                }
            }

            outputString += "+ " + GetPaddedSubstring(lineConstruction, AbsoluteLength, Offset) + " +";

            return outputString;
        }
        else
        {
            outputString = "+ " + GetPaddedSubstring(Input, AbsoluteLength, Offset) + " +";
            return outputString;
        }
    }

where GetPaddedSubstring  is used for getting a substring padded to a certain length.

    public static string GetPaddedSubstring(string Input, int AbsoluteLength, int Offset)
    {
        int targetLength = AbsoluteLength + Offset;
        string output = "";

        if(Input.Length > targetLength)
        {
            return Input.Substring(0, targetLength);
        }
        else
        {
            output = Input.PadRight(targetLength);

            return output;
        }
    }

Lastly, for some examples. GetBorderedText can take in something like

"This room looks sturdy, but old. Lots of storage and containers. There is a door on the far side."

And return something like this.

+ This room looks sturdy, but old. Lots of storage and containers. There is a door     +
+ on the far side.                                                                     +

The + on the side are just to create a nice border within the Console window. (Hence the -4 default on Offset)


texts: One dimension cellular automation in Python

texts:
Here is my implementation for one dimensional cellular automation in Python. Any suggestions for more efficiency - other strategies?

ncells = ['111','110','101','100','011','010','001','000']

def next_state (state, rule):
    newstate = ''
    binrule = bin(rule)[2:]
    binrule = (8-len(binrule))*'0' + binrule
    for i in range(len(state)):
        cells = state[i-1] + state[i] + state[(i+1)%len(state)]
        newstate += binrule[ncells.index(cells)]
    return newstate

def wolfram (init_state, generations, rule):
    state = init_state
    for i in range(generations):
        yield state
        state = next_state(state, rule)

for i in wolfram('000000000010000000000', 30, 30):
    print i


texts: Adding multiple items of different categories to one object

texts:
I want to run the function addItem() for every item. Multiple items will belong to the same slot (category). For each category I have to run the function with the same slot. I don't want to manually write down the slot for each and every item, because there could be 100's for each category.

The goal is to get the best result in terms of: readability, maintainability and effort to add items.

Here is my current code:

let equipment = {
    head: {},
    cape: {},
    neck: {},
    ammunition: {},
    weapon: {},
    body: {},
    shield: {},
    legs: {},
    hand: {},
    feet: {},
    ring: {}
};

function createShortName(name) {
    return name.toLowerCase().replace(/\s/g, '');
}

function addItem(slot, name, cost, img, income=0, atk_bonus=0, str_bonus=0, def_bonus=0, rngd_bonus=0, mage_bonus=0) {

    let newItem = {
        slot: slot,
        name: name,
        cost: cost,
        img: img,
        income: income,
        atk_bonus: atk_bonus,
        str_bonus: str_bonus,
        def_bonus: def_bonus,
        rngd_bonus: rngd_bonus,
        mage_bonus: mage_bonus
    }

    equipment[slot][createShortName(name)] = newItem;
}

let currentSlot = 'head';
addItem(currentSlot, 'head_item_1', 100, 'img');
addItem(currentSlot, 'head_item_2', 200, 'img');

currentSlot = 'cape';
addItem(currentSlot, 'cape_item_1', 100, 'img');

currentSlot = 'neck';
addItem(currentSlot, 'neck_item_1', 100, 'img');
addItem(currentSlot, 'neck_item_2', 200, 'img');
addItem(currentSlot, 'neck_item_3', 400, 'img');
addItem(currentSlot, 'neck_item_4', 800, 'img');

// etc. etc. etc.

As you can see, I add items to the equipment object at the bottom of the code. Is there a better approach?


texts:
from graphics import Graphics
from time import sleep
import random

class Hangman(object):

    def __init__(self, word):
        self.word = word
        self.used_letters = ""
        self.current_letter = ""

    @property
    def grid(self):
        grid = ""
        for i in self.word:
            if i in self.used_letters:
                grid += i
            else:
                grid += "_ "
        return grid

    def show_grid(self):
        print("Used Letters: " + self.used_letters)
        print("\n" + self.grid)

    def ask_letter(self):
        while True:
            letter = input("Guess a letter: ").lower()
            self.current_letter = letter
            if len(self.current_letter) > 1:
                print("\nYou have entered to many letters!")
            else:
                if self.current_letter in self.used_letters:
                    print("This letter has already been used!")
                    continue
                else:
                    self.used_letters += self.current_letter + " "
                    return "Letter Added"

    def check(self):
        if self.current_letter in self.word:
            if "_" in self.grid:
                return "Continue Game"
            else:
                return "Winner"

        else:
            return "Not a letter"

    def winner(self):
        print("\n")
        print("You have won!!")
        print("\nWould you like to play again?")
        reply = input("Y/N?").lower()
        if reply == "y":
            print("\n")
            main()
        else:
            print("Thank you for playing!")
            exit()

    def lost(self):
        print("\n")
        print("You have lost!")
        print(Graphics[0])
        print("The word was: " + self.word)
        sleep(2)
        print("\nWould you like to play again?")
        reply = input("Y/N?").lower()
        if reply == "y":
            print("\n")
            main()
        else:
            print("Thank you for playing!")
            exit()

def main():
    words = ["hello", "goodbye"]
    attempts = 8
    hangman = Hangman(random.choice(words))
    while attempts > 0:
        hangman.show_grid()
        hangman.ask_letter()
        hangman.check()
        if hangman.check() == "Winner":
            hangman.winner()
        if hangman.check() == "Not a letter":
            attempts -= 1
            print(Graphics[attempts])
            print("{0} attempts remain".format(attempts))
            print("\n")
    hangman.lost()

if __name__ == "__main__":
    main()

I am looking for any advice on how to improve my hangman game.

The graphics are in a separate document. It is just images of the hangman.


texts:
Problem statement is at http://www.codechef.com/DEC13/problems/MARBLEGF

  Lira is given array A, which contains elements between 1000 and 2000.
  Three types of queries can be performed on this array: add a given value to a single element on it, subtract a given value from a single element on it and find the sum of the values between indexes i and j, i.e. A[i]+...+A[j]. Check input and example section for details.

  Input

  The first line of the input contains two integers: N and Q, denoting respectively, the number of students that there are present to receive the marbles as a gift and the number of actions Lira's mom will perform.

  These actions can be of three different types:

  S i j - if the mom wants to find the sum of the number of marbles from students i to j.
  G i num_marbles - if the mom decides to give num_marbles to student i
  T i num_marbles - if the mom decides to take away num_marbles from student i

  Output

  The output should contain as many lines as the number of queries S and it should contain the answer for each query on a separate line

  Constraints

  2 ≤ N ≤ 1000000
  3 ≤ Q ≤ 50000
  The array is 0-indexed.
  1000 ≤ A[i] ≤ 2000
  A student can never have a negative value of marbles. (i.e. there's no data which can cause a student to have a negative value of marbles)
  0 ≤ i, j ≤ N-1, and i ≤ j for the sum query
  At any given time, it is assured that the maximum number of marbles each student can have (num_marbles) never exceeds the size of the int data type.

  Example

  Input:

5 3
1000 1002 1003 1004 1005
S 0 2
G 0 3
S 0 2

  Output:

3005
3008

My code gives time limit exceeded.

My code:

import java.util.*;

class funny_marbles
{
    public static void main(String[] ar)
    {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int q = sc.nextInt();
        int[] a = new int[n];
        for(int i = 0; i < n; i++)
            a[i] = sc.nextInt();
        for(int i = 0; i < q; i++)
        {
            String s = sc.next();
            int t1 = sc.nextInt();
            int t2 = sc.nextInt();
            if(s.equals("S"))
            {
                long sum = 0;
                for(int j = t1; j <= t2; j++)
                    sum+=a[j];
                System.out.println(sum);
            }
            else if(s.equals("G"))
                a[t1]+=t2;
            else if(s.equals("T"))
                a[t1]-=t2;
        }
    }
}

Updated to use cumulative sum, but still exceeding time limit:

import java.util.*;

class funny_marbles
{
    public static void main(String[] ar)
    {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int q = sc.nextInt();
        int[] a = new int[n];
        for(int i = 0; i < n; i++)
        {
            if(i == 0)
                a[i] = sc.nextInt();
             else
                a[i] = a[i-1] + sc.nextInt();
        }
        for(int i = 0; i < q; i++)
        {
            String s = sc.next();
            int t1 = sc.nextInt();
            int t2 = sc.nextInt();
            if(s.equals("S"))
            {
                int x;
                if(t1 == 0)
                    x = 0;
                else
                    x = a[t1-1];
                System.out.println(a[t2]-x);
            }
            else if(s.equals("G"))
            {
                update(a,t2);
            }
            else if(s.equals("T"))
            {
                update(a,-t2);
            }
        }
    }

    public static void update(int[] a, int t)
    {
        for(int i = 0; i < a.length; i++)
            a[i] += t;
    }
}


texts: Project Euler #4 - Largest Palindrome Project - Python

texts:
I solved the HackerRank version of the Largest palindrome problem (similar to Project Euler 4) in Python:

  Find the largest palindrome made from the product of two 3-digit numbers which is less than N, where 101101 < N < 1000000.

How can I make this more efficient? My solution keeps timing out.

Here is the Code:

# Find the Largest palindrome made from two three digit numbers which are less than N

# Get the input and store it in an array
def get_input():
    limit = int(input())
    limits = []

    for _ in range(limit):
        limits.append(int(input().strip()))

    return limits

# Check if palindrome or not
def is_palindrome(num):
    if str(num) == str(num)[::-1]:
        return True
    else:
        return False

# Find the Largest Palindrome
def largest_palindrome(num):
    largest = 0

    for i in range(2,999+1):
        for j in range(i+1 , 999+1):
            prod = i * j
            if is_palindrome(prod) and prod > largest and prod < num:
                largest = prod

    return largest

# Get the Limits
limits = get_input()

for limit in limits:
    print(largest_palindrome(int(limit)))


texts: Evicting an entry from a size-limited HashMap

texts:
I have a HashMap with a limited size of 1000 elements. When I want to put one more, the T with the lowest related Integer in the map should be replaced with the new one.

I already have this working solution for my problem, but it seems a bit too much code for me so maybe you have a better idea :)

HashMap<T, Integer> set = new HashMap<>();
   public boolean add(T element) {
    if (set.containsKey(element)) {
        return false;
    } else if (set.size() == length) {
        Integer searchedInteger = set.values().stream().sorted().findFirst().get();
        T searchedElement = set.entrySet()
                .stream()
                .filter(x -> x.getValue().equals(searchedInteger))
                .findFirst()
                .get()
                .getKey();
        set.remove(searchedElement);
    }
    set.put(element, 0);
    return true;
}


texts: A simple implementation of the producer/consumer pattern

texts:
Consider this class that consumes some items and handles them with the provided handler function:

#include <queue>
#include <mutex>
#include <atomic>
#include <thread>
#include <utility>
#include <condition_variable>

template < typename Item >
struct Handler
{
  template < typename Callable >
  Handler(Callable&& callable) : m_thread([&]()
  {
    for (std::queue<Item> queue; !m_isInterruptionRequested;)
    {
      {
        std::unique_lock<std::mutex> lock(m_mutex);
        m_queueIsNotEmpty.wait(lock, [&]{ return m_isInterruptionRequested || !m_queue.empty(); });
        m_queue.swap(queue);
      }
      for (; !queue.empty(); queue.pop())
        std::forward<Callable>(callable)(std::move(queue.front()));
    }
  }) { }

  void addItem(Item&& item)
  {
    {
      std::lock_guard<std::mutex> lock(m_mutex);
      m_queue.push(std::move(item));
    }
    m_queueIsNotEmpty.notify_one();
  }

  ~Handler()
  {
    m_isInterruptionRequested = true;
    m_queueIsNotEmpty.notify_all();
    m_thread.join();
  }

private:
  std::mutex              m_mutex;
  std::queue<Item>        m_queue;
  std::condition_variable m_queueIsNotEmpty;
  std::atomic<bool>       m_isInterruptionRequested = ATOMIC_VAR_INIT(false);
  std::thread             m_thread; // VM: Has to be the last field!
};

Any suggestions on what could be better in this implementation (e.g. a better way to handle the interruptions)?

Are there any hidden threats in this implementation that I don't see?


texts: Generation of Groovy source from parent Java class

texts:
I use Groovy to write business rules into big, long term Java software. Use Groovy in object way, that is not as groovy Script, but every elementary groovy source overrides some Java API class.

i.e. AtLoginScript, PreparePaport etc.

I had an idea to clone in very little scale IDE functionality: generate class from, or Override method.

My idea is much simpler: do automatically, only first-shot, write method stub where this must be done (abstract method), maybe in comment where may be done (non-abstract).

My mini project has first effects, in this sample GroovyGenerator create his-own 'child class'.

My target for next days is to:

implement negative conditions for final or private method,
some decisions with more deep parent class (now only one-level)
types when applicable
maybe implement groovy property from getter/setter pair?
constructors
extend from 0 or 1 class and implement zero to \$n\$ interfaces (What to do with override level?)

I haven't big trouble with coding (one small problem: reflection usually doesn't give parameters name), but with idea.

This tool is made for in-place IT-man, who generate business rules in, for example, Notepad or simple editor non-capable in generation.

What can be done better in this project?

package pl.cogitat.scripting;

import java.lang.reflect.Method;
import java.lang.reflect.Parameter;

public class GroovyGenerator {
    Class analyzedClass;
    private String packg;
    private String name;

    public GroovyGenerator(String pckg, String name, Class analyzedClass) {
        super();
        this.analyzedClass = analyzedClass;
        this.packg = pckg;
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPackg() {
        return packg;
    }

    public String performGeneration()
    {
        StringBuilder sb = new StringBuilder();
        sb.append("package ").append(packg).append("\n\n /* Code auto generated\n * do edit what You want \n */\n\n");

        String parentName = analyzedClass.getSimpleName();
        sb.append("class ").append(name).append(" extends ").append(parentName).append(" {\n");

        for(Method m : analyzedClass.getDeclaredMethods())
        {
            sb.append("def ").append(m.getName()).append("(");
            int pcnt = 0;
            for(Parameter p:m.getParameters())
            {
                if(pcnt>0)
                    sb.append(", ");
                sb.append(p.getType().getSimpleName()).append(" ").append(p.getName());
                pcnt++;
            }
            sb.append(")\n{\n}\n");
        }

        sb.append("\n}\n");
        return sb.toString();

    }
}

and untouched generated Groovy:

package my.script

 /* Code auto generated
 * do edit what You want
 */

class SelfGenerator extends GroovyGenerator {
def getName()
{
}
def setName(String arg0)
{
}
def performGeneration()
{
}
def getPackg()
{
}

}


texts:
I'm trying to learn Python by working my way through problems on the Project Euler website. I managed to solve problem #3, which is

  What is the largest prime factor of the number 600851475143 ?

However, my code looks horrible. I'd really appreciate some advice from experienced Python programmers.

import math
import unittest

def largestPrime(n, factor):
    """
    Find the largest prime factor of n
    """

    def divide(m, factor):
        """
        Divide an integer by a factor as many times as possible
        """
        if m % factor is 0 :
            return divide(m / factor, factor)
        else :
            return m

    def isPrime(m):
        """
        Determine whether an integer is prime
        """
        if m is 2 :
            return True
        else :
            for i in range(2, int(math.floor(math.sqrt(m))) + 1):
                if m % i is 0 :
                    return False
            return True

    # Because there is at most one prime factor greater than sqrt(n),
    # make this an upper limit for the search
    limit = math.floor(math.sqrt(n))

    if factor <= int(limit):
        if isPrime(factor) and n % factor is 0:
            n = divide(n, factor)
            if n is 1:
                return factor
            else:
                return largestPrime(n, factor + 2)
        else:
            return largestPrime(n, factor + 2)
    return n


texts: How can I optimise a foreach calling an API? The code calls an API and returns the first string reponse

texts:
I have the following code that makes a call to an external API, processes the response and returns a string. The problem is it is taking a very long time to process. I can't do anything to the API, but I was just wondering if there is a better way of doing the rest of the code.
foreach(var item in products)
{
    item.site = await _testRepo.GetSiteLink(item.Id, item.baseLink);
}

And the GetSiteLink method in a different class.
public async Task<string> GetSiteLink(int itemId, string baseLink)
{
    var encodedUrl = HttpUtility.UrlEncode(baseLink);
    var response = await _client.GetAsync($"apilink/{itemId}/?ulp={encodedUrl}");
    if (response.IsSuccessStatusCode)
    {
        var responseContent = await response.Content.ReadAsStringAsync();
        var parsedResponse = JsonConvert.DeserializeObject<string[]>(responseContent);
        return HttpUtility.UrlDecode(parsedResponse[0]);
    }
    return "";
}


texts:
I recently got in really deep on a question to find the overlapping meetings and I rewrote a bit of the code and added some things to the code, and I would just like a general review of my code and what I could do to make it even better, maybe performance wise or whatever.

Here is my LINQPad 5 Code Dump, you should be able to copy paste into LINQPad and run it, I don't think I did anything that is too cutting edge.

{
    var format = System.Globalization.CultureInfo.InvariantCulture.DateTimeFormat;
    Meeting[] meetings = new Meeting[]
    {
        new Meeting(DateTime.Parse("1/1/2015 21:30", format), DateTime.Parse("1/1/2015 23:00", format)),
        new Meeting(DateTime.Parse("1/1/2015 23:10", format), DateTime.Parse("1/1/2015 23:30", format)),
        new Meeting(DateTime.Parse("1/1/2015 20:00", format), DateTime.Parse("1/1/2015 21:30", format)),
        new Meeting(DateTime.Parse("1/1/2015 22:10", format), DateTime.Parse("1/1/2015 22:20", format)),
        new Meeting(DateTime.Parse("1/1/2015 23:20", format), DateTime.Parse("1/1/2015 23:50", format)),
        new Meeting(DateTime.Parse("1/1/2015 23:20", format), DateTime.Parse("1/2/2015 00:00", format)),
        new Meeting(DateTime.Parse("1/2/2015 09:00", format), DateTime.Parse("1/2/2015 12:00", format)),
        new Meeting(DateTime.Parse("1/2/2015 09:00", format), DateTime.Parse("1/2/2015 10:00", format)),
        new Meeting(DateTime.Parse("1/2/2015 11:00", format), DateTime.Parse("1/2/2015 11:30", format))
    };

    var overlappingMeetings = meetings.Overlappings();
    var meetingsOverlap = meetings.Overlappings().Any();
    overlappingMeetings.Dump();
    meetingsOverlap.Dump();
}

public static class StaffMeetings
{
    public static IEnumerable<Meeting[]> Overlappings(this IEnumerable<Meeting> meetings)
    {
        var first = (Meeting)null;
        var orderedMeetings = meetings.OrderBy(m => m.Start);
        var checkedMeetings = new List<Meeting>();

        foreach (var meeting in orderedMeetings)
        {
            if (first != null)
            {
                checkedMeetings.Add(first);
                var uncheckedMeetings = orderedMeetings.Where(x => (x.Start >= first.Start && !(x == first)) && !checkedMeetings.Any(m => m == x));
                foreach (var meet in uncheckedMeetings)
                {
                    if (first.OverlapsWith(meet))
                    {
                        yield return new[] { first, meet };
                    }
                }
            }
            first = meeting;
        }
    }
}
public class Meeting
{
    public DateTime Start { get; private set; }
    public DateTime End { get; private set; }

    public Meeting(DateTime start, DateTime end)
    {
        if (end < start)
        {
            throw new ArgumentException("Cannot create a meeting that ends before it starts.");
        }
        this.Start = start;
        this.End = end;
    }

    public bool OverlapsWith(Meeting second)
    {
        return this.End > second.Start;
    }
    public override bool Equals(object obj)
    {
        return base.Equals(obj);
    }
    public override int GetHashCode()
    {
        return base.GetHashCode();
    }
}

here are the results of that run as well

Did I miss anything?

Are there more edge cases that I didn't consider?

Is there a nice, neat, acceptable way of streamlining the foreach statements with the if statements inside of them?  (Kind of curious if it is possible to one line it)


texts: Invert bits of binary representation of number

texts:
This is the code I came up with.

I added comments to make the solution more verbose.

int findComplement(int num) {
    // b is the answer which will be returned
    int b = 0;

    // One bit will be taken at a time from num, will be inverted and stored in n for adding to result
    int n = 0;

    // k will be used to shift bit to be inserted in correct position
    int k = 0;

    while(num){
        // Invert bit of current number
        n = !(num & 1);

        // Shift the given number one bit right to accesss next bit in next iteration
        num = num >>1 ;

        // Add the inverted bit after shifting
        b = b + (n<<k);

        // Increment the number by which to shift next bit
        k++;
    }
    return b;
}

Is there any redundant statment in my code which can be removed? Or any other better logic to invert bits of a given integer


texts:
I am working with closures and want to confirm that I do not have any memory leaks in my code. Below is my current code:

// in ImageGalleryController.swift
class ImageGalleryCollectionViewController: UICollectionViewController {
  var images = [Image]()

func dropInteraction(_ interaction: UIDropInteraction, performDrop session: UIDropSession) {
    // assignment of closure
    var cellImage = Image() { [weak self](image) in
      self?.images.append(image)
      self?.collectionView.reloadData()
    }
    // asynchronous
    session.loadObjects(ofClass: NSURL.self) { urls in
      if let url = urls.first as? URL {
        cellImage.url = url
      }
    }
    // asynchronous
    session.loadObjects(ofClass: UIImage.self) { images in
      if let image = images.first as? UIImage {
        cellImage.aspectRatio = Double(image.size.height / image.size.width)
      }
    }
  }
}

// in ImageGallery.swift
struct Image {
  var url: URL? = nil {
    didSet {
      if propertiesAreSet() { handler(self) }
    }
  }
  var aspectRatio: Double? = nil {
    didSet {
      if propertiesAreSet() { handler(self) }
    }
  }

  init(handler: @escaping (Image) -> Void) {
    self.handler = handler
  }

  var handler: (Image) -> Void

  private func propertiesAreSet() -> Bool {
    let bool = (url != nil && aspectRatio != nil) ? true : false
    return bool
  }
}

Basically my logic is that when two separate asynchronous requests get and set two separate properties on the Image struct, then I want to append that Image struct to the images array.

Which brings me to my related questions:

Since I am fairly new to Swift, am I properly handling memory leaks by declaring [weak self] when I create a new Image instance?
Should I set the closure handler to nil after it executes?
Is what I am doing ok or am I violating any Swift principles?


texts:
update1:

- I need to make two different api calls.
- from the result of first api call I am getting id in the variable firstAPIid,
https://reqres.in/api/users?page=2
- I need to pass this id firstAPIid to the second api call.

can you review my code.
I did multiple api calls through promise.
right way is through promise or async or call back.
providing my code snippet and sandbox below.

https://codesandbox.io/s/redux-async-actions-xjdo7

<FetchButton
          onFetchClick={() => {
            store.dispatch(dispatchFunc => {
              dispatchFunc({ type: "FETCH_DATA_START" });
              axios
                .get("https://reqres.in/api/users?page=2")
                // axios.get('https://jsonplaceholder.typicode.com/posts')
                .then(response => {
                  console.log("response.data.data---->", response.data.data);
                  console.log(
                    "response.data.data[0].id---->",
                    response.data.data[0].id
                  );
                  //First of all we'll create the number of requestes base on the previous Response
                  const promises = response.data.data.reduce(
                    (previousValue, { id }) => {
                      previousValue.push(
                        axios.get(
                          `https://jsonplaceholder.typicode.com/comments?postId=${id}`
                        )
                      );
                      console.log(
                        " promises previousValue---->",
                        previousValue
                      );

                      return previousValue;
                    },
                    []
                  );

                  console.log("promises---->", promises);

                  //We use the built in function to fetch the data
                  axios.all(promises).then(responses => {
                    //Here you have all responses processed
                    const emailsMapped = responses.reduce(
                      (previousValue, { data }) => {
                        const emails = data.map(({ email }) => email);
                        previousValue.push(...emails);
                        return previousValue;
                      },
                      []
                    );
                    //You send the emails you want
                    dispatchFunc({
                      type: "RECEIVED_DATA",
                      payload: emailsMapped
                    });
                    console.log(emailsMapped);
                  });
                })
                .catch(err => {
                  dispatchFunc({ type: "FETCH_DATA_ERROR", payload: err });
                });
            });
          }}
        />


texts: Convert seconds to hours, minutes and seconds

texts:
My logic is as follow:

Convert actual time to minutes.
Extract seconds from minutes (30:04 -> 4 seconds).
Subtract seconds value from minutes (step1-step2) to get time only in seconds.
Convert time in minutes (step 3 output/60) to hours.

Now suppose i got time as 5404 which corresponds to 1:30:04. When I divide 5404, I get value as 90.0666666667. 0666666667 is actually 4 seconds to get value as 4 seconds. I convert the data to 60 unites by using percentage formula i.e

value * 60 / 100

I know there is a better solution here.

import java.math.BigDecimal;
import java.math.RoundingMode;

public class TimeCalc {

    public static void main(String[] args) {

        // Inital Time in seconds
        BigDecimal actualTime = new BigDecimal(5404);

        // 60 seconds
        BigDecimal seconds = new BigDecimal(60);

        // dividing original time to get time in mintues
        BigDecimal timeinMinutes = actualTime.divide(seconds, 2, RoundingMode.CEILING);

        // to get value of seconds from minutes
        double secondsValue = timeinMinutes.doubleValue() - Math.floor(timeinMinutes.doubleValue());

        // Seconds will be removed from Minutes to get only Minutes value
        BigDecimal deductiableSecondValue = new BigDecimal(secondsValue);
        timeinMinutes = timeinMinutes.subtract(deductiableSecondValue);
        timeinMinutes = new BigDecimal(Math.ceil(timeinMinutes.doubleValue()));

        // dividing minutes by 60 to get actual time in hours
        BigDecimal timeinHours = timeinMinutes.divide(seconds, 2, RoundingMode.CEILING);
        double hoursdecimalValue = timeinHours.doubleValue();

        // suppose time is 1.30 , below code is to get the 30 minutes
        double minutes = hoursdecimalValue - Math.floor(hoursdecimalValue);

        // converting value in units of Time since it is always measured wrt 60
        minutes = convertDateinTimeUnit(minutes);

        // suppose time is 1.30 below code is get 1 value
        String str = new Double(hoursdecimalValue).toString();
        str = str.substring(0, str.indexOf('.'));
        double v = Double.valueOf(str);

        // converting value in units of Time since it is always measured wrt 60
        secondsValue = convertDateinTimeUnit(secondsValue);

        secondsValue = Math.ceil(secondsValue);

        minutes = Math.ceil(minutes);

        System.out.println(" secondsValue " + secondsValue);
        System.out.println(" minutes decimal value " + minutes);
        System.out.println(" hours " + v);

    }

    static double convertDateinTimeUnit(double value) {
        double valueInTimeUnit = 60 * value / 100;
        return valueInTimeUnit * 100;

    }

}


texts:
I want to make show/hide logic more maintainable in my codebase.

Because they are too faraway located in separate js files, it hard for people to maintain.

The  flow in my codebase is:

  require.js init (hide the target DOM at first) → app.js → load_comments.js (show the target DOM if the comments length > 0)

main.js (require.js manifest file)

$("#target_dom").hide();

app.js

define([
    'load_comments',
    "jquery"
],function( comments, $){

    return {
        initialize: function(){
            console.log("app.js initialized");
        }
    }
})

load_comments.js

var CommentView = Backbone.View.extend({
    el: $("#comments_section"),
    render: function() {
        var notNullComments = comments.wellFormedComments();
        if (notNullComments.length > 0) {
            $("#target_dom").show();
        }
        var html = commentsTmpl(notNullComments.toJSON());
        $(this.el).append(html);
    },
});


texts:
Here is a function that formats a phone number and adds a country code prefix if it is not included in it.

So, as an in input value it could be, for example, '23581010' or '4923581010' and in output it would become via the formatNumber function '(02) 358 10 10'.

Is the positioning of the let assignment ok in this code ? If something else feels not ok can you tell me ?

import { formatNumber } from 'libphonenumber-js';

export const formatGermanPhoneNumber = phoneNumber => {
  if (!phoneNumber) {
    return '';
  }

  const phoneNumberString = `${phoneNumber}`;

  let prefix = '';
  if (!phoneNumberString.startsWith('49')) {
    prefix = '49';
  }

  return formatNumber(`+${prefix}${phoneNumberString}`, 'National');
};


texts: Configuring an editor for various languages using Factory Method Pattern

texts:
I need to know if my code is a valid implementation of the factory method pattern. Also, if the Configuration and Editor were interfaces would this still be a valid implementation of the Factory Pattern?

public abstract class Configuration {

    protected List<String> keyWords;

    abstract void getTheme();
    abstract String getKeyWords();
}

public abstract class Editor {

    public final void useEditor() {
        Configuration configuration = createConfiguration();
        configuration.getTheme();
        parse(configuration.getKeyWords());
        save();
    }

    //The Factory Method
    public abstract Configuration createConfiguration();

    public abstract void parse(String sourceCode);

    public void save() {
        System.out.println("The file was saved..");
    }
}

public class JavaConfiguration extends Configuration {
    public JavaConfiguration() {
        keyWords = new ArrayList<>();
        keyWords.add("class");
        keyWords.add("protected");
    }

    @Override
    void getTheme() {
        System.out.println("Applied Java Theme...");
    }

    @Override
    String getKeyWords() {
        return keyWords.toString();
    }
}

public class PythonConfiguration extends Configuration {

    public PythonConfiguration() {
        keyWords = new ArrayList<>();
        keyWords.add("def");
        keyWords.add("print");
    }

    @Override
    void getTheme() {
        System.out.println("Applied Python Theme...");
    }

    @Override
    String getKeyWords() {
        return keyWords.toString();
    }
}

public class JavaEditor extends Editor {
    @Override
    public Configuration createConfiguration() {
        return new JavaConfiguration();
    }

    @Override
    public void parse(String sourceCode) {
        System.out.println("Parsing Java code...");
    }
}

public class PythonEditor extends Editor {

    @Override
    public Configuration createConfiguration() {
        return new PythonConfiguration();
    }

    @Override
    public void parse(String sourceCode) {
        System.out.println("Parsing python code...");
    }
}

public class App {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String language = sc.next();
        Editor editor = createEditor(language);
        editor.useEditor();
    }

    private static Editor createEditor(String language) {
        switch(language) {
            case "Java":
                return new JavaEditor();
            case "Python":
                return new PythonEditor();
            default:
                return null;
        }
    }
}

Edit: It seems that the Factory Method Pattern is not the appropriate design pattern to use in this case, as suggested by @200_success and @Timothy Truckle. A simple Editor class which receives a Configuration as a parameter should be enough.


texts: Switch an image based on click coordinate

texts:
I'm still learning how to use jQuery. I created a function where when I click on some coordinate, it will then show a different image. I would like to make the code cleaner and more reusable, but don't know how.

https://jsfiddle.net/ewtt0kzg/

$('.main-image').click(function(e) {
  var main_image = $(this);
  var topleft = $(this).siblings('.single-page-image').eq(0).attr('src');
  var botLeft = $(this).siblings('.single-page-image').eq(1).attr('src');
  var botRight = $(this).siblings('.single-page-image').eq(2).attr('src');
  var topRight = $(this).siblings('.single-page-image').eq(3).attr('src');
  var width = $(this).width();
  var height = $(this).height();
  var offset = $(this).offset();
  var relativeX = (e.pageX - offset.left);
  var relativeY = (e.pageY - offset.top);
  if (relativeY < (height / 2) && relativeX < (width / 2)) {
    main_image.attr('src', topleft);
  }
  if (relativeY < (height / 2) && relativeX > (width / 2)) {
    main_image.attr('src', topRight);
  }
  if (relativeY > (height / 2) && relativeX < (width / 2)) {
    main_image.attr('src', botLeft);
  }
  if (relativeY > (height / 2) && relativeX > (width / 2)) {
    main_image.attr('src', botRight);
  }
});
.second {
  display: none;
}


texts: Singleton with a volatile and synchronized instance

texts:
I created a singleton to have a unique instance of ExecutorService in my application.

I whould like to know which is the better of the two classes below.

First one :

public class ExecutorServiceSingleton {
    private static final Logger LOG = LoggerFactory.getLogger(ExecutorServiceSingleton.class);
    private ScheduledExecutorService scheduledExecutorService;

    private static ExecutorServiceSingleton instance;

    private ExecutorServiceSingleton() {
        scheduledExecutorService = Executors.newScheduledThreadPool(1);
    }

    /**
     * Method to run the task
     */
    public void runTask(Runnable task) {
        scheduledExecutorService.submit(task);
    }

    /**
     * Get the instance : If the instance is null, then we return a new one. If the instance is diff than null, then, we use the instance value and we return it.
     *
     * @return the instance
     */
    public static ExecutorServiceSingleton getInstance() {
        if (instance == null) {
            instance = new ExecutorServiceSingleton();
        }
        LOG.info("Instance: " + instance);
        return instance;
    }
}

Second one :

public class ExecutorServiceSingleton {
    private static final Logger LOG = LoggerFactory.getLogger(ExecutorServiceSingleton.class);
    private ScheduledExecutorService scheduledExecutorService;

    private volatile static ExecutorServiceSingleton instance;

    private ExecutorServiceSingleton() {
        scheduledExecutorService = Executors.newScheduledThreadPool(1);
    }

    /**
     * Method to run the task
     */
    public void runTask(Runnable task) {
        scheduledExecutorService.submit(task);
    }

    /**
     * Get the instance : If the instance is null, then we return a new one. If the instance is diff than null, then, we use the instance value and we return it.
     *
     * @return the instance
     */
    public static ExecutorServiceSingleton getInstance() {
        if (instance == null) {
            synchronized (ExecutorServiceSingleton.class) {
                if (instance == null) {
                    instance = new ExecutorServiceSingleton();
                }
            }
        }
        LOG.info("Instance: " + instance);
        return instance;
    }
}


texts:
Here is a class named Text, which takes a string as its argument of its constructor. It has property-methods to get the words in the string and also the frequency of alphabets occuring in it.

The words property result in all words in the string. It works as follows, after using the .split method, there is a possibility that a "word" is of the form ,word or word. or ,word. etc. So to encounter this we check each end using .isalpha.

We also have find_words method, which has words as its inputs. This method will summarize the frequencies of a set of words.

How can I write this better to:

The level of a library/package (I don't really understand the techniques for this)
More efficient and readable (using re module is last option)
More functional, but compact

#Author: Arief. A

example = "This is an example, an Anonymous text.\
 This text has 59 letters or numbers.";

class Text:

    def __init__(self, input_text):
        self.text = input_text;

    def show(self):
        print(self.text);

    def as_list(self):
        return list(self.text);

    def get_length(self):
        return len(self.text);

    def count_char(self, char):
        return self.text.count(char);

    @property
    def letter_freqs(self):
        letters="abcdefghijklmnopqrstuvwxyz";
        res={i: self.count_char(i) \
             for i in letters};
        caps={i.capitalize(): self.count_char(i.capitalize()) \
             for i in letters};
        res.update(caps);
        return res

    @property
    def words(self):
        raw=self.text.split();
        for i in range(len(raw)):
            if not raw[i][0].isalpha():
                raw[i]=raw[i][1:];
            if not raw[i][-1].isalpha():
                raw[i]=raw[i][0:-1];
        [raw.remove('') for i in range(raw.count(''))];
        return raw

    def swap_first(word):
        swaped=word[0].swapcase();
        res=swaped+word[1:];
        return res

    def find_words(self, *args):
        return {i: self.words.count(i)\
                      +self.words.count(Text.swap_first(i))\
                      for i in args};

Example

text_obj=Text(example);
text_obj.show();
print(text_obj.as_list());
print(text_obj.get_length());
print(text_obj.count_char("a"));
print(text_obj.words)
print(text_obj.find_words("Anonymous", "Text","This"));

Output

This is an example, an Anonymous text. This text has 59 letters or numbers.
['T', 'h', 'i', 's', ' ', 'i', 's', ' ', 'a', 'n', ' ', 'e', 'x', 'a', 'm', 'p', 'l', 'e', ',', ' ', 'a', 'n', ' ', 'A', 'n', 'o', 'n', 'y', 'm', 'o', 'u', 's', ' ', 't', 'e', 'x', 't', '.', ' ', 'T', 'h', 'i', 's', ' ', 't', 'e', 'x', 't', ' ', 'h', 'a', 's', ' ', '5', '9', ' ', 'l', 'e', 't', 't', 'e', 'r', 's', ' ', 'o', 'r', ' ', 'n', 'u', 'm', 'b', 'e', 'r', 's', '.']
75
4
['This', 'is', 'an', 'example', 'an', 'Anonymous', 'text', 'This', 'text', 'has', 'letters', 'or', 'numbers']
{'This': 2, 'Text': 2, 'Anonymous': 1}


texts: Dictionary algorithm, computing all case options

texts:
I am building this algorithm as part of a larger project for a network security class. The gist of this part is that I have been given a dictionary, and I need to find every possible option for a word in both upper and lowercase.

My teacher selected a word out of this dictionary, and messed with the case of a few random letters in it, then created the SHA-256 hash value for it. We have been given the hash value and now have to find the word.

I figured I would create two new dictionaries, use the first one to create all possible options of the upper lowercase combinations, then use that second one to create a third with all the hash values.

Example:

to
tO
To
TO

My first thought was that it looked a lot like counting in binary, and that's what I have based this algorithm off of. The only problem is that it's pretty slow.

   public class DictionaryBuilder {

private Scanner in;
private PrintWriter out;

public DictionaryBuilder() {

}

public File createHashDictionary(File dictionary) throws IOException {
    File hashDict = new File("HashDictionary.txt");
    in = new Scanner(dictionary);
    out = new PrintWriter(hashDict);
    String word;
    String wordList[];

    while (in.hasNext()) {
        wordList = getSmallWordList(in.nextLine());
        for (int i = 0; i < wordList.length; i++) {
            out.println(wordList[i]);
        }

    }
    in.close();
    out.close();
    return hashDict;
}

public String[] getSmallWordList(String _word) {
    System.out.println(_word);
    char[] word = _word.toCharArray();

    int length = (int) (Math.pow(2, _word.length()));

    char[][] binaryList = new char[word.length][length];

    int weirdCount = length / 2;

    for (int i = 0; i < word.length; i++) {
        //System.out.println();
        int count = 0;
        int onOff = 1;

        for (int n = 0; n < length; n++) {
            if (count == weirdCount) {
                onOff++;
                count = 0;
            }
            if ((onOff % 2 == 0)) {
                binaryList[i][n] = Character.toLowerCase(word[i]);
                System.out.print(binaryList[i][n]);
                count++;
            } else {
                binaryList[i][n] = Character.toUpperCase(word[i]);
                //System.out.print(binaryList[i][n]);
                count++;
            }
        }
        weirdCount = weirdCount / 2;
    }

    //System.out.println();
    //System.out.println();
    String wordList[] = new String[length];

    for (int i = 0; i < wordList.length; i++) {
        wordList[i] = "";
        for (int n = 0; n < word.length; n++) {
            wordList[i] = wordList[i] + "" + binaryList[n][i];

        }
        if(i%10==0){
        System.out.println(wordList[i]);}
    }

    return wordList;
}

Main method:

    public class Launch {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) throws NoSuchAlgorithmException, IOException {

    File dictionary = new File("Dictionary");

    DictionaryBuilder build = new DictionaryBuilder();
    File x = build.createHashDictionary(dictionary);

   Scanner in = new Scanner(x);
   System.out.println(in.nextLine());

}

It's stuck on "Antidisestablishmentarian." Can I streamline this?


texts: Concatenate unlimited amount of arrays with predefined function

texts:
I am working on learning more about arrays and loops! I have been trying to create a method which will allow me to take for example an unlimited amount of arrays and append or concatenate them to each other!

The method takes multiple arrays as arguments and creates a merged array in the order in which the arrays where passed through the parameter. My question is:

Is there a more efficient way to do this which I am maybe not aware of?

I have done my research but most ways usually use a set amount of arrays in order to achieve this. This is just something I am doing for the sake of learning, and these functions may not be useful in real life scenarios.

public static Object[] merge(Object[]... arrays) {
    int[] lenghts = new int[arrays.length];
    int wholeLenght = 0;
    int maxLenght = 0;

    for(int i = 0; i<arrays.length; i++){
        lenghts[i] = arrays[i].length;
    }
    for(int i = 0; i<lenghts.length; i++){
        wholeLenght += lenghts[i];
    }
    Object[] merged  = new Object[wholeLenght];

    for(int i = 0; i<arrays.length; i++){
        System.arraycopy(arrays[i], 0, merged, maxLenght, lenghts[i]);
        maxLenght+=lenghts[i];
    }
    return merged;
}

Version which allows generic types. A similar function can be easily made for
primitive a primitive type array of choice.

@SuppressWarnings("unchecked")
public static <T> T[] mergeGenerics(T[]... arrays) {
    int[] lenghts = new int[arrays.length];
    boolean allowOperation = true;
    int wholeLenght = 0;
    int maxLenght = 0;
    T[] merged = null;
    for (int i = 0; i < arrays.length; i++) {
        if (arrays[0].getClass().getComponentType() != arrays[i].getClass().getComponentType()) {
            allowOperation = false;
            System.err.println("The arrays are not all of the same type!!");
        }
    }
    if (allowOperation) {
        for (int i = 0; i < arrays.length; i++) {
            lenghts[i] = arrays[i].length;
        }
        for (int i = 0; i < lenghts.length; i++) {
            wholeLenght += lenghts[i];
        }
        merged = (T[]) Array.newInstance(arrays[0].getClass().getComponentType(), wholeLenght);

        for (int i = 0; i < arrays.length; i++) {
            System.arraycopy(arrays[i], 0, merged, maxLenght, lenghts[i]);
            maxLenght += lenghts[i];
        }
    }
    return merged;
}

Test The method maybe with:

        Object[] obj1 ={"A","B"};
        Object[] obj2 ={"C","D","E","F"};
        Object[] obj3 ={"G","H","I","J","K"};
        Object[] obj4 ={"L","M","N"};
        String[] obj5 ={"O","P","Q","R"};
        Object[] obj6 ={"S"};
        Object[] merge = Class.merge(obj1,obj2,obj3,obj4,obj5,obj6);

        for(int i = 0; i<merge.length; i++)
            System.out.print(merge[i]+" ");


texts:
I'm looking for code review comments for text justification problem described here.

Problem:

Given an array of words and a length L, format the text such that each line has exactly L characters and is fully (left and right) justified.

You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces ' ' when necessary so that each line has exactly L characters.

Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line do not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right.

For the last line of text, it should be left justified and no extra space is inserted between words.

For example,
words: ["This", "is", "an", "example", "of", "text", "justification."]
L: 16.

Response:

[
   "This    is    an",
   "example  of text",
   "justification.  "
]

/**
 * @param {string[]} words
 * @param {number} maxWidth
 * @return {string[]}
 */
var fullJustify = function(words, maxWidth) {
    let text = new Text(maxWidth);

    text.parse(words);

    return text.toStringArr();
};

function Text (maxWidth){
    this.lines = [];
    this.currLineIndex = -1;

    Text.prototype.parse = parse;
    Text.prototype.toStringArr = toStringArr;

    function parse(words) {
        words.forEach(function(word)  {
            let line = this.lines[this.currLineIndex];

            if(line && line.canAddWord(word)){
                line.add(word);
           } else {

               // Justify current row, if exists
               if(line) {
                line.justify();
               }

               // Create new row and add element to that
               this.currLineIndex++;
               line = new Line(maxWidth);
               this.lines[this.currLineIndex] = line;

               line.add(word);
           }
        }, this);

        // Justify last line
        let lastLine = this.lines[this.currLineIndex];
        lastLine.justify(true);
    }

    function toStringArr() {
        let result = [];

        this.lines.forEach(function(line) {
            result.push(line.toString());
        });

        return result;
    }
}
function Line (maxLen){
    this.words = [];
    this.spaces = [];   //
    this.size = 0;   // Initial size of array
    this.maxLen = maxLen;

    function add(word) {
        if(this.canAddWord(word)) {
            this.words.push(word);
            this.size += word.length;
            return true;
        } else {
            return false;
        }
    }

    function toString() {
        let result = [];
        this.words.forEach(function(word, i) {
            result.push(word + " ".repeat(this.spaces[i]));
        }, this);

        return result.join("");
    }

    function justify(isLastLine) {
        let spacesCount = this.words.length - 1;
        let extraSpaces = this.maxLen - this.size;

        let quotient = extraSpaces / spacesCount;
        let mod = extraSpaces % spacesCount;

        if(isLastLine) {
            // Add one space between each word
            for(let i = 0; i < this.words.length - 1; i++) {
                this.spaces[i] = 1;
            }
        } else {
            // Distribute (maxLen - size) in $(spacesCount) evenly
            for(let i = 0; i < this.words.length - 1; i++) {
                this.spaces[i] = quotient + ((mod-- > 0)? 1 : 0);
            }
        }
    }

    function canAddWord(word) {
        return (this.size + (this.words.length - 1) + word.length <= this.maxLen)
    }

    Line.prototype.add=  add;
    Line.prototype.toString = toString;
    Line.prototype.justify = justify;
    Line.prototype.canAddWord = canAddWord;
}


texts: LINQ query that filters elements from a list of object

texts:
I have two lists of objects Person and PersonResult. Both are linked through the property PersonId. I need to create a filter for the list of PersonResult that meet certain criteria for the Person (e.g. Person.Gender == "female").

Im currently using the following LINQ query to achieve this:

PersonResultList = PersonResultList.Where(pr =>
    PersonList.FirstOrDefault(p => pr.PersonId == p.PersonId) != null &&
    PersonList.FirstOrDefault(p => pr.PersonId == p.PersonId).Gender == "female");

This works apparently well, however, I must iterate twice through PersonList to check if the person exist and its gender. Is there a more elegant way to achieve this?


texts:
I need to add search filters for firebase So that I can get search result easily and precisely
I was altering the code from hereThis Medium Post
I would like to optimize this code.
void main() {
  print(setSearchParam("Dr apj abdul Kalam"));
}

setSearchParam(String caseNumber) {
  List<String> caseSearchList = List();
  String temp = "";
  String temp2 = "";
  String temp3 = "";

  if (caseNumber.split(" ").length > 1) {
    String firstWord = caseNumber.split(" ")[0];
    String secondWord = caseNumber.split(" ")[1];
    String thirdWord = caseNumber.split(" ")[2];

    for (int i = 0; i < firstWord.length; i++) {
      temp = temp + firstWord[i];
      caseSearchList.add(temp);
    }
    for (int i = 0; i < secondWord.length; i++) {
      temp2 = temp2 + secondWord[i];
      caseSearchList.add(temp2);
    }
    for (int i = 0; i < thirdWord.length; i++) {
      temp3 = temp3 + thirdWord[i];
      caseSearchList.add(temp3);
    }
  } else {
    for (int i = 0; i < caseNumber.length; i++) {
      temp = temp + caseNumber[i];
      caseSearchList.add(temp);
    }
  }
  return caseSearchList;
}

OutPuts are like List of each word letters = [D, Dr, a, ap, apj, a, ab, abd, abdu, abdul]
I am pushing these lists to firebase so that I can get search results easily...
if there is an alternative for searching in firebase, then pls let me know...
if anyone still didn't understand my question, pls look at the link I provide above.


texts:
I have a makefile like the one below and I am trying to simplify it. I know I should be assigning variables to cut down on repeated things but I am still confused as to how to properly simplify this as small as possible.

    #
# Linux makefile
# Use with make
#

.SUFFIXES:
.SUFFIXES: .o .asm .cpp .c

AS=nasm
ASFLAGS= -f elf
CFLAGS=
CC=gcc
CXX=g++
CXXFLAGS=

.asm.o:
    $(AS) $(ASFLAGS) $*.asm

.cpp.o:
    $(CXX) -c $(CXXFLAGS) $*.cpp

.c.o:
    $(CC) -c $(CFLAGS) $*.c

all: prime math sub1 sub2 sub3 sub4 sub5 sub6 first memex dmaxt asm_io.o fprime quadt test_big_int

prime: driver.o prime.o asm_io.o
    $(CC) $(CFLAGS) -oprime driver.o prime.o asm_io.o

math : driver.o math.o asm_io.o
    $(CC) $(CFLAGS) -omath driver.o math.o asm_io.o

first : driver.o first.o asm_io.o
    $(CC) $(CFLAGS) -ofirst driver.o first.o asm_io.o

sub1 : driver.o sub1.o asm_io.o
    $(CC) $(CFLAGS) -osub1 driver.o sub1.o asm_io.o

sub2 : driver.o sub2.o asm_io.o
    $(CC) $(CFLAGS) -osub2 driver.o sub2.o asm_io.o

sub3 : driver.o sub3.o asm_io.o
    $(CC) $(CFLAGS) -osub3 driver.o sub3.o asm_io.o

sub4 : driver.o sub4.o main4.o asm_io.o
    $(CC) $(CFLAGS) -osub4 driver.o sub4.o main4.o asm_io.o

sub5 : main5.o sub5.o asm_io.o
    $(CC) $(CFLAGS) -osub5 main5.o sub5.o asm_io.o

sub6 : main6.o sub6.o
    $(CC) $(CFLAGS) -osub6 main6.o sub6.o

asm_io.o : asm_io.asm
    $(AS) $(ASFLAGS) -d ELF_TYPE asm_io.asm

array1 : driver.o array1.o array1c.o
    $(CC) $(CFLAGS) -oarray1 array1.o array1c.o asm_io.o

memex : memex.o memory.o
    $(CC) $(CFLAGS) -omemex memex.o memory.o

dmaxt : dmaxt.o dmax.o
    $(CC) $(CFLAGS) -odmaxt dmaxt.o dmax.o

quadt : quadt.o quad.o
    $(CC) $(CFLAGS) -oquadt quadt.o quad.o

readt : readt.o read.o
    $(CC) $(CFLAGS) -oreadt readt.o read.o

fprime : fprime.o prime2.o
    $(CC) $(CFLAGS) -ofprime fprime.o prime2.o

test_big_int : test_big_int.o big_int.o big_math.o
    $(CXX) $(CXXFLAGS) -otest_big_int test_big_int.o big_int.o big_math.o

big_int.o : big_int.hpp

test_big_int.o : big_int.hpp

first.o : asm_io.inc first.asm

sub1.o : asm_io.inc

sub2.o : asm_io.inc

sub3.o : asm_io.inc

sub4.o : asm_io.inc

main4.o : asm_io.inc

driver.o : driver.c

clean :
    rm *.o


texts:
I am trying to solve the Sherlock and The Beast HackerRank challenge. Most tests timeout, however when I try a custom stretch test case (T = 20 and all N = 100000), it returns successfully, so I'm not sure what the problem is.

The idea of the algorithm is that I find the number of possible combinations of threes and fives for a given number of digits, then I treat threes as zeros and fives as ones, in order to process a binary number. So for N = 3 digits, we have 8 combinations (from 7 to 0) which in binary terms is (descending) from 111 to 000, which in three and five terms is from 555 to 333.

public class Solution {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int testCases = in.nextInt();
        for(int i = 0; i < testCases; i++){
            System.out.println( solve( in.nextInt() ) );
        }
    }

    private static String solve(int n){

        long combos = (long)Math.pow(2,n);
        for(long i = combos-1; i>=0; i--){
            String toStr = String.format("%"+n+"s", Long.toBinaryString(i)).replace(' ', '0');

            String modified = toStr.replace("0","3").replace("1","5");
            int threes =0;
            for( int j=0; j<modified.length(); j++ ) {
                if( modified.charAt(j) == '3' ) {
                    threes++;
                }
            }
            if(threes%5==0) {
                int fives =0;
                for( int k=0; k<modified.length(); k++ ) {
                    if( modified.charAt(k) == '5' ) {
                        fives++;
                    }
                }
                if(fives%3==0) return modified;
            }
        }
        return "-1";
    }
}


texts:
I wrote a simple breakout game in javascript. I was wondering if anyone could give me some advice on improving my code. I wrote somethings a bit oddly so I am more then welcome to criticism (constructive would be preferred however.)

let canvas = document.getElementById("mainCanv");
let ctx = canvas.getContext("2d");
let brickLength = 14;
let score = 0;
let paddle = {
 w:80,
 h:15,
 x:180,
 y:canvas.height-40,
}
let ball = {
 w:20,
 h:20,
 x:200,
 y:200,
 speedY:Math.sin(0.6),
 speedX:Math.cos(0.6),
 speed:5
}

let keys = {
 Left:false,
 Right:false
}

let bricks = initBricks(brickLength);

function update(){
 //Draw everything
 ctx.fillStyle = 'black'
 ctx.fillRect(0,0,canvas.width, canvas.height)
 ctx.fillStyle = "green"
 ctx.fillRect(paddle.x, paddle.y, paddle.w, paddle.h)
 ctx.fillStyle = "red"
 ctx.fillRect(ball.x, ball.y, ball.w, ball.h)
 ctx.fillStyle = "white";
 ctx.fillText("Score: " + score, 20,20)
 for(let i = 0; i < brickLength; i++){
  if(bricks[i].showing){
   ctx.fillStyle = "blue";
   ctx.fillRect(bricks[i].x, bricks[i].y, bricks[i].w, bricks[i].h);
   if(ball.y<bricks[i].y+bricks[i].h && ball.y > bricks[i].y-bricks[i].h&& ball.x > bricks[i].x - bricks[i].w && ball.x < bricks[i].x +bricks[i].w){
    bricks[i].showing = false;
    ball.speedY *= 1;
    ball.speedX *= -1;
    score += 10;
   }
  }
 }

 //Do score calculations
 if(score % 13 == 0 && score >= 130){
  bricks = initBricks(brickLength);
  ball.speed += 2;
 }

 //Realtime movement
 if(keys.Right) {
  paddleMove(-5);
 }
 if(keys.Left) {
  paddleMove(5);
 }

 ballMove(ball, 5, 5)

 //Check out of bounds
 if(ball.y>480 || ball.y > paddle.y){
  ball.y = canvas.height/2
  ball.x = canvas.width/2
  ball.speed = 5;
  score = 0;
  bricks = initBricks(brickLength);
 }
}

//Key checking
window.addEventListener("keydown", function(event){
 switch(event.keyCode){
  case 37:
   keys.Right = true;
   keys.Left = false;
   break;
  case 39:
   keys.Right = false;
   keys.Left = true;
   break;
 }

})
window.addEventListener("keyup", function(event){
 if(event.keyCode == 37 || event.keyCode == 39){
  keys.Right = false;
  keys.Left = false;
 }
})

//Movement functions
function paddleMove(dir){
 paddle.x += dir;
 if(paddle.x<0||paddle.x>canvas.width-paddle.w){
  paddle.x -= dir;
 }
}

function ballMove(ball){

 ball.x+=ball.speedX*ball.speed;
 ball.y+=ball.speedY*ball.speed;

 if(ball.y<0 || (ball.y > paddle.y-paddle.h && ball.x < paddle.x+paddle.w && ball.x > paddle.x-paddle.w)){
  ball.speedY *= -1;
 }

 if(ball.x<0||ball.x>480 ){
  ball.speedX *= -1;
 }
}

//Initialise bricks
function initBricks(length){
 let bricks = [length];
 for(let i = 0; i < length; i++){
  bricks.push({
   x:0+i*40,
   y:60,
   w:20,
   h:20,
   showing:true
  })
 }
 return bricks
}

setInterval(update, 1000/60);
<!DOCTYPE html>
<html>
<head>
 <title>Breakout</title>
</head>
<body>
<canvas id="mainCanv" width="500" height="500" style="background-color:black"></canvas>
<script type="text/javascript" src="game.js"></script>
</body>
</html>


texts: Showing events on a multi room scheduler

texts:
I write a web app that shows events on a multi room scheduler. I use VueJS for the first time on a real project.

Here, I loop through the events array every room column (two nested v-for). In jQuery I need to loop once through this array to fill all columns at once.

My question: is there any other more efficient way to write this code that fills rooms divs with events in Vue?

var vm = new Vue({
        el: '#app',
        data: {
            rooms: [
               {id: 1, title: 'Room 1' },
               {id: 2, title: 'Room 2' }
            ],
            events: [
              { id: 1, start: 230, duration: 30, title: 'Event 1', room_id: 2},
              { id: 2, start: 400, duration: 45, title: 'Event 2', room_id: 1}
            ]
        }
    })
.agenda-wrapper { max-width: 100%; overflow-x: scroll; }

  .agenda { padding-top: 50px; overflow: hidden; }

.room {
    width:300px;
    height:1170px;
    padding: 0 10px;
    margin-left: 5px;
    background:#ECECEC;
    position:relative;
    float: left;
}

.room span {
    position: absolute;
    top: -20px;
    height: 10px;
    text-align: center;
    width: 300px;
    font-weight: bold;
}

.event {
    display: block;
    background:#fff;
    color:#4B6EA8;
    border:1px solid #ccc;
    border-left:4px solid #c4183c;
    position:absolute;
    padding:0 10px;
    font-weight:bold;
    font-size:13px;
    border-radius: 5px;
    width: 280px;
}

      {{ room.title }}

{{ event.title }}


texts:
I have the following piece of code. I would like to be able to combine my first big block if statement inside my while loop and clean up my usage of variables since I'm doing a lot of setting.
I've tried to do this to the best of my ability but would like to see a more efficient way.

int i;
int previous;

i = head;
if (data[i].occupied && data[i].pin == pin){
    head = data[i].next;
    data[i].occupied = 0;
    resource -= data[i].ask;
    return(1);
}
previous = i;
i = data[i].next;

while (data[i].occupied){
    if (data[i].pin == pin) {
        data[i].occupied=0;
        data[previous].next = data[i].next;
        if (i == tail) {
            tail = previous;
        }
        resource -= data[i].ask;
        for(int x = 0; x < max; x++) data[x].run = data[x].up = data[x].utilization = 0;
        return(1);
    }
    previous = i;
    i = data[i].next;
}

data is table of data processes. So, in any particular index, I'm checking if it's occupied, what pin it has (which is how I identify who processes it is), next is the pin of the next process and ask is how much processing power that process needs. So basically, this code is how I update the table when a process is ending.


texts:
I am a complete beginner in C and I have started learning it by implementing binary trees. So have implemented a basic k-d-Tree. I provide two structs and two methods for comparing values on different axis.

typedef struct Point2D {
    double x;
    double y;
} Point2D;

int x_comparator(const void *v1, const void *v2) {
    const Point2D *p1 = (Point2D *) v1;
    const Point2D *p2 = (Point2D *) v2;
    if (p1->x < p2->x)
        return -1;
    else if (p1->x > p2->x)
        return +1;
    else
        return 0;
}

int y_comparator(const void *v1, const void *v2) {
    const Point2D *p1 = (Point2D *) v1;
    const Point2D *p2 = (Point2D *) v2;
    if (p1->y < p2->y)
        return -1;
    else if (p1->y > p2->y)
        return +1;
    else
        return 0;
}

#define DIMENSION 2

typedef struct KdNode {
    Point2D *p;
    struct KdNode *left, *right;
    int splittingAxis;
} KdNode;

and my method for building the k-d-Tree :

KdNode* build(Point2D data[], int splittingAxis, int numberElements) {
    KdNode *temp = (KdNode*) malloc(sizeof(KdNode));
    KdNode *left = (KdNode*) malloc(sizeof(KdNode));
    KdNode *right = (KdNode*) malloc(sizeof(KdNode));
    if (temp == NULL || left == NULL || right == NULL) {
        exit(1);
    }
    if (numberElements == 0) {
        return NULL;
    }

    int median, numberElementsLeft, numberElementsRight;
    median = floor(numberElements / 2);
    Point2D leftSide[median], rightSide[numberElements - median - 1];
    splittingAxis = splittingAxis % DIMENSION;

    if (splittingAxis == 0) {
        qsort(data, numberElements, sizeof(Point2D), x_comparator);
    } else {
        qsort(data, numberElements, sizeof(Point2D), y_comparator);
    }

    numberElementsLeft = median;
    numberElementsRight = numberElements - median - 1;

    memcpy(leftSide, data, numberElementsLeft * sizeof(Point2D));
    memcpy(rightSide, &data[numberElements - median],
        numberElementsRight * sizeof(Point2D));

    Point2D *tPoint = (Point2D*) malloc(sizeof(Point2D));

    tPoint->x = data[median].x;
    tPoint->y = data[median].y;
    left = build(leftSide, (splittingAxis + 1) % DIMENSION,numberElementsLeft);
    right = build(rightSide, (splittingAxis + 1) % DIMENSION,
        numberElementsRight);
    temp->p = tPoint;
    temp->left = left;
    temp->right = right;
    temp->splittingAxis = splittingAxis;
    return temp;
}

Is this a correct implementation of a k-d-Tree in C? What would you criticize and how could it be improved?


texts: Displaying an item from an array on page load

texts:
This piece of Angular code is used to add/remove an item to a favourite array and display it on page load. Firstly I check if I have an array and then create one if not. It also checks the localStorage on page load.

How can this be improved?

$scope.favourites = $localStorage.favourites;

$scope.addExerciseToFavourites = function(exercise) {
  if($scope.favourites === undefined) {
    $scope.favourites = [];
    favouriteToggle(exercise)
  } else {
    favouriteToggle(exercise);
  };
};

function favouriteToggle(exercise) {
  if($scope.favourites.indexOf(exercise.exerciseName) == -1) {
      $scope.favourites.push(exercise.exerciseName);
  } else {
      $scope.favourites.splice($scope.favourites.indexOf(exercise.exerciseName),1);
  };
   $localStorage.favourites = $scope.favourites;
};