Unique short string for URL I needed short, unique, seemingly random URLs for a project I'm working on, so I put together the following after some research. I believe it's working as expected, but I want to know if there's a better or simpler way of doing this. Basically, it takes an integer and returns a string of the specified length using the character list. I'm new to Python, so help is much appreciated.

def genkey(value, length=5, chars='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890', prime=694847539):
    digits = []
    base = len(chars)
    seed = base ** (length - 1)
    domain = (base ** length) - seed
    num = ((((value - 1) + seed) * prime) % domain) + seed

    while num:
        digits.append(chars[num % base])
        num /= base
    return ''.join(reversed(digits))

The trouble with using a pseudo-random number generator to produce your shortened URLs is, what do you do if there is a collision? That is, what happens if there are values v and w such that v != w but genkey(v) == genkey(w)? Would this be a problem for your application, or would it be entirely fine?

Anyway, if I didn't need to solve the collision problem, I would use Python's built-in pseudo-random number generator for this instead of writing my own. Also, I would add a docstring and some doctests.

import random
import string

def genkey(value, length = 5, chars = string.ascii_letters + string.digits):
    """
    Return a string of `length` characters chosen pseudo-randomly from
    `chars` using `value` as the seed.

    >>> ' '.join(genkey(i) for i in  range(5))
    '0UAqF i0VpE 76dfZ oHwLM ogyje'
    """
    random.seed(value)
    return ''.join(random.choice(chars) for _ in xrange(length))

Update: you clarified in comments that you do need to avoid collisions, and moreover you know that value is a number between 1 and domain inclusive. In that case, you're right that your transformation is an injection, since prime is coprime to domain, so your method is fine, but there are several things that can be done to simplify it:

As far as I can see, there's no need to subtract 1 from value.
There's no need to use the value seed at all. You're using this to ensure that you have at least length digits in num, but it's easier just to generate exactly length digits. (This gives you a bigger domain in any case.)
There's no need to call reversed: the reverse of a pseudo-random string is also a pseudo-random string.

Applying all those simplifications yields the following:

def genkey(value, length=5, chars=string.ascii_letters + string.digits, prime=694847539):
    """
    Return a string of `length` characters chosen pseudo-randomly from
    `chars` using `value` as the seed and `prime` as the multiplier.
    `value` must be a number between 1 and `len(chars) ** length`
    inclusive.

    >>> ' '.join(genkey(i) for i in range(1, 6))
    'xKFbV UkbdG hVGer Evcgc 15HhX'
    """
    base = len(chars)
    domain = base ** length
    assert(1 <= value <= domain)
    n = value * prime % domain
    digits = []
    for _ in xrange(length):
        n, c = divmod(n, base)
        digits.append(chars[c])
    return ''.join(digits)

A couple of things you might want to beware of:

This pseudo-random scheme is not cryptographically strong: that is, it's fairly easy to go back from the URL to the value that produced it. This can be a problem in some applications.
The random strings produced by this scheme may include real words or names in human languages. This could be unfortunate in some applications, if the resulting words were offensive or otherwise inappropriate.


Directory write permissions check Consider the following method that I have for checking write permissions on a directory path:

/// <summary>
/// Check existence and write permissions of supplied directory.
/// </summary>
/// <param name="directory">The directory to check.</param>
protected static void CheckPermissions(string directory)
{
    if (!Directory.Exists(directory))
    {
        throw new DirectoryNotFoundException(String.Format(JobItemsStrings.Job_DirectoryNotFound, directory));
    }

    // Check permissions exist to write to the directory.
    // Will throw a System.Security.SecurityException if the demand fails.
    FileIOPermission ioPermission = new FileIOPermission(FileIOPermissionAccess.Write, directory);
    ioPermission.Demand();
}

When running FxCop, this code throws up a "CA2103 - Review imperative security" warning, albeit with a certainty of 25%, with this info:

  "Use of imperative demands can lead to
  unforeseen security problems. The
  values used to construct a permission
  should not change within the scope of
  the demand call. For some components
  the scope spans from the demand call
  to end of the method; for others it
  spans from the demand call until the
  component is finalized. If the values
  used to construct the permission are
  fields or properties, they can be
  changed within the scope of the demand
  call. This can lead to race
  conditions, mutable read-only arrays,
  and problems with boxed  value types."

Bascially, is FxCop being over-cautious, or am I doing it wrong?

This FxCop warning is basically asking you to make sure ("Review") that that non-constant you are passing (directory) to the security permission does not change while the permission is in effect.  Basically, FxCop isn't sure if it is possible for the code (or some rogue module that a hacker has put in place) to do something like the following:

Set directory to "c:\Temp\"
.Demand()
<untrusted>Set directory to "c:\Windows\System32\"</untrusted>
Write something into a file contained in directory.

In this particular case, since directory is a non-ref parameter, it is not possible for another module outside your call-descendants to modify it.  Thus, what you need to check for:

Anything in this method assigning a value to directory
Anything in this method that passes directory by reference (ref/out/unsafe pointers)

Disclaimer: I am not a code security expert and have no formal training as such.  I may have missed entire classes of things to look for here. If you are dealing with code that has real-world security implications, I highly suggest you hire a consultant who does, rather than take what I wrote above as gospel.


Joining two KeyedTuple objects in SQLAlchemy I have the following two queries:

res=session.query(t_marketing_mailing_stats_tbl).filter(
    t_marketing_mailing_stats_tbl.c.mailing_id==mid)

res_t=session.query(t_marketing_time_stat_tbl).filter(
    t_marketing_time_stat_tbl.c.mailing_id==mid)

try:
    return res.one() + res_t.one()
except NoResultFound as e:
    return None

res and res_t are both of type sqlalchemy.util._collections.KeyedTuple which support addition, however, the resulting object is a simple tuple, without keys.

I would like to have a combined result, so I did the following:

rv = {}
res=session.query(t_marketing_mailing_stats_tbl).filter(
    t_marketing_mailing_stats_tbl.c.mailing_id==mid)

res_t=session.query(t_marketing_time_stat_tbl).filter(
    t_marketing_time_stat_tbl.c.mailing_id==mid)

try:
    res =res.one()
    res_t = res_t.one()
    for k in res.keys():
        rv[k] = getattr(res, k)
    for k in res_t.keys():
        rv[k] = getattr(res_t, k)
except NoResultFound as e:
    return None

While this works, I suspect there is a built-in way, or a better way of achieving this with SQLAlchemy.

Your basic problem is you want to combine...erm, join... similar data from your database. There are a couple different angles we can take to solve this problem:

We could do as you are, but a more simple way.
We can let the database do the work.

The second way is the preferred solution. Databases are designed to solve this problem and they solve them very efficiently. They are meant to be a powerful tool to store, update, and eventually relate data.

If you are set on the first solution, this post describes several ways to combine two dicts. Combine any one of those solutions with the KeyedTuple._asdict function can simplify your code:

try:
    # In Python 3, you cannot use the + operator. You can use the | operator instead.
    joined_result = dict(res.one()._asdict().items() + res_t.one()._asdict().items())
except NoResultFound:
    return None

Now, the preferred solution would be to use a JOIN to combine the two queries into one. SQLAlchemy's join documentation has a quite a few examples of how join can be used. The basic example should suffice for your purposes:

joined_result = session.query(t_marketing_mailing_stats_tbl)\
                       .join(t_marketing_time_stat_tbl)\
                       .filter(t_marketing_mailing_stats_tbl.c.mailing_id==mid)

try:
    return joined_result.one()
except NoResultFound:
    return None

To wrap up, I have a few style comments:

Be consistent with your spacing. For the most part you have a single space before and after operators. This is good. However, in a few locations, you have one or both of the spaces missing.
Don't truncate words in variable names (unless they are very long). Typical Python convention tries to be more verbose than brief. Thus the variable name res would better named as result.

Also, make sure that your names are unambiguous: what does res_t do different than res? What does the prefix t_ mean in your table names mean? Given the context, t_ could easily mean 'table'; however, wouldn't the suffix _tbl then be redundant?


Program efficiency vs user experience. Python Ancestor app Bit of a basic question but I was creating a ancestor/family tree app thingy (haven't really worked out the details) and I wrote a small start-up program (seen below) which checks the AppData directory exists and the config file exist (consisting of the number of tree and their respective names).
I was wondering if it's better to include the code that updates the config file at the beginning of runtime EVERY TIME or not since its only there in case the user accidently changes something:
import json
import os

AncestoryDir = os.getenv("APPDATA") + "\Ancestry"
ConfigFile = AncestoryDir + "\CONFIG.ini"

# Make Ancestory Directory
if not os.path.exists(AncestoryDir):
    os.makedirs(AncestoryDir)

# Update Config.ini File
CONFIGTree = {"Tree Count": None, "Tree's": []}
for File in os.scandir(AncestoryDir):
    if File.is_file():
        Tree, Suffix = File.name.split(".")
        if Suffix == "json":
            CONFIGTree["Tree's"].append(Tree)
CONFIGTree["Tree Count"] = len(CONFIGTree["Tree's"])
with open(ConfigFile, "w") as JSON:
    json.dump(CONFIGTree, JSON, indent = 4)

Main File:
import os

os.system("python Ancestory.py")
#Other Stuff

As you can see it updates the config file EVERY TIME and im not sure if its worth it. Any thoughts or suggestions are appreciated.
Note:
Please don't tell me about PEP-8, I'm well aware of it and I choose to ignore it out of pure idiocy (my choice)

Pathlib
AncestoryDir = os.getenv("APPDATA") + "\Ancestry"
ConfigFile = AncestoryDir + "\CONFIG.ini"

# Make Ancestory Directory
if not os.path.exists(AncestoryDir):
    os.makedirs(AncestoryDir)

can reduce to
ancestry_dir = Path(os.getenv('APPDATA')) / 'Ancestry'
config_file = ancestry_dir / 'CONFIG.ini'

ancestry_dir.mkdir(exist_ok=True)

Note:

pathlib grants you a cleaner, object-oriented method for path manipulation
it's spelled "ancestry"
with pathlib there's no need for a separate existence check
even if you kept your approach, you have an invalid escape \A that either needs to be double-escaped or exist in a raw string

pathlib applies to your other code, too. Also it's spelled "Trees", not "Tree's".
PEP8
Protest thou may, but this actually matters. Coding is a form of communication, and the less we successfully communicate with other coders, the less they're able to help and work with us.


Socket chat room made with Tkinter Python This is a real live chatroom that I have made with Tkinter

I posted a question before about making a chatroom but the problem that I had with that one was that only one user could connect to the server so I restarted and have made this one. I just want suggestions on how I can improve it.

All suggestions will be greatly appreciated

Thanks

Server.py

import socket, threading
host = socket.gethostname()
port = 4000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host,port))
s.listen()
clients = {}
addresses = {}
print(host)
print("Server is ready...")
serverRunning = True
def handle_client(conn):
    try:
        data = conn.recv(1024).decode('utf8')
        welcome = 'Welcome %s! If you ever want to quit, type {quit} to exit.' % data
        conn.send(bytes(welcome, "utf8"))
        msg = "%s has joined the chat" % data
        broadcast(bytes(msg, "utf8"))
        clients[conn] = data
        while True:
            found = False
            response = 'Number of People Online\n'
            msg1 = conn.recv(1024)

            if msg1 != bytes("{quit}", "utf8"):
                broadcast(msg1, data+": ")
            else:
                conn.send(bytes("{quit}", "utf8"))
                conn.close()
                del clients[conn]
                broadcast(bytes("%s has left the chat." % data, "utf8"))
                break
    except:
        print("%s has left the chat." % data)
