texts: Python reimplementation of Lost In Space by Tim Hartnell

texts:
In a university library, there was copy of "Making The Most Of Your ZX 81" by Tim Hartnell. I flipped to an interesting page from the index and found this program in BASIC, and thought it interesting enough to rewrite in Python. It's a number guessing game.

from random import random
from sys import exit
print("LOST IN SPACE:\nYou have fifteen hours to find a capsule lost in a SEVEN kilometer cube of space.\n")
def main():
    def winCondition(i):
            print("You found it with {} hours of air left".format(15 - i))
            end()
    def end():
        print("Play again? Y/N")
        response = input()
        if response.lower() == "y":
            game()
        else:
            exit(0)
    def game():
        A = int(7 * random() + 1)
        B = int(7 * random() + 1)
        C = int(7 * random() + 1)
        """
        Ripped from https://stackoverflow.com/questions/57813858/iteratively-assigning-variables-in-python/57813901#57813901
        """
        def get_input(axis):
            while True:
                user_input = input(f"{axis}-Axis: ")
                try:
                    axis_int = int(user_input)
                    assert(axis_int <= 7)
                except:
                    print("Enter a natural number in the range!")
                    continue
                else:
                    break
            return axis_int
        for i in range(15):
            print("Input 3 search coordinates")
            D, E, F = [get_input(axis) for axis in "YXZ"]
            print(str(D) + str(E) + str(F))
            if A == D and B == E and F == C:
                winCondition(i)
            else:
                print("You have {} hours of air left.".format(15 - i))
                if A > D:
                    print("UP")
                elif A < D:
                    print("DOWN")
                if B > E:
                    print("PORT")
                elif B < E:
                    print("STARBOARD")
                if C > F:
                    print("FORWARD")
                elif C < F:
                    print("BACKWARD")
                if i == 14:
                    print("Choose your next move carefully... HYPOXIA IMMINENT.")
        print("Fail, astronaut dead; capsule was at coords {}.{}.{}".format(A, B, C))
        end()
main()

I first of all want to improve concision before anything else.


texts: How to avoid duplication in my document writer?

texts:
I have these two methods which are generating two different xml files whose header section is same and detail section varies. The root node is different for both xml files. Here I have two methods written, one for each. I want to optimize the code by avoiding the duplication of code in these two methods. Can you please guide me achieve this?

private string GenerateType1XML(TypeHeader header, List<TypeDetail> TypeDetailList)
{

    StringBuilder builder = new StringBuilder();
    using (StringWriter stringWriter = new StringWriter(builder))
    {
        using (XmlWriter writer = XmlWriter.Create(stringWriter))
        {
            writer.WriteStartDocument();
            writer.WriteStartElement(xmlElementConfig.CreateType1RootNode);
            WriteTypeHeader(writer, header);
            foreach (TypeDetail typ in TypeDetailList)
            {
                WriteType1Detail(writer, typ);
            }
            writer.WriteEndElement();
            writer.WriteEndDocument();
        }
    }

    return builder.ToString();

}

private string GenerateType2XML(TypeHeader header, List<TypeDetail> TypeDetailList)
{

    StringBuilder builder = new StringBuilder();
    using (StringWriter stringWriter = new StringWriter(builder))
    {
        using (XmlWriter writer = XmlWriter.Create(stringWriter))
        {
            writer.WriteStartDocument();
            writer.WriteStartElement(xmlElementConfig.CreateType2RootNode);
            WriteTypeHeader(writer, header);
            foreach (TypeDetail typ in TypeDetailList)
            {
                WriteType2Detail(writer, typ);
            }
            writer.WriteEndElement();
            writer.WriteEndDocument();
        }
    }

    return builder.ToString();

}


texts: Modelling user preference system with categories

texts:
I am modelling a user preference system with the following requirements

a user can have attributes (foods they eat)
a user can have dynamic categories of preferences
users which have all their categories with at least one intersect can match

So far I have used Postgres's arrays to build a system to avoid joins. NB. I'm not using proper keys at the moment for simplicity.

CREATE TABLE public.users (
    name text,
    food text[]
);

CREATE TABLE public.preferences (
    name text,
    category text,
    food text[]
);

INSERT INTO public.preferences VALUES ('John', 'Breakfast', '{toast,cereal}');
INSERT INTO public.preferences VALUES ('John', 'Dinner', '{ham}');
INSERT INTO public.preferences VALUES ('Jane', 'Breakfast', '{toast,eggs}');
INSERT INTO public.preferences VALUES ('Jack', 'Breakfast', '{grapefruit}');

INSERT INTO public.users VALUES ('John', '{peas,ham,"ice cream",toast}');
INSERT INTO public.users VALUES ('Jane', '{eggs,ham,"ice cream",cereal,toast}');
INSERT INTO public.users VALUES ('Jack', '{toast,cereal,eggs,peas}');

I have a query that seems to work, however was wondering if anyone had any feedback. It works by asserting that there "are not any categories, which don't match".

select * from users u where name <> 'Jane'
and not exists (select from preferences p where name = 'Jane' and not u.food && p.food)
and not exists (select from preferences p where u.name = p.name
                and not (select u.food from users u where u.name = 'Jane') && p.food);

 name |             food
------+------------------------------
 John | {peas,ham,"ice cream",toast}
 (1 row)


texts: Find foreign key membership including owner in SQL Server

texts:
Was hoping someone could sanity-check this SQL statement.  I need to find the owner (schema), table, and column on both sides of a foreign key:

SELECT
    s1.name AS FK_schema,
    o1.name AS FK_table,
    c1.name AS FK_column,
    fk.name AS FK_name,
    s2.name AS PK_schema,
    o2.name AS PK_table,
    c2.name AS PK_column,
    pk.name AS PK_name,
    fk.delete_referential_action_desc AS Delete_Action,
    fk.update_referential_action_desc AS Update_Action
FROM sys.objects o1
    INNER JOIN sys.schemas s1
        ON o1.schema_id = s1.schema_id
    INNER JOIN sys.foreign_keys fk
        ON o1.object_id = fk.parent_object_id
    INNER JOIN sys.foreign_key_columns fkc
        ON fk.object_id = fkc.constraint_object_id
    INNER JOIN sys.columns c1
        ON fkc.parent_object_id = c1.object_id
        AND fkc.parent_column_id = c1.column_id
    INNER JOIN sys.columns c2
        ON fkc.referenced_object_id = c2.object_id
        AND fkc.referenced_column_id = c2.column_id
    INNER JOIN sys.objects o2
        ON fk.referenced_object_id = o2.object_id
    INNER JOIN sys.schemas s2
        ON o2.schema_id = s2.schema_id
    INNER JOIN sys.key_constraints pk
        ON fk.referenced_object_id = pk.parent_object_id
        AND fk.key_index_id = pk.unique_index_id
ORDER BY s1.name, o1.name, s2.name, o2.name, fkc.constraint_column_id


texts: SQL query to obtain totals and subtotals

texts:
The query works fine but I'm just intrigued to know if there is a cleaner solution. The data are results from a survey and I'm obtaining the counts per question within a zone and an overall zone count.

With Cte1 (ZoneId, QuestionId, Count1)
AS
(
    Select
        tz.ZoneId,
        qn.QuestionId,
        Count(1) as Count1
    From
        Customers cust
        Inner Join Shops td on td.ShopCode = cust.ShopCode
        Inner Join Zones tz on tz.Id = td.SlsZone
        Inner Join Responses res on res.SampleId = cust.SampleId
        Inner Join QstNodes qn on qn.QuestionId = res.QstNodeId
    Where
        Event >= 201201 And Event <= 201212
    Group BY
        tz.ZoneId, qn.QuestionId
)
SELECT
    ZoneId,
    QuestionId
    Count1,
    (
        SELECT SUM(Count1)
        FROm Cte1 as innercte
        Where innercte.ZoneId = outercte.ZoneId
    )
    as ZoneTotal
FROM
    Cte1 outercte


texts:
I'm trying to think of a better way to write these routes in my routes.rb file:

Rails.application.routes.draw do
  root 'home#index'

  s = /section1|section2|section3|section4/
  y = /\d{4}/
  m = /\d{1,2}/

  resources :articles, except: [:index, :show]

  # The slug will replace the default params[:id] of the following resources:
  resources :articles, only: [:index, :show], path: '/:section/:year/:month', as: :my_articles, constraints: {:section => s, :year => y, month: m}

  get ':section/:year/:month', to: 'articles#by_month', as: :month, constraints: {section: s, year: y, month: m}
  get ':section/:year', to: 'articles#by_year', as: :year, constraints: {section: s, year: y}
  get ':section', to: 'articles#by_section', as: :section, constraints: {section: s}
end

This enables me to search articles by section, by year+section, by month+section+year. It also lets me add a nice slug to URLs.

One of the problems is that the constraints are common among all these routes. I'm wondering if there's a more clever way to go about writing this. Someone suggested I use concerns but I haven't figured out a way to do that.

Not a game changer, but I'm curious as to how I can write this properly.


texts:
Does this data structure make sense? It's essentially a vector of pointers, intended to point to larger objects. In effect, it gives the benefit of a linked list, with an \$O(1)\$ lookup at the cost of maintaining an array of pointers to each element.

What edge cases am I missing, and what's the formal name of this data structure? (What's the standard data structure used in such situations?)

#include<iostream>
#include<vector>
using namespace std;
template <class T>
class pointerArray
{

    vector<void*> addresses;
    public:
    pointerArray(int initialSize=100)
    {
        addresses.resize(initialSize);
    }
    ~pointerArray()
    {
        for(unsigned int i=0;i<addresses.size();i++)
        {
            if(addresses[i]!=0)
            {
                delete (T*)addresses[i];
            }
        }
    }
    T& operator[](unsigned int pos)
    {
        if(pos >= addresses.capacity())
        {
            addresses.resize(pos*2);
        }
        if(addresses[pos] == 0)
        {
            T* ptr = new T;
            addresses[pos] = ptr;
        }
        return *(T*)(addresses[pos]);

    }
};

int main()
{
    pointerArray<string> pa(100);
    for(int i=0;i<10000;i++)
    {
        pa[i]="Hello World This Is a Very Long String";
    }
    for(int i=0;i<10000;i++)
    {
        cout<<pa[i]<<endl;
    }
}


texts: Generate prime factorisations of factorial numbers

texts:
The code was written to generate the factorisation of numbers into primes in ascending order. E.g 3! ='2 * 3', 4!='2^3 * 3'. When I have huge numbers such as 100!, the run time becomes a problem. I want to have a code which will run in less time.
from math import floor,sqrt,factorial
from decimal import Decimal
def prime(x):
   if x==2 or x==3 or x==5:
      return True
   if (x%2==0) or (x%3==0) or (x%5==0) or (x==1):
     return False
   for i in range(6,floor(sqrt(x)),6):
      if x%(i+1)==0:
         return False
      elif i%(i+5)==0:
         return False
   return True
