Can I slim this UTF8-encoding program? Below is my entire program. You can read what it does thanks to the comments and specifications in particular.

My question is: can it be improved? Would it be possible, for example, to avoid writing a fwrite() inside each if? Is there a good pattern that can be implemented somewhere in this code?

The entire program is base on this UTF8 model and also studies the case in which a bit occurs in the 32nd position.

#include <stdio.h>
#include <math.h>
#include <stdint.h>

double log(double a);

/*
* This program reads 4 byte codepoints (in BIG ENDIAN) from a file strictly called "input.data" and creates another file called "ENCODED.data" with the relative encoding in UTF8.
*
* In order to compile this file, in Unix, you need to add the -lm clause because the library math.h function log() requires it.
* For example: gcc encoding.c -o encoding -lm
*/
int main() {

    unsigned char bufferCP[4]; //Buffer used to store the codepoints
    unsigned char bufferOut[6]; //Buffer used to store the UTF8-encoded codepoints

    FILE *ptr, *out;
    ptr = fopen("input.data", "rb"); //r for read, b for bynary
    out = fopen("ENCODED.data", "wb");

    int elem = 0, bytesRead = 0;
    unsigned char mask = 0x3F; //Mask used to keep bits interesting for analysis
    uint32_t codepoint = 0; //A codepoint must be an unsigned 32 bit integer

    //--------------------File-Reading--------------------
    while ((elem = fgetc(ptr)) != EOF) {
        //Stores the character in the buffer
        bufferCP[bytesRead++] = (unsigned char) elem;

        if (bytesRead == 4) { //A codepoint is ready to be managed

            //Builds a codepoint from the buffer. Reads it in BIG ENDIAN.
            for(int j=3; j>=0; j--) {
                    codepoint <<= 8;
                    codepoint |= bufferCP[j];
            }
            //Searches the position of the most significant bit
            double logRes = (log(codepoint)/log(2)) + 1;
            int bitPos = (int) logRes;

            //--------------------UTF8-Encoding--------------------
            if (bitPos <= 7) {
                bufferOut[0] = (unsigned char) codepoint; //No need to manage this codepoint
                fwrite(bufferOut, 1, 1, out);

            } else if (bitPos <= 11) {
                bufferOut[0] = (codepoint >> 6) | 0xC0;
                bufferOut[1] = (codepoint & mask) | 0x80;
                fwrite(bufferOut, 1, 2, out);

            } else if (bitPos <= 16) {
                bufferOut[0] = (codepoint >> 12) | 0xE0;
                for(int i=1; i<3; i++)
                    bufferOut[i] = ((codepoint >> 6*(2-i)) & mask) | 0x80;
                fwrite(bufferOut, 1, 3, out);

            } else if (bitPos <= 21) {
                bufferOut[0] = (codepoint >> 18) | 0xF0;
                for(int i=1; i<4; i++)
                    bufferOut[i] = ((codepoint >> 6*(3-i)) & mask) | 0x80;
                fwrite(bufferOut, 1, 4, out);

            } else if (bitPos <= 26) {
                bufferOut[0] = (codepoint >> 24) | 0xF8;
                for(int i=1; i<5; i++)
                    bufferOut[i] = ((codepoint >> 6*(4-i)) & mask) | 0x80;
                fwrite(bufferOut, 1, 5, out);

            } else if (bitPos <= 32) {
                if (bitPos == 32)
                    bufferOut[0] = (codepoint >> 30) | 0xFE; //UTF8-encoding first byte would be: 11111111?
                else
                    bufferOut[0] = (codepoint >> 30) | 0xFC;

                for(int i=1; i<6; i++)
                    bufferOut[i] = ((codepoint >> 6*(5-i)) & mask) | 0x80;
                fwrite(bufferOut, 1, 6, out);
            }

            bytesRead = 0; //Variable reset
        }
    }

}

Efficient file I/O

By default, files opened with fopen() are buffered, meaning that not every call to fread() or fwrite() will result in a system call. Instead, the C library has an internal buffer and will try to read and write larger chunks at a time. However, you are still paying for the overhead of a regular function call each time you call fread() and fwrite(). To avoid this, it is best that you read and write in large chunks in your own code as well.

While you could try to read in the whole file at once, or even use technique like mmap() to memory map the file, you can already get very good performance by reading and writing blocks of say 64 kilobytes at a time. This avoids using a lot of memory.
Of course, you have to handle the last block not being exactly 64 kilobytes large, but that is quite easy to deal with.

Furthermore, fread() and fwrite() allow you to specify the size of an element and the number of elements you want to read, this comes in handy to ensure you read in a whole number of 4-byte codepoints.

I would structure your code like so:

uint32_t bufferIn[16384]; // 16384 4-byte code points = 64 kB
char bufferOut[65536];

size_t countIn;

while ((countIn = fread(bufferIn, sizeof *bufferIn, sizeof bufferIn / sizeof *bufferIn, ptr)) > 0) {
    // There are countIn codepoints in the buffer
    for (size_t i = 0; i < countIn; i++) {
         uint32_t codepoint = ...; // Convert bufferIn[i] to native endian here.

         // Write UTF-8 to bufferOut here.
         // If bufferOut is almost full, fwrite() it and start writing to it from the start.
    }
}

// Flush the remaining bytes in bufferOut here.

Don't use floating point math for integer problems

Avoid using floating point math when you are dealing with integers. It is hard to get it right, and converting int to double, doing some math operation, and then converting back again can be quite slow.

There are several ways to get the highest set bit in an integer. If you want a portable one, I recommend using one of the bit twiddling hacks. Sometimes compilers will even recognize such a bit twiddling hack and convert it to a single CPU instruction if possible.


How to write elegant conditional bits of markup in Razor views? Suppose the following model:

public class ViewBookModel
{
    public string Title { get; set; }
    public string Subtitle { get; set; }
}

I'm currently rendering it like this in my Razor view:

@Model.Title

@if (Model.Subtitle != null)
{

@Model.Subtitle

}

My question is about the Subtitle bit. The above approach feels a little clunky, and can get repetitive (which is probably a bad sign) at times.

Are there any better, less verbose, more elegant ways to handle this situation?

I had considered (a) the option now mentioned in Mat's Mug's answer, as well as (b) moving the condition to the model:

public class ViewBookModel
{
    // ...
    public string ShowSubtitle {
        get { return string.IsNullOrEmpty(Subtitle); }
    }
}

With this change to the view:

@if (Model.ShowSubtitle)

However, that doesn't address my main issue: the verbosity (i.e. 4 lines of view code just to display Subtitle).

If you find a pattern getting too repetitive, you can use @helper instead:

@helper ShowIfNotNull(string header) {
    @if (!string.IsNullOrEmpty(header))
        @:
header

    }
}

@Model.Title

@ShowIfNotNull(Model.Subtitle)


Project Euler problem 12 Python I'm new to python and programming in general and I found Project Euler problems a good way to practice python. But my code is pretty slow. It seems to work, didn't wait long enough for the code to print the answer though. Any tips on how to make it faster ? I assume that you don't have to check every single number but that's just a guess any help appreciated.

tri_nums = [1]
divisors = []
temp_divisors =[]

while len(divisors) <= 500:
    for x in range(1, tri_nums[-1] + 1):
        if tri_nums[-1] % x == 0:
            temp_divisors.append(x)
    if len(temp_divisors) > len(divisors):
        divisors = temp_divisors[:]
    temp_divisors.clear()

    print("Number: " + str(tri_nums[-1]))
    print("Number of divisors: " + str(len(divisors)))
    print("List of divisors: " + str(divisors))
    tri_nums.append(len(tri_nums) + 1 + tri_nums[-1])

To avoid spoiling the problem for you, I'll offer some hints.

Hint 1:

   Have you read the Wikipedia article about the triangular numbers? It's always worth doing a bit of research into the mathematical background of a Project Euler problem.

Hint 2:

   There is a mathematical formula for the \$n\$th triangular number, namely \${1\over2}n(n+1)\$.

Hint 3:

   What do you know about the divisors of \${1\over2}n(n+1)\$? Try out some small examples and see if there is a pattern.

Hint 4:

   When a problem requires you to establish some facts about the divisors of all the numbers in a range, then what you need is a sieve.


Use a data frame of functions to calculate values using specific columns in another data frame Background

This routine is used in a package that calculates tree (as in Christmas tree) volumes for various species codes (spcd) and geographic regions. The equation forms and coefficients vary by species and region, so I have a dataframe of functions along with their respective species and region that calculate the volume based off of the height (ht) of the tree and diameter (dbh).

Data Setup

Note: In my package, this part is taken care of by other functions, this is just to create a reproducible example (please ignore the sloppyness)

I have a data frame that includes a column of functions, along with some information about "where" to apply those functions in another data frame.

The functions (in reality these are more complex):

func1 <- function(dbh,ht){dbh^2 + ht}
func2 <- function(dbh,ht){dbh^2 - ht}

The data frame (in reality this data frame is much longer):

spcd <- c(122, 122, 141, 141)
region <- c('OR_W', 'OR_E', 'OR_W', 'OR_E')

funcs_df <- data.frame(spcd, region, funcs)
funcs_df$funcs <- c("func1", "func2", "func1", "func2")

Then, I have another frame that has some information, including the spcd and region that should match the values in func_df:

spcd <- c(122, 141, 141, 122, 141, 122)
region <- c('OR_W', 'OR_E', 'OR_W', 'OR_E', 'OR_W', 'OR_W')
dbh <- c(12, 13, 15, 11, 10, 21)
ht <- c(101, 121, 100, 99, 88, 76)

tree_df <- data.frame(spcd, region, dbh, ht)

Applying the Functions

This is the part I would prefer feedback on.

First, I split the tree_df into distinct groups based on spcd and region so I can apply the functions that correspond to these distinct groups.

tree_split <- split(tree_df, list(tree_df$region, tree_df$spcd))

Then, I create an empty data frame to append to.

new_tree <- data.frame()

Next, (and this is where things get messy) I loop through each group, grab the top left cell that acts as a "key" to get the equation from the func_df and use mapply on each group (with some conditionals to handle NA values).

for (group in tree_split) {
    # Get the 'group key'
    region <- group$region[1]
    spcd <- group$spcd[1]

    # Get the equation from eqs
    eq <- funcs_df$funcs[which((funcs_df$spcd == spcd & funcs_df$region ==
          region))]

    # Convert func string into actual function
    eq <- eq[[1]]
    eq <- eval(parse(text=eq))

    # Apply the equation to each record in the group
    group$cvts <- mapply(eq, group$dbh, group$ht)

    # Append to new_tree
    new_tree <- rbind(new_tree ,group)
}

Discussion

This results in the desired output with the new cvts outputs according to each function defined in the dataframe:

  spcd region dbh  ht cvts
4  122   OR_E  11  99   22
1  122   OR_W  12 101  245
6  122   OR_W  21  76  517
2  141   OR_E  13 121   48
3  141   OR_W  15 100  325
5  141   OR_W  10  88  188

