Modified TextBox for forms generating SQL statements

There's not much to review here really. I'd be more interested in reviewing the code that's actually doing the work, but here goes.

Lose the Systems Hungarian notation. The IDE/Code tells me what the data type is. That is if you...
Declare the data types of the properties
Use auto properties. There's way too much code here for how simple this is.

Public Class ModifiedTextBox
    Inherits System.Windows.Forms.TextBox

    Property ID() As Integer
    Property TextModified() As Boolean
    Property SqlText() As String

    Property DefaultText() As String
        Set(strDefaultText)
            _strDefaultText = strDefaultText
            Me.Text = _strDefaultText
        End Set
        Get
            Return _strDefaultText
        End Get
    End Property

End Class


Programmatic text substitution across rows and columns in R

You could first create a mapping using a named vector:

map <- c("apple" = 1, "banana" = 1, "gum" = 2, "steak" = 2)

Then create a vector of all the variable names that need to be modified:

vars <- c(paste0("food_day_", 1:7),
          paste0("otherfood_day_", 1:10))

Then modify the data as follows:

example[vars] <- map[unlist(example[vars])]

(where unlist transforms the data.frame example[vars] into a single long vector.)

An interesting aspect of that approach, apart from its conciseness, is that it guarantees than the output columns become numeric. Whereas your approach, by making incremental changes to the columns, would preserve the original class of your columns, i.e. "character". Also note that foods that are not included in the map vector will be turned to NA since for example map["pineapple"] is NA.


1) You don't need to pass minlength and maxlength in your bruteforce function since you making it available at module level.

2) Also there are unwanted new-lines.

3) Also dict formatting can be improved a lot, this will help in readability of your code. Try using any online dict-formatter.

4) You can use datetime.now().time() instead of using a separate library time.

5) If possible avoid using too many print statements or atleast do that with proper messaging rather than any random string like ~~~~~~ you are using.


As you are correctly assuming there are multiple threading related issues with your code, but lets tease you and start with the usual suspects.

Naming

The name apply_prime is misleading and inexpressive.
Neither does the function really require a prime nor does apply do it justice.
You should name it something along the lines: strike_out_multiples or something similar.

Efficiency

Your loop can be twice as fast by doing steps of two instead of one.

And now for the main act:

Thread safety

I am no expert here but I can spot at least two problems:

Ordering:

Nothing prevents the system from "favoring" your main thread and letting all others run after the main thread is hitting the join loop. This results in wrong results as the mainthread plowed through the completely true vector before anyone could tell it that for example 4 is not prime.

Parallel writes:

This might be a bit of a corner case and not a problem anymore but at least in the old standard std::vector<bool> was a specialization that used only one bit per value. While this saves you some space it comes with the cost of actually accessing 8 bits when only working on one. This means that two threads might well be working on different bits but in the same byte. Consider this:

Thread 1 writes false to bit 4 while thread 2 writes false to bit 6. Both are located in byte 0. Now both start out with reading the initial value of the byte, say (true, true, true, false, true, true, true, true) and stores them! Now one of the two threads will write its value later than the other and overwrites the false of the other one -> lost update.

Maybe this can even happen with byte sized booleans as some architectures do not allow for only byte-wise access but only word wise (which results in the same problem, only with wider sizes).


Representing vehicles and their components

The architecture seems fine to me the way it is. It's nice that you have used a little bit of componentization instead of doing some absurd inheritance chain in Car. Maybe someone else will have more comments on the design, but if you are not having problems with it, my opinion is to leave it as it stands.

A few other details I would like to comment on:

There doesn't seem to be any method that changes a Vehicle after an instance is constructed. This is a good design. You should favor immutability whenever practical. Since this is the case, you should further enforce that the vehicles are not mutated by making its member variables const. Then you only allow setting them once in the constructor. E.g.:

const int m_id;
const int m_year;
const int m_mileage;
const int m_weight;
const int m_length;
const int m_width;
const int m_height;
const int m_wheelbase;
...

You probably won't be able to make the QLists const though. But that's not a big deal. Mark with const what you can.
Vehicle's constructor has a lot of parameters. It might be confusing to call it, since many parameters have the same type. One way to consolidate the large number of parameters would be having a sort of VehicleDesc helper structure grouping all the parameters. But that might or might not be a better solution, it depends. It also doesn't simplify setting up a Vehicle. Another possibility might be constructing from a stream or file (AKA serialize/de-serialize).
When you already delete the copy constructor and assignment operator you don't have to also delete the move ones. Remember that move operator and constructor are not added by default to all classes by the compiler, unlike the copy/assign ones. Quoting this very good StackOverflow answer:

  Even if you want your class to not be copyable nor movable, it is
  better to just delete the copy members and leave the move members
  undeclared (meaning they won't exist). If you're ever reviewing code
  (including your own), and see deleted move members, they are almost
  certainly incorrect, or at the very best superfluous and confusing.

You don't need to add the inline keyword when declaring a member method directly inside the class body in the header file. Such methods are already implicitly (to the compiler) and clearly (to the reader) inline.
Seconding for a comment in your post, don't write self evident comments like //ctor or //copy/move. That's just visual pollution, plus, if you shuffle class sections around and forget to move the comments with it, it will create discrepancies.
About your question of Car's constructor replicating the parameters of Vehicle, if you have access to C++11, the you'll probably want to use constructor inheritance. Otherwise, I'm afraid you will have to replicate the constructor's parameter list and just forward the data to Vehicle.
Finally, the ownership of pointers in your code worries me a little. Car has raw pointers to its components, which I assume are also replicated in the components list of Vehicle. There is a certain potencial for memory bugs there. You are probably very familiar with the code and knows exactly when things get allocated and deleted, but don't expect the next guy you pass this project on to be that familiar with it (or even yourself might forget about it in a few months time!). People maintaining your code are much more likely to introduce bugs than you are. For this reason, mainly, I would advocate for the use of smart pointers. Car should probably hold shared_ptrs to its components, so that Vehicle can store weak_ptrs in its component list.


That's a fine small piece of software for a beginner. Here is my review:

const-modifier
Since you don't modify the contents of the char *s you can safely change your function signature to void invert(const char *s).

Too many strlen() calls
You execute strlen(s) every for-loop iteration. This is quite bad for the performance (especially for large strings) since strlen loops through your whole string each call. If your string is 100 characters long (beside the NULL-character) this ends up in 100*100 = 10000 iterations.
As a quick solution you could just create a variable length and store the length of your string once. From that point on you'll compare with length instead of strlen(x) and will get the same result (since, s doesn't change while execution).

Comparison unused
n < strlen(s) remains unused in your first for-loop. I think you want to connect the two comparisons with &&:

for (i = strlen(s) - 1, n = 0; n < strlen(s) && i >= 0; i--, n++)

Why even reverse?
Since your function prints the reversed string, but doesn't return anything. You don't really need to reverse it. You could just loop through the input string starting at the end (like you did in your first loop), printing all the characters. The extra array only makes sense, if you return a pointer to it for later use.


Get first DateTime by given weekdays and a starttime

After some fresh air I think I got around my mental blockade. I simply convert to the natural C# DayOfWeek representation beforehand instead of fiddling around with the other one.

public static IEnumerable<DayOfWeek> ConvertDaysOfWeek( int[] daysOfWeekIds )
    => daysOfWeekIds.Select( x => x == 7 ? DayOfWeek.Sunday : (DayOfWeek)x );

public static DateTime GetNext( IEnumerable<DayOfWeek> daysOfWeek , TimeSpan startTime )
{
    var nextDate = DateTime.Now.Date;
    var isToday = daysOfWeek.Contains( nextDate.DayOfWeek ) && DateTime.Now.TimeOfDay < startTime;

    if( !isToday )
        nextDate = Enumerable.Range( 1 , 7 )
            .Select( x => nextDate.AddDays( x ) )
            .First( x => daysOfWeek.Contains( x.DayOfWeek ) );

    return nextDate.Add( startTime );
}


Quickly check whether file name is in column in an SQL Table and move to new folder

Output from invoke-sqlcmd is Formatted table i.e. something like PSCustomObject[] array (or collection). Hence, one could address its columns as .FILE_NAME properties and apply comparison operators -in, -contains, -match etc. (elaborated from my original comment):

param(
    [string] $src,
    [string] $dest,
    [string] $table
    )

$sql_instance_name = 'db'
$db_name = 'DB2'
$sql_user = 'user'
$sql_user_pswd = 'password'