def decomp(n):
   y=factorial(n)
   if y<7:
      pri =list(filter(prime,range(1,y+1)))
   else:
      pri=list(filter(prime,range(1,floor(Decimal(y).sqrt()+1))))
   a={};b=0
   for i in pri:
      while y%i==0:
         y=y//i
         b+=1
         a[i]=b
         b=0
   if len(list(a.keys()))==1:
      if list(a.values())!=[1]:

         c=str(a.keys())+'^'+str(a.values())
      else:
         c=str(list(a.keys()))
   elif len(list(a.keys()))>1:
      if a[list(a.keys())[0]]>1:
         c=str(list(a.keys())[0])+'^'+str(a[list(a.keys())[0]])

      elif a[list(a.keys())[0]]==1:
         c=str(list(a.keys())[0])
      for key in list(a.keys())[1:]:
         if a[key]!=1:
            c+=' * '+str(key)+'^'+str(a[key])

         elif a[key]==1:
            c+=' * '+str(key)

   return c


texts: Delete all virus-affected files with certain filenames

texts:
Purpose of the code is to delete all virus affected files from your pc.

   private static void SearchAndDeleteFiles(String directoryName, List<File> files) {

        File directory = new File(directoryName);

        File[] fList = directory.listFiles();

        if (fList != null) {

            for (File file : fList) {
                if (file.isFile() && (file.getName().endsWith(".ccc") || file.getName().startsWith("_how_recover_anj")
                        || file.getName().startsWith("_how_recover_jav"))) {
                    files.add(file);
                    System.out.println((new StringBuilder()).append(file).toString());

                    boolean isSuccess = file.delete();

                    System.out.println(
                            (new StringBuilder()).append(file).append(" delete status: ").append(isSuccess).toString());

                } else if (file.isDirectory()) {
                    SearchAndDeleteFiles(file.getAbsolutePath(), files);
                }

            }
        }

    }


texts:
I have written a small Brainfuck interpreter in C. More recent version hosted here.

I have found it very hard to test my interpreter because writing a program in Brainfuck is somewhat hard (or at least very tedious) and many snippets I found online either don't give output or do so very cryptically, so I don't know 100% sure if everything works as intended.

I have tested a few programs on it though, and that which I tested works.

Any criticism/advice would be very nice.

#include <stdio.h>

#define MEMSIZE 30000

int memory[MEMSIZE];
int instructions[MEMSIZE];

int memptr = 0;
int insptr = 0;

int isInstruction(char);
void runInstruction(char);

int main(int argc, char *argv[]) {
    // Open input file
    FILE *file = fopen(argv[1], "r");
    if (file == 0){
        printf("Error: Could not open source file\n");
        return 0;
    }

    // Read all instructions from input
    char c;
    int i = 0;
    int balance = 0; // Keeps track of `[` and `]` balance
    while ((c = fgetc(file)) != EOF && i < MEMSIZE){
        if(isInstruction(c)){
            instructions[i] = c;
            i++;
            if (c == '[')
                balance++;
            if (c == ']')
                balance--;
        }
    }

    // Close input file
    fclose(file);

    // Error if amount of instructions is more than permitted
    if (c != EOF && i >= MEMSIZE){
        printf("Error: cannot read more than 30000 instructions\n");
        return 0;
    }

    // Error if `[` and `]` aren't balanced
    if (balance != 0){
        printf("Error: `[` and `]` were not balanced\n");
        return 0;
    }

    // Run the program
    while(insptr < MEMSIZE && instructions[insptr] != 0){
        runInstruction(instructions[insptr]);
        insptr++;
    }
}

int isInstruction(char c) {
    if(c == '+' || c == '-' || c == '>' || c == '<' || c == '[' || c == ']' ||
       c == '.' || c == ','){
        return 1;
    } else {
        return 0;
    }
}

void runInstruction(char c) {
    switch(c){
    case '+':
        memory[memptr]++;
        break;
    case '-':
        memory[memptr]--;
        break;
    case '>':
        if (memptr < MEMSIZE - 1)
            memptr++;
        else
            memptr = 0;
        break;
    case '<':
        if (memptr > 0)
            memptr--;
        else
            memptr = MEMSIZE - 1;
        break;
    case '[':
        if (memory[memptr] == 0)
            // seek `]` forward
            while(instructions[insptr] != ']'){
                insptr++;
            }
        break;
    case ']':
        if (memory[memptr] != 0)
            // seek `[` backward
            while(instructions[insptr] != '['){
                insptr--;
            }
        break;
    case '.':
        putchar(memory[memptr]);
        break;
    case ',':
        memory[memptr] = getchar();
        break;
    default:
        printf("Error: Encountered unknown instruction `%c`\n",c);
    }
}


texts:
I've been experimenting with how to pass my managed object context throughout my application in Core Data and I came across an approach that I'd like reviewed.

I've been creating a protocol for all of my View Controllers that need a managed object context to implement:

protocol ManagedObjectContextProperty {
    var managedObjectContext: NSManagedObjectContext! { get set }
}

Then I create an extension to that protocol to assert that the context does indeed exist:

extension ManagedObjectContextProperty {
    func checkManagedObjectContext(name: String) {
        if managedObjectContext == nil {
            assertionFailure("\(name) is missing the managed object context.")
        }
    }
}

Finally, I create an extension that fetches my context from the app delegate and add's it to my managedObjectContext variable:

extension UIViewController {
    func getManagedObjectContext<T : UIViewController where T : ManagedObjectContextProperty>(controller: T) {
        var controller = controller
        let appDelegate = UIApplication.shared().delegate as! AppDelegate
        controller.managedObjectContext = appDelegate.managedObjectContext
    }
}

Then in my View Controller I simply do this:

class ViewController: UIViewController, ManagedObjectContextProperty {

    var managedObjectContext: NSManagedObjectContext!

    override func viewDidLoad() {
        getManagedObjectContext(controller: self)
        checkManagedObjectContext(name: "ViewController")
    }
}

Is this approach is against the general convention? If so, why?


texts:
I have this universal error handler for my HomeKit app (currently in development). It grew out of wanting a single place to write error messages, show alerts, etc. I wanted a short, simple way to call it from anywhere that may generate an error.

Here's the class:

import UIKit
import HomeKit

class ESErrorHandler : NSObject
{
    class func handleError(error: NSError) -> Bool
    {
        NSLog("Handling error \(error) in centralized handler")

        let code = HMErrorCode(rawValue: error.code)

        switch code! {
        case HMErrorCode.FireDateInPast:
            showAlertWithTitle("Invalid date", body: "Date must be in the future")
        case HMErrorCode.AccessDenied:
            showAlertWithTitle("Access Denied", body: "You don't have permission to access the specified item")
        ... // A bunch more cases

        default:
            NSLog("Couldn't handle error with code \(error.code)")
            showAlertWithTitle("Error", body: "Couldn't successfully complete action")
            return false
        }

        return true
    }
    class func showAlertWithTitle(title: NSString, body: NSString)
    {
        dispatch_async(dispatch_get_main_queue())
        {
            let alert = UIAlertView(title: title, message: body, delegate: nil, cancelButtonTitle: "OK")
            alert.show()
        }
    }
}

I call it from other code like this:

homeManager.addHomeWithName(currentHouseName) {(home: HMHome!, error: NSError!) in
        if error != nil
        {
            ESErrorHandler.handleError(error)

            self.title = "Add Home"
        }
        else
        {
           ... //Stuff worked, do other stuff
        }
    }

My concerns:

Something feels wrong about putting using a class method for showAlertWithTitle:body:
I don't really like having using switch code!, it seems clumsy like I'm missing something in unwrapping


texts:
Given a string, find the first repeating character in it.

  Examples:

  firstUnique("Vikrant") → None
  firstUnique("VikrantVikrant") → Some(V)

Scala implementation:

object FirstUniqueChar extends App {
  def firstUnique(s: String): Option[Char] = {
   val countMap =  (s groupBy (c=>c)) mapValues(_.length)
    def checkOccurence(s1: String ): Option[Char] = {
      if (countMap(s1.head) > 1) Some(s1.head)
      else if (s1.length == 1) None
      else checkOccurence(s1.tail)
    }
    checkOccurence(s)
  }
  println(firstUnique("abcdebC"))
  println(firstUnique("abcdef"))
}

I also have a followup question. What is the recommended way if I do not want to solve this problem with recursion? Instead of using the checkOccurence method I can traverse through the string and break when I find the first element with a count more than 1. But that will require a break, which is discouraged in Scala.


texts: Resistance is futile, Resistors have been dispatched to model your Resistance

texts:
Since it was getting boring to always do OOP Languages I decided to dabble in the functional realm of programming.

For that I chose the narrowly missed community-challenge by Edward: Resistor Mania, since it really is a quick-to solve using recursive and functional style.

Challenge description:

  In electronics, two resistors in series have a combined resistance
  \$R_1+R_2\$, and two resistors in parallel have combined resistance of
  \$\displaystyle \frac{R_1 R_2}{R_1 + R_2}\$.  Given an infinite supply
  of \$270\Omega\$ resistors with \$5\%\$ tolerance, write a program to
  describe how to combine them into any arbitrary resistance value.

To make things a little easier for me, I decided to ditch the tolerance for this first prototype. Instead of \$270\Omega\$ I also ask the user to provide the values for our resistors.

The code works as expected for rather simple inputs, and I didn't check for more complicated stuff yet.

The ouptut comes as a wiring help that uses simple "equations" to describe parallel and combining wiring.

Output of some manual tests:

*Main> resistor_mania 60 120
"60.0+60.0"
*Main> resistor_mania 120 60
"120.0||(120.0)"
*Main> resistor_mania 120 120
"120.0"

Code:

module Main where

import System.IO

main = do
    hSetBuffering stdin LineBuffering;
    putStrLn "Please enter the value of resistors we use";
    res_input <- getLine;
    putStrLn "Please enter the value you want to model with these resistors";
    target_value <- getLine;
    putStrLn (show (resistor_mania (read res_input) (read target_value)));

{-
Calculate the remaining resistor-strenght necessary to get to a given target
 when going in parallel to the given existing resistor.
-}
p_resistor :: Fractional a => a -> a -> a
p_resistor = (\existing target -> (1 / ((1 / target) - (1 / existing))));

{-
Resistor_Mania: Create a wiring schema for a given target resistor value
with one single available kind of resistor
-}
resistor_mania :: (Show a, Ord a, Fractional a) => a -> a -> String
resistor_mania resistor target =
    if resistor == target;
    then (show resistor);
    else if resistor < target;
    then (show resistor) ++ "+" ++ (resistor_mania resistor (target - resistor));
    else (show resistor) ++ "||(" ++ (resistor_mania resistor (p_resistor resistor target)) ++ ")";

There's quite a few things that I hope can be improved here. For one I don't like how p_resistor is declared as a lambda, and resistor_mania isn't.
Another thing I don't like is the concatenation of Strings in the control structure and the type-signature of resistor_mania makes me uneasy :/


texts:
I have a tsv file containing the mapping for two kinds of identifiers.

accession   accession.version   taxid   gi
V00184      V00184.1            44689   7184
V00185      V00185.1            44689   7186
V00187      V00187.1            44689   7190
X07806      X07806.1            7227    8179

Basically, I want to be able to get the taxid from an accession number. I though I could put this in a database with a PRIMARY KEY on the accession field.

This is what I did and It works but I have around 1.5billion lines and it takes a lot of time to do.

import sqlite3
import time

start = time.time()

connection = sqlite3.connect("test.sqlite")
cursor = connection.cursor()

cursor.execute("""
    CREATE TABLE IF NOT EXISTS map (
        accession TEXT PRIMARY KEY,
        accession_version TEXT,
        taxid TEXT, gi TEXT
    )""")

def read_large_file(f):
    """Generator for the file"""
    for l in f:
        yield l.strip().split()