def broadcast(msg, prefix=""):
    for sock in clients:
        sock.send(bytes(prefix, "utf8")+msg)

while True:
    conn,addr = s.accept()
    conn.send("Enter username: ".encode("utf8"))
    print("%s:%s has connected." % addr)
    addresses[conn] = addr
    threading.Thread(target = handle_client, args = (conn,)).start()

Client.py

import socket,threading,tkinter
host = input("Enter server name: ")
port = 4000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
address = (host,port)
def echo_data(sock):
   while True:
      try:
         msg = sock.recv(1024).decode('utf8')
         msg_list.insert(tkinter.END, msg)
      except OSError:
         break

def send(event=None):
   msg = my_msg.get()
   my_msg.set("")
   s.send(bytes(msg, "utf8"))
   if msg == "{quit}":
      s.close()
      top.quit()

def on_closing(event=None):
    my_msg.set("{quit}")
    send()

top = tkinter.Tk()
top.title("Chat Room")

messages_frame = tkinter.Frame(top)
my_msg = tkinter.StringVar()
my_msg.set("Type your messages here.")
scrollbar = tkinter.Scrollbar(messages_frame)
msg_list = tkinter.Listbox(messages_frame, height=15, width=100, yscrollcommand=scrollbar.set)
scrollbar.pack(side=tkinter.RIGHT, fill=tkinter.Y)
msg_list.pack(side=tkinter.LEFT, fill=tkinter.BOTH)
msg_list.pack()
messages_frame.pack()

entry_field = tkinter.Entry(top, textvariable=my_msg)
entry_field.bind("<Return>", send)
entry_field.pack()
send_button = tkinter.Button(top, text="Send", command=send)
send_button.pack()

top.protocol("WM_DELETE_WINDOW", on_closing)

address = (host,port)
s.connect(address)

threading.Thread(target=echo_data, args = (s,)).start()

tkinter.mainloop()

This is a nice snippet which makes it useful for teaching! Here are some points:

Make imports explicit

Though import socket, threading is valid in Python, importing in two lines improves readability

import socket
import threading

Two lines after imports

Add two lines after imports. From this:

import socket
import threading
host = socket.gethostname()
...

to this:

import socket
import threading

host = socket.gethostname()
...

Constants in caps

port = 4000 should be PORT = 4000

Use string formatting

From this:

"%s has left the chat." % data

to this:

"{} has left the chat.".format(data)

In case of curly braces, you escape using {{}} as in the following case:

'Welcome {}! If you ever want to quit, type {{quit}} to exit.'.format(data)

Broadcast before handle_client

Since in handle_client you use broadcast, define it first

def broadcast(msg, prefix=""):
    ...

def handle_client(conn):
    ...

Add a message function

enclose:

bytes(msg, "utf8")

in a function called message:

def message(text):
    return bytes(text, "utf8")

then it becomes neater to use:

broadcast(message('hi'))

More explicit messages:

1) Server message

When first connecting, the server console states for me:

jPC
Server is ready...

And then when running clients, you get asked:

Enter server name:

I had to deduce that jPC is my server name. Modifying to the following might be more explicit:

Server name: jPC
Server is ready...

2) Enter username

Enter username in the textbox might be a better message. Coupled with the fact that you did not use a placeholder for the entry, users are confused.

3) Quiting without username

If someone quits without setting a username the server says:

{quit} has left the chat.

Adding a default id for clients might be better

{
    '<id2>': {
                'username': None,
                'connection_ip': '192.168.56.1:50325'
    },
    '<id2>': ...
}

you can use the uuid module for id or use the ip itself as id

Add placeholder effect

Add a placeholder effect by adding the line:

entry_field.bind("<FocusIn>", lambda args: entry_field.delete('0', 'end'))

Setting the font color to gray completes the effect.

Miscellaneous

Use snake case for variables. serverRunning becomes server_running
Use a geometry manager like grid for better display


Selecting one form to be visible using jQuery I'm new to jQuery but have managed to get it working the way I want. The problem is, it's a bit convoluted and could easily get out of hand if I add more options.

I am trying to show and hide divs based on a user's dropdown selection. I've made a JSFiddle with where I am so far, but I think it could do with some streamlining.

I'd like to be able to add five more dropdown options, with five more divs to show or hide. Will I need to hide each of them individually, or is there a way to say "if the div id is not the value selected, then hide it"?

I'm using CF7 to build the form.

$(function() {
    $("select").change(function() {

        if ($(this).val() == "I have a query") {
            $("#cf-query").show("slow");
            $("#cf-booking").hide("slow")

        } else if ($(this).val() == "I would like to book") {
            $("#cf-booking").show("slow")
            $("#cf-query").hide("slow")

        } else {
            $(".cf-section").hide("slow");
        }
    });
});

What is the nature of your enquiry*:

<select id="cf-dd-nature">
    <option value="">--</option>
    <option value="I have a query">I have a query</option>
    <option value="I would like to book">I would like to Book</option>
</select>

Query

First Name:

Surname*:

Email Address*:

Telephone number*:

Booking

First Name:

Telephone number*:

Change the option values to the div ids

<option value="cf-query">I have a query</option>
…

Hide all elements with class cf-section.
Finally reference the value and show it, no need for the multiple if statements.

$("select").change(function() {
  $(".cf-section").hide();
  id = "#" + $(this).val();
  $(id).show("slow");
}

Now you can add as many as you want and your jQuery function code never changes.


Simple Pig Latin Translator The goal of my assignment is simple:

  Write a program that converts a given text to "Pig Latin".  Pig Latin
  consists of removing the first letter of each word in a sentence and
  placing that letter at the end of the word.  This is followed by
  appending the word with letters "ay".

  Example

  Input: THIS IS A TEST
  Output: HISTAY SIAY AAY ESTTAY

I want to know if there is any way to write this part of the code in a different/better way:

foreach (string word in engword.Split())

Here is my full code:

string engword = textBox1.Text; //english word
            string pig1 = ""; //pig latin
            string pig2 = ""; //first letter
            string space = " ";
            string extra = ""; //extra letters
            int pos = 0; //position

           foreach (string word in engword.Split())
           {
               if (pos != 0)
               {
                   pig1 = pig1 + space;
               }

               else
               {
                   pos = 1;
               }

               pig2 = word.Substring(0,1);
               extra = word.Substring(1, word.Length - 1);
               pig1 = pig1 + extra + pig2 + "ay";

            }

            MessageBox.Show(pig1.ToString());
        }
    }
}

This looks pretty decent for a beginner. Some suggestions:

Making a variable space instead of using the literal directly is actually a kind of nice idea. You can improve the code by marking the local const.
Why is pos an integer? it only has two values, and you are using it to test a condition. Use a bool instead.
For that matter, why have pos in the first place? Pos tells you the same thing as pig1.Length == 0.
Any time you write a comment, ask yourself did I add this comment because the code was unclear? and then can I write the code so clearly that I don't need the comment?  You say

string pig2 = ""; // First letter

Dude. If the name of the variable is firstLetter then you don't need the comment.
pig2 is just one letter, so it can be a char instead of a string. You can say:

char firstLetter;
...
firstLetter = word[0];

You're using pig1 as an accumulator; you're accumulating the final result piece by piece. This is totally fine for small strings. If that string was really big then this is not an efficient technique; you should use StringBuilder instead if you want to make an accumulator for a large string.
Finally, like I said, this is fine for a beginner, walk before you run, and so on. To give you a sense of how an expert would write this code, I'd write it like this:

string pigLatin = string.Join(" ",
  engword.Split()
         .Select(word => word.Substring(1, word.Length - 1) + word[0] + "ay"));

Which is nicely compact.


Simplifying a series of type checks and casts in a generic method The if/else statements below are not good. How can I improve this method?

public T GetContentByNodeIdSync<T>(Guid nodeId)
{
    var data = m_CMSCatalog.GetContentByNodeId(nodeId);

    if (typeof(T) == typeof(WebFolder))
    {
        var model = (WebFolderDTO)data;
        return Mapper.Map<WebFolderDTO, T>(model);
    }
    else if (typeof(T) == typeof(ContentListItem))
    {
        return Mapper.Map<ContentListItemDTO, T>((ContentListItemDTO)data);
    }
    else if (typeof(T) == typeof(Image))
    {
        return Mapper.Map<ImageDTO, T>((ImageDTO)data);
    }
    else if (typeof(T) == typeof(File))
    {
        return Mapper.Map<FileDTO, T>((FileDTO)data);
    }
    else if (typeof(T) == typeof(Folder))
    {
        return Mapper.Map<FolderDTO, T>((FolderDTO)data);
    }
    else if (typeof(T) == typeof(WebRoot))
    {
        return Mapper.Map<WebRootDTO, T>((WebRootDTO)data);
    }
    else if (typeof(T) == typeof(Article))
    {
        var model = (ArticleDTO)data;
        return Mapper.Map<ArticleDTO, T>(model);
    }
    else if (typeof(T) == typeof(WebContent))
    {
        var model = (WebContentDTO)data;
        return Mapper.Map<WebContentDTO, T>(model);
    }
    return default(T);
}

You should create a Dictionary<Type,Type> that would associate your object's type with their DTO equivalent, so you wouldn't need any if. Then you can use the dictionary to find the types to map. ex :

//This should be instanciated wherever you want, but try to do it only once.
//The dictionary should be static
dictionary = new Dictionary<Type,Type>();
dictionary.Add(typeof(File),typeof(FileDTO));
//etc..

public T GetContentByNodeIdSync<T>(Guid nodeId)
{
    var data = m_CMSCatalog.GetContentByNodeId(nodeId);
    Type dtoType;
    bool mapExists = dictionary.TryGetValue(typeof(T), out dtoType); //To make sure you have an existing map in your dictionary.

    if(mapExists)
        return (T)Mapper.Map(data, dtoType, typeof(T));

    return default(T);
}


Adding up dice rolls with constraints I have written the below code which generates 4 random, whole integer values between 1 and 6 and then saves the sum of the 3 largest values. It generates a total of 6 values this way, displays the total along with all 6 values once finished.

The order in which each value was generated must be preserved.
The total of all 6 values must be at least 75 or above.
At least 2 of the values must be 15 or more.

import java.util.Random;
import java.util.Arrays;

public class Test {
    static boolean goodRoll = false;

    public static int genAttribute() {

        Random dice = new Random();
        int[] sumArray = {dice.nextInt(6) + 1, dice.nextInt(6) + 1, dice.nextInt(6) + 1, dice.nextInt(6) + 1};
        for (int num : sumArray) {
            System.out.println(num);
        }

        int first = Integer.MIN_VALUE;
        int firstIndex = -1;
        int second = Integer.MIN_VALUE;
        int secondIndex = -1;
        int third = Integer.MIN_VALUE;

        for (int i = 0; i < sumArray.length; i++) {
            int num = sumArray[i];
            if (num > first) {
                first = num;
                firstIndex = i;
            }
        }

        for (int i = 0; i < sumArray.length; i++) {
            int num = sumArray[i];
            if (num > second && num <= first && i != firstIndex) {
                second = num;
                secondIndex = i;
            }
        }

        for (int i = 0; i < sumArray.length; i++) {
            int num = sumArray[i];
            if (num > third && num <= second && i != secondIndex && i != firstIndex) {
                third = num;
            }
        }
        System.out.println(first + " " + second + " " + third);

        return first + second + third;

    }