$query = "select * from $table"
$expcsvS = invoke-sqlcmd -Username $sql_user -PASSWORD $sql_user_pswd `
    -Database $db_name -Query $query -serverinstance $sql_instance_name

Get-ChildItem -Path $src -Recurse -File | ForEach-Object  {

    if ( $_.Name -in  $expcsvS.FILE_NAME )
    {
        $nextName = Join-Path -Path $dest -ChildPath $_.Name
        Write-Output $nextName
        $_ | Move-Item -Destination $nextName
    }
}

Note that I use $_.Name instead of ($_.BaseName + $_.Extension) as for files, the following code snippet always returns True.

(Get-ChildItem -Recurse -File |
    Where-Object { $_.Name -ne ($_.BaseName + $_.Extension) }) -eq $null

Also note that if ( $_.Name -in $expcsvS.FILE_NAME ) {} is equivalent to any of (incomplete list):

if ( $expcsvS.FILE_NAME -match "^$($_.Name)$") {}
if ( $expcsvS.FILE_NAME -contains $_.Name ) {}


SQL to match string value against multiple columns

The queries are the same except potentially the second won't use index if any exists on grade_* columns. And this flipped approach Is rather uncommon (at least i see it for first time). Possibly because you wouldnt need such approach if you had a better tables structure.

What if suddently students can study history or biology? You Will need to create new columns And Alter all related queries.

Instead there should be a "subjects" table and an M:N relation table between subjects and students. Your query wont contain any ORs or INs the way it does now. And adding new subjects Is matter of  merely inserting new row to subjects table.


Implementing HTTP data range representation class

Starting from bottom. If you have too many ifs and you want to get rid of them then you should start to name things (as you already did for HasUnspecifiedBytePos()).

This expression dataRange.FirstBytePos() == DataRange::UnspecifiedBytePos is saying IsFirstBytePosSpecified (or HasFirstBytePos). Just add two simple functions to your DateRange class:

bool HasFirstBytePos() const {
    return FirstBytePos() == UnspecifiedBytePos;
}

Now you can rewrite your first if like this:

if (!dataRange.HasFirstBytePos() && dataRange.HasLastBytePos()) {
    uint64_t rangeUpperBorder = std::min(dataSize, dataRange.LastBytePos());
    specifiedFirstBytePos = dataSize - rangeUpperBorder;
}

It's still there but it's shorter and easier to understand at first sight. The same should be applied to all the other checks. Let's do a further step in this direction and refactor out code to calculate specifiedFirstBytePos into its own method (this may stay here or in DataRange class, I don't see how and where you use it).

uint64_t ResolveFirstBytePos(const DataRange& dataRange, uint64_t dataSize) const {
    if (dataRange.HasFirstBytePos())
        return dataRange.FirstBytePos();

    if (dataRange.HasLastBytePos()) {
        uint64_t rangeUpperBorder = std::min(dataSize, dataRange.LastBytePos());
        return dataSize - rangeUpperBorder;
    }

    return 0;
}

Everything together:

DataRange SpecifyDataRangeBytePos(const DataRange& dataRange, uint64_t dataSize) {
    DataRange result(
        ResolveFirstBytePos(dataRange, dataSize),
        ResolveLastBytePos(dataRange, dataSize));

    assert(!result.HasUnspecifiedBytePos());

    return result;
}

Note that you may move assertion inside your constructor (I don't know if it's a valid condition then here I kept original code).

When you will read this code in future you won't need to deeply understand how it is doing things but in few lines you will understand what it is doing.

More things:

explicit on a constructor with two parameters is useless (no default value for lastBytePos), you may simply drop it.
I'd pick better names for FirstBytePos and LastBytePos. Without reading all your (unavailable) code I may just guess it's position (in bytes) within input data. If type is obvious (bytes) then you may simply use BeginInData and EndInData but I'd need more context to suggest anything meaningful. (BytePos comes from domain - its named like this directly in RFC - then it's a good name to use)
IMO HasUnspecifiedBytePos() expresses more an implementation detail (position, in bytes, is unspecified) than a behavior/state/property of your object. It should be renamed to something from domain, for example IsNull().
Your constructor has dataSize parameter but you pass LastBytePos() value. dataSize seems to indicate this parameter is an offset from firstBytePos. If it's not an offset then you should rename it, if it is then code is broken (when firstBytePos > 0)


Your algorithm looks fine, and efficient. Strictly speaking, since the stations are sorted, you could use binary search to find the next station to refill, by looking for the insertion point of lastRefill + 400. This could speed things up if gas stations are extremely dense. But that's unrealistic anyway, so I think no need to bother, your simple implementation is fine.

The implementation is a bit hard to read because of the names. I recommend these renames:

numbers -> stations
refillAt -> capacity
numOfRefills -> refills

The writing style is also too compact and hard to read.
It's recommended to put spaces around operators.

Lastly, the endpoint variable is redundant, stations.length is just as easy to understand.

With the renames and the formatting changed, the method becomes:

static int getMinRefill(int[] stations, int capacity) {
    int lastRefill = 0;
    int current = 0;
    int refills = 0;

    while (current < stations.length - 1) {

        if (stations[current + 1] - stations[current] > capacity) {
            return 0;
        }

        if (lastRefill + capacity < stations[current + 1]) {
            lastRefill = stations[current];
            refills++;
        }

        current++;
    }

    return refills;
}


Clearly, I need more experience with numeric programming, because I spent two days wrestling with overflow issues and floating point error

I'd suggest to just avoid it all. Use mod \$2^{32}\$ arithmetic, ignore overflow, forget floating point and forget BigInteger.

I'm afraid, the problem is not the code, but the algorithm. I can see that the Wikipedia really describes all the strange things concerning modular arithmetic, but I'm pretty sure that you took it too literally.

For a rolling hash, all you need is something like

h = BASE_MULTIPLIER * h + inChar + OUT_MULTIPLIER * outChar;

where inChar is the incoming character, BASE_MULTIPLIER is any number co-prime to \$2^{32}\$ (i.e., odd) and OUT_MULTIPLIER is its \$n\$-th power mod \$2^{32}\$, where \$n\$ is the length of the sliding window.

If you insist on using a prime instead of \$2^{32}\$, then you can do it all without BigInteger as long as the prime fits in an int (use long and compute modulus after each operation).

If you're still unsatisfied with the hash function, then there are simple ways to improve it (just ask).

throw new IllegalArgumentException("Pattern longer than text.");

What's illegal here? It's just not there, cf. "x".contains("abc").

throw new IllegalArgumentException("b cannot be larger than " + q);

It can... IIUIC, it's just hashing, so there's no reason to whine because of collisions as long as they're rare.

  How can I make the code more robust?

Don't require to specify the alphabet and similar things. It's not necessary.

  Did I miss any glaring performance traps?

Both % and BigInteger are performance killers.

  Because of the way I implemented the algorithm, supporting general Unicode strings in UCS-2 or UTF-16 would require doing base-65,536 arithmetic.

If you implemented it my way, there'd be no problem.

  There's no hard limit on the size, but larger alphabets mean more BigInteger math.

Do no BigInteger at all.

  Although the current code is Java 7, I plan to switch to Java 8 in the near future

Just don't. If you see something where Java 8 could obviously help a lot, go for it. Otherwise, I wouldn't care. I'm not saying that Java 8 is no big improvement, it's just that sticking with Java 7 or 6 makes your program more usable.


Basic T-SQL to compare two same length strings

Firstly, a stylistic point. SQL is typically written with keywords capitalised, SELECT instead of select for example.

Your table and variable names could use a little more meaning. Using @Countries or @CountryNames in place of the meaningless @t, for example.

You use NVARCHAR to hold your data, but immediately convert it to VARCHAR. I would recommend just using VARCHAR in your query, this allows you to remove the cast to VARCHAR's.

Lastly, the logic you use to set the score is a little convoluted, as you thought it might be. I would recommend using:

SET score = CAST(CAST(@SelectedCountry AS VARBINARY(MAX)) AS INT) - CAST(CAST(solution AS VARBINARY(MAX)) AS INT)

These changes would result in this:

DECLARE @CoutryNames TABLE (solution VARCHAR(32), score BIGINT)

INSERT INTO @CoutryNames(solution)
SELECT 'Portugal'
UNION SELECT '9ortugal'
UNION SELECT '9ortu8al'
UNION SELECT 'Portu8al'
UNION SELECT 'P0rtugal'
UNION SELECT '90rtugal'
UNION SELECT '90rtu8al'
UNION SELECT 'P0rtu8al'
UNION SELECT 'Portuga1'
UNION SELECT '9ortuga1'
UNION SELECT '9ortu8a1'
UNION SELECT 'Portu8a1'
UNION SELECT 'P0rtuga1'
UNION SELECT '90rtuga1'
UNION SELECT '90rtu8a1'
UNION SELECT 'P0rtu8a1'

DECLARE @SelectedCountry VARCHAR(32) = 'Portugal'

UPDATE @CoutryNames
SET score =
CAST(CAST(@SelectedCountry AS VARBINARY(MAX)) AS BIGINT)
- CAST(CAST(solution AS VARBINARY(MAX)) AS BIGINT)

SELECT * FROM @CoutryNames ORDER BY score --first result is the most similar

Here is the SQL Fiddle

The idea to use weighted errors got me thinking about how I would do it.

Here is what I came up with, you could pretty easily turn it into a function by adding the required boilerplate code and changing the SELECT @ErrorScore to RETURN @ErrorScore:

DECLARE @StringA VARCHAR(10) = 'bacon',
        @StringB VARCHAR(10) = 'bacon',
        @CharPosition TINYINT = 1,
        @ErrorScore INT = 0

DECLARE @LETTER_WEIGHTING TABLE(CorrectLetter CHAR(1), IncorrectLetter CHAR(1),LetterWeighting TINYINT)

INSERT INTO @LETTER_WEIGHTING
SELECT 'o','0',1 UNION ALL
SELECT 'o','Q',3 UNION ALL
SELECT 'g','6',2 UNION ALL
SELECT 'g','8',3

IF @StringA <> @StringB
BEGIN
    WHILE @CharPosition <= LEN(@StringA)
    BEGIN
        SELECT
        @ErrorScore +=
        CASE WHEN SUBSTRING(@StringA,@CharPosition,1) <> SUBSTRING(@StringB,@CharPosition,1)
        THEN
        ISNULL((
            SELECT TOP 1 LetterWeighting
            FROM @LETTER_WEIGHTING
            WHERE CorrectLetter = SUBSTRING(@StringA,@CharPosition,1)
            AND IncorrectLetter = SUBSTRING(@StringB,@CharPosition,1)
        ),5)
        *
        @CharPosition
        ELSE 0
        END

        SET @CharPosition+=1
    END
END

SELECT @ErrorScore

What this does is loop through all the characters of the first string and compare them with the appropriate character in the second string. If the characters do not match, then we use a lookup table of weightings for some errors or we use 5 as a base value if the correct/incorrect character pair is not in the lookup table. We then multiply the value in the previous step by the characters position in the string.

Here is an SQL Fiddle


Mongoose schema to store items from Wynncraft's API

As I see there is about 60 properties for each item in Wynncraft DB. I see two ways to improve your design:

Distribute all properties across multiple schemas: basic item information (name, category, etc), defense information, bonus damage information and other. In this case those schemas will be related to each other. Maybe you don't even need to store all item's data (depends on goal of your application).
If you want to identically map properties of item to your storage, then I guess you can get list of all properties as JSON (by using Wynncraft's public API) and convert it to schema definition. JSON with list of properties could be cached for better performance.


Split the code

This long method does a lot of things:

it reads the file
preprocesses it
searches for the bounding box of the area of interest
crops the result
writes the result to a file

Better would be to split this into more parts. This way, you don't need to comment as much, but let the function names speak for themselves.

Comments

If you do feel the need to comment, you can do that in the docstring. If you want to comment on the code, explain why you do it, not how.

#Ignore the limits/extremities of the document (sometimes are black, so they distract the algorithm)

is a useful comment.

# Apply adaptive mean thresholding

is not. It doesn't explain what problem this adaptive thresholding solves, and how you got to the parameters you use: 255, ADAPTIVE_THRESH_MEAN_C, 35 and 15

Indexing

negative indices start counting from the back of a sequence, so

(height, width) = img.shape[0:2]
image = erosion[50:height - 50, 50: width - 50]

can be replaced by erosion[50:-50, 50:-50]

There is also no need to put the parentheses around the height, width tuple.

Magic numbers

There are a lot of magic number in your code: 15 and 35 in the adaptive threshold, 15 in the kerneling, 50 in the cropping,...

Better would be to give them names, and define them in the function or use them as parameters to pass into the function.

Keyword arguments

amtImage = cv2.adaptiveThreshold(bit, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 35, 15)

would be a lot clearer as:

blocksize = 35
constant = 15
max_value = 255 # 8 bits
amtImage = cv2.adaptiveThreshold(
    src=bit,
    maxValue=max_value ,
    adaptiveMethod=cv2.ADAPTIVE_THRESH_MEAN_C,
    thresholdType=cv2.THRESH_BINARY,
    blockSize=blocksize ,
    C=constant,
)

Vectorizing

opencv uses numpy arrays internally, so you can use all the vectorisation goodies, instead of iterating over each pixel twice in python land.

bw_threshold = 150
limits = 0.2, 0.15

mask = image < bw_threshold
edges = []
for axis in (0, 1):
    count = mask.sum(axis=axis)
    limit = limits[axis] * image.shape[axis]
    index = np.where(count > limit)
    _min, _max = index[0][0], index[0][-1]
    edges.append((_min, _max))

does the same, but vectorized and about 1000 times faster.

Final result

def preproces_image(
    image,
    *,
    kernel_size=15,
    crop_side=50,
    blocksize=35,
    constant=15,
    max_value=255,
):
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    bit = cv2.bitwise_not(gray)
    image_adapted = cv2.adaptiveThreshold(
        src=bit,
        maxValue=max_value,
        adaptiveMethod=cv2.ADAPTIVE_THRESH_MEAN_C,
        thresholdType=cv2.THRESH_BINARY,
        blockSize=blocksize,
        C=constant,
    )
    kernel = np.ones((kernel_size, kernel_size), np.uint8)
    erosion = cv2.erode(image_adapted, kernel, iterations=2)
    return erosion[crop_side:-crop_side, crop_side:-crop_side]

def find_edges(image_preprocessed, *, bw_threshold=150, limits=(0.2, 0.15)):
    mask = image_preprocessed < bw_threshold
    edges = []
    for axis in (1, 0):
        count = mask.sum(axis=axis)
        limit = limits[axis] * image_preprocessed.shape[axis]
        index_ = np.where(count >= limit)
        _min, _max = index_[0][0], index_[0][-1]
        edges.append((_min, _max))
    return edges

def adapt_edges(edges, *, height, width):
    (x_min, x_max), (y_min, y_max) = edges
    x_min2 = x_min
    x_max2 = x_max + min(250, (height - x_max) * 10 // 11)
    # could do with less magic numbers
    y_min2 = max(0, y_min)
    y_max2 = y_max + min(250, (width - y_max) * 10 // 11)
    return (x_min2, x_max2), (y_min2, y_max2)

if __name__ == "__main__":

    filename_in = "NHnV7.png"
    filename_out = "res_NHnV7.png"

    image = cv2.imread(str(filename_in))
    height, width = image.shape[0:2]
    image_preprocessed = preproces_image(image)
    edges = find_edges(image_preprocessed)
    (x_min, x_max), (y_min, y_max) = adapt_edges(
        edges, height=height, width=width
    )
    image_cropped = image[x_min:x_max, y_min:y_max]
    cv2.imwrite(str(filename_out), image_cropped)


Yes, force unwrapping is ok if you're 100% sure the value won't be nil, but this should only be used when, for code structure reasons, you can't do otherwise. The thing is, most of the times, you can do otherwise, so using force-unwrapping should rarely happen. In your case, I think most of it can be refactored.
For example: why are your variables x and y declared as Optionals in the first place? Do they have to be?
If they are only used in this method, they should not be declared as Optional, and they should be declared inside the method, not outside.
If they are used elsewhere, they should be declared as Optional only if you know they will be nil at some point (which means that they should not be force unwrapped when used, but instead properly validated with error handling).
If they are used elsewhere and won't be nil when used, but you declared them as Optional for structural reasons, then you could use an implicitly unwrapped Optional instead.
private var x: Int!
private var y: Int!

This way you won't have to force unwrap them each time you use them.
Also, if this is acceptable in your context, you could make them non-optional and have an initial value.
private var x: Int = 0
private var y: Int = 0

But let's say that you have a good reason to declare them as Optionals. In this case, you still can improve your code by safely unwrapping the variables before using them.
guard let x = Int(ceil(sqrt(Double(rooms!)))) else {
    // show some message
    return
}

That way, if the user types a letter, space or non-numeric character, instead of a number, the app won't crash.
Maybe you're making sure elsewhere that the user can only input a number? In this case, force unwrap x before using it:
x = Int(ceil(sqrt(Double(rooms!))))!

Now, actually, the issue might only happen if numberOfRooms is not a number, so this unwrapping should happen earlier.
guard let numberOfRooms = selectedRooms.text, !numberOfRooms.isEmpty, let rooms = Int(numberOfRooms) else {
    // error message 'please input a number'
    return
}

Same idea about currentX and currentY: why are these declared as Optionals? Can the getRandom method return nil? Maybe that can be changed?
Same for maze: if MazeGenerator can return nil, the shouldn't you handle possible errors instead of force unwrapping? And if it won't ever return nil, then why does it return an Optional instead of a normal value? (or maybe it doesn't return an Optional and the issue is that maze was declared as an Optional but shouldn't have been).

These are the issues you should address.
While force unwrapping is indeed not bad if you can guarantee the value won't be nil when you use it, most of the times it's better to make sure earlier in the code flow that the value won't be nil, which will allow you to not having to use Optionals.
In short: validate the values before use, abort and show an error message if the content is incorrect at the validation step, and then proceed to use the values without having to use Optionals and unwrapping.


Algorithm to compute the n-th derivative of a polynomial in Python

You are going one by one derivative, when you could easily do them all at once. With a little multiply-and-divide trick, you could save on complexity.

Also, your function will return wrong results for negative dev (it should raise an exception instead).

Further, your function will mess up the original list:

>>> poly = [3, 5, 2, 2]
>>> print(poly_dev(poly, 2))
[18, 10]
>>> print(poly)
[18, 10, 2, 2]

Here is my take on it:

def poly_dev(poly, dev):
    if dev == 0:
        return poly[:]
    if dev > len(poly):
        return list()
    if dev < 0:
        raise ValueError("negative derivative")
    p = 1
    for k in range(2, dev+1):
        p *= k
    poly = poly[:-dev]
    n = len(poly)-1
    for i in range(len(poly)):
        poly[n-i] *= p
        p = p * (i+dev+1) // (i+1)
    return poly

So, the first thing I do after handling trivial cases is computing the multiplication factor for the first coefficient and take only a copy of the part of the list that I need (to avoid messing up the original).

Then I multiply each coefficient with the multiplication factor p, followed by computing the next one, meaning "divide by the smallest member of the product that defines p and multiply by the one bigger then the biggest one".

Notice that the division is //, which is integer division. That way you don't lose precision (and I think it's a bit quicker than the floating point one, but I'm not sure right now).

It may look redundant to multiply and later divide by the same number, but it's less work than multiplying dev numbers in each go.

Also, it would be more Pythonic to have enumerate(reversed(poly)) instead of range(len(poly)) in the for loop, but then we'd still need n-i somewhere, so this seemed cleaner to me for this particular case. Maybe I'm missing something obvious here.


Requesting product data from an eBay webform

Since you are sub-classing ActiveModel::Model you can use
you can use its ability to "magically" map an input hash to attributes:

def initialize(form={})
    super # magic!
    @product = set_product if @product_id
end

This works since you have created accessors for the properties :title, :price, :subtitle, :product_id, :duration.

Also as @nicolas-mccurdy mentioned you can replace each the enumerable methods
 map, select and reject. The rule of thumb being that you should only use each when you are solely concerned with
 the side-effects of a loop.

def item_specifics
    @product.properties.reject { |k,v| v == "0" }.map do |k,v|
        value = "#{v}#{PROPERTY_FORMATTER[k.to_sym]}"
        value = "included" if value == "1"
        Ebay::Types::NameValueList.new(name: k.to_s.for_humans, value: value)
    end
end

def remote_images
    # Side note - where does the variable `url` come from? Document it!
    @product.images.map do |i|
        url = "http://www.howmuchcomputer.com" + i
        remote_url = @api.upload_site_hosted_pictures({:external_picture_url => url})
        remote_images << remote_url.extract(ignore_errors: true)
    end.reverse
end

Also note the use of chaining - extremely common in Ruby - instead of creating intermediate variables or mutating.

The template method looks like it may be violation of MVC - models should not know about template or any kind of
visual representation. Presenting data to users and dealing with user input is the concern of your controllers.

# @todo refactor into controller! Violation of concerns!
def template(path)
    ERB.new(File.open(path, "r").read).result(binding).to_s
end

Also you should consider the visibility of your methods, all methods which you do not consider part of the "public API"
of a class should be private. These look like prime canidates:

def set_product
    @product = Product.find(@product_id)
end

def api
    @api ||= Ebay::Api.new
end

Addition

In general I would question the whole purpose of the class - "form classes" or form builders are pretty common in other frameworks such as Symfony2.
IMHO they are dinosaur concepts from the days of ASP.net, that get filled with gluecode and cruft.

Just stick with good old MVC:

Views create forms and can be DRY-ed with partials and helpers. (or the awesome gem SimpleForm
Controllers deal with the user input and pass DATA to model.
Models deal with getting/persisting data from databases or external sources. They also handle validation. DRY them out with concerns.

If you want to refactor I would consider moving the relevant functionality into Listing - for example the post method.

item_specifics and remote_images is also an example of something that should probably belong to Product.


def elementtree_to_dict(element):
    d = dict()

I'd avoid the name d its not very helpful

    if hasattr(element, 'text') and  element.text is not None:
        d['text'] = element.text

getattr has a third parameter, default. That should allow you to simplify this piece of code a bit

    d.update(element.items()) # element's attributes

    for c in list(element): # element's children

The list does nothing, except waste memory.

        if c.tag not in d:
            d[c.tag] = elementtree_to_dict(c)
        # an element with the same tag was already in the dict
        else:
            # if it's not a list already, convert it to a list and append
            if not isinstance(d[c.tag], list):
                d[c.tag] = [d[c.tag], elementtree_to_dict(c)]
           # append to the list
            else:
                d[c.tag].append(elementtree_to_dict(c))

Yeah this whole block is a mess. Two notes:

Put everything in lists to begin with, and then take them out at the end
call elementtree_to_dict once

return d

This whole piece of code looks like a bad idea.

<foo>
   <bar id="42"/>
</foo>

Becomes

{"bar" : {"id": 42}}

Whereas

<foo>
    <bar id="42"/>
    <bar id="36"/>
</foo>

Becomes

{"bar" : [{"id" : 42}, {"id": 36}]}

The XML schema is the same, but the python "schema" will be different. It'll be annoying writing code that correctly handles both of these cases.

Having said that, here's my cleanup of your code:

def elementtree_to_dict(element):
    node = dict()

    text = getattr(element, 'text', None)
    if text is not None:
        node['text'] = text

    node.update(element.items()) # element's attributes

    child_nodes = {}
    for child in element: # element's children
        child_nodes.setdefault(child, []).append( elementtree_to_dict(child) )

    # convert all single-element lists into non-lists
    for key, value in child_nodes.items():
        if len(value) == 1:
             child_nodes[key] = value[0]

    node.update(child_nodes.items())

    return node


Possible memory leak in a for loop macro

I wish you would have posted more of your code here. I suspect that the code you posted should be broken out into it's own subroutine and we could have made sure you're using appropriate variable declarations. That being said, I'm only going to address your vlookup method, as you only need one or the other and I don't believe the find method is a good idea.

Per my comment, this code becomes slower because each time you add a formula via Data.Cells(DataRow, 4) = Format((Data.Cells(DataRow, 2) - Result) / Result, "0.00%"), Excel will recalculate all of the formulas in the spreadsheet. Prior to executing this code, you should set calculation to manual with Application.Calculation = xlCalculationManual.

If you don't have an error handler, you will need to add one so you can ensure that calculation is always set back to automatic with Application.Calculation = xlCalculationAutomatic. If you set it to manual, and then an error happens (without a handler), your workbook could cause you some confusion because it's not updating values when you think it should. You would also want to make sure to execute Application.StatusBar = False should any error happen. You don't want the status bar to get "stuck" if an error happens.

Some other things:

I'm not a fan of the PascalCase variable names. They should be camelCase to avoid confusion with class properties.
You don't need = True in IsError(Result) = True. It can simply be If IsError(result) Then.
That same If statement contains some duplication. It can be simplified as below.

If (IsError(result)) Or (result = 0) Then
    Data.Cells(dataRow, 3) = "No Old Cost"
Else
    Data.Cells(dataRow, 3) = Result
    Data.Cells(dataRow, 4) = Format((Data.Cells(dataRow, 2) - Result) / Result, "0.00%")
End If

dataRow = dataRow + 1

Note that I also moved the variable incrementor outside of the If block. This also fixes what I believe is a bug that was causing you to skip rows. If you meant to skip rows, increment by two instead.
You're releasing the CPU to the OS at an inopportune time. Typically, DoEvents should come directly after you update the status bar. If you're concerned about saying it's at 100% while the code is still working, move the update to the end of the loop instead.
Unless you really feel like that status bar is needed, you should remove it. It's a performance hit as well. It sounds like you do need it though. Processing 70k rows takes some time and you don't want your users to think the program isn't responding.

The good stuff:

Thank you for ignoring Microsoft's recommendation to use hungarian notation!
Your variable names are clear and concise. No confusion about what is what. Well done.


Find valid triples for a sorted list of integers (part 2)

(I won't comment on the actual algorithm, just on the coding style.)

Overall, this feels pretty ok and standard Python style.

Some remarks:

remove commented-out code before going "live" (live here meaning, submitting to CR).
make sure your lines don't exceed 80 characters.
That will have the added convenience that there'll likely be no horizontal scrollbar for the code block here, making things overall easier to read.
I like the from __future__ import division, especially since the only division in the code is actually integer divison, and now is explicit with //.
Bonus: add from __future__ import print_function, add parentheses to yourprint` statement at the bottom and your code will be "generic" Python, not major version 2 or 3 specific.
(My preferred approach is to code Python 3, and then if necessary, refactor things to be Python 2 compatible. Start from the future, not from the past.)
the lower-first-CamelCase style is not Pythonic. CamelCase is used for classes, but functions and variable names are usually all lower case, with underscores as deemed necessary for readability.
(NB: you probably want to use the word "triangles", with an "n" in there, instead of "triagles". Or use e.g. find_triplets, since that's in your doc-string description.)
the quadruple nesting in findTriagles is about the limit of nesting (for-loop within an if-statement within a for-loop within a for-loop), but since the function is really short, it's probably ok. When there's a lot more code in any of these indented parts, consider moving a part to a separate function.
There is no general document doc-string (describing the purpose of the code), and the doc-string for findTriagles is missing its initial line/sentence: it jumps straight into the parameter description. findSum does this better.
findSum is an odd name: I don't see any sum calculation there. find_max_index or similar might be better.
for consistency: add space around the equal sign in upperBoundIndex=min(i+2, len(numbers)-1).


Checking if a sequence is almost strictly increasing

You are repeating a lot of work.

For example, let's take a look at the sequence [1,2,3,4,5].

Your code does the following:
- copy it to a list
- remove "1" and check if {2,3,4,5} is sorted
- remove "2" and check if {1,3,4,5} is sorted
- remove "3" and check if {1,2,4,5} is sorted
- remove "4" and check if {1,2,3,5} is sorted
- remove "5" and check if {1,2,3,4} is sorted

Instead, let's go over the entire sequence once and do something special on the first item that is smaller than the previous one.

At some point into the loop we see the following where sequence[i-1] > sequence[i]

  {done part, a, sequence[i-1], sequence[i], c, remainder}

The whole start of the sequence up to sequence[i-1] is strictly increasing (checked in earlier iterations of the loop). So what do we still need to check here to give a meaningful answer?

Given that sequence[i-1]>sequence[i] either one of those needs to be removed. So we have 2 cases:

remove sequence[i-1] -> check if {a, sequence[i], c, remainder} is strictly increasing
remove sequence[i] -> check if {a, sequence[i-1], c, remainder} is strictly increasing

Note that in both cases we want to check if the remainder is strictly ascending. So the main loop will look something like this:

for(int i = 1; i < sequence.length; i++){
    if (sequence[i - 1] > sequence[i]) {
        // {..., a, sequence[i-1], sequence[i], c, remainder}
        //check if remainder is sorted
        for(int j = i+1; j < sequence.length; j++){
            if (sequence[j - 1] > sequence[j]) {
                return false;
            }
        }
        int a = sequence[i - 2];
        int c = sequence[i + 1];
        //remove i-1
        if (a < sequence[i] && sequence[i] < c) {
            return true;
        }
        //remove i
        if (a < sequence[i - 1] && sequence[i - 1] < c) {
            return true;
        }
        //neither removing i-1 or i fixed the strictly increasing rule
        return false;
    }
}
//entire list is strictly increasing
return true;

There's still some edge cases that will cause trouble. This loop as it is now will throw an ArrayIndexOutOfBoundsException because we're accessing from sequence[i-2] up to sequence[i+1].

Let's handle those cases before the loop to keep things as simple as possible and reduce the bounds for the loop:

//trivial case with up to 2 items
if(sequence.length < 3){
    return true;
}
//edge case first 3 items are descending
if(sequence[0]>sequence[1]
        &&sequence[1]>sequence[2]) {
    return false;
}
//edge case last 3 items are descending
int last = sequence.length-1;
if(sequence[last-2]>sequence[last-1]
        &&sequence[last-1]>sequence[last]) {
    return false;
}
for(int i = 2; i < sequence.length-1; i++){ //skip first 2 and last item
    ...

With this we're no longer checking the same items over and over again and we no longer copy all the items into a list which should give you a major improvement in speed.

DISCLAIMER I have not tested this code. It's possible it contains typo's or other edge cases. Be sure to fully understand it instead of blindly copy-pasting.


You aren't using braces {} for the outer loops body which is bad, bad, bad. You should always use them although they are optional it just will make your code less error prone.

If you decide not to use them, you should stick to your style. Right now you are mixing them.

Using a guard clause is a good idea, but if one needs to scroll to the right to see each condition its suboptimal.

Use some vertical space to group related code together makes your code much more readable and easier to maintain.

By adding a method which returns an IEnumerable<int> containing the start positions of the possible patterns will improve readability like so

private static IEnumerable<int> GetPatternStartings(byte[] body, byte[] pattern, bool[] wild, int start = 0)
{
    for (var index = start; index <= body.Length - pattern.Length; index += 1)
    {
        if (wild[0] || (body[index] == pattern[0]))
        {
            yield return index;
        }
    }
}

The name of the method could/should be adjusted but I couldn't come up with a better one.

If we would now add a method to check if there really is a pattern like so

private static bool IsPattern(byte[] body, byte[] pattern, bool[] wild, int bodyIndex)
{
    for (var index = 1; index <= pattern.Length - 1; index++)
    {
        if (wild[index] || (body[bodyIndex + index] == pattern[index])) continue;

        return false;
    }

    return true;
}

we can then implement the mentioned points and change the former FindPattern() method to

public static int FindPattern(byte[] body, byte[] pattern, bool[] wild, int start = 0)
{
    var foundIndex = -1;

    if (body.Length <= 0
        || pattern.Length <= 0
        || start > body.Length - pattern.Length
        || pattern.Length > body.Length)
    { return foundIndex; }

    foreach (int patternStart in GetPatternStartings(body, pattern, wild, start))
    {
        if (IsPattern(body, pattern, wild, patternStart)) { return patternStart; }
    }

    return foundIndex;

}

So let us take a look at this

private async void GetResponse(NetworkStream stream)
{
  while (true)
  {
    var readBuffer = new byte[4096];
    var asyncReader = await stream.ReadAsync(readBuffer, 0, readBuffer.Length);
    var result = RemoveBytes(readBuffer, new byte[] { 130, 119, 126, 118, 48, 49, 12, 19, 14 });
    List<byte> l = null;
    var w = 1;
    while (w > 0)
    {
      w = FindPattern(result, new byte[] { 1, 0, 131 }, new[] { false, true, false });
      if (w <= 0) continue;
      l = result.ToList();
      l.RemoveAt(w);
      l.RemoveAt(w);
      l.RemoveAt(w);
      Buffer.BlockCopy(l.ToArray(), 0, result, 0, result.Length - 3);
    }
    if (l != null) txtBoxMessagesIn.Text += Encoding.ASCII.GetString(l.ToArray()) + Environment.NewLine;
    if (asyncReader <= 0) break;
  }
}

The call to ToList() and 3 times RemoveAt() together with the Buffer.BlockCopy() will slow down the whole thing.
if (w <= 0) continue; the continue should better be a break. There is no need to evaluate again the while condition. In addition this condition should be (w < 0) if the pattern should be found at the start too.
the pattern and wild to be used in FindPattern() should be created at the start of the method. It won't change.
w is a poorly named variable, let us use patternIndex instead.

Applying this will lead to

private async void GetResponse(NetworkStream stream)
{
    byte[] pattern = new byte[] { 1, 0, 131 };
    bool[] wild = new bool[] { false, true, false };
    int patternLength = pattern.Length;

    while (true)
    {
        var readBuffer = new byte[4096];
        var asyncReader = await stream.ReadAsync(readBuffer, 0, readBuffer.Length);
        var result = RemoveBytes(readBuffer, new byte[] { 130, 119, 126, 118, 48, 49, 12, 19, 14 });

        var patternIndex = 1;
        while (patternIndex > 0)
        {
            patternIndex = FindPattern(result, pattern, wild);
            if (patternIndex < 0) { break; }

            byte[] current = new byte[result.Length - patternLength];
            Buffer.BlockCopy(result, 0, current, 0, patternIndex);
            Buffer.BlockCopy(result, patternIndex + patternLength, current, patternIndex, result.Length - patternIndex - patternLength);
            result = current;
        }

        if (result != null && result.Length > 0)
        {
            txtBoxMessagesIn.Text += Encoding.ASCII.GetString(l.ToArray()) + Environment.NewLine;
        }
        if (asyncReader <= 0) { break; }
    }
}

So now we are finished, aren't we ? NO !

Lets check this RemoveBytes() method, because I see a pattern there.

After renaming the method to RemovePattern we can have 2 overloaded ones like so

private static byte[] RemovePattern(byte[] input, byte[] pattern)
{
    return RemovePattern(input, pattern, new bool[pattern.Length]);
}

private static byte[] RemovePattern(byte[] input, byte[] pattern, bool[] wild)
{
    int patternLength = pattern.Length;
    var patternIndex = -1;

    while ((patternIndex = FindPattern(input, pattern, wild)) >= 0)
    {
        byte[] current = new byte[input.Length - 3];
        Buffer.BlockCopy(input, 0, current, 0, patternIndex);
        Buffer.BlockCopy(input, patternIndex + patternLength, current, patternIndex, input.Length - patternIndex - patternLength);
        input = current;
    }
    return input;
}

You see, I have extracted the removal to a separate method. Now the former GetResponse() method will become this

private async void GetResponse(NetworkStream stream)
{
    byte[] pattern = new byte[] { 1, 0, 131 };
    bool[] wild = new bool[] { false, true, false };
    byte[] responsePattern = new byte[] { 130, 119, 126, 118, 48, 49, 12, 19, 14 };
    int patternLength = pattern.Length;

    while (true)
    {
        var readBuffer = new byte[4096];
        var asyncReader = await stream.ReadAsync(readBuffer, 0, readBuffer.Length);

        var result = RemovePattern(readBuffer, responsePattern);
        result = RemovePattern(result, pattern, wild);

        if (result != null && result.Length > 0)
        {
            txtBoxMessagesIn.Text += Encoding.ASCII.GetString(l.ToArray()) + Environment.NewLine;
        }
        if (asyncReader <= 0) { break; }
    }
}


Form validation for user account creation

Don't nest your conditions like this.  Validate the input up front and fail out if need be.

For example that might look like this:

if(empty($params['submit'])) {
   // no parameters set
   // log error, throw exception, etc. as approrpiate
}
if(Utilities::checkAllFieldsNotEmpty($params) === false) {
   // fail out
   // not sure if you really need this condition if you validate each field
   // individually
}
// etc.

Then I would suggest that your Admin class should abstract away the details of user creation away from this script.  Ideally this script could just have something like:

try {
    $user = Admin::createNewUser(...);
} catch (Exception $e) {
    // do something to handle exception
}

And createNewUser() would go through all the logic of for validating user name, setting up directories, etc.  This code should know nothing about what is required to create a "user" outside of whatever information needs to be passed (i.e. user name).


Return lambda expression based on parameters

Personally, I find your code easy enough to follow. The flow control is lengthy but is quite simple. A few notes before searching alternatives for the flow control.

Expression<Func<ScheduleItemDto, bool>> notAdminExpression = x => x.Active == true;

Could be

Expression<Func<ScheduleItemDto, bool>> notAdminExpression = x => x.Active;

Your function could be broken in two pieces, one for the switch statement and another for the permission part. It may be a matter of personal preference, but allows early return statements, removing the assignment operation and thus entirely removing any state from the function, pure functions are easier to follow.

// ...
case null:
    if (eventGuid == null)
    {
        return baseExpression;
    }
    else
    {
        return Expression.Lambda<Func<ScheduleItemDto, bool>>(Expression.AndAlso(baseExpression.Body, eventExpression.Body), baseExpression.Parameters[0]);
    }
// ...

private Expression<Func<ScheduleItemDto, bool>> RestrictPermission(Expression<Func<ScheduleItemDto, bool>> baseExpression)
{
    Expression<Func<ScheduleItemDto, bool>> notAdminExpression = x => x.Active
    return Expression.Lambda<Func<ScheduleItemDto, bool>>(Expression.AndAlso(baseExpression.Body, notAdminExpression.Body), baseExpression.Parameters[0]);
}
// ...
RestrictPermission(Where(...));

Now the ways I can think of rewriting the switch statement

If chain

if(closed == null && eventGuid == null)
    return ...;
else if (closed == null && eventGuid != null)
    return ...;
else if (closed && eventGuid == null)
    return ...;
...

Very easy to parse which case each return belongs, but quite verbose.

Dictionary

 var options = new Dictionary<Tuple<bool?, bool>, Expression<Func<ScheduleItemDto, bool>>> {
    { Tuple.Create(null, true), baseExpression },
    { Tuple.Create(null, false), Expression.Lambda<Func<ScheduleItemDto, bool>>(Expression.AndAlso(baseExpression.Body, eventExpression.Body), baseExpression.Parameters[0]) },
    { Tuple.Create(true, true), Expression.Lambda<Func<ScheduleItemDto, bool>>(Expression.AndAlso(baseExpression.Body, closedExpression.Body), baseExpression.Parameters[0]) },
    // ...
}
return options[closed, eventGuid == null];

Adds complexity and reduces readability, but is probably the most compact version.

If plus ternary

if (closed == null)
    return eventGuid == null
        ? baseExpression
        : Expression.Lambda<Func<ScheduleItemDto, bool>>(Expression.AndAlso(baseExpression.Body, closedExpression.Body), baseExpression.Parameters[0]);
else if (closed)
    ...
else
    ...

Half-way between readability and verbosity.

Honestly, I would stick to your switch or a chained-if. You can't get much elegance without making the code unnecessary complex. Or at least not with the options I know, I hope someone has a better solution.


Moar built-ins... MOAR (and a look-up table)!

It is great that you are using the built-in insertRule method for style sheets here:

sheet.insertRule('.' + className + ' {' + sty + '}');

It is not great that you aren't using the built in deleteRule for style sheets here:

function unstyle(className, sty) {

Reading the docs, it says that the deleteRule method accepts an index. This index comes from the second parameter of insertRule which you are currently not using. That means all you need to do is start keeping track of the indexes.

In order to keep track of the indexes, class names, and CSS rules, simply create a look up table and use a counter for the indexes:

var ruleToIndexTable = {};
var indexCounter = 0;

Now, when you are styling a rule, simply add it to the table:

indexCounter++;
ruleToIndexTable[rule] = indexCounter;

Note that this will require you to compute the rule somehow, which are technically already doing in the earlier part of the style function:

sheet.insertRule('.' + className + ' {' + sty + '}');

We'll be using this logic again later, so it'll be best to extract this into it's own function computeRule(className, sty) and have both your style and unstyle functions take the single rule as a parameter.

Then later, in your unstyle function, you can simply use the lookup table to find out which table to delete:

function unstyle(rule) {
    sheet.removeRule(ruleToIndexTable[rule]);
}

This assumes that unstyle can access sheet, too, which it now should be able to so you don't have to get the sheet element over and over again (which is inefficient).

With these changes, your code is much more efficient now. With the addition of this look-up table and the new use of the removeRule function, your code now runs in \$O(1)\$ time (I think).


Finding the difference between postal addresses

The characteristic numbers are not always indicating bad code...

However, you could do something like that to improve the numbers:

private static List<Difference> RetrieveDifferences(IEnumerable<AddressPoco> newValues, AddressPoco item)
{
    var c = newValues.SingleOrDefault(x => x.xedsAddressID == item.xedsAddressID);
    if (c != null)
        return GetDifferences(c, item).ToList();

    return Enumerable.Empty<Difference>().ToList();
}

private static IEnumerable<Difference> GetDifferences(AddressPoco newAdress, AdressPoco oldAddress)
{
    if (item.xgeoCountryID != c.xgeoCountryID)
        yield return new Difference("Country", item.xgeoCountryID.ToString(), c.xgeoCountryID.ToString()));
    if (item.AddressTypeName != c.AddressTypeName)
        yield return new Difference("Address Type", item.AddressTypeName, c.AddressTypeName));
    if (item.City != c.City)
        yield return result.Add(new Difference("City", item.City, c.City));
    if (item.POBox != c.POBox)
        yield return result.Add(new Difference("POBox", item.POBox, c.POBox));
    if (item.MainContact != c.MainContact)
        yield return result.Add(new Difference("Main Contact", item.MainContact, c.MainContact));
    if (item.PostCode != c.PostCode)
        yield return result.Add(new Difference("PostCode", item.PostCode, c.PostCode));
    if (item.Street != c.Street)
        yield return result.Add(new Difference("Street", item.Street, c.Street));
}


Finding min and max values of an iterable on the fly

There are three obvious suggestions here.

Measure!

First, and most important: develop a timing framework to measure your changes! You can't know if a change is beneficial if all you have is "the old version doesn't pass" and "the new version doesn't pass".

Build a standard set of test cases, and a timing framework, and subject any change to measurement in the timing framework. It's better if the timing is better, otherwise it's not.

Cache your results

The examples shown at the hackerrank site specifically include one where the same gene string is repeated twice. So it seems likely that caching your results might provide an obvious performance win.

Stop using the regex engine

This is a "maybe." You're using the regex engine to get the findall behavior, which is sensible, since it gives you access to C code that does what you want. But using that engine comes at a price -- regex operations are traditionally slower than string operations. So see if you can write your code to do the same job without using regex calls.

I'm honestly not sure if this will benefit you or not, since the regexes you are using are so simple. But if you pre-compute the minimum offset for each pattern, to allow for overlaps (like "a" -> +1, "aa" -> +1, "ab" -> +2) you should be able to scan using str.find or str.index and get what you want without any re calls.

Bonus: generator

Your original question asked about using generators. Because the underlying operation is so expensive, I'd suggest writing a single minmax function that yields both values at the same time (like divmod does). You can feed that function with a generator that yields up the scores:

queries = [input() for _ in range(s)]
low, high = minmax(gene_scores(int(l[0]), int(l[1]), l[2] for l in queries))

(This has nothing to do with performance. But you wanted to use them, so here's a way!)


I assume your algorithm is correct and will comment only coding style

I would change INF = float("inf") to INF = math.inf (also you have to import it), since you use python 3.x (I'll asume you can use newest version) inf is now in math package.

Do not put any algorithms directly to the file (I am thinking about with open("input.txt") as f: and so on...) create a function - this is a good pracice because if someone would ever wanted to load your package he wouldnt like to start algorithm right away and also it helps if it comes to testing (you cannot test file but you can test a function).

Regarding a tuple construct

def vector(u, w):
    return (w[0] - u[0], w[1] - u[1])

I would love to see namedtuple here, it is kind of named tuple but it helps other programmers to see what the object exactly is and improve readibility (you would use edge.x instead of edge[0]). It also helps IDE to intelisence it.

Regarding T = int(f.readline()):

If (and only if) you assume that input file is correct such lines are fine but if not a try-except(python's try-catch) closure would be great here. The same thing might be applied to all the parsing in your script.

Note about performance:
I cannot see any real code improvements if it comes to pure pythonic way, in my opinion if you want a faster solution you should try to come up with faster algorithm (maybe some assumptions for your set that would reduce edges to check?).


I personally think this is fine if the concept of creating a UserContact, User is directly tied to creating a UserAccount, i.e. one cannot live without the other.

That is because the abstraction of the method CreateAccount() hides away the implementation details of what needs to be done (insertion of data into 3 tables).

As you already have this abstraction you are now in the postion to potentially refactor the CreateAccount without effecting the rest of your code. Excellant!

So, as an option, I might consider refactoring the service layer itself so that the CreateAccount() method is a bit more streamlined, as you put it.

public UserAccount CreateAccount(NewAccount newAccount)
{
  if (!AccountAlreadyExists(newAccount.UserName))
  {
    UserAccount account = CreateUserAccount(newAccount);
    User user = CreateUser(newAccount);
    UserContact contact = CreateContact(newAccount);

    db.Entry(account).State = EntityState.Added;
    db.Entry(contact).State = EntityState.Added;
    db.Entry(user).State = EntityState.Added;

    db.SaveChanges();

    return account;
  }

  return null;
}

private UserAccount CreateUserAccount(NewAccount newAccount)
{
    string salt = StringCipher.GenerateCypher();

    return new UserAccount()
    {
      UserId = newAccount.UserName,
      PasswordHash = CreatePasswordHash(newAccount.Password),
      Lock = true,
      Created = DateTime.UtcNow
    };
}

private User CreateUser(NewAccount newAccount)
{
    return new User()
    {
      UserId = newAccount.UserName
    };
}

private UserContact CreateContact(NewAccount newAccount)
{
    return new UserContact()
    {
      ContactTypeId = ContactType.EmailPrimary,
      Contact = StringCipher.Encrypt(newAccount.UserEmail, salt),
      UserId = newAccount.UserName,
      Active = true,
      Created = DateTime.UtcNow
    }
}

This first lot of refactoring lead me to realise that newAccount is passed to each of the 3 methods.  I thought at this stage perhaps a class for these actions might make sense so that the common parameter is extracted to a class level variable.

public UserAccount CreateAccount(NewAccount newAccount)
{
  if (!AccountAlreadyExists(newAccount.UserName))
  {
    var accountBuilder = new AccountBuilder(newAccount);
    Account account = accountBuilder.CreateAccount();

    db.Entry(account.UserAccount).State = EntityState.Added;
    db.Entry(account.Contact).State = EntityState.Added;
    db.Entry(account.User).State = EntityState.Added;

    db.SaveChanges();

    return account;
  }

  return null;
}

internal class UserAccountBuilder
{
    private readonly NewAccount _newAccount;

    public UserAccountBuilder(NewAccount account)
    {
        _newAccount = account;
    }

    public Account CreateAccount()
    {
        return  new Account(
            CreateUserAccount(),
            CreateUser(),
            CreateUserContact()
        );
    }

    private string GetUsername()
    {
        return _newAccount.UserName;
    }

    private UserAccount CreateUserAccount()
    {
        string salt = StringCipher.GenerateCypher();

        return new UserAccount()
        {
          UserId = GetUsername(),
          PasswordHash = CreatePasswordHash(_newAccount.Password),
          Lock = true,
          Created = DateTime.UtcNow
        };
    }

    private User CreateUser()
    {
        return new User()
        {
          UserId = GetUsername()
        };
    }

    private UserContact CreateContact()
    {
        return new UserContact()
        {
          ContactTypeId = ContactType.EmailPrimary,
          Contact = StringCipher.Encrypt(_newAccount.UserEmail, salt),
          UserId = GetUserName(),
          Active = true,
          Created = DateTime.UtcNow
        }
    }
}

public class Account
{
    public UserAccount Account { get; private set; }
    public User User { get; private set; }
    public UserContact Contact { get; private set; }

    public Account(
        UserAccount userAccount,
        User user,
        UserContact userContact)
    {
        Account = userAccount;
        User = user;
        Contact = userContact;
    }
}

  NOTE:  This might be overkill but what I was going for here was
  extracting the persistance criteria out from the creation of the
  account itself.  Hence you could use this class to unit test creation
  of accounts without mocking or worrying about the db persistance layer
  which is contained in the service class layer.


How can I tidy up this servlet parameter check code?

In my opinion you could use the Regex to solve this

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    resp.setContentType(CONTENT_TYPE);
    PrintWriter out = resp.getWriter();
    int maximumResults = defaultMaxResults;

    // you could create pathPattern as a Class field
    Pattern pathPattern = Pattern.compile("http://www.hostname.com/servletname/([^/]+)(/(\\d+))?$");

    Matcher m = pathPattern.matcher(req.getPathInfo());
    if(m.find()) {
         String param1 = m.group(1);
         String param2 = m.group(2); // NOTE param2 may be null
         // TODO your business here
         return;
    } else {
         // TODO throw your exception here
    }

}

You can change the pathPattern to meet your need. Hope this help. Feel free to response.


Counting occurrences of each word in a sentence

Guard.NotNullOrEmpty(() => sentence, sentence);

This introduces a dependency on a third-party library, which is 100 lines. Why not just write

if (string.IsNullOrEmpty(sentence))
{
    throw new ...
}

The ISplitter interface is overkill. As is the StringSplitter class, probably -- as @NickUdell mentioned, a regular expression looks like the right tool for the job here.

You have the core of the solution right here:

      var words = _splitter.SplitIntoWords(sentence);

       var wordsCounts = from word in words
           group word by word.ToLower()
           into g
           select new {Word = g.Key, Count = g.Count()};

       return wordsCounts.ToDictionary(wc => wc.Word, wc => wc.Count);

Which can be simplified to

var words = _splitter.SplitIntoWords(sentence.ToLower());
return words.GroupBy(word => word)
            .ToDictionary(group => group.Key, group => group.Count());

Besides being a little shorter, we are creating fewer objects. Let's say there are \$n\$ words returned by SplitIntoWords, \$d\$ of which are distinct (up to case). The first version creates \$2n\$ string objects (the \$n\$ returned by SplitIntoWords and these same \$n\$ words lower-cased) and \$d\$ instances of the anonymous type. The second version creates \$n + 1\$ string objects. This might not be a concern, but since it's an easy win, we should just take it.

SplitIntoWords could be written using yield. Again, not a big difference but it makes the code a bit more re-usable, since client code can use Take, First, etc without having to have generate every word in the string.

public IEnumerable<string> SplitIntoWords(string sentence)
{
    var word = new StringBuilder();
    foreach (var chr in sentence)
    {
        if (Char.IsPunctuation(chr) || Char.IsSeparator(chr) || Char.IsWhiteSpace(chr))
        {
            if (word.Length > 0)
            {
                yield return word.ToString();
                word.Clear();
            }
        }
        else
        {
            word.Append(chr);
        }
    }

    if (word.Length > 0)
    {
        yield return word.ToString();
    }
}


Replacing strings to have a single blank

There a few concerns I have with this program.  Let's go through it line by line:

You don't declare what you are returning from main(), or what parameters you are going to take in.  You should always be declaring these instead of letting the compiler assume them.

int main(void)

You asked in the comments why we should declare this to return an int and not void.  We don't want to just throw away that useful exit status information. There is great answer here that goes into great detail as to why, you should take a look over there.

"But wait!", you say.  "We didn't actually return anything from our main function!  How does this black magic work?"  Yep, I know.  That is just what is declared in the standards.

  C99 & C11 §5.1.2.2(3):

  "...reaching the } that terminates the main() function returns a value of 0."

You don't use your nc variable in your program.  It should be removed.
You declare otherBlank as a char on one line and assign it the character f on the next line.  You should be assigning on the same line as you are declaring in this case.
Analyzing your program further, it is questionable as to why you aren't using a boolean value to represent otherBlank.  You only seem to be using it as a "flag" of a sort, so it makes sense to me to represent it as the bool type.  Keep in mind that you will have to include <stdbool.h> if you choose to change this.
Further refactoring your program, there is no need for the otherBlank variable.  Use a while loop to capture all of the ' ' characters and then output only one ' ' character.  Then continue with the printing of the other non-blank characters.
You don't check putchar for it's return value, as you should be doing.  @Michael went into great detail with this, give his answer a look and an upvote to see why!

Here is what I managed to come up with:

#include <stdio.h>

int main(void)
{
    int c;
    while ((c = getchar()) != EOF) {
        if (c == ' ') {
            while ((c = getchar()) == ' ');
            if (putchar(' ') == EOF) return -1;
            if (c == EOF) break;
        }
        if (putchar(c) == EOF) return -1;
    }
}

Here is how this could be further improved:

Use the function fgets() to capture the input once; looping over each character to capture it manually isn't very efficient (and if your program doesn't handle input properly, it could be dangerous).
Store the input string in a character array and loop over the characters to test them for ' '.  Then make the necessary changes and print out the entire string at once, instead of looping and printing out the individual characters (again, inefficient).


Build a local cache of all streams from Twitch.TV API

At a glance I'd be almost certain that the network requests are your bottleneck here.

If you think of the difference between some code interpreted and run locally vs instantiating a network connection, sending the request, waiting for their servers to run their code and the network latency to respond I think it's safe to say the network time is going to be the bottleneck. Particularly when you consider you're doing hundreds of network connections.

To speed this up I'd say Memcached is your best option. APC is also pretty useful, but not specifically for this. The general idea would be to check if you have cached results and if not generate the data you need and stick it in memcached and return the data. Then, in separate code, take that data and format it as required.

Roughly speaking:

if (Cache->check('key-to-your-data'))
{
    $twitchTvData = Cache->get('key-to-your-data');
}
else
{
    $twitchTvScraper = new TwitchTvScraper();
    $twitchTvData = $twitchTvScraper->scrape();
    Cache->set('key-to-your-data', $twitchTvData);
}

echo PageBuilder->buildFoo($twitchTvData);

In this example I've split out the caching, scraping of content and building of pages into separate classes. Having these all in the one place is a recipe for disaster/embarrassingly silly bugs.

Also, it's worth noting that hitting someone's API repeatedly like this is usually considered bad form and if they're monitoring for such activity you could get blocked. It might be worth looking into a package that can scrape pages with a rate limit. I'm sure there are a few out there. If you don't need the data refreshed often you could just use wget and read the files from a directory locally.

Finally; it's fine to stick some html together when you're learning a new language but in practice it isn't the way to go. Typically you use an off the shelf framework that can build HTML from templates. Something like, Zend, Laravel etc. (http://www.phpframeworks.com/ for more).

Having said all that, if you're just learning to code, don't take this all on at once! Take it piece by piece and save early, save often.


I know that my approach may not add much value, but I would like to share it with you.

Detecting room hours overlapping with this logic is correct, but it is hard to read and understand:-

if (lectureInterval[0] > reserved[0] && lectureInterval[0] < reserved[1]) roomBusyInLectureHours = true;
if (lectureInterval[1] > reserved[0] && lectureInterval[1] < reserved[1]) roomBusyInLectureHours = true;
if (reserved[0] > lectureInterval[0] && reserved[0] < lectureInterval[1]) roomBusyInLectureHours = true;
if (reserved[1] > lectureInterval[0] && reserved[1] < lectureInterval[1]) roomBusyInLectureHours = true;

I think following the approach below will make it more readable and understandable:-

let [reservedStart, reservedEnd] = reserved, [lectureStart, lectureEnd] = lectureInterval;
let busyHours = [...new Array(reservedEnd - reservedStart)].map((v, i)=> reservedStart+i);
let lectureHours = [...new Array(lectureEnd - lectureStart)].map((v, i)=> lectureStart+i);
roomBusyInLectureHours = busyHours.filter(hour => lectureHours.includes(hour)).length > 0;


Filtering visible map layers based on multiple conditions

Okay, so here is how I decided (yes we can say a lot of things about 20 little lines):

Performance

The first code (with a few if) is probably
the best, since the || operator stops whenever a condition is
evaluated to true.
The second one (with the big switch) is a very lil bit slower,
since we compute minRes, maxRes and curRes before evaluating
the first exit conditions where they are unused.
Otherwise, the switch statement stops whenever a truthy case is found.
The third one (with the Array) is the most wrong approach if I want
speed. We compute the variables, store the N conditions in an array
of size N, so they're all evaluated, and then we loop through said array
(.some() method) to tell whether it contains a truthy value.

However, regarding this specific app I'm working on, code legibility
and future features are more important than a few microseconds.

Legibility

My problem here is that legibility is kinda subjective.
I follow specific coding style and guidelines, and it's easier for me
to read code which follows these guidelines that code which doesn't.

Sadly, on this project, there are no defined conventions and there's an
interesting diversity of whitespace habits.

The first code is the most legible for most people coming from C,
but anyone who would come after me would be very tempted to write nested
if, since there are loads of nested code in the repo.
The second one is still quite legible for C pals, and honestly
the individual comments on each condition are nice. Also I believe it is
less tempting to nest conditions, since we would have to change the
structure first.
The last one is the most "eye-candy": it has the advantages of the
switch, while being less heavy (case, break). However, it is
trickier: "What on Earth is this !hideOn.some(Boolean) thing?
Damn, I'll have to check the docs."

Actually, reading the doc is nice I think. Learning about .some()
does not take long, and it's better if maintainers make sure they
know some of the language before, well, maintaining.

Extensibility

Extensibility is also important to me. I know this code will not be
reviewed now, but in a few months someone will probably ask:
"what if we also check this and that?".

In fact, what's likely to happen is "what if we make these conditions
conditional?", ie, add a parameter somewhere, and if this parameter has
some value, then we'll do some more things. This is an interesting way to
check extensibility. Now I'll insert some code since there's been too much
text.

// First code with ifs; nice but we end up nesting conditions
if (configuration === 'wow') {
    doSomething();
    // Comment both conditions
    if (newCond1 || newCond2) {
        return false;
    }
} // Continue

// Second code with switch; I had higher expectations for you
switch () {
case configuration === 'wow':
    doSomething();
    // Comment both conditions
    if (newCond1 || newCond2) {
        return false;
    }
     // Non-breaking case!!
case ...
}

// Other possibility; we may end up with very long lines,
// or multiline conditions (I limit my lines at 80 chars)
switch () {
case configuration === 'wow':
    doSomething();
    // Non-breaking case!!
case configuration === 'wow' && newCond1:  // Comment condition 1
case configuration === 'wow' && newCond2:  // Comment condition 2
case ...
}

// Last code with Array; free candy
if (configuration === 'wow') {
    doSomething();
    hideOn.concat([
        newCond1,  // Comment condition 1
        newCond2   // Comment condition 2
    ]);
}

In this particular situation, I think the last one is the most elegant.
Given it's also the most legible in my opinion, and that I'm clearly biased,
and that I want maintainers to read at least ES5 docs once in a while, my choice has been to use the third versions, with the array of booleans.


One way would be to find the sum of all numbers divisible by three, five and fifteen. To do this define another function that calculates the sum of first n number using the formula  \$\sum\limits_{k=1}^n k = \frac{n(n+1)}{2}\$. Now to find the sum of all number divisible by three all we need to do is pass the quotient of num // 3 to sum_of_n_numbers and multiple its result by 3, same thing of five and fifteen as well.

In the end we simply subtract the sum of all fifteen from sum of five and three because we counted those twice.

def sum_of_n_numbers(n):
    return (n*(n+1))/2.0

def ashwch(test_cases):
    for _ in xrange(test_cases):
        num = int(raw_input()) - 1
        sum_of_threes = 3 *  sum_of_n_numbers(num//3)
        sum_of_fives = 5 *  sum_of_n_numbers(num//5)
        sum_of_fifteenes = 15 *  sum_of_n_numbers(num//15)
        print sum_of_three + sum_of_fives - sum_of_fifteenes

Few other points:

Don't use variable names that start with capital letter for normal variables, such variable names are recommended for class names.
In case number of test-cases are huge you will end up creating a huge list in memory because range() returns a list in Python 2. This applies to your first code as well where you've used range() for the number itself, so your computer will crash with inputs like 10,000,000,000. So, better use xrange() in Python 2.
I have used the // operator instead of / because it will round down the number in both Python 2 and 3.
As this is from a programming challenge you may not need to worry about malicious inputs, but try not to use input() in Python 2 as it evals anything that user enters. So an input like __import__('os').system('ls -l') can be deadly if you replace ls -l with something else. So, use raw_input with int().

>>> input()
__import__('os').system('ls -l')
total 586952
-rw-rw-r-- 1 ashwini ashwini   3468213 Jan 27 02:54 1.txt
-rw-rw-r-- 1 ashwini ashwini   3467213 Jan 27 03:10 4.txt


This is looking pretty good! But there is definitely room for improvement:

Better template parameter name

T generally refers to "any type". Since your template is based on a character type, you should use something like CharT to be more explicit.

Is there really a reason for this to be mutable?

addBracketPairs(), removeBracketPairs() and clearBracketPairs() is just extraneous api surface to me.

I would personally have favored a public API consisting entirely of:

Construct a brackets matcher.
Use the bracket matcher to match brackets.
MAYBE have a join() function to combine two matchers together into 1.

On the surface, it looks less flexible, but it's as functional as your version, and takes a fraction of the time to wrap your head around.

It also means that your emptiness check can be moved to the constructor, so that you don't have to perform that check every single time isBalanced() is invoked.

isBalanced() should take a pair of iterators.

The correct signature for isBalanced() is:

template<typename IteT>
bool isBalanced(IteT begin, IteT end) const;

This way, you can consume from vectors, strings, character arrays, etc... and there is no need to make a copy of the data into a vector prior.

member functions that do not mutate the class should be marked const.

Pretty simole, isBalanced() should be marked const.

Use const references when not taking posession of the data.

For example:

bool isBalanced(const std::basic_string<T>& expression)

This avoids extra copies.


Recursively find data in array of objects

From a medium review;

This code belongs in a well named function
I always forget about destructuring in a filter, very nice
Mapping to an object automatically removes dupes, something I (ab)use in my counter
const findManager = (manager)  should probably be const findManager = (employee)
const findManager = (employee)  should probably be const findLineManagers = (employee)
From there, next should probably be manager , it is definitely not 'next' but more 'actual' ;)
You are not using semicolons, unless you understand all nuances, you should use them
It's more idiomatic in recursive programming to first check for the exit condition than then to check at the end if you should recurse or not

I struggled with this counter-proposal. I imagine in a codebase I maintain I would want my data structure to be linked. So this function gets a linked version of the data and then gets what is needed in what I think is an easier manner. YMMV.

// Initial list of names

function indexPeopleData(peopleData){
  //Index by name
  const indexedPeople = peopleData.reduce((out,person) => (out[person.name] = person, out), {});
  //Make reports point to a people object
  peopleData.forEach(person => person.reports = indexedPeople[person.reports]);
  return indexedPeople;
}

function getLineManagers(peopleData, names){
  const indexedPeople = indexPeopleData(peopleData);
  //Return list of employees and their managers
  let out = {}, name;
  while(name = names.pop()){
    out[name] = indexedPeople[name];
    if(out[name].reports.rank > 1){
      names.push(out[name].reports.name);
    }
  }
  return Object.values(out);
}

var data = [
  {
    name: 'rebecca',
    reports: '',
    rank: 1
  },
  {
    name: 'will',
    reports: 'rebecca',
    rank: 2
  },
  {
    name: 'jose',
    reports: 'will',
    rank: 3
  },
  {
    name: 'tomas',
    reports: 'jose',
    rank: 4,
  },
  {
    name: 'matt',
    reports: 'jose',
    rank: 5
  },{
    name: 'alison',
    reports: 'john',
    rank: 5
  }
];

console.log(getLineManagers(data, ['tomas', 'matt']));


In a sense, your math is wrong.  In

double angle = i / (SAMPLING_FREQUENCY_IN_HZ / hz) * 2 * Math.PI;

… both of the divisions are done using integer arithmetic.  As a result, I get nothing more than a clicking noise.  To get the intended signal, you have to cast i to a double.  Better yet, write it instead as

double angle = 2 * Math.PI * i * hz / SAMPLING_FREQUENCY_IN_HZ;

By the Nyquist criterion, a sample rate of 8000 Hz means that you can play a frequency no higher than 4000 Hz.  Therefore, for robustness, you should do one of three things:

Throw an exception if hz >= SAMPLING_FREQUENCY_IN_HZ / 2.
Let the sampling frequency vary, by setting it to 16 * hz, for example.
Set SAMPLING_FREQUENCY_IN_HZ high enough so that it covers the range of human hearing (44.1 kHz for CD audio, 48 kHz for DVD video soundtracks).

It would also be wise to define the fade-in / fade-out period as a multiple of the sampling rate.


Digit sum loops+random positive number generator

I have some suggestion for you.

Code duplication

In your code, you have some code duplication that can be extracted in a method. By extracting the code, the code will become shorter, be less error-prone and easier to read.

I suggest that you make a method to print a question and read the user input.

public static void main(String[] args) {
   //[...]
   int a1 = askQuestionAndReceiveAnswer(scn, "1TH NUMBER : ");
   int a2 = askQuestionAndReceiveAnswer(scn, "2ND NUMBER : ");
   //[...]
}

private static int askQuestionAndReceiveAnswer(Scanner scn, String s) {
   System.out.println(s);
   return scn.nextInt();
}

Since the logic is the same to handle the sum, you can extract both of the while into a method. This extraction will remove lots of code!

public static void main(String[] args) {
   //[...]
   int sum1 = getSum(a1);
   int sum2 = getSum(a2);

   int temp = sum1 + sum2; //temporary-for storage /=

   int sum3 = getSum(temp);
   //[...]
}

private static int getSum(int userInput) {
   int currentSum = 0;
   while (userInput > 0) {
      currentSum += userInput % 10;
      userInput /= 10;
   }
   return currentSum;
}

Other observations

In my opinion, I would extract the last calculation in a method and return the result.

public static void main(String[] args) {
   //[...]
   int number = findNumber(rnd, sum3);
   System.out.println(number + " this is my number");
   //[...]
}

private static int findNumber(Random rnd, int sum3) {
   int sum4 = 0;
   while (true) {
      int a3 = rnd.nextInt(Integer.MAX_VALUE);
      sum4 += (a3) % 10;
      (a3) /= 10;
      if (sum4 > sum3) {
         return a3;
      }
   }
}

Refactored code

public static void main(String[] args) {
   Random rnd = new Random();
   Scanner scn = new Scanner(System.in);

   int a1 = askQuestionAndReceiveAnswer(scn, "1TH NUMBER : ");
   int a2 = askQuestionAndReceiveAnswer(scn, "2ND NUMBER : ");
   System.out.println((0 > a1 || 0 > a2 ? "ERROR-NEGATIVE NUMBER" : "OK"));

   int sum1 = getSum(a1);
   int sum2 = getSum(a2);
   int temp = sum1 + sum2; //temporary-for storage /=

   int sum3 = getSum(temp);

   int number = findNumber(rnd, sum3);
   System.out.println(number + " this is my number");
}

private static int findNumber(Random rnd, int sum3) {
   int sum4 = 0;
   while (true) {
      int a3 = rnd.nextInt(Integer.MAX_VALUE);
      sum4 += (a3) % 10;
      (a3) /= 10;
      if (sum4 > sum3) {
         return a3;
      }
   }
}

private static int getSum(int userInput) {
   int currentSum = 0;
   while (userInput > 0) {
      currentSum += userInput % 10;
      userInput /= 10;
   }
   return currentSum;
}

private static int askQuestionAndReceiveAnswer(Scanner scn, String s) {
   System.out.println(s);
   return scn.nextInt();
}


Abstract base classes are only useful if you're inheriting functionality. So, what you've done with Mail is good, because all of your inheritors get their properties "for free". In contrast, there's no sense in your MailSender class. Inheritors get no functionality, but are forced to adhere to the contract you've decided on. That's what Interfaces are for.

What I actually don't like is that it's only possible to send an email to exactly one person with your classes. Very soon, you'll wish that you could send an email to a bunch of people at once. EmailTo should mimic the class that you're wrapping up and return a collection.

You're also missing any concept of From in your Mail class. I would expect an email message to know who it's coming from.


Groovy script to get average price per group from different data arrays

After being investigating a little bit more about usage of closures and some other facilities that Groovy provides, I managed to reduce a little bit the algorithm, after looking for benchmarking posts, I believe this is probably not the most optimal solution, but it looks a lot better than the first proposal (the one in my question).

One of the things I considered to improve the solution is to use Groovy "maps" instead of multiple arrays to hold the data.

I also considered using one additional variable to hold the value of a group being evaluated.

And finally, I decided to avoid using more conditionals to add the results to the arrays and use a more simple instruction taking advantage of the map definition.

MAX_DEFAULT_VALUE_WHEN_NULL = 99999.9

def calculateResult() {
    def pricesPerGroupMap = [G1:[], G2:[], G3:[]]
    def avgPricePerGroupMap = [:]

    category.each { cat ->
        String categoryId = cat[0]
        BigDecimal min = cat[1]
        BigDecimal max = cat[2]

        if (max == null) {
            max = MAX_DEFAULT_VALUE_WHEN_NULL
        }

        products.each { product ->
            BigDecimal currProductPrice = BigDecimal.valueOf(product[2])
            String group = product[1]
            if (currProductPrice.compareTo(min) >= 0 && currProductPrice.compareTo(max) == -1) {
                String selectedMarginAsString = margins.getAt(categoryId);
                BigDecimal selMargin = 0.0;

                if (selectedMarginAsString.endsWith("%")) {
                    selMargin = new BigDecimal(selectedMarginAsString.trim().replace("%", "")).divide(BigDecimal.valueOf(100))
                } else {
                    selMargin = new BigDecimal(selectedMarginAsString)
                }
                pricesPerGroupMap[group].add(currProductPrice * (1 + selMargin))
            }
        }
    }
    pricesPerGroupMap.each { k, v ->
        avgPricePerGroupMap.put(k, new BigDecimal(v.sum()).divide(v.size(), 1, RoundingMode.UP))
    }
    return avgPricePerGroupMap
}


What is the best way to conditionally add to an immutable collection in Scala?

You can use the fact that Map() ++ None == Map() along with Map() ++ Some((k,v)) == Map((k,v)) and Option.map to get the following pattern:

def generateObject(foo: Option[String]) = {
  Map("bar" -> "baz") ++ foo.map("foo" -> _)
}


Caesar Cipher that takes an arbitrary offset

Some comments on your updated code in Rev 3:

I would define your constants as follows:

#define LSTART ('a')
#define USTART ('A')
#define NALPHA ('z' - 'a' + 1)

You now need no comments - they are obvious.
It would be normal to use perror(argv[1]); to print the error on opening
the file.
My man-page says atoi has been depracated in favour of strtol
return values from main are traditionally EXIT_FAILURE and EXIT_SUCCESS
I would define offset and wrap at their point of first use.  Also it is
generally recommended not to define multiple variables on one line.
In the while loop you should put the fputc(ec, stdout); outside the
if(isalpha(ec)) {...} condition.  That way the format of what you encrypt
is maintained.  Equally, I would omit printing \n at the end so that the
output file (on stdout) has the same form as the input.
I prefer to see a space after keywords, if, while etc.
Don't overuse ?: - it is not a universal replacement for if-else
I find a character named ec to be less intuitive than one named ch, but
maybe that is just me.
I think your encryption code:

    int ascii_offset = islower (ec) ? LSTART : USTART;

    wrap = (ec + offset - ascii_offset) % NALPHA;
    wrap = (wrap < 0) ? NALPHA + wrap : wrap;
    ec = islower(ec) ? wrap + LSTART : wrap + USTART;

would be better written:

    const int ascii_offset = islower(ec) ? LSTART : USTART;
    int wrap = (ec + offset - ascii_offset) % NALPHA;
    if (wrap < 0) {
        wrap += NALPHA;
    }
    ec = wrap + ascii_offset;


Compact a comma delimited number list into ranges

You could calculate a value to group on, i.e. number - index. All consecutive numbers have the same value:

index  number  number - index
-----  ------  --------------
  0       1          1
  1       2          1
  2       3          1
  3       4          1
  4       5          1
  5      12          7
  6      13          7
  7      14          7
  8      19         11

Then you just check how many items there is in each group to determine if it should be a range.

Example:

List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 12, 13, 14, 19 };

List<string> items = numbers
  .Select((n,i) => new { number = n, group = n - i })
  .GroupBy(n => n.group)
  .Select(g =>
    g.Count() >= 3 ?
      g.First().number + "-" + g.Last().number
    :
      String.Join(", ", g.Select(x => x.number))
  )
  .ToList();

Console.WriteLine(String.Join(", ", items));

Output:

1-5, 12-14, 19


There are a few things that I would do differently and/or change:

I usually find it easier to put all the public methods at the top and the private methods at the bottom instead of mixing them. This is also what I see most people do.
Be consistent. In pin_error you return an error message, in over_error you print the message (elsewhere you use puts). I would make both methods just puts the error message.
I would not assign an instance variable in amount just return the value and then change withdraw to use a local variable. I would also call it get_amount or something since it does more than just return an amount.

def withdraw
  amt = get_amount
  if  amt <= @balance
    @balance -= amt
    puts "Withdrew: $#{amt}. Updated balance: $#{@balance}."
  else
    over_error
  end
end

The pin method is odd in that it returns the bin but also sets an instance variable unnecessarily. I would pass the pin into the constructor.
I would make pin_check actually check if the pin is correct and return true or false. I would also give it an active name, with a bang, like check_pin!


Just focusing on the initialization part.

The code is using both index and idx which gives off a code smell, something could be better there
The code is using idx just to loop over an array, apply a function and push. We can do better than this
Comments should be useful, commenting the end of an if statement is not useful

(function(){
  process.argv.forEach(function (val, index, array) {

    try{
      //Add the comma separated numbers to myArray as integers
      if(index === 2){
        myArray = myArray.concat( val.split(",").map(c=>parseInt(c)) );
      } else if (index === 3){
        //Third index is the number to be searched.
        searchNum = parseInt(val)
      }
    }catch(e){
      console.log(e)
    }
  });
})();

If you think further, then we could skip the whole loop business, and just access the 2 values we need. It would be simpler, and better.

    (function(){
      var args = process.argv;

      try{
        //Add the comma separated numbers to list as integers
        list = list.concat( args[2].split(",").map(c=>parseInt(c)) );
        //Third index is the number to be searched.
        searchNum = parseInt( args[3] );
      }catch(e){
        console.log(e)
      }
    })();

myArray is not a great name, I preferred list.


Secure/Bulletproof Image Upload Using PHP

Questions

Is this code really secure against uploading of malicious codes ? Anything i have to add to this code to make it more secure?

My initial thought is to ensure that the uploaded file is not an executable file or a file that may be run as a separate script- e.g. PHP or some other language the server may handle. The Mime type checking from finfo::file() should handle that.
You could also :

check that a GD function like imagecreatefromgif(), imagecreatefromjpeg(), etc. does not return FALSE
check the permissions on the file after it is uploaded to ensure anything that shouldn’t be executed cannot be executed - perhaps use is_executable(), fileperms and chmod
like you say: “move images folder out of public_html (root) folder.”- Ensure that any uploaded files are not stored in a web accessible directory unless that is your desire. This may lead to needing a (PHP/other) script or web server module to read files.

Suggestions
avoid excess else
Whenever a conditional block contains a die statement then subsequent code does not need to be prefixed with else e.g.

//check if error is set
if(!isset($_FILES['image']['error']) ){
    echo 'Invalid upload.';
    die();
}
// check formultiple uploads and block
elseif(is_array($_FILES['image']['error'])){
    echo 'Only one file allowed.';
    die();
}

When else is used it adds more complexity to the decision tree.
Returning early
Going along with the previous point, in some parts of the code when a precondition is not met then an error message is printed to the screen before die() is called. However this is not true in all cases - e.g. the first conditional:

if(isset($_POST['submit'])){

Flipping the logic on that so the error message that is displayed when that condition is false and adding a call to die would allow the indentation levels to be decreased dramatically, which would likely make the code more readable. Further improvement would come from moving some logic to functions - e.g. a function to determine if the file can be uploaded - if not then return early.
With such changes the decision tree of the logic could go from something like this:

screenshot captured from source: Your code sucks, let's fix it - By Rafael Dohms at 15:17
To this:

screenshot captured from source: Your code sucks, let's fix it - By Rafael Dohms at 15:28
storing max size

    $maximumsize=5000000000;

Since that value shouldn’t be reassigned during the runtime it is advisable to use a constant instead, and a common convention in many programming languages is to use all caps, which is in-line with the PHP Standards recommendation PSR-1 - e.g.
const MAXIMUM_SIZE = 5000000000;

And define those near the top of the code or in a configuration file to allow quick access should you ever need to change the value - that way you won’t need to go hunting through the code to find it.
Array syntax
There isn't anything wrong with using array() but as of the time of writing, PHP has Active support for versions 8.0 and 7.4, and since PHP 5.4 arrays can be declared with short array syntax (PHP 5.4).

$allowed = array('jpg' => 'image/jpeg', 'png' => 'image/png', 'gif' => 'image/gif');

Can be shortened slightly to
$allowed = ['jpg' => 'image/jpeg', 'png' => 'image/png', 'gif' => 'image/gif'];

checking mimetype
$filemime could either be string or Boolean - check for Boolean, then if it isn’t then in_array() could be used to determine if it exists in the array instead of using array_search()
Appending to $newfilename
The extension is appended to the file name:

 $newfilename= $newfilename.'.'.array_search($filemime, $allowed);

The dot equals operator can be used to append to the variable:
 $newfilename .= '.' . array_search($filemime, $allowed);

Spaces added for readability.