with open("test_file.map", "r") as f:
    next(f)  # ignore header
    cursor.executemany("INSERT INTO map VALUES (?, ?, ?, ?)", read_large_file(f))

cursor.close()
connection.commit()
connection.close()

print(time.time() - start)

Do you have any tricks or ideas I could use to speed up the insert ? (I will do very basic SELECT on the data using the accession primary key)


texts:
A recent comment to an answer of mine here on Code Review brought up an interesting point.  The comment was that one should use std::vector<char> over std::vector<bool> in most cases because the standard requires std::vector<bool> to actually pack bits.  I replied that for small vector sizes, the speed wouldn't matter much and for large ones, cache locality would give the advantage to bool vectors.

However somewhere in between "small" and "large" is a lot of numbers!  I wanted to do a test to characterize any std::vector<bool> advantage.  The method I used is fairly simple.  I wrote a program that takes 3 arguments:

minsize = the smallest vector size to test
maxsize = the largest vector size to test
steps   = the number of steps between those two

Since I wanted to test a large range quickly, and guessing how the vectors would scale, I chose to step through the range logarithmically.  Using the output from the test, and normalizing the speed advantage of std::vector<bool> over std::vector<char> by subtracting the two times and dividing by the size of the vector yielded this chart on my machine (an older 64-bit Linux machine, using g++ version 5.3.1 for x86_64).

It seems that for a range of sizes in the 2000 to 75000 range, the advantage is with std::vector<char> but for all other ranges, the two were either identical (to the resolution of my timer) or the std::vector<bool> had the advantage.

I'm interested in comments on the code or the test method.

booltest.cpp

#include <iostream>
#include <vector>
#include <cstdlib>
#include <cmath>
#include "stopwatch.h"

template <typename F>
struct testfunc {
    F *fn;
    const char *name;
};

#define TEST(x) { x, #x }
template <typename T>
void vectest(unsigned n)
{
    std::vector<T> arr(n, false);
    unsigned remaining = n;
    static constexpr unsigned incr = 13;

    for (unsigned j = 0; j < incr; ++j) {
        for (unsigned i = j; i < n && remaining; i += incr) {
            if (!arr[i]) {
                arr[i] = true;
                --remaining;
            }
        }
    }
}

#define SHOW(x) std::cerr << #x << " = " << x << "\n"

int main(int argc, char *argv[])
{
    const testfunc<decltype(vectest<bool>)> test[]{
        TEST(vectest<char>),
        TEST(vectest<bool>),
    };

    if (argc < 4) {
        std::cerr << "Usage: booltest minsize maxsize steps\n";
        return 0;
    }

    unsigned min = std::stod(argv[1]);
    unsigned max = std::stod(argv[2]);
    unsigned steps = std::stod(argv[3]);
    double logmin = std::log10(min);
    double logmax = std::log10(max);
    double step = (logmax - logmin)/steps;

    SHOW(min);
    SHOW(max);
    SHOW(steps);

    // print header data
    std::cout << "\"n\"";
    for (const auto t : test) {
        std::cout << ", \"" << t.name << "\"";
    }
    std::cout << "\n";

    for (unsigned i = 0; i < steps; ++i) {
        unsigned val = std::pow(10, logmin + i * step);
        std::cout << val;
        for (const auto t : test) {
            std::cout << ", " << timeit<>(t.fn, val);
        }
        std::cout << std::endl;
    }
}


texts: Checking if a computer is part of a domain

texts:
I am currently using the following code to see if the current machine has joined a domain. I was wondering if there is a more efficient way of doing this. I am currently using the JNA to receive the Secur32 instance variable.

public static String CurrentDomainName() {
        char[] userNameBuf = new char[10000];
        IntByReference size = new IntByReference(userNameBuf.length);
        boolean result = NativeMethods.Secur32.INSTANCE.GetUserNameEx
                (Secur32.EXTENDED_NAME_FORMAT.NameSamCompatible, userNameBuf, size);

        if (!result)
            throw new IllegalStateException("Cannot retrieve name of the currently logged-in user");

        String[] username = new String(userNameBuf, 0, size.getValue()).split("\\\\");
        return username[0];
    }

public static String CurrentMachineName() {
        try {
            java.net.InetAddress localMachine = java.net.InetAddress.getLocalHost();
            return localMachine.getHostName();
        } catch(UnknownHostException e) {
            e.printStackTrace();
        }
        return "Error";
    }

This is the final function that returns the result:

public static Boolean IsDomainJoined() {
        return !Windows.UserInfo.CurrentMachineName().equals(CurrentDomainName());
    }


texts: Breadth First Search to find connected primes

texts:
I've been working through the British Informatic Olympiad's 2016 Paper, and I've been struggling with some of the larger cases for question 3, specifically the larger cases on the mark scheme (the 3 before last specifically).

  Two prime numbers are connected if the difference between them is 2n for some whole number n ≥ 0.
  A path is a sequence of (at least two) prime numbers, without repetition, where adjacent numbers in the sequence are connected. If
  the first number in the sequence is p and the last number is q
  then we say the path is between p and q.
  The length of a path is the total number of prime numbers used. There may be multiple paths between two prime numbers; the lengths of
  these paths may be different.

  Write a program to determine the length of the shortest path between
  two primes. Your program should accept three integers in order: l (4
  ≤ l ≤ 224) indicating the highest value you are allowed to use,
  followed by the primes p then q (2 ≤ p < q < l). You will only
  be given input where there is a path between p and q using values
  below l. You should output the length of the shortest path.

Inputs I was struggling with:

614700 3643 90149 | outputs 18
987654 3643 90149 | outputs 16
1000000 2 968137  | outputs 18

How can I improve its performance?

import math

primes = None
upper_limit = 0
powers_of_two = []

class Node:
    def __init__(self, value, parent):
        self.value = value
        self.parent = parent
    def get_adjacent(self):
        for i in powers_of_two:
            if (self.value + i < upper_limit
            and self.parent != self.value + i
            and self.value + i in primes):
                yield Node(i+self.value, self)
            if (self.value - i >= 2
            and self.parent != self.value - i
            and self.value - i in primes):
                yield Node(self.value - i, self)

def sieve(n):
    numbers = list(range(0, n))
    for prime in numbers:
        if prime < 2:
            continue
        elif prime > n ** 0.5:
            break
        for i in range(prime ** 2, n, prime):
            numbers[i] = 0
    return [x for x in numbers if x > 1]

def bfs(f, to):
    f = Node(f, None)
    q = [f]
    visited = [f.value]
    while len(q) != 0:
        if q[0].value == to:
            return q[0]
        else:
            for x in q[0].get_adjacent():
                #print(q[0].value, x.value)
                if x.value not in visited:
                    #print("added", x.value)
                    visited.append(x.value)
                    q.append(x)
        del q[0]
while True:
    inp = [int(x) for x in input().split(' ')]
    upper_limit = inp[0]
    m = int(math.ceil(math.log2(inp[0]))) if math.log2(inp[0]) % 1 != 0 else int(math.log2(inp[0]))
    for i in range(0, m):
                   powers_of_two.append(2**i)
    primes = sieve(inp[0])
    x = bfs(inp[1], inp[2])
    counter = 0
    while x is not None:
        print(x.value)
        x = x.parent
        counter += 1

    print("--------------------")
    print(counter)


texts: A python default dictionary which seamlessly saves to disk

texts:
I sometimes do experiments at work and separate the computation and the analysis so I can do the computation on a cluster and the analysis locally and sometimes in a Jupyter notebook. I wrote a class which allows me to save results to a hidden file as if it was a dictionary. The idea is to create an object specifying the name of the experiment and from there you can use it as a dictionary, and it is saved to disk so you can access it from other python files. I'd appreciate any thoughts since IO isn't my forte. I used python 2.7 but I think it should work for python 3.0

import os
import cPickle as pickle

class FileDict():

    def __init__(self, name, default = None):
        self.fpath = '.{}.fd'.format(name)
        self.default = default

    def __getitem__(self, key):
        if os.path.isfile(self.fpath):
            d = pickle.load(open(self.fpath))
            if key in d:
                return d[key]
        else:
            return self.default

    def __setitem__(self, key, value):
        if os.path.isfile(self.fpath):
            d = pickle.load(open(self.fpath))
            d[key] = value
        else:
            d = {key : value}
        pickle.dump(d, open(self.fpath, 'w'))

if __name__ == '__main__':
    test = FileDict('test', 0)
    print(test[1])
    test[1] = 'thing'
    print(test[1])
    print(test[2])


texts:
I have several objects which are assigned a certain size and position, works fine. The only problem is that in certain special cases the item has to be positioned a bit to the left and be a bit smaller; I solved this problem as follows:

private void initSprites(){
    sprites = new HashMap<String, Sprite>();
    sprites.put("lock", new Sprite(new Texture(Gdx.files.internal("lock.png"))));
    sprites.put("pauseMenu", new Sprite(new Texture(Gdx.files.internal("pauseMenu.png"))));
    for(int x = 0; x < creators.size(); x++){
        Sprite tmp = new Sprite(new Texture(Gdx.files.internal("sprites/"+creators.get(x)+".png")));
        tmp.setSize(creators.get(x).equals("stick")?10f:20f, 20f);
        sprites.put(creators.get(x), tmp);
    }
}

and

private void addCreator(String name, Stage stage, int location){
    Sprite spr = sprites.get(name);//here
    Box2DObjectCreator act = new Box2DObjectCreator(locations[location]+(name.equals("stick")?4f:0f), items.get(name), spr, stage, definitions.get(name), camera);
    act.setBounds(act.getX(), act.getY(), spr.getWidth(), spr.getHeight());
    creatorObjects.add(act);
    table.addActor(act);
}

The code works obviously but there are going to be a couple of special cases and the only way I can check for those cases is comparing a string which seems a little ugly. Is there a cleaner way to do this besides something like

   private int method(string str)
            return (str.equals("specialCase")?10:20);

or a method that uses switches with all special cases?

That doesn't seem too efficient but seems like my only option if I'm going to have several special cases (which I will, something like 40 normals and 5-10 special cases).


texts: Is this a good way to create an article in HTML5?

texts:
Is this the good way to create a portfolio article in HTML5 or do you have any suggestions?

Not sure about the section but I need it as overlay over the image. Is it better to use a DIV instead?

Ski Trail

       <time datetime="2010-03-20">20th March, 2010</time>

       Graphic


texts: TamperMonkey Script to replace the YouTube favicon with the channel logo

texts:
I felt that having a plain red favicon for every youtube tab is a little boring. So, I wrote a TamperMonkey Script with the new ES6 promises that replaces the favicon with the channel's logo. Link to the script here.

The script works by first extracting the channel logo's URL from the window.ytInitialData object. Then, a mutation listener is attached to the title, and whenever the title of the page changes, the script makes a GET request using the window.location.href and then extracts the logo's URL from the responseText.

Since this is my first time writing a userscript, I wanted to confirm that I am following best practices and not breaking anything on the site. Also, is there a better way of achieving the same result?

Thank you for your time.

My code:

// ==UserScript==
// @name        YouTube Favicon to Channel logo
// @version     1.1
// @description Changes the YouTube Favicon to the Channel logo
// @author      Kartik Soneji
// @updateURL   https://openuserjs.org/meta/KartikSoneji/YouTube_Favicon_to_Channel_logo.meta.js
// @match       https://www.youtube.com/*
// @exclude     https://www.youtube.com/
// @exclude     https://www.youtube.com/tv*
// @exclude     https://www.youtube.com/embed/*
// @exclude     https://www.youtube.com/live_chat*
// @grant       none
// @run-at      document-end
// @license     MIT
// ==/UserScript==

