Summary:

If you have multiple function that does similar tasks, make it as one that passes an arg.
If you have to repetitively type the something over and over again, there's probably a better way to do it
Include some error checking in spots such as input()
Take advantage of the string module. For example: string.ascii_letters is the same as 'abcdef...ABCDEF...'

Note to the OP:

Here's a more concise version of your code. I also made it be able to take any amount of length. Read the comments cause they explains every change I made

import random
import string

def gen_pass(length):  # Prints a generated string of any length of chars

    # don't name anything list or other type name. Use a name like word_list instead
    word_list = list(string.ascii_letters+string.digits) # use string module to make it shorter, so you dont need to type everything

    generatepassword = "".join([random.choice(word_list) for i in range(length)]) # typing the same thing over and over again is redundent
                                                                        # use a variable for the length instead of making multiple functions

    print(generatepassword)
    print("The passwords consists of: {} Characters\n".format(length)) # use str.format instead of + to make it look neater.
                                                            # isn't length the same as len(generatepassword)?
                                                    # add the \n on to the previous print statement

# don't need the other functions now

def generate():  # This askes how long the password should be

    print("How long do you want your password? ") # now it supports any length of password
    while 1: # do some checking, while 1 is an infinite loop until it's breaked
        try: # do some error checking as well
            choice = int(input("please input the length >> ")) # make it an integer
            if choice < 1: # should not be less than 1
                raise TypeError()

        except TypeError: # if choice < 1:
            print("Length should not be less than 1") # show an error message

        except ValueError: # if choice is not a number:
            print("Please input a valid integer") # show an error message

        except:
            print("Some other error occured... :(") # show an error message if some other error occured, though I don't think it's possible

        else:
            break # if no error occured

    gen_pass(choice) # generates a password with any length
    # everything else isn't needed

again = 'yes'
while again.lower() in ['yes','y']: # use lower in case they capped it, use this kind of checking method
  generate()
  again = input("\nDo you want to generate another password? [yes] or [no] >> ") # put the print statements inside the input()


Honestly, for the symbol, I'd just go with using uppercase characters (X and O) since the pieces don't really have any special functionality at this stage, and it's good to keep some simplicity with earlier projects.

I'd put the win condition checking into the game class. If you want to reuse the board class in the future, it's a good idea for you to avoid having any implementation-specific code (i.e. functionality that's specific to Tic-Tac-Toe) in the class - when you're dealing with Object Orientied Programming, you have to consider SOLID principles.

In terms of self.available_positions, I'd forego it entirely. You already have a structure which keeps track of the board, so adding a second structure to keep track of available positions is largely redundant - because one is just the inverse of the other (i.e. self.available_positions are the null elements in self.grid), and duplication is wasting memory and can lead to error (it's also good practice to have a single source of truth).

In terms of code, it's a good start, but I have a few suggested modifications for the Board class:

class Board:
    def __init__(self):
        self.grid = {1: '', 2: '', 3: '', 4: '', 5: '', 6: '', 7: '', 8: '', 9: }
        # Board starts with 9 available positions, and we'll decrement it by one.
        # I've changed to this from the self.available_position dictionary because you were
        # essentially maintaining two structures to maintain the progress of the game,
        # and having a single integer that we decrement is easier.
        self.remaining_turns = 9

    def update_board(self, index, symbol):
        self.grid[index-1] = symbol
        # Decrease the number of available turns after placing a piece.
        self.remaining_turns -= 1
        # Probably worth checking for 0 remaining turns after performing this decrement.

    def check_for_win_condition(self,symbol):
        # This if statement will be entered if any of the functions return true

        if check_diagonal(symbol) or check_horizontal(symbol) or check_vertical(symbol):
            return True

    def check_horizontal(self, symbol):
        # 0,3,6 refer to the starting elements in your vertical grid check, the additions
        # refer to the offsets to get to the other elements in the line
        for element in [0, 3, 6]:
            if self.grid[element]==self.grid[element+1]==self.grid[element+2]==symbol:
                return True

    def check_vertical(self, symbol):
        # 0,1,2 refer to the starting elements in your vertical grid check, the additions
        # refer to the offsets to get to the other elements in the line
        for element in [0, 1, 2]:
            if self.grid[element]==self.grid[element+3]==self.grid[element+6]==symbol:
                return True

    def check_diagonal(self, symbol):
        # You can chain equality checks
        if (self.grid[0]==self.grid[4]==self.grid[8]==symbol) or (self.grid[2]==self.grid[4]==self.grid[6]==symbol):
            return True

It's just something I typed up quickly, and I haven't had the opportunity to test it yet. My biggest issue was with the check_for_win_condition function - you were repeating a lot of the same checks (just altering the element reference for the grid).

In terms of language choice; Python is great - it's versatile, and it's intuitive - however, go with Python 3. Python 2 is end of life in 2020 - which means it will no longer have support from the Python developers/maintainers, but Python 3 is in active development, and it has a number of improvements and new features.


I would try to create a data structure which stores both event data and required action. Something like this:

Map<byte[], Runnable> commands = new HashMap<>();
commands.put(Keys.POWER, SHUTDOWN);
...

Then you can iterate it over:

for (Map.Entry<byte[], Runnable> entry: commands) {
    if (Array.equals(entry.getKey(), recData)) {
        Platform.runLater(entry.getValue());
    }
}

It seems that the logger uses a wrong classname here:

Logger.getLogger(Keys.class.getName()).log(Level.SEVERE, null, ex);

It might mislead maintainers/bug hunters.
The comments is just a noise here, you should remove it:

throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.

(Clean Code by Robert C. Martin: Chapter 4: Comments, Noise Comments)
Usually I try to avoid abbreviations like upde, shtdnWin, actShutdown. They are not too readable and I suppose you have autocomplete (if not, use an IDE, it helps a lot), so using longer names does not mean more typing but it would help readers and maintainers a lot since they don't have to remember the purpose of each variable - the name would express the programmers intent and would not force readers to decode the abbreviations every time they read/maintain the code.

See also: Clean Code by Robert C. Martin, Use Intention-Revealing Names, p18; Avoid Mental Mapping, p25

  If you can’t pronounce it, you can’t discuss it without sounding like an idiot. “Well,
  over here on the bee cee arr three cee enn tee we have a pee ess zee kyew int, see?” This
  matters because programming is a social activity.

Source: Clean Code by Robert C. Martin, Use Pronounceable Names, p21
Key_Action does not follow the usual Java naming conventions. Classnames should be CamelCase, without underscore.


Telling a client that there is no result via the DTO pattern

I only quickly glanced at your code, so this isn't going to be a thorough review, but I think the basic idea is surprising:

Service never returns null or throws exceptions.

I think this approach is error-prone. When I call a method called GetUserById, for an Id that doesn't exist, I expect either an ArgumentOutOfRangeException (or similar), or a null return value - the last thing I expect is a valid object filled up with default values filling up all members.
As @jlnorsworthy mentioned in his excellent comment, your approach is far from instinctive. Instead of:
var userDto = UserService.GetUserById(1);
if(!userDto.Response.HasValue)
{
      //No result is available
}

I would perfer to have:
var userResult = UserService.GetUserById(1);
if(userResult.Result == null)
{
      //No result is available
}

Also HasValue confusing because it is a well-known member of Nullable<T>, so I'd consider changing EntityId to be Nullable<long> or Nullable<Int64>:
public bool HasValue
{
    get { return EntityId.HasValue; }
}

What is IRepositoryLocator? If it is what I think it is, you should read up on Mark Seeman's blog. Shortly put:

Service Locator is a well-known pattern, and since it was described by Martin Fowler, it must be good, right?
No, it's actually an anti-pattern and should be avoided.

Little nitpick, I wouldn't use ForEach here:
public void AddBusinessWarnings(IEnumerable<BusinessWarning> warnings)
{
    warnings.ToList().ForEach( w => _businessWarningList.Add(w));
}

It would be much more readable (and less semantically controversial) to write it like this:
public void AddBusinessWarnings(IEnumerable<BusinessWarning> warnings)
{
    _businessWarningList.AddRange(warnings);
}


DRY. Actual computations are repeated twice, which is always a signal for improvement:

if (x < 0) {
    t = 1 / (1 - p*x);
} else {
    t = 1 / (1 + p*x);
}

result = compute_the_formula(t, x);

if (x < 0) {
    result = -result;
}
return result;

Try to cut down multiplications. Instead of

a_1*t + a_2*t*t + a_3*t*t*t

consider

t*(a_1 + t*(a2 + t*a_3)))

Three multiplications instead of original six is not only faster, but generally more accurate.


The functional approach is almost certainly faster despite having worse big-O — \$O(j \cdot s)\$ functional vs \$O(j + s)\$ imperative — because linear searches of small arrays are very fast.

You don't need to destructure j and adding a boolean to a number coerces the boolean to 0 or 1.

sum is a better name than num and c is a good name for a character iterator.

const findNumberOfJewels = (j,s) => [...s].reduce( (sum, c) => sum + j.includes(c),  0 );


This is how I ended up doing it now:

<?php

namespace App\Registration\GroupUploads\Errors;

/**
 * Error that appear during parsing csv file
 * @var [type]
 */
abstract class Error
{
  const USEREXISTS  = 7;
  const MAILINVALID = 1;
  const SEALUSED    = 2;
  const MIXEDUP     = 3;
  const QUALMISSING = 20;

  public $id;
  protected $msg;

  /**
   * Get error message
   * @return [type] [description]
   */
  public function getMsg()
  {
    return $this->msg;
  }

  /**
   * Error if user existed before registration
   * @param  [type] $name [description]
   * @return [type]       [description]
   */
  public static function userAlreadyExists($name)
  {
    $error = new Error();
    $error->id   = static::USEREXISTS;
    $error->msg  = "User " . $name .  " already exists";
    return $error;
  }

  /**
   * Mail is not valid
   * @param  [type] $mail [description]
   * @return [type]       [description]
   */
  public static function mailInvalid($mail)
  {
    $error = new Error();
    $error->id   = static::MAILINVALID;
    $error->msg  = "The mail " . $mail .  " is not valid";
    return $error;
  }

  //..
}

This way the getMsg method is short. Also adding a new error only requires to add one method instead of two (and no modification of the getMsg function).

To identify an error I call if($error->id == Error::USEREXISTS){...}.

Having the id was quite important, because I wanted to store the errors in DB.


I have to say your code is clean and well thought-through. There is always space of improvement though.

Cut the fluff. Reduce your access modifiers. There is no (visible) reason for seconds nor running not to be private.

And no reason why timer-controlling methods have to be public, either. Indeed, this is not how you would want the external word to communicate with your Activity - in the Android world, Activities have their own life-cycle and they get shut down and recreated by the OS, meaning you don't normally want to hold on to any particular instance of an Activity.

