SQL stored procedure for fruit checks with several joins I developed a SQL stored procedure which works lovely, but when under stress, it takes more than 2 minute to get back to the user. I am providing the stored procedure but would also provide the table structure if required.

/* Stored procedure to get fruits checks that the user has access to*/
ALTER procedure [dbo].[Fruits_GetChecksForUser]
(
    @UserID VARCHAR(200),
    @CheckUrlFilter varchar(256)
)
AS

SELECT Distinct
    Fruits_Checks.*,
    ManagementCommittees.Title As CommitteeName,
    FruitCategories.ID As CategoryID,
    FruitCategories.Title As CategoryName,
    dbo.IsUserInGroup(@UserID, FruitCategories.FruitOfficerGroupID) AS IsUserFruitOfficer,
    dbo.IsUserInGroup(@UserID, Fruits_Checks.AllocatedGroup) AS IsUserCheckResponsible,
    Policies.CompanyID,
    Policies.ID As PolicyID

FROM Groups_UserAccess
INNER JOIN FruitCategories_GroupAccess ON FruitCategories_GroupAccess.GroupID = Groups_UserAccess.GroupID
INNER JOIN FruitCategories ON FruitCategories.ID = FruitCategories_GroupAccess.FruitCategoryID
INNER JOIN Policies ON Policies.ID = FruitCategories.PolicyID
LEFT JOIN Policies_AppSettings ON Policies_AppSettings.PolicyID = Policies.ID
LEFT JOIN Clients_AppSettings ON Clients_AppSettings.ID = Policies.CompanyID
FULL OUTER JOIN Fruits ON Fruits.CategoryID = FruitCategories.ID
INNER JOIN Fruits_Checks ON Fruits_Checks.FruitID = Fruits.ID
INNER JOIN ManagementCommittees on Fruits_Checks.CommitteeID = ManagementCommittees.ID

WHERE
    Fruits.ID IS NOT NULL
    AND Fruits_Checks.URL LIKE '%' + @CheckUrlFilter + '%'

ORDER BY Fruits_Checks.EndDate

There are a couple of things slowing you down.

Two Left Outer Joins and a Full Outer Join.

There may not be much you can do about this unless you can trim down the fields that need to be returned. Start with trying to remove the Full Outer Join. It will have worse performance than the Left Outer Joins.
Scanning an entire field will also be a bit on the slow side, but again, there may be little you can do beyond making sure there are proper indices on the table if this is truly a requirement.

LIKE '%' + @CheckUrlFilter + '%'

It looks very much like this is a requirement.
It's poor practice to select all fields from a table using the table.* notation. Doing this will force the RDBMS to lookup the table's meta data. I've found that it's pretty rare that I'll need every column from a table. It's best to be explicit about what you're selecting, even if you're selecting everything. Any performance improvement from this will be marginal, but it has the benefit of protecting your code from breaking if the underlying table changes.

I don't know enough about the data or requirements to give any real concrete advice, but nixing that Full Outer Join is the best bet for getting a performance boost. Looking at your query carefully, it doesn't seem that you ever select from Fruits so you should be able to replace the Null check on the ID with a Where Exists clause and get rid of the Full Outer Join altogether. Something like...

WHERE EXISTS(
        SELECT FRUITS.ID
        FROM FRUITS
        WHERE Fruits.CategoryID = FruitCategories.ID
)


Implement HTTP server using libevent #include "fmt/format.h"
#include <cstdint>
#include <cstdio>
#include <event2/event-config.h>
#include <event2/util.h>
#include <evhttp.h>
#include <memory>
#include <type_traits>
auto
main() -> int
{
    constexpr char host[] = "127.0.0.1";
    std::uint16_t port = 5555;

    using event_base_new_type
        = std::pointer_traits<decltype(event_base_new())>::element_type;
    using event_base_deleter_type = decltype(&event_base_free);
    auto event_base
        = std::unique_ptr<event_base_new_type, event_base_deleter_type>(
            event_base_new(), &event_base_free);

    if(!(event_base))
    {
        fmt::print(stderr, "Failed to init libevent.\n");
        return -1;
    }

    using evhttp_new_type
        = std::pointer_traits<decltype(evhttp_new(event_base.get()))>::element_type;
    using evhttp_deleter_type = decltype(&evhttp_free);
    auto http = std::unique_ptr<evhttp_new_type, evhttp_deleter_type>(evhttp_new(event_base.get()), &evhttp_free);

    auto handle = evhttp_bind_socket_with_handle(http.get(), host, port);
    if(!handle)
    {
        fmt::print(stderr, "Failed to init http server.\n");
        return -1;
    }
    auto callback = [](evhttp_request* req, void*) {
        auto* OutBuf = evhttp_request_get_output_buffer(req);
        if(!OutBuf)
            return;
        evbuffer_add_printf(OutBuf,
            "
Hello World!
");
        evhttp_send_reply(req, HTTP_OK, "", OutBuf);
    };
    evhttp_set_gencb(http.get(), callback, nullptr);
    if(event_base_dispatch(event_base.get()) == -1)
    {
        fmt::print(stderr, "Failed to run messahe loop.\n");
        return -1;
    }

    return 0;
}

Compile

g++ a.cpp -lfmt -levent

Run

$ ./a.out
$ ab -c 1000 -k -r -t 10 http://127.0.0.1:5555/

Open http://127.0.0.1:5555/ in browser

What I want to know:

Is my unique_ptr necessary? valgrind reports no memory leak even though I don't use unique_ptr nor free manually.
more elegant/correct code.

Not too much to review as the code uses evhttp to handle HTTP and provide a basic, static reply for each request.

Why is host constexpr, but not the port?

All those using statements, combined with traits and decltype one after the other makes the code very hard to read, almost obscuring the fact that evhttp is being initialized at that point. I would try to rewrite that part in a simpler way.

Why auto main() -> int instead of the simple, classic int main()?


Project Euler #1 - Multiples of 3 and 5 If we list all the natural numbers
  below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum
  of these multiples is 23.

  Find the sum of all the multiples of 3 or 5 below 1000.

Can someone give me suggestions on how to improve this solution? Also, please tell me whether or not my programming style is good.

#include<stdio.h>

int main()
{
    int a,b,c,d,sum3,sum5,sum15,total_sum;
    b=999/3;
    c=999/5;
    d=999/15;
    sum3=b*(3+999)/2;
    sum5=c*(5+995)/2;
    sum15=d*(15+990)/2;
    total_sum=sum3+sum5-sum15;
    printf("%d",total_sum);
    return 0;
}

Functions in C with no parameters should have a void parameter:

int main(void)

Variables should be declared/initialized on separate lines:

int a;
int b;
int c;
int d;
int sum3;
int sum5;
int sum15;
int total_sum;

Try to avoid single-character variable names.  They're very ambiguous and say nothing about the variable's purpose.  The only valid exception to this is loop counter variables.
Statements/blocks of different purposes should be separated to increase readability.  That would be the divisions, the sums, and the printf().
Your operands should be spread out to make the lines more readable:

sum3 = b * (3+999) / 2;

Initializations should be done as late as possible to help aid in maintenance:

sum3 = b * (3+999) / 2;

Remove int a since it's never used.


Login Script Utilising List Comprehension This a fairly basic script I made for use in some other projects, nothing too complex or sophisticated and obviously lacking in some features (Password/Username encryption, Missing file contingencies etc.).

It loads a text file (formatted as USERNAME, PASSWORD\nUSERNAME, PASSWORD\n) into a 2D array, then checks the inputs against it, until 2 separate logins are used.

I'm what I'd consider intermediate in terms of python competency, but there are always things to be improved upon: any suggestions? I tend to use something similar to this for all projects that require a login, so any improvements or areas to look into, no matter how minor, would be greatly appreciated.

def login():
    player_count, details = 0, [[data.strip() for data in line.split(",")] for line in open("username_password.txt", "r").read().splitlines()]
    while player_count != 2:
        username, password = input("USERNAME"), input("PASSWORD")
        for data in details:
            if username == data[0] and password == data[1]:
                print("LOGIN CORRECT")
                details.pop(details.index(data))
                player_count += 1
                break
        else:
            print("INCORRECT")
    main()

def main():
    print("LOGGED IN\nMAIN")

login()

I would split off player_count = 0 to a different line. Multiple assignments on one line is perfectly fine for simple assignments (like a, b = 1, 2), but a double list comprehension doesn't qualify for "simple".

Readability Counts

In general, Readability is far more important than conciseness. In fact, the reason concise code is often better is because it's more readable.

Normally, I'd be very careful with double list assignments for that reason. However, in this specific case, I think making it a single line is a good call. It's not overly long nor complex.

Performance

For pure python, I don't think you can really improve your performance even more. You won't get any issues until your password file grows into the MB's, and if that's a problem, you shouldn't be using a file with plaintext passwords anyway, since you'll be running your software in a production environment.

Instead, you'd be hashing and salting your passwords and storing them in a database, which is coincidentally also the best way to improve your performance if you get datasets that large.

However, as long as your username and password are requested from the user by means of the input() function, you won't have an issue.

dict.pop()

This function removes the value from the list. However, you don't seem to be actually doing anything with that value, and you're also discarding the list. So I'd just drop that line.

The only thing I can imagine you fix it would be to stop player2 from using the same credentials as player1. However, you don't save player references anyway. If you want to stop the same credentials from being used twice, I'd recommend to instead save references to the players for later, and then check that a player hasn't already been logged in as another player.


Write millions of lines to a file - Python, Dataframes and Redis I have the following code snippet that reads a CSV into a dataframe, and writes out key-values pairs to a file in a Redis protocol-compliant fashion, i.e. SET key1 value1. The code is piecemeal and I have tried to use multiprocessing, though I am not sure of its performance (gains).

The CSV has about 6 million lines, that is read into a dataframe pretty quickly (under 2 minutes). The output file has 12 million lines (2 lines per line of the input file). This takes about 50 minutes to complete. Can any part of my code be optimized/changed to make this run faster? Once the file is complete, loading it to Redis takes less than 90 seconds. The bottleneck really is in writing to the file.

I was looking into loading all the strings I generate into a dataframe and then use the to_csv() function to dump it to a file, but I'm not sure of how its performance will be.

filepath = '/path/to/file.csv'

def df_to_file:
    df = pd.read_csv(filepath)
    f = open('output_file', 'w')
    for i in range(len(df.index)):
        if df['col1'].iloc[i] != '':
            key1 = str_const1+str(df['col1'].iloc[i])+str(df['col4'].iloc[i])+str(df['col5'].iloc[i])+...+str(df['col_n'].iloc[i])
            val1 = df['col_n+1'].iloc[i]

            key1a = str_const1a+str(df['col1'].iloc[i])+str(df['col4'].iloc[i])+str(df['col5'].iloc[i])+...+str(df['col_n'].iloc[i])
            val1a = df['col_n+2'].iloc[i]

            print('SET {0} {1}\nSET {0} {1}'.format(key1, val1, key1a, val1a), file = f)

        if df['col2'].iloc[i] != '':
            key1 = str_const2+str(df['col2'].iloc[i])+str(df['col4'].iloc[i])+str(df['col5'].iloc[i])+...+str(df['col_n'].iloc[i])
            val1 = df['col_n+1'].iloc[i]

            key1a = str_const2a+str(df['col2'].iloc[i])+str(df['col4'].iloc[i])+str(df['col5'].iloc[i])+...+str(df['col_n'].iloc[i])
            val1a = df['col_n+2'].iloc[i]

            print('SET {0} {1}\nSET {0} {1}'.format(key1, val1, key1a, val1a), file = f)
        if df['col3'].iloc[i] != '':
            key1 = str_const3+str(df['col3'].iloc[i])+str(df['col4'].iloc[i])+str(df['col5'].iloc[i])+...+str(df['col_n'].iloc[i])
            val1 = df['col_n+1'].iloc[i]

            key1a = str_const3a+str(df['col3'].iloc[i])+str(df['col4'].iloc[i])+str(df['col5'].iloc[i])+...+str(df['col_n'].iloc[i])
            val1a = df['col_n+2'].iloc[i]

            print('SET {0} {1}\nSET {0} {1}'.format(key1, val1, key1a, val1a), file = f)
    f.close()

p = Process(target = df_to_file)
p.start()
p.join()

I'm not a hard core Pythonista, but a few points I can think of are:

The assignments of key1, val1, ... appear unneeded as they're used only once in the call to format()
Terminate each if with a continue, or use else, as it appears that only one branch is executed in each iteration of the range. Order the conditions according to data's expected distribution if possible (i.e. most frequently evaluated to true condition comes first)
Try writing less, e.g. see if you can use MSET to shave a few bytes in each iteration (times millions this may have significant effects ;))