(function(){
    'use strict';

    const urlRegex = /https:\/\/yt3.ggpht.com\/a[/-]{1,2}[A-Za-z\d-_]+/;

    function isInIframe(){
        try{
            return window.self !== window.top;
        }
        catch(e){
            return true;
        }
    }
    if(isInIframe()) return;

    console.log("Started");

    roundImageToDataUrl(JSON.stringify(window.ytInitialData).match(urlRegex)[0]).then(setFavicon);

    function run(){
        getChannelLogo(window.location.href).then(roundImageToDataUrl).then(setFavicon);
    }

    async function getChannelLogo(url){
        return new Promise((resolve, reject) => {
            let xhr = new XMLHttpRequest();
            xhr.open("GET", url);
            xhr.onload = () =>{
                let u = xhr.responseText.match(urlRegex)[0];
                console.log(u);
                resolve(u);
            }
            xhr.send();
        });
    }

    let observer = new MutationObserver(run);

    function registerUrlChangeListener(){
        let e = document.querySelector("title");
        if(e){
            //observer.observe(e, {attributes: true});
            observer.observe(document.querySelector("title"), {attributes: true, characterData: true, childList: true});
            return;
        }

        setTimeout(registerUrlChangeListener, 250);
    }
    registerUrlChangeListener();

    async function roundImageToDataUrl(url){
        return new Promise((resolve, reject) => {
            if(url.src) url = url.src;

            let img = document.createElement("img");
            img.crossOrigin = "anonymous";
            img.src = url;
            img.style = "position: absolute; top: -100000px; left: -100000px;";

            img.onload = function(){
                let canvas = document.createElement("canvas"), g = canvas.getContext("2d");

                canvas.height = img.naturalHeight;
                canvas.width = img.naturalWidth;

                g.beginPath();
                g.arc(canvas.width/2, canvas.height/2, canvas.width/2, 0, Math.PI * 2);
                g.clip();

                g.drawImage(img, 0, 0);

                img.parentElement.removeChild(img);

                resolve(canvas.toDataURL());
            }

            document.body.appendChild(img);
        });
    }

    function setFavicon(url){
        let a = document.querySelectorAll("link[rel *= 'icon']");

        if(a.length == 0){
            let link = document.createElement('link');
            link.type = 'image/x-icon';
            link.rel = 'icon';
            document.head.appendChild(link);
            a = [link];
        }

        for(let i of a) i.href = url;
    }
})();


texts: Integer-to-string conversion using recursion

texts:
Adapt the ideas of printd to write recursive version of itoa; that is, convert integer into a string by calling a recursive routine

Here is the implementation of printd:

void printd(int n) {
    if(n < 0)
        putchar('-');
    if(n / 10)
        printd(n / 10);
    putchar(n % 10 + '0')l
}

And here is my solution:

int itoa(int n, char s[]) {
    int i;

    if(n < 0) {
        n *= -1;
    }

    i = 0;
    if(n / 10) {
        i = itoa(n / 10, s);
    }
    s[i] = n % 10 + '0';
    s[++i] = '\0';

    return i; /* next free slot in array */
}

As you can see, my version of itoa is a little bit different than the one presented in the book. It returns a variable i that represents the index of the next free slot in array, at every step it fills the next empty slot with the null character. At the deepest level of recursion, it returns 1.

Could you review my exercise?


texts: LeetCode 124: Binary Tree Maximum Path Sum 2

texts:
I'm posting my code for a LeetCode problem. If you'd like to review, please do so. Thank you for your time!
Problem
Given a non-empty binary tree, find the maximum path sum.
For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root.
Example 1:
Input: [1,2,3]

       1
      / \
     2   3

Output: 6

Example 2:
Input: [-10,9,20,null,null,15,7]

   -10
   / \
  9  20
    /  \
   15   7

Output: 42

Inputs
[1,2,3]
[-10,9,20,null,null,15,7]
[-10,9,20,null,null,15,7,9,20,null,null,15,7]
[-10,9,20,null,null,15,7,9,20,null,null,15,720,null,null,15,7,9,20,null,null,15,7]
[-10,9,20,null,null,15,7,9,20,null,null,15,720,null,null,15,7,9,20,null,null,15,7999999,20,null,null,15,7,9,20,null,null,15,720,null,null,15,7,9,20,null,null,15,7]

Outputs
6
42
66
791
8001552

Code
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right

class Solution:
    def maxPathSum(self, root: TreeNode) -> int:
        def depth_first_search(node: TreeNode) -> int:
            if not node:
                return 0
            left_sum = depth_first_search(node.left)
            right_sum = depth_first_search(node.right)
            if not left_sum or left_sum < 0:
                left_sum = 0
            if not right_sum or right_sum < 0:
                right_sum = 0
            self.sum = max(self.sum, left_sum + right_sum + node.val)
            return max(left_sum, right_sum) + node.val

        self.sum = float('-inf')
        depth_first_search(root)
        return self.sum

References

Problem

Discuss

Solution


texts: Where to define constants (Bundle Keys) used between 2 Activities?

texts:
public class FirstActivity extends Activity {

    private String userName;
    private Uri userPhoto;

    private void onOkButtonPressed() {
        Intent intent = new Intent(this, SecondActivity.class);
        intent.putExtra(SecondActivity.Key.USER_NAME, userName);
        intent.putExtra(SecondActivity.Key.USER_PHOTO, userPhoto);
        startActivity(intent);
    }

}

public class SecondActivity extends Activity {

    public static class Key {
        public static final String USER_NAME = "USER_NAME";
        public static final String USER_PHOTO = "USER_PHOTO";
    }

    private String userName;
    private Uri userPhoto;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.container);
        init();
    }

    private void init() {
        Intent intent = getIntent();
        userName = intent.getStringExtra(Key.USER_NAME);
        userPhoto = intent.getParcelableExtra(Key.USER_PHOTO);
    }

}

Or maybe it would be better to make the keys private inside SecondActivity and do something like this?

public class SecondActivity extends Activity {

    private static class Key {
        public static final String USER_NAME = "USER_NAME";
        public static final String USER_PHOTO = "USER_PHOTO";
    }

    public static void start(Context context, String userName, Uri userPhoto) {
        Intent intent = prepareIntent(context, userName, userPhoto);
        context.startActivity(intent);
    }

    public static Intent prepareIntent(Context context, String userName, Uri userPhoto) {
        Intent intent = new Intent(context, SecondActivity.class);
        intent.putExtra(Key.USER_NAME, userName);
        intent.putExtra(Key.USER_PHOTO, userPhoto);
        return intent;
    }

    // skipped

}

It slightly improves readability:

SecondActivity.start(this, userName, userPhoto);

But on the other hand, it becomes complicated to make changes. Every time when I want add new fields or change existing fields, I should also change the arguments list in the method start(). And this way is also not suitable in the case when number of the input parameters will increase significantly.


texts:
This is a project I always meant to do, but now that I've done it, I am wondering if/how I can do it better. I've made some fixes and done general testing on the parsing to make sure it works, but I sense there is more to do that could be very instructive to me in terms of organizing my code and thoughts.

This came about because I played several Sokoban games and wrote solutions only to notice that many levels were rotations of others, so I wanted to save time. (There are Sokoban solvers out there, but I wanted to provide explanations with the solutions.)

The code below takes a text file (it need only be one line - the comments provide one) and user-suggested rotations (argument 1 on the command line) and changes all directions(2U, 3L, 4D, 5R) to how the user wants the board rotated.