(Also, don't use redundant arguments: your timer-controlling methods don't make any use out of your View parameter.)

Due to the lifecycle thing I mentioned - more info at  http://developer.android.com/training/basics/activity-lifecycle/index.html - you should check whether the Activity is still there before you call textView.setText(time)!

Attempting to update a UI that's no longer in sight (and therefore gone) will result in a crash. How could it happen? Very simple - let's say your timer is running, and there's an incoming call in between two ticks. Or user switches to another app, or dims the screen. Etc. And it's fairly nondeterministic, especially when the device is running short on memory.

Using a Handler is a convenient way of sending actions to the thread message queue. And this trick with your Handler calling itself is an easy way of ensuring that "ticks" repeat over and over (without using the actual Timer, whose API is a bit clunky).

However, this Handler is a perpetuum mobile. It will prevent the Activity from ever getting garbage-collected. Even if it refrains from touching the UI if it no longer exists, it would keep on going. You should kill it if user exits the Activity - see https://stackoverflow.com/a/20377022/168719

To minimize these problems, I'd recommend extracting the timer logic into a separate class, and have your StopWatchActivities (note the plural: you shouldn't assume there'll only be a single instance!) subscribe and unsubscribe from it in their onResume / onStop methods.

Another thing: a Handler by default runs on the same thread on which it was created, in this case it's the UI thread. This is okay in this case because the task is light-weight and pretty much limited to updating the UI (which has to be done on the UI thread anyway). If it was computationally expensive though, you'd have to delegate it to another thread, but then make sure to eg. call the textView.setText(time) via  Activity.runOnUiThread().

I would also have a few cosmetic remarks related to naming.

stopTimer should rather be pauseTimer, because it doesn't reset it.
having variables named sec and seconds is a bit confusing. I'd prefer seconds and totalSeconds or secondsElapsed - it distinguishes them better.

I'm not sure what's exactly wrong with the code from your link - for starters, I can't see where the 1 second delay between ticks is enforced?? - but it proves my point as for why having sec next to seconds isn't a good idea:

int sec = seconds % 60;
String time = String.format("%02d:%02d:%02d", hours, minutes, seconds);

Surely the author meant to pass sec, not seconds, to String.format, no? :)


Parse and extract synonym data from a website

You're doing things the hard way.   By that I mean, why build a web crawler for this?   Is it a requirement that you only use thesaurus.com?   There are several quality thesaurus services out there with APIs that you could utilize.

I've never used any of them, but a quick web search and a bit of sifting results and these ones appear to be at the head of the thesaurus API ballgame.

Altervista Thesaurus:  Thesaurus is a web service providing search capability for synonyms in different languages.
The synonyms are retrieved from the thesauri dictionaries of OpenOffice according to the relevant licenses.
Big Huge Thesaurus: This site sports a very simple API for retrieving the synonyms for any word. You can access the API by making a GET request...

I also found another Stack Exchange post on the topic, which lists some more options:
https://webapps.stackexchange.com/questions/9156/database-of-english-synonyms

If thesaurus.com is absolutely a requirement, then you're doing the best you can.  You have to send the request, crawl the page, extract the information you want, and format it into something you can use.

thesaurus.com does have an API, but from how they describe it, its difficult to get them to give you access.  You can read more about that here:

thesaurus.com API


PHP function to compare two Roman numerals

It gives wrong results for 9 (IX) and 5 (V).

Some notes about the code:

In the following block the $evaluate = 8; and the break; statements are unnecessary, they never run because of the return statement.

{
    return true;
    $evaluate = 8;
    break;
}

Instead of commenting name the variable to what the comment says.

//Create array with ordered list of roman numerals.
$evaluation= array("M","D","C","L","X","V","I");

It could be $numerals or $numerals_in_order, for example.
7 and 8 are a magic numbers. They should be named constants or computed values. Do they come from the size of the array? If they do make it clear, it would improve readability.
while ($counter < ((strlen($x_num)))&& $counter < ((strlen($y_num))))

This could be simplified to the following:

$size = min(strlen($x_num), strlen($y_num));
while ($counter < $size)

Instead of big if-elseif structures you could use continue and simple ifs since some of them returns the function if the condition is true, so the remaining code won't run. The last else also would be unnecessary.

$size_min = min(strlen($x_num), strlen($y_num));
while ($counter < $size_min) {
    if ($x_num_arr[$counter] == $y_num_arr[$counter]) {
        $counter++;
        continue;
    }

    if(($x_num_arr[$counter]!=$evaluation[$evaluate])&&($y_num_arr[$counter]==$evaluation[$evaluate])) {
        return true;
    }

    if(($x_num_arr[$counter]==$evaluation[$evaluate])&&( $y_num_arr[$counter]!=$evaluation[$evaluate])) {
        return false;
    }

    $counter++;
}

Inside the for loop the $evaluation array is always indexed with $evaluate. You should create a local variable for this.
The same is true for $y_num_arr[$counter] and $x_num_arr[$counter] inside the while loop. (They could be $current_x and $current_y).
It might not be an issue (depending on the specification) but the function currently accepts invalid Roman numerals too (like IIX).
At the end of the function it returns with implicit NULL if both conditions are false in the following snippet:

if ($evaluate<8&&(strlen($x_num) < strlen($y_num)))
{return true;}

elseif ($evaluate<8&&(strlen($x_num) > strlen($y_num)))
{return false;}

You should make this explicit (add a return false as the last statement) or use an assert call if it should never happen.
You could easily write some test code to check that the comparison is fine for every possible Roman numeral.

for ($i = 1; $i <= $max; $i++) {
    for ($j = 1; $j <= $max; $j++) {
        $i_r = numberToRoman($i);
        $j_r = numberToRoman($j);
        $smaller = x_smaller_than_y($i_r, $j_r);
        if ($i >= $j && $smaller) {
            echo "error: $i, $j, $i_r, $j_r\n";
        }
    }
}

If I'm right $max should be 3888 and it finishes in a few minutes. You can find a numberToRoman function here, for example..


Email a notification when detecting changes on a website

You do not need to find the differences manually, you can use difflib.SequenceMatcher:

I think this is what you need:

>>> a, b = "foobxr", "foobar"
>>> diffs = difflib.SequenceMatcher(None, a, b).get_matching_blocks()
>>> diffs
[Match(a=0, b=0, size=4), Match(a=5, b=5, size=1), Match(a=6, b=6, size=0)]
>>> max((a, b), key=len)[diffs[0].size : diffs[1].a]
'x'

Specific except

Specify what you want to except exactly. Bare except catches even typos!

Use a logger

You print a lot of info, a logger is more flexible and can be very easily redirected to a file.

.format

You can make your messages more readable:

For example:

    print(date+": Start Monitoring... hash: "+self.urlhash)

Becomes:

print("{date}: Start Monitoring... Hash: {self.urlhash}".format(**locals()))

Or the more standard:

print("{}: Start Monitoring... Hash: {}".format(date, self.urlhash))

Thanks to @Jatimir for noticing that in python 3.6+ f-strings are a nice way to interpolate variables in strings with a clean sintax: for example:

print(f'{date}: Start Monitoring... Hash: {self.urlhash}')


What about making the Register method generic?

public class Mediator
{
    private Dictionary<Messages, Action<object>> registeredCallback =
        new Dictionary<Messages, Action<object>>();

    public void Register<TParam>(Messages message, Action<TParam> callback)
    {
        registeredCallback[message] = p => callback((TParam)p);
    }

    public void Notify(Messages message, object parameter)
    {
        callback(parameter);
    }
}

The typecasting is done inside the Register method, making it invisible to any class using it.

You can also change signature of the GreetUser method so that it takes a User instead of a string as a parameter. By doing so you can call Register like this:

mediator.Register<User>(Messages.UserCreated, GreetUser);


Print a Connect 4 grid based on some rules for each cell

Is the graphic representation of a data structure an integral part of that data structure (val gString = myGrid.asText) or separate and independent from the data structure (val gString = asText(myGrid))?

I tend to favor the former, but if the Grid API is solid and supplies everything needed for one or more graphic representations, then the latter is probably the better choice. It's a little hard to judge here as you haven't provided the Grid (or Piece) code.

I question the choice of iterating through coordinates that are known to be outside the Grid just for the purpose of drawing a border. Wouldn't it be easier to get the grid contents and simply "wrap" them with border characters?

def asText(grid :Grid) :String = {
  val border = "|" + "-"*grid.x + "|"
  (1 to grid.y).map{ y =>
    (1 to grid.x).map{ x =>
      if      (grid.pieces.contains(Piece("X", x, y))) "X"
      else if (grid.pieces.contains(Piece("O", x, y))) "O"
      else "."
    }.mkString("|", "", "|")
  }.mkString(s"$border\n", "\n", s"\n$border")
}


Multiple games with same rpg-classes base

I'm having trouble visualizing what your intention here is.

Let's talk about your code itself, then I'll move on to a slight redesign:

C# has a nice-new language feature called "Expression-Bodied members", basically, this:

public int Strength => 5;

That's equivalent, but much shorter than your version:

public int Strength { get { return 5; } }

So, I would recommend moving to something like that, if you want to keep this design.

But, I would redesign this:

Everything has the same stats, right? They all need the stats, they just might have different values?

public class Stats
{
    public int Strength { get; }
    public int Constitution { get; }
    public int Agility { get; }
    public int Accuracy { get; }
    public int Intelligence { get; }
    public int Charisma { get; }
    public int Luck { get; }
}

So we're using another new language feature here: auto-implemented readonly properties. Basically: don't put code in the get, and these can only be set by the constructor. Of course, we need a constructor:

public Stats(int strength, int constitution, int agility, int accuracy, int intelligence, int charisma, int luck)
{
    Strength = strength;
    Constitution = constitution;
    Agility = agility;
    Accuracy = accuracy;
    Intelligence = intelligence;
    Charisma = charisma;
    Luck = luck;
}

Now, because everyone has their own specific stats, but they all follow the same structure, we use this class in the object:

public abstract class Entity
{
    public Stats Stats { get; }
    public Entity(Stats stats)
    {
        Stats = stats;
    }
}

So, because everybody is the same type of "Entity" with different attributes, we then move on to the Warrior / Wizard / etc.:

public abstract class Warrior : Entity
{
    public Warrior()
        : base(new Stats(5, 4, 3, 3, 2, 3, 1))
    { }
}

public abstract class Wizard : Entity
{
    public Wizard()
        : base(new Stats(2, 3, 3, 3, 5, 4, 1))
    { }
}

Now you can use the ILocatable etc. in the specific games, but the basics are all the same across-the-board. We build a more extracted model: the things that have to be there are, and are enforced.

With this part:

public interface IGame
{
    Type WarriorType { get; }
    Type WizardType { get; }
}