Lastly, it looks that you're not using the last two arguments you pass to format, so if that isn't a typo you can remove them as well.


C# consecutive and redundant null checks I am working on a C# application and I want to support multiple themes, so I wrote a ThemeManager class that can check, load and apply a specific theme. A theme is considered valid, when all of it's member variables are set (not null). If a theme is invalid I want to throw an IncompleteThemeException. However the following code feels a bit stupid...
public static void Load(Theme theme)
{
    AccentBrush = theme.AccentBrush ?? throw new IncompleteThemeException();
    AccentBrushLight = theme.AccentBrushLight ?? throw new IncompleteThemeException();
    WarningBrush = theme.WarningBrush ?? throw new IncompleteThemeException();
    WarningBrushLight = theme.WarningBrushLight ?? throw new IncompleteThemeException();
    ErrorBrush = theme.ErrorBrush ?? throw new IncompleteThemeException();
    ErrorBrushLight = theme.ErrorBrushLight ?? throw new IncompleteThemeException();
    MainBackgroundBrush = theme.MainBackgroundBrush ?? throw new IncompleteThemeException();
    InactiveDecoratorBrush = theme.InactiveDecoratorBrush ?? throw new IncompleteThemeException();
    SecondaryBackgroundBrush = theme.SecondaryBackgroundBrush ?? throw new IncompleteThemeException();
    MainTextBrush = theme.MainTextBrush ?? throw new IncompleteThemeException();
    SecondaryTextBrush = theme.SecondaryTextBrush ?? throw new IncompleteThemeException();
    DefaultPasswordIndicatorBrush = theme.DefaultPasswordIndicatorBrush ?? throw new IncompleteThemeException();

    AccentColor = theme.AccentColor ?? throw new IncompleteThemeException();
    MainBackgroundColor = theme.MainBackgroundColor ?? throw new IncompleteThemeException();
    AccentColorLight = theme.AccentColorLight ?? throw new IncompleteThemeException();
}

I thought about maybe using reflection to somehow iterate over all members of the theme instance to check if one of them is null, but I'm unsure what the best solution to this would be in terms of readability, performance and extensibility in the future.
How can this be improved?

Two things to think about:

Could you code this so it's impossible to create an invalid Theme instance thus not having to worry about it in this method?
How does a consumer know what is invalid about their instance?

For 1, you could simply have a constructor that takes all of the arguments and throws if any are invalid. A pattern that can also work well is having defaults - that way, a theme can just override part of the default theme rather than having to specify everything.
For 2, add some context to your exceptions:
throw new IncompleteThemeException("Default Password Indicator Brush was not specified");

However, I would probably lean towards having a mutable builder class with defaults and have a create method there. Consuming it could look like:
var builder = new ThemeBuilder(Theme.Default /* or existing theme etc. */)
     .WithErrorBrush(myErrorBrush)
     .WithAccentBrush(myAccentBrush);

// Now build it.
var theme = builder.Build();

That seems like it would make it easier for consumers to use a Theme as all instances would always be valid and you get the ease of use via the builder class. A nice bonus is that you can add new properties to the theme without breaking consumers. They get a sensible default that they can choose to override if needed. You don't just start throwing IncompleteThemeException.


Scripts loading Scripts Dynamically in Lua I have been working with Lua lately and I have discovered that it is capable of doing some very interesting things. I have created a proof of concept that allows one Lua script to load another Lua script and use the loaded script to modify itself by passing itself as an argument to the creation function of the loaded script.  The basic example here is from a simple card game.

In this specific example, I have a Card "object" which is really just a LuaTable. At the top of the Player.lua script I have:

local card = require "Card"

Then I create a card "object" by calling:

function Player:addSpecificCardToDeck(cardSuit, cardType, cardId)
    table.insert(self.deck, card:new(cardSuit, cardType, cardId))
end

The Card.lua script loaded by require contains code that loads another script during its creation.  Here is the Card.lua script.  Please ignore cardSuit in this example as that code is incomplete and I have omitted it.

Card.lua

Card = {} -- the table representing the class, which will double as the metatable for the instances
Card.__index = Card -- failed table lookups on the instances should fallback to the class table, to get methods

local cardList = require "Cardlist"

-- syntax equivalent to "MyClass.new = function..."
function Card:new(cardSuit, cardType, cardId)

    local self = setmetatable({}, Card)

    self.id = cardId
    self.type = cardType

    --this is where another script is loaded
    print(self.id .. " cardID")
    --getAbilityScriptsForId returns the appropriate string
    self.testScript = require (cardList:getAbilityScriptsForId(2)) --2 is the proof of concept script being called
    test = self.testScript:new(self)
    test:increaseCardId()
    print(self.id.. " new cardID") --the cardID will have increased by 1

    return self
end

return Card

Here is the sample script being loaded:

SampleScript02.lua

SampleScript02 = {} -- the table representing the class, which will double as the metatable for the instances
SampleScript02.__index = SampleScript02 -- failed table lookups on the instances should fallback to the class table, to get methods

-- syntax equivalent to "MyClass.new = function..."
function SampleScript02:new(inputCard)

    self.card = inputCard

    return self
end

function SampleScript02:increaseCardId()
    self.card.id = self.card.id + 1
end

return SampleScript02

As stated in the comments, the self.id of the script that loads the sample script will be incremented by 1.  In theory, a script could pass itself into any potential script that modifies it.  When a table is passed as the argument to a function in Lua, changes made to it inside that function apply to the original table.  In contrast, when values such as integer or boolean are passed into a function, a copy is made instead.

What I am looking for is whether I am following the best practices for Lua, and also how to avoid any potential pitfalls that the language presents. Am I using require properly? I am still learning the language, so any tips on syntax are also much appreciated.

On the first line, Card = {} should be local Card = {}, otherwise Card becomes a global, breaking encapsulation. You might want to consider using strict.lua or another method of "locking" the global table to prevent mistakes like this.

Having Card double as the metatable for card instances is pretty unusual. It will work, but now Card and each of its instances are polluted with an __index property, and this could be avoided simply by writing setmetatable({}, { __index = Card }) instead of setmetatable({}, Card), which is probably what people would expect to see anyway.

You declare the function as Card:new; it has an implicit self argument because of the colon. But you never use that argument; instead, you shadow it with a local variable named self. You probably wanted to do something like local instance = setmetatable({}, self), although as mentioned it would probably be better not to have Card double as the metatable for instances, so instead you could use local instance = setmetatable({}, { __index = self }).

local Card = {}

function Card:new(cardSuit, cardType, cardId)
    local instance = setmetatable({}, { __index = self })

    instance.id = cardId
    instance.type = cardType

    -- ...

    return instance
end

return Card

The same things apply to your second block of code.


Updating tables with bulk of data through CSV My work is pretty simple.  I have to migrate a bulk of data into the specified tables, so that the data does show up at the front-end.  The data is provided through the Excel sheet and I have to convert it into a CSV file with $ as a field delimiter.

And later I have to write a method in an Active Record Model to perform the migration.

def self.discipline_and_speciality_migration_21Jan14

  filename = "#{RAILS_ROOT}/config/discipline_and_speciality_migration_220114.csv"
  file=File.new(filename,"r")

  while (line = file.gets)
  columns = line.split("$")

  location = Location.find_by_name(columns[2].to_s.chomp.strip)
  if location.blank?
  location = Location.create!(:name => columns[2].to_s.chomp.strip,:short_name => columns[2].to_s.slice(0,11) , :status => "Active")
   end

   discipline = Discipline.find_by_name_and_location_id(columns[0].to_s.chomp.strip,location.id)
   if discipline.blank?
   discipline = Discipline.create!(:name=>columns[0].to_s.chomp.strip,:status=>'Active',:location_id => location.id,:code=> columns[1].to_s.chomp.strip)
    else
    discipline.update_attributes(:location_id => location.id)
    end

    speciality = Speciality.find_by_name_and_location_id(columns[3].to_s.chomp.strip)
    if speciality.blank?
    speciality = Speciality.create!(:name => columns[3].to_s.chomp.strip,:status=>'Active',:location_id => location.id,:code=> columns[4].to_s.chomp.strip,:discipline_id => discipline.id)
     else
     speciality.update_attributes(:location_id => location.id,:discipline_id => discipline.id)
     end
    end
    end

I have no Issues with the code.  I am just wondering is there any better approach to do this.  Is CSV the only way? Notable modifications in the code are also welcomed.

You can use first_or_initialize and first_or_create! to skip the if...else statementes.

location = Location.where(name: 'New York').first_or_create! do |loc|
  loc.short_name = 'NY'
  loc.status     = 'Active'
end

discipline = Discipline.where(name: 'Name', location_id: location.id).first_or_initialize
discipline.assign_attributes code: 'code', status: 'Active'
discipline.save!

speciality = Speciality.where(name: 'Name', location_id: location.id).first_or_initialize
speciality.assign_attributes code: 'code', discipline_id, discipline.id
speciality.save!


Countdown - word solver Here is my Countdown word solver.