I have a few concerns with this approach:

The old adage "if you write a for-loop you are doing it wrong" seems to apply here. Is there some way I could reduce this for-loop to some sort of apply or mapply type function?
Grabbing the key from a cell (see "# Get the 'group key'" comment above) seems sloppy. Is there a way to get this 'group key' in a more formal fashion?

Other advice is, of course, welcome.

I would suggest you merge your data.frames so you can split the data per function:

mg <- merge(funcs_df, tree_df)
sp <- split(mg, mg$funcs)

print(sp)
# $func1
#   spcd region funcs dbh  ht
# 2  122   OR_W func1  12 101
# 3  122   OR_W func1  21  76
# 5  141   OR_W func1  15 100
# 6  141   OR_W func1  10  88
#
# $func2
#   spcd region funcs dbh  ht
# 1  122   OR_E func2  11  99
# 4  141   OR_E func2  13 121

Then, you just have to call each function once (since you confirmed the functions are vectorized):

cvts_list <- Map(function(fun, x) fun(x$dbh, x$ht),
                 fun = mget(names(sp)), x = sp)

print(cvts_list)
# $func1
# [1] 245 517 325 188
#
# $func2
# [1] 22 48

and stack the results into a new column, using unsplit:

mg$cvts <- unsplit(cvts_list, mg$funcs)

print(mg)
#   spcd region funcs dbh  ht cvts
# 1  122   OR_E func2  11  99   22
# 2  122   OR_W func1  12 101  245
# 3  122   OR_W func1  21  76  517
# 4  141   OR_E func2  13 121   48
# 5  141   OR_W func1  15 100  325
# 6  141   OR_W func1  10  88  188