We can do some trickery:

public abstract class Game<TWarrior, TWizard>
    where TWarrior : Warrior
    where TWizard : Wizard
{
    public Type WarriorType => typeof(TWarrior);
    public Type WizardType => typeof(TWizard);
}

Now, I don't know why you need the WarriorType or WizardType, you probably don't need them in this version, because we put those types on the Game class.

We obviously haven't handled the TakeDamages or Shoot, right? We need to find a way to deal with that on a game-by-game basis: enter ECS (entity-component-system).

We built the entities, they have stats (components), now we need "systems" to handle the components.

public class ActualWizard : Wizard { }
public class ActualWarrior : Warrior { }

public class ActualGame : Game<ActualWizard, ActualWarrior>
{
    public class ShootSystem
    {
        public static void Shoot(Entity source, Entity target)
        {
            Console.WriteLine($"Shooting with STR={source.Stats.Strength}");
        }
    }
}

So, now you would call ShootSystem.Shoot(myWarrior, myWizard);, which would be where you handle all of the logic to actually shoot the wizard with the warrior. This also means that all entities can use the same function, whatever they may be. (Paladin, etc.)

var myGame = new ActualGame();
var myWarrior = new ActualWarrior();
var myWizard = new ActualWizard();
myGame.ShootSystem.Shoot(myWarrior, myWizard);

You would add any stats specific to warriors to ActualWarrior, same with ActualWizard, but you don't put the logic there, you build a System for it.


The server announces HTTP 1.1, therefore it must support HTTP 1.1 features, most importantly pipelining (client has a right to send multiple requests over the same socket). In any case, if you chose to close the client socket immediately you should inform client with a Connection: close header.
You expect to consume a complete request with a single read. In a streaming world of TCP you never know how many bytes has actually been consumed. You should be prepared to get as little as one byte at a time (same goes for send/write).

A correct way to read the request is to read it in the loop until the end of headers (i.e. an empty string) is seen.
Network program must be defensive. A malicious client can play tricks with your server.

For example, it may never send anything; eventually the server would run out of file descriptors (or pthreads), resulting in denial of service. Another client may close the socket immediately upon sending a request; the server receives a SIGPIPE and dies with a core dump.


How to properly call an "upsert" using parameterized raw SQL to Postgresql in ActiveRecord?

Statement, formatted readably:

WITH
sel AS (
  SELECT id FROM categories WHERE name=$1 AND source=$2
),
ins AS (
  INSERT INTO categories (name, source, created_at, updated_at )
  SELECT  $1, $2, 'now', 'now'
  WHERE NOT EXISTS (SELECT * FROM sel)
  RETURNING id
)
SELECT id FROM ins
UNION ALL
SELECT id FROM sel;

Dummy table:

CREATE TABLE categories (
    id serial not null PRIMARY KEY,
    name text not null,
    source text not null,
    created_at timestamp,
    updated_at timestamp,
    UNIQUE(name, source)
);

Demo, with three concurrent psql sessions:

Session1: PREPARE q(text,text) AS WITH ...
Session2: PREPARE q(text,text) AS WITH ...
Session0: BEGIN;
Session0: LOCK TABLE categories IN ACCESS EXCLUSIVE MODE;
Session1: EXECUTE q('n', 's');
Session2: EXECUTE q('n', 's');
Session0: ROLLBACK;

One session will report:

regress=> EXECUTE q('n', 's');
 id
----
  1
(1 row)

and one will report:

regress=> EXECUTE q('n', 's');
ERROR:  duplicate key value violates unique constraint "categories_name_source_key"
DETAIL:  Key (name, source)=(n, s) already exists.

So it might be OK if you have a unique constraint on (name, source) and are willing to retry errors, but if you don't have that unique constraint:

ALTER TABLE categories DROP CONSTRAINT categories_name_source_key;

then you'll get a double insert, because your SELECT for IDs can run on both sessions before either session executes the INSERT.

If you have a unique constraint, there's no point wasting your time with all this hoop jumping. You're better off just running the insert and if it fails, querying for the ID of the existing row.


Algorithm to determine if a string is all unique characters

You probably shouldn't call toUpperCase() twice on each character.

If you wanted to split your code properly (if it was for a real-life project for instance), it would make sense to make the documentation a bit better and to define a method taking a String as an argument and returning a boolean. Let's keep things simple for the time being; you can return immediately after printing "not unique". If you do so, there's no need for the test on x and there's no need for x at all.

You probably should check that the characters are in the right range before accessing chars.

I'd rather read if (c) { A } else { B } than if (!c) { B } else { A } even though it depends from one situation to another. In our case, it also allows to remove a level of nesting because of the return.

You don't need an instance of PracticeProblems at all, and the function could just be static.

Finally, I do not know if Java optimises out the different call to length() so we might ensure we don't call it every time.

public class PracticeProblems {
    public static void questionOne(String input) {
        boolean[] chars = new boolean[26];
        String upper = input.toUpperCase();

        for(int i = 0, n = upper.length(); i < n; i++)
        {
            char c = upper.charAt(i);
            if ('A' <= c && c <= 'Z')
            {
                if(chars[(int)c - 'A'])
                {
                    System.out.println("not unique");
                    return;
                }
                chars[(int)c - 'A'] = true;
            }
        }
        System.out.println("unique");
    }

    public static void main(String[] args) {
        questionOne("dsfdddft");
    }
}


Hello and Welcome to Code Review!
There are two main concerns I have with your solution:

Side Effects

Your program has side effects outside of its scope: Arrays.sort(arr) When you call this function you are sorting the array object whose reference you have been passed. This means you are sorting the array that exists outside of your method scope, thus transforming any array you have been passed.

Since Arrays.sort() causes side effects, I'd recommend using Arrays.copyOf() to make a local copy, then sort the local copy.

Over-copying

You use Arrays.copyOf() inside your for loop, meaning you are frequently copying and making new arrays. These memory operations are expensive, and unnecessary.

You copy a range, but check only the end points of the range. Would it not make more since to simply check the values that would otherwise become those endpoints? Essentially, while looping, maintain two indeces, the head and tail pointers(i and i+k-1), and check those values rather than creating a new copy.

A good way to view this approach: We are essentially maintaining a abstract sliding range of k elements, and starting at 0, we slide our range along the array, checking each endpoint for a minimum without the need to create concrete copies.

With the above I reduced your solution to the below

static int maxMin(int k, int[] arr) {
    int arrLen = arr.length;
    //1)Make Sorted Local Copy to prevent Side Effects
    int[] localArr = Arrays.copyOf(arr, arrLen);
    Arrays.sort(localArr);

    int minUnfairness = Integer.MAX_VALUE;
    //2)Loop while maintaining two pointers
    // NOTE: we use J instead to prevent side effects on the int k
    int i = 0;
    int j = k - 1;
    while(j < arrLen){
        int tempMinUnfairness = localArr[j] - localArr[i];
        if ( tempMinUnfairness < minUnfairness ) {
            minUnfairness = tempMinUnfairness;
        }
        i++;
        j++;
    }
    return  minUnfairness;
}


those volatile variables: not only do they seem redundant, they actually breach thread safety.  volatile variables are used when you actually want the variable to be accessed by multiple threads (for example, when you want one thread to set a boolean and then have another read that variable).  as far as I could detect, the two variables can be replaced by local ones.
those notifyAll() calls: they are mostly redundant. the method is only useful if a client thread has called wait().  that is usually the case if the queue is empty and a client wants to block until a new item has ben added. if the list is not empty, the client usually pops an item and goes about processing it. so you need to understand when clients will want to wait for an event to happen and get notified about it.  Secondly, calling notifyAll() only makes sense if you release the lock immediately after the notification.  calling notifyAll() in a loop without releasing the lock will not do anything.
as an exercise, this solution will work. However, it is not efficient. synchronizing all the methods mean that any access to the queue will prevent all other access. for example, if one thread calls isEmpty() it has locked the entire queue. you may think that isEmpty() is such a small method, but what if the thread just entered the wethod and got a context switch from the OS. it can wait for 2-3 milliseconds before releasing the lock (and that is a long time in the computation universe).  so in order to be more efficient, you need better granularity on the scope of the locking.  For example, set a boolean if the queue is in the process of being modified and only at these times lock the reading methods.  and you can get more efficient with more sophisticated (and complex) mechanisms (like locking only part of the queue this is being modified etc)
ALL_CAPITAL names in Java (and other languages), are used for constant variables, not for those that hold state. (i.e. recevied from arguments). even if they are immutable.

EDIT

Regarding the question in the comment:

  What happen when isEmpty and size don't be synchronized? Do we
  care?

well, it can be that one thread will ask isEmpty at the same time that another is pushing an item into the queue. that is why I believe that in the body of the reading methods you need to create a synchronized block that is dependant on a boolean that is set when a writing method is called.

Another advice I can give you is to have a look at java.util.concurrent package.  it contains several lock mechanisms that are more powerful and flexible than synchronized blocks.  For example, ReentrantLock has the following text in its documentation:

  A reentrant mutual exclusion Lock with the same basic behavior and
  semantics as the implicit monitor lock accessed using synchronized
  methods and statements, but with extended capabilities.

there is a useful example in this topic it shows how you can use a ReentrantLock instance across methods, something that may be useful in your case.

lastly, have a look at java.util.concurrent.ConcurrentLinkedQueue which seems to fit at least some of your requirements. if you are doind this asan exercise, then take a look at the class' source code and see hoe they dealt with thread safety issues.


Speaking as a human programmer (i.e. I am not Lint software), your use of "100" there looks fine to me.

Wikipedia has an article (without citations) titled Accepted limited use of magic numbers: IMO your "100" is in the same category as these other "accepted" magic numbers.

This Wiki describing magic numbers says two things.

Firstly,

  Practical Magic Number rule: A literal is a not a magic number if the most meaningful variable name for it is the same as the spoken name of the literal.

That's applicable here: you're looking for a named constant like HUNDRED or CENTUM.

Secondly, it also suggests loading "magic" numbers (e.g. a "discount rate") from a configuration file:

static final double DISCOUNT_PERCENT = getProperty( "sales.discount_percent" );
static final double DISCOUNT_FACTOR = 1 - (DISCOUNT_PERCENT / 100);

// ...

salePrice = DISCOUNT_FACTOR * regularPrice;

Note that though this example code carefully loaded DISCOUNT_PERCENT from a configuration, the "100" used to calculate the DISCOUNT_FACTOR is hard-coded.

If you use "100" instead of HUNDRED, it's easier for a programmer to understand, and to verify that it's correct.

IMO the only benefit to using HUNDRED is to find the several methods which use the same magic number (in your example it's used by getPercent and getRate).


You have a common bug that will send you into an infinite loop. :-)