Some of it seems a bit brute force, though, especially the for loop and the regular expression (I've only recently moved beyond ending with just /g or /gi). In particular, I am wondering whether I should use an array instead, especially since I may want an option to convert the full words "up"/"right"/"left"/"down" to their rotational equivalents.

Any suggestions big or small are appreciated...whether it's technical or code organization.

This seems like the sort of exercise that might help me learn other languages I'm not familiar with, so I wanted to see how things went with a language I was okay at, first.

Thanks to all who are able to contribute, and I hope my example is somewhat interesting.

################################
#sokoban solution rotator
################################
#sok.txt has lines like so: Your way to the end: 2U 4R 3D 5L 2u 4r 3d 5l.
#the command line argument is any combination of l r h u d v (d and v are equivalent to u, vertical flips. L/R rotate left/right, h = horizontal flip)
#

use strict;
use warnings;

my $file = "sok.txt";
my $dir;
my $anyDif; # checks for differences once we've parsed rotations

# this hash transforms a move to a different direction. By default each move points to itself.
my %rotate = ( 'u' => 'u',
  'r' => 'r',
  'd' => 'd',
  'l' => 'l');

if (!defined($ARGV[0]))
{
  die ("You need a command line argument (no spaces) to use rotations: R, L, H and V/U/D rotate right, left, horizontally and vertically.");
}

my @adjust = split(//, lc($ARGV[0]));

for $dir (@adjust)
{
  if ($dir eq 'r') # rotate right
  {
    ($rotate{'r'}, $rotate{'d'}, $rotate{'l'}, $rotate{'u'}) = ($rotate{'u'}, $rotate{'r'}, $rotate{'d'}, $rotate{'l'});
    next;
  };
  if ($dir eq 'l') # rotate left
  {
    ($rotate{'l'}, $rotate{'u'}, $rotate{'r'}, $rotate{'d'}) = ($rotate{'u'}, $rotate{'r'}, $rotate{'d'}, $rotate{'l'});
    next;
  };
  if (($dir eq 'v') || ($dir eq 'u') || ($dir eq 'd')) # vertical flip
  {
    ($rotate{'d'}, $rotate{'r'}, $rotate{'u'}, $rotate{'l'}) = ($rotate{'u'}, $rotate{'r'}, $rotate{'d'}, $rotate{'l'});
    next;
  };
  if ($dir eq 'h') # horizontal flip
  {
    ($rotate{'u'}, $rotate{'l'}, $rotate{'d'}, $rotate{'r'}) = ($rotate{'u'}, $rotate{'r'}, $rotate{'d'}, $rotate{'l'});
    next;
  };
  die ("I didn't recognize $dir. RLHVUD (case insensitive) are the only directions I do.");
}

for $dir (sort keys %rotate)
{
  #print "$dir becomes $rotate{$dir}\n";
  $anyDif += ($dir ne $rotate{$dir});
}

#print "Rotation: URDL => $rotate{'u'}$rotate{'r'}$rotate{'d'}$rotate{'l'}\n";

if (!$anyDif) { die("The rotations you requested don't change the puzzle's orientation."); }

open(A, "sok.txt") || die ("No sok.txt.");

while (my $line = <A>)
{
  print "Orig: $line";
  print "NEW:: ";
  $line =~ s/\b([0-9\*]*)([URDL])\b/$1 . newdir($2)/gei; # I included * with numbers because it means "push to the end"
  chomp($line);
  print "$line\n"; #this is to avoid orig/new appearing on the same line at the end of a file.
}
close(A);

##################################subroutine

sub newdir
{
  if ($_[0] eq lc($_[0]))
  {
    return $rotate{$_[0]};
  }
  return uc($rotate{lc($_[0])});
}


texts: Is the Button, an  element with svg code and hidden link content inside, ARIA conform and well laid out?

texts:
I have an a element for a button. The SVG snippet inside links to the containing SVG file at the top of the body.

   <svg viewBox="0 0 70.115 53.162" class="head__btn">
     <use xlink:href="#skmenu"></use>
   </svg>

When I checked with Codesniffer for WCAG2AA compliance it criticized:

  Anchor element found with a valid href attribute, but no link content
  has been supplied.

So I've added text inside the  element and wrapped it with a span.

Menu Toggle
   <svg viewBox="0 0 70.115 53.162" class="head__btn">
     <use xlink:href="#skmenu"></use>
   </svg>

And hid the text with the following CSS snippet. Without the span, both, the text as well as the SVG would have been hidden.

.srtext {
    position: absolute;
    top: -9999px;
    left: -9999px;
}

Question is, is the solution ARIA as well as browser compliant? Or are there ways to improve the solution (maybe without span)?


texts:
I'm just trying to be more pythonic in my coding style and was wondering if this is a good way to get a list of seven days leading up to and including endDate:

daysDelta   = 6
lastSeven   = [endDate - datetime.timedelta(days=daysDelta)]
for x in range(1,7):
    myOffset    = daysDelta - x
    lastSeven.append(endDate - datetime.timedelta(days=myOffset))


texts: d20pfsrd Discord Bot Scraper Abstraction and Deployment

texts:
I wrote a discord bot that listens for links to the d20pfsrd rulebook in discord chat, checks if they are feats or magic, and then scrapes the page, formats it, and spits it back into chat as formatted text. The pages I'm checking are formulaic enough, so even though the cheerio selectors I'm using are probably fairly brittle, it seems to work in most cases. The text formatters are some ugly beasts though (though the logic is probably unique), and the axios calls could use some cleaning up as well.
My problem is as follows: I suspected a good 40% of the code can be refactored out of existence if I properly generalized it. My solution was to do something that could probably be described as an abuse of the spread operator:
async function getPage(msg, url){
  let message = "placeholder";
  await axios.get(url).then( (response) => {
      message = responder(...selectResponder(url), response);
    }
    ).catch((error) => {
      console.error(error.message);
    });
  sendMessage(message, msg);

}

A week later I'm now realizing I wrote the functions in a way that causes them to read backwards? Aesthetics aside, this is how it ends up working out:
function selectResponder(siteUrl){
  if (siteUrl.startsWith("https://www.d20pfsrd.com/feats/")){
      return feats.featsConfig;
    } else if (siteUrl.startsWith("https://www.d20pfsrd.com/magic/")){
      return magic.magicConfig;
  }
}

function responder(parser, formatter, messageFormatter, response){
    const replyData = parser(response.data);
    const formattedData = formatter(replyData);
    return messageFormatter(formattedData);
}

The idea is that as much unique logic as I could separate out exists in magic.js and feats.js as possible. How can I clean this section up? The github repo is here and I would love and feedback on the entire project. I did most of that because I thought it as weird to have a big if block here and duplicating the axios calls:
client.on('message', msg => {

  if(validateUrl(msg.content)){
    const siteUrl = encodeURI(msg.content);
    getPage(msg, siteUrl);
  }

});

Also I wrote up this gist on how I deployed it to a raspberry pi. That works, so suggestions on how to improve it would be greatly appreciated
In broad strokes this program:

Listens for a message
Validates the message
Gets the page content at the message url
Parses the page content
Re-formats the page content
Converts the page content into a message
Sends the message


texts: Checking whether a directed graph contains a cycle

texts:
I create a myGraph class as shown below.  Then I created an instance of the graph by giving the adjacency list as a NSDictionary and then call the isGraphCycleFree method.  Will this answer look good if asked during an interview programming round?

Initializing the myGraph class and calling the isGraphCycleFree method

NSDictionary *graphAdjacencyList = @{@(0): @[@(1),@(2)],
                                             @(1): @[@(3)],
                                             @(2): @[@(4)],
                                             @(3): @[@(2)],
                                             @(4): @[@(3)]
                                             };
        myGraph *newGraph = [[myGraph alloc] initWithAdjacencyList:graphAdjacencyList];

        if([newGraph isGraphCycleFree])
            NSLog(@"Graph is cycle free");
        else
            NSLog(@"Graph has a cycle");

.h of the myGraph class

@interface myGraph : NSObject

-(instancetype) initWithAdjacencyList:(NSDictionary <NSNumber*,NSArray*>*)adjacencyList;

-(BOOL) isGraphCycleFree;

@end

.m of the myGraph class

@interface myGraph()

@property NSDictionary <NSNumber*,NSArray*>*adjacencyList;

@end

@implementation myGraph

-(instancetype) initWithAdjacencyList:(NSDictionary <NSNumber*,NSArray*>*)adjacencyList
{
    self = [super init];
    if (self) {
        _adjacencyList = adjacencyList;
    }

    return self;
}

    -(BOOL) isGraphCycleFree
    {
        //DO a DFS from any node (pick first node that is a key in adjacency list).
        NSNumber *firstNode = [[self.adjacencyList allKeys] objectAtIndex:0];

        return [self dfsWithStartNode:firstNode withVistedSet:nil];
    }

    -(BOOL) dfsWithStartNode:(NSNumber *)visitedNode withVistedSet:(NSMutableSet *)visitedSet
    {

        if(visitedSet != nil)
        {
            if ([visitedSet containsObject:visitedNode]) {
                return FALSE; //Visiting a node that os alreday in visited set == Cycle
            }
        }
        else
        {
            visitedSet = [[NSMutableSet alloc] init];
        }

        [visitedSet addObject:visitedNode];

        for (NSNumber *nextEdge in self.adjacencyList[visitedNode])
        {
            NSLog(@"from %@ Calling dfs on node %@ with visited list %@",visitedNode,nextEdge,visitedSet);
            if([self dfsWithStartNode:nextEdge withVistedSet:[visitedSet mutableCopy]] == FALSE)
                return FALSE;
        }

        return TRUE;
    }

    @end


texts: Divide-and-conquer approach for finding the closest pair of points

texts:
This is an algorithm for finding the closest pair of points on a 2d plane by dividing the problem by half recursively, as illustrated here:

use point::Point;

type PairDistance = (Point, Point, f64);

// Divide and conquer approach for finding the closest pair of points
// See http://i.imgur.com/bm0vid8.png
pub fn closest_pair(points: &mut Vec<Point>) -> PairDistance {
    fn helper(points: &[Point]) -> PairDistance {
        assert!(points.len() >= 2);
        match points.len() {
            2 => (points[0], points[1], points[0].distance(&points[1])),
            3 => {
                let p0 = points[0];
                let p1 = points[1];
                let p2 = points[2];
                let d01 = p0.distance(&p1);
                let d02 = p0.distance(&p2);
                let d12 = p1.distance(&p2);
                let mut v: Vec<PairDistance> = vec![(p0, p1, d01), (p0, p2, d02), (p1, p2, d12)];
                v.sort_by(|a, b| a.2.partial_cmp(&b.2).unwrap());
                v[0]
            }
            _ => {
                let mid = points.len() / 2;
                let mid_point = points[mid];
                let mid_x = mid_point.x.to_f64();
                let pair1 = helper(&points[0..mid]);
                let pair2 = helper(&points[mid..points.len()]);
                // which is closer, pair1 or pair2?
                let mut v_pair12: Vec<PairDistance> = vec![pair1, pair2];
                v_pair12.sort_by(|a, b| a.2.partial_cmp(&b.2).unwrap());
                let min_pair12 = v_pair12[0];
                let min_d_pair12 = min_pair12.2;
                // filter out all points that are not in the ±d strip
                let points_in_strip: Vec<_> = points.iter()
                    .cloned()
                    .filter(|p| (p.x.to_f64() - mid_x).abs() < min_d_pair12)
                    .collect();
                if points_in_strip.len() >= 2 {
                    let pair_in_strip = helper(points_in_strip.as_slice());
                    if pair_in_strip.2 < min_d_pair12 {
                        pair_in_strip
                    } else {
                        min_pair12
                    }
                } else {
                    min_pair12
                }
            }
        }
    }

    points.sort();
    let res = helper(points.as_slice());
    res
}

#[test]
fn test_closest_pair() {
        let mut v = vec![
        Point::new(-3.0, -1.0),
        Point::new(-2.0, 0.0),
        Point::new(0.0, 0.0),
        Point::new(1.0, 1.0),
        Point::new(3.0, 1.0),
        Point::new(3.0, 2.0),
    ];
    let p = closest_pair(&mut v);
    let p_should_be = (
        Point::new(3.0, 1.0),
        Point::new(3.0, 2.0),
        1.0
    );
    assert_eq!(p, p_should_be);
}

Point can be found in my previous post.

All suggestions are welcome.


texts:
I'm working through Cracking the Coding Interview. The first challenge is to implement an algorithm to determine if a string has all unique characters.

I've gone through several iterations, but here's my "final" solution. I've made several assumptions:

We are considering case-insensitive strings.
We are only considering strings that contain alphabetic characters.
We are only considering ASCII strings.

Here's my algorithm and a quick driver. The logic is simple, but I wanted to explain what's going on for sake of the reader.

/*
Implement an algorithm to determine if a string has all unique characters.
What if you can not use additional data structures?
*/

#include <iostream>
#include <string>

bool is_unique(const std::string& s) {
    // seen is a 32-bit bitset. We have seen no letters yet.
    int seen = 0;
    // for every character in the string
    for(auto c: s) {
        // convert the string to lowercase (assumption 1)
        char lower_c = std::tolower(c);
        // normalize the character (assumptions 2 and 3)
        int offset = lower_c - 'a';
        // shift 1 at most 26 to the left. Fits within 32-bit bitset.
        int shifted = 1 << offset;

        if(!(seen & shifted)) {
            // if we haven't seen it, add it to seen
            seen |= shifted;
        } else {
            // otherwise return false -- we have seen it
            return false;
        }
    }
    // if we haven't returned false after the loop, it must be unique
    return true;
}

int main(int argc, char** argv) {
    std::string s{argv[1]};
    std::cout << "Is " << s << " unique? " << is_unique(s) << '\n';
}

Does anyone have recommendations?


texts: Euler Project 14 Longest Collatz Sequence

texts:
I have been working through the euler project and I have created the following code for Problem 14, which asks which starting number, under 1 million, produces the longest Collatz Sequence chain.

It takes a good minute to process.  Can I make it faster?

class Collatz:

    def __init__(self):
        self.c = 1

    def if_even(self, n):
        return int(n / 2)

    def if_odd(self, n):
        return int(n * 3 + 1)

    def decide(self, n):
        if (n & 1) == 0:
            return self.if_even(n)
        elif (n & 1) == 1:
            return self.if_odd(n)

    def iter_nums(self, n):
        if n == 1:
            return n
        self.c += 1
        n = self.decide(n)
        self.iter_nums(n)

largest = 0

# col = Collatz()
# col.iter_nums(13)

# print(col.c)

for i in range(1000000, -1, -1):
    col = Collatz()
    col.iter_nums(i)
    if col.c > largest:
        largest = i

print(largest)


texts: Waiting for a file to be accessible with Thread.Sleep() and exception catching

texts:
I know I've already asked a similar question, but this feels quite different to me.

The main goal is to wait for a file to be accessible (read: waiting until the file lock releases), since it seems like there's no way to do this built into the .NET framework I've written a quick and dirty function to do this.

The requirements which should be kept in mind with this:

The file shouldn't be locked often. Actually, it should be locked quite rarely (figure how often clients manage to still hit that).
There's no need for a limit, if the file is locked for longer then a second, something is fuc^H^H^Hscrewed up.
It should block the main thread until the file is available.

///<summary>
/// Tries to open the specified file over and over again until it is acessible.
///</summary>
public static FileStream WaitForStream(String filename, FileAccess fileAccess, FileShare, fileShare)
{
    while(true) // Gives me the chills
    {
        try
        {
            return new FileStream(filename, FileMode.OpenOrCreate, fileAccess, fileShare);
        }
        catch (IOException ex)
        {
            Logger.LogError(ex); // Information purposes only
            Threading.Thread.Sleep(250); // Just looks wrong
        }
    }

    return null; // Only to keep the compiler happy.
}

The problems I see myself:

while(true)
Thread.Sleep()
It might loop forever, but as I said, if that happens we need to intervene anyway.

Reimplementing this with a similar solution I already used smells like absolute overkill to me, given that this should be built-in functionality anyway. What stuff didn't I think about?


texts:
Inspired by this question on Stack Overflow, I've attempted to code such animation, mostly to get some more practice with async, promises and Q.js:

(Live demo)

function addOutput(s) {
  $('<div>').text(s).appendTo(wnd);
  //return Q.defer().promise;
  return Q.delay(100).then(function() { return addPrompt(); });
}

function addInput(s) {
  var l = $('.prompt:last');
  return addLettersRecursive(l, s);
}

function addPrompt() {
  var prompt = "kos@codepen % ";
  var l = $('<div>').text(prompt).addClass('prompt').appendTo(wnd);
  return Q.delay(900);
}

function addLettersRecursive(container, s) {
  container.append(s.charAt(0)); // dangerous :(
  var row_complete = Q.defer();
  Q.delay(100).then(function() {
    if (s.length <= 1) {
      Q.delay(300).then(function() {
        row_complete.resolve();
      });
    }
    addLettersRecursive(container, s.substr(1)).then(function() {
      row_complete.resolve();
    })
  });
  return row_complete.promise;
}

// Usage

addPrompt(">>> ")
.then(function() { return addInput("whoami"); })
.then(function() { return addOutput("kos"); })
.then(function() { return addInput("uname -a"); })
.then(function() { return addOutput("Javascript in codepen.io, powered by Q.js"); })
.then(function() { return addInput("raz dwa"); })
.then(function() { return addOutput("zsh: command not found: raz"); })
.then(function() { return addInput("trzy cztery"); })
.then(function() { return addOutput("zsh: command not found: trzy"); })
.done();

I'm not really satisfied by this implementation, though. How can I simplify it? Here are the specific concerns I have:

I implemented addInput in terms of a recursive helper function addLettersRecursive which still is overly complicated according to my gut feeling.
There's this .then(function() { return function_that_returns_promise(args); }); pattern all over, which seems like a very verbose way of chaining behaviour.

What I have tried:

I attempted to unwind the recursion by stacking the promises one on top of another in a loop, which was a bit tricky to implement because of the selective closure involved. There's some improvement but still looks messy:

function addInput(s) {
  var container = $('.prompt:last');
  var d = Q.delay(0);
  for (var i=0; i<s.length; ++i) {
    d = d.then(function(i) { return function() { // pass i by value
      container.append(s.charAt(i));
      return Q.delay(100);
    }}(i));
  }
  return d.then(function() { return Q.delay(300); });
}

I'm not sure if this kind of pattern is typical to promise-driven code, or I'm just doing something sub-optimally. One thing that came to my mind is this substitution:

  /* before */ .then(function() { return addInput("whoami"); })
  /* after  */ .then(addInput.bind(null, "whoami"))

  /* before */ return d.then(function() { return Q.delay(300); });
  /* after  */ return d.then(Q.delay.bind(Q, 300));

Is it a good track?

Generally I haven't seen much "real life" uses of promises yet except the book cases, so if anything else looks out of the ordinary or sub-optimal, please raise it.


texts: Processing array of objects into two strings

texts:
I have an array of Item objects that each have a string particular and a numeric amount.  I want to put all particulars  (separated by newlines) into a single string and the same for all amounts.

Here's what I came up with:

particulars = []
amounts = []

items.each do |item|
  particulars << item.particular
  amounts << item.amount
end

particulars_string = particulars.join("\n")
amounts_string = amounts.join("\n")

So if

item1.particular = "food"
item2.particular = "drink"
item1.amount = 1000
item2.amount = 2000

then running the code above gives

particulars_string # "food\ndrink"
amounts_string # "1000\n2000"

which is correct.  However, I feel that the above code can be done better.  In particular, I want all the code in one loop, not the three (each and two joins) I have now.  What's a better way to do this?


texts:
I created small simple PHP Authentication API. I have a couple of scripts that I use for session, authentication and registration. Since I'm not an experienced backend and PHP developer, I wanted someone more experienced to review my scripts and tell me what I did wrong and what I can improve.

I did not use any framework; this is plain PHP.

User registration:

<?php
require_once '../dbConnect.php';

$object = json_decode(file_get_contents("php://input"), true);

if (isset($object['email']) && isset($object['password']) && isset($object['firstName']) && isset($object['lastName'])) {
    $email = $object['email'];

    $validationQuery="select * from members where email='$email'";
    $result = $mysqli->query($validationQuery) or die($mysqli->error.__LINE__);
    $member = mysqli_fetch_assoc($result);

    if($member) {
        $message = array('message' => 'Member with provided email address already exist, please use other email.');
        http_response_code(406);
        echo json_encode($message);
    } else {
        session_start();
        $firstName = $object['firstName'];
        $lastName = $object['lastName'];
        $password = password_hash($object['password'], PASSWORD_DEFAULT);

        $registrationQuery = "INSERT INTO members
                (firstName, lastName, email, password)
                VALUES
                ('$firstName', '$lastName', '$email', '$password')";

        if ($mysqli->query($registrationQuery) === TRUE) {
            $message = array(
                'message' => 'Registration Successful, you can use your credentials to log in.',
                'memberId' => mysqli_insert_id($mysqli));
            $_SESSION["id"] = $message['memberId'];
            echo json_encode($message);
        }
    }

    $mysqli->close();
} else {
    http_response_code(400);
}
?>

Getting authenticated member from session:

<?php
require_once '../dbConnect.php';
session_start();

$object = json_decode(file_get_contents("php://input"), true);

if (isset($object['email']) && isset($object['password'])) {

    $email = $object['email'];
    $password = $object['password'];
    $query="select * from members where email='$email'";
    $result = $mysqli->query($query) or die($mysqli->error.__LINE__);
    $member = mysqli_fetch_assoc($result);

    if($member) {
        if (password_verify($object['password'], $member['password'])) {
            $message = array('message' => 'Authentication Successful!');
            $_SESSION["id"] = $member['id'];
            echo json_encode($message);
        } else {
            $message = array('message' => 'Wrong Credentials, Authentication failed!');
            session_destroy();
            http_response_code(400);
            echo json_encode($message);
        }
    } else {
        session_destroy();
        http_response_code(406);
    }

    $mysqli->close();
} else {
    session_destroy();
    http_response_code(400);
}
?>

Getting authenticated member from PHP session cookie

<?php
require_once '../dbConnect.php';
session_start();

if (isset($_SESSION["id"])) {
    $memberId = $_SESSION["id"];
    $query="select id, firstName, lastName, email, profileImage from members where id='$memberId'";

    $result = $mysqli->query($query) or die($mysqli->error.__LINE__);
    $member = mysqli_fetch_assoc($result);

    echo $json_response = json_encode($member);

    $mysqli->close();
} else {
    http_response_code(401);
}

?>

Simple logout script:

<?php

session_start();

if (isset($_SESSION["id"])) {
    $message = array('message' => 'Successful log out!');
    session_destroy();
    echo json_encode($message);
} else {
    echo 'You are not logged in!';
    http_response_code(403);
}

?>


texts:
So I've coded a fill in the blanks game but my last procedure, play_game() is far too long.
Trying to figure out how to divide it into two functions:

Initialize
process_answer

import time
from time import sleep

name = raw_input("Hey there, what's your name?") #Basic raw_input
intro = "Welcome to my Udacity, Mad-Libs game " + name #text plus value of "name"

blanks = ["__1__","__2__","__3__", "__4__"]

questions_easy = '''Python is an __1__ oriented __2__ programming language that has become very popular. It was created by __3__ Van Rossum.Python has been used widely, especially for __4__ learning.'''

questions_medium = '''Python has full support for object-__1__ programming including user-defined __2__, inheritance,
 and run-time binding of methods. Python has an extensive standard __3__, which is one of the main reasons for its popularity.
 Python was first created in __4__ 1989'''

questions_hard = '''Python is intended to be a highly readable __1__. It is designed to have an clear visual __2__.
Essencially the first step when creating a new program is creating a "draft" code also called __3__. This will allow you to have a basic idea on how the code
should be structured. When your code is complete and ready to testing for __4__ inputs and outputs.'''

answers_list_easy = ["object", "dynamic", "Guido", "machine"]
answers_list_medium = ["oriented", "classes", "library", "December"]
answers_list_hard = ["language", "layout", "pseudocode", "valid"]

game_data = {
   'easy': {
        'quiz': questions_easy,
        'answers': answers_list_easy,
        'message': "you chose easy, okay"
    },
   'medium': {
        'quiz': questions_medium,
        'answers': answers_list_medium,
        'message': "You chose medium, a fair challenge"
    },
   'hard': {
        'quiz': questions_hard,
        'answers': answers_list_hard,
        'message': "So you're a tough nugget aren't ya!!"
    }
}

def get_level(): #Inputs easy, medium or hard. Output, Relevant questions and answers.
    pick_level = raw_input("Type in your difficulty level. Choose from easy, medium or hard")
    while pick_level not in ["easy", "medium", "hard"]:
        pick_level = raw_input("Invalid input, please try again. Choose from easy, medium or hard")
    print game_data[pick_level]['message']
    return pick_level

def check_answer(user_answer, answers_list, answers_index):
    if user_answer == answers_list[answers_index]:
        return "right_answer"
    return "Wrong"
    pass

def you_lost():
    print "Wawaooohh, you lost..... :("
    time.sleep (3)
def you_win():
    print "We got ourselves a winner!!"
    time.sleep (3)

def play_game():
    level = get_level()
    quiz = game_data[level]['quiz']
    print quiz
    answers_list =  game_data[level]['answers']
    blanks_index = 0
    answers_index = 0
    guesses = 3

    while blanks_index < len(blanks):
        user_answer = raw_input("So what's your answer to question " + blanks[blanks_index] + "? : ")
        if check_answer(user_answer,answers_list,answers_index) == "right_answer":
            print "\n nice job! that is the right answer!\n"
            quiz = quiz.replace(blanks[blanks_index], user_answer.upper())
            blanks_index += 1
            answers_index += 1
            guesses = 3
            print quiz
            if blanks_index == len(blanks):
                return you_win()

        else:
            guesses -= 1
            if guesses == 0:
                return you_lost()
                break
            print "Wrong!! Please try again. you have " + str (guesses) + " guesses left!"

play_game()


texts: Program to print all evironment variables

texts:
I'm learning x86 assembly on Linux and this is the first program I wrote, so I'm looking for all kinds of ways to improve it.

; Build using these commands:
;   nasm -f elf printenv.asm
;   ld -o printenv printenv.o -m elf_i386 -s

section .data
section .bss

section .text

global _start

_start:
  pop ecx                 ; load argument count
  lea esp,[esp+ecx*4+4]   ; move past every argument and null ptr

  PopEnv:
  pop esi                 ; get next env variable
  cmp esi,0               ; null means end
  je Exit                 ; exit if null

  ; calculate length
  mov ecx,0ffffffffh      ; max length
  xor eax,eax             ; search for null byte
  mov edi,esi             ; where to look for
  repne scasb             ; search
  dec edi                 ; edi points one past the null
  mov byte [edi],0ah      ; replace null with EOL
  sub edi,esi             ; length
  mov edx,edi             ; set arg for sys_write
  inc edx                 ; include EOL

  ; print env to console
  mov eax,4               ; sys_write
  mov ebx,1               ; stdout
  mov ecx,esi             ; location
  int 80h                 ; call
  cmp eax,edx             ; check return value
  jb ExitFailure          ; error

  jmp PopEnv              ; get another env

  Exit:
  mov eax,1               ; sys_exit
  mov ebx,0               ; EXIT_SUCCESS
  int 80h                 ; make the call

  ExitFailure:
  mov eax,1               ; sys_exit
  mov ebx,-1              ; EXIT_FAILURE
  int 80h                 ; make the call


texts:
I have a list of tuples which may vary in size quite significantly. Typical number of tuples in the list would be somewhere around 100.000. I am trying to perform a down-selection on these tuples to end up with a more workable amount of them.

Each tuple contains (among other insignificant for this example data) an integer and 3 floats. These are of interest to me (shown bold below, positions 0, 2, 3, 4).

Example:

(100213, 'foo',-23.412, -277.11, 12.567, 12.24, 23.25, 150.14, 'bar', 'foobar')

And the criterion to implement is the following in pseudocode:

Assume tuples i and j:

if i[2] < j[2] and i[3] < j[3] and abs(i[4]) > abs(j[2]) then j leaves the list.

I wrote a couple algorithms for the task, timed them and improved them and finally I arrived here:

def clean3(lst):
    lst = sorted(lst, key=lambda x: abs(x[4]), reverse=True)  # the abs comparison is taken care off.
    remove = set()  # for quicker membership checks
    for i, forces_i in enumerate(lst[:-1]):
        if forces_i not in remove:  # the current entry might have already been removed
            for forces_j in lst[i+1:]:  # forward check only - progressive gains
                if forces_j not in remove: # the current entry might have already been removed
                    if all(forces_i[x] < forces_j[x] for x in range(2, 4)):  # check with `all` now possible
                        remove.add(forces_j)
    return list(set(lst) - remove)

To my eyes, this looks as streamlined as it could be, but:

Can it be further improved, and if yes, how?
Would an entirely different approach be better here?


texts: Counting permutations without repetitions for a number or a string

texts:
Can I make the following code faster with minor modifications? It times out on CodeWars website.

'''
Write a function that takes a number or a string and gives back the number of
permutations without repetitions that can generated using all its element
'''

from itertools import permutations
def perms(object):
    string = str(object)
    perm_set = []
    perm_repeated = permutations(string)
    print(perm_repeated)

    perm_list = [''.join(p) for p in permutations(string)]
    for item in perm_list:
        if item not in perm_set:
            perm_set.append(item)
    return len(perm_set)

#print(perms(737)) == 3


texts: Comparing two Strings which could be null or blank in a Comparator

texts:
I would like a review of how I am comparing two java.util.String in a private method in a java.util.Comparator.  Either of the Strings could be null or blank, and would be "less than" the other String if that other String were not null/blank.

My gut feeling is that this is at the very least inelegant, probably difficult to read, and at worst inefficient if it had to be done millions of times per second.  Oh, and there could even be a flaw in the logic!

Is there a better way to do this?

private Integer compareDateStrings(BeanToDoTask arg0, BeanToDoTask arg1, String strProperty) {

    /* Don't worry too much about this part. */
    String strDate0 = BeanUtils.getProperty(arg0, strProperty); _logger.debug("strDate0 = " + strDate0);
    String strDate1 = BeanUtils.getProperty(arg1, strProperty); _logger.debug("strDate1 = " + strDate1);
    /* If strDate0 is null or blank and strDate1 is not, then strDate1 is greater. */
    if ((strDate0 == null || strDate0.equals(""))) {
        if (strDate1 != null && !strDate1.equals("")) {
            return -1;
        } else {
            /* They both are null or blank! */
            return 0;
        }
    }
    /* We know strDate0 is not null or blank. */
    if (strDate1 == null || strDate1.equals("")) {
        return 1;
    }
    /* At this point neither strDate0 or strDate1 are null or blank, so let's compare them. */
    return strDate0.compareTo(strDate1);
}


texts: Online Principal Component Analysis with spectral bounds

texts:
I have question regarding online PCA implemented in the paper. I am interested in the Algorithm 2. I am not certain if there is a bug in my code can someone confirm if my code is correct?  The algorithm is as follows:

  input: \$X\$,\$\Delta\$
  \$U\leftarrow\$ all zero matrix (dimensions are not given in the paper , 0 rows and 0 columns)
  \$B\leftarrow\$ a covariance sketch
  for \$x_t\in X\$ do
      Add \$x_t\$ to sketch \$B\$
      while \$||(I-U U^{\top})B||^2 \geq \Delta\$
          Add the top left singular vector of \$(I-UU^{\top})B\$ to \$U\$
      yield\$\;y_t=U^{\top}x_t\$ (I think while loop ends before yielding, not mentioned in the paper)
  end for

Following is the R code I wrote:

PCA<-function(X,delta){
    n<-nrow(X)
    d<-ncol(X)
    B<-cov(X)
    Nrow<-nrow(B)
    Ncol<-ncol(B)
    U<-matrix(0,Nrow,Ncol)
    Y<-matrix(0,n,d)
    idx<-0
    for(i in 1:n){
      inc<-X[i,]
        B<-cbind(B,inc)
        Id<-diag(Nrow)
        while(norm((Id-(U%*%t(U)))%*%B,"2")^2 >= delta){
           idx=idx+1
            test<-(Id-(U%*%t(U)))%*%B
            topleft<-as.matrix(eigen(test%*%t(test))$vectors[,1])
            add<-cbind(U,topleft)
            U<-add[,which(!apply(add,2,FUN=function(x){all(x==0)}))]
        }
        y<-matrix(0,1,d)
        if(idx >0){y[1,1:idx]<-t(U)%*%X[i,]}
        Y[i,]<-y
    }
    Y<-Y[,which(!apply(add,2,FUN=function(x){all(x==0)}))]
    return(Y)
}

Then to test what I have done make sense I used Fisher iris data, and I got:

log.ir <- log(iris[, 1:4])
ir.species <- iris[, 5]

ir.pca <- prcomp(log.ir)
ir.pca$rotation #this is the built in r function equivalent output, which is very different then what I get in my understanding I get (ir.pca$x) from the online PCA implementation.

OPCA<-PCA(as.matrix(log.ir),300)#If you change the value 300 to 0.34 say then you will have X1,X2,X3 and X4
rotationOPCA<-data.frame(t(t(OPCA) %*% as.matrix(log.ir) %*% solve(cov(log.ir))))


texts:
As many of you know goto is usually signs of code smell. However I thought this could be an appropriate case, and would like confirmation or criticism.

Unnecessary section such as the called functions were removed. Every non-standard function returns an int as status, 0 is "OK"; except linkedlist_open() which returns a pointer which could be NULL if the system runs out of memory.

packagetarget_close() does implement the necessary NULL checks.

packagetarget *packagetarget_open()
{
    packagetarget *target = (packagetarget*) malloc(sizeof(packagetarget));

    if (!target) return NULL;

    if (packagetarget_setname(target, ""))
        goto disposer;
    if (packagetarget_setsys(target, PACKAGETARGET_SYS))
        goto disposer;
    if (packagetarget_setarch(target, PACKAGETARGET_ARCH))
        goto disposer;
    if (packagetarget_setmin(target, PACKAGETARGET_MIN))
        goto disposer;
    if (packagetarget_setver(target, PACKAGETARGET_VER))
        goto disposer;
    if (packagetarget_setmax(target, PACKAGETARGET_MAX))
        goto disposer;

    linkedlist *comp = linkedlist_open();

    if (!comp) goto disposer;

    target->comp = comp;

    return target;

    disposer:
        packagetarget_close(target);
        return NULL;
}

Each setter function follows a simple pattern. Since each setter is identical, I will only put the code for packagetarget_setname.

int packagetarget_setname(packagetarget *target, char *name)
{
    if (!target) return 1;

    if (!name) return 2;

    target->name = realloc(target->name, strlen(name) * sizeof(char));

    if (!target->name) return 3;

    strcpy(target->name, name);

    return 0;
}

Here is the packagetarget_close function:

void packagetarget_close(packagetarget *target)
{
    if (!target) return;

    if (target->name) free(target->name);
    if (target->sys) free(target->sys);
    if (target->arch) free(target->arch);
    if (target->min) free(target->min);
    if (target->ver) free(target->ver);
    if (target->min) free(target->min);
    if (target->comp) linkedlist_close(target->comp);

    free(target);

    return;
}

linkedlist_open is a similar function to the packagetarget_open.

linkedlist *linkedlist_open()
{
    linkedlist *list = (linkedlist*) malloc(sizeof(linkedlist));

    if (!list) return NULL;

    list->head = NULL;
    list->length = 0;
    list->remhook = NULL;

    return list;
}

The one thing most of these functions is they may fail when the system runs out of memory. So I have implemented checks for each step.


texts:
How can I improve my remove function?  Could someone also give me a solid explanation of the free() function?

Here is my remove function:

void removeData(void *data, struct accList *theList)
{
  if(theList->head == NULL)                  //nothing can be deleted
    return;
  else if(theList->head == theList->tail)          //there is only one element in the    list
  {
    free(theList->head);
    theList->head = theList->tail = NULL;
  }
  else if(data == theList->head->data)           //the node to be deleted is the head
  {
    struct accListNode *temp = theList->head;
    free(theList->head);
    theList->head = temp;
    theList->head->next = temp->next;
  }
  else if(data == theList->tail->data)      //the node to be deleted is the tail
  {
    struct accListNode *cur;
    for(cur = theList->head; cur->next->next != NULL; cur = cur->next);
    theList->tail = cur;
    free(cur->next);
    cur->next = NULL;
  }
  else                                     //the node to be deleted is any other node
  {
    struct accListNode *cur;
    for(cur = theList->head; cur != NULL; cur = cur->next)
    {
      if(cur->data == data)     //this is the node we must delete from theList
      {
        struct accListNode *temp = cur->next->next;
        free(cur->next);
        cur->next = temp;
        break;
      }
    }
  }
}


texts: Find the minimum number of operations to convert 1 into n, and print the sequence of numbers

texts:
Here is my solution for the following task: Given an integer n, print the minimum number of operations needed to obtain the number n starting from the number 1, and the sequence of numbers towards the number n. The allowed operations are: multiply by 2; multiply by 3; add 1:

def min_operations(x, y):
    visited = set()
    sequences = [[x]]

    while True:
        new_sequences = []
        for s in sequences:
            val = s[-1]

            if val == y:
                return s

            val_times_2 = val * 2
            if val_times_2 <= y and val_times_2 not in visited:
                visited.add(val_times_2)
                new_sequences.append(s + [val_times_2])

            val_times_3 = val * 3
            if val_times_3 <= y and val_times_3 not in visited:
                visited.add(val_times_3)
                new_sequences.append(s + [val_times_3])

            val_plus_1 = val + 1
            if val_plus_1 <= y and val_plus_1 not in visited:
                visited.add(val_plus_1)
                new_sequences.append(s + [val_plus_1])

        sequences = new_sequences

if __name__ == '__main__':
    y = int(input())
    mo = min_operations(1, y)
    print(len(mo) - 1)
    print(mo)

Examples:

> 1
0
1

> 5
3
1 2 4 5

> 96234
14
1 2 6 7 21 22 66 198 594 1782 5346 16038 16039 32078 96234

Is there a more efficient and/or maintainable way of doing that? Perhaps usual algorithms for doing this and similar tasks? Is the code alright?


texts: Find minimal number of days to meet all your friends

texts:
I was asked this in an interview yesterday:

You get an array of segments (segment contains 2 numbers, representing days count (say in a month, but could be in a year, etc.): start, end). You need to find the minimum number of days where you can meet as many of your friends.

For example, if you get [2, 5], [4, 8], [6, 10] - then one possible answer would be  4 and 6. If you get [1,10], [2,9], [3,7] one possible answer would be 5, as in day 5 everyone is available and you can meet them all.

My way of solving was to order the segments by start, and then look for the biggest intersection. Though I was told this is not the most optimal solution. So  I wonder - what is the optimal solution (i.e. more efficient)?

Here's my code:

def optimal_dates(segments):
    # sort the segments
    sorted_segments = sorted(segments_list, key=lambda var: var[0])

    # perform actual algorithm
    final_intersections = set()         # stores the final return result
    working_intersection = set()        # stores the working accumulative intersections
    for i in range(len(sorted_segments) - 1):
        seg_b = set(range(sorted_segments[i + 1][0], sorted_segments[i + 1][1] + 1))
        if not working_intersection:
            seg_a = set(range(sorted_segments[i][0], sorted_segments[i][1] + 1))
            working_intersection = seg_a.intersection(seg_b)
            # if empty, seg_a doesn't intersects forward, so add any element from it
            if not working_intersection:
                final_intersections.add(seg_a.pop())
        else:
            temp = working_intersection.intersection(seg_b)
            # if empty, this was end of intersection, so add any element from the previous accumulative intersections
            if not temp:
                final_intersections.add(working_intersection.pop())
            working_intersection = temp

    # add the final element
    if working_intersection:
        final_intersections.add(working_intersection.pop())
    else:
        final_intersections.add(sorted_segments[-1][0])

    return final_intersections


texts: Submitting form using dynamic variable with query

texts:
I have a form that I submit with these variables: category_time, date_month, date_year, and status_time.

Here is an example of different form possibilities:

CATEGORY_TIME     1
DATE_MONTH    Month:
DATE_YEAR     Year:
FIELDNAMES    DATE_MONTH,DATE_YEAR,SUBMIT
STATUS_TIME   Select:
SUBMIT    submit
----------------
CATEGORY_TIME     Choose:
DATE_MONTH    Month:
DATE_YEAR     Year:
FIELDNAMES    DATE_MONTH,DATE_YEAR,SUBMIT
STATUS_TIME   Pending
SUBMIT    submit
----------------
CATEGORY_TIME     Choose:
DATE_MONTH    Month:
DATE_YEAR     2016
FIELDNAMES    DATE_MONTH,DATE_YEAR,SUBMIT
STATUS_TIME   Select:
SUBMIT    submit

After I submit the form depending on the variables it outputs a query. For example, with the first possibility only category_time chose, it will output the second if statement.

From what you can see, there's a lot of ifs statements that will be needed. Is there an easier way to make this work without so many ifs statement and just depending on the variables that are chosen, even if I have to use JavaScript to make it work better?

<cfif  structKeyExists(form, "category_time") ||  structKeyExists(form, "date_month")  || structKeyExists(form, "date_year") || structKeyExists(form, "status_time") >
<cfquery ....>
SELECT  *
    FROM work_timeline
    <cfif  (category_time eq 'ALL' || category_time eq 'Choose:') &&  date_month eq 'Month:' && date_year eq 'Year:' && status_time eq 'Select:' >
        order by year(date_time) desc, month(date_time) desc
    </cfif>

    <cfif  category_time neq 'ALL' && category_time neq 'Choose:' &&  date_month eq 'Month:' && date_year eq 'Year:' && status_time eq 'Select:' >
    where category_time = #category_time#
    </cfif>
    <cfif structKeyExists(form, "category_time") && date_month neq 'Month:' && date_year eq 'Year:' && category_time neq 'Choose:'
        and category_time neq 'ALL' && status eq 'Select:'>
    where category_time = #category_time# and month(date_time)=#date_month#
    </cfif>
    more if's statments .....
</cfquery>
</cfif>


texts:
Mu solution to Leetcode problem Cousins in Binary Tree works, but the code feels bulky. Is there a better way to solve this problem, particularly to use less additional variables? I will appreciate any suggestions on how to improve this code.
Problem:

In a binary tree, the root node is at depth 0, and children of each depth k node are at depth k+1.
Two nodes of a binary tree are cousins if they have the same depth, but have different parents.
We are given the root of a binary tree with unique values, and the values x and y of two different nodes in the tree.
Return true if and only if the nodes corresponding to the values x and y are cousins.

My code:
/**
* Definition for a binary tree node.
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode() : val(0), left(nullptr), right(nullptr) {}
*     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
*     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/

class Solution {
private:
    void is_cousins(TreeNode* root, int to_find, int depth,
        TreeNode* parent, pair<int, TreeNode*>& pair) {

    if (!root)
        return;

    is_cousins(root->left, to_find, depth + 1, root, pair);
    is_cousins(root->right, to_find, depth + 1, root, pair);

    if (root->val == to_find) {
        pair.first = depth;
        pair.second = parent;
        return;
    }
}

public:
    bool isCousins(TreeNode* root, int x, int y) {

        pair<int, TreeNode*> pairx = make_pair(0, nullptr);
        pair<int, TreeNode*> pairy = make_pair(0, nullptr);

        is_cousins(root, x, 0, nullptr, pairx);
        is_cousins(root, y, 0, nullptr, pairy);

        if (pairx.first == pairy.first && pairx.second != pairy.second)
            return true;
        return false;
    }
};


texts:
This code is meant to take in a command line argument and output a 'tag cloud'. It's more of an exercise in learning F# for me because this is my first non-tutorial code file. How could this code be improved?

open System.IO
open System
[<EntryPoint>]
let main args =

    let directory = args.[0]

    let fileNames = Directory.EnumerateFiles(directory, "*Tests.cs", SearchOption.AllDirectories) |> Seq.toList

    let allLines = List.collect(fun (x:string) -> System.IO.File.ReadLines(x) |> Seq.toList) fileNames

    let allWords = List.collect(fun (x:string) -> x.Split([|' ';'_';';';':';'(';')';'\\';'/';'>';'<';'{';'}';'0';'1';'2';'3';'4';'5';'6';'7';'8';'9';'.'|], StringSplitOptions.RemoveEmptyEntries) |> Seq.toList) allLines
    //printfn "%A" allWords

    let countOccurance (word:string) list =
        let count = List.filter (fun x -> word.Equals(x)) list
        (word, count.Length)

    let distinctWords = allWords |> Seq.distinct |> Seq.toList

    let print (tup:string*int) =
        match tup with
        | (a,b) -> printfn "%A: %A" a b

    let rec wordCloud distinct (all:string list) (acc:(string*int) list) =
        match distinct with
        | [] -> acc
        | head :: tail ->
            let accumSoFar = acc @ [(countOccurance head all)]
            wordCloud tail all accumSoFar

    let acc = []
    let cloud = (wordCloud distinctWords allWords acc)

    let rec printTup (tupList:(string*int) list) =
        match tupList with
        | [] -> 0
        | head :: tail ->
            printfn "%A" head
            printTup tail

    printTup cloud

    0


texts: Find the cheapest order placed out of all of the stores visited - follow-up #2

texts:
Made some adjustments to the previous code thanks to the helpful and thoughtful review by @G.Sliepen.

Problem statement: This  program should  ask  for  the  total  number  of  shops  that  will  be  visited.   At  each  shop,  ask  for  the  number of  ingredients  that  need  to  be purchases.   For  each  ingredient,  ask  for  the  price.    Keep  track  of the  total for  the  order  so  that  you  can  write  it  down  before  leaving  the  shop.   This  program should  also  track  with  order  was  the  cheapest  and  which  shop  the  cheapest  order  was  at.

Original code: Find the cheapest order placed out of all of the stores visited

1st adjustments to the original code: Adjustments based on reviews #1; Find the cheapest order placed out of all of the stores visited

Any  and all hints, tips, tricks, advice, suggestions are greatly appreciated!

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

int read_positive_int(const char* prompt)
{
   printf("%s", prompt);

    int n;
    while (true)
    {
        if (scanf("%d", &n) != 1)
        {
            fprintf(stderr, "Invalid input!\n");
            return 1;
        }
    return n;
    }
}

float read_real_positive(const char* prompt)
{
    printf("%s", prompt);

    float m;
    while (true)
    {
        if (scanf("%f", &m) != 1)
        {
            fprintf(stderr, "Invalid input!\n");
            return 1;
        }
    return m;
    }
}
int main(void)
{
    int num_shops = read_positive_int("How many shops will be visited? ");

    float total_cost[num_shops];

    float cheapest_order;
    int cheapest_shop = 1;

    for (int i = 0; i < num_shops; i++)
    {
        printf("You are at shop #%d.\n", i+1);
        int num_ingredients = read_positive_int("How many ingredients are needed? ");

        float cost_ingredient[num_ingredients];

        total_cost[i] = 0;

        for (int j = 0; j < num_ingredients; j++)
        {
            printf("What is the cost of ingredient #%d", j+1);
            cost_ingredient[j]= read_real_positive("? ");
            total_cost[i] += cost_ingredient[j];
        }
        printf("The total cost at shop #%d is $%.2f.\n", i+1, total_cost[i]);

        if (i == num_shops - 1)
        {
            cheapest_order = total_cost[0];

            for (int k = 1; k < num_shops; k++)
            {
                if (total_cost[k] < cheapest_order)
                {
                    cheapest_order = total_cost[k];
                    cheapest_shop = k + 1;
                }
            }
        }
    }
    printf("The cheapest  order  was  at  shop #%d, and the total cost of the order was $%0.2f\n", cheapest_shop, cheapest_order);
    return 0;
}![enter image description here](https://i.stack.imgur.com/GcAtS.jpg)


texts:
I use this method to extract table name and field name from formula.

public List<string> ExtractFieldsFromFormula(string formula)
{
    List<string> formulas = new List<string>();
    formulas.AddRange(formula.Split(new char[] {'{', '}'}).Where(f=>!f.Contains("+") && !f.Contains("-")&&!f.Contains("/")&&!f.Contains("*")&& !f.Contains("(")&& !f.Contains(")") && f.Trim()!=String.Empty));
    return formulas;
}

my formula is like this:

  "{City.a}+5*(2/{City.b})"

and result of method is a list :

City.a
City.b

how can i write this code better than this?!!