Writing input into separate arrays and an output file The code inputs an int, n, which is the number of lines to follow. Then, on each line, the first number goes to array A, the second to B, and the third to C. I then pass these 4 arguments to sub which I have no control over (in an object file where I don't know the implementation). All I know is that it returns an int.
What I do then is write n, the three arrays, and the result of sub into an output file. Pretty simple code.
This code works as expected, but I just want to see if there are any conventions I should be following (especially C++11) and ideas to consider for efficiency.
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <sstream>
#include "sub.h"

int main()
{
    std::ifstream file;
    file.open(...);

    if (!file) {
        std::cerr << "Error opening file." << std::endl;
        return EXIT_FAILURE;
    }

    int n;
    std::string firstLine;
    getline(file, firstLine);
    std::stringstream(firstLine) >> n;

    int a,b,c;
    std::vector<int> A1,B1,C1;
    while (file >> a >> b >> c) {
        A1.push_back(a);
        B1.push_back(b);
        C1.push_back(c);
    }

    file.close();

    std::ofstream output;
    output.open(...);

    output << n << "\n";

    size_t size = A1.size();
    for (size_t i=0; i<size; ++i) {
        output << A1[i] << " " << B1[i] << " " << C1[i] << std::endl;
    }

    //call sub method with pointer to beginning of vectors
    //I have no control over sub method, its signature is (int, int*, int*, int*)
    int n1 = sub(n, &A1[0], &B1[0], &C1[0]);

    //output result and close file
    output << n1;
    output.close();
}

Example input:

0 1 2 <- This is A[0], B[0], C[0]
2 3 4 <- This is A[1], B[1], C[1]
4 5 6 <- This is A[2], B[2], C[2]

The range-based for-loop would not work in this case. It would, however, if I printed all of A, B, or C on one line.

It's a good idea to order your STL #includes either alphabetically or by groups (see this answer for more details).  Header files should also precede STL #includes to avoid dependencies.
I'd give your IO files more accurate names (such as inFile and outFile).
Include <cstdlib> for EXIT_FAILURE.
This is C++ and not C, so use std::size_t instead of size_t.
Put the std::vector declarations (A1, B1, C1) on separate lines.
You don't have to create another size variable for A1.size() just for a loop.

In that same loop: you're looping through all three arrays at once, but are using one vector's size to do that.  That's a bad idea.  If they happen to be different sizes, you're going to run into problems.
This:

int n1 = sub(n, &A1[0], &B1[0], &C1[0]);

is best written as this (with iterators):

int n1 = sub(n, A1.begin(), B1.begin(), C1.begin());


Tarjan's Algorithm Python Implementation I'm planning to use Tarjan's algorithm for a program in which I would be processing a file, converting the processed data to a dictionary, doing a topological sort on that dictionary (using this implementation), and then finding the longest path.

Is there any optimization that can be made to the below code, or can be be made more pythonic?

def strongly_connected_components(graph):

    index_counter = [0]
    stack = []; result = []
    lowlinks = {}; index = {}

    def tarjan(node):

        index[node] = index_counter[0]
        lowlinks[node] = index_counter[0]
        index_counter[0] += 1
        stack.append(node)

        try:
            successors = graph[node]
        except:
            successors = []
        for successor in successors:
            if successor not in lowlinks:
                tarjan(successor)
                lowlinks[node] = min(lowlinks[node],lowlinks[successor])
            elif successor in stack:
                lowlinks[node] = min(lowlinks[node],index[successor])

        if lowlinks[node] == index[node]:
            connected_component = []
            while True:
                successor = stack.pop()
                connected_component.append(successor)
                if successor == node: break
            component = tuple(connected_component)
            result.append(component)

    for node in graph:
        if node not in lowlinks:
            tarjan(node)

    return result

Source

The graph is unweighted, and would look something like this:-

test_graph = {
    'A' : ['B','S'],
    'B' : ['A'],
    'C' : ['D','E','F','S'],
    'D' : ['C'],
    'E' : ['C','H'],
    'F' : ['C','G'],
    'G' : ['F','S'],
    'H' : ['E','G'],
    'S' : ['A','C','G']
}

Multi-statement lines

This:

stack = []; result = []
lowlinks = {}; index = {}
# ...
if successor == node: break

is generally discouraged; just use two lines.

snake_case

This:

lowlinks

is usually spelled out, i.e. low_links.

Bare except

    try:
        successors = graph[node]
    except:
        successors = []

has an except statement that's too broad. If you expect a KeyError from this, then except KeyError.


Create elasticsearch document from php Can you please provide some improvement advice for the following function?
It is working OK now, but as I have zero experience with PHP I guess there is a lot of room for improvement.

function addNewUser($ES_Client, $username, $password, $fullname, $email, $function, $department, $access){
    auditLog($ES_Client, "Creating new user: ".$username.", ".$fullname.", ".$email.", ".$function.", ".$department.", ".$access);
    $checkIfUserExists = getUserDetails($ES_Client,$username)['hits']['total'];
    if($checkIfUserExists != 0){
        auditLog($ES_Client, "User ".$username." already exists! Operation aborted.");
        return -1;
    } else {
        $hashed_password = crypt($password);
        $userAddQuery= [
            'index' => 'system',
            'type' => 'users',
            'body' => [
                'username' => $username,
                'password' => $hashed_password,
                'fullname' => $fullname,
                'email' => $email,
                'function' => $function,
                'department' => $department,
                'access' => $access,
                'lastlogin' => round(microtime(true) * 1000)
            ]
        ];
        try{
            $userAddResponse = $ES_Client->index($userAddQuery);
            if($userAddResponse['created'] == 1)
            {
                auditLog($ES_Client, "User ".$username." added successfully!");
                return 0;
            }
            else{
                auditLog($ES_Client, "Error adding user ".$username."! Did not receive acknowledgement from elastic.");
                return -1;
            }
        } catch(Exception $e) {
            auditLog($ES_Client, "Error adding user ".$username."! ".$e->getMessage());
            return -1;
        }
    }
}

Guard Clauses

You can save a level of nesting by using guard clauses. In this case, it just means removing the else:

auditLog($ES_Client, "Creating new user: ".$username.", ".$fullname.", ".$email.", ".$function.", ".$department.", ".$access);
$checkIfUserExists = getUserDetails($ES_Client,$username)['hits']['total'];
if($checkIfUserExists != 0){
    auditLog($ES_Client, "User ".$username." already exists! Operation aborted.");
    return -1;
}

$hashed_password = crypt($password);
[...]

Error Handling

First of all, your return values are quite confusing. If you were to check them, you would get code like this:

if (addNewUser(...)) {
    // handle the error
}

The problem is that 0 is actually false, while -1 is true. But really, returning integers as error codes is confusing and difficult to use. The numbers themselves don't have any meaning, so you always need to look up what they mean in the documentation (if it even exists).

If you just have a boolean state, you might as well return boolean values.

But really, I would prefer to throw exceptions. Not being able to add a user is an exceptional state after all. This also gives you the option of being more explicit about what went wrong, so a calling method may have a change to recover, or show a better error message to the user.

Hashing

Don't use crypt, especially not without additional arguments. The documentation explicitly warns against this, as it is not secure:

  The salt parameter is optional. However, crypt() creates a weak password without the salt. PHP 5.6 or later raise an E_NOTICE error without it. Make sure to specify a strong enough salt for better security.

You should just use password_hash.

Formatting

Your indentation is partly off.
You are not consistent with your curly bracket positions.
You are also not consistent with your use of spaces.

Use an IDE to fix all of these issues automatically.

Naming

You should be consistent with your variable names. Don't mix camelCase and snake_case without reason.

Generally, your variable names are very clear. But you could shorten some without loosing any meaning. checkIfUserExists for example may be userExists. Although this actually doesn't seem to represent what the variable actually holds (it holds some counter instead).


Words in text counter This accepts text and returns a list of all words which occur with a required frequency (default frequency is 2). It works well, but gets too slow with large texts, more than 1M words. Where can this function be improved to speed searches in larger text?

from collections import Counter
import re

def words_in_text_counter(in_text,frequency=2):
    no_noise_text = re.sub(r'[0-9.,:;<>"#!%&/()=?*-+]','',in_text.lower()).strip().split()
    frequency_dict = {}
    for key, value in Counter(no_noise_text).items():
        frequency_dict.setdefault(value, []).append(key)
    try:
        print(str(frequency)+' times words in text.')
        return frequency_dict[frequency]
    except KeyError:
        return str(frequency)+' times never happens in text.'

Your problem is ultimately:

no_noise_text = re.sub(r'[0-9.,:;<>"#!%&/()=?*-+]','',in_text.lower()).strip().split()

There's a lot to dislike about this line. It horribly violates the Law of Demeter. It takes a while to figure out what it is supposed to do. It uses the wrong tool for the job. And it's inefficient.

First, to start with, if the goal is to split a strict by non-alpha characters, then we should just use the correct function: re.split:

words = re.split("[^a-z']+", in_text.lower())
counts = Counter(words)

Next, this is going to be inefficient. We have to walk the entire string once (to make it lower-case), then again to split it. And then we have to keep all of the words in memory. We don't have to do any of that if we really start with the correct function: re.finditer:

re.finditer("([a-zA-Z']+)", in_text)

That will give you an iterator over the words. Which you can stick into a generator expression that you can pass to Counter:

words = re.finditer("([a-zA-Z']+)", in_text)
counts = Counter(m.group(0).lower() for m in words)

And if you're already using Counter, you may as well use defaultdict:

freq_dict = defaultdict(list)
for key, val in counts.iteritems():
    freq_dict[key].append(val)

Note that I'm using iteritems() (which just gives you a generator) rather than items() (which must give you the full list).

Furthermore, why do we need a frequency_dict? We only care about those words which match the given frequency. Why not just keep a list?

frequency_list = []
for key, val in counts.iteritems():
    if val == frequency:
        frequency_list.append(key)

Putting it all together

from collections import Counter
import re

def words_in_text_counter(in_text, frequency=2):
    words = re.finditer("([a-zA-Z']+)", in_text)
    counts = Counter(m.group(0).lower() for m in words)

    frequency_list = []
    for key, val in counts.iteritems():
        if val == frequency:
            frequency_list.append(key)

    if frequency_list:
        print(str(frequency)+' times words in text.')
        return frequency_list
    else:
        return str(frequency)+' times never happens in text.'


Filtering cards into appropriate list elements Background:

I have two lists: one with a list of workcentres and the other with a list of the stations in the centres.

This code matches the stations to the centres by comparing the stations' workcentre number property with the name property of the centres.

    private void WsSorter(WorkcentreList wcl, List<WorkstationCard> wscl)
    {
        // Find index of workcentres
        foreach (Workcentre wc in wcl.WcList)
        {
            foreach (WorkstationCard wsc in wscl)
            {
                if (!(wsc.WorkcentreNo == MAIN_WORKCENTRE_1 ||
                 wsc.WorkcentreNo == MAIN_WORKCENTRE_2 ||
                 wsc.WorkcentreNo == MAIN_WORKCENTRE_3 ))
                {
                    wc.CardList.Add(wsc); // Must be adding to "Other WC"
                }
                // Add to matching workcentre
                else if (wsc.WorkcentreNo == wc.WcName)
                {
                    wc.CardList.Add(wsc);
                }
            }
        }
    }

Question

The lint tool I am using, SonarLint is telling me off for violating the DRY principle in the else if condition.

It works, albeit with poor error checking but I would like to know, is there a better way I could write the code / approach the situation, especially regarding not repeating the line wc.CardList.Add(wsc);?

Additional context: There are 3 main workcentres. All other workcentres (of which there is an arbitrary amount) should be classified under 'other'. I set the code up such that if the stations don't belong to a main workcentre, it must belong in the 'other' workcentre.

By simply adding the else condition to the if, the DRY warning will go away. It's just telling you that both the if and else block currently execute the same code, and can therefore be consolidated into a single block.
The comment // Find index of workcentres is misleading and should be removed.
Don't use abbreviations for naming. It makes it very hard to read and understand the code.
By extracting the condition to a separate method, you can use the Where() LINQ method and call AddRange() instead of repeatedly calling Add() .
Like @Paparazzi mentioned in a comment, you are filtering, rather than sorting, so you should change the name of the method.

Implementing the changes (except for the naming), you code will look like the following:

private void WsSorter(WorkcentreList wcl, List<WorkstationCard> wscl)
{
    foreach (Workcentre wc in wcl.WcList)
    {
        wc.CardList.AddRange(wscl.Where(workstationCard => IsDesiredWorkstationCard(workstationCard, wc.WcName)));
    }
}
private bool IsDesiredWorkstationCard(WorkstationCard workstationCard, string workCentreName)
{
    return !(workstationCard.WorkcentreNo == MAIN_WORKCENTRE_1 ||
             workstationCard.WorkcentreNo == MAIN_WORKCENTRE_2 ||
             workstationCard.WorkcentreNo == MAIN_WORKCENTRE_3 ) ||
             workstationCard.WorkcentreNo == workCentreName
}


Counting word occurences This is a simple word count program I wrote to play around and get familiar with using std::map. Is there anything I can improve upon?

I didn't use CTRL+Z to stop the program because that suspends the process on Linux.

#include <iostream>
#include <iomanip>
#include <string>
#include <map>
#include <iterator>
using std::cout;
using std::cin;
using std::endl;
using std::string;

int main(){
    std::map<string, int> words;
    cout << "Enter some text. Type "***" to end." << endl;

    std::istream_iterator<string> begin(cin);
    std::istream_iterator<string> end;

    while(begin != end){
        if(*begin == string("***"))
            break;
        words[*begin++]++;
    }
    for(std::map<string,int>::iterator iter = words.begin(); iter != words.end(); ++iter)
        cout << std::setw(6) << iter->second << " " << iter->first << endl;

return 0;
}

Sample input:

engie does wut engie wants
pyro mad
engie rek pyro
pyro go cry
deny engie u try
rekt u will get

Output:

 1 cry
 1 deny
 1 does
 4 engie
 1 get
 1 go
 1 mad
 3 pyro
 1 rek
 1 rekt
 1 try
 2 u
 1 wants
 1 will
 1 wut

You cannot use double quotes in a string literal like this:

cout << "Enter some text. Type "***" to end." << endl;

(The syntax-highlighting even changes the color of the ***.)

In order to print them out, you have to escape them as such:

cout << "Enter some text. Type \"***\" to end." << endl;

I suppose your compiler ignored the original, as I got an error when I tried it.

See this for more info on escape sequences in C++.


Project Euler - Smallest multiple (Ruby) My code is very slow to run, and I am trying to find a way to make it more efficient. I know there must be a better way than to write each modulo operation.

The goal of the script is to find the smallest possible number than can be divided by numbers 1 to 20 without a remainder.

def divide
  (2..Float::INFINITY).each do |x|
      if x % 2 == 0 && x % 3 == 0 && x % 4 == 0 && x % 5 == 0 && x % 6 == 0 && x % 7 == 0 && x % 8 == 0 && x % 9 == 0 && x % 10 == 0 && x % 11 == 0 && x % 12 == 0 && x % 13 == 0 && x % 14 == 0 && x % 15 == 0 && x % 16 == 0 && x % 17 == 0 && x % 18 == 0 && x % 19 == 0 && x % 20 == 0
        print x
        break
      end
  end
end

divide

Array provides lcm() which gives you the least common multiple of two numbers. You can apply this to an entire array by applying it to each result as you go through it. This is what reduce does.

puts (1..20).reduce{|m,n| m.lcm(n)}

or even shorter:

puts (1..20).reduce(:lcm)

Because most of the calculations are done in the ruby implementation (e.g. C for MRI), this will be fast.


Metaballs and Gravity game; For past two days I made my first OpenGL project, I know, It's fixed pipeline, but my focus was on gravity algorithm, so, tell what do you think, and how can I make it faster?

main.cpp

#pragma comment(lib, "glew32.lib")
#include <stdlib.h>
#include <string>
#include <vector>
#include <iostream>
#include <fstream>
#include "GL/glew.h"
#define GLEW_STATIC
#include <glut.h>
#define WIDTH   800
#define HEIGHT  640
#define AU      (149.6e6 * 1000)
#define SCALE   (250 / AU)
#define G       6.67428e-11

int scale = 10;

struct Vec2 {
    double x;
    double y;
};

using namespace std;

struct Object {
    int id;
    Vec2 pos;
    Vec2 vel;
    double mass;
    double r;
};

Object b = Object{ 0, Vec2{ 2 * AU, 1 * AU, }, Vec2{ 0, 20 * 1000 }, 1.98892 * pow(10, 30), 40 };
Object b2 = Object{ 1, Vec2{ 1 * AU, 1 * AU }, Vec2{ 0, -20 * 1000 }, 1.98892 * pow(10, 30), 40 };
vector<Object> bodies;
int bodyIndex = 0;

void init() {
    glClearColor(0, 0, 0, 1);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluOrtho2D(0, WIDTH, 0, HEIGHT);
    glewInit();

    glPointSize(10);

    bodies.push_back(b);
    bodies.push_back(b2);
    bodyIndex = bodies.size();
}

Vec2 attraction(Object body, Object other) {
    // Compute the distance of the other body
    double dx = other.pos.x - body.pos.x;
    double dy = other.pos.y - body.pos.y;
    double d = sqrt(pow(other.pos.x - body.pos.x, 2) + pow(other.pos.y - body.pos.y, 2));

    // Report an error if the distance is zero; otherwise we'll
    // get a ZeroDivisionError exception further down
    if (d == 0) std::cout << "[ ! ] Collision between objects is not possible;" << std::endl;

    // Compute the force of attraction
    double f = G * body.mass * other.mass / pow(d, 2);

    //Compute the direction of the force
    double theta = atan2(dy, dx);
    return Vec2{ cos(theta) * f, sin(theta) * f };
}

void render() {
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glMatrixMode(GL_MODELVIEW);

    int timestep = 24 * 3600;
    glBegin(GL_POINTS);
    for (auto b : bodies) {
        Vec2 totalForce{ 0, 0 };
        for (auto other : bodies) {
            if (bodies.at(b.id).id != bodies.at(other.id).id) {
                Vec2 force = attraction(bodies.at(b.id), bodies.at(other.id));
                totalForce.x += force.x;
                totalForce.y += force.y;
            }
        }

        bodies.at(b.id).vel.x += totalForce.x / bodies.at(b.id).mass * timestep;
        bodies.at(b.id).vel.y += totalForce.y / bodies.at(b.id).mass * timestep;
        bodies.at(b.id).pos.x += bodies.at(b.id).vel.x * timestep;
        bodies.at(b.id).pos.y += bodies.at(b.id).vel.y * timestep;

        for (int x = 0; x < WIDTH; x += scale) {
            for (int y = 0; y < HEIGHT; y += scale) {
                float sum = 0;
                for (auto b : bodies) {
                    sum += (b.r / (sqrt(pow(b.pos.x*SCALE - x, 2) + pow(b.pos.y*SCALE - y, 2))*0.001))*0.0001;
                    glColor3f(sum, sum, sum);
                    glVertex2i(x, y);
                }
            }
        }
    }
    glEnd();

    glutSwapBuffers();
}

void OnMouseClick(int button, int state, int x, int y){
    if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN){
        Object X = Object{ bodyIndex, Vec2{ x / SCALE, (HEIGHT - y) / SCALE, }, Vec2{ 0, 0 }, 3.302 * pow(10, 13), 40 };
        bodies.push_back(X);
        bodyIndex++;
    }
}

void timer(int) {
    glutPostRedisplay();
    glutTimerFunc(1000 / 60, timer, 0);
}

int main(int argc, char* argv[]) {
    glutInit(&argc, argv);
    glutInitWindowSize(WIDTH-2, HEIGHT);
    glutInitWindowPosition(500, 200);
    glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE);
    glutCreateWindow("Gravity");

    init();
    glutDisplayFunc(render);
    glutMouseFunc(OnMouseClick);
    glutTimerFunc(50, timer, 50);

    glutMainLoop();
    return 0;
}

Refactoring code structure