This code aims to find all possible permutations of any length of a given input (which in the Countdown words game is any random assortment of letters).
It then compares each permutation with the dictionary and prints it if it is a valid word. For example the letters "PHAYPC" could yield the following words (not limited to):

Chap
Happy
Hay

I've used the enchant library as my dictionary checker.

import itertools
import enchant

word = input("Please enter the letters or words to scramble: ")
perm_words = itertools.chain.from_iterable(itertools.permutations(word, i) for i in range(3,len(word)))
list_possible = []
list_words_print = []

for item in perm_words:
    list_possible.append("".join(item).lower())

dictionary = enchant.Dict("en_UK")
for word in list_possible:
    if dictionary.check(word):
        if word not in list_words_print: list_words_print.append(word)

print (list(item for item in list_words_print))
exit_key = input("Press any key to exit")

Two suggestions for improvement. First, there's no need to keep track of all those possible words in a list list_possible. You could create and check them on the fly instead, saving memory and a bunch of append calls:

for item in perm_words:
    word = "".join(item).lower()
    if dictionary.check(word):
        if word not in list_words_print:
            list_words_print.append(word)

EDIT There's a sneaky bug preventing this, as pointed out by OP. Due to perm_words generating the combinations with a length as determined by range(3, len(word)), word is not a variable that should be overwritten in this loop. Or, rename the user input.

Second, having a list to keep the dictionary words in is unnecessarily slow. For every new word found, it's being compared to each word in that list. A faster option would be to store them in a set. Sets can't contain duplicates, so you could simply add each word without having to worry if you've seen it before:

found_words = set()
for item in perm_words:
    word = "".join(item).lower()
    if dictionary.check(word):
        found_words.add(word)


Database in Class for Reusability Does this code fine for database reusability?

<?php
/**
 * Database
 *
 * Class for handling database connections
 *
 *
 * @category   Global Class
 * @copyright  ---
 * @license    ---
 * @version    1.0
 * @link       ---
 * @since      File available since Release 1.0
 * @created    ---
 * @modified   ---
 * @author     Original Author <--->
 * @author     Future Author <--->
 */

class Database
{
    private $database_connection = null;

    public function __construct( $database_id )
    {
        $database_host     = '';
        $database_name     = '';
        $database_username = '';
        $database_password = '';

        switch ( $database_id ) {
            case 'db1':
                $database_host     = 'host';
                $database_name     = 'name';
                $database_username = 'user';
                $database_password = 'pass';
                break;
            case 'db2':
                $database_host     = 'host';
                $database_name     = 'name';
                $database_username = 'user';
                $database_password = 'pass';
                break;
            default:
                trigger_error( 'Undefined database id', E_USER_ERROR );
        }

        try {
            $this->database_connection = new PDO( "mysql:host={$database_host};
                                                  dbname={$database_name}",
                                                  $database_username,
                                                  $database_password );

            $this->database_connection->setAttribute( PDO::ATTR_ERRMODE,
                                                      PDO::ERRMODE_EXCEPTION );
        } catch ( PDOException $pdo_exception ) {
            trigger_error( $pdo_exception, E_USER_ERROR );
        }

        if ( empty( $this->database_connection ) ) {
            trigger_error( 'Undefined database connection', E_USER_ERROR );
        }
    }

    public function execute_query( $query, $statement_id, $values )
    {
        $statement = $this->database_connection->prepare( $query );

        if ( $statement_id == 'db1' ) {
            $statement->bindParam( ':id', $values[ 0 ] );
        } else if ( $statement_id == 'db2' ) {
            $statement->bindParam( ':id1', $values[ 0 ] );
            $statement->bindParam( ':id2', $values[ 1 ] );
        } else {
            trigger_error( 'Undefined statement id', E_USER_ERROR );
        }

        $statement->execute();

        return $statement;
    }
}

?>

and call it here like this?

<?php
require once( "database.php" );

$database_1 = new Database( "db1" );
$database_2 = new Database( "db2" );

$database_1->execute_query( "SELECT * FROM user WHERE id = :id", "db1", array( 0 ) );
$database_1->execute_query( "SELECT * FROM user WHERE id = :id", "db1", array( 1 ) );
$database_2->execute_query( "SELECT * FROM user WHERE id = :id1 AND id2 = :id2", "db2", array( 0, 1 ) );
$database_2->execute_query( "SELECT * FROM user WHERE id = :id1 AND id2 = :id2", "db2", array( 2, 3 ) );

?>

No, this code isn't reusable.

Currently, you cannot "execute queries" but execute SELECT queries with exactly one or two parameters. What if you need to add a third id? Or a fourth? Or have a query with no parameters?

The easiest way to solve your problem is to just pass your $values array to execute:

public function execute_query( $query, $statement_id, $values )
{
    $statement = $this->database_connection->prepare( $query );
    $statement->execute($values);
    return $statement;
}

But this still doesn't make very much sense. Your function returns a PDO statement, which still has to be processed, so you didn't really gain anything by introducing this method (well, you save one line for every query you write).

You should either get rid of it and use PDO directly (or some alternative such as an ORM), or you should handle all PDO related code inside of this method (make sure that the method actually improves on using just PDO though).

Misc

It is pretty much never a good idea to change the behavior of a function based on some control string (like your db1/db2), as it is difficult to use, it must be properly documented, it can easily lead to bugs, etc. In your case, you could simply get rid of the parameter and ask for the size of $values.
$statement_id is poorly named.
You use the same db1/db2 string for two very different things (one for different database credentials, one for the number of ids. This is very confusing.


Ruby selenium script waiting for an element to disappear I'm a Java developer, I'm new to Ruby and I'm worried that I'm forcing or not-so-well using the goodness of the Ruby syntax.

What do you think about the Exception catching and how to print it in error messages?
What about the code block (closure?) I'm passing to the "until" method?
Is it ok to implicitly rely on what the last executed sentence of the block will be, regarding what would be its returned value?

def waitUntilDisappears(type, name) #Waits for a particular element to disappear
  begin
    puts "Waiting for element #{name} to disappear..."
    wait = Selenium::WebDriver::Wait.new(:timeout => 5)
    wait.until do
      element = driver.find_element(type, name)
      if element != nil
        displayValue = element.css_value("display")
        puts "Element #{name} has displayValue #{displayValue}."
        displayValue != "block"
      end
    end
    puts "Element #{name} disappeared or not present. OK."
  rescue Exception => e
    puts "Error: Could not wait for element #{name} to disappearDetails: #{e.inspect}"
  end
end

Some notes:

waitUntilDisappears. In Ruby, always: wait_until_disappears.
if element != nil -> if element.
if element != nil. I think find_element never returns nil, it raises exception if not found, so this is not needed.
rescue Exception => e. A rescue that covers a whole method can omit the begin.
rescue Exception => e. Rescuing from Exception is bad practice. Rescue from StandardError, which is the same as rescue => e.
puts "Error". It's bad practice to catch an exception (even worse ifit's all exceptions), just print to the screen and return as if nothing happened. Raise an exception or return a value that signals the error.
Is Element#visible? not enough?

I'd write:

def wait_until_disappears(type, name, timeout: 5)
  wait = Selenium::WebDriver::Wait.new(timeout: timeout)
  wait.until { !driver.find_element(type, name).visible? }
end


Implementing a Time class in c++ Design a class TIME which stores hour, minute and second. The class
  should have

  the methods to support the following:

  User may give the time value in 24-hour format.
  User may give the time value in AM/PM format
  Display the time in 24-hour format.
  Display the time in AM/PM format.
  User may like to add minute with a time value.

#include <iostream>
#include <string>

class Time {
    public:
        Time(int h = 0, int m = 0, int s = 0, const std::string &am_or_pm = "");
        void print_time24();
        void print_time12();
        void add_min();
    private:
        int hr;
        int min;
        int sec;
};

Time::Time(int h, int m, int s, const std::string &am_or_pm):
    hr(h), min(m), sec(s)
{
    if (am_or_pm == "AM" && hr == 12)
        hr = 0;
    if (am_or_pm == "PM" && hr != 12)
        hr += 12;
}

void Time::print_time24()
{
    std::cout << hr << ':' << min << ':' << sec;
}

void Time::print_time12()
{
    if (hr == 0 || hr == 12)
        std::cout << "12";
    else
        std::cout << hr % 12;
    std::cout << ':' << min << ':' << sec;

    if (hr / 12 == 0)
        std::cout << " AM";
    else
        std::cout << " PM";
}

void Time::add_min()
{
    if (min == 59)
        hr = (hr + 1) % 24;

    min = (min + 1) % 60;
}

// To test the class
int main()
{
    using namespace std;
    cout << "Choose option(1. 12 hr format 2. 24 hr format): ";
    int op;
    cin >> op;
    cout << "Enter the time: ";
    int hr, min, sec;
    cin >> hr >> min >> sec;
    string am_or_pm;
    if (op == 1)
        cin >> am_or_pm;
    Time t(hr, min, sec, am_or_pm);
    t.print_time12();
    cout << '\n';
    t.print_time24();
    cout << '\n';

    cout << "Adding a minute,\n";
    t.add_min();
    t.print_time12();
    cout << '\n';
    t.print_time24();
    cout << '\n';

    return 0;
}

The code works but can it be made better? Also what will be the correct way to handle invalid arguments in the constructor?

I see some things that may help you improve your program.

Use const where practical

The print_time24() and print_time12() functions only print and do not modify the underlying Time object, so they should both be declared const:

void print_time24() const;
void print_time12() const;

Make printing prettier

The current print_time24() routine does not emit nice looking time.  If the time is 12:06:07, the program emits 12:6:7 which is not quite right.  Instead, you have to format the data so that minutes and seconds are both two digits.  I show how in the next comment.

Create a stream inserter

Right now the code is only capable of printing to std::cout and not a std::stringstream or std::ofstream.  This can be fixed by one of two ways.  Either you can add a std::ostream& parameter to each of the print routines or you can create a friend inserter like this:

friend std::ostream& operator<<(std::ostream& out, const Time& t) {
    auto oldfill = out.fill('0');
    return out << t.hr
        << ':' << std::setw(2) << t.min
        << ':' << std::setw(2) << t.sec << std::setfill(oldfill);
}

You will also have to #include <iomanip>.  Now it can be used like so:

cout << t << '\n';

Think of the user

While the add_min() routine does indeed add exactly 1 minute, I would instead have expected that one would be able to add an arbitrary number of minutes instead, as with add_min(int minutes).

Also, it seems likely that a user would have a preference for either AM/PM or 24-hour time.  I'd suggest making that preference either a boolean data member of the class or perhaps a static data member for all instances of the class.

Consider signed vs. unsigned

Would a time of -3:-80:-155 be something you would recognize as a time?  Probably not, but unfortunately your Time object has no problem with that. Both the constructor arguments and the private data members should be unsigned rather than int.  If you want to save some space, you could even declare the private data members as unsigned char.

Use braces

Lines like this:

if (am_or_pm == "AM" && hr == 12)
    hr = 0;

while technically accurate are a potential error waiting to happen.  The problem is that if someone adds a line, perhaps for troubleshooting or diagnostics, the if statement will break unless braces are added.  You can both make your code more clear and prevent this kind of future error by using braces.

Handle out-of-range constructor arguments

There are two choices for how to handle invalid constructor arguments.  Either you can ignore them and silently substitute a default or throw an error.  I'd recommend the latter approach.  At the bottom of your constructor, add these three lines:

if (hr > 24 || min > 59 || sec > 59) {
    throw(std::domain_error("Time value out of range"));
}

You will also have to #include <stdexcept>.

Use helper functions to make code simpler

The code to print the time could be much simpler if you use helper functions.  I'd suggest these member functions:

    bool is_pm() const {
        return hr >= 12;
    }
private:
    unsigned get_hour(bool am_pm) const {
        if (!am_pm)
            return hr;
        if (is_pm())
            return hr-12;
        if (hr == 0)
            return 12;
        return hr;
    }
    const char *get_suffix(bool am_pm) const {
        if (!am_pm)
            return "";
        if (is_pm())
            return " PM";
        return " AM";
    }

Now the two separate print routines can be refactored as one member function taking a bool to tell whether to print 24-hour or AM/PM time:

std::ostream& print(std::ostream &out, bool am_pm) const
{
    auto oldfill = out.fill('0');
    return out << get_hour(am_pm)
        << ':' << std::setw(2) << min
        << ':' << std::setw(2) << sec
        << get_suffix(am_pm)
        << std::setfill(oldfill);
}

This, in turn can be used by the friend inserter I mentioned above:

friend std::ostream& operator<<(std::ostream& out, const Time& t) {
    return t.print(out, false);
}

Simplify the add_min() code

The code does more mathematics than it needs to.  Now that the constructor throws an error if it's malformed, we know that the stored values are always valid.  This means that the add_min() code can be simplified:

void Time::add_min()
{
    if (++min > 60) {
        hr = (hr + 1) % 24;
        min = 0;
    }
}

Eliminate return 0 at the end of main

When a C++ program reaches the end of main the compiler will automatically generate code to return 0, so there is no reason to put return 0; explicitly at the end of main.


Really basic terrain generator This is my first attempt at writing a c++ program, so bear with me. I tried to use as many methods as I learned in about a week-long period.

#include <iostream>
#include <stdlib.h>
#include <time.h>

void generator(char tree, char water, char land)
{
    const char tileList[] = {tree, water, land};
    int tileIndex = rand() % 3;

    std::cout << tileList[tileIndex] << " ";
}

int main()
{
    srand(time(NULL));

    while(true)
    {
        generator('T', '~', '.');
    }
}

I took out comments to improve code readability. What can be improved? What needs to be changed?

This won't compile:

void generator(char tree, char water, char land);
// ...
generator("T", "~", ".");

Because generator takes 3 chars, and you're giving it const char* instead.

Of course that's easy to fix, just make the params chars:

generator('T', '~', '.');

It would be better if the generator generated, instead of printing.
It's to preserve the single responsibility principle.
Like this:

char generator(char tree, char water, char land)
{
    const char tileList[] = {tree, water, land};
    int tileIndex = rand() % 3;
    return tileList[tileIndex];
}

int main()
{
    srand(time(NULL));

    while(true)
    {
        std::cout << generator('T', '~', '.') << " ";
    }
}

Of course the loop will never end... Are you ok with that?

Taking 3 chars as possible tiles doesn't seem too flexible. How about making it work with arbitrary number of tiles? Something like this:

char generator(const char * tiles, int len)
{
    int index = rand() % len;
    return tiles[index];
}

int main()
{
    srand(time(NULL));

    const char * tiles = "T~.";
    int len = strlen(tiles);

    while(true)
    {
        std::cout << generator(tiles, len) << " ";
    }
}


Python Barcode Generator v2 This is a complete rewrite of the code posted for review in this question. The question is identical.
def render(digits):

    '''This function converts its input, a string of decimal digits, into a
    barcode, using the interleaved 2 of 5 format. The input string must not
    contain an odd number of digits. The output is an SVG string.

    Wikipedia [ITF Format]: http://en.wikipedia.org/wiki/Interleaved_2_of_5
    '''

    top = '<svg height="58" width="{0}" style="background:white">'
    bar = '<rect x="{0}" y="4" width="{1}" height="50" style="fill:black"/>'
    barcode = [top.format(len(digits) * 14 + 24)]

    byte_map = {
        '0': (2, 2, 4, 4, 2), '1': (4, 2, 2, 2, 4),
        '2': (2, 4, 2, 2, 4), '3': (4, 4, 2, 2, 2),
        '4': (2, 2, 4, 2, 4), '5': (4, 2, 4, 2, 2),
        '6': (2, 4, 4, 2, 2), '7': (2, 2, 2, 4, 4),
        '8': (4, 2, 2, 4, 2), '9': (2, 4, 2, 4, 2)
        }

    byte = lambda i: byte_map[digits[i]]

    def encode(bits, i=0):

        '''Encodes a string of decimal digits. The output's a binary string,
        but as a list of ints, all 2s and 4s, rather than zeros and ones, as
        the bars in the SVG barcode are rendered 2px wide for zeros, 4px for
        ones.'''

        if i == len(digits): return bits

        for b, w in zip(byte(i), byte(i+1)): bits.extend([b, w])

        return encode(bits, i+2)

    def svg(bits, i=0, x=4):

        '''Converts the list of ints returned by `encode` to a list of SVG
        elements that can be joined to form an SVG string.'''

        if i == len(bits): return barcode + ['</svg>']

        b, w = bits[i:i+2]
        barcode.append(bar.format(x, b))

        return svg(bits, i+2, x+b+w)

    # The call to `encode` passes in the itf start code, and the itf end
    # code's added to the list that `encode` returns. The complete list
    # is passed to `svg`, which returns a list of SVG element strings
    # that're joined with newlines to create the actual SVG output.

    return '\n'.join(svg(encode([2, 2, 2, 2]) + [4, 2, 2, 0]))

The use of recursive functions to implement what appear to be simple iterators does make sense. It avoids the need to try and assign xrange to range for Python2, as we don't need the range function now. As well, neither function can be replaced with a generator expression, so you end up with a couple of fairly crufty loops and more temporary variables otherwise.
Note: This works in both Python 2 and Python 3

Your code looks pretty good. There are a few improvements that I can see.

Firstly, when following PEP8 (the official Python style convention guide) we want to avoid using multiple statements per line:

# Avoid this style.
if i == len(digits): return bits

# Use this style.
if i == len(digits):
    return bits

Because of your use of multiple statements per line, your code looks like it has an extraneous amount of blank lines (another no-no as defined by PEP8). Fixing the statements will also help mitigate the feeling that your code has too many blank lines.