    public static boolean checkFinalArray(int[] checkArray) {
        int fifteenCount = 0;
        for (int z : checkArray) {
            if (z >= 15) {
                fifteenCount++;
            }
        }

        return (fifteenCount >= 2 && Arrays.stream(checkArray).sum() >= 75);
    }

    public static void main(String[] args) {

        while (!goodRoll) {
            int[] finalArray;
            finalArray = new int[6];

            for (int i = 0; i < 6; ++i) {
                finalArray[i] = genAttribute();
            }

            if (checkFinalArray(finalArray)) {
                System.out.println("sum: " + Arrays.stream(finalArray).sum());
                // Enhanced for to print each die
                for (int x : finalArray) {
                    System.out.println(x);

                }
                goodRoll = true;
            }
        }
    }

}

Can this be more efficiently written?

Document your code. In the code.
Be sure you got the specification right.
Very helpful here is giving test serious consideration early on.
• testing order in which each value was generated must be preserved
 looks a nightmare

One way to present the approach coded:
1) generate six sums
2) if this sextuple is not admissible, start over
Alternatives:
2b) while sextuple is not admissible, delete oldest sum and append a new one
  This still results in six sums generated in a row.
2c) while sextuple is not admissible, delete smallest sum and append a new one
  This still preserves the order in which each value was generated
  - but it skews the distribution.