As of right now, you have:

A struct named Object.
A global std::vector<Object> of Objects.
A function named attraction, which (I assume) calculates the attraction between two separate Objects.
A function named render which (I assume) renders all of the objects in bodies.

While this structure works fine, it's somewhat rigid and will probably cause you issues in the future if you ever try to expand this project by any significant amount. Instead of having this structure, I'd recommend that you design something more akin to the following:

A struct (or class) named Object which represents a gravitational body, with the following member functions:

CalculateAttraction(), for calculating object attractions.
Update(), for updating anything related to the object, like position, etc.
Render(), for rendering the object.

A struct (or class) named ObjectManager which is used to store and manage objects, with the following member functions:

AddBody(), for adding a new gravitational body.
Update(), for updating the object manager and its stored Objects.
Render(), for rendering the object manager and its stored Objects.

A top-level Update() function for GLUT to use.
A top-level Render() function for GLUT to use.

While you don't have to follow this exact structure (you may also need additional behaviors included with the ones I provided), it will make managing and expanding this project much easier.

Using const instead of #define

In C++ (and even later versions of C), it's always better to use const (or constexpr in some special cases) for defining constant values rather than a macro. Using macros can often lead to obscure and confusing issues popping up, especially if you're overzealous in your use of them. The macros in your code (excluding GLEW_STATIC) should be declared as:

const int WIDTH = 800;
const int HEIGHT = 800;
const float AU = 149.6e6 * 1000;
const float SCALE = 250 / AU;
const float G = 6.67428e-11;

Instead of:

#define WIDTH   800
#define HEIGHT  640
#define AU      (149.6e6 * 1000)
#define SCALE   (250 / AU)
#define G       6.67428e-11

Nitpicks

You have a small bug in your code where you #define GLEW_STATIC. In order to use GLEW properly as a static library, GLEW_STATIC must be declared before you include glew.h. You'll also likely have to change "glew32.lib" to "glew32s.lib". Example:

#pragma comment(lib, "glew32s.lib")

...

#define GLEW_STATIC
#include "glew.h"

Please don't ever use using namespace std; in your C++ code. It's a very bad idea. See this Stack Overflow post for the reason why.
The variable bodyIndex is poorly named and unnecessary. std::vector<T> already has a size() function which returns the number of elements in the vector.
While you mentioned that you know you used the fixed function pipeline, I'm going to recommend against it anyways. It's deprecated in a lot of graphics hardware and sometimes requires some special workarounds to get working. It's also much less flexible than the programmable function pipeline.
The various #includes and #defines at the beginning of your code are are grouped together in one big cluster, which isn't very visually appealing. I'd highly recommend separating them into distinct groups, like so:

#pragma comment(lib, "glew32.lib")
...

#include <stdlib.h>
#include <string>
#include <vector>
#include <iostream>
#include <fstream>
...

#define GLEW_STATIC
#include "GL/glew.h"
#include <glut.h>
...

#define WIDTH   800
#define HEIGHT  640
#define AU      (149.6e6 * 1000)
#define SCALE   (250 / AU)
#define G       6.67428e-11
...

As you can see, there are four distinct groups here, #pragmas, standard #includes, 3rd-party #includes and #defines.


Stock quote checking script I know that this code would look a lot better if I made it so that checking the current prices against the open prices were in a function. This would avoid rewriting it for every stock I want to check. But I'm not sure how to get started on doing that properly. Do any of you have some tips to get me started?

from yahoo_finance import Share

apple = Share('AAPL')

appleopen = float(apple.get_open())
applecurrent = float(apple.get_price())

if appleopen > applecurrent:
    print(("Apple is down for the day. Current price is"), applecurrent)
else:
    print(("Apple is up for the day! Current price is "), applecurrent)

applechange = (applecurrent - appleopen)
if applechange > 0:
    print(('The price moved'),abs(applechange),("to the upside today."))
else:
    print(('The priced moved'),abs(applechange),("to the downside today."))
print('-----------------------')
nflx = Share('NFLX')

nflxopen = float(nflx.get_open())
nflxcurrent = float(nflx.get_price())

if nflxopen > nflxcurrent:
    print(("Netflix is down for the day. Current price is"), nflxcurrent)
else:
    print(("Netflix is up for the day! Current price is "), nflxcurrent)

nflxchange = (nflxcurrent - nflxopen)
if nflxchange > 0:
    print(('The price moved'),abs(nflxchange),("to the upside today."))
else:
    print(('The priced moved'),abs(nflxchange),("to the downside today."))

As you yourself noted, you need a function:

def financial_info(acronym):
    company = Share(acronym)

    company_open = float(company.get_open())
    company_current = float(company.get_price())

    if company_open > company_current:
        print(company, " is down for the day. Current price is ", company_current)
    else:
        print(company, " is up for the day! Current price is ", company_current)

    # ...

I just wrote a part of it, you sure are able to finish it :)


Table Printer excercise I'm new to Python and I came to the following excercise:

  Write a function named printTable() that takes a list of lists of
  strings and displays it in a well-organized table with each column
  right-justified. Assume that all the inner lists will contain the same
  number of strings. For example, the value could look like this:

tableData = [['apples', 'oranges', 'cherries', 'banana'],
             ['Alice', 'Bob', 'Carol', 'David'],
             ['dogs', 'cats', 'moose', 'goose']]

  Your printTable() function would print the following:

  apples Alice  dogs
 oranges   Bob  cats
cherries Carol moose
  banana David goose

My solution is this:

table_printer.py

tableData = [['apples', 'oranges', 'cherries', 'banana'],
             ['Alice', 'Bob', 'Carol', 'David'],
             ['dogs', 'cats', 'moose', 'goose']]

def printTable(tableData):
    """
    Print table neatly formatted:
    e.g:

    [['apples', 'oranges', 'cherries', 'banana'],
    ['Alice', 'Bob', 'Carol', 'David'],
    ['dogs', 'cats', 'moose', 'goose']]

    becomes:

      apples Alice  dogs
     oranges   Bob  cats
    cherries Carol moose
      banana David goose
    """
    # make list of ints to store later max len element of each list
    colWidths = [0] * len(tableData)

    # Store maxlen of each list
    i = 0
    while i < len(tableData):
        colWidths[i] = len(max(tableData[i], key=len))
        i = i + 1

    # Print formatted
    for x in range(len(tableData[0])):
        for y in range(len(colWidths)):
            print(tableData[y][x].rjust(colWidths[y]), end=' ')
        print(end='\n')

printTable(tableData)

I wonder if this is a good solution or if there is an easier/better way. It took me quite some time to come up with a solution. Still I feel its probaly not very elegant. Maybe I'm overcomplicating it because I came from C/C++ where you oftenly have to do stuff by hand.

I read that it's often not a good idea in python to write loops like in other languages with explicit indices (what I basically did here). Are there any alternatives?

Here is my proposal. It is shorter than OP's solution, specially to compute the length of each word to be used in the format procedure while printing.

In a single line, we obtain a 1D array with maximal lengths.

import numpy as np

tableData = [['apples', 'oranges', 'cherries', 'banana'],
             ['Alice', 'Bob', 'Carol', 'David'],
             ['dogs', 'cats', 'moose', 'goose']]

max_len = np.array([np.array(max([len(xii) for xii in xi])) for xi in tableData])

for col in range(len(tableData[0])):
    for i in range(len(tableData)):
        print ("{:>%d}" % max_len[i]).format(tableData[i][col]),
    print ""

Output

  apples Alice  dogs
 oranges   Bob  cats
cherries Carol moose
  banana David goose


Returning MIME types according to input filenames' extensions I am coding on codingame.com, where one of the 'easy' challenges is to assign MIME type strings to input strings of file names based on their extensions.

My code passes four out of five of the test cases, and the last one is an optimization test. A big data set is inputted, and my approach times out.

I started coding in python under a year ago, and I haven't had much practice. I would like to know what I could do to improve my code.

I have seen really short solutions to other puzzles in the 'other solutions' tab, so I am not surprised if there is a clever workaround to make this shorter.

import sys
import math

n = int(input())  # Number of elements which make up the association table.
q = int(input())  # Number Q of file names to be analyzed.

MIMETable = {}
fileNames = {}
extensions = {}
answer = ''

#extract association input to table
for i in range(n):
    # ext: file extension
    # mt: MIME type.
    ext, mt = input().split()
    MIMETable [ext.lower()] = mt
    #print(str(ext) + '\t|   ' + str(mt), file=sys.stderr)

#print('\n', file=sys.stderr)

#extract filename input
for i in range(q):
    fname = input()  # One file name per line.
    fileNames[i] = fname
    #print(str(i) + ' ' + fname, file=sys.stderr)

#   find the extensions of the filenames
#   and add them to extensions{} in lowercase as they are in MIMETable
for index, name in fileNames.items():
    if '.' in name:
        try:
            extensions[index] = name.split('.')[-1].lower()
        except IndexError:
            extensions[index] = 'unknown'
    else:
        extensions[index] = 'unknown'
    #print(extensions[index], file=sys.stderr)

#print('', file=sys.stderr)

#if there is an extension, find the corresponding MIME type
for fileIndex in range(q):
    extensionFound = False
    for mimeExtension, mimetype in MIMETable.items():
        if extensions[fileIndex] == mimeExtension:
            answer += mimetype
            extensionFound = True
            #print('extension found: ' +  extensions[fileIndex] + '\t' + mimetype, file=sys.stderr)
    if not extensionFound:
        answer += 'UNKNOWN'
    answer += '\n'

print('\n', file=sys.stderr)

# For each of the Q filenames, display on a line the corresponding MIME type. If there is no corresponding type, then display UNKNOWN.
print(answer)

You should use a list rather than a dictionary for fileNames or extensions.
You don't get any benefit for using a dictionary,
and actually makes the code slightly harder to use.
You should utilize a dictionary's \$O(1)\$ key lookup, rather than re-implement an \$O(n)\$ look up.
This is as if extensions[fileIndex] in MIMETable is already fast.
Utilize dictionary functions such as get(key, default).
You don't need three separate loops, as they are all just different sections of transforming from a file name to a MIME type.
It would also be easier to read it without the loops too.
You should follow PEP8, this means your names should be MIME_table rather than MIMEtable.
Also MIME_table looks odd, so I'd change it to mime_table.
You don't need math or sys, and so I'd remove them.
Your comments are left overs to debugging,
instead of commenting out prints when you're debugging,
I'd recommend that you use Pythons logging library.

Without merging the loops together, you can change your code to:

amount_mime_types = int(input())
amount_file_names = int(input())
mime_table = {}
for i in range(amount_mime_types):
    ext, mt = input().split()
    mime_table[ext.lower()] = mt

file_names = []
for _ in range(amount_file_names):
    file_names.append(input())

extensions = []
for name in file_names:
    if '.' in name:
        extensions.append(name.split('.')[-1].lower())
    else:
        extensions.append('unknown')

