interface design for allowing custom parameter struct, falling back on defaults Right now I have an awkward setup, but don't really know what the cleaner solution would look like. The parameter struct is defining the action keys for a simple fly camera. Right now it looks like this:

struct FlyCameraKeyParams {
    virtual int flyForwardKey() const = 0;
    virtual int flyBackwardKey() const = 0;
    // ... and others ...
};

struct FlyCameraDefaultKeyParams : public FlyCameraKeyParams {
    virtual int flyForwardKey() const override { return 'W'; }
    virtual int flyBackwardKey() const override { return 'S'; }
    // ...
};

The question is how to most conveniently allow this to be specified. I don't think it makes much sense to allow switching the control keys mid execution, so I'm leaning toward a template. But that feels unnecessary. Currently, though, I have this ridiculous pointer bool approach:

class FlyCamera {
public:
    FlyCamera(/* position, gaze, etc params */,
              FlyCameraKeyParams *keyParams = nullptr,
              bool deleteKeyParams = true) {
        if (!keyParams) {
            mKeyParams = new FlyCameraDefaultKeyParams();
            mDeleteKeyParams = true;
        }
        else {
            mDeleteKeyParams = deleteKeyParams;
        }
    }

    virtual ~FlyCamera() {
        if (mKeyParams && mDeleteKeyParams) delete mKeyParams;
    }

protected:
    FlyCameraKeyParams *mKeyParams = nullptr;
    bool mDeleteKeyParams = true;
};

In theory the user could just issue a new CustomKeyParams() in the construction of the FlyCamera and forget about it, and if they really need to own the memory then they could by setting the boolean at the end to false. But there's no reason for this, so should I just do:

template <class KeyParams = FlyCameraDefaultKeyParams>
class FlyCamera {
public:
    static_assert(std::is_base_of<FlyCameraKeyParams, KeyParams>::value,
                  "Template parameter KeyParams must inherit from FlyCameraKeyParams");

    FlyCamera(/* no key params arg here */) {
        mKeyParams = new KeyParams();
    }

    virtual ~FlyCamera() {
        if (mKeyParams) delete mKeyParams;
    }

protected:
    FlyCameraKeyParams *mKeyParams = nullptr;
};

I want to allow users to e.g. implement using the actual arrow keys if they don't want to use WASD. Are there any cleaner alternatives that come to mind?

It sounds like your primary problem right now is memory management — you're worried about how to use dynamic memory allocation without leaks or double-frees. C++ has a solution for that!

class FlyCamera {
public:
    FlyCamera(/* position, gaze, etc params */,
              std::unique_ptr<FlyCameraKeyParams> keyParams = nullptr) {
        if (keyParams == nullptr) {
            keyParams = std::make_unique<FlyCameraDefaultKeyParams>();
        }
        mKeyParams = std::move(keyParams);  // take ownership
    }

private:
    std::unique_ptr<FlyCameraKeyParams> mKeyParams = nullptr;
};