When reading data (especially user input data) you must validate the read worked correctly. If the read fails and sets one of the error flags on the stream than any subsequent attempt to read will silently be ignored.

Thus usually read operations are checked in the loop test.

std::string word;
while(word != "STOP") {
    std::cin >> word;
    std::cout << "Word: " << word << "\n";
}

In the above you will enter an infinite loop if your hit an EOF marker (Note: this can be generated from the keyboard) or in unix systems a file can be piped to the input stream of an application etc..

To prevent this you test the result of the read operation.

std::string word;
while(std::cin >> word && word != "STOP") {
    std::cout << "Word: " << word << "\n";
}

This works because of two things. The operator>> returns a reference to the stream (usually for chaining). When a stream is used in a boolean context (like a test) it is converted to a bool using operator bool which calls good() which returns true if the stream is still in a good state (ie the read operation did not cause an error).

Secondly declares variables as close to the use point as possible.

This is a good habit to get into with C++ as objects have constructors that can potentially be expensive (also destructors). Declaring them at the top of the function and then not using them is wasteful.

Also be declaring them near the use point also allows for locality of reading when checking variables types.

In your case:

    std::string answer;

This is declared at the top but only used inside the loop.

Also prefer not to use return 0; in main() when the application never returns an error state. The compiler will automatically generate the required return 0 and leaving it off is a marker used by programs to indicate that the program never fails.

Give this I would rewrite as:

bool checkAnswerOK(std::string& answer, bool& result)
{
    std::transform(answer.begin(), answer.end(), answer.begin(),
                   [](unsigned char x){return ::tolower(x);});

     bool answer_valid =
            (answer == "y")   ||
            (answer == "n")   ||
            (answer == "yes") ||
            (answer == "no");

    result = answer_valid && answer[0] == 'y';
    return answer_valid;
}

bool question_yesno(std::string const& message)
{
    std::string answer;
    bool        result;

    std::cout << message << "? [Y/n]\n";
    while(std::cin >> answer && !checkAnswerOK(answer, result))
    {
        std::cout << "Invalid answer: " << answer << " Please try again\n"
                  << message << "? [Y/n]\n";
    }
    if (!std::cin) {
        // We never got an answer.
        // Not much we can do here. Probably give up?
        throw std::runtime_error("User Input read failed");
    }
    return result;
}

int main()
{
    question_yesno("Should the password include digits");
}


HashTable - separate chaining collision in C++

You're attempting to read values from uninitialized variables which has undefined behavior:

int sum; // uninitialized`
for(int i=0; i < length; i++){`
    sum+=e[i]; // reading from uninitialized variable "sum"

Read this
From "HASHSET_H_" I gather it's a header file.
You should never use using namespace std; in a header file (and chances are it's a bad idea to use it anywhere else, too -- unless you're porting legacy 1980s C code to C++):

Link 1
Link 2
If you can use C++11 then nullptr is a better choice than NULL: read this

// Note, however, that if you're NOT using C++11, then the following is a potential performance problem:
int HashSet<Element>::HashFunction(string e)
Pre-C++11 this can create unnecessary copy, so prefer to pass-by-const-reference in C++98/03 instead.

Compare:

copy
move
no copy (elided)
int is a wrong type for a variable holding size or count (such as hashSize, bucketSize, totElems).
In particular, this is very bad: int length = e.size();
Not only you're using a wrong type, but potentially also losing performance due to unsigned-to-signed conversion // which, perhaps more importantly, is completely unnecessary and only makes the code harder to read -- are you suggesting that length can be negative? If not, then don't use int.

Prefer std::size_t instead (defined in header <cstddef>):

Link 1
Link 2
Make sure to use meaningful variable names. This includes not using ambiguous abbreviations. totElems is not a good name. totalElementsCount is better.
Additional idea: make sure to pick a naming convention and stick to it.
For instance, some of your functions start with uppercase character, like IsEmptyAtGivenKey, but some with a lowercase character, like setInfo.
It's better if they all follow the same convention (e.g., all functions start with lowercase, all types start with uppercase, etc.).

As a hint, read the "Naming" section from Google C++ Style Guide.

// Extra hint: feel free to completely ignore the other sections, or even take them as examples of what NOT to do (like the one on exceptions), unless you're working at Google with Google's code base.
Manual memory management is troubling.

I've read from your comments that this is for school, so chances are the class / teaching methods simply aren't exactly up-to-date (thinking teaching C before C++ is a good idea is often a good indicator), but IRL invoking raw new (such as here: new Node*[hashSize];) without a very good reason is nowadays unnecessary and considered a bad practice.

If you want to learn best practices, start with this.

// Not to repeat myself from my previous answer, here's a link to it, if you'd like more information on memory management specifically: here.


To start with, I'd like to give you credit for using "use strict" and limiting the scope of variables using functions.

Your tol33t() function is weird to me.  If the randomcase button is checked, you call randomizeCase() with no arguments.  What are you randomizing the case of?  It turns out that randomizeCase() calls changeWords(), so it turns out that the two code branches have something in common after all.  That wasn't apparent from looking at tol33t().

There should be clearer separation responsibility between the DOM-interaction and text-translation layers of code.  The text translation code should reside in pure functions (whose results depend solely on their parameters) that you could call from the JavaScript console or from a unit testing engine.  That separation of concerns could be accomplished with:

function onTranslateButtonClicked() {
    var l33tText = toL33t(elite.value, adv.checked);
    if (randomcase.checked) l33tText = randomizeCase(l33tText);
    leet.value = l33tText;
}

Your "l33t the words object" initialization routine lays a trap for anyone trying to  read the code.  When code in changeWords() refers to the words associative array, one would reasonably think that it's using the definition above (i.e., words = { "am": "m", … }) instead of the munged version (words = { "4m": "m" }).  Better to make that munging explicit when you define words (and do so by returning a copy rather than mutating the dictionary as you iterate):

var words = l33tKeys({
    "am": "m",
    …
});

function l33tKeys(dict) {
    var l33tDict = {};
    for (var word in dict) {
        l33tDict[changeWord(word)] = dict[word];
    }
    return l33tDict;
}

I would write changeLetters() as:

 // letterSubsts may be alphabet or alphabet2
function changeLetters(text, letterSubsts) {
    return text.toLowerCase().replace(/[a-z]/g, function(letter) {
        return letterSubsts[letter] || letter;
    });
}

… which is actually analogous to your implementation of changeWords().


Keep elements present an odd number of times in an unsorted vector

Since you asked for performance relevant code review I will answer these questions first and than will make some comments on the coding style.

The comments allready mentioned Profiling, so I will start with your original code and run it with CodeXL. Afterwards I will modify the code based on the profiling and will comment on possible performance improvements.

Profiling the Program

Since CodeXL works with samples wich is a statistical method (see https://en.wikipedia.org/wiki/Profiling_(computer_programming) ). For compilation I used MSVC2013 with the "-O2" flag for code optimization. I run your code in 10^5 times in for-loop. The result was this:

The Column with % of deep samples is an indicator of how much time the program spends in a function and its child function. Thus the main function is typically on the top.
Interesting are the third and fourth row which show that the "<<" operator and "std::endl" does take around 48% of your program. Based on this I just deleted the code for output and rerun the program. With 10^5 repeats it finished in less than a second. It should be mentioned that that was a lot faster than just 50%. The reason for this can be better compiler-optimization possibilities due to the missing ouput, because the loop has not more sideeffects, but this is only a guess. Nevertheless I rerun the program with 10^6 repeats to gather good profiling Data.

The top three functions (ignoring main) were:

std::vector<...>::_Reallocate 58.13% of deep samples
std::vector<...>::_Insert 11.96% of deep samples
std::_Sort<...> 10.01% of deep samples

Based on this I will give some comments about how to speed up the Code.

General possibilities for performance improvements

As shown above the vector::_Reallocate does take a lot of time in the code. This might be cause by the line output.push_back(input[i-1]); in your code. It will reallocate if the allocated memory of the vector needs to increase to store all elements. It will then allocate new memory and copy all its elements. This can be avoided by calling output.reserve(x); aft the construction of output. This will preallocate the memory for x elements. Since you optimize for speed and not for memory input.size() would be a good guess for the "x", because than you can be sure that output will not reallocate within the loop.

For your question of using the input vector for output and directly operating on it: I would guess that such an approach would include a lot of "erase" calls wich will also lead to a lot of copying, thus I do not think it would be faster.
Since you mentioned that your input will only have around 10 elements, I would not take to much time considering O-Notations because they are mainly interesting for large amounts of elements. In small dimensons the so oft forgotten constant in front of an O(...) will matter.
On the original code: The use of std::endl may have a big performace impact since it does not only produce a newline but it also flushes the putput. The use of "\n" or '\n' might be better.
Some times the compiler flags may have a big impact on performance. I does not have the knowledge for a detailed review, but I know of many cases were people look for code improvements because the program is slow but they compiled their program with debug configuration, so I thought it shopuld be mentioned.

Some small comments on coding style

Avoid "using namespace std" it is considered bad practice because it can lead to suprising collisions and ambiguity.
Prefer the prefix "++" to the postfix "++" unless you really want to increase a value and get the original value returned.
Avoid the using of std::endl, for the reasons stated above.

I hope this give a good overview on how to improve code for performance.


Unique compile time (constexpr) type ID without RTTI

I'm convinced that your design will work correctly. Uniqueness of static variables is guaranteed, and they won't be optimized away if you define and odr-use them (taking the address of a variable is odr-using it). Running it through stack-overflow would be a good idea though, because it will probably catch the eye of one of those 200K+ reputation guru who answer all the tricky language questions.

What I can't understand is what you're trying to achieve with this. The only useful property of this compile-time id is its uniqueness, so it doesn't achieve anything more than the type itself: what is the difference between if (type_id<A>() == type_id<B>()) and if (std::is_same_v<A, B>)? I would argue that it achieves a lot less, because types have other useful traits (for a partial but ready-made list, just take a look at the type_traits header in the standard library).

Besides, your id generator isn't truly generic: type_id<int&>() won't compile because a pointer can't point to a reference (thus static const int&* const id is illegal). Of course there's always the possibility to remove the reference, but it means that you'll use type_traits to make your type_id work -so it underlines that you should use well-established, standard type traits instead of this new compile-time type_id.

I'd suggest, if it is possible, that you post here a larger part of your code,
 containing use cases, and let our collective brain work on the solution of the broader problem.

Edit: I understand now better what you want to do. I really like the simplicity of use, and I find the hack very clever. Actually, if it was uglier, limitations like no-references-allowed wouldn't matter much, because everyone would see it as work-around. But since it seems so fluent, it could quickly become pervasive in the code; then limitations matter, all the more when they result in obscure error messages.

Anyway, I believe I would have come up with a less ambitious design, which would also be easier to maintain and understand (this concrete implementation relies on C++17 but it wouldn't be to difficult to implement in previous standards):

#include <iostream>
#include <vector>

template <typename... Types>
struct Type_register{};

template <typename Queried_type>
constexpr int type_id(Type_register<>) { static_assert(false, "You shan't query a type you didn't register first"); return -1; }

template <typename Queried_type, typename Type, typename... Types>
constexpr int type_id(Type_register<Type, Types...>) {
    if constexpr (std::is_same_v<Type, Queried_type>) return 0;
    else return 1 + type_id<Queried_type>(Type_register<Types...>());
}

int main() {
   Type_register<int, float, char, std::vector<int>, int&> registered_types;
   constexpr auto test1 = type_id<int&>(registered_types);
   constexpr auto test2 = type_id<int*>(registered_types);
}


Take care extending built in objects

Extending the prototype of builtin objects should be done with care. The best way is via Object.defineProperty  and first check if something has not already done so. (See 2nd rewrite)

Why create two copies of this.. self and that. Why  not just use this and create a map object with a meaningful name. (see 2nd rewrite)

Don't add functionality outside the role of the function. Array.unique Defiantly should not be calling an alert (in fact you can not trust alerts (clients can turn them off) so you should never use them)

You have actually repeated the process of removing duplicates in the keypress handler. You could just have checked if the length of data and result are different and alerted the client from that. (see 1st rewrite)

Rewrites
First quick rewrite showing you don't need Array.unique
$(document).ready(function(){
  const lol = $('#lol');
  lol.keypress(function(){
    const data = lol.val().split('\n');
    const result = data.filter((word, i, arr) => arr.indexOf(word) === i);
    lol.val(result.join('\n'));
    result.length !== data.length && (alert("duplicate"));
  });
});

The second rewrite showing a safe way to add to inbuilt prototypes.
Note that the options configurable, enumerable, writable are set to false. Particularly you MUST set enumerable to be false or you could end up with all sorts of bugs appearing in existing code.
You should also learn to not use jQuery. It has had its day and will just set you back as it shelters you from learning modern JS and DOM interfaces.

"use strict";
lol.focus();
lol.addEventListener("keyup", event => {
    const data = lol.value.split("\n");
    const result = data.unique();
    info.textContent = result.length !== data.length ? "Duplicate removed" : "";
    lol.value = result.join('\n');
});

if (!Array.prototype.unique) {
    Object.defineProperty(Array.prototype, "unique", {
        configurable: false,  // these 3 properties default to false so not needed
        enumerable: false,    // But have added them just to show their availability.
        writable: false,
        value: function() {
            const existing = {};
            return this.filter(a => existing[a] = !existing[a] ? true : false);
        }
    });
} else {
    throw new Error("Array.prototype.unique already defined.");
}
<textarea id="lol"></textarea>


Function

Certainly no reason to swap when values are equal.  In worse case of array {3,3,3,3}, leads to infinite loop.

//if( a[i+1] <= a[i]){
if(a[i+1] < a[i]) {

Use size_t to index arrays.

// void printMyArray(int a[],int n){
void printMyArray(int a[], size_t n) {

Style

Rather than int for Boolean variables use bool.

#include <stdbool.h>

// int swap = 0;
bool swap = false;

Recommend const when able.  Adds clarity to the function and allows for optimizations with some compilers.

// void printMyArray(int a[],int n){
void printMyArray(const int a[], int n) {

Minor: prefer int *a rather than int a[] as argument in printMyArray().
More useful to separate main() from the code under test.  Something like:

int main(void) {
    int a[] = {-1 , 2 , 0 , -3 , 5 , 1};
    bubble_sort(a, sizeof a/ sizeof a[0]);
    printMyArray(a, sizeof a/ sizeof a[0]);
    return 0;
}

Suggest fully {} blocks.  Use Idiomatic for(), Avoid  n-1, as size_t n may be 0.

   // int i = 0;
   // for(; i < n-1; i++)

   for(size_t i = 1; i < n; i++) {
     if(a[i] < a[i-1]) {
       int temp = a[i];
       a[i] = a[i-1];
       a[i-1] = temp;
       swap = 1;
     }
   }


Why are you using matrix rather than array? I recommend sticking with array

As for a better way:

seq = numpy.array([0, 1, 2, 3])
numpy.clip(seq[:,None] - seq, -1, 1)

seq[:, None], moves the numbers into the second dimension of the array
seq[:, None] - seq broadcasts the numbers against each other, and subtracts them.
numpy.clip converts lower/higher values into 1 and -1


System to handle the short lived async task

I would strongly recommend a use of Java 8 features to make your library (which has an API) an easier to use system.

Your Task interface should be a @FunctionalInterface. It is one already, but you should make it formal with the annotation:

@FunctionalInterface
interface Task<V>{
    public  V doTask();
}

Now, any time you want a task, you can do things like:

Task<Long> wordcount = () -> countWords("Hello World");

The above is equivalent to:

Task<Long> wordcount = new Task<Long>() {
    @Override
    public Long doTask() {
        return countWords("Hello World");
    }
}

This leads on to the next concern I have with the TaskManager. Here's your code copied:

class AsyncTaskManager
{
    private ExecutorService service;

    public AsyncTaskManager(ExecutorService service){
        this.service = service;
    }

    public <T> Future<T>  submit(Callable<T> callable){
        Future<T> result = service.submit(callable);
        return result;
    }

    public void shutdown(){
        service.shutdown();
        try {
            service.awaitTermination(60, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            service.shutdownNow();
        }
        service.shutdownNow();
    }

}

The following concern me:

The service should be final, make it immutable.
The service is created outside the class, but then shut down inside the class. This is asymmetrical. If the service is created outside then it should be shut-down outside.
The class should be AutoClosable instead of having the shutdown() method.

Again, I would use a Java-8 concept called a supplier. Instead of passing in a service, pass in a method that can create a service. That way, you can still add a custom service, but you create it, not the people who call you.

About the try/catch block in the shutdown... you should use a finally block instead of what you currently have, and also, you should reset the interrupted flag if there is an interrupt. This is better than doing nothing (which is what you currently do). It avoids the exception, but makes the next thing that checks have to handle it. In other words, you pass the buck.

This is how it would look:

class AsyncTaskManager implements AutoClosable {
    private final ExecutorService service;

    public AsyncTaskManager(Supplier<ExecutorService> service){
        this.service = service.get();
    }

    public <T> Future<T>  submit(Callable<T> callable){
        return service.submit(callable);
    }

    @Override
    public void close() {

        service.shutdown();

        try {
            service.awaitTermination(60, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        } finally {
            service.shutdownNow();
        }
    }

}


Single MySQLI query to check for admin privileges

You do not need to re-fetch or use a while loop, simply reuse the array that you fetched the first time.

<?php
session_start();
$identification = $_SESSION['session_name'];
include 'inc/database.php';
$query = "SELECT * FROM `members` WHERE `username` = '$identification' LIMIT 1";

$result = mysqli_query($database, $query);

$user_info = mysqli_fetch_array($result, MYSQLI_ASSOC);
$user_level = $user_info["privs"];
if ($user_level=='ADMIN'){}
else {
  header('Location: security.php?error=missing correct privileges. user is not admin');
  exit();
}

?>
<html>
<head>
<title>Zona de Pruebas</title>
</head>
<body>
Username: <?php echo $user_info['username']?>, can be here because is admin</div>
</body>
</html>
<?php
}
?>


I've used the below for a while:

public abstract class PropertyChangedBase : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected void RaisePropertyChanged(string propertyName)
    {
        var propertyChanged = this.PropertyChanged;

        if (propertyChanged != null)
        {
            propertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    protected bool SetProperty<T>(ref T backingField, T Value, Expression<Func<T>> propertyExpression)
    {
        var changed = !EqualityComparer<T>.Default.Equals(backingField, Value);

        if (changed)
        {
            backingField = Value;
            this.RaisePropertyChanged(ExtractPropertyName(propertyExpression));
        }

        return changed;
    }

    private static string ExtractPropertyName<T>(Expression<Func<T>> propertyExpression)
    {
        var memberExp = propertyExpression.Body as MemberExpression;

        if (memberExp == null)
        {
            throw new ArgumentException("Expression must be a MemberExpression.", "propertyExpression");
        }

        return memberExp.Member.Name;
    }
}

I can write my properties like this:

    private int id;

    public int Id
    {
        get
        {
            return this.id;
        }

        set
        {
            this.SetProperty(ref this.id, value, () => this.Id);
        }
    }


Primitive full-text search on some properties of an object

You have a lot of code that is not needed.

The two continue are not needed.
Rather than assign the variable foundObjects the filtered result just return the result directly.
The variable val that holds the property can be side stepped.
Then the hasOwnProperty can be combined with the if statement
Rather than use the for loop you can also use Array.some to find if any item matches the search

Thus you get

export const search = <T, K extends keyof T>(term: string, objects: T[], keys: K[]): T[] => {
    return objects.filter(x =>
        keys.some(key =>
            x.hasOwnProperty(key) &&
            typeof x[key] === 'string' &&
            x[key].toLowerCase().includes(term)
        )
    );
};


Printing out a binary tree level by level

I got the following output:

Level 1: 5   Level 2: 2  8   Level 4: 4  7  10   Level 3: 1  3  6  9

Printing the layers in a non-deterministic order is probably undesirable behaviour.  You used an unordered_map, which guarantees the order of neither its keys nor its values.  To impose order on the values (the nodes of each level), you store a vector in the map, which complicates the data structure.

The traditional way to do a breadth-first traversal of a tree is to use a queue, and to work iteratively on elements of the queue rather than recursively on elements of the tree.  Not only is this a less complex data structure than an unordered map of ints to vectors of nodes, it also stores nodes from no more than two levels of the tree at a time, rather than all nodes of the tree at once.

#include <queue>
#include <utility>   // for std::pair

template <typename T>
void printBinaryTree(const Node<T> *n) {
    if (nullptr == n) {
        return;
    }
    int level = 0;

    // Use a queue for breadth-first traversal of the tree.  The pair is
    // to keep track of the depth of each node.  (Depth of root node is 1.)
    typedef std::pair<const Node<T>*,int> node_level;
    std::queue<node_level> q;
    q.push(node_level(n, 1));

    while (!q.empty()) {
        node_level nl = q.front();
        q.pop();
        if (nullptr != (n = nl.first)) {
            if (level != nl.second) {
                std::cout << " Level " << nl.second << ": ";
                level = nl.second;
            }
            std::cout << n->data << ' ';
            q.push(node_level(n->left,  1 + level));
            q.push(node_level(n->right, 1 + level));
        }
    }
    std::cout << std::endl;
}

As a final touch, pay attention to the const-correctness of the function's parameter.


C-string appender for buffers and strings

In addition to what the other answers say and I generally agree with:

Don't call strlen more than once.  That's just a waste.  Count the length of orig_str and append_str once at the beginning of the function and store them away in const variables.  That will also make your initial check whether append_str is empty look cleaner:

const size_t append_len = strlen(append_str);
if (!append_len)
    return orig_str;
const size_t orig_len = strlen(orig_str);

Moving the strlen(orig_str) above the conditional would look cleaner in my eyes but it might be a pessimization if append_str is often empty.

Of course, the most efficient way would be if you could pass orig_len as an additional input parameter.  Or you could use a

struct string_buffer
{
  size_t length;
  size_t capacity;
  char * data;
};

that encapsulates all the required info and change your function's signature to

ssize_t
append_string(struct string_buffer * buffer, const char * appendix);

where the function could return the number of bytes successfully appended or –1 on error.

My second remark would be that you are growing your buffer by a constant amount each time you reallocate.  It should really grow exponentially unless you really know that linear growth will be preferable in your specific use-case, which I find hard to imagine how that could be.

Concerning your comments: there is no NULL byte.  NULL is a macro constant for the null pointer.  The null byte is abbreviated as NUL in the ASCII character set.  I would also find it helpful to have your function's semantics exactly documented in a comment.  For example, should the user free the buffer if it fails and returns NULL?  Will the existing data be modified in that case?  I can try answering those questions by reading your implementation but that doesn't allow me to distinguish a bug in your code from a different valid design decision.


Returns two elements from a list whose sum is a target variable

Your search function is terribly unclear. search is a vague name, and a, b, d and m don't communicate anything. Looking at the usage I can see you're testing if a number is in the list, but Python can already do that for you much more readably.

if number in list

The in keyword tests if a value exists in a list, returning either True or False. So you can forget about search and just directly test for pair's existence in the main loop:

x = [1,4,5,7,9,6,2]
target = int(raw_input("Enter the number:"))
for i in x:
    if i < target:
        pair = int(target) - int(i)
        if pair in x:
            print "the first number= %d the second number %d"%(i,pair)
            break

Back to the naming, x is not clear, at least using numbers indicates what it contains. x implies a single value which makes using for i in x extra confusing. pair also sounds like it's multiple items, when really it's the difference you want.

You also don't need to call int on i when the list is populated with integers already.

Lastly, you're using the old form of string formatting. You should instead use str.format, like so:

            print("the first number= {} the second number {}".format(i,pair))

It works very similarly, except that it's type agnostic. It will just do it's best to get a string representation of the two values and insert them. There's lots of other uses for this approach so it's good to get used to.


Dynamically resizing panels based on browser window size

The problem is basically calculating the number of panels.
I'm no expert in media queries, but this is how i would solve it using js:

function PanelCount(lowerBound, upperBound, panelCount) {
  this.lowerBound = lowerBound;
  this.upperBound = upperBound;
  this.panelCount = panelCount
  this.isApplicableToContainerWidth = function(containerWidth) {
    return lowerBound <= containerWidth&& containerWidth< upperBound;
  };
}

function getCorrectPanelCount(containerWidth) {
    var panelCounts = [];
    panelCounts.push(new PanelCount(1500, Number.MAX_SAFE_INTEGER, 5));
    panelCounts.push(new PanelCount(1120, 1500, 3));
    panelCounts.push(new PanelCount(768, 1120, 2));
    panelCounts.push(new PanelCount(0, 768, 1));

    for (i = 1; i < panelCounts.length; i++) {
      if (panelCounts[i].isApplicableToContainerWidth(containerWidth)) {
        return panelCounts[i].panelCount;
      }
    }
}

Naming needs some improvement though, PanelCount is a horrible class name


Transforming XML with null checks vs variables

I'd definitely go for the second version. If you are not in a very specific limited environment, the additional memory won't hurt. Note that you basically just copy the references to the concrete content, not the content itself, so the whole memory-signature-thing essentially revolves around a few 4-byte pointers.

As for the code itself: one way of coping with these long if a != null && a.getB() != null && a.getB().getC() != null chains is, to use Optional and its map function. In the end it's all matters of taste, but you might e.g. do:

// inner if from last code sample
Optional.ofNullable(subObject)
    .map(XmlSubObject::getLocation)
    .ifPresent(this::mapOtherStuff);

I like this style very much, but seriously: matters of taste.

One more thing: in similar situations I found it really helpful to include static utility functions which map from null to empty collection/list and vice versa:

public static <T> List<T> emptyListIfNull(List<T> l) {
  if(l == null)
     return new ArrayList<T>(); // or Collections.emptyList() if immutable is OK
  return l;
}

public static <T> List<T> nullIfEmpty(List<T> l) {
   if(l != null && !l.isEmpty())
       return l;
   return null;
}

That way, you can shorten expressions like

xmlObject.getIdentifiers() != null && !xmlObject.getIdentifiers().isEmpty()

to

nullIfEmpty(xmlObject.getIdentifiers()) != null

... which helps a lot in readability.

Edit: one more afterthought. As bowzerfood mentioned nulls and equals in his answer, I'd like to point out additionally, that today you can use Objects.equals(a, b) instead of a.equals(b) which handles nulls correctly and without resorting to third-party libraries.


Implementation of getUsersWithStatuses based on getUsersWithStatus

I would say that in your case it is not a good idea because you will execute the same query many times.

However you can change you calls to have the method with a single status calling the one with many satuses.

List<UserDTO> getUsersWithStatus(Long locationId, Status status) {
  return getUserWithStatuses(EnumSet.of(status));
}

List<UserDTO> getUsersWithStatuses(Long locationId, EnumSet<Status> statuses) {
  // SELECT * FROM users WHERE status IN (..)
}


Integer math in tight loops is an area where C++ will definitely run circles around Python. I think your expectations are too high. However, I'd like to point out a couple of things for you, even if they are not enough to reach your goal.

Avoid indexing when you can use direct iteration instead. For example, insert can be written like this and Python won't have to deal with i:

def insert(tree,n):
     for level in tree:
         level[n] += 1
         n /= 2

Python does not optimize constant subexpressions out of loops, so you'll want to compute (K+1)/2 before the main loop and store it in a variable.


Video downloader app implemented in RxJs

Overall, I think this is very decent code, some observations:

JSHint

Use JsHint ;)
You have a number of missing semicolons, and an unnecessary semicolon
return url = new Buffer(url, 'base64').toString('ascii'); <- I dont think you wanted to assign to buffer?
You are not using the function fileName(url, season, episode){ anywhere

Odd stuff

You use the extremely cool fetchContent({ url }); but also the mundane

{
  response: response,
  body: body,
  args: args
}

You should stick to 1 approach
Your regex /"http(.*)(\.flv|\.mkv|\.mp4)"/

Is not supporting avi, wmv, or mpg file extensions.
Is not supporting uppercase incoming file names extentions.
Keeps repeating the \. for each extension, so I would keep that out of the brackets.
If you plan for many entries, then I would keep the regex outside of the function, and generate that regex only 1 single time for performance

You have a stray console.log(params.url);, get rid of it
It seemed odd that the HTML you prepare has no text in the anchor:

return `<a href=${url}></a>`;

Also, do you want to consider at least surrounding the URL with double quotes?

Sugar

You use req.body 3 times in getResult, I would have had a var params = req.body; as a shortcut
This seems a good use case for a ternary:

if (matches && matches[0]) {
    return
} else {
    return null;
}

could be

return (matches && matches[0]) ? matches[0] : null;

I am still not sure why you return null actually. PrepareHtml will return , so perhaps consider

return (matches && matches[0]) ? matches[0] : '';

Anonymous functions kill kittens every day

The 3 functions within your subscribe call are anonymous. It is in general terrible to look at a stack trace filled with anonymous functions
You also have one in getEpisodeRange
I do like that you declare your other functions 'the right way'

Comments go a long way

getEpisodeRange needs comments, it is the most intense code
There are actually no comments at all in this code, and I can parse everything just fine except the above mentioned function

Style

Formatting looks good to me
Naming looks good to me
I did not find obvious repetitions from a DRY perspective


2D lattice random walk plots in functional style

Looks good.  The code is functional with the exception of using
return, which is not necessary as the last value will be returned
anyway, so I'd simplify to the following and also in the interested of
efficiency only compute the coords once and without seq, as : is
shorter:

step <- function(x) {
        unlist(sample(possibleSteps, 1))
}

takeRandomWalk <- function(nSteps) {
        coordPairs <- Reduce(`+`, lapply(1:nSteps, step), accumulate = T)
        x <- sapply(coordPairs, `[`, 1)
        y <- sapply(coordPairs, `[`, 2)
        list(x, y)
}

plotRandomWalk <- function(nSteps, margins) {
        walkObj <- takeRandomWalk(nSteps)
        coords <- -margins:margins
        plot(coords, coords, type = 'n', xlab = "", ylab = "")
        lines(walkObj[[1]], walkObj[[2]])
}

Reduce with accumulate is pretty cool, I think this is the first
time I've seen an accumulate parameter on a reduce-like function
anywhere.

Now I think you know that, but usually R code like this would be written
with less lists and more data frames or matrixes.  That doesn't mean the
code isn't functional:  As long as it's using functions, not mutating
things and using functional abstractions instead of imperative
constructs it's fine.

So the following is probably more idiomatic and at the same time uses
more efficient representations for the data:

possibleSteps <- matrix(c(-1, 0, 0, -1, 1, 0, 0, 1), ncol = 2, byrow = TRUE,
                        dimnames = list(NULL, c("X", "Y")))

Gives a matrix with named columns like so, which will be the representation
throughout the rest of the code (which is good for consistency):

> possibleSteps
      X  Y
[1,] -1  0
[2,]  0 -1
[3,]  1  0
[4,]  0  1

The random walk will still be created by sample, except it's sampling
indexes.  cbind will create a new matrix from the two accumulated sums
(cumsum):

takeRandomWalk <- function(nSteps) {
        indexes <- sample(1:dim(possibleSteps)[1], nSteps, TRUE)
        walk <- possibleSteps[indexes,]
        cbind(X = cumsum(walk[,1]), Y = cumsum(walk[,2]))
}

And finally plotRandomWalk is a bit simpler as we can just give
lines the constructed coordinates matrix:

plotRandomWalk <- function(nSteps, margins) {
        coords <- -margins:margins
        plot(coords, coords, type = 'n', xlab = "", ylab = "")
        lines(takeRandomWalk(nSteps))
}


SqlConnection Transaction Management Approach

Don't add a the parameters to the save method. It adds unnecessary complexity to the api and it makes it a leaky abstraction because it forces knowledge of the underlying data store onto consumers.

Add a SaveAll method to your repository (why is it called a Facade?)

public static Product SaveAll(IEnumerable<Product> products)
{
    using (var scope = new TransactionScope())
    using (var conn = new SqlConnection(DatabaseHelper.ConnectionString))
    {
        conn.Open();
        foreach (var product in products)
        {
            Save(product, conn);
        }
        scope.Complete();
    }
}

// Used by both public `Save` and public `SaveAll`.
private static Product Save(Product product, SqlConnection conn)
{
    using (var cmd = conn.CreateCommand("SaveProduct"))
    {
        cmd.CommandType = CommandType.StoredProcedure;

        // etc.
    }
}

I haven't written raw ADO.Net code for several years so I apologise if the above is massively incorrect. You should explore a product like Entity Framework (full ORM) or Dapper (more lightweight) to simplify a lot of this repetitive code.


You are using i = 1 as a special case, when in fact that can be handled by your other code already:

for (int i = 1; i <= 100; i++) {
    for (int j = 1; i * j <= 100; j++) {
        lockers[i * j] = !lockers[i * j];
    }
}

However, to be more readable, I suggest changing the inner loop:

for (int i = 1; i <= 100; i++) {
    for (int j = i; j <= 100; j += i) {
        lockers[j] = !lockers[j];
    }
}

Now it reads as "Start j at i, repeat as long as j is less than or equal to 100, increase j by the value of i"


I would replace

i = 1
Dir.foreach(CWD) do |file|
    next if file == "." or file == ".."
    next if !file.end_with? "jpg" and !file.end_with? "JPG"

with

Dir[File.join(CWD, '*.png')].each_with_index do |file, i|

or

Dir.glob(File.join(CWD, '*.png')).each_with_index do |file, i|

I prefer DIR[] over Dir.glob, but I think this is a question on your private coding style.
File.join(CWD, '*.png')] creates a path. Advantage: the system may decide, it if use / or \ (or whatever the OS needs).

Another change I would do:
Use the string format options instead of replacing $.
If you want to use the $ in the command line, then you can replace the $ with a format string.
I use in my example below $02i - this means, replace the string with the given integer value, use at least 2 digits and add leading zeros.
This may be a help if you have more then 10 images.

Some more changes I would do:

I wouldn't use constants to fill it with parameters from the command line.
Either use global variables or normal variables.
Instead of Dir.pwd, I would use '.'
I would separate the real action and the user interface.
You have no checks, if the parameters are empty. In my later example I define defaults.
I would't check for n, but for a Yes.

My complete Code:

require "rmagick"
require "readline"

def convert_images(prefix, max_dim, path = Dir.pwd)
  #Use a glob instead of checking the pathes later,
  #Use each_with_index (Attention, i will start with 0!)
  Dir.glob(File.join(path, '*.jpg')).each_with_index do |file, i|
      img = Magick::Image.read(file).first
      resized = img.resize_to_fit(max_dim)
      #Don't use string operations for pathes
      newpath = File.join(path,prefix % [i+1] + ".jpg") #i starts with 0, so add 1.

      resized.write(newpath) do
          self.quality = 80
      end

      puts "%s -> %s" % [ file, newpath ]
      #~ File.delete file

      img.destroy!
      resized.destroy!
    end
  end

#Define parameters with defaults.
max_dim = ARGV[0] || 100
prefix = ARGV[1]     || 'my_pic_version_%i'
prefix.sub!(/\$/, '%02i') #use string format options.

puts "max dimension: #{max_dim}"
puts "prefix: #{prefix}"

read = Readline.readline "continue Y/n: "
if read =~ /^[Yy]/
  convert_images(prefix, max_dim)
end

Some other ideas:

Use the optparse-gem for interfaces
prefix could contain *.jpg (and the call it target_template or similar).


Modify or not modify your objects when creating computing functions?

I suggest cloning. If it was possible (like in Java), I'd even suggest making your objects immutable...

Why do I suggest cloning? Consider being after a busy Friday, with business users ranting all day on some totally unimportant feature, and you see this code fragment all of a sudden, having a, b and c variables:

b=sum_modifying(a,b);
 //some other code here
a=sum_modifying(c,a);
 //some other code here
b=sum_modifying(c,a);

Will you be able to track back what's going on? I woudn't, for sure...

Even this is a tough situation, but at least, the value of the variables change only with the assignment.

b=sum_cloning(a,b);
 //some other code here
a=sum_cloning(c,a);
 //some other code here
b=sum_cloning(c,a);

However, I'd suggest a third alternative: add functions to the objects themselves, to enable schemes like this:

result = a.add(b);

I'd find this the most readable of these.
(I stole the idea mainly from Java's BigDecimal.)


Listing in order the things I made note of/changed looking through your code:

output chan HHResult is declared but never used in go funcs(output chan HHResult). It's fine that it's not used, the go func has access to  Result in the parent function, but you don't need to declare it if it's not needed.

The headers map argument is never used either.

Looking at Request and RequestWithOptions they're the same function except for the variable timeout. Request can be a small wrapper that just sets a default timeout then calls the more general function

Similarly, you repeatedly return the same HHResult only substituting which err is used so that can be pulled into it's own function sendErr(chan, err)

Any exported function or type (any that start with capital letters) should be commented

If you look in the net/http package you'll see it's standard to capitalize HTTP in variable names. Same with JSON.

Bugs:

a. One bug in your code is you send JSON via http.Request but you don't actually set the Content-Type to application/json which can cause issues with how your request is interpreted on the other end
b. Another bug is that the error in respbytes, err := ioutil.ReadAll(resp.Body) is never used and you actually return nil for it whether or not you could actually read the body.
c. Timeout: time.Second * 30 throws an error

As written, I don't see the need for the IHTTPHelper interface. HttpHelper has the only two methods used hanging directly from the struct and there's no way to inject a different type implementing the same interface into any of your code. As is HttpHelper alone does everything you need.

Purely stylistically, I think some of the variable names like HHResults are confusing and rewrote them

package services

import (
    "bytes"
    "encoding/json"
    "io/ioutil"
    "net/http"
    "time"
)

// HelperResponse is the response returned by an HTTPHelper.Request()
type HelperResponse struct {
    Result     string
    StatusCode int
    Error      error
}

// HTTPHelper hangs Request and RequestWithTimeout methods
type HTTPHelper struct{}

var singleton *HTTPHelper

// NewHTTPHelper returns a pointer to the HTTPHelper singleton
func NewHTTPHelper() *HTTPHelper {
    if singleton == nil {
        singleton = &HTTPHelper{}
    }
    return singleton
}

func sendErr(out chan HelperResponse, err error) {
    out <- HelperResponse{
        Result:     "",
        StatusCode: 0,
        Error:      err,
    }
}

// Request wraps RequestWithTimeout with default 30 second timeout
func (h *HTTPHelper) Request(method string, url string, payload interface{}) (out chan HelperResponse) {
    return h.RequestWithTimeout(method, url, payload, 30)
}

// RequestWithTimeout returns Response, StatusCode, and any Errors from an http request
func (h *HTTPHelper) RequestWithTimeout(method string, url string, payload interface{}, timeout int) (out chan HelperResponse) {
    go func() {
        payloadJSON, err := json.Marshal(payload)
        if err != nil {
            sendErr(out, err)
        }

        req, err := http.NewRequest(method, url, bytes.NewReader(payloadJSON))
        req.Header.Add("Content-Type", "application/json")

        client := http.Client{Timeout: time.Second * time.Duration(timeout)}

        resp, err := client.Do(req)
        if err != nil {
            sendErr(out, err)
        }

        respBytes, err := ioutil.ReadAll(resp.Body)
        defer resp.Body.Close()

        out <- HelperResponse{
            Result:     string(respBytes),
            StatusCode: resp.StatusCode,
            Error:      err,
        }
    }()

    return out
}


Building a minimal-height BST from a monotonically increasingly ordered array structure

Simplified Node type

This constructor:

Node() : left(), right() {}

Can be replaced with:

constexpr Node() noexcept
    : data{}
{}

The default constructor of std::unique_ptr<>  will initialize its contained pointer to nullptr, so you do not need to explicitly call it.

All of your classes' data members have non-throwing default constructors. Thus, you can safely mark yours as noexcept.

We can mark this constructor as constexpr, because similarly, all of your data member's default constructors are constexpr. This can be useful if you want to define a static compile-time special value, such as the empty node value.

This constructor:

Node(int data) : data(data), left(), right() {}

Can be replaced with:

constexpr Node(int const data) noexcept
    : data(data)
{}

We mark the parameter as const, because it is not modified.
We remove the redundant calls to the default constructors of left and right.
We mark it as constexpr and noexcept.
We use new lines for readability.

Finally, since you can live with initializing data with zero, you can replace both constructors with a single one:

constexpr Node(int const data = 0) noexcept
//                          ^^^^^ default value
    : data(data)
{}

Simplified calls

Your get_midpoint_iterator() function can be simplified. Here is how it currently looks:

template <typename It>
It get_midpoint_iterator(It start, It end) {
    auto midpoint = std::distance(start, end) / 2;
    It mid = start;
    std::advance(mid, midpoint);
    return mid;
}

These statements:

It mid = start;
std::advance(mid, midpoint);
return mid;

Can be replaced with:

return std::next(mid, midpoint);

View the documentation here: http://en.cppreference.com/w/cpp/iterator/next

Since your function's body now looks like this:

auto midpoint = std::distance(start, end) / 2;
return std::next(start, midpoint);

You can simply erase midpoint and put the calculation at the function call location:

return std::next(start, std::distance(start, end) / 2);

You end up with a concise function that is guaranteed copy elision in C++17.

template <typename It>
It get_midpoint_iterator(It start, It end) {
    return std::next(start, std::distance(start, end) / 2);
}

As @miscco points out, this obfuscates the operation slightly, so you might also want to add a comment indicating that std::distance(start, end) / 2 is the midpoint.

Your create_bst_helper() function currently initializes a std::unique_ptr<> in the following fashion:

root = std::move(std::unique_ptr<Node>(new Node(*midpoint)));

This can be more clearly expressed with:

root = std::make_unique<Node>(*midpoint);

Your create_bst_helper() function currently creates a std::unique_ptr<> instance by assigning nullptr to it:

std::unique_ptr<Node> bst = nullptr;

The default constructor of std::unique_ptr<> already does so:

std::unique_ptr<Node> bst; // equivalent to `= nullptr;`


The following is very Pythonic, but a little too terse if you are not used to it:

def createTreeFromEdges(edges):
    tree = {}
    for v1, v2 in edges:
        tree.setdefault(v1, []).append(v2)
        tree.setdefault(v2, []).append(v1)
    return tree

Basically, setdefault does the following:

def setdefault(self, key, default=None):
    if key not in self:
        self[key] = default
    return self[key]


Exposing .NET's internal StorageRoot via Reflection for accessing file/stream-based Structured Storage

A stream-like class that doesn't implement IDisposable and needs to be closed manually, and worked with static methods, breaks POLA/POLS.

I would expect to be able to do this:

using(var ms = new MemoryStream(bytes))
using(var root = new StorageRoot(ms))
{
    // do stuff
}

I like the reflection idea to access these otherwise hidden gems, however in a code base that uses objects in a standard/idiomatic way, I see this one sticking out like a sore thumb.

I'd definitely do whatever it takes to make it work with a proper instance.


Counting Hamiltonian triangulations (OEIS 3122)

To start with, the spec is badly phrased. I know it's not your fault, but it might help you (and would almost certainly help reviewers) to clarify it. It talks about partitions of s but since m = m_1 + m_2 + ... + m_s the m_i are actually a partition of m, and it requires unpicking of the definition. I suggest the following rephrasing:

  $$B(s, m) = \sum_{\lambda \vdash s,\, |\lambda| = m} \binom{m}{a_1, \ldots, a_k} r(1)^{a_1} \ldots r(k)^{a_k}$$
  where the sum is over all partitions of \$s\$ into exactly \$m\$ parts, \$\lambda = 1^{a_1} 2^{a_2} \ldots k^{a_k}\$ in the frequency representation.

Memoisation support in Python

30 seconds with Google turned up https://docs.python.org/3/library/functools.html#functools.lru_cache . If you know that you're only going to want 10000 different arguments memoised then

@lru_cache(maxsize=10000)
def b(s, m):
    ...

Optimising the integer partition search

How do you form a partition of \$s\$ into \$m\$ parts? You take a part \$p\$ and add it to a partition of \$s - p\$ into \$m - 1\$ parts. To avoid duplication you enforce that the parts are decreasing.

def partitions(s, m):
    return partitions_inner(s, m, s)

def partitions_inner(total, num_parts, max_part):
    # Each of the parts must be between 1 and max_part
    if total < num_parts or num_parts * max_part < total:
        return []
    if num_parts == 1:
        return [[total]]

    results = []
    for part in range(1, max_part + 1):
        for subpartition in partitions_inner(total - part, num_parts - 1, part):
            results.append([part] + subpartition)
    return results

This should be about as efficient as your code, but has the great advantage that partitions_inner can be memoised. Converting to frequency representation is quite simple, and in fact you could refactor this to produce output directly in frequency representation.

But that's irrelevant

If you look at how the \$B(s, m)\$ are used, you see that it's only in \$A(n, s) = \sum_{m=1}^{s} \binom{n}{m} B(s, m)\$. So \$B\$ sums over all partitions with a given number of parts, and then is summed over all numbers of parts. If you cut out the middle-man you get just $$A(n, s) = \sum_{\lambda\vdash s} \binom{n}{a_1, \ldots, a_k} r(1)^{a_1} \ldots r(k)^{a_k}$$ where the sum is over all partitions of \$s\$, \$\lambda = 1^{a_1} 2^{a_2} \ldots k^{a_k}\$ in the frequency representation.

Generating all partitions is (obviously) simpler than generating all partitions with a given number of parts.

def partitions_inner(total, max_part):
    if total == 0:
        return [[]]

    results = []
    for part in range(1, min(max_part, total) + 1):
        for subpartition in partitions_inner(total - part, part):
            results.append([part] + subpartition)
    return results

Again, this can be memoised. It's also possible to trade off memory for speed by splitting up the multinomial as $$\begin{eqnarray}T(\lambda) & = & \binom{m}{a_1, \ldots, a_k} r(1)^{a_1} \ldots r(k)^{a_k} \\
A(n, s) & = & \sum_{\lambda\vdash s} \binom{n}{m} T(\lambda)\end{eqnarray}$$ where the sum is over all partitions of \$s\$, \$\lambda = 1^{a_1} 2^{a_2} \ldots k^{a_k}\$ in the frequency representation, and \$m = \sum_i a_i\$. \$T(\lambda)\$ can be memoised, but also it can be calculated incrementally by using a more complicated object to store the partitions instead of just an array of the parts:

class Partition:
    def __init__(self, maxPart, tail = None):
        self.part = maxPart
        self.tail = tail
        if tail is None:
            self.partFreq = 1
            self.numParts = 1
            tailTerm = 1
        else:
            self.partFreq = tail.partFreq + 1 if tail.part == self.part else 1
            self.numParts = tail.numParts + 1
            tailTerm = tail.term
        self.term = tailTerm * r(self.part) * self.numParts // self.partFreq

@lru_cache(maxsize=100)
def partition(n):
    accum = []
    for maxPart in range(1, n):
        for tail in partition(n - maxPart):
            if tail.part > maxPart:
                break

            accum.append(Partition(maxPart, tail))
    accum.append(Partition(n))
    return accum

(Note that I'm not a Pythonista and I haven't checked the above code against PEP8).


Rounds off numbers from 1 - 10, 000 including negatives

min < value < max

Python makes this kind of conditions really easy:

if absol < 10 and absol > 0:

Like this:

if 0 < absol < 10:

Don't repeat yourself

Instead of this:

    if floater < 0: #Negative check
        print(-temp)
    else:
        print(temp)

    # ...

    if floater < 0: #Negative check
        print(-temp)
    else:
        print(temp)

Create a helper function:

def abs(num):
    if num < 0:
        return -num
    return num


new Thread(this).start();

I may be wrong about this, but I don't think this is recommended in the constructor.

ExecutorService implementations exist to provider better/consistent handling of asynchronous tasks. Arguably, a better form will be to extend your abstract class and use it with an ExecutorService instance, instead of having it (Connection) decide when to start running.

Inside your run() method, you may want to consider the following rewrite as it is slightly more expressive and reduces one level of nesting:

while (run) {
    byte send[] = null;
    synchronized (posts) {
        if (posts.isEmpty()) {
            continue;
        }
        send = posts.get(0);
        posts.remove(0);
    }
    // send != null probably not required, as long as post() does not accept null
    // if (send != null) {
    try {
        os.write(send);
    } catch (IOException e) {
        hasError(e);
    }
    // }
    // ...
}

Considering you are doing something like:

posts.get(0);
posts.remove(0);

You might actually be looking for a Queue implementation to simplify this approach. In fact, you may be looking for a thread-safe implementation so that you do not need the explicit synchronized blocks, such as something that implements a BlockingQueue.

  Given the above sample of my idea of how to make maintainable modular code, what sort of pitfalls should I look out for while making the excursion into a legitimate program of larger than two or three files?

A thorough answer for this will be out-of-scope here on CR, so my only advice is to perhaps ask that on Programmers.SE (as long as you can make it on-topic there). :)


You have 2 models (Ringtone extends Contenido). As I understand you store same nombre, fecha_creacion, keyword in both models and every update/delete/insert operation on the first model must be synchronized with another one. You can avoid this, make foreign key to base model:

class Contenido(models.Model):
    nombre = models.CharField(max_length=100)
    fecha_creacion = models.DateTimeField('fecha creacion')
    keyword = models.CharField(max_length=100)

class Ringtone(models.Model):
    contenido = models.ForeignKey(Contenido)
    grupo = models.ManyToManyField(Artista)
    archivo = models.FileField(upload_to="uploads")

class Wallpaper(models.Model):
    contenido = models.ForeignKey(Contenido)
    categoria = models.ForeignKey(Categoria)
    archivo = models.ImageField(upload_to="uploads")

Then in your Views

def tempurl(request,hash):
    p = get_object_or_404(Dynpath, url_path=hash)
    try:
        obj=Wallpaper.objects.get(contenido_id=p.id)
    except Wallpaper.DoesNotExist:
        try:
            obj=Ringtone.objects.get(contenido_id=p.id)
        except Ringtone.DoesNotExist:
            raise Http404
    fname = str(obj.archivo)

    # use with statement
    with open(fname,'rb') as fn:
        response = HttpResponse(fn.read())

Uhh.. Is it still complicated? If you can retrieve content type (ringtone or wallpaper) and save it in Dynpath field, solution will be easier.

P.S. Please write your code in English not Spanish )


Generic cached value class mimicking Lazy

First off, never lock on this. You never know who else is locking on that instance. Conversely, clients don't know that the cache is locking on itself either. For example, this seemingly innocent code would lead to a deadlock:

//Thread A
lock(cache)
lock(someObject)
{
    //do something
}

//Thread B
lock(someObject)
{
    //here, the cache will lock on itself.
    //the locks are accidentally taken in reverse order -> deadlock!
    var x = cache.Value;
}

That's why it's good practice to lock on a private readonly object.
Moving on...

Your current implementation allows the value to be refreshed twice in a row. This is a problem if the resource is expensive to create (and resources worth caching usually are).

Two threads might check whether DateTime.Now >= _expiration, then both go into the RefreshValue method and execute the critical region in quick sucession. To solve this you can either:

move the lock up to the place where the expiration date is being checked.
move the expiration check inside the RefreshValue method.

I would go with option 2, and add a double-checked lock to avoid hitting the lock every single time:

private readonly object _refreshLock = new object();

private void RefreshValueIfNeeded()
{
    if (DateTime.Now >= _expiration)
    {
        lock (_refreshLock)
        {
            if (DateTime.Now >= _expiration)
            {
                _value = new Lazy<T>(_valueFactory);
                _expiration = DateTime.Now.Add(_duration);
            }
        }
    }
}

public T Value
{
    get
    {
        RefreshValueIfNeeded();
        return _value.Value;
    }
}

One more thing: you don't need to wrap the value factory into another delegate, you can just pass it directly to Lazy<T>'s constructor:

//change this
new Lazy<T>(() => _valueFactory())
//to
new Lazy<T>(_valueFactory)


Fast API path parameters from Enum Class

The fact is that you need the LHS and RHS somewhere in your code, in some form. It can be a list, or dict, or in some other forms.
For example:
from enum import Enum
from fastapi import FastAPI

app = FastAPI()
some_dict = dict(
    path1="AcceptedEventRelation",
    path2="Account",
    path3="AccountChangeEvent",
    path4="AccountCleanInfo",
    path5="AccountContactRole"
)

Subjects = Enum('Subjects', some_dict)

@app.get("/subjects/{sobjectname}")
async def process_subjects(sobjectname: Subjects):
    endpoint_subjects = "/services/data/v49.0/sobjects"
    url_to_request = endpoint_subjects + "/" + sobjectname.value
    return {
        "subject": sobjectname,
        "url_to_request": url_to_request
    }

Here, the some_dict is the variable you need to generate, which also looks ugly if there is a 100 items in it as the way you feel for the Enum class.


Minimize boilerplate code in Action class

Aspect-Oriented programming would seem to be the way to go here. Since you're using Struts2, use Interceptors to wrap around the relevant actions. Inside the interceptors, do your check and redirect. You want two, one for the affirmative, and  one for the negative.