mime_types = []
for extension in extensions:
    mime_types.append(mime_table.get(extension, 'UNKNOWN'))

print('\n'.join(mime_types))

Where if you join the file_names, extensions and mime_types loops together you get:

amount_mime_types = int(input())
amount_file_names = int(input())
mime_table = {}
for i in range(amount_mime_types):
    ext, mt = input().split()
    mime_table[ext.lower()] = mt

mime_types = []
for _ in range(amount_file_names):
    name = input()
    if '.' in name:
        extension = name.split('.')[-1].lower()
    else:
        extension = 'unknown'
    mime_type = mime_table.get(extension, 'UNKNOWN')
    mime_types.append(mime_type)

print('\n'.join(mime_types))

There are still a couple ways to improve this:

You can write all this in a function.
This also improves the speed of the program.
Pre-define mime_types to an 'array' of None. mime_types = [None] * amount_file_names.
This is as lists sometimes have to move and is more a 'just in case' optimisation.


Building a 2D array "month view" for a given date I am working on a calendar widget for a project. For any given date, I need to build a 2D array representing the "Month" that the date falls in, where the rows represent weeks in the month and the cells in those rows are individual days. The weeks must start on Monday, and if the month does not start on a Monday, it must "backfill" in the days from the previous month. Similarly, if the last week in the month isn't "full" because it didn't end on a Sunday, fill the last week with the beginning of the following month.

For example, let's use today, May 26th of 2016. Given an input of new Date(2016, 04, 26), I would want an output of an array with 6 elements (the weeks), each element itself an array containing 7 date objects (the days). Because May started on a Sunday, the first date in the first week would actually be April 25th (the previous Monday). Because May ends on a Tuesday, the last date in the last week would be June 5th (the following Sunday).

function getCalendarMatrix(date){
    var calendarMatrix = []

    var startDay = new Date(date.getFullYear(), date.getMonth(), 1)
    var lastDay = new Date(date.getFullYear(), date.getMonth()+1, 0)

    // Modify the result of getDay so that we treat Monday = 0 instead of Sunday = 0
    var startDow = (startDay.getDay() + 6) % 7;
    var endDow = (lastDay.getDay() + 6) % 7;

    // If the month didn't start on a Monday, start from the last Monday of the previous month
    startDay.setDate(startDay.getDate() - startDow);

    // If the month didn't end on a Sunday, end on the following Sunday in the next month
    lastDay.setDate(lastDay.getDate() + (6-endDow));

    var week = []
    while(startDay <= lastDay){
        week.push(new Date(startDay));
        if (week.length === 7){
          calendarMatrix.push(week);
          week = []
        }
        startDay.setDate(startDay.getDate() + 1)
    }

    return calendarMatrix;
}

My code seems like it's working well, but I'm seeking input on any flaws this might have or how I could go about this in a "better" way.

I have only minor comments.

This logic appears twice, do is a good candidate to extract to a helper function to eliminate duplicate code:

(startDay.getDay() + 6) % 7;

Instead of this:

// If the month didn't start on a Monday, start from the last Monday of the previous month
startDay.setDate(startDay.getDate() - startDow);

It would be slightly more readable to move this code into a helper function with a descriptive name, for example:

function getStartingMonday(startDay, startDow) {
    // If the month didn't start on a Monday, start from the last Monday of the previous month
    return new Date(startDay.getDate() - startDow));
}

This way, the code in the caller will be shorter, and the implementation detail is not really important, it's enough to know that the returned date is the sizing day and it's a Monday.

The same goes for getting the last Sunday.

You're using semicolons inconsistently, sometimes omitting it. It would be better to use a consistent style, for example put it always.