The destructor of unique_ptr<T> takes care of calling delete on the owned pointer (which will call the proper derived-class destructor as long as you've made the base-class destructor virtual).

However, for this particular problem, I don't see why you want a whole polymorphic class for FlyCameraKeyParams. Have you considered flattening things out into a more "C-like" style?

The name of the class should tip you off: I understand a desire for generic KeyBindings or something; but if your FlyCameraKeyParams are literally nothing more than Params to the FlyCamera, then you should make them params to the FlyCamera. Parameterizing the behavior of a concrete class is generally done by setting member variables.

Bonus: FlyCameraDefaultKeyParams describes the defaults of the key params of FlyCamera. So with C++11 member-variable-default-initializer syntax, we flatten that class away as well.

class FlyCamera {
public:
    FlyCamera(/* position, gaze, etc params */) { ... }

    void setFlyForwardKey(int k) { mFlyForwardKey = k; }
    void setFlyBackwardKey(int k) { mFlyBackwardKey = k; }

private:
    int mFlyForwardKey = 'W'; // Self-documenting defaults!
    int mFlyBackwardKey = 'S';
    // ...
};

Notice in passing that I removed your virtual destructor from FlyCamera and made the protected members private, just to discourage people from inheriting from it. If you really need to allow inheritance, go ahead and put the virtual stuff back.


Oracle trigger to keep a copy of deleted records in another table I am using this trigger to keep a copy of the deleted record from table Orders_Details in table Orders_Details_Deleted.

I am using this trigger for two reasons:

security, in case the record is accidentally deleted
to keep a history of deleted records by the user

Is there any better way?

CREATE OR REPLACE TRIGGER TRG_Record_Deleted
   BEFORE DELETE
   ON Orders_Details
   FOR EACH ROW
BEGIN
   INSERT INTO Orders_Details_Deleted
      SELECT *
        FROM Orders_Details
       WHERE Orders_Details.Order_ID = Orders_Details.Order_ID;
END;

I am using this trigger to keep a copy of the deleted record from table Orders_Details in table Orders_Details_Deleted.

No, you're not. The code copies all rows from orders_details to order_details_deleted every time the trigger is run.

  Is there any better way [than using a trigger] ?

Yes, there is a better way. Don't reinvent database features but use native functionality instead. Have a look for the following Oracle features:

Flashback Data Archive

  A Flashback Data Archive provides the ability to track and store transactional changes to a table over its lifetime. A Flashback Data Archive is useful for compliance with record stage policies and audit reports.

Auditing

  Auditing is the ability to track changes that users make in the database.

Workspace Manager

  Keep a history of changes to data

  You can navigate workspaces and row versions to view the database as of a particular milestone or point in time. You can roll back changes to a row or table in a workspace to a milestone. A typical example might be a land information management application where Workspace Manager supports regulatory requirements by maintaining a history of all changes to land parcels.


Facility to run code explicitly implemented in a base class that does not follow CA1033 Sometimes when working with components created by a library vendor such as DevExpress you want to extend the components. Good vendors will leave plenty of virtual methods for you to put to use, but once in a while you need to hook into an interface method call in a class that implements the method explicitly. You can simply reimplement the interface method, but nine times out of ten you will still want to call the base implementation as though it were virtual. As a matter of fact, it should have been virtual (CA1033).

In the meantime, the base implementation is private and you need to use reflection. This class mitigates some of that nuisance so that you don't have to hand-roll reflection code. It hands you an object implementing the interface that calls directly into the private base implementation methods.

An example is worth a thousand explanations:

interface IExampleInterface
{
    string InterfaceMethod();
}

class BaseClass : IExampleInterface
{
    // The authors of BaseClass did not follow CA1033: Interface methods should be callable by child types
    string IExampleInterface.InterfaceMethod()
    {
        return "BaseClass implementation";
    }
}

sealed class CustomizedClass : BaseClass, IExampleInterface
{
    // We have no choice but to override by implementing the method.
    string IExampleInterface.InterfaceMethod()
    {
        // Now in order to access the base explicit implementation, we use the class below:
        return LanguageUtils.ExplicitImplementation<BaseClass, IExampleInterface>(this).InterfaceMethod() + " has been customized.";
    }
}

Surprisingly, there's barely any code:

public static class LanguageUtils
{
    public static TInterface ExplicitImplementation<TBase, TInterface>(TBase @this)
        where TBase : TInterface
        where TInterface : class
    {
        return (TInterface)new ExplicitImplementationProxy(typeof(TBase), @this).GetTransparentProxy();
    }

    private sealed class ExplicitImplementationProxy : RealProxy, IRemotingTypeInfo
    {
        private readonly Type baseType;
        private readonly object instance;

        public ExplicitImplementationProxy(Type baseType, object instance) : base(typeof(MarshalByRefObject))
        {
            this.baseType = baseType;
            this.instance = instance;
        }

        public bool CanCastTo(Type fromType, object o)
        {
            return fromType.IsInterface && fromType.IsAssignableFrom(baseType);
        }

        public string TypeName { get; set; }

        public override IMessage Invoke(IMessage msg)
        {
            var methodCall = msg as IMethodCallMessage;
            if (methodCall == null) throw new NotSupportedException();

            var map = baseType.GetInterfaceMap(methodCall.MethodBase.DeclaringType);
            var args = new object[methodCall.Args.Length];
            Array.Copy(methodCall.Args, args, args.Length);
            return new ReturnMessage(map.TargetMethods[Array.IndexOf(map.InterfaceMethods, (MethodInfo)methodCall.MethodBase)].Invoke(instance, args), args, args.Length, methodCall.LogicalCallContext, methodCall);
        }
    }
}

This is a pretty tidy implementation, not much to say here. A couple very minors:

This is a bit hard to read:

return new ReturnMessage(.Invoke(instance, args), args, args.Length, methodCall.LogicalCallContext, methodCall);

I'd split it up:

var targetMethod = map.TargetMethods[Array.IndexOf(map.InterfaceMethods, (MethodInfo)methodCall.MethodBase)];
return new ReturnMessage(targetMethod.Invoke(instance, args), args, args.Length, methodCall.LogicalCallContext, methodCall);

Clone the argument array instead of explicitly copying it:

var args = (object[])methodCall.Args.Clone();

Expresses the semantics on a more compact way.
For me this seems to be some sort of method forwarding so I'd possibly consider renaming it and maybe turning it into an extension method (I like the syntactic sugar of it). Something along these lines:

public static TInterface ForwardToBase<TBase, TInterface>(this TBase @this)
    where TBase : TInterface
    where TInterface : class
{
    return (TInterface)new ExplicitImplementationProxy(typeof(TBase), @this).GetTransparentProxy();
}

In which case the call would then read as:

this.ForwardToBase<BaseClass, IExampleInterface>().InterfaceMethod()


Change a string into a function/def activator import random

import string

# every def from 'def nothing()' to 'def wxyz()' Print out several lines of text, printing: keyword 1, call number, phone number and keyword 2
def nothing():
    print("keyword: (nothing)\ncalls: 1\n" + str(random_number()) + "\nkeyword: exit\n")

def abc():
    print("keyword: abc\ncalls: 1\n" + str(random_number()) + "\nkeyword: exit\n")

def deft():
    print("keyword: deft\ncalls: 1\n" + str(random_number()) + "\nkeyword: exit\n")

def ghi():
    print("keyword: ghi\ncalls: 1\n" + str(random_number()) + "\nkeyword: exit\n")

def jkl():
    print("keyword: jkl\ncalls: 1\n" + str(random_number()) + "\nkeyword: exit\n")

def mno():
    print("keyword: mno\ncalls: 1\n" + str(random_number()) + "\nkeyword: exit\n")

def pqrs():
    print("keyword: pqrs\ncalls: 1\n" + str(random_number()) + "\nkeyword: exit\n")

def tuv():
    print("keyword: tuv\ncalls: 1\n" + str(random_number()) + "\nkeyword: exit\n")

def wxyz():
    print("keyword: wxyz\ncalls: 1\n" + str(random_number()) + "\nkeyword: exit\n")

# keywords that are accepted and not denied
accepted_keywords = {
    0: nothing,
    1: abc,
    2: deft,
    3: ghi,
    4: jkl,
    5: mno,
    6: pqrs,
    7: tuv,
    8: wxyz
}

# creates a random phone number
def random_number():
    string = []
    x = 0
    while x != 10:
        x += 1
        number = str(random.randrange(0, 10))
        string.append(number)
    return str('(' + string[0] + string[1] + string[2] + ')' + string[3] + string[4] + string[5] + '-' + string[6] + string[7] + string[8] + string[9])

# these two things pick a random value & key from the accepted_keywords() dictionary then calls that value & key
#tester = random.randrange(len(accepted_keywords))
#accepted_keywords[tester]()

# randomizes letter so it can be aproved or denied
def random_keyword():
    keyword = ''
    chrt_count = random.choice([3,4])
    for i in range(chrt_count):
        lowercase = string.ascii_lowercase #lowercase letters
        random_letter = random.randrange(len(lowercase)) # chooses random character from var lowercase which is converted to a number based on its place in alphabet
        keyword_letter = lowercase[random_letter] # grabs the letter from lower using the number from var random_letter to located the place value of a letter
        keyword += keyword_letter
    while True:
        if keyword in accepted_keywords.values():
            print("keyword: " + keyword + "\n*Approved*\n")
            break
        else:
            print("keyword: " + keyword + "\nDenied\n")
            break

random_keyword()

Here is the scenario, I am using python 3.x and I am supposed use cases but since Python does not use cases, I had to use a dictionary.
My problem is that I have a function named wxyz() and I created another function named random_keyword that picks random letters from the alphabet, one at a time, and adds it into a variable named keyword that is a blank string. So by the time random_keyword has ran its course, keyword will have 3 or 4 random letters in it. For now let’s say that those random letters are “wxyz”, which is a string. Then I go through if keyword in accepted_key: print .... The problem is that keyword is a string, therefore it does not match the wxyz in accepted_keywords. Is there a way to turn a string into a function/def activator?

There are quite a lot of things you should do differently.

Let's start with your function random_number. You should not overwrite the string module (even though it is only locally), which you imported. You should also use list comprehensions to build the string. To pretty print the number as a phone number, use str.format. Use the fact that random.randrange takes an implicit 0 as its first argument (just like range). And finally use tuple unpacking, instead of manually indexing the list.

def random_number():
    phone_number = [random.randrange(10) for _ in range(10)]
    return "({}{}{}){}{}{}-{}{}{}".format(*phone_number)

Next, your random_keyword function. You can vastly simplify the building of random_letter by using a list comprehension again, together with str.join, to avoid costly string addition.

Your while True loop also serves no purpose, since you break it in either case.

Also, what is the point of storing something in a dictionary (with \$\mathcal{O}(1)\$ lookup time if a key is in it) and then checking to see if something is in the values, which is a list and takes therefore \$\mathcal{O}(n)\$? At this point your dictionary is just a simple list. You can access its members with numbers from 0 to len(accepted_keywords). Instead have a list of your functions and have a dictionary with their names as keys (which you can build using a dictionary comprehension).

functions = [nothing, abc, deft, ghi, jkl, mno, pqrs, tuv, wxyz]
accepted_keywords = {f.__name__: f for f in functions}

def random_keyword():
    keyword = ''.join(random.choice(string.ascii_lowercase)
                      for _ in range(random.choice([3, 4])))
    print("keyword: {}".format(keyword))
    print("*Approved*\n" if keyword in accepted_keywords else "Denied\n")

Finally, Python has an official style-guide, PEP8. It recommends using ALL_CAPS for global constants (like accepted_keywords).

Python also has a docstring convention (written down in PEP257), which in its simplest form looks something like the following:

def random_number():
    """creates a random phone number"""
    ...

At this point you should also notice that that function name is not very descriptive, maybe something like random_phone_number instead?


Calculate future date based on business days (using Objects) I realize there is already a review about this here, but it's using strings and stuff rather than date objects.

I'm trying to make a simple function to calculate days from a point in time and return object(s). The days have to follow an ignore list (like weekends and holidays) to calculate a range of days, then consider itself landing on any of those ignore days/dates in the end range, then compensate to skoot the final range if needed.

After trial and error with different methods of doing this (++ iterations mostly), I settled on this function. It seems too heavy though considering (mostly) all it's doing is skipping certain ISO day numbers to do some adds.

Are there some PHP date hidden secrets that I am missing? Or a way to boil this down? It seems like a feature such as this (skipping day codes) would be baked into PHP DatePeriod() or DateInterval() but sadly it's not. How would you approach this, pref without counters/strtotime stuff, and pref without extra classes or libs?

<?php

function getWorkingDaysFrom($from, $amtOfDays) {
    $globalDays = 0; // a global addition to $amtOfDays (such as a minimum shipping time of 3 days across all objects)
    $amtOfDays = $amtOfDays + $globalDays; // set base amount of days for initial range before calculations applied
    $ignore = array('6', '7'); // days of the week to ignore (weekends are 6 & 7) in ISO-8061
    $holidays = array('*-06-13', '*-11-23', '*-12-25', '*-01-01', '*-02-29'); // holiday dates (holidays are ignored if they fall into ignore list)
    $oneDay = new DateInterval('P1D');
    $from = new DateTime($from);
    $to = new DateTime();
    $to->add(new DateInterval('P' . $amtOfDays . 'D'));

    foreach(new DatePeriod($from, $oneDay, $to) as $day) {
        if (in_array($day->format('N'), $ignore)) {
            $to->modify('+1 day');
        } elseif (in_array($day->format('*-m-d'), $holidays)) {
            $to->modify('+1 day');
        }
        while (in_array($to->format('N'), $ignore) || (!in_array($to->format('N'), $ignore) && in_array($to->format('*-m-d'), $holidays))) {
            $to->modify('+1 day');
        }
    }
    return $to;
}

getWorkingDaysFrom('now', 20);

?>

Thanks for your time and insights.

First of all, you can get away from having to deal with weekends altogether by using:

$to->modify('+1 weekday');

I think using the above and due to the nature of your function just needing to count X number of "valid" days from  given day, that you are kind of wasting your time using DatePeriod and DateInterval (both classes that usually I am a big proponent for their use).

Here this can be as simple as the following code:

function addWorkingDays(DateTime $from, $dayCount)
{
    $datetime = clone $from;
    while($dayCount > 0) {
        $datetime->modify('+1 weekday');
        if(!isHoliday($datetime)) {
            $dayCount--;
        }
    }
    return $datetime;
}

function isHoliday(DateTime $datetime)
{
    // holiday calculation logic here
    // return boolean
}

Note a few things here:

Here I require the caller to pass a valid DateTime object for $from.  Your current function just kind of assumes $from is valid value from which a DateTime object can be instantiated.  I would go ahead and remove all uncertainty from the function and require a DateTime object to operate against. In your usage example, it would be just as easy to pass new DateTime('now') to the function.
I have defined a separate function isHoliday() where one could define their holiday determination logic.  This also gives possible re-use outside the context of this function.  I wasn't quite sold on your holiday logic. I would think it would be rather trivial to actually get better data structure here to look up against (why the *- part?  that is not necessary to simply compare month and day)  Should you be using holiday dates as key in array instead of value to allow for direct lookup, vs. iterating array using in_array()? I did not specify an implementation of this function, as really, you might want to build a more robust listing of holidays well out into the future if you have any variable date holidays.
I renamed the function to perhaps better indicate what it is doing - adding working days to a given date, not getting the number of working days in some interval.


Printing an arrow of asterisks in Haskell This code will print an arrow of asterisks, like:

*
**
***
****
***
**
*

raisingAsterisks, decreasingAsterisks, arrow :: Int -> [String]
raisingAsterisks n = take n $ iterate ('*' :) "*"
decreasingAsterisks = reverse . raisingAsterisks
arrow n = raisingAsterisks n ++ (tail (decreasingAsterisks n))

main :: IO()
main = mapM_ putStrLn $ arrow 4

The way you're actually generating the list of Strings seems fine, but the formatting, at least in my opinion, can be improved: since raisingAsterisks and decreasingAsterisks are both relatively small "helper" functions for arrow, I would suggest putting them inside a where clause to make things a little easier to read.

arrow :: Int -> [String]
arrow n = increasing ++ tail decreasing
    where increasing = take n $ iterate ('*' :) "*"
          decreasing = reverse increasing

In this context, the variable names could be shortened, due to the fact that it's easy to understand what's happening. Note that the n variable no longer needs to be passed, so increasing and decreasing actually are no longer even functions!

I hope you agree that changing your code just a little greatly improves readability.


Splitting multiple strings I'm sure there's a better way to approach the following. I'm writing a plugin where users can enter settings in the following format:

Setting: "object1setting -> object2setting"

It's done this way to allow for multiple objects to be passed within the same JS call. I'm breaking the the strings apart at the "->" symbol and saving them, however there are many settings and I'm thinking there has to be a more efficient way of writing this:

// START PLUGIN, SETUP DEFAULT OPTIONS, EXTEND OPTIONS TO "O" .....
// I'VE JUST PULLED SOME RANDOM SETTINGS AS AN EXAMPLE.

bg_x_speed_in_set = o.bg_x_speed_in.toString().split("->"), // X PROPERTY SPEED IN
bg_x_speed_out_set = o.bg_x_speed_out.toString().split("->"), // X PROPERTY SPEED OUT
bg_y_speed_out_set = o.bg_y_speed_out.toString().split("->"), // Y PROPERTY SPEED OUT

...
// ETC

This continues on and gets lengthy. Everything works perfectly in all browsers. I'm just trying to clean up the code.

I think you can use object literals. The user of your plugin can pass in an array of object literals:

var settings = [
    {bg_x_speed_in: ..., bg_x_speed_out_set : ...}
    , {bg_x_speed_in: ..., bg_y_speed_out_set : ....}
    , {bg_x_speed_in: ..., bg_x_speed_out_set : ....}
];

In your code, loop through the array; each element contains the settings for one object.


Adding and subtracting Matrices based on condition procedure E(n, m: integer; A, B: tMatrix; var C: tMatrix);
var i, j: integer;
begin
  for i:=1 to n do
    for j:=1 to m do begin
      if i<=j then C[i,j]:=A[i,j] + B[i,j] else C[i,j]:=A[i,j] - B[i,j];
    end;
end;

Input: three matrix. Output: new matrix which created by addition or subtraction of two elements of two matrix depending on conditions

You are only using single-letter variable names. While this is quite understandable for A, B and C, I don't recommend it for n and m.

The big problem about n and m (and i and j) is that it is hard to tell what is the row and what is the column. (The thing I hate the most about mathematics is the undescriptive variable names, it is not something I'd personally recommend carrying over to the programming side of things)

Speaking of names, your method is named E. That really doesn't say anything whatsoever.

I believe it's convention in Delphi to use an uppercase letter for the T prefix, so that would be TMatrix.

I'd use slightly more spacing in the code, and I'd also use a begin also for the outer for-loop.

This line:

if i<=j then C[i,j]:=A[i,j] + B[i,j] else C[i,j]:=A[i,j] - B[i,j];

is, except for the short and confusing variable names, not that bad really. I think it boils down to opinions how to write it 'the best'. An alternative to what you are doing is to use a addValue variable:

procedure ConditionallyAdd(rows, cols: Integer; A, B: TMatrix; var C: TMatrix);
var
  row, col: Integer;
  addValue: Real; // or Integer? or something. The type that your matrix uses
begin
  for row := 1 to rows do begin
    for col := 1 to cols do begin
      if row <= col then addValue = B[row, col];
      else addValue = -B[row, col];
      C[row, col] := addValue;
    end;
  end;
end;

There is essentially a lot of different ways to write this. Use the way you like the best.

I suspect that the integer values passed to the procedure always match the size of the matrices, in that case, use rows and cols as properties of the matrices if possible.


Loop through database and run shell commands with Python and exiftool Briefly, I'm looking at getting the code below to execute faster. I have 100k images to go through. I'm running a query against MySQL, looping through results and then running exiftool against an image, then moving it.

I started running it and it quickly became evident it wouldn't be a quick thing :-(

import mysql.connector
import os

cnx = mysql.connector.connect(user='root',database='database', password='password')
cursor = cnx.cursor()

query = ("SELECT post_title,Event,File,Name from a order by File")

cursor.execute(query)

def shellquote(s):
    return s.replace("'", "")

for (post_title, Event,File,Name) in cursor:
    olddir = r'/home/alan/Downloads/OLD/'
    newdir = r'/home/alan/Downloads/NEW/' + post_title

    oldfile = olddir + File
    newfile = newdir + "/"+File

    if not os.path.exists(newfile):
        os.makedirs(newfile)
    if os.path.isfile(oldfile):
        print " > PROCESSING: " + oldfile
        os.system("exiftool -q "+shellquote(oldfile)+" -xmp:title='"+shellquote(post_title)+"'")
        os.system("exiftool -q "+shellquote(oldfile)+" -xmp:description='"+shellquote(Name)+" courtesy of https://www.festivalflyer.com'")
        os.system("exiftool -q "+shellquote(oldfile)+" -description='"+shellquote(Name)+" courtesy of https://www.festivalflyer.com'")
        os.rename(oldfile, newfile)
cursor.close()
cnx.close()

I tried using subprocess but for whatever reason, I didn't get it to run. Any advice is welcome.

I suppose I could move the 3 lines of exiftool commands to just one and pass multiple arguments. I also saw -stay_open as an option to exiftool but not sure how to apply it

Close your connection to your database, even if there's an error. Use a try-finally to do this.
Make some functions, moving the database stuff into it's own function makes it much easier to read.
From os.system docs:

  The subprocess module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using this function. See the Replacing Older Functions with the subprocess Module section in the subprocess documentation for some helpful recipes.

You may want to use os.path for various file related things, such as os.path.join to join path sections.
print is slow. Try removing it for a massive speed up.

And so you may want to start changing your code to look like:

import mysql.connector
import os
import subprocess

def read_database():
    cnx = mysql.connector.connect(user='root', database='database', password='password')
    cursor = cnx.cursor()
    try:
        query = ("SELECT post_title,Event,File,Name from a order by File")
        cursor.execute(query)
        for item in cursor:
            yield item
    finally:
        cursor.close()
        cnx.close()

def main():
    path = os.path
    old_dir = r'/home/alan/Downloads/OLD/'
    new_dir = r'/home/alan/Downloads/NEW/'
    for (post_title, event, file_name, name) in read_database():
        old_file = path.join(old_dir, file_name)
        new_file = path.join(new_dir, post_title, file_name)
        if not path.exists(new_file):
            os.makedirs(new_file)
        if path.isfile(old_file):
            subprocess.call(["exiftool", "-q", old_file, "-xmp:title='" + post_title.replace("'", "") + "'"])
            subprocess.call(["exiftool", "-q", old_file, "-xmp:description='" + name.replace("'", "") + " courtesy of https://www.festivalflyer.com'"])
            subprocess.call(["exiftool", "-q", old_file, "-description='" + name.replace("'", "") + " courtesy of https://www.festivalflyer.com'"])
            os.rename(old_file, new_file)

if __name__ == '__main__':
    main()


Organizing matches between sports teams How could I improve this algorithm? The goal is to organize matches between sport teams such that:

Each team affront each other
A minimum number of team should start a match after just finishing one

The interesting part is here:

myPerm [] _ = [[]]
myPerm xs threshold = [x:ys | x <- xs,
                    ys <- take nbToKeep $
                            filter
                              (\ts -> price ts <= threshold)
                              (myPerm (delete x xs) threshold)]

It is a way to remove from the enumeration of permutations all sub-sequences not being good enough. Even with this, the problem for 6 teams is very long to resolve.

Here is the complete program:

import System.Environment
import Data.Ord
import Data.List

-- The number of items we keeps to only search
-- from bests local results
nbToKeep :: Int
nbToKeep = 10

type Match = (Int,Int)
type MatchSequence = [Match]

-- Give all sport matches in the form
-- (1,2) => match between Team 1 and Team 2
all_matches :: Int -> MatchSequence
all_matches n = [ (x,y) | x <- [1..n], y <- [1..n], x < y ]

-- A price function for sequence of matches
-- 0 if no team make a match just after finishing one
-- Possible with 5 teams not for 3 and 4
price :: MatchSequence -> Int
price ((x,y):((z,t):rest))
    | x==z = 1 + price ((z,t):rest)
    | x==t = 1 + price ((z,t):rest)
    | y==z = 1 + price ((z,t):rest)
    | y==t = 1 + price ((z,t):rest)
    | otherwise = price ((z,t):rest)
price _ = 0

-- Simple adjoin the price to a MatchSequence
addPrices :: MatchSequence -> (Int,MatchSequence)
addPrices xs = (price xs, xs)

-- Instead of listing _all_ permutations
-- Just keep the one such that its subsequece price
-- is under the threshold
myPerm [] _ = [[]]
myPerm xs threshold = [x:ys | x <- xs,
                    ys <- take nbToKeep $
                            filter
                              (\ts -> price ts <= threshold)
                              (myPerm (delete x xs) threshold)]

-- Keep the best one under some threshold
find_best_under n threshold = take nbToKeep $
                                sortBy (comparing fst) $
                                    map addPrices ( myPerm (all_matches n) threshold)

isNonEmpty [] = False
isNonEmpty _ = True

-- Try to test with the minimal threshold (0)
-- Then repeat until a solution is found for some threshold
find_best n = head $ filter isNonEmpty $ map (find_best_under n) [0..]

showMatchSequence :: MatchSequence -> String
showMatchSequence [] = []
showMatchSequence ((team1,team2):[]) = show team1 ++ "-" ++ show team2
showMatchSequence ((team1,team2):xs) = show team1 ++ "-" ++ show team2 ++ "   " ++ showMatchSequence xs

showResult :: (Int,MatchSequence) -> String
showResult (score,xs) = show score ++ " collisions: " ++ showMatchSequence xs

main = do
    args <- getArgs
    mapM_ (putStrLn . showResult) $ find_best (read (head args)::Int)

I know I do a linear number of computation using price, while, I shouldn't need it if I integrate the price computation inside the myPerm function.

I take all advice, concerning not only style but also sytactic optimisations. For example, I am pretty sure I could have used a Monad to find the first n for which there is a solution.

No algorithmic improvement, just some cosmetics...

import System.Environment
import Data.Ord
import Data.List

-- The number of items we keeps to only search
-- from bests local results
nbToKeep :: Int
nbToKeep = 10

type Match = (Int,Int)
type MatchSequence = [Match]

-- gives a different order, but I think this is okay
all_matches :: Int -> MatchSequence
all_matches n = [ (x,y) | y <- [2..n], x <- [1..(y-1)]]

-- A price function for sequence of matches
-- 0 if no team make a match just after finishing one
-- Possible with 5 teams not for 3 and 4
price :: MatchSequence -> Int
price xs =  sum $ zipWith comp xs $ tail xs where
   comp (x,y) (z,t) = fromEnum $ x==z || x==t || y==z || y==t

-- Simple adjoin the price to a MatchSequence
addPrices :: MatchSequence -> (Int,MatchSequence)
addPrices xs = (price xs, xs)

-- Instead of listing _all_ permutations
-- Just keep the one such that its subsequece price
-- is under the threshold
myPerm [] _ = [[]]
myPerm xs threshold = [x:ys | x <- xs,
                    ys <- take nbToKeep $
                            filter
                              ((<= threshold).price)
                              (myPerm (delete x xs) threshold)]

-- Keep the best one under some threshold
find_best_under n threshold = take nbToKeep $
                                sortBy (comparing fst) $
                                    map addPrices ( myPerm (all_matches n) threshold)

-- Try to test with the minimal threshold (0)
-- Then repeat until a solution is found for some threshold
find_best n = head $ filter (not.null) $ map (find_best_under n) [0..]

showMatchSequence :: MatchSequence -> String
showMatchSequence [] = []
showMatchSequence ((team1,team2):[]) = show team1 ++ "-" ++ show team2 --is this case needed?
showMatchSequence ((team1,team2):xs) = show team1 ++ "-" ++ show team2 ++ "   " ++ showMatchSequence xs

showResult :: (Int,MatchSequence) -> String
showResult (score,xs) = show score ++ " collisions: " ++ showMatchSequence xs

main = do
    args <- getArgs
    mapM_ (putStrLn . showResult) $ find_best (read (head args)::Int)


Python Word definition practice I've written this script to practice (not necessarily memorize, but familiarize myself with) the definitions of a lot of words.

import csv
import random

WORDS = 5    # Number of words
CHOICES = ["A", "B", "C", "D", "E"]    # Number and labelling of choices

with open("wordlist.csv") as csvfile:
    wordreader = csv.reader(csvfile)
    wordlist = [row for row in wordreader]
    words = [pair[0] for pair in wordlist]
    definitions = [pair[1] for pair in wordlist]

score = 0

count = 1
while count <= WORDS:
    print("\nQuestion", str(count))
    randomnumber = random.randint(0, len(words)-1)
    print("Word:", words[randomnumber])

    correct_answer = definitions[randomnumber]
    answers = []
    answers.append(correct_answer)
    for i in range(len(CHOICES)-1):
        randomanswer = random.randint(0, len(words)-1)
        if definitions[randomanswer] in answers:
            randomanswer -= 1
        answers.append(definitions[randomanswer])
    answers.sort()
    correct_index = answers.index(correct_answer)

    for i in range(len(CHOICES)):
        print(CHOICES[i] + ": " + answers[i])

    userinput = input("Answer: ")
    if userinput[0].upper() in CHOICES:
        userindex = CHOICES.index(userinput)
        if userindex == correct_index:
            score += 1
            print("Correct")
    else:
        print("Wrong: " + correct_answer)

    count += 1

print(str(score) + "/" + str(WORDS))

Sample output:

Python 3.4.5 (default, Jul 03 2016, 13:55:08) [GCC] on linux-027e.site, Standard
>>>
Question 1
Word: accentuate
A: Adapt
B: Forgiveness of their sins
C: Stress
D: Superintendent of a monastery
E: Unreasonable
Answer: C
Correct

Question 2
Word: ackja
A: Sami sledge
B: Singing without instruments
C: Speech problems
D: Superintendent of a monastery
E: Unreasonable
Answer: A
Correct

Question 3
Word: a cappella
A: Adapt
B: Adapt
C: Appropriate
D: Forgiveness of their sins
E: Singing without instruments
Answer: E
Correct

Question 4
Word: adequate
A: Adapt
B: Appropriate
C: Forgiveness of their sins
D: Intangible
E: Sami sledge
Answer: B
Correct

Question 5
Word: ackja
A: Adapt
B: Forgiveness of their sins
C: Sami sledge
D: Speech problems
E: Stress
Answer: C
Correct
5/5

Note that there shouldn't be duplicate questions, it's just more likely with a short wordlist like the one at the end of this post and the current implementation. Also, the same definitions shouldn't appear twice in the same question (like in Question 3) My solution to that seems to work most of the time, it's unclear to me why it doesn't work for Question 3 above.

There are a number of things that I'm wondering about:

Use of random.sample to choose words and answers, it doesn't
seem like this will make the code any shorter or concise.
I'm not quite satisfied with the code for choosing the random answers, it seems to be too complicated, as well as the code for checking the user answer. Is there an easier way to verify that the chosen letter is the one that stands for the correct definition?
How could I eliminate the chance of the same word being asked twice in one run of the script?

Here is a sample wordlist.csv, where I've translated 10 of the ca. 3500 original entries:

a cappella,Singing without instruments
absurd,Unreasonable
abbot,Superintendent of a monastery
accentuate,Stress
Aphasia,Speech problems
ackja,Sami sledge
abstrakt,Intangible
absolution,Forgiveness of their sins
adequate,Appropriate
accommodate,Adapt

In python it is usually frowned upon iterating with:

l = [1, 2, 3]
for i in range(len(l)):
    print l[i]

and it is preferred to iterate over the iterable directly:

l = [1, 2, 3]
for x in l:
    print x

Similarly, it is a lot easier to use random.sample (or random.choice if you don't care if a word is asked multiple times) to choose a random word to test now.

Also, it is easier to leave the word and its definition bundled in a tuple, because most of the time you need both of them.

Your choices included sometimes multiple times the same words, because you check only once whether the random answer is already included (if it is, you choose randint - 1, which might also already be included). You should keep on polling until you find a word not included in answers yet (This assumes your dictionary to have more words than CHOICES).

Similar for your user choice. It is nicer (to the user) to keep on asking for an answer until he answers with a possible choice.

I made you enumeration of the choices to be numbers rather than letters because it makes it easier to validate the correct answer.

You should in general use python's str.format methods rather then string addition. It is usually faster and also more readable (and extendable, you can add text justification, padding, etc).

I also added random.shuffle(answers) instead of answer.sort() just so it does not get too boring.

Final code:

import csv
import random

WORDS = 5    # Number of words
CHOICES = 5    # Number of choices

with open("wordlist.csv") as csvfile:
    words = list(csv.reader(csvfile))

score = 0
count = 1

while count <= WORDS:
    print("\nQuestion {}".format(count))
    word, correct_answer = random.choice(words)
    print("Word: {}".format(word))

    answers = [correct_answer]
    while len(answers) < CHOICES:
        _, random_answer = random.choice(words)
        if random_answer not in answers:
            answers.append(random_answer)
    random.shuffle(answers)
    correct_index = answers.index(correct_answer) + 1

    for choice, answer in enumerate(answers, start=1):
        print("{}: {}".format(choice, answer))

    userinput = 0
    while not 0 < userinput <= CHOICES:
        try:
            userinput = int(input("Answer: "))
        except ValueError:
            continue
    if userinput == correct_index:
        score += 1
        print("Correct")
    else:
        print("Wrong: {}".format(correct_answer))
    count += 1

print("{}/{}".format(score, WORDS))


jQuery dynamic toggle class function I wrote this function that will toggle a class of a targeted element. Applying the class js_class_toggle to any element will trigger the function when clicking on it.

To define what the target element is and the class you want to toggle is, you have to add data-class-toggle="target_element_id.className" to the element. You can also add this to any element on the page and it will work the same since its targeting the element by its id.

For example:

    This element will have a class toggled

JS:

$(document).on("click", ".js_class_toggle", function(e){

    //Set variables
    var element = $(e.currentTarget),
        elementsClasses = element.attr('data-class-toggle'),
        elementsClassesSplit = elementsClasses.split('.'),
        targetElement = elementsClassesSplit[0],
        targetClass = elementsClassesSplit[1];

    //Toggle the class
    $("#"+targetElement).toggleClass(targetClass);
});

Here is a working example of it: https://jsfiddle.net/fxo1a5w3/2/

What i will work on next is to be able to have multiple toggles in the same request, for example:

    This element will have its class toggled

But before that i want to know if there is a better way of doing what i have done so far. The goal is for it to be a function that can be used in any project.

You can access the data element via dataset property and camelCase data name

const data = element.dataset.classToggle;

You can add a click event to the document as follows that will only do something if the target is class js_class_toggle

const togClass = `.js_class_toggle`;

addEventListener("click", e => {
    if (e.target.classList.contains(togClass)) {
        /* ...do stuff... */
    }
}

Or you can add a click to each element containing the class.

document.querySelectorAll(togClass).forEach(el => el.addEventListener("click", toggleClick));

By the looks you are toggling the class on the element that is clicked so there is no need to add the reference

    This element will have a class toggled

making the function to toggle very simple

function toggleClick(e) {
     e.target.classList.toggle(e.target.dataset.classToggle);
}

To include the reference id you can make the data JSON like

    This element will have a class toggled

Then the function becomes

function toggleClick(e) {
     const data = JSON.parse(e.target.dataset.classToggle);
     const el = document.querySelector(data.query);
     if (el) { el.classList.toggle(data.toggleClass) }
}


Simplifying an associative array() Would it be better to convert the array in the following code to

$langs = array("en", "de", "fr");

and then reusing the values for both $folder and $flag? If so, how then would my foreach (or maybe a while?) loop be written?

<?php
    $langs = array(
        "en/" => "en.png",
        "de/" => "de.png",
        "fr/" => "fr.png"
    );
    $self    = $_SERVER['REQUEST_URI'];
    $pattern = "{^.*/}i";
    $links   = array();
    foreach ($langs as $folder => $flag) {
        $url  = preg_replace($pattern, "$folder", $self);
        $link = "

";
        array_push($links, $link);
    }
    echo implode($links) . "\n";
?>

I'm trying to "fool proof" the code, by effectively limiting the folder structures and file names that can be used, as I create a basic template of files for quick rolling out of our websites. If you can see any other improvements, that would be much appreciated.

You can definitely simplify this, as the only part of each element of $langs that changes is the two-letter language code. Something like this would work:

<?php
$langs = array(
    "en",
    "de",
    "fr"
);
$self    = $_SERVER['REQUEST_URI'];
$pattern = "{^.*/}i";
$links   = array();
foreach ($langs as $code) {
    $url  = preg_replace($pattern, "$code/", $self);
    $link = "

";
    array_push($links, $link);
}
echo implode($links) . "\n";
?>

You just use a non-associative array and append / or .png where needed; much cleaner.


Ruby Callback System I need a way to store and retrieve callbacks in Ruby, so I made a Callbacks class. Any suggestions would be greatly appreciated.

class Callbacks
  def initialize
    # name: name of callback
    # event: event of which it belongs
    # callback: block to call
    @callbacks = []
  end

  def add name, event, &block
    if block_given?
      @callbacks << {
        name: name,
        event: event,
        callback: block
      }
    end
  end

  def get options={}
    name = options[:name]
    event = options[:event]

    @callbacks.each do |h|
      if name and event
        return h if h[:name] == name and h[:event] == event
      else
        return h if h[:name] == name or h[:event] == event
      end
    end
    nil
  end
end

Why not use a hashmap as the main DS? That way, you optimize for when name and event are defined, and suffer only a constant penalty and degrades to linear for other cases. (In your solution the cost is always linear). (As below)

class Callbacks
  def initialize
    @callbacks = {}
  end

  def add(name, event, &block)
    key = {:name => name, :event => event}
    @callbacks[key] = block if block_given?

shouldn't we throw an exception if block is not given?

  end

  def get(o={})

We can use values_at to extract multiple values from a hash.

    name,event = o.values_at(:name,:event)

We don't need to check if name and event separately because equality checking does it for us.

    return @callbacks[o] if name and event
    @callbacks.each do |k,v|
      return v if k[:name] == name or k[:event] == event
    end
    nil
  end
end

And shouldn't you provide a way to unregister from callback?


Multi-threaded game loop This is a start on a multi-threaded game loop and I just wish to confirm my code is going in the correct direction, and if not, if there is any way it can be improved. I have good experience in game development and C++ in general, but limited experience when it comes to multi-threaded environments.

#include <iostream>
#include <string>
#include <thread>
#include <mutex>
#include <memory>
#include <chrono>

class Test
{
public:
    Test()
    {
        std::cout << "Test starting" << std::endl;
        start();
    }
    ~Test()
    {
        stop();
        std::cout << "Test finished" << std::endl;
    }
    inline void quit()
    {
        running = false;
    }
private:
    void start()
    {
        renderThread = std::unique_ptr<std::thread>(new std::thread(&Test::renderFunc, this));
        updateThread = std::unique_ptr<std::thread>(new std::thread(&Test::updateFunc, this));
        std::cout << "Threads Created" << std::endl;
        running = true;
    }
    void stop()
    {
        renderThread->join();
        updateThread->join();
        std::cout << "Threads joined" << std::endl;
    }

    void updateFunc()
    {
        while(running)
        {
            mutex.lock();
            std::cout << "update" << std::endl;
            mutex.unlock();
        }
    }

    void renderFunc()
    {
        while(running)
        {
            mutex.lock();
            std::cout << "render" << std::endl;
            mutex.unlock();
        }
    }

    volatile bool running;
    std::mutex mutex;
    std::unique_ptr<std::thread> renderThread;
    std::unique_ptr<std::thread> updateThread;
};

int main(int argc, char* argv[])
{
    std::unique_ptr<Test> test = std::unique_ptr<Test>(new Test());

    typedef std::chrono::high_resolution_clock Clock;
    typedef std::chrono::seconds Seconds;

    Clock::time_point t0, t1;
    Seconds seconds;

    t0 = Clock::now();
    do
    {
        t1 = Clock::now();
        seconds = std::chrono::duration_cast<Seconds>(t1 - t0);
    }while(seconds.count() <= 15);

    test->quit();

    return 0;
}

(The timer code is just there for testing the threaded code.)

Yes you have added enough explicit locks to make it safe (under normal situations).

But it is not exception safe and not written in C++ style. You are writing the code as if it was Java (maybe). Which is causing all sorts of problems.

Why do you need the start() and stop() functions? They provide no utility and they initialize members that should be initialized in the constructor. Also the threads are started before the object is fully initialized and thus you have a thread running in a function when the object is not initialized correctly (and thus will probably immediately exit).

    void start()
    {
        // Soon as you create a thread
        // It starts running. So the next thing that is going to be
        // executed is the function `renderFunc()` which also depends
        // on member 'running' which has not been set.
        renderThread = std::unique_ptr<std::thread>(new std::thread(&Test::renderFunc, this));
        updateThread = std::unique_ptr<std::thread>(new std::thread(&Test::updateFunc, this));
        std::cout << "Threads Created" << std::endl;

        // You already have running threads that depend on this variable.
        // Yet this is the first time you even set it. Your code is already
        // broken.
        running = true;
    }

The next thing is the dynamic creation of the thread objects. Why. There is no need to dynamically create them. They should be automatic variables (ie non pointer members). The problem is that you need to be very careful with the initialization order.

class Test
{
    volatile bool running;
    std::mutex    mutex;
    std::thread   renderThread;
    std::thread   updateThread;
  public:
    Test()
        : running(false) // Make sure this is first.
        , renderThread(&Test::renderFunc, this)
        , updateThread(&Test::updateFunc, this)
    {
        std::cout << "Test starting" << std::endl;
    }
    ~Test()
    {
        std::cout << "Test finished" << std::endl;
        updateThread.join();
        renderThread.join();
    }
    inline void quit()
    {
        running = false;
    }

Next thing is your locking and unlocking of the mutex.

    void updateFunc()
    {
        while(running)
        {
            mutex.lock();
            std::cout << "update" << std::endl;
            mutex.unlock();
        }
    }

This is not exception safe. Any situation were you do:

{
    lock(x);
    work();
    unlock(x);
}

Where lock/unlock is a combination that must be called as a pair. Then you should be using RAII. This is where you have an object where lock() is called in the constructor and unlock() is called in the destructor. This also makes the code exception safe because the destructor will always be called even  if their are exceptions.

{
    LockObject  locker(x);  // calls lock(x)
    work();
}                           // destructor of locker will call unlock(x)

For this simple situation there is no need to create your own type. There is one defined in the standard scoped locked.

    void updateFunc()
    {
        while(running)
        {
            std::lock_guard<std::mutex> locker(mutex);
            std::cout << "update" << std::endl;
        }
    }

Stop using dynamic allocation when you do not need it:

    std::unique_ptr<Test> test = std::unique_ptr<Test>(new Test());

    // Just do this:
    Test    test;


MVC OnActionExecuted - session cookie - expire after x minutes of inactivity first time poster here.

I'm creating a session cookie which should expire after 30 minutes of user inactivity. I've added the following code to the base controllers OnActionExecuted method.

protected override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        var sessionCookie = Request.Cookies[COOKIE_VALUE];

        if (sessionCookie == null)
        {
            sessionCookie = new HttpCookie(COOKIE_VALUE)
            {
                Expires = DateTime.Now.AddMinutes(30)
            };

            sessionCookie.Value = Guid.NewGuid().ToString();
        }
        else
        {
            sessionCookie.Expires = DateTime.Now.AddMinutes(30);
        }

        Response.Cookies.Add(sessionCookie);

        base.OnActionExecuted(filterContext);
    }

As this is happening every time a request is made, would this cookie update be noticeable in regards to speed? Any help or suggestions would be greatly appreciated.

The ideal and correct way is to create a class that inherits ActionFlterAttribute and override OnActionExecuting method. Then register it in the GlobalFilters in Global.asax.cs.

Finally do not use Add but use Set method. Why? Below is from MSDN and explains what the difference is:

  The Set method first checks to see if a cookie already exists in the collection and if so updates it. The Set method does not allow duplicate cookies in the cookie collection. To add duplicate cookies in the cookie collection, use the Add method.


A clean and efficient makefile for a simple c program I have an instructor who is very stringent on makefiles only containing rules and dependencies that need to be included.

The structure for the program is very basic.  The requirement is to produce two executable files:  a3b and a3m.  There was some code duplication, so I included that in a source code file called myarray.c (with a header by the same name).

I have already tested the makefile, and everything seems to work.  However, can the makefile be cleaner or more accurate (such as removing or adding rules or dependencies)?

The macro names and values were specified by the instructor.

CFLAGS = -g -Wall - Werror
CC = gcc
LD = gcc
PROG1 = a3b
PROG2 = a3m
PROG3 = myarray
OBJ1 = a3b.o
OBJ2 = a3m.o
OBJ3 = myarray.o

all : $(PROG1) $(PROG2) $(PROG3)

$(PROG1) : $(OBJ1) $(PROG3)
    $(LD) $(OBJ1) $(OBJ3) -o $(PROG1)

$(PROG2): $(OBJ2) $(PROG3)
    $(LD) $(OBJ2) $(OBJ3) -o $(PROG2)

$(PROG3): $(OBJ3) $(PROG3).h
    $(LD) $(PROG3).c -c

clean :
    /bin/rm -f *.o a.out $(PROG1) $(PROG2) $(PROG3)

clean and all are not files should therefore be declared as phony.

.PHONY: clean all
all : $(PROG1) $(PROG2) $(PROG3)
...
clean :
    /bin/rm -f *.o a.out $(PROG1) $(PROG2) $(PROG3)


Loading URLs via a case statement I have the following code which loads in a URL based on the id of a user-clicked button. I'm looking to compress it down as much as possible, and make it more modular and reusable:

function loadDoc(UrlString) {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
      document.getElementById("storybox").innerHTML = xhttp.responseText;
    }
  };
  console.log("URL = " + UrlString);
  xhttp.open("GET", UrlString, true);
  xhttp.send();
}

function buttonClicked(buttonid)  {
  console.log("entered case statement");
  var UrlString = "templates/story/pt1/Start.html";
  switch(buttonid) {
    case "YesStart":
        UrlString = "templates/story/pt1/YesStart.html";
        console.log("test");
        loadDoc(UrlString);
        break;
    case "Sleep":
       UrlString = "templates/story/pt1/Sleep.html";
        loadDoc(UrlString);
        break;
     case "Swindon":
        UrlString = "templates/story/pt1/Swindon.html";
        loadDoc(UrlString);
        break;
    default:
        document.getElementById("storybox").innerHTML = "
That part of the story hasn't been written yet. Click to
<button type='button' class='btn btn-danger' id='nobtn' onclick='buttonClicked('YesStart')'>Restart</button>";

        console.log(buttonid);
    };
};

The case statement actually goes on a lot longer but I've cut it down. What I want to do is to shorten this code down as much as possible, so it dynamically creates URLs based on buttonid. Does anyone have an ideas about the best way to do this?

function loadDoc(UrlString) {
  var xhttp = new XMLHttpRequest();

First, I'd suggest replacing that XHR code with the newer fetch. There's a polyfill for it for older browsers. fetch returns Promises, which should be analogous to monads if I'm not mistaken.

xhttp.onreadystatechange = function() {
  if (xhttp.readyState == 4 && xhttp.status == 200) {
    document.getElementById("storybox").innerHTML = xhttp.responseText;
  }
};

Next would be to pull in the functionality that updates HTML to the caller instead of pushing it out to your AJAX operation. One big problem with your approach is that you're pushing out functionality all over the place. This becomes maintenance headache as the logic is all over the place. Should I want to change storybox to something else, I would have to trace all the way to loadDoc.

For that big switch statement, use an object as a map instead. Have it hold the url values. When a key doesn't exist, it should return undefined which you can easily default using || and a right-hand-side value.

In the end, your code can be as simple as:

var defaultUrl = 'templates/story/pt1/Start.html';

var urls = {
  YesStart: 'templates/story/pt1/YesStart.html',
  Sleep: 'templates/story/pt1/Sleep.html',
  Swindon: 'templates/story/pt1/Swindon.html'
};

function buttonClicked(buttonid){
  fetch(urls[buttonid] || defaultUrl).then(function(response) {
    return response.text()
  }).then(function(body) {
    document.getElementById("storybox").innerHTML = body
  })
}


Filtering parent and children elements of list of dictionaries I have a list of dictionaries and its elements has id and parent_id fields.

Main purposes:

If the parent_id field of an element is defined, it should be returning the rest of elements except itself.
If the parent_id field of element is not defined, it should be returning the rest of elements. In other words, its all child elements. Because it is parent element.

I'll be sharing my implementation below. But I need more concise and Pythonic way.

products = [
    {"id": 5, "counter": 10, "parent_id": None},
    {"id": 6, "counter": 10, "parent_id": 5},
    {"id": 7, "counter": 10, "parent_id": 5},
]

def get_by_id(product_id):
    product = list(filter(lambda p: p["id"] == product_id, products))
    return product[0] if product else False

def get_by_product(product):
    p = []
    for i in products:
        if product["parent_id"]:
            if i["id"] == product["parent_id"] or i["id"] != product["id"]:
                p.append(i)
        else:
            if i["parent_id"] == product["id"]:
                p.append(i)
    return p

p = get_by_id(7)
g = get_by_product(p)
print(g) # [{'id': 5, 'counter': 10, 'parent_id': None}, {'id': 6, 'counter': 10, 'parent_id': 5}]

p = get_by_id(5)
g = get_by_product(p)
print(g) # [{'id': 6, 'counter': 10, 'parent_id': 5}, {'id': 7, 'counter': 10, 'parent_id': 5}]

I have changed ridiculous if statements above like this:

def get_by_product(product):
    p = []
    for i in products:
        if product["parent_id"] and i["id"] == product["parent_id"] or i["id"] != product["id"] or i["parent_id"] == product["id"]:
            p.append(i)
    return p

If your actual program has the products list is a constant global variable, declare it as PRODUCTS (uppercase global constants)
Using list(filter(lambda can be removed by a simple comprehension. A list comprehension is the preferred method of iterating over lists as per PEP-0202
Instead of returning False in get_by_id, return a None, as that is more user intuitive.

Check the following:

def get_by_id(product_id):
    """Return a product from the list with given id, or None if not found"""
    return next((p for p in PRODUCTS if p["id"] == product_id), None)

There is no extra list being created in-memory. The generator expression returns the first value (if any) or defaults to the None. Check docs for the next function.

For the get_by_product, you can have 2 snippets. One will remove the given product from list if product.parent_id exists, and another will search for child products.

def get_by_product(product):
    if product["parent_id"] is not None:
        return [p for p in PRODUCTS if p != product]
    return [p for p in PRODUCTS if p['parent_id'] == product['id']]


I have code that loops through a column of a dataframe. How can I make this code faster? (Python/Pandas) I have datasetA with 90,000 rows and datasetB with 5,000 rows. Each dataset has a column called "ID" with employee IDs. My goal is to to create another column in datasetA that identifies whether the employee ID in datasetA is also in datasetB with a True/False. Additionally, there are most likely some multiples for certain employees/employee ids in both datasets. I am fairly certain that the code I wrote works, but it is way too slow, and I was wondering what I could change to make it faster? Thanks!
#Creating the new column to identify whether the ID in datasetA is also in datasetB.

datasetA["inB"] = "Empty"

# Looping through

for id_num in datasetA["ID"]:
    filt = (datasetA["ID"] == id_num)
    if (datasetB["ID"] == id_num).any():
        datasetA.loc[filt, "inB"] = True
    else:
        datasetA.loc[filt, "inB"] = False
```

Is this what you want?
import pandas as pd

datasetA = pd.DataFrame(
    [
        [
            'ID222'
        ],
        [
            'ID233'
        ],
        [
            'ID2123'
        ],
        [
            'ID233'
        ]
    ], columns = ['ID']
)

datasetB = pd.DataFrame(
    [
        [
            'ID222'
        ],
        [
            'ID233'
        ],
        [
            'ID212355'
        ],
        [
            'ID233'
        ]
    ], columns = ['ID']
)
datasetA["inB"] = datasetA.ID.isin(datasetB.ID)
datasetA.drop_duplicates()

    ID  inB
0   ID222   True
1   ID233   True
2   ID2123  False


Add sorting to a namedtuple I currently override the sorting methods provided by namedtuple by doing something like this:

class Subtitle(namedtuple('Subtitle', ['index', 'start', 'end', 'content'])):
    def __eq__(self, other): return self.start == other.start
    def __ne__(self, other): return self.start != other.start
    def __lt__(self, other): return self.start <  other.start
    def __le__(self, other): return self.start <= other.start
    def __gt__(self, other): return self.start >  other.start
    def __ge__(self, other): return self.start >= other.start

Typically I would use functools.total_ordering as a decorator to fill in the other sort methods from one, but in this case, collections.namedtuple already defines sort methods, so decorating with it has no effect.

As it is, fleshing out all of these comparisons when they can be deduced from each other seems a waste of code -- something that is much better handled by functools.total_ordering if only I could use it. I suppose I could delete the other sort methods from the object, but that seems quite messy. I'm not interested in reimplementing something like functools.total_ordering from scratch in my code.

Is there a better way to do this?

You could use multiple inheritance:

@functools.total_ordering
class SubtitleOrdering(object):
    def __eq__(self, other): return self.start == other.start
    def __lt__(self, other): return self.start <  other.start

class Subtitle(SubtitleOrdering, namedtuple('Subtitle', ['index', 'start', 'end', 'content'])):
    pass

total_ordering works normally on SubtitleOrdering, and making it the first base class overrides the comparison methods of the namedtuple.


Reduce the length of words in a sentence This function's goal is to reduce the length of a sentence to exactly max_length characters by cutting each word in the sentence to a length of minimum 4 characters, if cutting each word to 4 characters isn't enough the the sentence is returned anyway.
All sentences are free of special characters and words are separated by spaces.
Here is the function:

def cut_everything(sentence, max_length):
    """
    reduces each word in sentence to a length of 4

    :type sentence: string
    :param sentence: the sentence to cut
    :type max_length: int
    :param max_length: the length to which the sentence will be reduced
    """
    words = sentence.split()
    for index, word in enumerate(words):
        word_length = len(word)
        if word_length > 4:
            to_cut = len(sentence) - max_length
            to_keep = word_length - to_cut
            if to_keep < 4:
                to_keep = 4
            words[index] = word[:to_keep]
            sentence = ' '.join(words)
            if len(sentence) <= max_length:
                break

    return sentence

My main concern for this review is performance, but any readability comment is appreciated

Review

Magic numbers

4 is a magic number, it is best to assign these to a variable name, that way it is more clear what this number means

numbers don't have names, variables do

MAX_WORD_LENGHT = 4

Use built-ins when possible

to_keep = word_length - to_cut
if to_keep < 4:
to_keep = 4

Can be replaced with the max builtin

 to_keep = max(word_length - to_cut, 4)

Add tests

That way it becomes easy to check after a change if the function still works

Alternative

I went a slightly different route,

Instead of joining after each word, I calculate the chars we need to cut beforehand

So we can keep a variable that will hold the amount of chars we still need to cut to reach our target

And only at the return join the words

import doctest

MAX_WORD_LENGHT = 4

def cut_everything(sentence, max_length):
    """
    reduces each word in sentence to a length of 4

    :type sentence: string
    :param sentence: the sentence to cut
    :type max_length: int
    :param max_length: the length to which the sentence will be reduced

    >>> cut_everything('foo bar foooobar', 16)
    'foo bar foooobar'

    >>> cut_everything('foo bar foooobar', 8)
    'foo bar fooo'

    >>> cut_everything('foo bar foooobar baaarfoo', 20)
    'foo bar fooo baaarfo'

    >>> cut_everything('fooooooo baaaaaaar foooobar baaarfoo', 2)
    'fooo baaa fooo baaa'
    """
    words = sentence.split()
    chars_to_cut = len(sentence) - max_length
    for index, word in enumerate(words):
        if chars_to_cut < 0:
            break
        word_length = len(word)
        if word_length > MAX_WORD_LENGHT:
            to_keep = max(word_length - chars_to_cut, MAX_WORD_LENGHT)
            words[index] = word[:to_keep]
            chars_to_cut -= word_length - to_keep
    return ' '.join(words)

if __name__ == '__main__':
    doctest.testmod()


WPF circle and line drawer solution I've created a WPF program which can draw lines and circles on a canvas. It works well, but I don't think it's the best solution. How can I make it work better? How would you create this program?

MainWindow class:

public partial class MainWindow : Window
    {
        DrawCircle dc;
        DrawLine dl;
public MainWindow()
        {
            InitializeComponent();
        }

        private void cVas_MouseMove(object sender, MouseEventArgs e)
        {
                switch (rbLine.IsChecked)
                {
                    case true:
                        if (dl != null)
                            dl.MouseMove(Mouse.GetPosition(cVas));
                        break;
                    default:
                        if (dc != null)
                            dc.MouseMove(Mouse.GetPosition(cVas));
                        break;
                }
        }

        private void cVas_MouseDown(object sender, MouseButtonEventArgs e)
        {
            switch (rbLine.IsChecked)
            {
                case true:
                    dl = new DrawLine(this);
                    dl.MouseDown(Mouse.GetPosition(cVas));
                    break;
                default:
                    dc = new DrawCircle(this);
                    dc.MouseDown(Mouse.GetPosition(cVas));
                    break;
            }

        }

        private void cVas_MouseUp(object sender, MouseButtonEventArgs e)
        {
            dc = null;
            dl = null;
        }

        private void Window_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
                cVas.Children.Clear();
        }
    }

DrawLine class (the DrawCircle is similar to this):

class DrawLine
    {
        private Line myLine;
        MainWindow mw;

        public DrawLine(MainWindow mw)
        {
            this.mw = mw;
        }

        public void MouseDown(Point mousePoint)
        {
            myLine = new Line();
            myLine.Stroke = Brushes.Black;
            myLine.StrokeThickness = 2;
            myLine.X1 = myLine.X2 = mousePoint.X;
            myLine.Y1 = myLine.Y2 = mousePoint.Y;
            mw.cVas.Children.Add(myLine);
        }

        public void MouseUp()
        {
            myLine = null;
        }

        public void MouseMove(Point mousePoint)
        {
            if (myLine != null)
            {
                (mw.cVas.Children[mw.cVas.Children.IndexOf(myLine)] as Line).X2 = mousePoint.X;
                (mw.cVas.Children[mw.cVas.Children.IndexOf(myLine)] as Line).Y2 = mousePoint.Y;
            }
        }
    }

XAML:

<Window x:Class="WPFdraw.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525" KeyDown="Window_KeyDown">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="*"></RowDefinition>
            <RowDefinition Height="20"></RowDefinition>
        </Grid.RowDefinitions>
        <Canvas Grid.Row="0" Background="Transparent" Name="cVas" Width="Auto" Height="Auto" MouseMove="cVas_MouseMove" MouseDown="cVas_MouseDown" MouseUp="cVas_MouseUp"></Canvas>
        <Grid Grid.Row="1">
            <Grid.ColumnDefinitions>
                <ColumnDefinition></ColumnDefinition>
                <ColumnDefinition></ColumnDefinition>
                <ColumnDefinition></ColumnDefinition>
            </Grid.ColumnDefinitions>
            <RadioButton Grid.Column="0" GroupName="tool" IsChecked="True" Name="rbLine" VerticalAlignment="Center">Line</RadioButton>
            <RadioButton Grid.Column="1" GroupName="tool" Name="rbCircle" VerticalAlignment="Center">Circle</RadioButton>
            <Button Name="btn" Grid.Column="2" Content="klikk" ></Button>
        </Grid>
    </Grid>
</Window>

A little explanation first. I have written your code in a different way. This does not mean that my code is perfect in any way. I just wanted you to see other options and possibilities to achieve the same result. I'm open for comments if supported by valid arguments.

First of all I suggest you use another naming convention. This way, the name of your controls and variables have a better meaning. For example 'cVas', I'd rename that to 'DrawingCanvas' or 'DrawingSurface'.

Then there's the structure of your code. You have different shapes that have a similar structure and share a certain functionality. In situations like that, you can start thinking about inheritance and/or the use of interfaces.

Below you'll see the code that I have written. Again, this code is not perfect but it shows how it can be done. And to be honest: I think my code is easier to read, shorter and also easier to expand.

I have used an interface, from which both class derive. This way it was easy to create a Pen-object that will draw an IDrawable object. Using the Pen-object also de-couples your UI from the shape-objects. In the constructor you pass the UIElement (in this code only Canvas can be passed through) on which the pen will draw: they are coupled but in this case this is needed.

Due to the fact of the interface and pen-object, the code in your MainWindow.xaml.cs will also be a lot cleaner. You only need to instantiate one IDrawable-object and depending on the mouse-actions you provide what is needed.

I hope you find this useful and helpful! ;)

XAML:

I have not changed much about the XAML except for the names of the controls and I used a StackPanel instead of a Grid with columns.

IDrawable

public interface IDrawable
{
    void Draw(Point location);
}

MyCircle

//Since you didn't provide the code of your circle-class
//I quickly wrote a dummy-circle class, it works but not
//flawless (X and Y coordinates)
public class MyCircle : IDrawable
{
    public Ellipse Circle { get; private set; }

    public MyCircle(Point location)
    {
        Circle = new Ellipse
        {
            Stroke = Brushes.Black,
            StrokeThickness = 2,
            Margin = new Thickness(location.X, location.Y, 0, 0)
        };
    }

    public void Draw(Point location)
    {
        if(Circle != null)
        {
            Circle.Width = location.X - Circle.Margin.Left;
            Circle.Height = location.Y - Circle.Margin.Top;
        }
    }
}

MyLine

public class MyLine : IDrawable
{
    public Line Line { get; private set; }

    public MyLine(Point location)
    {
        Line = new Line
        {
            Stroke = Brushes.Black,
            StrokeThickness = 2,
            X1 = location.X,
            X2 = location.X,
            Y1 = location.Y,
            Y2 = location.Y
        };
    }

    public void Draw(Point location)
    {
        Line.X2 = location.X;
        Line.Y2 = location.Y;
    }
}

Pen

public class Pen
{
    public Pen(Canvas holder)
    {
        _holder = holder;
    }

    private readonly Canvas _holder;

    public void Down(IDrawable obj)
    {
        //if more shapes are added:
        //better use a switch-statement
        if(obj is MyCircle)
            _holder.Children.Add((obj as MyCircle).Circle);
        if(obj is MyLine)
            _holder.Children.Add((obj as MyLine).Line);
    }

    public void Draw(IDrawable obj, Point location)
    {
        obj.Draw(location);
    }
}

MainWindow

public MainWindow()
{
    InitializeComponent();
    KeyDown += MainWindowKeyDown;
    DrawingSurface.MouseMove += DrawingSurfaceMouseMove;
    DrawingSurface.MouseDown += DrawingSurfaceMouseDown;
    DrawingSurface.MouseUp += DrawingSurfaceMouseUp;
    _pen = new Pen(DrawingSurface);
}

private IDrawable _dr;
private readonly Pen _pen;

private void DrawingSurfaceMouseUp(object sender, MouseButtonEventArgs e)
{
    _dr = null;
}

private void DrawingSurfaceMouseDown(object sender, MouseButtonEventArgs e)
{
    if(LineRadioButton.IsChecked == true)
        _dr = new MyLine(Mouse.GetPosition(DrawingSurface));
    else if(CircleRadioButton.IsChecked == true)
        _dr = new MyCircle(Mouse.GetPosition(DrawingSurface));

    _pen.Down(_dr);
}

private void DrawingSurfaceMouseMove(object sender, MouseEventArgs e)
{
    if(_dr != null)
        _pen.Draw(_dr, Mouse.GetPosition(DrawingSurface));
}

private void MainWindowKeyDown(object sender, KeyEventArgs e)
{
    if(e.Key == Key.Enter)
        DrawingSurface.Children.Clear();
}


Checking for minimum image dimensions This code is part of one of the methods. I'm pretty sure it is really bad programming. The third if statement is supposed to be called if all 4 variables were set. Is another method needed? How would you write this piece?

int width = img.Width;
int height = img.Height;
int thumbWidth = 0 , thumbHeight = 0;
int preWidth = 0, preHeight = 0;

//if Landscape
if (width > height && width >= 471)
{
    thumbWidth = 120;
    thumbHeight = ((120 * height) / width);
    preWidth = 471;
    preHeight = ((471 * height) / width);
}
//if portrait
else if (height > width && height >= 353)
{
    thumbHeight = 120;
    thumbWidth = ((120 * width) / height);
    preHeight = 353;
    preWidth = ((353 * width) / height);
}

//If values were set
if (thumbWidth != 0 && thumbHeight != 0 && preWidth != 0 && preHeight != 0)
{

}
else
{
    //do other stuff
}

The problems I see here involve code duplication and magic values, and perhaps some incomplete logic.

You use the numbers 120, 471, 353. I don't know what those mean. And they're duplicated. Make those variables with descriptive names.

Now let's look at this:

//if Landscape
if (width > height && width >= 471)

This is more than than just if landscape. This is if landscape and is too big. But I'm not encouraging you to write a better comment! Instead, I encourage you to encapsulate that conditional into it's own method, with a more descriptive name, and then remove the comment.

private bool IsLandscapeAndTooBig(width, height)
{
    return width > height && width > maximumWidth; // notice the new variable?
}

The same idea applies to your "if portrait" piece.

Let's look inside those ifs now. Again, the problem is the magic values, but perhaps these inner blocks need to be methods, perhaps ResizeLandscape and ResizePortrait (but you probably want to think a bit longer on these names). And instead of operating on 4 local variables, perhaps they should instead return a single encapsuting data object.

class ImageDimension
{
     public int ThumbWidth { get; set; }
     // continues
}

one other thing I see is that you build thumbnail dimensions for too large of a landscape and too large of a portrait, but you don't seem to build them for images that are not too large. Does something just smaller than your threshold for "large" not need a thumbnail? This is where I think you might have some missing logic. On the other hand, you might not, I don't know entirely what you are trying to do. Just keep this in mind.


Deterministic finite automaton in Java Formally, a deterministic finite automaton is a 5-tuple \$M = (Q, \Sigma, \delta, q_0, F)\$, where

\$Q\$ is the set of all possible states
\$\Sigma\$ is the alphabet
\$\delta \colon Q \times \Sigma \to Q\$ is the transition function
\$q_0\$ is the starting state
\$F\$ is the set of accepting states

Basically, each DFA represents a so-called regular language \$L\$, and given input string \$s\$, answers whether \$s \in L\$. This is done in \$\mathcal{O}(|s|)\$ time simply by consuming each character and making the state transitions starting from \$q_0\$; if after reading the entire string we end up in a state in \$F\$, the DFA accepts the string.

Please, tell me anything that comes to mind.

TransitionFunction.java

package net.coderodde.dfa;

import java.util.HashMap;
import java.util.Map;

/**
 * This class implements a transition function.
 *
 * @author Rodion "rodde" Efremov
 * @version 1.6 (Apr 2, 2016)
 */
public class TransitionFunction {

    private final Map<Integer, Map<Character, Integer>> function =
          new HashMap<>();

    public void setTransition(Integer startState,
                              Integer goalState,
                              char character) {
        function.putIfAbsent(startState, new HashMap<>());
        function.get(startState).put(character, goalState);
    }

    public Integer process(Integer startState, char character) {
        if (!function.containsKey(startState)) {
            return null;
        }

        return function.get(startState).get(character);
    }
}

DFA.java

package net.coderodde.dfa;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Objects;
import java.util.Scanner;
import java.util.Set;

/**
 * This class implements a
 *
 * deterministic finite automaton.
 *
 * @author Rodion "rodde" Efremov
 * @version 1.6 (Apr 2, 2016)
 */
public class DFA {

    private final TransitionFunction transitionFunction;
    private final int startState;
    private final Set<Integer> acceptingStates;

    public DFA(TransitionFunction transitionFunction,
               int startState,
               Set<Integer> acceptingStates) {
        this.transitionFunction =
                Objects.requireNonNull(transitionFunction,
                                       "Transition function is null.");
        this.startState = startState;
        this.acceptingStates =
                Objects.requireNonNull(acceptingStates,
                                       "Accepting state set is null.");
    }

    public boolean matches(String text) {
        Integer currentState = startState;

        for (char c : text.toCharArray()) {
            currentState = transitionFunction.process(currentState, c);

            if (currentState == null) {
                return false;
            }
        }

        return acceptingStates.contains(currentState);
    }

    public static void main(String[] args) {
        // A regular language over binary strings with even number of 1's.
        TransitionFunction transitionFunction = new TransitionFunction();

        transitionFunction.setTransition(0, 0, '0');
        transitionFunction.setTransition(1, 1, '0');
        transitionFunction.setTransition(0, 1, '1');
        transitionFunction.setTransition(1, 0, '1');

        Set<Integer> acceptingStates = new HashSet<>(Arrays.asList(0));
        DFA dfa = new DFA(transitionFunction, 0, acceptingStates);

        Scanner scanner = new Scanner(System.in);

        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();

            if (line.trim().equals("end")) {
                break;
            }

            System.out.println(dfa.matches(line));
        }
    }
}

Java 8 constructs

The following

function.putIfAbsent(startState, new HashMap<>());
function.get(startState).put(character, goalState);

can be simplified by using the computeIfAbsent(key, mappingFunction) method. This method will return the current value associated with the given key or compute a new value for that key and return it. As such, you could have:

function.computeIfAbsent(startState, k -> new HashMap<>()).put(character, goalState);

Also, the following

if (!function.containsKey(startState)) {
    return null;
}
return function.get(startState).get(character);

can be also written more simply with the getOrDefault(key, defaultValue) method. This will return the value associated with the given key or else return the default value. You could have:

return function.getOrDefault(startState, Collections.emptyMap()).get(character);

When the map doesn't contain the key startState, an empty map (that was already instantiated, it is a cached value) is returned with Collections.emptyMap().

Code structure

You currently have a class TransitionFunction that holds all transitions and offers a method to go from one state to another for a particular character.

I find the name TransitionFunction a bit misleading because it would imply that the class is in fact a Function in that it is a functional interface taking a parameter and returing a value. But it is more than that since it is the class that holds all possible transitions.

Why not rename the class Transitions and:

Rename the method setTransition to addTransition to better reflect the fact that this method adds a transition (instead of setting it).
Move the code for processing all transitions, that is currently placed inside the matches method, in this class. This method would be called processAll(Integer startState, char[] characters) and would process all the characters given starting at the given state.

This is what the class could look like

public class Transitions {

    private final Map<Integer, Map<Character, Integer>> function = new HashMap<>();

    public void addTransition(Integer startState, Integer goalState, char character) {
        function.computeIfAbsent(startState, k -> new HashMap<>()).put(character, goalState);
    }

    public Integer process(Integer startState, char character) {
        return function.getOrDefault(startState, Collections.emptyMap()).get(character);
    }

    public Integer processAll(Integer startState, char[] characters) {
        return IntStream.range(0, characters.length)
                        .boxed()
                        .reduce(startState, (s, i) -> s == null ? null : process(s, characters[i]));
    }

}

Notice that the processAll method leverages an IntStream over the indexes of the input array. The final state is calculating by reducing from the starting state and calling process each time on the accumulated result. The difference between your initial code is that it is not short-circuiting; if you wish to keep that, you can keep your for loop as-is.

With this change, the matches method would just be:

public boolean matches(String text) {
    Integer finalState = transitionFunction.processAll(startState, text.toCharArray());
    return finalState != null && acceptingStates.contains(finalState);
}

Using Optional

You are currently relying on null values to mean "no state". Using an Optional would remove all that. We could make the methods process and processAll return an Optional<Integer> with

public Optional<Integer> process(Integer startState, char character) {
    return Optional.ofNullable(function.getOrDefault(startState, Collections.emptyMap()).get(character));
}

public Optional<Integer> processAll(Integer startState, char[] characters) {
    return IntStream.range(0, characters.length)
                    .boxed()
                    .reduce(
                      Optional.of(startState),
                      (o, i) -> o.flatMap(s -> process(s, characters[i])),
                      (o1, o2) -> o1.map(Optional::of).orElse(o2)
                    );
}

process makes a call to Optional.ofNullable to wrap the value. The reducing part works on the optional values. The combiners combines two optional into a single one.

Then, the matches method becomes

public boolean matches(String text) {
    return transitionFunction.processAll(startState, text.toCharArray())
                             .map(acceptingStates::contains)
                             .orElse(false);
}


Adding two singly linked lists in C++ I took a challenge from a web site. I aim to have a runtime performance as good as possible. My solution was accepted, though I think it is not the most efficient because I saw others having a faster solution.
Are there dos and don'ts in regard to C++ programing in order to try to get the best performance possible.
This question is about coding optimally. I have no means to tweak around with compiler options or so.

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode* res = NULL;

        if (size(l1) < size(l2))
            res = add(l1, l2);
        else
            res = add(l2, l1);

        return res;
    }

private:

    /**
     * Input: A list
     * Output: size of the list
     */
    static int size(const ListNode *l) {
        int size = 0;
        while(l != NULL)
            ++size, l = l->next;
        return size;
    }

    /**
     * Input: Two lists l1 and l2 with size(l1) <= size(l2)
     * Output: result list
     */
    ListNode* add(const ListNode *l1, const ListNode *l2) {
        ListNode *head, *l;
        register bool carry_over = false;
        int x = l1->val + l2->val + carry_over;

        if (x > 9) {
            carry_over = true;
             x -= 10;
        }
        head = l = new ListNode(x);
        l1 = l1->next;
        l2 = l2->next;

        while (l1 != NULL) {
            x = l1->val + l2->val + carry_over;
            if (x > 9) {
                carry_over = true;
                x -= 10;
            } else
                carry_over = false;
            l = l->next = new ListNode(x);
            l1 = l1->next;
            l2 = l2->next;
        }

        while(l2 != NULL) {
            x = l2->val + carry_over;
            if (x > 9) {
                carry_over = true;
                x -= 10;
            } else
                carry_over = false;
            l = l->next = new ListNode(x);
            l2 = l2->next;
        }

        if (carry_over)
            l->next = new ListNode(1);

        return head;
    }

};

Eliminate size

The size function is not useful. Imagine if one list contains 1 element and the other contains a million. If you're lucky you might traverse the shorter list first, and use that size to stop traversing the second list early when possible.

Instead of trying to check the size first, you could adjust the main loop in add from this:

while (l1 != NULL) {

to this:

while (l1 != NULL && l2 != NULL) {

and add this condition after, to prepare for the second loop:

if (l1 != NULL) {
    l2 = l1;
}

More natural int carry

Instead of bool carry_over, it would be more natural to have an int carry, with 0 or 1 as values. The end result is the same, but more natural, less surprising.

Duplicated adding logic

The logic of adding is duplicated several times:

For the first pair of elements
For the pairs of elements while exist
For the remaining elements of the longer list

You can easily eliminate the first, by using a dummy node to mark the head of the new list. The value of this node will not be used, but dummy->next will point to the first element. In addition, this little trick will make the implementation more robust, and handle the case when one of the lists is empty (null).

Declare variables in the smallest scope

There's no need to declare x at the top. You can declare it inside the loops where needed.

Naming

Lowercase l is one of the worst possible names for a variable. In some fonts it might look like the number one. Almost any name would be better than that. For example node.

Braces

It's recommended to use braces always, even with single-statement if.

Suggested implementation

Applying the above suggestions, the implementation becomes:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        return add(l1, l2);
    }

private:

    /**
     * Input: Two lists l1 and l2 with size(l1) <= size(l2)
     * Output: result list
     */
    ListNode* add(const ListNode *l1, const ListNode *l2) {
        // dummy node, helps simplify the code a bit
        ListNode dummy(0);
        ListNode *node = &dummy;

        int carry = 0;

        while (l1 != NULL && l2 != NULL) {
            int x = l1->val + l2->val + carry;
            if (x > 9) {
                carry = 1;
                x -= 10;
            } else {
                carry = 0;
            }
            node = node->next = new ListNode(x);
            l1 = l1->next;
            l2 = l2->next;
        }

        if (l1 != NULL) {
            l2 = l1;
        }

        while (l2 != NULL) {
            int x = l2->val + carry;
            if (x > 9) {
                carry = 1;
                x -= 10;
            } else {
                carry = 0;
            }
            node = node->next = new ListNode(x);
            l2 = l2->next;
        }

        if (carry) {
            node->next = new ListNode(1);
        }

        return dummy.next;
    }
};

Speed

I suppose the exercise comes from here.
I don't know how to make this faster.
I submitted your original code, and some variations, but the result appears to be randomly within 36-56ms. At 36ms it beats 64% of submissions, at 40ms it beats only 18% of submissions. But I don't think speed is important at all. The time complexity of your algorithm is \$O(n)\$, and I don't think it's possible to solve this problem faster than that. Any speed optimizations at this level are just micro-optimizations, neither relevant nor interesting.


On hover, hide text and display options Recently I learned HTML+CSS and a bit of jQuery and am building various web-things to stretch my skills and learn more about how to do things the right way.  I was a bit surprised at just how many different ways there are to do the same thing using just CSS and JavaScript.

Currently I am building a bit of a "landing page" style website bit by bit, and the component I am working on right now is an interactive discovery menu type thing.  Essentially there is an initial text, which incites the user to hover over it, and once hovering, various options appear, which are links.  My current code is below and functional, however I am not confident that I am executing this efficiently or properly.

A couple of specifics I want to learn are:

What HTML element should I use for the initial text?
Is the structure of my hover-menu proper?  Or is there a better way that is more standard for this sort of thing?
Would this be better done in CSS transitions rather than JS?  NOTE: I want to add a context box below the menu (or somewhere not directly attached to the individual links) which fills with contextual information about the currently hovered link, so I assume JS is the solution in the long run.
Not that important but: I had trouble attempting to classify what to call this sort of thing (so as to google it).  Is there a standard name for this sort of set-up?

Final Note:

I don't really know any general JavaScript outside of the jQuery I have learned.  I do however have programming experience, so I am not opposed to using any other external JS libraries which would be more suited to my goals.  I have simply not had much time to explore JavaScript and the many extensions it has.  Basically I'd love some directing from anyone who knows what I don't!

$(document).ready(function() {
  $('#menu').hover(
    function() { // mouseenter
      // hide & compress initial text
      $('#menu span').stop().animate({
        width: '0px',
        opacity: 0
      }, $('#menu span').hide);

      // show & decompress link options
      $('#menu a').stop().show().animate({
        width: '100px',
        opacity: 1
      });

    },
    function() { //mouseleave
      // hide & compress options
      $('#menu a').stop().animate({
        width: '0px',
        opacity: 0
      }, $('#menu a').hide);

      // show & decompress link options
      $('#menu span').stop().show().animate({
        width: '250px',
        opacity: 1
      });

    });
});
#menu {
  width: auto;
}
#menu * {
  overflow: hidden;
  white-space: nowrap;
  font-size: 30px;
  text-align: center;
}
#menu a {
  display: none;
  width: 0px;
  opacity: 0;
}
#menu span {
  display: inline-block;
  width: 250px;
}

    Hover for items!
    Item 1
    Item 2
    Item 3

One thing you could do is create functions to call instead of writing each sub function out every time you want to animate something.

var hideText = function(element) {

    $('#menu ' + element).stop().animate({
      width: '0px',
      opacity: 0
    }, $('#menu ' + element).hide);
}

var showText = function(element, elementWidth) {

    $('#menu ' + element).stop().show().animate({
      width: elementWidth,
      opacity: 1
    });
}

Now you can call this like this, with less repeated code:

  $('#menu').hover(
    function() { // mouseenter

      hideText('span');
      showText('a', '100px');
    },
    function() { //mouseleave

      hideText('a');
      showText('span', '250px');
    });
});

$(document).ready(function() {

  var hideText = function(element) {

      $('#menu ' + element).stop().animate({
        width: '0px',
        opacity: 0
      }, $('#menu ' + element).hide);
  }

  var showText = function(element, elementWidth) {

      $('#menu ' + element).stop().show().animate({
        width: elementWidth,
        opacity: 1
      });
  }

  $('#menu').hover(
    function() { // mouseenter

      hideText('span');
      showText('a', '100px');
    },
    function() { //mouseleave

      hideText('a');
      showText('span', '250px');
    });
});
#menu {
  width: auto;
}
#menu * {
  overflow: hidden;
  white-space: nowrap;
  font-size: 30px;
  text-align: center;
}
#menu a {
  display: none;
  width: 0px;
  opacity: 0;
}
#menu span {
  display: inline-block;
  width: 250px;
}

    Hover for items!
    Item 1
    Item 2
    Item 3


Nested IF code in GUI Controls I'm writing GUI controls and there are many places where there are many nested ifs checking for some result.

function TMyObject.GetCursor: TCursor;
begin
  if CanDragX then
  begin
    if CanDragY then
      Result := crSizeAll
    else
      Result := crSizeWE;
  end
  else if CanDragY then
    Result := crSizeNS
  else
  if CanClick then
    Result := crHandPoint
  else
    Result := crArrow;
end;

How would you format/rewrite this code?

I would do this:

function TMyObject.GetCursor: TCursor;
begin
  if CanDragX and CanDragY then
    Result := crSizeAll
  else if CanDragX then
    Result := crSizeWE
  else if CanDragY then
    Result := crSizeNS
  else
    if CanClick then
      Result := crHandPoint
    else
      Result := crArrow;
end;

But really it is a matter of style and what is most readable to you (and the person who will maintain it).