But: What if the real requirement was
Generate six pseudo-random values with a distribution identical to the one from a procedure as sketched, with utmost efficiency
(You'd have to define efficiency.)
Name things for what they can/will be used for. Difficult to guess for (test,) genAttribute(), checkFinalArray()
Parametrise where it does not add effort
What if you next wanted seven values each from five rolls of tetrahedral dice, three over a threshold of eleven and a total of at least 42?
sometimes it pays to take a step back and try to look at the requirements specification from a different angle:
The sum of the three largest values out of four may seem to require identifying those three values.
From a distance, it looks like the total minus the minimum.

I started putting in writing what I think should do:

   /** @param nSums count of sums to return
    *  @param nDraws count of summands for each sum
    *  @param from lower bound for summands
    *  @param to_inclusive upper bound for summands
    *  @param threshold for "big enough"
    *  @param requiredCount count of sums required to be
    *                                                   "big enough"
    *  @param lowestTotal total to reach
    *
    *  @return nSums of nDraws values each
    *   but the smallest among those
    *   - if

    *    - at least requiredCount
    *               sums reach threshold and

    *    - the total is lowestTotal, at least */
    public static int[]
    sufficientTopSums(int nSums, int nDraws, int from, int to_inclusive,
        int threshold, int requiredCount, int lowestTotal) {
        // Start with a queue filled with very negative values
        // keep a total and a count of sufficiently high sums

        // check int range suffices
        assert((long)(nDraws - 1) * to_inclusive < Integer.MAX_VALUE / nSums);
        final int veryNegative = Integer.MIN_VALUE/nDraws;
        Queue<Integer> q = new ArrayDeque<>(Collections.nCopies(
            nSums, veryNegative));
        for (int total = veryNegative * nSums, sufficient = 0 ; ; ) {
            int replaced = q.remove();
            // account for value removed
            total -= replaced;
            if (threshold <= replaced)
                sufficient--;
            // generate & keep new sum
            int sum = sumIgnoringMin(nDraws, from, to_inclusive);
            q.add(sum);
            // account for new value
            if (threshold <= sum)
                sufficient++;
            if (lowestTotal <= (total += sum)
                && requiredCount <= sufficient)
                return q.stream().mapToInt(x->x).toArray();
        }
    }
    public static void main(String[] args) {
        System.out.println(Arrays.toString(
            sufficientTopSums(6, 4, 1, 6, 15, 2, 75)));
    }

    static final java.util.Random dice = new java.util.Random();
    private static final int[] NO_INTS = {};

   /** @param nDraws count of values to draw
    *  @param from lower bound for values
    *  @param to_inclusive upper bound for values
    *  @return sum of draws, excluding minimal value drawn */
    static int sumIgnoringMin(int nDraws, int from, int to_inclusive) {
        int to = to_inclusive - from + 1;
        int min = Integer.MAX_VALUE,
            sum = from * (nDraws);
        while (0 <= --nDraws) {
            int drawn = dice.nextInt(to);
            if (drawn < min)
                min = drawn;
            sum += drawn;
        }
        return sum - min - from;
    }

and stumbled upon not really knowing what representation to choose for the return value.
Oh, well, int[] and Collection<Integer> can be converted easily enough.
For lack of array rotation support, I went for a Queue<Integer>.


3-stack implementation with a single array I'm teaching myself data structures and would really appreciate some feedback on my stack implementation.

A couple of things I'm not sure if I should be doing:

creation of the array and pointer using new
style

// Implement 3 stacks with one array
#include <iostream>

class SingleArrayStacks{
    private:
        int stack_size;
        int *array;
        int *pointers;
        int get_top_position(int stack_num){
            return (stack_num * stack_num)  + pointers[stack_num];
        }

    public:
        SingleArrayStacks (int array_size = 100, int num_stacks = 3) {
            array = new int[array_size];
            pointers = new int[num_stacks];
            stack_size =  array_size / num_stacks;
            std::fill_n(pointers, num_stacks, -1);
        }

        ~SingleArrayStacks (){
            delete[] array;
            delete[] pointers;
        }

        void print_stack (int stack_num) const {
            std::cout << "Current stack state: ";
            for (int i = 0; i < sizeof(array); i++) {
                std::cout << array[i];
            }
            std::cout << std::endl;
        }

        bool is_empty(int stack_num) const {
            return pointer[stack_num] == -1;
        }

        void push (int stack_num, int val) {
            if (pointers[stack_num] > stack_size) {
                throw std::runtime_error("Stack is full");
            } else {
                array[get_top_position(stack_num) + 1] = val;
                pointers[stack_num]++;
            }
        }

        int pop(int stack_num){
            if (is_empty(stack_num) {
                throw std::runtime_error("Stack is empty");
            } else {
                int val = array[get_top_position(stack_num)];
                array[get_top_position(stack_num)] = NULL;
                pointers[stack_num]--;
                return val;
            }
        }

        int top(int stack_num){
            if (is_empty(stack_num) {
                throw std::runtime_error("Stack is empty");
            } else {
                return array[get_top_position(stack_num)];
            }
        }
};

Compiler errors:

You code did not compile under Clang! It would not compiler anywhere for that matter, as it has a few syntax errors:

In method is_empty(), pointer is not declared. It should be pointers (plural).
In both pop() and top() methods, this line is broken:

if (is_empty(stack_num) {
//                    ^-------- Missing a `)` here!

Compiler warnings:

Always compile with warnings turned on and set them to the highest level practical.
If you have the habit of ignoring warnings, try compiling with "warnings as errors" (-Werror for Clang and GCC) to force yourself into fixing them.

That said, your code only produced one warning, after the errors above where fixed:

array[get_top_position(stack_num)] = NULL;
//                                   ^^^^--------- implicit conversion of NULL constant to 'int'

NULL is not the same as int. In fact, an implementation is free to define NULL to whatever, so don't assume it will be convertible to an integer on all compilers/platforms.

Code review:

Now if I get the idea behind your code, you intend to have a single array with several stack
sharing this array. Your implementation doesn't seem to be doing that correctly. I could not test it thoroughly, but the helper array pointers, which doesn't store pointers by the way, seems questionable. The method get_top_position() also seems a bit contrived to me. print_stack() is broken, so I couldn't print the stacks to validate the state of the structure.

I would suggest that you attempt to simplify this by storing actual pointers (or indexes) to the sub-array inside the main array. Then you won't need any additional offset calculation once pushing/poping. You also have the advantage that all stacks share the same size.

               main array of ints:
    +--+--+--+--+--+--+--+--+--+--+--+--+----
    |  |  |  |  |  |  |  |  |  |  |  |  | ...
    +--+--+--+--+--+--+--+--+--+--+--+--+----
    |           |           |           |
    V           V           V           V
    +-----------+-----------+-----------+----
    |  stack 0  |  stack 1  |  stack 2  | ...
    +-----------+-----------+-----------+----
    |           |           |           |
    V           V           V           V
pointer[0]  pointer[1]  pointer[2]  pointer[N] ...

Overall code improvements:

sizeof misuse: This is not doing what you expect:

for (int i = 0; i < sizeof(array); i++) {

sizeof is a compile-time operator, so it cannot infer the size of dynamically allocated arrays, only arrays in which the size is known at compile-time (e.g.: char buf[128]) can have the size inferred with sizeof. You must keep a member variable with the size of the stacks and another with the main array's.
top() only inspect data, so it should also be a const method.
Simplify if-else logic where it is not needed. Example:

if (is_empty(stack_num)) {
    throw std::runtime_error("Stack is empty");
} else {
    return array[get_top_position(stack_num)];
}

No need to keep the if-else when both paths will exit the function.

if (is_empty(stack_num)) {
    throw std::runtime_error("Stack is empty");
}
return array[get_top_position(stack_num)];

Instead of hardcoding cout in print_stack(), you could take the output parameter as an std::ostream &. However, such function is asking to become an output stream operator.
Manual memory management (with new/delete) is a dated practiced in C++. Even for custom containers, the use of smart pointers is strongly advised. I would replace the raw pointers by at least a std::unique_ptr or even better a std::vector.


Sending SMS through twilio from play framework I am trying to send SMS using Twilio with Scala 2.10 in Playframework 2.2, but this code is looking odd to me, maybe due to lots of conditions.  I'm sure it needs some important reviews.

val invalidEX = List(21211, 21614, 21608, 30006, 30005, 21604, 21601, 14101)
val reachEX = List(21612, 30004)

def sendSms = Action { implicit request =>
    val smsTo = request.body.asFormUrlEncoded.get("number").head
    val deviceId = request.body.asFormUrlEncoded.get("deviceId").head
    try {
      if(smsTo.length<=6||smsTo.length>=18||deviceId.length>=150){
       Ok(write(Map("result" -> "error")))
      }else{
      if (smsNeeded(smsTo)) {
        if (numberBlocked(smsTo)) {
            if (!todayBlocked(smsTo)) {
              var code = random6Digit
              val appLang =request.acceptLanguages(0).code.toString.splitAt(2)._1
              var body = ""
              appLang.equals("en") match {
                case true =>
                  body = Messages("sms_body", "\n", code)(Lang(appLang))
                case false =>
                  body = Messages("sms_body", "\n", code)(Lang(appLang)) + "\n" + Messages("sms_body", "\n", code)(Lang("en"))
              }
              TwilioAPI.sendSMS(smsTo, body)
              Future {todayEntry(smsTo) }
              Ok(Json.obj("response" -> "success"))
            } else
              Ok(Json.obj("response" -> "temporaryblock"))
        } else
          Ok(Json.obj("response" -> "permanentblocked"))
      } else {
        Ok(Json.obj("response" -> "regular"))
      }
     }
    } catch {
      case twilioEx: TwilioRestException =>
        if (invalidEX.contains(twilioEx.getErrorCode))
          Ok(Json.obj("response" -> "invalidNumber"))
        else if (reachEX.contains(twilioEx.getErrorCode))
          Ok(Json.obj("response" -> "unreachableNumber"))
        else {
          Future { models.LogFile.errorLogs(Json.obj("route" -> request.tags, "post" -> request.body.asFormUrlEncoded.toString, "address" -> request.remoteAddress, "error" -> twilioEx).toString) }
          Ok(Json.obj("response" -> "error"))
        }
      case e: Exception =>
        println(e)
        Future { models.LogFile.errorLogs(Json.obj("route" -> request.tags, "post" -> request.body.asFormUrlEncoded.toString, "address" -> request.remoteAddress, "error" -> e.toString).toString) }
        Ok(Json.obj("response" -> "error"))
    }
  }

As I'm new to scala, I don't feel I could generate the appropriate code, but I wanted to make a couple points.
First, your method is doing way to much.  I see validation, I see messing with a request object, I see sending the SMS, I see response generation.  From my point of view, when looking at this method, you can't tell what is going on without a lot of effort.  So my recommendation would be to add more methods.  If I were writing this, I would have an outer method that abstracts away the HTTP portions of your code
sendSms should pull the string value from the request and then delegate to parseSmsPhoneNumber (or something like that) to perform the logic of validating the string.  My second suggestion with this method is that it not return a string, but a type safe object.  Now that you have a type safe smsPhoneNumber, you could write another method that does the status checks: is the number blocked?, ...  Now that we know everything is good, create a method that takes the smsPhoneNumber and actually sends it.  The last bit I would emphasis is that the JSON response generation should happen within sendSms.  The other methods will return values types or throw exceptions so signal when bad things happen.  Keep all of you HTTP related code isolated to sendSms.
Update:
Below is my take at trying to break your code apart.  It is completely untested and there is almost certainly no way that it compiles, but I think it does a reasonable job of demonstrating how you could break things down.  So, just think of it as pseudo code that looks similar to scala, but not actually scala.
First, note that I convert things from strings to a type safe type as soon as I possibly can with parseSmsPhoneNumber() and parseSmsDeviceId().  Note that they return an option instead of the actual types.  You probably could throw exceptions as well, but I preferred this.  The next thing I did was create a bunch of case classes.  This is to abstract out the status of situations from happening.  There could be a different way to do it, but I liked using case classes because they seem to work with within matches.  Next I isolate all of the sending of the sms to withing doSendSms; notice how the exceptions stay within this method.  There really isn't any benefit of having the API specific exceptions spill out.  If you ever need to change service used to send SMS, then you would only need to modify this one method.  Lastly, notice how all of the HTTP related objects (request and response) are isolated to within sendSms.  Perhaps you want to do a similar process but without being attached to a request (such as a timed job), with the HTTP information isolated, then this is nearly trivial.
I agree that my pseudo code below still needs more work (i don't like the if/else plus two matches in sendSms, I feel it should be "flatter"), but this is the best I can do right now.  Hopefully, some of my points make more sense with some pseudo code.
Completely Un-Tested/UnCompiled Code
val invalidEX = List(21211, 21614, 21608, 30006, 30005, 21604, 21601, 14101)
val reachEX = List(21612, 30004)

case class SmsPhoneNumber(value: String)

def parseSmsPhoneNumber(valueAsString: String): Option[SmsPhoneNumber] = {
  if(valueAsString.length<=6||valueAsString.length>=18) {
    return Some(SmsPhoneNumber(valueAsString))
  } else {
    return None
  }
}

case class SmsDeviceId(value: String)

def parseSmsDeviceId(valueAsString: String): Option[SmsDeviceId] = {
  if(valueAsString.length<=8||valueAsString.length>=150) {
    return Some(SmsDeviceId(valueAsString))
  } else {
    return None
  }
}

sealed trait SmsPhoneNumberStatus
case class SmsNotNeeded extends SmsPhoneNumberStatus
case class NumberBlocked extends SmsPhoneNumberStatus
case class NumberTemporarilyBlocked extends SmsPhoneNumberStatus
case class Valid extends SmsPhoneNumberStatus

def checkSmsPhoneNumberStatus(smsPhoneNumber:SmsPhoneNumber) :SmsPhoneNumberStatus = {
  if (!smsNeeded(smsPhoneNumber)) {
    return SmsNotNeeded
  } else if (!numberBlocked(smsPhoneNumber)) {
    return NumberBlocked
  } else if (todayBlocked(smsPhoneNumber)) {
    return NumberTemporarilyBlocked
  } else {
    return Valid
  }
}

def buildMessageBody(code:String,appLang:String):String = {
  if (appLang.equals("en"))  {
    return Messages("sms_body", "\n", code)(Lang(appLang))
  } else {
    return Messages("sms_body", "\n", code)(Lang(appLang)) + "\n" + Messages("sms_body", "\n", code)(Lang("en"))
  }
}

sealed trait SentSmsResult
case class InvalidNumber extends SentSmsResult
case class UnreachableNumber extends SentSmsResult
case class Error(message:String) extends SentSmsResult
case class Success extends SentSmsResult

def doSendSms(recipient:SmsPhoneNumber,body:String):SentSmsResult = {
  try{
    TwilioAPI.sendSMS(recipient, body)
  } catch {
      case twilioEx: TwilioRestException =>
        if (invalidEX.contains(twilioEx.getErrorCode))
          return InvalidNumber
        else if (reachEX.contains(twilioEx.getErrorCode))
          return UnreachableNumber
        else {
          return Error(twilioEx)
        }
      case e: Exception =>
          return Error(e.toString)
    }
}

def sendSms = Action { implicit request =>
    val smsPhoneNumber = parseSmsPhoneNumber(request.body.asFormUrlEncoded.get("number").head)
    val smsDeviceId = parseSmsDeviceId(deviceId)//not sure where devideId came from

    if(smsPhoneNumber.isEmpty() || smsDeviceId.isEmpty()) {
      Ok(write(Map("result" -> "error")))
    } else {
      checkSmsPhoneNumberStatus(smsPhoneNumber.get) match {
        case SmsNotNeeded => Ok(Json.obj("response" -> "regular"))
        case NumberBlocked => Ok(Json.obj("response" -> "permanentblocked"))
        case NumberTemporarilyBlocked => Ok(Json.obj("response" -> "temporaryblock"))
        case Valid => {
          doSendSms(smsPhoneNumber,buildMessageBody(random6Digit,request.acceptLanguages(0).code.toString.splitAt(2)._1 )) match {
            case InvalidNumber =>  {
               Ok(Json.obj("response" -> "invalidNumber"))
            }
            case UnreachableNumber =>  {
               Ok(Json.obj("response" -> "unreachableNumber"))
            }
            case e:Error =>  {
              Future { models.LogFile.errorLogs(Json.obj("route" -> request.tags, "post" -> request.body.asFormUrlEncoded.toString, "address" -> request.remoteAddress, "error" -> e.message).toString) }
              Ok(Json.obj("response" -> "error"))
            }
            case Success =>  {
              Future {todayEntry(smsTo) }
              Ok(Json.obj("response" -> "success"))
            }
          }
        }
      }
    }
  }


LINQ Query returning all original objects I'm just refactoring some code I've come across whilst fixing a bug, but just wanted a quick sanity check to make sure I'm not missing any reason for keeping what I'm going to remove.

The current code:

uxButton.Enabled = ((from a in actions select a).Distinct().Count() == 1);

There really doesn't seem to be a need for the LINQ query, so:

uxButton.Enabled = actions.Distinct().Count() == 1;

Should do the trick, right?

As the other answers stated your given code does do the same thing, but could give performance issues for big collections since the entire collection is traversed when calling Count().

The following code should solve this:

var distinct = actions.Distinct();
uxButton.Enabled = distinct.Take( 2 ).Count() == 1;

Perhaps you could turn this into an extension method:

uxButton.Enabled = actions.Distinct().CountOf( 1 );

It seemed useful, so I added it to my library, along with a unit test.

/// <summary>
///   Returns whether the sequence contains a certain amount of elements.
/// </summary>
/// <typeparam name = "T">The type of the elements of the input sequence.</typeparam>
/// <param name = "source">The source for this extension method.</param>
/// <param name = "count">The amount of elements the sequence should contain.</param>
/// <returns>
///   True when the sequence contains the specified amount of elements, false otherwise.
////</returns>
public static bool CountOf<T>( this IEnumerable<T> source, int count )
{
    Contract.Requires( source != null );
    Contract.Requires( count >= 0 );

    return source.Take( count + 1 ).Count() == count;
}


Identifying the closest player to an internal 2D grid I've written a function that returns which player is closer to a given 2D grid within a larger 2D grid. I would like to make the function shorter (in LOC) and better. I would appreciate any advice on this topic.
it gets location for both players(x and y) and same for the carpet(the smaller grid), and than calculate the distance b/w each player to the carpet. the reason it takes so much if's is because i'm calculating x from x and y from y, and if the player is on the far side of x/y i have to add size to compassion. that's why i have an if for every corner plus if player is in the range of y/x
public static int getWhoIsCloser(
      int xFirstPlayer,
      int yFirstPlayer,
      int xSecondPlayer,
      int ySecondPlayer,
      int xCarpet,
      int yCarpet,
      int size) {

    size = size - 1;
    int xFirstPlayerProximity = 0;
    int yFirstPlayerProximity = 0;
    int xSecondPlayerProximity = 0;
    int ySecondPlayerProximity = 0;
    int firstPlayerResult;
    int secondPlayerResult;

    if (xFirstPlayer >= xCarpet && xFirstPlayer <= xCarpet + size) {
      yFirstPlayer -= (yCarpet + size);
      firstPlayerResult = Math.abs(yFirstPlayer);
    } else if (yFirstPlayer >= yCarpet && yFirstPlayer <= yCarpet + size) {
      xFirstPlayer -= (xCarpet + size);
      firstPlayerResult = Math.abs(xFirstPlayer);
    } else {
      if (xFirstPlayer < xCarpet && yFirstPlayer < yCarpet) {
        xFirstPlayerProximity = xFirstPlayer - xCarpet;
        yFirstPlayerProximity = yFirstPlayer - yCarpet;
      } else if (xFirstPlayer < xCarpet && yFirstPlayer > yCarpet) {
        xFirstPlayerProximity = xFirstPlayer - xCarpet;
        yFirstPlayerProximity = yFirstPlayer - (yCarpet + size);
      } else if (xFirstPlayer > xCarpet && yFirstPlayer < yCarpet) {
        xFirstPlayerProximity = xFirstPlayer - (xCarpet + size);
        yFirstPlayerProximity = yFirstPlayer - yCarpet;
      } else if (xFirstPlayer > xCarpet && yFirstPlayer > yCarpet) {
        xFirstPlayerProximity = xFirstPlayer - (xCarpet + size);
        yFirstPlayerProximity = yFirstPlayer - (yCarpet + size);
      }
      firstPlayerResult = Math.abs(xFirstPlayerProximity) + Math.abs(yFirstPlayerProximity);
    }
    if (xSecondPlayer >= xCarpet && xSecondPlayer <= xCarpet + size) {
      ySecondPlayer -= (yCarpet + size);
      secondPlayerResult = Math.abs(ySecondPlayer);
    } else if (ySecondPlayer >= yCarpet && ySecondPlayer <= yCarpet + size) {
      xSecondPlayer -= (xCarpet + size);
      secondPlayerResult = Math.abs(xSecondPlayer);
    } else {
      if (xSecondPlayer < xCarpet && ySecondPlayer < yCarpet) {
        xSecondPlayerProximity = xSecondPlayer - xCarpet;
        ySecondPlayerProximity = ySecondPlayer - (yCarpet);
      } else if (xSecondPlayer < xCarpet && ySecondPlayer > yCarpet) {
        xSecondPlayerProximity = xSecondPlayer - (xCarpet);
        ySecondPlayerProximity = ySecondPlayer - (yCarpet + size);
      } else if (xSecondPlayer > xCarpet && ySecondPlayer < yCarpet) {
        xSecondPlayerProximity = xSecondPlayer - (xCarpet + size);
        ySecondPlayerProximity = ySecondPlayer - yCarpet;
      } else if (xSecondPlayer > xCarpet && ySecondPlayer > yCarpet) {
        xSecondPlayerProximity = xSecondPlayer - (xCarpet + size);
        ySecondPlayerProximity = ySecondPlayer - (yCarpet + size);
      }
      secondPlayerResult = Math.abs(xSecondPlayerProximity) + Math.abs(ySecondPlayerProximity);
    }

    if (firstPlayerResult > secondPlayerResult) {
      return 2;
    } else if (firstPlayerResult < secondPlayerResult) {
      return 1;
    } else {
      return 0;
    }
  }

You are exactly duplicating the code for checking the distance for player 1 and player 2. You could move that code into a separate getDistanceToCarpet function, and have the getWhoIsCloser function call that twice.
If I understand your code correctly, you seem to be using so-called taxicab distance, meaning the total distance is equal to the X distance plus the Y distance (this is perfectly valid, as long as you're doing it on purpose). This is convenient, because it lets you separately calculate the X and Y distances and then just add them together.
Let's look at just the X distance for now. We can see that if X is on the carpet, the distance is 0. If is is less than xCarpet, it's equal to xCarpet - xPlayer, and if it's more than xCarpet + size the distance is equal to xPlayer - (xCarpet + size).
And hey, we're doing the same exact thing for Y. We could just copy-paste it and replace all the xes with ys, or we could break it out into another function. The copy-paste approach can be error-prone, so I'd recommend more functions.

Put all that together, it might look a little something like this:
public static int singleAxisDistance(int playerCoordinate, int carpetCoordinate, int carpetSize) {
    if (playerCoordinate < carpetCoordinate) {
        return carpetCoordinate - playerCoordinate;
    } else if (playerCoordinate < carpetCoordinate + carpetSize - 1) {
        return 0;
    } else {
        return playerCoordinate - (carpetCoordinate + carpetSize - 1);
    }
}

public static int getDistanceToCarpet(int xPlayer, int yPlayer, int xCarpet, int yCarpet, int sizeCarpet) {
    int xDistance = getSingleAxisDistanceToCarpet(xPlayer, xCarpet, sizeCarpet);
    int yDistance = getSingleAxisDistanceToCarpet(yPlayer, yCarpet, sizeCarpet);

    return xDistance + yDistance;
}

public static int getWhoIsCloser(
      int xFirstPlayer,
      int yFirstPlayer,
      int xSecondPlayer,
      int ySecondPlayer,
      int xCarpet,
      int yCarpet,
      int size) {

    int firstPlayerResult = distanceToCarpet(xFirstPlayer, yFirstPlayer, xCarpet, yCarpet, size);
    int secondPlayerResult = distanceToCarpet(xSecondPlayer, ySecondPlayer, xCarpet, yCarpet, size);

    if (firstPlayerResult > secondPlayerResult) {
        return 2;
    } else if (firstPlayerResult < secondPlayerResult) {
        return 1;
    } else {
        return 0;
    }
}

If I were to look past that function, I might eventually want to bundle the parameters into position and carpet objects, and put the distance calculations in their classes. Passing a single object is usually neater than passing multiple primitive values, and tends to have less of a risk of getting the parameters confused. And while I admit it's a matter of opinion, I do think this looks nicer on some level:
public static int getWhoIsCloser(
      Point firstPlayerPosition,
      Point secondPlayerPosition,
      Carpet carpet) {

    int firstPlayerDistance = firstPlayerPosition.getDistanceTo(carpet);
    int secondPlayerDistance = secondPlayerPosition.getDistanceTo(carpet);

    if (firstPlayerDistance > secondPlayerDistance) {
        return 2;
    } else if (firstPlayerDistance < secondPlayerDistance) {
        return 1;
    } else {
        return 0;
    }
}
```


Using a compiler specified on the command line or automatically detected Here is part of my build system.

guessCompilers :: Options -> IO Options
guessCompilers options =  foldl (>>=) (return options) modifiers where
  modifiers =
    [guessMetapost
     -- guessAsymptote,
     -- guessTex,
     -- guessLatex,
     -- guessXelatex
    ]
guessMetapost :: Options -> IO Options
guessMetapost opts = if isJust $ optMetaPost opts
                         then
                           putStrLn $ printf "using enforced Metapost compiler: %s" (fromJust $optMetaPost opts)
                           >> return opts
                         else do
                           cc <- compiler Metapost.interface
                           if isJust cc then putStrLn $ printf "found Metapost compiler: %s" (fromJust cc)
                                             else putStrLn "found Metapost compiler: none"

Compiler can be spectified by cmd args or can be guessed. But double checking for Nothing is not cool in my opinion. Also, I heard fromJust is evil. Any suggestions to improve my code?

Pattern match instead of using isJust and fromJust. (You could use maybe instead of pattern matching, but I think pattern matching is clearer in this case.)

This eliminates the possibility of forgetting to ensure a value is a Just before calling fromJust on it.

guessMetapost :: Options -> IO ()
guessMetapost opts
   = case optMetaPost opts of
         Just mcc -> putStrLn $ printf "using enforced Metapost compiler: %s" mcc
         Nothing -> do
           cc' <- compiler Metapost.interface
           case cc' of
               Just cc -> putStrLn $ printf "found Metapost compiler: %s" cc
               Nothing -> putStrLn "found Metapost compiler: none"

(Your code wasn't consistently returning any options, so I've stripped that bit out.)


Effective 3d array transposition with R/C++ (Rcpp) Task is reshape 3d array from [row, col, slice] to [slice,row,col]. I tried implement base::aperm analog with Rcpp.

// [[Rcpp::export]]
Rcpp::NumericVector array_perm(const Rcpp::NumericVector& x) {
    if (Rf_isNull(x.attr("dim"))) {
        throw std::runtime_error("'x' does not have 'dim' attibute.");
    }
    Rcpp::Dimension d = x.attr("dim");
    if (d.size() != 3) {
        throw std::runtime_error("'x' must have 3 dimensions.");
    }
    std::size_t n = d[2];
    std::size_t n_vec = d[0] * d[1];
    std::size_t n_out = n_vec * n;
    Rcpp::NumericVector res = Rcpp::no_init(n_out);
    std::size_t ind_from = 0;
    for (std::size_t i = 0; i < n; ++i) {
        std::size_t ind_to = i;
        for (std::size_t j = 0; j < n_vec; ++j) {
            res[ind_to] = x[ind_from];
            ind_to += n;
            ind_from += 1;
        }
    }
    res.attr("dim") = Rcpp::Dimension(d[2], d[0], d[1]);
    return res;
}

How can I improve it?

For testing code:

# Observations
n <- 1000
# Dimension
d <- 100
# Array
a <- replicate(n, matrix(seq_len(d * d), nrow = d, ncol = d))
# Desired result
res <- aperm(a, c(3, 1, 2))
res

Small benchmark current variant of the code:

b <- bench::mark(aperm(a, c(3, 1, 2)), array_perm(a))
b[, c("expression", "min", "median", "max", "itr/sec")]
#>   expression                min   median      max `itr/sec`
#>   <chr>                <bch:tm> <bch:tm> <bch:tm>     <dbl>
#> 1 aperm(a, c(3, 1, 2))   84.9ms   85.1ms   85.5ms     11.7
#> 2 array_perm(a)         124.8ms  125.2ms  127.2ms      7.96

RcppArmadillo solution

// [[Rcpp::export]]
arma::Cube<double> array_perm2(const arma::Cube<double>& x) {
    std::size_t rows = x.n_rows;
    std::size_t cols = x.n_cols;
    std::size_t slices = x.n_slices;
    arma::Cube<double> res(slices, rows, cols);
    for(std::size_t i = 0; i < rows; ++i) {
        for(std::size_t j = 0; j < cols; ++j) {
            for(std::size_t k = 0; k < slices; ++k) {
                res(k, i, j) = x(i, j, k);
            }
        }
    }
    return res;
}

Benchmark:

  expression                min   median      max `itr/sec`
  <chr>                <bch:tm> <bch:tm> <bch:tm>     <dbl>
1 aperm(a, c(3, 1, 2))   85.8ms   86.4ms   87.7ms     11.6
2 array_perm(a)         116.1ms  127.3ms  129.6ms      8.08
3 array_perm2(a)        217.4ms  219.7ms  222.1ms      4.55

If you can change the signature, to directly get cols, rows and slices count, you will not have to check for their validity.

Rcpp::NumericVector array_perm(const Rcpp::NumericVector& input,
                               std::size_t rows, std::size_t cols, std::size_t slices);

Otherwise, if you can change the error management, I think you'll get a speed boost. Exceptions handling come with a cost. Maybe return an empty vector? I don't know R , so I don't know possibilities.

You can also try to flattening your loops, here you have multiples options:

With the computations into output indexing

Rcpp::NumericVector array_perm(const Rcpp::NumericVector& input, std::size_t rows, std::size_t cols, std::size_t slices) {
    // Think about the error management here...
    auto output = Rcpp::NumericVector(Rcpp::no_init(10));

    auto rc = rows * cols;
    auto size = rc * slices;
    for (std::size_t i = 0; i < size; ++i) {
        output[i / rc + i % rc * slices] = input[i];
    }
    return output;
}

With the computations into intput looking

//...
    for (std::size_t i = 0; i < size; ++i) output[i] = input[i/slices + i % slices * rc];
//...

Or in reverse order

//...
    while (size--) output[size] = input[size/slices + size % slices * rc];
//...

Or a mix

//...
    while (size--)  output[size / rc + size % rc * slices] = input[size];
//...

Or even a range-based for loop

//...
    std::size_t i = 0;
    for (auto e : input) {
        output[i / rc + i % rc * slices] = e;
        ++i;
    }
//...

PS: Did you tried with another contiguous storage type? (std::vector, plain old C array, ...)

PPS: I don't have R environment, so I only tested transposition algorithms with c++

Edit:

Two other way:

//...
    for(std::size_t i = 0, j = 0; i < size; ++i, j+=rc) {
        if (size <= j) j -= size - 1;
        output[i] = input[j];
    }
//...
// or
//...
    for(std::size_t i = size, j = i-1; i--; j -= rc) {
        if (size < j)  j += size-1;
        output[i] = input[j];
    }
//...


Database select script Is there any way I could improve this script, such as by writing it in fewer lines (more efficient)? I'm very interested in keeping my code dry and fast! Also, if there is a way to make it more dynamic don't hesitate to tell me!

  <?php
    /* Connect to an MYSQL database Using credentials and PDO(PHP DATA OBJECT) */
    $dsn = 'mysql:host=**;dbname=**';
    $user = '**';
    $password = '**';
    $connection = new PDO($dsn, $user, $password);
    $table = $_POST['table'];
    $querySQL = "";
    $datum = $_POST['datum'];

    //SELECT content,author FROM quote LIMIT 10
    //INSERT INTO birthday (date,name) VALUES ('2012-05-05','henk')

    switch ($table) {
        case "quote":
            $querySQL = "SELECT content,author FROM quote WHERE datum = ? LIMIT 10";
            $stmt = $connection->prepare($querySQL);
            $stmt->execute(array($datum));
            break;
        case "birthday":
            $querySQL = "SELECT date,name FROM birthday LIMIT 10 WHERE datum = ? LIMIT 10";
            $stmt = $connection->prepare($querySQL);
            $stmt->execute(array($datum));
            break;
        case "facts":
            $querySQL = "SELECT content from facts WHERE datum = ? AND category = ? LIMIT 10";
            $categorie = $_POST['categorie'];
            $stmt = $connection->prepare($querySQL);
            $stmt->execute(array($datum, $categorie));
            break;
        case "lifehacks":
            $querySQL = "SELECT content from lifehacks WHERE datum = ? LIMIT 10";
            $stmt = $connection->prepare($querySQL);
            $stmt->execute(array($datum));
            break;
    }
    if(isset($stmt)) {
        $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
        $json = json_encode($results);
        echo $json;
    }
    ?>

$querySQL = "SELECT ";
$parameters = [$datum];
switch ($table) {
    case "quote":
        $querySQL .= "content, author FROM quote WHERE datum = ?";
        break;
    case "birthday":
        $querySQL .= "date, name FROM birthday WHERE datum = ?";
        break;
    case "facts":
        $querySQL .= "content FROM facts WHERE datum = ? AND category = ?";
        $parameters[] = $_POST['categorie'];
        break;
    case "lifehacks":
        $querySQL .= "content FROM lifehacks WHERE datum = ?";
        break;
}
$querySQL .= " LIMIT 10";
$stmt = $connection->prepare($querySQL);
$stmt->execute($parameter);

Perhaps you're looking for something such as this. You had lots of repetition in your code, and so I basically applied the DRY rules to your code. It could still use a lot of work and I'm sure there's other approaches, but this might help you kickstart the process!

Another way to possibly help improve your code would be to separate the logic, database access, and your echos. You've probably heard of frameworks and such, and you might want to start looking into your options. It will keep your code separated, and while maybe not shorter, it will be much neater!


Laravel user permission system I wanted to create a simple and easy to use permissions system. The ones I've found on the Internet would need to attach every permission to a route manually (e.g. Entrust).

My idea is to build a permission name out of the current action, so for example method 'store' in 'TestController' becomes 'test.store' permission.

Is it a good approach? I couldn't find anything similiar on the web.

class SecuredController extends Controller {

    /**
     * @var array
     * unguarded actions (method names)
     */
    protected $unguarded = [];

    /**
     * @var array
     * actions (method names) that need csrf token checked
     */
    protected $csrfguarded = [];

    private $permission;

    public function getCurrentPermission() {
        return $this->permission;
    }

    public function callAction($method, $parameters) {
        if(! $this->canAccessCurrentAction()) {
            return $this->accessDenied();
        }

        return parent::callAction($method, $parameters);
    }

    /**
     * @param string $action e.g. TestController@store
     *
     * @return bool
     * @throws \Illuminate\Session\TokenMismatchException
     */
    public function canAccessAction($action) {
        /**
         * split $action(e.g. TestController@store) into two parts
         * and build a permission name (e.g. test.store) and check for access
         */

        list($controller, $method) = explode('@', $action);

        if(in_array($method, $this->unguarded, true)) {
            return true;
        }

        if(in_array($method, $this->csrfguarded, true)
           && Session::token() !== Input::get('_token'))
        {
            throw new Illuminate\Session\TokenMismatchException;
        }

        if(! Auth::check()) {
            return false;
        }

        $this->permission = $this->buildPermissionName($controller, $method);

        if(Auth::getUser()->capable($this->permission)) {
            return true;
        }

        return false;
    }

    public function canAccessCurrentAction() {
        return $this->canAccessAction( \Route::getCurrentRoute()->getActionName());
    }

    public function buildPermissionName($controller, $method) {
        return strtolower(
            substr(
                $controller,
                strrpos($controller, '\\'),
                - 10 // 'controller' word
            ) . '.' . $method
        );
    }

    /**
     * Override it!
     */
    public function accessDenied() {
        if(Request::ajax()) {
            return Response::make('You cannot access this!', 403);
        }

        return Response::make('You cannot access this!', 403);
    }
}

The capable method of User:

public function capable($neededPermission) {
    foreach($this->getPermissions() as $permission) {
        if(substr($permission, -1) === '*') {
            $permission = substr($permission, 0, -1);

            if(startsWith($neededPermission, $permission)) {
                return true;
            }
        }
        elseif($permission === $neededPermission) {
            return true;
        }
    }

    return false;
}

I see a lot of if-else statements that could be improved upon.

Ones like these for example, are returning a boolean variable depending on an if-else statement with nothing else inside.

In those cases you can return boolean values directly.

  if(in_array($method, $this->unguarded, true)) {
      return true;
  }

into:

return (in_array($method, $this-unguarded, true));

The following code does the same thing for both 'cases', meaning that no matter what 'Request::ajax()' is, the same result will be given:

public function accessDenied() {
    if(Request::ajax()) {
        return Response::make('You cannot access this!', 403);
    }

    return Response::make('You cannot access this!', 403);
}

Which could simply be turned into:

public function accessDenied() {
    return Response::make('You cannot access this!', 403);
}

Your usage of the following code really bothers me, and I believe it could do with refactoring:

return strtolower(
        substr(
            $controller,
            strrpos($controller, '\\'),
            - 10 // 'controller' word
        ) . '.' . $method
    );


Insert new row to a QTableView by double-clicking the last row Recently I was experimenting with QTableViews and I wanted to create something where I can add a new row to a table without having any additional button/menu item outside the table. I achieved this by adding a single item to the view's model and set that not editable. Then if a double-click happens on the table I check if it was on the last item. IF that is true I just add a new item before the last so my special item will be the last row every time.

Here is a minimal example which works:

#include <QApplication>
#include <QStandardItem>
#include <QStandardItemModel>
#include <QTableView>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    QTableView tableView;
    QStandardItemModel model{ 0, 1 };
    QStandardItem insertRow{ "<Click to add new item>" };
    insertRow.setEditable(false);

    tableView.setModel(&model);
    model.insertRow(0, &insertRow);

    QApplication::connect(&tableView, &QTableView::doubleClicked,
            [&model](const QModelIndex index)
    {
        int rowCount = model.rowCount();
        if (index.row() == rowCount - 1)
            model.insertRow(rowCount - 1, new QStandardItem{ "New item" });
    });

    tableView.show();

    return a.exec();
}

Is there a more proper way to implement this? Am I doing it right or this functionality is built into the Qt framework and I completely missed?

Your answer is a good one, but it has that non-editable last row hanging around. If you want to make the extra row editable, you can do as shown here. The idiom of hitting a return in the current last row that produces an empty row, is a standard one.

I don't believe there is a built-in mechanism in Qt.

A variation of the approach found in the above link

In my app, I use a slightly different approach, and thought I would share it here. For convenience, I summarize both approaches here.

In the answer at the above link, both MyTableModel and MyBlankRowModel are derived from QAbstractTableModel, and the former is set as a sourceModel in the latter. This idiom implies that all QAbstractTableModel methods overridden in MyTableModel must be re-implemented in MyBlankRowModel, mostly forwarding to the MyTableModel methods, with exceptions as noted in that answer. This approach can be cumbersome if a large number of QAbstractTableModel methods are overridden in MyTableModel as is the case in my app.

Therefore I derive MyBlankRowModel from MyTableModel, only override a few methods: rowCount() returning MyTableModel::rowCount() + 1; data(...) and setData(...) to handle the row buffer. This offers the flexibility that MyTableModel can be designed to handle a complex model, and nothing in MyBlankRowModel has to change! It also simplifies the view interaction since I simply do qTableView->setModel(myBlankRowModel).


Switching some text labels when the first image of a carousel is active Is there any way I can simplify this inefficient piece of JavaScript?

$(function () {
    var $carousel = $('#carousel');
    var $switch = $('#switch');
    var $header = $('#header');
    var $submit = $('#submit');

    $carousel.bind('slid', function() {
        var index = $('#carousel .item').index($('#carousel .carousel-inner .active'));
        if (index == 0) {
            $header.text('Sign In');
            $switch.text('Sign Up');
            $submit.text('Sign In');
            $submit.attr('form', 'sign_in');
        } else {
            $header.text('Sign Up');
            $switch.text('Sign In');
            $submit.text('Sign Up');
            $submit.attr('form', 'sign_up');
        }
    });
});

You could do this:

$(function () {
    var $carousel = $('#carousel');
    var $switch = $('#switch');
    var $headerSubmit = $('#header, #submit');
    var $submit = $('#submit');
    var text_strings = [ 'Sign In', 'Sign Up' ];
    var form_strings = [ 'sign_in', 'sign_up' ];

    $carousel.bind('slid', function() {
        var index = $('#carousel .item').index($('#carousel .carousel-inner .active'));
        var sign_in = (index == 0);
        $headerSubmit.text(text_strings[sign_in ? 1 : 0]);
        $switch.text(text_strings[sign_in ? 0 : 1]);
        $submit.attr('form', form_strings[sign_in ? 1 : 0]);
    });
});

If you want to reduce the lines of code (with a slight negative impact to performance if this function gets called a lot), you could do this:

$(function () {
    var text_strings = [ 'Sign In', 'Sign Up' ];
    var form_strings = [ 'sign_in', 'sign_up' ];

    $('#carousel').bind('slid', function() {
        var index = $('#carousel .item').index($('#carousel .carousel-inner .active'));
        var sign_in = (index == 0);
        $('#header, #submit').text(text_strings[sign_in ? 1 : 0]);
        $('#switch').text(text_strings[sign_in ? 0 : 1]);
        $('#submit').attr('form', form_strings[sign_in ? 1 : 0]);
    });
});


Associating a string with a derived class I am using the following code to get a string that is associated with the class of an instance:

std::string gate =
    dynamic_cast<AND*>(pComponent) != nullptr ? "AND" :
    dynamic_cast<NAND*>(pComponent) != nullptr ? "NAND" :
    dynamic_cast<NOR*>(pComponent) != nullptr ? "NOR" :
    dynamic_cast<NOT*>(pComponent) != nullptr ? "NOT" :
    dynamic_cast<OR*>(pComponent) != nullptr ? "OR" :
    dynamic_cast<XNOR*>(pComponent) != nullptr ? "XNOR" :
    dynamic_cast<XOR*>(pComponent) != nullptr ? "XOR" : ""
;

This works, but I feel like there should be a better way to do this. Perhaps create some kind of map with a reference to the class type of pComponent as key and the related string as value?

All classes (AND, NAND, etc) inherit the same base class, Node. I have been thinking about adding the following code to Node:

virtual std::string get_gate() const = 0;

Then have every derived class implement the method, returning its string and call:

pComponent->get_gate();

Would this solution use memory for every class instance rather than once per class? For example I declare two objects of AND, would both of them allocate memory for the method? Will the compiler do something smart?

Would this solution use memory for every class instance rather than once per class?

Depends on whether your class already contains a vtable pointer or not.

If it does, there will be no additional memory requirements per instance (just another entry in the vtable, which is shared by all instances).

If it doesn't, each class will need an additional vtable pointer (that will be automatically inserted by the compiler to make virtual dispatch work). Also, a vtable will be generated, but those are one per class.

However, since you are already using (and that includes possibly deleting) instances of derived classes via pointer to base class, the base classes destructor (in this case Node::~Node()) should already be marked virtual so the derived classes destructor gets called correctly when deleting the Node*. This means each class should already have a vtable anyways - so no additional per-instance overhead.


Counting trains by type code A train operator has decided to hire an observer to track the
  different types of trains transiting at a major train platform in
  Europe. Write a program, using a for loop, to track the different
  train types at the major train station.

  The different types of trains are shown in the following table:

Train types | Train code

Inter-city  | 23
Regional    | 51
Overnight   | 72

  The program should ask the user to enter five sets of train codes.

  The program should then count the number of train codes entered and
  display the statistics.

  Sample run

Enter train type #1: 23
Enter train type #2: 23
Enter train type #3: 51
Enter train type #4: 72
Enter train type #5: 23

  Sample output

Statistics:
3 Inter-city trains
1 Regional train
1 Overnight train

Can you please check whether this code is correct, and maybe make it shorter?

#include <iostream>
using namespace std;

int main()
{
    int train;
    int InterCity = 0;
    int Regional = 0;
    int Overnight = 0;

    cout << "          ------Trains------" << endl;
    for (int i = 1; i <= 5; i++)
    {
        cout << "Enter train type #" << i << ": ";
        cin >> train;

        if (train == 23)
        {
            InterCity++;
        }
        else if (train == 51)
        {
            Regional++;
        }
        else if (train == 72)
        {
            Overnight++;
        }
    }
    cout << "\n        ------Statistics------" << endl;
    cout << InterCity  << " InterCity trains." << endl;
    cout << Regional << " Regional trains." << endl;
    cout << Overnight << " Overnight trains." << endl;

    return 0;
}

Use a switch statement.  Add a default condition to show the error message when the entered train type is not matched with any specified train type.

switch (train) {
    case 23: InterCity++; break;
    case 51: Regional++;  break;
    case 72: Overnight++; break;
    default: // TODO: error handling
}


Reading entire contents of file at a given java.no.file.Path into a String What I'm wanting to do is create a String readFile(Path filePath, Charset encoding) method, that returns the entire contents of a given file.

I'm wanting the equivalent of Guava's Files.toString(file, encoding), but without calling the Path.getFile() method (as this method only works with the default filesystem provider, and in this particular case I'm wanting to write tests that use JimFS).

I've written the following, but I'm wondering if it can be improved:

import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import java.nio.file.Files;
⋮
public String readFile(Path path, Charset encoding) throws IOException {
    Preconditions.checkState(Files.exists(path), "File does not exist: %s", path);
    Preconditions.checkState(Files.isRegularFile(path), "File is not regular file: %s", path);

    return Joiner.on(System.lineSeparator()).join(Files.readAllLines(path, encoding));
}

Is there a better way to read the file in (such as without using Files.readAllLines() which results in a slightly awkward List<String>). I'd previously joined this result together by streaming the lines of the file, and then immediately collecting them with Collectors.joining(System.lineSeparator()), but since the project has a dependency on Guava for other purposes, it seems preferable to use the Joiner available.

I'm happy to restrict this to Java 8 and onwards if needed, and as previously mentioned I already have a dependency on Guava, but I'd rather not add too many dependencies if possible.

I believe you are missing a relatively obvious, although somewhat memory-inefficient Files.readAllBytes(...) .... Consider this:

public String readFile(Path path, Charset encoding) throws IOException {
    return new String(Files.readAllBytes(path), encoding);
}

In your code you also have two full copies of the file in-memory at one time, so the files can't be huge. The code I suggest also pulls all the data in to memory twice, once as a byte[] array, which gets converted to a String, and the byte[] array is discarded.

There would be a loopy way to solve it by using a StringBuilder and a smaller byte[] array, or ByteBuffer, but, if your files are smallish, I would not worry about the byte[] size.


Efficiently aggregating nested data Problem

Given the following data:

[
  {
    "users": [
      {
        "id": "07bde76f-aff0-407d-9241-a12b323d4af8",
        "transactions": [
          {
            "category": "purchase"
          },
          {
            "category": "unknown"
          }
        ]
      },
      {
        "id": "40aa040f-7961-4e06-a31b-32052be67fcc",
        "transactions": [
          {
            "category": "sale"
          },
          {
            "category": "unknown"
          }
        ]
      }
    ],
    "groups": [
      {
        "id": "00c61181-b133-4be9-9d44-dc3c224b3beb",
        "transactions": [
          {
            "category": "atm"
          },
          {
            "category": "cash"
          }
        ]
      },
      {
        "id": "eb959ff1-da1d-41e5-b5b7-45fef3dbc2df",
        "transactions": [
          {
            "category": "atm"
          },
          {
            "category": "cash"
          }
        ]
      }
    ]
  },
  {
    "users": [
      {
        "id": "af095f1c-fe43-43fb-9571-dabe2dd56bcf",
        "transactions": [
          {
            "category": "bill"
          }
        ]
      }
    ],
    "groups": [
      {
        "id": "c5bafe16-c5ec-428e-8c7c-30cbd9963750",
        "transactions": [
          {
            "category": "fee"
          },
          {
            "category": "cash"
          }
        ]
      }
    ]
  }
]

... I want to produce the following output:

{
  "groups_atm": 2,
  "groups_fee": 1,
  "groups_cash": 3,
  "users_purchase": 1,
  "users_unknown": 2,
  "users_bill": 1,
  "users_sale": 1
}

Implementation

I've approached this by first mapping over transactions and summing their occurrences:

const sum = (transactions) =>
    transactions.map((transaction) => transaction.category).reduce((acc, transactionCategory) => {
        return {
            ...acc,
            [transactionCategory]: (acc[transactionCategory] || 0) + 1,
        };
    }, tally);

... then aggregating by scope ("user", "group") per element of the data list and merge the counts by category:

const aggregate = (datum, tally) =>
    ['user', 'group'].reduce((acc, scope) => {
        const aggregates = datum[`${scope}s`].reduce(
            (agg, data) => sum(agg, data.transactions),
            {},
        );

        return {
            ...acc,
            [scope]: acc[scope] ? merge(acc[scope], aggregates) : aggregates,
        };
    }, tally);

const difference = (arrA, arrB) => arrA.filter((x) => !arrB.includes(x));
const intersection = (arrA, arrB) => arrA.filter((x) => arrB.includes(x));

const merge = (objA, objB) => {
    const acc = {};
    const aKeys = Object.keys(objA);
    const bKeys = Object.keys(objB);
    intersection(aKeys, bKeys).forEach((key) => (acc[key] = objA[key] + objB[key]));
    difference(aKeys, bKeys).forEach((key) => (acc[key] = objA[key]));
    difference(bKeys, aKeys).forEach((key) => (acc[key] = objB[key]));
    return acc;
};

... then re-reducing over the whole dataset:

const aggregates = data.reduce((acc, datum) => aggregateScope(datum, acc), {});

... and finally reformatting the aggregates to match the expected output:

const format = (aggregates) =>
    Object.keys(aggregates).reduce((acc, scope) => {
        Object.keys(aggregates[scope]).forEach((category) => {
            acc[`${scope}_${category}`] = aggregates[scope][category];
        });
        return acc;
    }, {});

Questions

what are alternative ways of breaking down the problem?
what is it's Big O complexity? Can it be reduced?
can merge be avoided?
are there language features (JS/ES6) that can make this more idiomatic?
is "aggregation" the correct terminology?

Way way too complex

One way to help workout how to solve a problem is to solve it in your head (or on paper) first. That way you know the problem from the top to the bottom. Then use that approach in your script.

The code looks like you started at the top with no clear idea of the solution, and solve many separate problems as you encountered them. The result is unreadable and way to complex.

I could not make a good assessment due to its complexity and bugs.

Your code does not run.

The name aggregateScope in aggregates should be aggregate
sum throws TypeError map is not a function

Patching those problems it still did not run.

The hell of a zillion iterators is not easy to traverse so I stopped trying to work it out at that point.

Questions.

You have some questions.

  what are alternative ways of breaking down the problem?

Its just a set of nested arrays and named objects. The names are fixed, so its just a process of stepping over each array in turn storing the counts in a named map (see example)

  what is it's Big O complexity?

I am guessing its It more than \$O(n)\$ and less than or equal to \$O(n^2)\$ where \$n\$ is the number of category items. As there is only a small sample dataset and the code does not work I can not give a accurate evaluation.

I did count 18 different iteration function calls throughout your code. With 2 or 7 iterations each, nested to about 6 levels. If I use that and average (2 + 7) / 2 = 4.5 per iterator then its 4.56 approx steps, so that's a big \$O(n^3)\$ for the given dataset of 11 category items

  Can it be reduced?

Yes, it can be O(n) as there is no need to search, and no need to compare items (see example).

  are there language features (JS/ES6) that can make this more idiomatic?

Use for of loops to iterate.
Use bracket notations to create named properties.
Keep your functions ordered. From bottom to top, it makes it easier to locate functions and follow the code.
No more than one iterator per line. You quickly lose track of how complex it gets.

Is all that comes to mind, that and  K.I.S.S.

An alternative example solution

I am not that conventional when it comes to code, so not quite idiomatic. less is good in my book and helps find the optimal \$O(n)\$ solution.

function aggregateTransactionCategories(data, types) {
  const result = {};
  const mapCategories = (type, transactions) => {
    for (const cats of transactions) {
      const name = type + "_" + cats.category;
      result[name] = result[name] ? result[name] + 1 : 1;
    }
  }
  for (const type of types) {
    for (const entries of data) {
      for (const entry of entries[type]) {
        mapCategories(type, entry.transactions);
      }
    }
  }
  return result;
}

setTimeout(() =>
    log(aggregateTransactionCategories( data,  ["groups", "users"]))
    ,0
);

const data = [{
    users: [
      { id: "07bd", transactions: [{category: "purchase"}, {category: "unknown"}] },
      { id: "40aa", transactions: [{category: "sale"}, {category: "unknown"}] }
    ],
    groups: [
      { id: "00c6", transactions: [{category: "atm"}, {category: "cash"}] },
      { id: "eb95", transactions: [{category: "atm"}, {category: "cash"}] }
    ]
  }, {
    users: [
      { id: "af09", transactions: [{category: "bill"}] }
    ],
    groups: [
      { id: "c5ba", transactions: [{category: "fee"}, {category: "cash"}] }
    ]
  }
];

//Just displays the result and not related to the problem
function log(data) {
  for(const [name, value] of Object.entries(data)) {
    displayResult.appendChild(Object.assign(
      document.createElement("div"),{
        textContent : name + ": " + value + ","
      }
    ))
  }
}


A Stack Implementation In C I've written a very simple linked list based stack implementation and was wondering if this is the standard way to do it in C.

typedef struct Node {
    int value;
    struct Node *prev;
} Node;

Node * push(Node *top, int value) {
    Node *node = (Node *) malloc(sizeof(Node));
    node->value = value;
    node->prev = top;
    return node;
}

Node * pop(Node *top, int *val_addr) {
    *val_addr = top->value;
    Node *new_top = top->prev;
    free(top);
    return new_top;
}

int is_empty(Node *top) {
    return top == NULL;
}

Before deciding to post on code review I decided to check google for stack implementations to see if mine was okay. But most of the decent sources that I checked used an array implementation. I was wondering in what situation is it better to use a dynamic array based stack?

A dynamic array based stack will use less memory, as it does not have to store an address with each element. It will probably be faster for push because it doesn't need to make an allocation each time.

The main benefit of using a linked list is immutability. With a linked list, you can make stack operations that leave the previous stack as it is.
However this is difficult without garbage collection.

Since you are not going for an immutable stack, I would recommend changing the signatures of you push() and pop() functions to something like this:

void push(Node **top, int value);
int pop(Node **top);

This way, you don't leave users of your utility with pointers to freed values, so they can't screw up their stack by popping and using the original stack, which is now invalid.


Handling arrow keys and tabIndex I'm wondering how to "beautify"/"simplify" this code:

function handleKeyDown (e) {
  if (e.key === 'Enter') {
    e.preventDefault()
    myCustomEvent(e)
    return
  }
  if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
    e.preventDefault()
    e.key === 'ArrowDown'
      ? document &&
        document.activeElement &&
        document.activeElement.nextElementSibling &&
        document.activeElement.nextElementSibling.focus()
      : document &&
        document.activeElement &&
        document.activeElement.previousElementSibling &&
        document.activeElement.previousElementSibling.focus()
  }
}

It seems too verbose to me. Is there something I'm doing wrong? How can I write it better?

Through clever usage of destructuring and using objects to store possible events, you can do this.
function focus(key){
  const {activeElement:{[key]: elementSibling} = {}} = document;
  if(elementSibling){
    elementSibling.focus();
  }
}

const ACTIONS = {
  ArrowDown: () => focus('nextElementSibling'),
  ArrowUp: () => focus('previousElementSibling'),
  Enter: (e) => myCustomEvent(e)
}

function handleKeyDown (e) {
  const handler = ACTIONS[e.key];
  if(handler) {
    e.preventDefault();
    handler(e);
  }
}

Here is a working example:

function focus(key){
  const {activeElement:{[key]: elementSibling} = {}} = document;
  if(elementSibling){
    elementSibling.focus();
  }
}

const ACTIONS = {
  ArrowDown: () => focus('nextElementSibling'),
  ArrowUp: () => focus('previousElementSibling'),
  Enter: (e) => myCustomEvent(e)
}

function handleKeyDown (e) {
  console.log(e.key, e.target);
  const handler = ACTIONS[e.key];
  if(handler) {
    e.preventDefault();
    handler(e);
  }
}

// simulating an event
window.addEventListener('keyup', handleKeyDown);

Click on an element then press ArrowUp or ArrowDown

<input type="text"/>
<input type="text"/>
<input type="text"/>
<input type="text"/>


Merge sort in Scheme (define (merge-sort lst (lt? <))
  (define (truthy=? a b)
    (eq? (not a) (not b)))

  (let sort ((lst lst)
             (size (length lst))
             (flip #f))
    (define (merge l r (res '()))
      (cond ((null? l) (append-reverse r res))
            ((null? r) (append-reverse l res))
            ((truthy=? (lt? (car r) (car l)) flip)
             (merge l (cdr r) (cons (car r) res)))
            (else
             (merge (cdr l) r (cons (car l) res)))))

    (if (<= size 1) lst
        (let*-values (((mid) (quotient size 2))
                      ((l r) (split-at lst mid)))
          (merge (sort l mid (not flip))
                 (sort r (- size mid) (not flip)))))))

Tested with Racket and Guile; requires SRFIs 1 and 11. (If you want to use this for Guile, you will need to adjust the syntax used for optional arguments.)

This version is tailored for Scheme in a number of ways:

The length of the list is calculated only once, at the beginning. At each split, the length of the split parts is passed to each recursive call.
The merge step uses a right-unfold rather than a left-unfold, to be tail-recursive. This results in a reversed list at each step.
Rather than reverse the list at each merge, I just keep a flag saying whether the lists are reversed. The merging step takes this flag into account and then does the right kind of merge to maintain sort stability.

Four years, 1400 views, and two dozen upvotes before a review on a site dedicated to code reviews points toward unreviewability as a prominent feature of the code. What hinders reviewability is, I think, the high level of cognitive load the code places on anyone reading it.

Reading

The cognitive load begins at the top level. Merge-sort is a well documented algorithm. Like many people interested in programming, I wrote an implementation for an algorithms class. It makes a good assignment because the details are non-trivial (and discovering those details was serious work seventy years ago when the John Von-Neumann for which computing's Von-Neumann Architecture is named, did so..."how serious?" one might ask and the answer would be "Manhattan Project serious"). I imagine I'm like some other people in that I've forgotten the ins and outs of my implementation and recycled whatever synapses were storing the pseudo-code to something else. For me, merge-sort is vaguely familiar in a sort of \$\mathcal{O}(n\log n)\$ sort of way since that's the fact that's most likely to be relevant at the sorting level of abstraction.
For the purposes of this review, I'll say that the next level down is the top level of the implementation. Here the question claims a clever implementation detail: calculating the length of the list only once. I don't recall how my implementation calculated length or whether it did...I think I used vectors/arrays rather than lists [I wrote it in either Clojure or Racket]. Anyway, being clever makes the code harder to review.
At the next level down, the structure induces additional cognitive load. At best the mixture of define and let/let* is inconsistent style. At worst, the let's just make for less readable code of the sort that made nested define's worth implementing in Scheme itself.
Finally, there's variable names.

Advice

Help the reader by commenting the code. Don't require expertise in merge-sort as a pre-requisite to understanding. Consider using something like the HtDP Program Recipe as a starting point. Explain the algorithm and use the terms of that explanation in the implementation.
I'm reminded of Kernighan's Lever: Everyone knows that debugging is twice as hard as writing a program in the first place. So if you're as clever as you can be when you write it, how will you ever debug it? Looking at the code, it isn't obvious where the innovation is implemented. Even after I obtain some level of merge-sort knowledge, I still have detective work to understand the innovation. Make the innovation explicit.
Make everything explicit using define rather than let/let* the syntax is better and the high level concepts can be articulated together rather than mixed in among the implementation details, e.g. merge can be defined alongside truthy=?, mid, etc.
There's no need to name parameters/variables using the criteria for minified JavaScript. l and r might be abstractions 'left' and 'right' but left and right are not abstractions that are explicit in the code. It's only via research that a reader might possibly make the connection.

A bit more on Item 2: If performance is a concern the question of why lists and parameter passing  rather than vectors or some other data structure seems relevant. Going further, benchmarking is probably the best justification for added complexity:

  Programmers waste enormous amounts of time thinking about, or worrying about, the speed of noncritical parts of their programs, and these attempts at efficiency actually have a strong negative impact when debugging and maintenance are considered. We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil. Yet we should not pass up our opportunities in that critical 3%.

Fast sorting seems to be a place where using an FFI is the road to meaningful improvement for interestingly sized data.


Building SQL from multiple combinations of query parameters I have a node.js/express.js based REST application. In one GET service I am querying data based on different set of request parameters. I am looking for a better way to implement it.

function handleGet(connection,req,res) {

var sql = 'SELECT id, name, age, rent, marks FROM student WHERE class = 10';

if (req.param('minAge') && req.param('maxAge')) {
    sql = sql + ' AND age BETWEEN ' + connection.escape(req.param('minAge')) + ' AND ' + connection.escape(req.param('maxAge'));
}

if (req.param('minRent') && req.param('maxRent')) {
    sql =sql + ' AND rent BETWEEN ' + connection.escape(req.param('minRent'))
        + ' AND ' + connection.escape(req.param('maxRent'));
};

if (req.param('marks')) {
    sql = sql + ' AND marks >= ' + connection.escape(req.param('marks'));
};

};

var limit = ('undefined' === typeof req.params.limit) ? 20: req.params.limit;

connection.query(sql + ' ORDER BY id DESC LIMIT ' + limit, function handleSql(err, rows){
        if (err){ logAndRespond(err,res); return; }
        if (rows.length === 0){ res.send(204); return; }
        res.json(200, {'students':rows});
        connection.release();
});
}

Data can be queried by passing difference combination request parameters. Can anyone please suggest any better (reusable, abstract, robust) way of doing it? I was wondering if I can create a module for building query. Something like setting all param values in the module and let the module validate and construct the query.

Instead of dynamic string concatenation, you can do a logic trick. I'm going to use named sql placeholders for clarity. You'll obviously need to implement the code, I'm just giving you the idea.

select a
     , b
     , c
  from someTbl
 where (:PMaxAge  is null or maxAge <= :PMaxAge)
   and (:PMinRent is null or rent   >= :PMinRent)
   and (:PMaxRent is null or rent   <= :PMaxRent)
   -- etc ...

You may need to check for an empty string instead of checking for null to detect when a param was omitted depending on you implementation, but you get the point - let each criteria be satisfied if the param is missing.


Bulleted list from dashes Let's keep this simple.

Input:

- abc
- def
- ghi

Desired output (whitespace optional):

abc

def

ghi

Current code:

$output = preg_replace_callback(
    "((^- (.*)$\r*\n*)+)m",
    function($m) {
        return "

".
            implode(
                "

",
                preg_split(
                    "(^- )m",
                    substr($m[0],2)
                )
            ).
            "

";
    },
    $input
);

It works, the output is exactly what I want, but it seems kinda... hackish. Having a preg_split inside a preg_replace_callback seems a bit redundant, but I can't seem to find a way of capturing subpatterns that are inside a quantifier. If I could do that then I would implode the subpatterns rather than having to split the matched part again.

Any suggestions?

Wouldn't this give you the desired output:

$result = '
' . preg_replace('/^- (.*)$/m', '
$1
', $subject) . '
';

Update:

$output = preg_replace_callback(
    "((^- (.*)$\r*\n*)+)m",
    function($m) {
        return '
' . preg_replace('/^- (.*)$/m', '
$1
', $m) . '
';
    },
    $input
);