The === is redundant here:

    if (week.length === 7){

You create week yourself, inside the function, so you know it's an array, and therefore must have an integer .length property, so a simple == is enough.


Generic PHP function for making a struct out of multiple resultsets from a stored procedure call The stored procedures must return their first resultset in the form:

(
    [index] int,
    [id] varchar(50)
)

where

[index] is 0,1,2,3,... and
[id] is the name of the struct.

As long as the first resultset returns the names of the resultsets in the same order they are returned by the stored procedure the php struct will store each struct in the struct by it's name.

Example ResultSet 0:

0,'resultsets'
1,'codes'
2,'listings'
3,'users'

Example Function Call:

$struct = genericMultiResults('exec dbo.genericProcedure');

Example Results:

$struct['resultsets'][0]; // 'resultsets'
$struct['resultsets'][1]; // 'codes'
foreach($struct['codes'] as $code) {  // loop over the records of the codes resultset
    ...
}
foreach($struct['listings'] as $listing) { /* loop over the records of the listings resultset */
    ...
}

Implementation:

function genericMultiResultSet($sql) {
    global $conn;

    // resultset holder
    $resultSets = array();
    // resultsets key name, can be changed by record 0 of resultset 0
    $resultSetsKey = 'resultsets';
    // current resultset name, only used by resultsets 1 and above, not by 0, defaults to name of 0
    $resultSetKey  = 'resultsets';

    // execute multi-resultset procedure or sql statement
    $results = sqlsrv_query($conn,$sql);
    // assume we have the first resultset, loop over resultsets
    do {
        // loop over rows in resultset
        while($row = sqlsrv_fetch_array($results,SQLSRV_FETCH_ASSOC)) {
            // if the structure is $row['index'], $row['id'] then assume it is a resultsets key
            if(isset($row['index']) && isset($row['id']) && count($row) == 2) {
                // if resultsets key not created yet, create it
                if(count($resultSets) == 0) {
                    $resultSets[$row['id']] = array();
                    // assume first record in resultset describes itself (the resultset, not the row)
                    $resultSetsKey = $row['id'];
                }
                // add entry to resultsets key
                $resultSets[$resultSetsKey][$row['index']] = $row['id'];
            // otherwise, not a resultsets key
            } else {
                // if no array for current $resultset create it
                if(!isset($resultSets[$resultSetKey])) {
                    $resultSets[$resultSetKey] = array();
                }
                // add row to it's resultset within $resultSets
                array_push($resultSets[$resultSetKey],$row);
            }
        }
        // get next key for next resultset
        if(isset($resultSets[$resultSetsKey][count($resultSets)])) {
            $resultSetKey = $resultSets[$resultSetsKey][count($resultSets)];
        }
    // get next resultset
    } while(!is_null(sqlsrv_next_result($results)));

    sqlsrv_free_stmt($results);
    return $resultSets;
}

So my implementation works perfectly, does exactly what I want, lets me edit the procedures (add remove resultsets at will) and I only have to modify my php that uses the function, I never have to touch the function.

So my question:  Is there a more elegant implementation to get the same result, ie, reference the resultsets by name set in first resultset, rather than referencing them by the order they are returned?

In the way you formed your post it looks like you were asking for a better way to do what you are already doing, which it still apears that you are. That's fine, I just had no idea what you wanted from this code. I had to walk myself through your code step by step, so some of this is just going to be repeating what you've already said in an attempt to affirm it into my mind. I don't know why I was having difficulties before, I guess, as I said, I was just being dense.

First of all, your example function call does not call the same function as the one you provided, though this is most likely just a typo.

Alright, with you so far. You seem to be saying you don't like your current output and that you desire a ResultSet that uses associative indexing rather than numerical indexing, similar to:

array(
    [ "resultsets" ] => array(),
    [ "codes" ] => array(),
    [ "listings" ] => array(),
    [ "users" ] => array()
)

However, the ResultSet I'm seeing does not have this problem. I do see you are using the $row[ 'index' ] as a key for some reason, maybe that is what you mean? You can remove those and just use automatically generated incrementals, which I'll show you below. Let's take a look at that function.

Immediately I see a global. These are bad. Avoid globals at all costs. Globals don't exist. Forget you ever heard of them. If you need a variable to exist outside of the function in which you are using it, have it be the return value. If you need it inside a new function, have it be one of the parameters required to run it. In this case, you probably defined $conn just before this function is called, just pass it as a second parameter. Or rather, pass it as the first and the SQL as the second, that way it makes sense when compared to the other functions. The best way to do this would actually be to use a class and class properties, however this is beyond the scope of this review. I'd recommend becoming a little more familar with the "Don't Repeat Yourself" and "Single Responsibility" Principles, DRY and SR respectively, before attempting to learn OOP. Though SR is not usually abbreviated I will do so to save time.

Your loop seems odd. I'm not familiar enough with SQLSRV to be 100% sure, but it looks like your code is somewhat redundant. The only reason you haven't noticed it is because the internal iterator is smart enough to know better than to reset itself. Your first loop says it will continue looping through the results while there is a next result in the array. Your second, internal loop to the first, says the same. So, because you set up your first loop as a do/while loop, it will immediately perform the first iteration without checking the condition in the first while. So, as the second while loop iterates over the same array its as if that first loop were never there. Once you exit the do statement the internal pointer on the $results array is already pointing to the end of the array, this means when it checks that while statement at the end of the do/while block it will see that its job is already done and proceed with the code. Unless I miss my guess completely, you should be able to remove the do/while loop and this should perform the same.

Now, inside your loop. This is where the DRY and SR Principles begin. SR states that a function/method/class should only be concerned with a SINGLE RESPONSIBILITY. In other words its specialized to perform one task. Usually this task is repeatable, which is where the the DRY principle comes in. DRY states that you should never repeat yourself. If you find that you are performing the same task, create a function/method/class to do that task for you. So, if you want to "fetch" or "get" something, a repeatable task, you create a function that will do just that. And if there are any other smaller tasks associated with doing this one task it should be delegated to another specialized function that does just that. So this one big function you provided could actually be broken up into a few separate, more specialized, functions. So how do we separate it?

Believe it or not, you've already got the ground work laid out for it. Because we are in a loop, anything we do can be considered a repeatable task. While this isn't the only type of "repeatable" task, it is the easiest to spot. Tasks are any group of related actions done to accomplish an end goal. In plain english we refer to a task such as, "do this". In programming we refer to them much the same, but with slightly differnt termanology, such as "if, else, for, while, do, etc...". Sounds pretty daunting, but it isn't. Not everything in an if statement needs to be separated into its own custom function. Usually its already done for us. For example, isset(), count(), and empty() are all predefined tasks that do just one thing. But sometimes we can create a larger task that uses these smaller tasks.

Hopefully with those hints you will be able to figure out how to break this up. I don't want to do all the work for you, else you'll never learn. Now, I will show you a modified if/else statement that shows how to remove those $row[ 'index' ] indices and replace them with auto-incrementing indices. I'll also make a few other improvements and try explaining them below. I don't know enough about your data structure to determine if the initial if/else statement needs to be changed, but I can work with the rest.

if( isset( $row[ 'id' ] ) {
    $resultSetsKey = $row[ 'id' ];
}
if( ! isset( $resultSets[ $resultSetsKey ] ) ) {
    $resultSets[ $resultSetsKey ] = array();
}

if(isset($row['index']) && isset($row['id']) && count($row) == 2) {
    $resultSets[ $resultSetsKey ] [] = $row['id'];
} else {
    $resultSets[ $resultSetKey ] [] = $row;
}

So, first thing you will notice, I moved the code used to set the $resultSetsKey and initial value of that array index, outside of the initial if/else statement. This is to reduce the amount of DRY violations. The new if/else statement is much smaller. Now all its concerned about is which part of the arrow to set to the $resultSets array.

I hope these points helped.


Bash manual page selection menu I wrote the following script in the hopes of streamlining the finding and reading of multiple manual pages. Since I am always looking up different utilities' manual pages I thought this would a good learning aid.

#!/bin/bash

while true
do
    echo
    echo "1) /bin"
    echo "2) /sbin"
    echo "3) /usr/bin/"
    echo "4) /usr/sbin"
    echo "5) /usr/local/bin"
    echo "6) /usr/local/lib"
    echo "7) /usr/local/share"
    echo "8) /usr/local/include"
    echo "9) exit"
    echo
    read -p 'Select a directory ' d
    if [[ $d = 1 ]]; then
        dir=/bin
    elif [[ $d = 2 ]]; then
        dir=/sbin
    elif [[ $d = 3 ]]; then
        dir=/usr/bin
    elif [[ $d = 4 ]]; then
        dir=/usr/sbin
    elif [[ $d = 5 ]]; then
        dir=/usr/local/bin
    elif [[ $d = 6 ]]; then
        dir=/usr/local/lib
    elif [[ $d = 7 ]]; then
        dir=/usr/local/share
    elif [[ $d = 8 ]]; then
        dir=/usr/local/include
    elif [[ $d = 9 ]]; then
        exit
    else
        echo 'No such directory'
        exit 1
    fi
    echo
    while true
    do
        menu=( $(ls -1 ${dir}) )
        i=0
        for m in ${menu[@]}
        do
            echo "$(( i++ ))) $(basename $m)"
        done | xargs -L3 | column -t
        echo
        echo 'Select from the list above'
        echo 'Type b to go back to main menu'
        read -p 'Type q to quit at anytime ' n
        echo
        if [[ $n = 'b' || $n = 'B' ]]; then
            break 1
        elif [[ $n = 'q' || $n = 'Q' ]]; then
            exit
        else
            for item in ${menu[$n]}
            do
                if [[ $item =~ '.txt' ]]; then
                    item="$(echo ${item%.*})"
                fi
                man $item
            done
        fi
    done
done

One thing I should point out. My /usr/local/bin directory has several .txt files. That is the reason for if [[ $item =~ '.txt' ]]; then item="$(echo ${item%.*})"; fi Maybe it is normal to have plain text files in this directory or maybe this is something I did unintentionally when experimenting writing this script. (An earlier version of this script wrote all the man pages to plain text files.) I really don't know but that's why that part of the script is there.

I think this script does what I hoped it would do so now I would like other people's opinion. Is there anything I could do better? Am I overlooking anything?

Use a table driven menu

The menu to select from /bin, /sbin and other is very repetitive.
A table-based approach would be more compact, easier to write and maintain.
Try to use an array, as you did in other places of the script.

First, put the directories in an array, for example:

dirs=('' /bin /sbin /usr/bin)  # fill the rest

Note that I added a dummy empty first element.
This is to make the 1-based indexes of your menu work with the 0-based array indexes.

Build the menu from this array using a counting loop from 1, the first non-empty element:

for ((index = 1; index < ${#dirs[@]}; index++)); do
    echo "$index) ${dirs[$index]}"
done

To validate the user input, simply check if ${dirs[$index]} is empty.
If yes, the input is invalid.

Security

  Maybe it is normal to have plain text files in this directory or maybe this is something I did unintentionally when experimenting writing this script. (An earlier version of this script wrote all the man pages to plain text files.)

No, it is not normal to have .txt files in any of those directories.
So I guess your earlier script put them there.
But a normal user should not have write access to these directories.
Which seems to suggest that you're playing with a privileged account,
possibly root.
That's a bad idea, avoid using root casually.

Simplify

You can simplify [[ $n = 'b' || $n = 'B' ]] using pattern matching: [[ $n == [bB] ]].

Strangeness

You don't need the -1 here.

menu=( $(ls -1 ${dir}) )

When inside $(...), ls does not columnize its output.

In this code, I don't see why you need basename:

echo "$(( i++ ))) $(basename $m)"

It seems the value of $m will always be a simple filename without a path part.


Computing the standard deviation of a Number array in Java (See the next iteration.)

I have this funky class method for computing standard deviation from an array of Number objects using the Stream API:

StandardDeviation.java:

package net.coderodde.util;

import java.util.Arrays;

public class StandardDeviation {

    public static double computeStandardDeviation(Number... collection) {
        if (collection.length == 0) {
            return Double.NaN;
        }

        final double average =
                Arrays.stream(collection)
                      .mapToDouble((x) -> x.doubleValue())
                      .summaryStatistics()
                      .getAverage();

        final double rawSum =
                Arrays.stream(collection)
                      .mapToDouble((x) -> Math.pow(x.doubleValue() - average,
                                                   2.0))
                      .sum();

        return Math.sqrt(rawSum / (collection.length - 1));
    }

    public static void main(String[] args) {
        // Mix 'em all!
        double sd = computeStandardDeviation((byte) 1,
                                             (short) 2,
                                             3,
                                             4L,
                                             5.0f,
                                             6.0);

        System.out.println(sd);
    }
}

Please, tell me anything that comes to mind.

You are traversing the collection twice to determine the standard deviation when you could do it in a single pass.
Also, you could accumulate quickly rounding errors with the Math.pow(x.doubleValue() - average, 2.0) call. It would be best to implement the Kahan summation algorithm (that the Stream API has for DoubleStream#sum()).
In the lambda expression (x) -> x.doubleValue(), you don't need to add the parentheses around (x). You can just have x -> x.doubleValue(). You could also use a method-reference, which avoids a lamda, and have Number::doubleValue.

On Stack Overflow, I wrote an answer which calculates the standard deviation in a single pass with compensation. It is parallel-friendly:

static class DoubleStatistics extends DoubleSummaryStatistics {

    private double sumOfSquare = 0.0d;
    private double sumOfSquareCompensation; // Low order bits of sum
    private double simpleSumOfSquare; // Used to compute right sum for
                                        // non-finite inputs

    @Override
    public void accept(double value) {
        super.accept(value);
        double squareValue = value * value;
        simpleSumOfSquare += squareValue;
        sumOfSquareWithCompensation(squareValue);
    }

    public DoubleStatistics combine(DoubleStatistics other) {
        super.combine(other);
        simpleSumOfSquare += other.simpleSumOfSquare;
        sumOfSquareWithCompensation(other.sumOfSquare);
        sumOfSquareWithCompensation(other.sumOfSquareCompensation);
        return this;
    }

    private void sumOfSquareWithCompensation(double value) {
        double tmp = value - sumOfSquareCompensation;
        double velvel = sumOfSquare + tmp; // Little wolf of rounding error
        sumOfSquareCompensation = (velvel - sumOfSquare) - tmp;
        sumOfSquare = velvel;
    }

    public double getSumOfSquare() {
        double tmp = sumOfSquare + sumOfSquareCompensation;
        if (Double.isNaN(tmp) && Double.isInfinite(simpleSumOfSquare)) {
            return simpleSumOfSquare;
        }
        return tmp;
    }

    public final double getStandardDeviation() {
        long count = getCount();
        double sumOfSquare = getSumOfSquare();
        double average = getAverage();
        return count > 0 ? Math.sqrt((sumOfSquare - count * Math.pow(average, 2)) / (count - 1)) : 0.0d;
    }

    public static Collector<Double, ?, DoubleStatistics> collector() {
        return Collector.of(DoubleStatistics::new, DoubleStatistics::accept, DoubleStatistics::combine);
    }

}

It has the same logic as DoubleSummaryStatistics but extended to calculate the sum of squares.

With such a class, you can then have:

public static double computeStandardDeviation(Number... collection) {
    return Arrays.stream(collection)
                 .map(Number::doubleValue)
                 .collect(DoubleStatistics.collector())
                 .getStandardDeviation();
}


Finding Pythagorean Triple that sums to 1000 I am doing this Project Euler Question #9:

  A Pythagorean triplet is a set of three natural numbers, \$a < b < c\$, for which,

  $$a^2 + b^2 = c^2$$

  For example, \$3^2 + 4^2 = 9 + 16 = 25 = 5^2\$.

  There exists exactly one Pythagorean triplet for which \$a + b + c =
> 1000\$.
  Find the product \$abc\$.

I have implemented the code but I feel like it runs slow and doesn't perform well enough:

def check_pathagorean(a, b, c):
    return (a**2) + (b**2) == (c**2)

SUM = 1000

for i in range(1, SUM):
    for j in range(i+1, SUM):
        c = SUM - (i + j)
        if(check_pathagorean(i, j, c)):
            if i + j + c == SUM:
                print i * j * c
                break

What could I do to make this run faster and better?

Any pythagorean triple is in form of

  $$ k(u^2 - v^2), 2kuv, k(u^2 + v^2) $$

where u, v, and k are positive integers with u > v, u − v odd, and with u and v  coprime. The sum is therefore

  $$ ku(u + 2v) $$

(the restrictions still apply).

Now your job is factor 1000 into 3 terms (not so many ways to do so, 1000 = 5*5*5*2*2*2) and determine if those terms can be represented with u and v being coprime with an odd difference.


Extracting sleep quality scores from periodic readings How can I optimize the next function to work faster? The function must prepare a list to put in a CSV file. The list must contain values of average percentage of sleep per minute counted from scores - a list of the form [[stage, time]], where stage could be 'S', 'R' or 'W' and time is in '%d %H:%M:%S' format; it's something like this:

scores = [['S', '01 12:11:00'], ['S', '01 12:11:20'], ['W', '01 12:11:40'], ['S', '01 12:12:00'], ...]

The function also must group counted values by hour and day, so the output should be like this:

quantities = [[1, 12, 11, 0.66], [1, 12, 12, 0.33], [1, 12, 13, 1], ...]

from itertools import product
import datetime

def sleep_quantity(scores):
    global quantities
    quantities = []
    for day, hour, minute in product(range(1,4), range(24), range(60)):
        sleep = 0
        total = 0
        quantity = []
        for line in scores:
            time = datetime.datetime.strptime(line[1], '%d %H:%M:%S')
            stage = line[0]
            if time.hour == hour and time.day == day and time.minute == minute:
                total += 1
                if stage == 'S' or stage == 'R':
                    sleep += 1
        if total != 0:
            sleep_per_minute = sleep / total
            quantity.append(hour)
            quantity.append(day)
            quantity.append(minute)
            quantity.append(sleep_per_minute)
            quantities.append(quantity) #for export to CSV
    return quantities

First of all the quantities global sounds unnecessary.  The value is
cleared at the start and the value is returned from the function too,
no need to clobber a global.

The way quantity is updated can be written much more concisely by
immediately appending a literal list instead of updating a variable:

quantities.append([hour, day, minute, sleep / total])

Now just another quick suggestion is to use destructuring in the inner
for loop too:

    for (stage, time_string) in scores:

Finally, the ordering of hour, day, minute in the result means that the
normal sort method on a list isn't sufficient to sort the list in a
sensible manner - I'd suggest to put it in decreasing order, i.e. day,
hour, minute.

Edit: Was updated before I ended up posting, but my assumptions still hold I think. (Unfortunately there's not much of an explanation of why this function does what it does.)

However it's immediately a concern that the way the iterations are set
up is less efficient than the other way round: the product list is
4320 elements long, while the scores list is likely much shorter -
that sounds like they should be nested the other way round.

Given that there's no explanation of what the code is supposed to do I'm
going to guess a bit on the semantics.  Now we're iterating over three
days in one minute steps, checking whether any of the elements in
scores match and do something if so.  For total, we accumulate all
the matches for that moment in time and if we got one, we append to the
quantities list.

That means, I think, that you're looking for all timestamps in the list,
which occur at the same moment, then add up the "type" of the timestamp
and append one result for each moment where there were any matches.

That can be written much better in terms of sorting (the timestamps) and
accumulating consecutive ranges instead:

def sleep_quantity2(scores):
    buckets = {}

    for stage, time_string in scores:
        time = datetime.datetime.strptime(time_string, '%d %H:%M:%S')

        stages = buckets.get(time, [0, 0])
        buckets[time] = stages

        stages[0] += 1
        if stage == "R" or stage == "S":
            stages[1] += 1

    quantities = []
    for time, stages in buckets.iteritems():
        quantities.append([time.day, time.hour, time.minute, stages[1] / stages[0]])

    quantities.sort()

    return quantities

The process is thus: accumulate entries into buckets, one bucket for
each moment and at the same time updating the numbers for that bucket,
then at the end, iterating over all buckets and producing the result
list and, since the order is arbitrary, sort them again so it matches
the output of the previous approach.

Now if you want, you can still use yield instead of accumulating the
list in place and use xrange instead of range in Python 2.7.

Oh and run a profiler.

For reference, I ended up comparing it with the following code:

def sleep_quantity1(scores):
    quantities = []
    for day, hour, minute in product(range(1, 4), range(24), range(60)):
        sleep = 0
        total = 0
        for (stage, time_string) in scores:
            time = datetime.datetime.strptime(time_string, '%d %H:%M:%S')
            if time.hour == hour and time.day == day and time.minute == minute:
                total += 1
                if stage == 'S' or stage == 'R':
                    sleep += 1
        if total != 0:
            quantities.append([day, hour, minute, sleep / total])
    return quantities


Haikuifier (Or at least Haiku Identifier) All the usual stuff. Style, substance, algorithm please! I'm vaguely considering plugging it into a bot, hence the lacklustre catching of exceptions right now.

import requests
import sys

def get_num_syllables(value):
    try:
        res = requests.get("http://www.thefreedictionary.com/" + value)
    except requests.exceptions.ConnectionError as e:
        return -1

    for word in res.text.split():
        if "<h2>" not in word:
            continue
        word = word[word.find("<h2>")+ 4:word.find("</h2>")]

        if '·' in word:
            return word.count('·') + 1
    if "Word not found in the Dictionary and Encyclopedia." in res.text:
        return -1
    return 1

def haikuify(sentence):
    sentence = sentence.strip()
    num_syllables = []
    for word in sentence.split():
        num_syllables.append(get_num_syllables(word))

    if -1 in num_syllables:
        raise SyntaxError("Someone can't spell - can't find a word from the sentence in the dictionary")

    haiku_form = [5, 7, 5]
    haiku_indices = []
    i = -1
    run = 0
    line = 0

    for value in num_syllables:
        run += value
        if run is haiku_form[line]:
            haiku_indices.append(i)
            line += 1
            run = 0
        elif run > haiku_form[line]:
            raise SyntaxError("Not a haiku")
            break
        i += 1

    haiku_indices.append(len([len(x) for x in sentence.split()]) - 1)

    if len(haiku_indices) is not 3:
        raise SyntaxError("Not a haiku")

    i = -1
    line = 0
    this_line = ""
    haiku = []
    for word in sentence.split():
        word = word.replace(" ", "")
        if not word:
            continue

        this_line += " " + word
        i += 1
        if i is haiku_indices[line]:
            haiku.append(this_line)
            this_line = ""
            line += 1

    return haiku

if __name__ == "__main__":
    sentence = input("Sentence to haikuify: ")
    haiku = []
    try:
        haiku = haikuify(sentence)
    except SyntaxError as err:
        print(err.msg)
    print(haiku)

You should be more helpful to the user, both when the entered sentence can't be made into a haiku (too short or too long) and when not finding the word in the dictionary. At least tell which word was not found in the dictionary.
Also when thefreedictionary.com is not reachable (for whatever reasons), your code will insult the user by telling him he can't spell.
You dictionary lookup fails for some words:

"sparrow's", or any possessive form (raises SyntaxError)
"banging", or any gerund form. (gives the syllables of the infinitive instead)
Any punctuation (also raises SyntaxError)

I tested your program with this haiku from wikipedia:

Snow in my shoe
Abandoned
Sparrow's nest
— Jack Kerouac, collected in Book of Haikus, 2003

And this:

Whitecaps on the bay:
A broken signboard banging
In the April wind.
— Richard Wright, collected in Haiku: This Other World, 1998

The first raises a SyntaxError and the second puts In on the end of the second line because of the gerund counting as one less syllable.
What your code also does not catch is that thefreedictionary puts a flood mechanism into place after some time. I found this out by testing my own script. In this case the fifth request in a row returns with HTTP code 403 (Access forbidden).

How I would write it:
import requests
import sys
import re

def get_num_syllables(value):
    if value.endswith("ing"):
        return get_num_syllables(value[:-3]) + 1
    try:
        res = requests.get("http://www.thefreedictionary.com/" + value)
    except requests.exceptions.ConnectionError as e:
        print("Can't connect to dictionary website: http://www.thefreedictionary.com/" + value)
        sys.exit(1)
    if res.status_code != 200:
        raise requests.exceptions.ConnectionError("Can't connect to dictionary website: http://www.thefreedictionary.com/{}, HTTP code {}".format(value, res.status_code))
    value_re = re.compile(value)
    for word in res.text.split():
        if "<h2>" not in word:
            continue
        word = word[word.find("<h2>") + 4:word.find("</h2>")].lower()
        if '·' in word:
            match = re.match(word.replace('·', ''), value)
            if not match:
                continue
            return word.count('·') + 1
    not_founds = ("Word not found in the Dictionary and Encyclopedia.",
                 "is not available in the general English dictionary")
    if any(not_found in res.text for not_found in not_founds):
        raise SyntaxError("Can't find word in dictionary: {}".format(value))
    return 1

def get_num_syllables_all(words):
    syllables = {}
    for word in words:
        word = word.lower()
        if word in syllables:
            continue
        syllables[word] = get_num_syllables(word)
    return syllables

def haiku(words, haiku_form):
    # words = "Whitecaps on the bay A broken signboard banging In the April wind".split()
    num_syllables = get_num_syllables_all(words)

    lines = [[] for _ in range(len(haiku_form))]
    count, line = 0, 0
    for word in words:
        count += num_syllables[word.lower()]
        if count > haiku_form[line]:
            raise SyntaxError("Not possible to split word at syllable boundary: {}, {}".format(word, syllables))
        lines[line].append(word)
        if count == haiku_form[line]:
            line += 1
            count = 0

    # validate the haiku
    for i, line in enumerate(haiku_form):
        sum_line = sum(num_syllables[word] for word in lines[i])
        if sum_line > line:
            raise SyntaxError("Too many syllables in line {}. Got {}, want {}".format(i, sum_line, line))
        elif sum_line < line:
            raise SyntaxError("Not enough syllables in line {}. Got {}, want {}".format(i, sum_line, line))
    return "\n".join(" ".join(line) for line in lines)

if __name__ == '__main__':
    haiku_form = (5, 7, 5)
    words = input("Please enter the words to use: ").strip().split()
    try:
        print(haiku(words, haiku_form))
    except SyntaxError as e:
        print(e)


Inserting strings in middle of a text file using streams I have a text file in a specific format that I pass as the input of my program.  I then want to write the output back to that same file.  The format is as follows:

Input1:
1 2 3 4 5 6 7

1 2 3 4 5 6 7

1 2 3 4 5 6 7
-----------------------------------------
Input2:
1 2 3 8 5 6 7

1 2 3 9 5 6 7

1 2 3 10 5 6 7
-----------------------------------------
Input3:
1 2 3 4 5 6 7

1 2 3 4 5 6 7

1 2 3 4 5 6 7

If I want to process Input2 and add the output, the resulting file should be:

Input1:
1 2 3 4 5 6 7

1 2 3 4 5 6 7

1 2 3 4 5 6 7
-----------------------------------------
Input2:
1 2 3 8 5 6 7

1 2 3 9 5 6 7

1 2 3 10 5 6 7
    output: 1 2 3 4 5 6 7
-----------------------------------------
Input3:
1 2 3 4 5 6 7

1 2 3 4 5 6 7

1 2 3 4 5 6 7

I am looking for a way to insert lines into that section.  For that I wrote the following routine:

//string fileName: Filename on which read and write operation are being done
//int outputNumber: Number of output to be written
//int nInputLine: How many lines each input is taking
//int nOuputLine: How many lines each output is taking. For now it is not
//being used
//string outpur: Output to be Written
void CFirstIO::WriteOutPut(string fileName, int outPutNumber, int
 nInputLine, int nOutPutLine, string outPut)
{
  ifstream fileSt(fileName.c_str(),ios::binary);
      if(fileSt.good() && fileSt.is_open())
  {
    //Storing the content of the file in a string
    fileSt.seekg(0,ios::end);
    int nLength=fileSt.tellg();
    fileSt.seekg(0,ios::beg);
    char *buff = new char[nLength];
    fileSt.read(buff,nLength);
    string strFileContent(buff);
    delete []buff;

    string strToFind;
    char formatinput[256];
    sprintf(formatinput,"Input%d:",outPutNumber);
    strToFind+=formatinput;

    fileSt.seekg(0,ios::beg);
    int nPos= strFileContent.find(strToFind,0);
    fileSt.seekg(nPos);

    //Trying to reach at the bytes Number where I want to insert the
    //output
    string sLine;
    for(int i=0; i<nInputLine+1;i++)
    {
        if(!fileSt.eof() && fileSt.good())
        getline(fileSt,sLine);
    }

    nPos=fileSt.tellg();
    strFileContent.insert(nPos,outPut);
    fileSt.close();

    ofstream fileOut(fileName.c_str(),ios::out|ios::trunc);
    fileOut<<strFileContent;

    fileOut.close();

    }
}

This function works, but adds some unintended characters at the end of the file when reading the whole file in the buffer.

All in all, this function does not look nice to me as I feel like I'm not using the full potential of the standard library.  How could my code be improved?

First and foremost, fix your formatting.  A little bit of effort spent on making the code readable will mean that it can be understood (and thus reviewed) faster.  By the way, you are not using the STL.

Now, significant issues in order of when they appear in your code:

Use an std::vector in favour of new[] pretty much always.  In this case, as the content is all text, an std::string may be even better, but causes problems due to you wanting to read directly into it.
As you want to work with the input on a line-by-line basis, I would advise an std::vector<std::string> that you can populate using a std::string line; while (fileSt >>
line) lines.push_back(line);.  There may be more efficient solutions, but check that you really need them first.
What you're doing with sprintf doesn't make sense.  That could all be replaced with std::string strToFind = "Input" + boost::lexical_cast<std::string>(outPutNumber);.
Notice that if you store the strings as I recommended above, finding a certain line is as simple as lines[nInputLine].
To write everything back, just insert another line into the vector and then write it using a loop or with stream iterators.
No need to explicitly close the files unless you care about the exception that may throw.

And some minor issues:

Your comments are inconsistent, and duplicate information.  You have specified the type everywhere except for in filename, despite the type already being given by the signature.
No need to check for fileSt.good() when checking if its open.
As your function only does anything if the file is opened successfully, return early instead of wrapping the whole thing in a giant if.
Be consistent with qualifying things with std::; do it or don't do it, but don't mix it.  (I would advise explicitly qualifying things above using-declarations (and even more so above using-directives), but all three may be acceptable.)
Same with Hungarian notation: even if you don't agree that the qualifiers don't help with anything, you should at least either use them consistently.


Find all combinations of 4 elements whose sum equals a target in Python I wrote a solution to find all combinations of 4 elements from a list whose sum of elements equals some target

  Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.

If there is better way for me to do it? it seems like the performace for the following code is too bad.

def fourSum(self, nums, target):
    """
    :type nums: List[int]
    :type target: int
    :rtype: List[List[int]]
    """
    from itertools import combinations
    if len(nums) <= 3:return []
    res, col = [], []
    for i in combinations(nums, 4):
        check = set(i)
        if sum(i) == target and check not in col:
            res.append(list(i))
            col.append(check)
    return res

Lists are pretty inefficient for this type of thing. The majority of the complexity is from iterating over the lists and comparing contents. Sets use a hash for their content, reducing complexity.

When using sets, most of the complexity comes from the combinations function.

Here are the results of a time test on your code

res1 = Solution().fourSum([-5,5,4,-3,0,0,4,-2],4)
print(time.time() - start)
# 0.0001342296600341797

The results of a method using only sets

res = Solution().fourSum([-5,5,4,-3,0,0,4,-2],4)
print(time.time() - start)
# 9.918212890625e-05

Code for the second function
(updated to prevent 3-number outputs)

class Solution:
    def fourSum(self, nums, target):
        from itertools import combinations
        res = set()
        # Create all possible combinations

        for i in combinations(nums, 4):
            if sum(i) == target:
                # Turns the tuple of numbers into list of strings
                # Then joins them into a single string
                # This allows hashing for the set
                res.add(" ".join(sorted(list([str(x) for x in i]))))
            # Splits the strings into lists of ints
        return list([ [int(z) for z in x.split()] for x in res])


Matasano CryptoPals Problem 8: Detecting ECB encryption For the Matasano CryptoPals Challenges Set 1 Problem 8, which states:

  In this file are a bunch of hex-encoded ciphertexts.

  One of them has been encrypted with ECB.

  Detect it.

  Remember that the problem with ECB is that it is stateless and deterministic; the same 16 byte plaintext block will always produce the same 16 byte ciphertext.

I have written the following Python Code. Since I'm a programmer coming from C++ to Python, some of it might be reminiscent of that transfer. Can I be more Pythonic than the code I've written? Any more suggestions?

#! /usr/bin/env python

from binascii import a2b_hex

def is_ECB_encoded(data, block_size):
  block_count = len(data)/block_size
  for i in range(block_count):
    for j in range(i+1,block_count):
      if data[i*block_size:(i+1)*block_size] == data[j*block_size:(j+1)*block_size]:
        return True
  return False

filename = '8.txt'
for line in open(filename):
  line = line.strip()
  if is_ECB_encoded(a2b_hex(line), 16):
    print line

Assuming your algorithm is correct:

Follow the pep8 style guide.
You should use range(0, len(data), block_size) so you don't have to do all the multiplication over and over.
You can use itertools.combinations to reduce it to only one loop.
You don't close the file.  You should use with to open and close the file.
You can use zip (or for python2 itertools.izip) to get both the first and second index at the same time.
You can simplify the whole thing using any and a generator expressions.
You can use str.join to simplify the printing.

Since iterators and generator expressions are lazy evaluated, it won't create any intermediate arrays.  This makes it very fast but also very readable.

from binascii import a2b_hex
from itertools import combinations, izip

def is_ecb_encoded(data, block_size):
   myrange = range(0, len(data), block_size)
   inds = combinations(zip(myrange, myrange[1:])), 2)
   return any(data[i1:i2] == data[j1:j2] for (i1, i2), (j1, j2) in inds)

filename = '8.txt'
with open(filename) as fobj:
   lines = (line.rstrip() for line in fobj)
   lines = (a2b_hex(line) for line in lines)
   lines = (line for line in lines if is_ecb_encoded(line, 16))
   print '\n'.join(lines)


Check whether a given sequence can be rearranged using a stack Working on a problem, for a given input sequence to a stack, check whether it could produce (using stack push/pop operations) the output sequence.

For example if input is [1,2,3,4,5], possible output is [4,5,3,2,1] (push 1, push 2, push 3, push 4, pop 4, push 5, pop 5, pop 3, pop 2, pop 1), but [4,3,5,1,2] is not a feasible output.

Here is my code written in Python 2.7, and wondering if logically is correct?

stackInput = [1,2,3,4,5]
expOutput = [4,5,3,2,1] # return True
#expOutput = [4,3,5,1,2] # return False
stack = []
outputIndex = 0
result = True
i = 0

while i < (len(stackInput)):
    stack.append(stackInput[i])
    i += 1
    while outputIndex < len(expOutput) and stack[-1] == expOutput[outputIndex]:
        stack.pop(-1)
        outputIndex += 1

print outputIndex == len(expOutput)

FYI, this question is probably off-topic here because you asked "if [the code] is correct" instead of merely asserting that it was correct and waiting for someone else to find the bugs. ;)  However, I think your code is correct, although it can be improved.

The biggest improvement you should make is to use functions. See your first few lines?

stackInput = [1,2,3,4,5]
expOutput = [4,5,3,2,1] # return True
#expOutput = [4,3,5,1,2] # return False

Commented-out code is a code smell. In this case, the root problem is that you need a way to run your algorithm with two (or more) different inputs... and the structured-programming solution to that is to use a function. Example:

def canBeReachedByStackManipulations(stackInput, expOutput):
    # ...
    return outputIndex == len(expOutput)

assert canBeReachedByStackManipulations([1,2,3,4,5], [4,5,3,2,1]) == True
assert canBeReachedByStackManipulations([1,2,3,4,5], [4,3,5,1,2]) == False

Ta-da, your whole program works without needing manual commenting-and-uncommenting! And as a bonus, you've gotten started on writing unit tests for your function.

By the way, I called the parameters stackInput and expOutput because that's what you did; but in practice I would call them input and output.

i = 0
while i < (len(stackInput)):
    stack.append(stackInput[i])
    i += 1

First, (len(stackInput)) is a silly way to write len(stackInput).

Second, you should learn about for-loops. What you wrote is equivalent to

for value in stackInput:
    stack.append(value)

and if you actually needed the i for some reason, you could have written

for i, value in enumerate(stackInput):

It's strange that you call your output index outputIndex but you call your input index i. Your readers will appreciate it if you keep symmetry as much as possible: write inputIndex and outputIndex, or else write i and j, but don't mix and match like that.

result appears to be unused. This is especially obvious once you start using functions, because then it becomes an unused local variable, and there are plenty of tools out there (e.g. pyflakes or pep8) which will "lint" your code for unused variables and other trivial mistakes. You should get in the habit of using one of these linters and fixing all the issues it finds, even before you run your code for the first time.

Finally, here's your bug! (Remember how I said I thought your code was correct? Well, I did...)

assert canBeReachedByStackManipulations([1,2,3], [1,2,3]) == True

Traceback (most recent call last):
  File "x.py", line 17, in <module>
    assert canBeReachedByStackManipulations([1,2,3], [1,2,3]) == True
  File "x.py", line 10, in canBeReachedByStackManipulations
    while outputIndex < len(expOutput) and stack[-1] == expOutput[outputIndex]:
IndexError: list index out of range


Towers of Hanoi in Haskell Of course the recursive version is trivial:

hanoi n = solve n 1 2 3

solve 0 _ _ _ = []
solve n from help to = (solve (n-1) from to help) ++ [(from,to)] ++ (solve (n-1) help from to)

However my iterative version looks terrible with a lot of code repetition:

hanoi n = map rep $ solve [1..n] [] [] where
          rep (x,y) | odd n = ([1,3,2] !! (x-1), [1,3,2] !! (y-1))
                    | otherwise = (x,y)

solve from help to = head $ mapMaybe ready $ iterate step (from,help,to,[]) where
   step (1:xs,ys,zs,sol) = let (xs',zs',sol') = try xs zs 1 3 ((1,2):sol)
                           in (xs',1:ys,zs',sol')
   step (xs,1:ys,zs,sol) = let (xs',ys',sol') = try xs ys 1 2 ((2,3):sol)
                           in (xs',ys',1:zs,sol')
   step (xs,ys,1:zs,sol) = let (ys',zs',sol') = try ys zs 2 3 ((3,1):sol)
                           in (1:xs,ys',zs',sol')
   try [] [] _ _ sol = ([],[], sol)
   try (x:xs) [] a b sol = (xs,[x], (a,b):sol)
   try [] (y:ys) a b sol = ([y],ys, (b,a):sol)
   try (x:xs) (y:ys) a b sol | x < y = (xs,x:y:ys, (a,b):sol)
                             | y < x = (y:x:xs,ys, (b,a):sol)
   ready ([],[],_,sol) = Just $ reverse sol
   ready ([],_,[],sol) = Just $ reverse sol
   ready _ = Nothing

Any ideas? More general, how to deal with situations like this where you have a lot of different cases and args?

[Clarification]

With "iterative solution" I mean the algorithm described here: http://en.wikipedia.org/wiki/Tower_of_Hanoi#Iterative_solution

Umm. What about

import Data.Bits
hanoi :: Int -> [(Int, Int)]
hanoi n = map (\x -> ((x .&. (x-1)) `mod` 3, ((x .|. (x-1)) + 1) `mod` 3)) [1..shift 1 n]
main = print $ hanoi 5

?