Secondly, I typically try to avoid declaring functions inside of functions (unless I'm doing something REALLY funky: think async plus decorators plus magic). As many of the answers say here, functions inside functions are useful for creating closures and decorators, both of which are not really needed here in your implementation.

Thirdly, in your for loop within encode() you unpack the tuple returned from zip then take those unpacked elements and put them into a list to extend bits:

# Unpack into `b` and `w`
for b, w in zip(byte(i), byte(i+1)):
    # 'Re-pack' back into list
    bits.extend([b, w])

Instead, you can just take the tuple itself and pass that to extend():

for tup in zip(byte(i), byte(i+1)):
    bits.extend(tup)

Finally, your variable names are a tad ambiguous. They can be guessed (if you know ITF format) but we don't want to necessarily assume others know ITF format or require them to have guess what each of our variables are for.


Skinny model, fat controller in Rails managing user IP addresses As part of learning Rails framework, I have small app in progress. Basically idea is, user can create IP address, define is it in use, to which server is assigned, which user is it using and role of IP address in web hosting environment. I have 3 models, IpAddress, IpAddressRole and IpAddressUser. User is able to define IpAddressRole and IpAddressUser from prepopulated postgresql database.

Main controller is IpAddressesController, which is responsible for creating, showing and other CRUD operations on primary model.

ip_addresses_controller.rb code is here:

class IpAddressesController < ApplicationController

    def index
        @ip_addresses = IpAddress.all.order(:title)
    end

    def show
        @ip_address = IpAddress.find(params[:id])
    end

    def new
        @ip_address_roles = IpAddressRole.all
        @servers = Server.all
        @ip_address_users = IpAddressUser.all
    end

    def create
        @ip_address_roles = IpAddressRole.all
        @servers = Server.all
        @ip_address_users = IpAddressUser.all

        @ip_address = IpAddress.new(ip_address_params)
        @ip_address.save
        redirect_to ip_addresses_path
        #render plain: params[:ip_address].inspect
    end

    def destroy
        @ip_address = IpAddress.find(params[:id])
        @ip_address.destroy
        flash[:success] = "Record successfully deleted"
        redirect_to ip_addresses_path
    end

    private
        def ip_address_params
            params.require(:ip_address).permit(:title, :server, :user, :is_in_use, :role)
        end
end

And ip_address.rb code is here:

class IpAddress < ActiveRecord::Base
    def is_ip_address_in_use
        if self.is_in_use == 'true'
            self.is_in_use = 'yes'
        else
            self.is_in_use = 'no'
        end
    end

end

I have some great resources near hand, but my controller is getting fat, and model skinny, also, in my controller I have a lot of repetition. How can I refactor model and controller? Controller is really ugly.

First of all you should look at your controller and see what common functionality you can extract to a private methods and callbacks.

Another fairly large concern with you controller is that you are just assuming that a record is created or deleted without checking the return value. Create / Update / Destroy actions can and will fail.

class IpAddressesController < ApplicationController

    before_filter :set_ip_address, only: [:show, :edit, :update, :destroy]

    def index
        @ip_addresses = IpAddress.all.order(:title) # extract to model default scope?
    end

    def show
    end

    def new
        load_form_resources
        @ip_address = IpAddress.new
    end

    def create
        @ip_address = IpAddress.new(ip_address_params)
        if @ip_address.save
            redirect_to ip_addresses_path
        else
            load_form_resources
            render :new
        end
    end

    def destroy
        # Remember that destroy can actually fail!
        if @ip_address.destroy
            flash.success "Record successfully deleted"
            redirect_to ip_addresses_path
        else
            flash.alert "Record not deleted"
        end
    end

    private

        def set_ip_address
          @ip_address = IpAddress.find(params[:id])
        end

        def load_form_resources
            @ip_address_roles = IpAddressRole.all
            @servers = Server.all
            @ip_address_users = IpAddressUser.all
        end

        def ip_address_params
            params.require(:ip_address).permit(:title, :server, :user, :is_in_use, :role)
        end
end

When it comes to your model, then I usually preach so much against boolean state flags that I feel somewhat like a broken record.

Instead of having a ip_addresses.is_in_use column you could add a ip_addresses.state integer column.

Rails has a really fancy trick called enums.

class IpAddress < ActiveRecord::Base
  enum state: [:available, :in_use]
end

Which gives you:

IpAddress.available # gets all free ip adresses
IpAddress.in_use # gets all in_use ip adresses
@ip_adress.available? # check status
@ip_adress.in_use?
@ip_adress.in_use! # setters


Making two sequential asynchronous requests using promises The following code is making two asynchronous requests to obtain the desired data. The second request needs to access the data from the first request, hence I need to nest it. I know that it is better to chain promises, but this is a case where nesting seems necessary.

However the lint raises a warning: avoid nesting promises. Should I ignore the warning or there is a better way to rewrite the code?

function get_note_full(note_id) {
  return db.collection('notes').doc(note_id).get()
    .then(doc => {
      const data = doc.data();
      return get_author_data(data.author_uid)
        .then(author => {
          return ({
              id: note_id,
              title: data.title,
              text: data.text,
              author: author
            });
        });
    });
}

You should be able to convert that code to using async / await from ES2017. Notice that I changed the function names to suit general JavaScript naming standards (camelCase for functions and variables, etc.)

async function getFullNote(noteId) {
    const note = await db.collection('notes').doc(note_id).get();
    const author = await getAuthorData(note.author_uid);
    return {
        id: note_id,
        title: data.title,
        ext: data.text,
        author: author
    }
}

This is how MDN defines an async function:

An asynchronous function is a function which operates asynchronously via the event loop, using an implicit Promise to return its result. But the syntax and structure of your code using async functions is much more like using standard synchronous functions.

Link: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function


Class for modifying stats of units I am specifically looking for input on naming ModifierCalculator and Modifiers. I would also appreciate input on whether ModifierCalculator should extend EnumMap instead of having it as a field.

These classes are for modifying the status of units. The StatType enum contains different types of ..stats, such as "life", "armor", "weapon damage", etc.

StatModifier objects' purpose is to modify a unit's stat. This kind of modification can be a flat bonus, a percentage increment or a multiplication, using the formula

total = (base + flat)*(1 + percent_increments)*(1 + mult_1)*(1 + mult_2)*... *(1 + mult_n)

ModifierCalculator puts all three kinds of modifiers in a map of Modifiers data structures with StatType serving as keyword.

public enum StatType
{
    //code is trivial to the problem
}

public enum StatModifierType
{
    FLAT, PERCENTAGE, MULTIPLICATIVE;
}

public class StatModifier
{
    private StatType statType;
    private double magnitude;
    private StatModifierType modType;

    public StatModifier(StatType statType, double magnitude, StatModifierType modType)
    {
        this.statType = statType;
        this.magnitude = magnitude;
        this.modType = modType;
    }

    public StatType getStatType()
    {
        return statType;
    }

    public double getMagnitude()
    {
        return magnitude;
    }

    public StatModifierType getModifierType()
    {
        return modType;
    }
}

public class Modifiers
{
    public double flat = 0;
    public double percentage = 0;
    public final ArrayList<Double> multipliers = new ArrayList<Double>();
}

public class ModifierCalculator
{
    private EnumMap<Stat, Modifiers> statToModifiers
          = new EnumMap<Stat, Modifiers>(Stat.class);

    public ModifierCalculator()
    {
        for (StatType s : Stat.values())
            statToModifiers.put(s, new Modifiers());
    }

    public void evaluate(ArrayList<StatModifier> modifiers)
    {
        for (StatModifier modifier : modifiers)
            evaluate(modifier);
    }

    public void evaluate(StatModifier modifier)
    {
        double magnitude = modifier.getMagnitude();
        Modifiers mods = statToModifiers.get(modifier.getStat());
        switch (modifier.getModifierType())
        {
        case FLAT:
            mods.flat += magnitude;
            break;
        case PERCENTAGE:
            mods.percentage += magnitude;
            break;
        case MULTIPLICATIVE:
            mods.multipliers.add(1 + magnitude);
            break;
        }
    }

    public Modifiers getStatModifiers(StatType statType)
    {
        return statToModifiers.get(statType);
    }
}

IMHO The names are fine. You could maybe want to modify Modifiers in StatModifiersSummary as it's, after all, a summary "view" of the actual modifiers.

You should make its fields final or private, though.

In that case, your calculator would become StatModifiersSummaryCalculator.

W.r.t. extending / having one map inside, composition is in general preferable to inheritance, so stick with the current design: after all you happen to use a Map, but there is no reason why you couldn't use another representation and you don't want your "users" to be able to pass your calculator around where a map is needed.


Definition of power functions I needed to write a simple function that could raise a value x to the n'th power. I found out I could write this function in 2 different ways:

(defun power1 (x n)
  "Raise x to the n'th power"
  (cond ((zerop n)
          1.0)
         ((< n 0.0)
          (/ 1.0 (reduce #'* (loop for i below (- n) collect x))))
         (t
          (reduce #'* (loop for i below n collect x)))))

(defun power2 (x n)
  "Raise x to the n'th power"
  (cond ((zerop n)
         1.0)
        ((< n 0.0)
         (/ 1.0 (power2 x (- n))))
        (t
         (* x (power2 x (- n 1))))))

Now, I was curious to known which of these 2 functions is better. So I ran some calls to these functions wrapped in a call to the time function. Here are some results:

(time (power1 2 100))
took 0 milliseconds (0.000 seconds) to run.
2,248 bytes of memory allocated.

(time (power2 2 100))
took 0 milliseconds (0.000 seconds) to run.
800 bytes of memory allocated.

(time (power1 2 1000))
took 0 milliseconds (0.000 seconds) to run.
82,232 bytes of memory allocated.

(time (power2 2 1000))
> Error: FLOATING-POINT-OVERFLOW detected

The first function takes more memory, since it creates an entire list, while the second function uses recursion. But the first one can handle larger numbers.

How can I choose which of these functions is the best? Choose for memory usage, readability, Lisp-like style, range of inputs it can handle, .... Maybe a function that uses tail-call optimization would be even better?

(defun power3 (x n)
  (labels ((pow (x n acc)
             (if (zerop n)
                 acc
                 (pow x (- n 1) (* acc x)))))
    (cond ((zerop n) 1.0)
          ((< n 0.0) (/ 1.0 (pow x (- n) 1.0)))
          (t (pow x n 1.0)))))

(time (power3 2 100))
took 1 milliseconds (0.001 seconds) to run.
800 bytes of memory allocated.

Major

All 3 of your functions are linear (they do O(n) multiplications) while, in fact, only O(log(n)) is necessary:

(defun pow (x n)
  (if (minusp n)
      (/ (pow x (- n)))
      (multiple-value-bind (d r) (floor n 2)
        (let ((p (if (zerop d) 1 (pow x d))))
          (* p p (if (zerop r) 1 x))))))

In addition to much fewer multiplications, I am returning ratios for rational x.

Minor

Use minusp instead of comparison with 0.0 and (/ a) instead of (/ 1 a).


Time interval class that enhances constructor argument handling of its parent class I am making a subclass of a well-established python class:  pendulum.Period, which overrides both __new__ and __init__ (it does this because it is subclassing the python builtin class timedelta, which uses __new__).

In my case, I want my class to handle a wider range of arguments than the superclass.  The only way I have managed to get the code to work is to duplicate my handling code in both __new__ and __init__ -- this is because, per the documentation, the arguments passed to __new__ are then passed to the __init__ of the new instance, unaltered.

The result is repeated code execution. Is this avoidable?

from pendulum import Period, Date

def _toDate(val):
    """
    Convert various inputs into a Date
    """
    if isinstance(val, int) or isinstance(val, float):
        return Date.fromtimestamp(val)
    elif isinstance(val, tuple):
        return Date(*val)
    return Date(val.year, val.month, val.day)

class MyInterval(Period):
    def __new__(cls, start, end, inclusive=True, **kwargs):
        start = _toDate(start)
        end = _toDate(end)

        if inclusive:
            end = end.add(days=1)

        return super(MyInterval, cls).__new__(cls, start, end, **kwargs)

    def __init__(self, start, end, inclusive=True, **kwargs):
        """
        Creates a pendulum Period where the interval is limited to whole
        days. Both are cast to dates, then the end date is incremented by
        one day if inclusive=True
        :param start: cast to date
        :param end: cast to date
        :param inclusive: [True] whether the last day of the interval should
          be included (increments by 1 day)
        """
        start = _toDate(start)
        end = _toDate(end)

        if inclusive:
            end = end.add(days=1)

        super(MyInterval, self).__init__(start, end, **kwargs)

If you don’t expect to be further subclassing MyInterval, you could just use a helper method for construction.

class MyInterval(Period):

    @classmethod
    def create(cls, start, end, inclusive=True, **kwargs):
        start = _toDate(start)
        end = _toDate(end)

        if inclusive:
            end = end.add(days=1)

        return cls(start, end, **kwargs)

Alternatively, you could use a helper method to avoid the duplicated code (but not duplicated execution).

class MyInterval(Period):

    @staticmethod
    def _fixup(start, end, inclusive):
        start = _toDate(start)
        end = _toDate(end)

        if inclusive:
            end = end.add(days=1)

        return start, end

    def __new__(cls, start, end, inclusive=True, **kwargs):
        start, end = cls._fixup(start, end, inclusive)
        return super().__new__(start, end, **kwargs)

    def __init__(self, start, end, inclusive=True, **kwargs):
        start, end = self._fixup(start, end, inclusive)
        return super().__init__(start, end, **kwargs)


Converting an object to be used with a treegrid I'm a bit novice/moderate at JS. To my surprise I managed to put this together and it does work for what I intended.

The objective is to convert an object into a format that is more conducive to being used with a treegrid. I'm using the underscore library to grab object keys at various points.

I just wanted to know if maybe there's a better or perhaps more performant way of looping through these deeply nested objects that I may be overlooking. Something that's capable of handling hundreds, or even a thousand, of these nodes without potentially locking up a browser?

I found a hint about storing the length variables separately in a similar question that displayed looping through things in this manner, I just wanted to know if there may be any other tips?

JSBin

var data_source = {"sprint":{"children":{"country":{"us":{"clicks":26}},"device":{"iphone":{"clicks":26}},"isp":{"comcast cable":{"clicks":26}},"os":{"ios":{"clicks":15},"android":{"clicks":10}},"referer":{"unknown":{"clicks":26}}},"clicks":26},"verizon":{"children":{"country":{"us":{"clicks":10,"conversions":5,"earned":0.5,"spent":0.2}},"device":{"galaxy s":{"clicks":1}},"isp":{"comcast cable":{"clicks":1}},"os":{"android":{"clicks":1}},"referer":{"unknown":{"clicks":1}}},"clicks":1,"conversions":1}};

var object = [];

function convert(data){
  var keys = _.keys(data);
  var keyslength = keys.length;
  for (var i = 0; i < keyslength; i++){
    var me = data[keys[i]];
    var rootleaf = buildLeaf(me);
    rootleaf.name = keys[i];
    rootleaf.children = [];

    var childkeys = _.keys(me.children);
    var childkeyslength = childkeys.length;
    for (var i2 = 0; i2 < childkeyslength; i2++){
      var childme = me.children[childkeys[i2]];
      var childleaf = {};
      childleaf.name = childkeys[i2];
      childleaf.children = [];

      var grandchildkeys = _.keys(childme);
      var grandchildkeyslength = grandchildkeys.length;
      for (var i3 = 0; i3 < grandchildkeyslength; i3++){
        var grandchildme = childme[grandchildkeys[i3]];
        var grandchildleaf = buildLeaf(grandchildme);
        grandchildleaf.name = grandchildkeys[i3];
        childleaf.children.push(grandchildleaf);
      }

      rootleaf.children.push(childleaf);
    }

    object.push(rootleaf);
  }
}

convert(data_source);
console.log(object);

function buildLeaf(node){
  var tempnode = {};
  var clicks = ((node.clicks) ? node.clicks : 0);
  var conversions = ((node.conversions) ? node.conversions : 0);
  var earned = ((node.earned) ? node.earned : 0);
  var spent = ((node.spent) ? node.spent : 0);
  tempnode.clicks = clicks;
  tempnode.conversions = conversions;
  tempnode.earned = '$' + earned.toFixed(2);
  tempnode.spent = '$' + spent.toFixed(2);
  tempnode.conversion_rate = conversionRate(conversions,clicks);
  tempnode.net_earned = netEarned(earned,spent);
  tempnode.epc = epc(clicks,earned,spent);
  tempnode.roi = roi(earned,spent);
  return tempnode;
}

// calculation functions

function conversionRate(cv, cl) {
    if (cl === 0) return '0%';
    return ((cv/cl)*100).toFixed(1) + '%';
}
function epc(cl, e, s) {
    if (cl === 0 || e === 0) return '$0.000';
    return '$' + ((e - (cl * s)) / cl).toFixed(3);
}
function netEarned(e, s) {
    if (e === 0) return '$0.00';
    return '$' + (e - s).toFixed(2);
}
function roi(e, s) {
    if (e === 0) return '0%';
    return (((e - s) / s) * 100).toFixed(0) + '%';
}

I believe this does the same as yours, except it uses buildLeaf on each step (your function skips it in the "middle" loop, and just makes an empty object).

// Recursive convertion function
function convert(obj) {
  var item, leaf, key, leaves = [];
  for( key in obj ) {
    if( !obj.hasOwnProperty(key) ) continue;
    item = obj[key];
    leaf = buildLeaf(key, item)
    leaves.push(leaf);
    if( typeof item.children === 'object' ) {
      leaf.children = convert(item.children);
    }
  }
  return leaves;
}

// I also refactored buildLeaf slightly to accept both
// name and content, and to make use of JavaScript's
// `||`-style fallbacks

function buildLeaf(name, node) {
  var leaf        = { name: name, children: [] },
      clicks      = node.clicks || 0,
      conversions = node.conversions || 0,
      earned      = node.earned || 0,
      spent       = node.spent || 0;

  leaf.clicks          = clicks;
  leaf.conversions     = conversions;
  leaf.earned          = '$' + earned.toFixed(2);
  leaf.spent           = '$' + spent.toFixed(2);
  leaf.conversion_rate = conversionRate(conversions,clicks);
  leaf.net_earned      = netEarned(earned,spent);
  leaf.epc             = epc(clicks,earned,spent);
  leaf.roi             = roi(earned,spent);

  return leaf;
}

// In the calculation functions, I made the value checking
// less strict. Generally, strong checking is encouraged,
// but in this case other useless values would slip through,
// when only strongly checking for zero (since that allows
// `false`, empty strings, etc. to pass through).

function conversionRate(cv, cl) {
  if( !cl ) return '0%';
  return ((cv/cl)*100).toFixed(1) + '%';
}

function epc(cl, e, s) {
  if( !cl || !e ) return '$0.000';
  return '$' + ((e - (cl * s)) / cl).toFixed(3);
}

function netEarned(e, s) {
  if( !e ) return '$0.00';
  return '$' + (e - s).toFixed(2);
}

function roi(e, s) {
  if( !e ) return '0%';
  return (((e - s) / s) * 100).toFixed(0) + '%';
}

Addendum

If you need to handle the conversion differently for different levels of nesting (re: the comments), you could do something like this

function convert(obj) {
  // get the extra, optional, argument.
  // It defaults to 1, and increments otherwise
  var level = (arguments[1] || 0) + 1;

  var item, leaf, key, leaves = [];
  for( key in obj ) {
    if( !obj.hasOwnProperty(key) ) continue;
    item = obj[key];
    // Check the level here
    if( level === 2 ) {
      // 2nd level will only be converted to a simpler, non-leaf object
      leaf = { name: key, children: [] };
    } else {
      // Other levels will become "leaves"
      leaf = buildLeaf(key, item);
    }
    leaves.push(leaf);
    if( typeof item.children === 'object' ) {
      // remember to pass the level on
      leaf.children = convert(item.children, level);
    }
  }
  return leaves;
}

I don't know if there's a system in the data you're converting, but you could also check for level % 2 === 0 to handle every second (i.e. even-numbered) level differently.


Convert string format python I want to fix number of digits after '.' in digit represented by string.
Is there better solution than mine?
My code
def convert(s):
    """ Convert 1234.12345678 to 1234.123"""
    vec = s.split('.')
    if len(vec) == 2 and len(vec[1]) > 3:
        return vec[0] + '.' + vec[1][:3]
    return s

In fact this would be sufficient:
return '{0:1.3f}'.format(s)

(provided that the argument passed is a float).
There is no need for a function.
The above will return a string, if you want to return a float then use the float function:
return float('{0:1.3f}'.format(s))

Or even shorter, taking advantage of F-strings. I prefer this option personally:
return f'{s:.3f}'

Again, this returns a string but you can cast it to a float if necessary.
As a reference: Python f-string tutorial


Detecting socket disconnect in .NET First off, I know there are other solutions and practices but I'm referring to MS proposed code from .NET documentation.

It goes like this:

client.Connect(anEndPoint);

bool blockingState = client.Blocking;
try
{
    byte [] tmp = new byte[1];

    client.Blocking = false;
    client.Send(tmp, 0, 0);
    Console.WriteLine("Connected!");
}
catch (SocketException e)
{
    // 10035 == WSAEWOULDBLOCK
    if (e.NativeErrorCode.Equals(10035))
        Console.WriteLine("Still Connected, but the Send would block");
    else
    {
        Console.WriteLine("Disconnected: error code {0}!", e.NativeErrorCode);
    }
}
finally
{
    client.Blocking = blockingState;
}

 Console.WriteLine("Connected: {0}", client.Connected);

I've tried using it in my TCP client to detect disconnection from server. My problems is that on some occasions it detects disconnect where server does not, so on server I have connection left hanging while client reconnects.

I'm asking anyone who tried using this method to share experiences and maybe help make it more robust.

First off, I'm not an expert about TCP and Sockets, though I have had some experiences in the past.

  My problems is that on some occasions it detects disconnect where server does not, so on server I have connection left hanging while client reconnects.

If you have a client-server scenario, then one will never ever know about what is the state of the other without explicitly finding out!

Say you open the connection, client is idle for 10 seconds and now suddenly the client loses all power. The server doesn't know that the client lost it's power, the client didn't send a disconnect signal, the client was in an idle state so there is no sending/receiving that cut out midway or timed out. The only way for the server to know what is the state of the client on the 11-th second (for instance) is to query/ping the client. The term Keep-Alive applies here, although I can't think of good wording for it right now...

  I'm asking anyone who tried using this method to share experiences and maybe help make it more robust

The state of the problem isn't currently very clear to me. In what specific scenario does the problem exist? When you remove the LAN cable? When you close the client application?

So what, if the connection on the server is left hanging? You have to account for such a very likely possibility. You will need to apply some sort of timeout or keep-alive methodology, inorder to keep the server from hanging on to the connection indefinently and thus consuming and running out of resources. Accounting for all possible scenarios - that is robustness!

As I said, I'm no expert, so I won't be able to tell you exactly which Socket class properties or methods to apply to your code to help you make it more robust. But I will say this, your code example is missing Disconnect() / Close() statements, most likely even using statements. I see no timeouts being applied, surely the Connect() and Send() methods have some sort timeout mechanism (maybe a property, eg client.SendTimeout)...


Controller with too many parameters with DI Is there a way to reduce the number of parameters of this constructor?
All the services must be used in this Controller. The majority of them are used more than 2 times(some of them >10), with the exception of IService7 that is used only in one method.

public class MyController : CustomBaseApiController
  {
    private readonly IService1 service1;
    private readonly IService2 service2;
    private readonly IService3 service3;
    private readonly IService4 service4;
    private readonly IService5 service5;
    private readonly IService6 service6;
    private readonly IService7 service7;
    private readonly IService8 service8;

    public MyController(IService1 service1, IService2 service2, IService3 service3, IService4 service4, IService5 service5, IService6 service6, IService7 service7, IService8 service8)
    {
      this.service1 = service1;
      this.service2 = service2;
      this.service3 = service3;
      this.service4 = service4;
      this.service5 = service5;
      this.service6 = service6;
      this.service7 = service7;
      this.service8 = service8;
    }

All the methods are specific for this controller and no more refactoring into different Controllers should be done.
How can I refactor this in order to have fewer parameters?
This Controller is heavily tested (using Moq), so, if possible, I would want to keep it easier to mock the dependencies.

Create a class that will expose the services as properties. That class should also have DI set up. Register that class with interface in the container. Inject the class into your own controller.


Limiting the maximum amount of goroutines run simultaneously Here is my code which helps me to contol the maximum amount of goroutines run simultaneously.
In example below maximum is 5.

var wg sync.WaitGroup
// Create bufferized channel with size 5
goroutines := make(chan struct{}, 5)
// Read data from input channel
for data := range input {
    // 1 struct{}{} - 1 goroutine
    goroutines <- struct{}{}
    wg.Add(1)
    go func(data string, goroutines <-chan struct{}, results chan<- result, wg *sync.WaitGroup) {
        // Process data
        results <- process(data)
        // Read from "goroutines" channel to free space for new goroutine
        <-goroutines
        wg.Done()
    }(data, goroutines, results, &wg)
}

wg.Wait()
close(goroutines)

Is there a better way to control the maximum amount of goroutines?How can I improve my code?

You can use the Golang Concurrency Manager goccm to limit the maximum number of goroutines to run concurrently:

Example:

package main

import (
    "fmt"
    "goccm"
    "time"
)

func main()  {
    // Limit 3 goroutines to run concurrently.
    c := goccm.New(3)

    for i := 1; i <= 10; i++ {

        // This function have to call before any goroutine
        c.Wait()

        go func(i int) {
            fmt.Printf("Job %d is running\n", i)
            time.Sleep(2 * time.Second)

            // This function have to when a goroutine has finished
            // Or you can use `defer c.Done()` at the top of goroutine.
            c.Done()
        }(i)
    }

    // This function have to call to ensure all goroutines have finished
    // after close the main program.
    c.WaitAllDone()
}


Clearing up property and field confusion in C#? I understand that creating public properties that control private fields is good practice because of coupling and encapsulation, although lately I have seen it as such a waste of boilerplate code for a simple entity class like below.
Take this class for instance,
public class PersonEntity
{
    private string _firstName;
    private string _lastName;
    private int _age;

    public class PersonEntity(string firstName, string lastName, int age)
    {
        _firstName = firstName;
        _lastName = lastName;
        _age = age;
    }

    public string FirstName
    {
        get { return _firstName; }
        set { _firstName = value; }
    }

    public string LastName
    {
        get { return _lastName; }
        set { _lastName = value; }
    }

    public int Age
    {
        get { return _age; }
        set { _age = value; }
    }
}

If all I am using is the property, is it okay to refactor the class to look something like this?
public class PersonEntity
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }

    public class PersonEntity(string firstName, stirng lastName, int age)
    {
        FirstName = firstName;
        LastName = lastName;
        Age = age;
    }
}

Or maybe even this is more simple (using object initialization to construct):
public class PersonEntity
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
}

Which one should I implement if all I want to use the entity for is to map data from a database, and use it as a model to write to the database at a later date than when it was created?
Which versions should I use, when should I use them, and for what reasons should I use each one?

There is a special use case when the (slightly modified) second approach could be beneficial. Namely when you want to create immutable objects.
public sealed class PersonEntity
{
    public string FirstName { get; }
    public string LastName { get; }
    public int Age { get; }

    public PersonEntity(string firstName, string lastName, int age)
    {
        FirstName = firstName;
        LastName = lastName;
        Age = age;
    }
}

By removing the setters you are not allowing the consumer of the class to alter its data after creation. In case of concurrency immutable structures can be shared safely between multiple workers without extra syncronization.
You can define with method(s) to this class as an extension to provide copy with alternative value functionality.
public PersonEntity WithFirstName(string firstName)
{
    return new PersonEntity(firstName, LastName, Age);
}

public PersonEntity WithLastName(string lastName)
{
    return new PersonEntity(FirstName, lastName, Age);
}

public PersonEntity WithAge(int age)
{
    return new PersonEntity(FirstName, LastName, age);
}

Of course you can make it a bit more generic:
public PersonEntity With(string firstname = null, string lastName = null, int? age = null)
{
    return new PersonEntity(
       firstName ?? this.FirstName,
       lastName ?? this.LastName,
       age ?? this.Age);

}

Usage sample:
var xy = new PersonEntity("x", "y", 15);
var xz = xy.With(lastName: "y");
var xz25 = xz.With(age: 25);

UPDATE: C# 9's record
In C# 9 there will be a new construction called record.
Declaration
public record PersonEntity
{
    public string FirstName { get; init; }
    public string LastName { get; init; }
    public int Age { get; init; }
}

Usage
var xy = new PersonEntity { FirstName = "x", LastName = "y", Age = 15 };
var xz = xy with { LastName = "y" };
var xz25 = xz with { Age = 25 };


Most efficient way to populate a vector of integers with no duplicates I am trying to populate a vector of integers with one billion random number.  The only constraint is that there can be no duplicates in the array.

#include <iostream>
#include <algorithm>
#include <vector>
#include <ctime>

using namespace std;

int main()
{
    srand(time(NULL));

    vector<int> container;

    vector<int>::iterator i1;

    for (int i=0;i<1000000000;i++) //a billion numbers
    {
        int number = rand() ;

        i1 = find (container.begin(),container.end() , number );

        if ( i1 != container.end() )
        {
            container.push_back(number);
        }

    }

}

How can my solution be improved on? It can be anything, like time taken or space complexity.

Your solution as it stands currently is going to be incredibly slow - it's complexity is O(n^2), so you're looking at roughly 10^18 "operations" for a billion numbers. This is because you need to search through the vector as it grows to see if you have a duplicate, which will go through the vector (on average) (1 + 2 + ... + 999,999,999) / 2 times over the course of the algorithm.

Edit: In fact, it's actually slightly worse than this, since as you generate more numbers, the probability that you generate something you've already "seen" increases.

I'd suggest the following: since an int on most platforms is still 4 bytes, this still has a maximum value of a bit over 2 billion. Hence create a vector with the first billion values in order, and use std::shuffle. This will give you a billion "random" values, with the constraint that nothing will be selected from the upper range [1e9, INT_MAX].

int main()
{
    constexpr int num_values = 1000000000;
    std::vector<int> rand_values(num_values);
    std::mt19937 eng{std::random_device{}()};

    for(int i = 0; i < num_values; ++i) {
        rand_values[i] = i;
    }

    std::shuffle(rand_values.begin(), rand_values.end(), eng);
}


Python Web-Scraping with BeautifulSoup I'm relatively new to python and for an assignment I had to write a program that fetches a webpage with BeautifulSoup, extract all Paragraphs from it, and extract all words ending with "ing", and in the end save it to a file with the format "Word" + tab + "wordcount" + "newline".
This is my code so far. Is there a more pythonic way to handle this?
Or generally ways to improve the code?
from bs4 import BeautifulSoup
import requests
import re

def main():
    site = "https://en.wikipedia.org/wiki/Data_science"
    r = requests.get(site).content
    soup = BeautifulSoup(r)
    ps = soup.findAll('p')
    fulltext = ''
    for p in ps:
        fulltext += p.get_text()
    words = match_words(fulltext)
    formated_words = sort_and_format(words)
    with open(r"Q1_Part1.txt","w") as file:
        file.write(formated_words)

def match_words(string):
    pattern = re.compile(r'\b(\w*ing)\b')
    words = re.findall(pattern, string.lower())
    matching_words = {}
    for word in words:
        if word in matching_words:
            matching_words[word] += 1
        else:
            matching_words[word] = 1
    return matching_words

def sort_and_format(dict):
    ordered_keys = sorted(dict, key=dict.get, reverse=True)
    output_string = ''
    for r in ordered_keys:
        output_string += f"{r}\t{dict[r]}\n"
    return output_string

main()

if word in matching_words:
    matching_words[word] += 1
else:
    matching_words[word] = 1

If you're checking if a dictionary has a key before adding to it, a defaultdict may be a better option:
from collections import defaultdict

matching_words = defaultdict(int)
matching_words[word] += 1

int returns a 0 when called without arguments, and that 0 is used as a default value for the dictionary when the key doesn't exist.

fulltext = ''
for p in ps:
    fulltext += p.get_text()

This isn't very efficient. Performance of += on strings has gotten better in later versions of Python, but it's still generally slower. The typical alternative is using join:
pieces = [p.get_text() for p in ps]
fulltext = "".join(pieces)

# Or just

fulltext = "".join([p.get_text() for p in ps])

Then similarly in sort_and_format:
output_string = "".join([f"{r}\t{dict[r]}\n"] for r in ordered_keys])

In sort_and_format, you've named the parameter dict. This is suboptimal for a couple reasons:

dict is a generic name that doesn't properly describe the data.
dict is the name of a built-in class, and shadowing it makes your code more confusing, and prevents you from using the built-in.

Indicating the type can be helpful though, so I might introduce type hints here
from typing import Dict

def sort_and_format(words: Dict[str, int]) -> str:
    . . .

This says that the functions accepts a Dictionary mapping strings to ints, and returns a string

Also for sort_and_format, I've found that when you start sticking and into names, that can suggest that the function is doing too much. You may find that the code will make more sense if the sorting and formatting happen separately. That functions can handle purely formatting, and can be handed a sequence to work with instead. If that sequence is sorted, great, if not, also great. It doesn't matter for the purposes of formatting what the sort order is.


Calculating a specific entry in a Pascal’s triangle recursively Our task was to calculate the entry of a Pascal’s triangle with a given row and column recursively. The triangle was specified in a way that the tip of the triangle is column = 0 and row = 0. That said, column 0 has always the entry 1.

My concerns are that the way I initialize the triangle as an array and filling in the entries are not so super.

class EntryOfPascalsTriangle {
    public static void main(String[] args) {
        validateInput(args);

        int row = 0;
        row = parseInteger(args[0]);

        int column = 0;
        column = parseInteger(args[1]);

        // A Pascal’s triangle expands quadratic.
        // There are never entries at a position greater column length
        if (column > row) {
            handleError("There can't be entries in a column that doesn't exist in a Pascal's triangle.");
        }

        // We know already that the first and last entries in a row are always 1
        if (column == 0 || column == row) {
            System.out.println(1);
            System.exit(0);
        }

        int pascalsTriangle[][] = initPascalsTriangle(row);

        // initPascalsTriangle() takes care of the cases `0` and `1` already …
        if (row > 1) {
            // … so we can start to fill the rows starting from 2.
            pascalsTriangle = fillPascalRows(pascalsTriangle, 2);
        }

        System.out.println(pascalsTriangle[row][column]);
    }

    /**
     * Initializes a Pascal’s triangle with all cells filled with `0`
     * except for the first and last cell in a row which are `1`
     */
    private static int[][] initPascalsTriangle(int rows) {
        int[][] pascalsTriangle = new int[rows+1][];

        // Iterate over the columns of the rows of pascalsTriangle
        for (int cell = 0; cell < pascalsTriangle.length; cell++) {
            pascalsTriangle[cell] = new int[cell+1];

            // Fill the first cell of each row with `1`
            pascalsTriangle[cell][0] = 1;

            // Also fill the last cells with `1`
            pascalsTriangle[cell][cell] = 1;
        }

        return pascalsTriangle;
    }

    /**
     * Fills in the cells of Pascal’s triangle recursively
     */
    private static int[][] fillPascalRows(int[][] pascalsTriangle, int row) {
        for (int cell = 1; cell < pascalsTriangle[row].length-1; cell++) {
            pascalsTriangle[row][cell] = pascalsTriangle[row-1][cell-1] + pascalsTriangle[row-1][cell];
        }

        if (row < pascalsTriangle.length-1) {
            fillPascalRows(pascalsTriangle, row+1);
        }

        return pascalsTriangle;
    }

    /**
     * We need to make sure that two arguments are provided
     * and fail with a helpful message if they weren’t.
     */
    private static void validateInput(String[] args) {
        if (args.length < 2) {
            handleError("Not enough arguments.");
        }

        if (args.length > 2) {
            handleError("Too many arguments.");
        }
    }

    /**
     * Small wrapper to parse strings as integers.
     */
    private static int parseInteger(String arg) {
        int result = 0;

        try {
            result = Integer.parseInt(arg);
        } catch (NumberFormatException nfe) {
            handleError("'" + arg + "' was not an integer.");
        }

        return result;
    }

    /**
     * Small wrapper to produce error messages
     */
    private static void handleError(String errorMessage) {
        String basicUsage = "Please enter the column and the row of a Pascal's triangle.";
        System.out.println(errorMessage);
        System.out.println("\n" + basicUsage);
        System.exit(1);
    }
}

Since this question is marked as beginner, let me compliment the neat structure and consistent style I see throughout. It's well done.

Variable, method, and class names are all meaningful, and useful.

The validation and error handling systems are uncommonly comprehensive, and again, well done.

Validation

The validation should provide more feedback to the user. Saying 'not enough arguments' is fine, but then you should also say how many are expected. Does the user have to engage on a guessing game, bouncing between too many arguments, and not enough arguments before discovering how many they need?

Pre-initializing variables

There is no need to preinitialize variables. The following:

    int row = 0;
    row = parseInteger(args[0]);

    int column = 0;
    column = parseInteger(args[1]);

can just be:

    int row = parseInteger(args[0]);
    int column = parseInteger(args[1]);

Algorithm

THis is where I see the biggest problem, and it's not because you've made a mess, but because I think you've missed the point. If the problem is: "... to calculate the entry of a Pascal’s triangle with a given row and column recursively" then that is not what you have done.

You have calculated all entries and stored them in an array, then indexed the values you need. Sure, some parts are recursive, but I expect that the point is to not have the arrays at all.

Consider the triangle:

1
1   1
1   2   1
1   3   3   1
1   4   6   4   1
.....

The 'simple' solution is to have a method like:

public int getPascalValue(int row, int column) {
    if (column == 0 || column == row) {
        return 1;
    }
    return getPascalValue(row - 1, column - 1) + getPascalValue(row - 1, column);
}

That is a system for recursively calculating the value at a given row/column (assuming valid input).

It does a fair number or recalculations, but the point is that it solves the problem as stated.


Battle a random enemy I am trying to write a text adventure as my first Python project. For this segment, I wanted a random enemy (part of a class with its own attributes) to appear and then enter a turn based battle with the player until either the enemies health is 0 or the player's health is 0. The player can use one of three moves to attack the enemy. The difficulty to beat the enemy is based on its strength, defence and health attribute.

Feel free to pull it apart and mention improvements or constructive criticisms that you may come up with.

import random, time

player_health = 100

class Enemy:

    def __init__(self, name, strength, defense, health):
        self.name = name
        self.strength = strength
        self.defense = defense
        self.health = health

    def attack_enemy(self):
        time.sleep(1)
        print ("what move would you like to make? (punch, kick or headbutt?")
        print("")
        answer = input()

        if answer == "punch":
            self.health = self.health -     (random.randint(1,100)/(random.uniform(0,1)*     self.defense))
            self.health = int(self.health)
        elif answer == "kick":
            self.health = self.health - (random.randint(1,100)/(random.uniform(0,1)* self.defense))
            self.health = int(self.health)
        elif answer == "headbutt":
            self.health = self.health -   (random.randint(1,100)/(random.uniform(0,1)* self.defense))
            self.health = int(self.health)
        else:
            print("you stumble...")

        time.sleep(1)

        print (self.name + "'s health is now: " + str(int(self.health)))
        print("")

        return int(self.health)

    def enemy_attack(self):
        global player_health
        time.sleep(1)
        print ("The enemy " + self.name + " " + "attacks...")
        print("")
        player_health = player_health - (self.strength * random.uniform(0.1, 1.4))
        player_health = int(player_health)
        time.sleep(1)
        print ("Your health is now " + str(int(player_health)))
        print ("")
        return int(player_health)

    def battle_script(self):
        global player_health
        print ("An enemy " + self.name + " appears...")
        print ("")
        time.sleep(1)
        while player_health > 0 and self.health > 0:
            self.attack_enemy()
            if self.health <=0:
               break
            self.enemy_attack()
            if player_health <=0:
                break
        if self.health <= 0:
            time.sleep(1)
            print ("You have killed the " + self.name)

        if player_health <= 0:
            time.sleep(1)
            print ("Sorry, you are dead")

enemies = [Enemy("Boar", 10, 5, 100), Enemy("Wolf", 20, 10, 100), Enemy("Lion", 30, 20, 100), Enemy ("Dragon", 40, 30, 130)]

random_enemy = random.choice(enemies)
random_enemy.battle_script()

A positive to begin with - your code generally follows the style guide, which is an excellent start. Some docstrings would be nice, though (I have also omitted these, but they are generally a good idea). Also, your imports should really be on separate lines:

import random
import time

Having a global is generally a bad sign. Why not make your Player a class too? This would be very similar to Enemy, so we can do some inheritance:

class Character:

    def __init__(self, health):
        self.health = health

    def attack(self, other):
        raise NotImplementedError

Note that all Characters will have health and be able to attack, although at this point we don't supply an implementation for the latter. This separates the enemy_attack and attack_enemy methods into separate classes, which makes much more sense (the use of self is currently a bit confusing).

class Player(Character):

    def __init__(self, health=100):
        super().__init__(health)

    def attack(self, other):
        answer = input("What move would you like to make (punch, kick or headbutt)? ")
        if answer.lower() in ('punch', 'kick', 'headbutt'):
            other.health -= int(random.randint(1, 100) /
                                (random.uniform(0, 1) * other.defense))
        else:
            print("you stumble...")

The Player will only have health, and its attack is based on user input. Note the use of super to call the parent __init__, and the use of in to check the user's input.

class Enemy(Character):

    def __init__(self, name, strength, defense, health):
        super().__init__(health)
        self.name = name
        self.strength = strength
        self.defense = defense

    def attack(self, other):
        print("The {0.name} attacks...".format(self))
        other.health -= int(self.strength * random.uniform(0.1, 1.4))

The Enemy has some additional attributes, and the attack is entirely random. Note the use of str.format to provide output.

This isn't perfect, because:

a Player relies on other having a defense attribute, so two Players can't attack each other; and
health can fall below zero, which doesn't make much sense.

Perhaps you could refactor to solve these problems?

The battle logic is independent of which Characters are involved, so should become a separate function rather than an instance method:

def battle(player, enemy):
    print ("An enemy {0.name} appears...".format(enemy))
    # Combat loop
    while player.health > 0 and enemy.health > 0:
        player.attack(enemy)
        print("The health of the {0.name} is now {0.health}.".format(enemy))
        if enemy.health <= 0:
            break
        enemy.attack(player)
        print("Your health is now {0.health}.".format(player))
    # Display outcome
    if player.health > 0:
        print("You killed the {0.name}.".format(enemy))
    elif enemy.health > 0:
        print("The {0.name} killed you.".format(enemy))

Note that there is no need to break for the player.health, as the loop will end there automatically.

Now the overall game becomes:

if __name__ == '__main__':
    enemies = [Enemy("Boar", 10, 5, 100), Enemy("Wolf", 20, 10, 100),
               Enemy("Lion", 30, 20, 100), Enemy ("Dragon", 40, 30, 130)]
    battle(Player(), random.choice(enemies))

Note the use of if __name__ == '__main__', to allow e.g. import elsewhere without running the loop (so you can use the Characters in other scripts more easily), and the line break in enemies to keep line lengths reasonable.


AsyncPages in ASP.NET 2.0 I'd like a review of this implementation of Async in ASP.NET 2.0 web form page below.  Let me know if I am missing something.

AsyncPagesASPNET20.aspx

<%@ Page Language="C#" Async="true" AutoEventWireup="true" CodeFile="AsyncPagesASPNET20.aspx.cs" Inherits="AsyncPagesASPNET20" %>

AsyncPagesASPNET20.aspx.cs

public partial class AsyncPagesASPNET20 : System.Web.UI.Page
{
    private string queryCustomerSelect = "SELECT FirstName, LastName FROM SalesLT.Customer";
    private DataAccess dataAccess = new DataAccess(WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            this.PreRenderComplete += AsyncPage_PreRenderComplete;
            AddOnPreRenderCompleteAsync(new BeginEventHandler(BeginAsyncOperation), new EndEventHandler(EndAsyncOperation));
        }
    }

    private void EndAsyncOperation(IAsyncResult ar)
    {
        Trace.Write("EndAsyncOperation...");
        this.dataAccess.EndAsyncSelect(ar);
    }

    private IAsyncResult BeginAsyncOperation(object sender, EventArgs e, AsyncCallback cb, object extraData)
    {
        Trace.Write("BeginAsyncOperation...");
        return dataAccess.BeginAsyncSelect(sender, e, cb, extraData, this.queryCustomerSelect);
    }

    void AsyncPage_PreRenderComplete(object sender, EventArgs e)
    {
        this.GridView1.DataSource = this.dataAccess.reader;
        this.GridView1.DataBind();
    }

    public override void Dispose()
    {
        this.dataAccess.Dispose();
    }
}

DataAccess.cs

public class DataAccess : IDisposable
{
    string connectionString = string.Empty;
    private SqlConnection connection;
    private SqlCommand command;
    public SqlDataReader reader;
    public DataAccess(string connectionString)
    {
        this.connectionString = connectionString;
        this.connection = new SqlConnection(this.connectionString);
        this.command = new SqlCommand();
    }

    public IAsyncResult BeginAsyncSelect(object sender, EventArgs e, AsyncCallback cb, object extraData, string query)
    {
        this.command.CommandText = query;
        this.command.CommandType = CommandType.Text;
        this.command.Connection = this.connection;
        this.connection.Open();
        return this.command.BeginExecuteReader(cb, extraData);
    }

    public void EndAsyncSelect(IAsyncResult ar)
    {
        this.reader = this.command.EndExecuteReader(ar);
    }

    public SqlDataReader SelectSync(string query)
    {
        this.command.CommandText = query;
        this.command.Connection = connection;
        this.connection.Open();
        this.command.Connection = connection;
        return this.command.ExecuteReader();
    }

    #region IDisposable Members

    public void Dispose()
    {
        if (this.connection != null)
        {
            this.connection.Close();
        }
    }

    #endregion
}

Overall a very cleanly written class.  It is easy to follow and understand.

A couple of suggestions though.

Make the reader class variable a Property with a private setter.  This will eliminate the ability to reassign it from outside of the class.  I would also rename it Reader to fit with C# coding standards.

Most C# coding standards I have read suggest prefixing private class variables with a _.  This will allow you to remove the this. statement whenever you need to access one of the class variables.  I think doing that will make you code much easier to read.

I'm not sure what the SelectSync method is used for.  I see it as a way to do a non-async query into the database.  If that is the case, I would move it to a different class as it interferes with the async nature of the one you have written.  Maybe rename this class to DataAccessAsync, and have a second one DataAccess?  Its hard to say without an example of a call to that method.

I can't see much more at this point.