SQL query to count loans issued during each week

Your query could be simplified.

use inner join to avoid ambiguity when reading the query
temporal interval join date between start and end (inclusive end)

join business_calendar as bc
        on (bc.date_begin < d.dl_valutation_date
        or bc.date_begin = d.dl_valutation_date)
        and (dateadd(day, 6, bc.date_begin) > d.dl_valutation_date
        or dateadd(day, 6, bc.date_begin) = d.dl_valutation_date)

 inner join business_calendar as bc
        on d.dl_valutation_date between bc.date_begin and dateadd(day, 6, bc.date_begin)

snippet:

select
    trd.name as "Региональное подразделение",
    bc.bc_year as "Год",
    bc.week as "Неделя",
    sum(d.dl_sum) as "Сумма выданных займов",
    count(d.dl_id) as "Кол-во займов"
from deal as d
inner join business_calendar as bc
    on d.dl_valutation_date between bc.date_begin and dateadd(day, 6, bc.date_begin)
inner join territory as t on t.id = d.dl_territory_id
inner join territory as trd on t.parent_id = trd.id
where bc.week in (38,39,40)
group by trd.name,bc.bc_year, bc.week
order by trd.name, bc.week asc


VBA macro which filters and splits dataset into new workbooks

I agree with @RubberDuck about the RowHeight issue.  There are a couple ways to look at this.

Look at the Help in VBA for this:

  If you return the RowHeight property of several rows, you will either get the row height of each of the rows (if all the rows are the same height) or null (if they’re different heights).

So you can either write code to test if the RowHeight of your source = a number and then set the new sheet to the same value knowing that they are all the same. This is a bit fiddly maybe if you are new to VBA.

The other answer is to copy the EntireRow from your filtered data which will then copy the RowHeight for you. Is there anything beyond column S which you don't want copied? If not, then let's copy the entire row. It might even be quicker to copy the entire row and then Clear columns T:whatever.

Another point is that you are not touching Application.Calculation but you have a sheet that uses the INDIRECT function and you are doing a lot of filtering. I suspect this is the biggest issue. That function is Volatile which means Excel recalculates it even if it doesn't need to. This is because Excel cannot track which cells feed the function.

I suggest that you set Application.Calculation = xlCalculationManual at the top  of your code (like you do with ScreenUpdating) and then set it to Application.Calculation = xlCalculationAutomatic at the end. It is a good idea to store the original value before setting it to xlCalculationManual and then you can use that value to restore it. Here's the code:

Dim xlCalc As XlCalculation

' Save the original setting
xlCalc = Application.Calculation
' Put calcs to manual
Application.Calculation = xlCalculationManual
'
' ... do some intensive work
'

' Put calcs back to original setting
Application.Calculation = xlCalc

When you save a workbook with calculations set to xlCalculationManual the workbook remembers the setting which can then cause problems when you re-open the workbook because it doesn't re-calculate itself. So we should somehow keep track of your new workbooks, keep them open and save & close them after putting calculations back to their original setting. We can use the Collection object for this.

I've added some references to ThisWorkbook so that the code is referring to the correct workbook. Change these to Workbooks("book_name.xlsm") if it is not the workbook that is running the code.

This is what I think the changed code looks like. This includes copying the EntireRow so you'll need to revert back to your code if this doesn't fit your requirements. WARNING: I cannot be sure it will work correctly for your data, so use F8 to step through it and test it thoroughly.

Sub Create_by_keyrecord()

Dim r As Long, rng As Range, ws As Worksheet, wb As Workbook
Dim xlCalc As XlCalculation
Dim newBookNames As Collection
Dim bookName As Variant
Dim filePath As String
Dim newFileName As String
Dim lastRow As Integer

    Application.DisplayAlerts = False
    Application.ScreenUpdating = False

    ' Save the original setting
    xlCalc = Application.Calculation
    ' Put calcs to manual
    Application.Calculation = xlCalculationManual

    Set newBookNames = New Collection

    With ThisWorkbook.Sheets("Sheet1")
        ThisWorkbook.Sheets.Add().Name = "temp"
        .Range("D7", .Range("D" & Rows.Count).End(xlUp)).AdvancedFilter Action:=xlFilterCopy, CopyToRange:=Sheets("temp").Range("D7"), Unique:=True
         For Each rng In Sheets("temp").Range("D7", Sheets("temp").Range("D7").End(xlDown))
            .AutoFilterMode = False
            .Range("D7").AutoFilter Field:=3, Criteria1:=rng
            Set ws = ThisWorkbook.Sheets.Add

            lastRow = .Range("B7:I7").End(xlDown).Row
            .Range("B7:S" & lastRow).EntireRow.SpecialCells(xlCellTypeVisible).Copy
            ws.Range("A7").PasteSpecial xlPasteColumnWidths
            ws.Range("A7").PasteSpecial xlPasteAll
            .Range("B2:S6").EntireRow.Copy ws.Range("A2")

            ' Maybe empty column A?
            ws.Columns("A:A").ClearContents

            ws.Columns("A:A").ColumnWidth = 1

            ws.Name = "source_data_worksheet"
            ' Create the new workbook using a Workbook object variable
            ' It means we already have a reference to the new workbook later
            ' in the code
            Set wb = Workbooks.Add
            ws.Move Before:=wb.Worksheets(1)
            Set ws = wb.Worksheets(1)
            .AutoFilterMode = False
            ' Which workbook/sheet are these lines of code for?
            Rows.Hidden = False
            Columns.Hidden = False

            ' Make sure the new book & sheet are active
            wb.Activate
            ws.Activate
            ActiveWindow.DisplayGridlines = False
            ws.Range("G7").Select
            ActiveWindow.FreezePanes = True

            ws.Range("B6:S6").AutoFilter

        'copy additional worksheets to new workbook
            ThisWorkbook.Sheets("SheetA").Copy After:=wb.Sheets(1)
            wb.Sheets("SheetA").Visible = xlSheetHidden

            ThisWorkbook.Sheets("SheetB").Copy After:=wb.Sheets(1)
        'end new code'

            wb.Protect Password:="password", Structure:=True, Windows:=True

            filePath = "C:\...\"
            newFileName = rng & "filename.xlsm"
            ActiveWorkbook.SaveAs _
                Filename:=filePath & newFileName, _
                FileFormat:=xlOpenXMLWorkbookMacroEnabled

            newBookNames.Add newFileName
        Next rng

        ThisWorkbook.Sheets("temp").Delete

    End With

    ' This might take a while because everything will re-calculate
    Application.Calculation = xlCalculationAutomatic

    ' Now loop through the new book names
    ' and save each workbook
    For Each bookName In newBookNames
        Workbooks(CStr(bookName)).Save
        Workbooks(CStr(bookName)).Close False
    Next bookName

    Application.DisplayAlerts = True
    Application.ScreenUpdating = True

End Sub


Simplifying if statement in a StateT monad transformer

I don't like your pop and push. They're shaped specially for StateT, but leave off the wrapper. I'd suggest, instead, something like this:

pop :: Monad m
    => StateT [a] m (Maybe a)
pop = do
  s <- get
  case s of
    x : s' -> Just x <$ put s'
    [] -> pure Nothing

push :: Monad m
     => a -> StateT [a] ()
push a = modify (a :)

Of course, you can implement those using state, but I think this way is clearer. Once you've gone that far, you might consider using Control.Monad.State.Strict (from mtl) and changing the type signatures:

pop :: MonadState [a] m
    => m (Maybe a)
push :: MonadState [a] m
     => a -> m a

Side note: Control.Monad.Trans.State implements lazy state transformers, which are rather weird beasts you usually don't need. Unless you have a special reason, reach for Control.Monad.Trans.State.Strict or Control.Monad.State.Strict instead.

Moving on with the mtl approach: StateT s (MaybeT m) a is really

s -> MaybeT m (a, s)

or

s -> m (Maybe (a, s))

What about MaybeT (StateT s m) a? That's

StateT s m (Maybe a)

or

s -> m (Maybe a, s)

Not quite the same, but pretty similar! Their monadic operations are essentially the same. The big difference is that in the latter case you get the last state whether or not the operation stopped short. I think you may end up happier that way, with

mainLoop :: MaybeT (StateT Stack IO) x
mainLoop = do
  input <- liftIO getLine
  if null input
    then do
      -- No pattern match!
      x <- MaybeT pop
      liftIO . putStrLn $ x
    else push input
  mainLoop

Extra side note: we can make mainLoop polymorphic in its return value, because it never returns.

An alternative:

pop :: (MonadState [a] m, MonadFail m)
    => m a
pop = do
  s <- get
  case s of
    x : s' -> x <$ put s'
    [] -> fail "Empty stack"

Now you can use the same mainLoop code whichever order you choose to stack the transformers:

mainLoop :: ( MonadState Stack m
            , MonadIO m
            , MonadFail m )
         => m x
mainLoop = do
  input <- liftIO getLine
  if null input
    then do
      x <- pop
      liftIO . putStrLn $ x
    else push input
  mainLoop

In my opinion, though, this is less clear than the other options, and probably doesn't add much useful flexibility.


jQuery function to create a container div with some content

First of all, In terms of readability, when chaining jquery operations, I like to put the operation at the start of the line. When I create an Object with only one attribute, a one liner with no trailing comma is also good. And naming your jquery objects with a heading $ makes anyone understand that you're using a jquery object here :

function create_container(type, counter) {
      var $ret = $('<div />')
          .attr({class: 'container-box'})
          .data({
              type: type,
              counter: counter,
          })
          .append(
              $('<span />')
                  .attr({class: 'remove'})
                  .append('&times;')
          );
      return $ret
  }

  var $b = create_container('text', 0);
  console.log(create_container('text', 0));

Then you coud use the jquery method addClass instead of attr({class: 'foo'} :

function create_container(type, counter) {
  var $ret = $('<div />')
      .addClass('container-box')
      .data({
          type: type,
          counter: counter,
      })
      .append(
          $('<span />')
              .addClass('remove')
              .append('&times;')
      );
  return $ret
}

var $b = create_container('text', 0);
console.log(create_container('text', 0));

Finally, if you get to use es6, you could get this kind of code, which I find a lot more readable :

function create_container(type, counter) {
  const $ret = $('<div />')
      .addClass('container-box')
      .data({type, counter})
      .append(
          $('<span />')
              .addClass('remove')
              .append('&times;')
      );
  return $ret
}

const $b = create_container('text', 0);
console.log(create_container('text', 0));


I notice that the elements you show have classes namesd after the elements you click.

For example:

The element with the class air-quality-news-tab
Will show the elements matching selector ".featured-article .aqn"

If this will always be the case, you could just reduce the clicked class down to the initials and use that to select the appropriate element like this:

(note that someone better at regex than me could probably make this even shorter)

$('.newsroom-tabs div.pane-content ul li').click(function() {
  var className = $.map($(this).attr('class').split('-'), function(val) {
    return val.match(/^[a-z]/i);
  }).join('').replace(/t$/i, '');
  $('.featured-article').hide();
  $('.featured-article.' + className).fadeIn(300);
});
.featured-article {
  display: none;
  width: 300px;
  height: 200px;
  background-color: #cccccc;
}

air-quality-news-tab

awards-and-reviews-tab

in-the-community-tab

press-releases-tab

aqn

aar

aqn

pr


You cannot use recvfrom with a TCP socket (SOCK_STREAM). You don't see the error, because of your wrong exception handling. Never ignore all exceptions! Don't write your own server, use the appropriate interface from asyncio.


There's lots of indentation that should be on a single line instead.
Including most of the lets.  There's also no reason to keep nesting
lets when you can just add additional definitions in a single let.
E.g. for make-gui it's entirely feasible just to have a single let
instead of four.

The save-but function doesn't need "./" in there, that's already
what will happen there's no additional path specified.

The bitmap should be only read once from disk; the additional read when
pressing the button is not necessary.  Hard coding the 700x500
dimensions into the code is also something that could be fixed by
querying the image (or the thing it's drawing on) for its size instead,
making it way more flexible in the process.  You should probably also
add a way to specify the output (and input) filename while you're at it.

random-member is not efficient, see
Rosetta Code,
i.e. it should be something like (list-ref my-list (random (length my-list))) instead, while not shuffling the entire list.

Otherwise I don't see too much to complain about; the variable names
could be more descriptive (save-but) and less truncated (horiz),
also the overuse of my- is a bit annoying (by which I mean that the
prefix doesn't provide the reader with any additional information).


Class to unit-test functions, with rudimentary support for testing multi-parameter functions

Since indentation is crucial in Python, you should consistently use four spaces, as specified in PEP 8, the official Python style guide.

Also, don't mix naming styles.  Based on PEP 8, the class should be named UnitTester.

Your test harness neglects to support…

calling functions with no parameters, or with more than 3 parameters.  This is easily solved using the * operator:

function_output = function_to_test(*test_input)

calling functions with keyword parameters.  You could accomplish this using the ** operator.
testing that a function raises an exception as expected.  That is left as an exercise for you.
testing whether a function performs expected side-effects, such as printing certain output.  This is quite tricky to implement, but it's something that doctest can easily handle.

def aloha():
    """
    >>> aloha()
    Hello
    'Goodbye'
    """
    print('Hello')
    return "Goodbye"

This code is an abuse of assertions:

    try:
        assert function_output == expected_output
        print(self.unit_test_response(True, test_input, function_output, expected_output))
    except AssertionError:
        print(self.unit_test_response(False, test_input, function_output, expected_output))

Assertions are a way for you, as a programmer, to state that a certain condition must logically be true, not that you hope for a condition to be true.

Furthermore, assertions can be disabled, in which case every test would succeed!

You should replace that code with:

      result = (function_output == expected_output)
      print(self.unit_test_response(result, test_input, function_output, expected_output))

My biggest complaint about this unit-testing class, though, is that it is unclear how it is meant to be used.  You didn't describe the intended usage in the question, and you didn't write docstrings like you should have.  I'm guessing that this is your intended usage:

Unit_Tester(max, [
    ([3, 1, 4], 4),
    ([-3, -1, -4], -1),
]).run()

But why does the run_unit_tests(…) method exist?  Is this a "valid" way to use your harness?

Unit_Tester(None, None).run_unit_tests(max, [
    ([3, 1, 4], 4),
    ([-3, -1, -4], -1),
])

If it is, then I recommend getting rid of the tests parameter in the constructor.  If it isn't, then I recommend merging run_unit_tests() into run(), so that misuse is impossible.

Alternatively, name your "private" methods with a leading underscore (e.g. _unit_test_response(…) to indicate that a method should not be called directly.


C# beginner's exercise in calling methods

I have a few tips for your code:

Keep variable names consistent. Doing this makes it easier to remember (or guess) what you named them in the future. One good way of doing this is capitalizing all variable names the same way. Most programmers use what's known as camel case.

Example:

int camelCaseRules;

This will help you A LOT in the future when coming up with coherent variable names, and since most programmers use camel case, it will help you in team projects.
Another thing about variables is to make sure that you can understand it. E.g. don't name a variable NID (Standing for noIDont). When naming variables, you should make sure that you can get a basic understanding of what they do/are used for without digging in the code to figure it out.
Comment, comment, and comment. Keeping up good commenting habits early on in programming will help you tremendously in the future. This will heavily increase your code readability and make it so that when you come back to the code in a week, you can understand why you did something the way you did it. Just putting in those two forward slashes makes a huge difference. Something to keep in mind when commenting your code however (which was brought to my attention by Hosch250), is to not comment on what the code does, but what it is used for. Basically, well written code should explain what it does without comments, and comments should explain what it is used for in the program.

// Comment your code!

Finally, only make this public if they have to be (e.g. your YesIDo variable in the OtherClass class. I would explain why, but I think this article does a much better job of doing so.

Also, a good YouTube video I would check out is here.


TapeEquilibrium implementation does not satisfy all requirements

I coded up my own solution, and mine was pretty close to yours, but mine received 100%.

Here are the problems:

List<int> list = A.Cast<int>().ToList();

Both the Cast and the ToList are redundant here. Arrays implement IEnumerable, which is enough for LINQ. The ToList is iterating the entire array, which is costing you some runtime.

int temp = 0;
int sum = list.Sum();
List<int> result = new List<int>();
foreach (int i in list)
{
    temp = temp + i;
    result.Add(Math.Abs(  ( sum - temp) - temp));
}
return  result.Min();

This is hurting you on the space requirements -- you're generating a list of every subtraction. Then it's hurting you on time requirement again because it has to iterate the entire result list to find the lowest number.

You can do the entire thing with two passes of the input. You're doing 4.

I'll also say that you should almost never have a variable named temp. Give it a name that describes what it actually is. I used the names "left" and "right".

Left starts at 0, Right starts at the Sum. For each number, add it to Left, subtract it from Right. Much easier to read.

Update
I actually realized that in addition to everything I said, there's a major logic flaw in your version, which is probably what's hurting you more than the other stuff:

What happens if your code tries to handle {3, -1}?

First pass:

temp = 3
sum = 2

|(2 - 3) - 3| = 4

There should be no second pass, but you do one anyway:
Second pass:

temp = 2
sum = 2

|(2 - 2) - 2| = 2


Game Of Life implemented with for-loops and a boolean-array

I'd start it with a Cell and a Grid class and probably a two-dimensional Cell array field in the Grid.  Cell provides type-safety and more readable code while  probably contains only a boolean flag.

Anyway, this implementation can be improved. I'd extract out a List<Integer> getSurroundingCells(int cellIndex) and an int countLiveCells(final List<Integer> cellIndexes) method. A boolean getNextValue(int cellIndex, boolean oldValue, int liveNeighborCount) also could help.


It looks ok to me.

As a few comments in a random order:

I guess I don't have to tell you that writing a non-recursive function for this is quite straightforward.
You could give tmp its final value as you define it : char tmp = a[i];.
You could make it a tail call recursion by doing reverse(a, i+1, j-1) at the end.
It might be a good option to define a function reverse taking only the array and the length as an argument and calling the one you've just posted here. If you were to use this function in a C++ program, you could do this with a single function definition if you use default parameter (i is 0 by default). The main drawback is that you have to give the parameter a somewhat awkward order.


Python already has an exception that denotes that the value you passed is inappropriate somehow. It is ValueError, which is what the built-in int also raises if a wrong string is passed.

In addition, defining a nice readable error which you can raise, only to catch it directly within the function and to return None (the output of print) and print to the terminal is not ideal. Just let the exception rise to the caller of the function, it should be their problem if the function is used in a bad way (which you are telling them all about with that exception).
You should avoid magic constants. What are 57  and 48? Either give them names and use compound comparisons:

zero = ord("0")
nine = ord("9")

if not zero <= code <= nine:
    ...

Or, maybe even better, write a isdigit function:

def isdigit(s):
    return s in set("0123456789")

Which can be slightly sped up by using the standard library string module:

from string import digits

DIGITS = set(digits)

def isdigit(s):
    return s in DIGITS

Incidentally, don't shadow the standard library string module, just call the input s or x, as int does.

Note that there are also str.isdigit, but this unfortunately also returns true for unicode digits, such as all of ¹²³⁴⁵⁶⁷⁸⁹⁰. Only with a whitelist can you fully control what counts as a digit in your case.
Instead of iterating over the string and directly calling ord, you can use map (and reversed):

for code in map(ord, reversed(string)):
    ...

You could also iterate over multiplier (or rather its exponent) at the same time using enumerate:

for exponent, code in enumerate(map(ord, reversed(string))):
    ...
    value += (code - zero) * 10 ** exponent

Actually directly manipulating ASCII values is not the most robust (although it works). Instead you could just make a dictionary that maps strings to integer values:

VALUES = {c: d for d, c in enumerate(DIGITS)}

Using string[0] to check for a sign character can fail if the empty string is passed. Instead you can use str.startswith("+") or even str.startswith(("+", "-")). This will just return False for an empty string.
With all this done, your function can actually easily be extended to arbitrary bases (but let's stick to maximum base 36, like int, i.e. all digits and lowercase letters):

DIGITS = string.digits + string.ascii_lowercase
VALUES = {c: d for d, c in enumerate(DIGITS)}

def isdigit(s, base=10):
    return s in DIGITS[:base]

def atoi(x : str, base : int = 10):
    if not 2 <= base <= 36:
        raise ValueError("Only 2 <= base <= 36 currently supported")
    sign = 1
    if x.startswith(("+", "-")):
        if x[0] == "-":
            sign = -1
        x = x[1:]
    value = 0
    for exp, c in enumerate(reversed(x)):
        if c not in VALUES or VALUES[c] >= base:
            raise ValueError(f"{c} is not a valid digit in base {base}")
        value += VALUES[c] * base ** exp
    return sign * value

This works, as demonstrated below:

atoi("12345")
# 12345
atoi("+12345")
# 12345
atoi("-12345")
# -12345
atoi("12345", base=6)
# 1865
atoi("12345", base=5)
# ValueError: 5 is not a valid digit in base 5
atoi("101010", base=2)
# 42
atoi("1234567890abcdef", base=16)
# 1311768467294899695
atoi("1234567890abcdefghijklmnopqrstuvwxyz", base=36)
# 3126485650002806059265235559620383787531710118313327355
atoi("")
# 0
atoi("111", base=1)
# ValueError: Only 2 <= base <= 36 currently supported
atoi("Az", base=62)
# ValueError: Only 2 <= base <= 36 currently supported

You should surround your calling code with a if __name__ == "__main__": guard to allow importing from this module from another script without the user input/output being run:

if __name__ == "__main__":
    x = input('Enter an optionally signed integer: ')
    try:
        print('It was a valid int! atoi() returned:', atoi(x))
    except ValueError:
        print('It was an invalid int!)


Angularjs CRUD views, controllers, navigation

Ideally your code should be easily understandable where you read it.

The buttons says "Go to edit", then is better readable as ng-click="edit(Company). Also the Company is not a class, so general convention is not to capitalize it. But what is CRUDOperationEnum.Update? I don't see where it comes from, so I'd rather avoid it there. If it is already on your scope - it is already accessible inside your controller - no need to pass it again.

Also it looks strange that the same Button leads to different things - that may be confusing to the User.

I would not put different routes inside the same function. Either put clickable links to different routes directly inside your HTML, or use dedicated functions to update the location.


What you've written is more or less the standard implementation of spl_autoload().

This is an equivalent approach:

$paths = array(
    get_include_path(),
    ROOT . DS . 'library'  . DS . 'intranet'  . DS  . 'classes',
    ROOT . DS . 'application' . DS . 'controller',
    ROOT . DS . 'application' . DS . 'model',
    ROOT . DS . 'application' . DS . 'view',
);

// help system to find your classes
set_include_path(join(PATH_SEPARATOR, $paths));

// use standard auto loader
spl_autoload_register();

Using namespaces in your application would help a lot as well; for instance, in each of your controller classes you simply add:

namespace controller;

When you take a similar approach for models and views as well, you reduce above code to this:

$paths = array(
    get_include_path(),
    ROOT . DS . 'library'  . DS . 'intranet'  . DS  . 'classes',
    ROOT . DS . 'application',
);

set_include_path(join(PATH_SEPARATOR, $paths));

// use standard auto loader
spl_autoload_register();

// ...
$x = new controller\something();

Namespaces are converted to directories by spl_autoload() so you only need to set the application directory to make it work.


I think you're right to be suspicious of your test setup. Given your code, I imagine you're using #to_json/#as_json in your controllers already, which in effect reduces your test to:

assert_equal record.as_json, record.as_json

which doesn't prove much of anything.

It can also hide bugs. For instance, say your product attributes are name and an optional description, and you expect both to be saved. But your create action accidentally filters away description, so that's never set (and since it's optional, there's no validation error). But you're comparing the created record to itself, you'll never know that the description got lost on the way.

A stricter test would be to say:

attrs = attributes_for(:product)
assert_equal attrs, json_response_body.slice(*attrs.keys)

not pretty, but it's more comprehensive.

(Caveat: If your attributes_for method has some random or sequenced elements, you have to do some boring busywork to make sure it's only called once so you can use it for comparison purposes.)

But it's not totally comprehensive, though. Your response should probably also include added attributes like id, which aren't among the ones you specified in the request.

You could simply add a line like:

assert_equal Product.last.id, json_response_body[:id]

but if you have multiple server-computed attributes to check, this gets annoying too.

You could however use your current helpers for that part. I.e. check some attributes against the ones you posted (so you're sure they made it through), and the computed ones against the Product.last record. That'll help guarantee that the response JSON contains everything you expect it to contain.

All that being said, if your JSON becomes even slightly more complex (e.g. includes associated/nested records), the tests become trickier.

Similarly, your JSON could include values you'll have to check in yet another way. Maybe the JSON response contains something that's neither a saved attribute in the record, or a param you sent. Maybe it contains some random element that changes for each request (don't know why it would, but it's possible), you can't compare it to a known value. Instead you'll have to check it in some other way.

I'm pretty happy with this gem which lets you declare a "pattern" with varying degrees of specificity for the JSON you expect. E.g. you can check that the returned name is the specific string you expect, while id is simply an integer since its exact value isn't important but its type and presence are. Give it a look.


I see you have already applied using to the transaction.

But given that a new SqlConnection is created for each command, I would suggest wrapping it in a using statement as well.

private async Task<T> CommandAsync<T>(Func<IDbConnection, IDbTransaction, int, Task<T>> command)
{
    using(var connection = new SqlConnection(_connectionStrings.CurrentValue.MainDatabase))
    {
        await connection.OpenAsync().ConfigureAwait(false);
        await using var transaction = await connection.BeginTransactionAsync();
        try
        {
            T result = await command(connection, transaction, 300).ConfigureAwait(false);

            await transaction.CommitAsync().ConfigureAwait(false);

            return result;
        }
        catch (Exception ex)
        {
            await transaction.RollbackAsync().ConfigureAwait(false);
            _logger.LogError(ex, "Rolled back transaction");
            throw;
        }
    }
}


Better approach

First, if you got rid of all floating point and just use long, that would fix your inaccuracy problems.

Second, your loop is trying to find the greatest factor of the number that is a square.  But for a large number it will run for a long time because you check every number up to \$\sqrt n\$.  You can shorten the time by dividing any factors you find along the way.  For example, if 2 divides into \$n\$ 7 times, then \$2^3\$ can be factored out of the square root  and \$2\$ will remain under the radical.  I.e.:

If: \$n = 2^7 * m\$
\$\sqrt n = 2^3 \sqrt {2 * m}\$

If a factor divides an even number of times into your number, then it can be pulled out without leaving anything under the radical.

After you simplify for each factor, you keep going to find factors of \$m\$, which is smaller, so you only need to check factors up to \$\sqrt m\$.  You just need to keep track of the internal and external factors as you go.

In the worst case (if the number is prime), it will still take the same amount of time.  You could research factorization algorithms if you want something better.


1. Too Many Spreadsheet Reads and Writes

Would you be comfortable turning ws2.Range(ws2.Cells(2,1),ws2.Cells(lastRow22,80)) into an array? You can do that like this:

Dim arrEntireWs2() as Variant
With ws2
    arrEntireWs2 = .Range(.Cells(2,1),.Cells(lastRow22,80)).Value
End With

By cutting out all of those spreadsheet reads and writes, you'll be able to make all your checks and value changes much less expensively. Loop through the array like this (assuming from your code you want to loop through rows):

Dim lngArrEntireWs2Index as Long
For lngArrEntireWs2Index = LBound(arrEntireWs2,1) to Ubound(arrEntireWs2,1)
    <stuff you want to do here>
Next lngArrEntireWs2Index

And write it all to the spreadsheet one time like this:

With ws2
    .Cells(2,1).Resize(Ubound(arrEntireWs2,1), Ubound(arrEntireWs2,2)).Value = arrEntireWs2
End With

Using arrays will save you the most time, but one other habit I have is to do this:

2. VBA doesn't support short-circuit evaluation, so add it manually

Others will have different preferences since doing this makes your code uglier and thus less maintainable, but at the moment I currently prefer to implement manual short-circuit evaluation by breaking multiple-condition If And lines into several pieces. Thus:

If x = y And xDate = yDate And xQD = yQD And ws2.Cells(i, 82) = 0 And ws3.Cells(j, 27) = 0 Then

becomes:

If x = y Then
    If xDate = yDate Then
        If xQD = yQD Then
            If ws2.Cells(i, 82) = 0 Then
                If ws3.Cells(j, 27) = 0 Then
                    <do stuff>
                End If
            End If
        End If
    End If
End If

There's could be a more sensible way to deal with your logic that doesn't involve Arrow Code, but without more of your code available, it's hard for me to help further.


Binary tree from given Inorder and Preorder traversal

Recursive Code Should Be Recursive

Making build_tree recursive makes perfect sense. After all, pretty much everything you're going to do with trees is recursive, and this algorithm definitely lends itself well to recursion. However, your function isn't recursive. It calls a recursive function, and recurse takes a node - which obfusticates the algorithm. It would be much easier to understand if you just made it recursive - this goes a long way "to reduce the cognitive overload."

Let's start with the base case - if we have no ordering, we have no tree:

def build_tree(inorder, preorder):
    if not inorder:
        return None
    else:
        ### ??

Now, your enumerated steps for recursion seem to overcomplicate the algorithm. We want to go top-down! Given your example, when we start with:

in:  DBEAFC
pre: ABDECF

What's the root? A. The first element of pre-traversal is the root. Now we just need to find the left and right subtrees. To find that, we need to break up our in orderings into the root, left, and right sections:

in:  DBE|A|FC

So we have 3 nodes less than A and two nodes greater than A. We use the same sizes for the preorder:

pre: A|BDE|CF

And then recurse on those two parts. That is:

def build_tree(inorder, preorder):
    if not inorder:
        return None
    else:
        idx = inorder.index(preorder[0])
        return TreeNode(preorder[0],
                left=build_tree(inorder[:idx], preorder[1:idx+1]),
                right=build_tree(inorder[idx+1:], preorder[idx+1:])
                )

As a truly recursive solution, divided neatly into base and recursive cases, I find it much easier to follow the logic.

Debugging

Rather than write a level-by-level comparison, you should simply write an __eq__ method on TreeNode (or, alternatively, a much more correct __str__ or __repr__), and then use that to compare:

self.assertEqual(
    build_tree('DBEAFC', 'ABDECF'),
    TreeNode('A',
        TreeNode('B', TreeNode('D'), TreeNode('E')),
        TreeNode('C', TreeNode('F'))))

This is a more direct comparison. As is, you're comparing the levels, but there's not one unique tree that has three levels 'A', 'BC', and 'DEF'. For instance, what if your code erroneously returned one of these:

     A        |        A
   /   \      |     /    \
  B     C     |    B      C
 / \     \    |     \    / \
D   E     F   |      D  E   F

You'd think you succeeded. Always compare directly against what you want to get.


Generating a sequence number based on last item of a list

There are a couple of things you could do differently.

number - this variable is not necessary, you can return anytime
myList - if this is already a list then you don't need to copy it
lastNumber - this is initialized too early. It should be placed inside else
if - don't ommit the {}
!items.Any() and items.Any() - you don't need to check it twice and even with different results
: "" - this value is never used because you don't enter the first else if myList.Any() - in this case you use .Number and the only place where you use the resulting lastNumber is the first else
[1] - you should name this index
intitialNumber - define this as a constant

number = myList.FirstOrDefault(p => p.Id == id).Number;

You know that this might blow? If the list is empty then the Number cannot be read. You need either C# 6 for this or one more line of code.

Putting everything together gives:

const string intitialNumber = "Number#000001";

if (id == Guid.Empty)
{
    if(myList.Any())
    {
        const int someMagicValue = 1;
        var lastNumber = myList.Last().Number; // Last is O(1) for IList
        var nextNumber = int.Parse(lastNumber.Split('#')[someMagicValue]) + 1;
        return = $"Number#{nextNumber:D6}";
    }
    else
    {
        return intitialNumber;
    }
}
else
{
    var first = myList.FirstOrDefault(p => p.Id == id);
    return first != null ? first.Number : intitialNumber;

    // C# 6
    // myList.FirstOrDefault(p => p.Id == id)?.Number ?? intitialNumber;
}


Split all images over x amount of pages with $_GET

$total_images = 0;
foreach ($all_pictures as $img_total) {
    $total_images++;
}

This could be just

$total_images = ($all_pictures === false) ? 0 : count($all_pictures);

or

if ($all_pictures === false) {
    $total_images = 0;
    $success === false;
} else {
    $total_images = count($all_pictures);
}

The glob function returns an array, so you can just do the normal array operations on it.  You only have to check for an error.  I'm not quite sure what your original code would have done if there was an error.  You might want to check later so you can say something like "Oops, there was an error looking for images!" rather than "No images".

if ($page <= -1) {

This is a weird way to write this.  First, what would you do if page were set to -.5 here?  Second, what does a page value of 0 mean?  You are defaulting to 1, so it would seem that you are 1-indexed.  So why accept anything less than 1?  Consider

if ($page < 1) {

That eliminates all the invalid values below the range.

For much the same reason,

$page = array_key_exists('page', $_GET) ? $_GET['page'] : 1;

should probably be

$page = array_key_exists('page', $_GET) ? intval($_GET['page']) : 1;

Get parameters can be user input, so you should sanitize them to what you expect.

    echo "

No pictures to be displayed.

";

This is an odd way to write a string in PHP.  Using double quotes indicates that there is a value to interpolate in it.  But you don't have one here.  This could just as well be

    echo '

No pictures to be displayed.

';

or

?>

No pictures to be displayed.

<?php

Consider moving the whole thing into a function or even a class.

class Page_Handler {

    private $image_count;

    private $success = true;

    private $all_pictures;

    private $max_page_number;

    private $page;

    private $images_per_page = 30;

    function __construct($path = 'crossles/*.jpg') {
        $this->all_pictures = glob($path);
        $this->success = $this->parse();
    }

    private function parse() {
        if ($this->all_pictures === false) {
            return false;
        }

        $this->image_count = count($this->all_pictures);
        $this->max_page_number = ceil($this->image_count / $this->images_per_page);

        $this->page = array_key_exists('page', $_GET) ? $_GET['page'] : 1;
        if ($this->page < 1 || $this->page > $this->max_page_number) {
            return false;
        }

        return true;
    }

There would also be getters and possibly other helper methods.  I'll leave those as an exercise for the reader (mostly because I'm lazy).  Note that you could differentiate between a failure to load the images and an invalid page.  Those are two separate problems and you may want to message them differently, as one is a server error and the other is user error.  Page number out of range is often a problem that the user can fix.

I changed the names of some of the variables.  I generally use a system where plural names indicate collections and singular names indicate scalars.  You don't have to follow the same system, but it's the one I use when writing code.

One of the differences here is that the parse code doesn't have to keep processing after an error.  At the first error, it returns failure.


Adding credentialsID node to SVN location nodes

You can take a few shortcuts here and there, but overall it's not bad.

My comments:

You don't need both open and close when you just want to read everything; File.read(filename) will work just fine
I'd like to see some constants or command line arguments used in place of the many hardcoded strings. E.g. tag names and xpaths could be constants, while the project directory's path and credentials string could be provided from the command line.
Either one would make the script more maintainable and reusable.
Don't insert the new credentials tag as a raw string; use doc.create_element instead
The if...else isn't strictly necessary; you can just look for and remove any existing credentialsId tags, and then insert your own (though that may mess with the file's whitespace a little)
The Ruby convention is to use 2 spaces of indentation, not 4 (and not tabs)

My Nokogiri is a bit rusty (no pun intended1), but I imagine this should work too.
I've left the project path and the credentials string hard-coded because I don't know if you'll want those from ARGV or something.

require 'nokogiri'

CONFIG_FILE_GLOB = ".jenkins/jobs/*/config.xml"
LOCATION_XPATH = "/project/scm/locations/hudson.scm.SubversionSCM_-ModuleLocation"
CREDENTIALS_TAG = "credentialsId"

Dir["somepathhere/#{CONFIG_FILE_GLOB}"].each do |filename|
  doc = Nokogiri::XML(File.read(filename)) # simplified file read

  # create a credentials element ahead of time
  credentials = doc.create_element(CREDENTIALS_TAG, "somevalue")

  doc.xpath(LOCATION_XPATH).each do |location|
    location.xpath(CREDENTIALS_TAG).remove # remove any existing credentials
    location.add_child(credentials.clone) # insert a new one
  end

  File.write(filename, doc.to_xml) # slightly simpler file write
end

Note that in order to insert the new element properly, we must always insert a clone. If you just use add_child(credentials), and there are multiple locations, the element will end up in the last of those locations, because add_child will add or re-parent the element. So the first add_child call would add it, and subsequent ones would move it since it's the same object. Hence, the need for clone.

1) because nokogiri means hand saw


Your program is great in that it does the job, but there are some ways to improve the implementation significantly.

As a design decision, some programs need to process data as it is being captured from the inputs. This program is not one of those, so it makes sense to make the input and processing steps very discrete.

Then, using some of the more modern Java features (the ones that have been there since Java7), you should use a try-with-resources statement to manage the input exceptions.

I would also recommend creating a container and calling method to handle the two-part inputs (the key, and the encrypted text).

Sometimes it's easier to show, than to tell. Let's start with the core decode routine. The two methods should make sense:

public static final String decode(final int key, final String encoded) {
    final int len = encoded.length();
    // prepare a space to store the decoded value
    final char[] decoded = new char[len];
    for (int i = 0; i < len; i++) {
        // use i+1 here since the algorithm has the first char at position 1, not 0.
        decoded[i] = decodeChar(encoded.charAt(i), i + 1, key);
    }
    // convert the decoded chars back to a String.
    return new String(decoded);
}

private static char decodeChar(final char encoded, final int position, final int key) {
    // modulo 26 eliminates multiple wrap-arounds.
    int rotate = (3 * position + key) % 26;
    // apply the rotation shift to the input
    int decval = (encoded - 'A') + 26 - rotate;
    // use another % 26 to keep the letters in range.
    return (char)('A' + (decval % 26));
}

Note how using the function extraction makes the code simpler?

Now, how to get the input in to that function? That would be simple:

public static void main(String[] args) {
    CypherText input = getEncoded();
    String decoded = decode(input.getKey(), input.getText());
    System.out.println("Decoded: " + decoded);
}

Note, that CypherText class is new.... but you can clearly see how the decode(...) would fit. Biw is the CypherText done?

private static final class CypherText {
    private final int key;
    private final String text;

    public CypherText(int key, String text) {
        super();
        this.key = key;
        this.text = text;
    }

    public int getKey() {
        return key;
    }

    public String getText() {
        return text;
    }

}

public static CypherText getEncoded() {
    try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))){
        int k = Integer.parseInt(reader.readLine());
        String word = reader.readLine();
        return new CypherText(k, word);
    } catch (IOException e) {
        e.printStackTrace();
        return new CypherText(0, "");
    }
}

I put this in an Ideone here


Looks like a lot of extra code for very little gain, considering you can simply call iter() on an iterable object to return an iterator:

>>> c = C()
>>> i = iter(c)
>>> next(i)
0
>>> next(i)
1
>>> next(i)
2
>>> c.state
1

Also, note your new class C can have more than one iterator, with only 1 "state".  The first iterator is created automatically by the constructor, for use with the next(c) call.  Additional iterators are created each time you start looping over c, since iter(c) gets called and returns a new generator!

>>> c = C()
>>> next(c)
0
>>> print(next(c), c.state)
1 0
>>> print(next(c), c.state)
2 1
>>> for x in c: print(x, c.state)       # Start a new iteration
...
0 1
1 0
2 1
3 2
>>> print(next(c), c.state)             # Continue original iteration
3 2
>>> next(c)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 9, in __next__
StopIteration


Determine if a string only contains repetitions of a substring

The code is relatively concise and easy to read. Here are some points that could be improved:

A general thing is the amount of commenting, you should generally resort to comments only when it's hard to make the code self-explanatory. You don't really need to comment each line of the code.
stringCopy = (stringOrig+'.')[:-1] # copy string contents
You can make a copy this way instead stringCopy = stringOrig[:].
To make the code more readable, you can create a function that shifts a string n characters. This will really help make the code more readable.
The else keyword after the for loop is not needed since you return anyway if you didn't finish the loop. else is usually used with break in the for loop.
The name of the function could be slightly improved, maybe consists_of_repeated_substrings. This is longer but is very easy to understand.
A note on performance: your algorithm creates a copy of the original string in each iteration. This works fine for shorter strings, but if you wanna make it more efficient you can consider matching the string without making a shifted copy of it.

Incorporating these comments you could rewrite the code as follows:

def shifted_string(str, n):
  return str[n:] + str[:n]

def consists_of_repeated_substrings(str):
    '''
    Checks whether a string consists of a substring repeated multiple times.
    Ex. 'testtesttest' is the string 'test' repeated 3 times.
    '''

    # The string can only contain equal substrings if you can shift it n
    # times (0 < n < len) and get the same original string.
    for i in range(1, len(str)):
        if shifted_string(str, i) == str:
            return True
    return False

A clever algorithm for doing the same thing is as follows:

double_str = (str + str)[1:-1]
return double_str.find(str) != -1

The idea is similar to yours, so I will leave understanding it as an exercise.


Lispy code? Sum multiples of 3 or 5 up to 1000

Conditions
In general something like "if a then true else false" can be simplified as "a". So your first function could be simplified as:
(defun multiple-of-3-or-5p (n)
  "predicate for multiple of 3 or 5"
  (or (= 0 (rem n 3)) (= 0 (rem n 5))))

Cond with only two cases
A cond with only two cases is written preferibly as an if. For instance:
(defun sum35 (n)
  "sum all multiples of 3 or 5 up to n (including n)"
  (if (= n 0)
      0
      (+ (if (multiple-of-3-or-5p n) n 0) (sum35 (- n 1)))))

Use the operators 1+ and 1- instead of adding or subtracting 1
The usual way of writing (- n 1) is (1- n).
Recursion and Iteration
Common Lisp has a very powerful iteration construct, loop (see for instance here for a detailed
discussion), that can make
simpler to write cases like in the last two functions. For instance:
(defun sum35 (n)
  "sum all multiples of 3 or 5 below n"
  (loop for i below n
        when (multiple-of-3-or-5p i) sum i))

; (sum35 1000)

Analogously,
(defun predicate-sum35 (predicate n)
  "sum integers up to n (including n) that match the predicate"
  (loop for i below n
        when (funcall predicate i) sum i))

; (predicate-sum35 #'multiple-of-3-or-5p 1000)

(note the use of #' to get a function).
Finally, to answer your last two questions:

The “natural” way in Common Lisp is to exclude the last value, as in all predefined functions that specify a range (for instance to get a substring with the first two characters of "foo", you can write (subseq "foo" 0 2), that returns "fo",
with the index starting from 0).

A primitive function does not exists. You can obtain a list of this kind very easily by using loop, for instance: (loop for i below 1000 collect i).

Edited
As suggested in a comment by @slepic, the algorithm is not the best one, since it checks for all the numbers from 0 to n, while one could simply sum directly all the multiples. Here is a possible solution:
(defun sum35 (n)
  (flet ((sum-m (k)
           (loop for i from k below n by k sum i)))
    (+ (sum-m 3) (sum-m 5) (- (sum-m 15)))))

Or you can use a direct formula, like that in another comment.


Handling two datepickers in a form with angularjs

Would something like that work better?

$scope.$watchGroup(['$scope.EndDateFrom', '$scope.EndDateTo'], function () {
  const FORMAT = 'MM/dd/yyyy';
  const dates = [];

  if (!angular.isUndefined($scope.EndDateFrom))
    dates.push($filter('date')(new Date($scope.EndDateFrom), FORMAT));

  if (!angular.isUndefined($scope.EndDateTo))
    dates.push($filter('date')(new Date($scope.EndDateTo), FORMAT));

  const expression = `expr://${dates.join(' and ')}`;
  console.log(expression);
  return expression;
});

Array.join() will help avoid branching. In your case we don't really save any branches, but in more complex cases it may save a lot.
I left angular.isUndefined(...) untouched since I don't know how different it is from the native JavaScript's analogue, but if it's equivalent you may want to use $scope.EndaDateFrom !== undefined instead.
Original return console.log is counter-intuitive. Is it returning a value, or logging it to the console, or both? I split that into two separate operations.
FORMAT is a reusable constant.
expr://${dates.join(' and ')} uses string interpolation to create result object.

Update 1

`expr://${dates.join(' and ')}`

in older versions of JavaScript should be replaced with a classic equivalent

'expr://' + dates.join(' and ')


Back end validation as front end validation

You should separate it in different functions.
Here is how you can have validation in different functions and use it in both places - for creating posts and for front-end validation. Besides you should extract this validation logic elsewhere, it's bad to put such logic in your controller.

public function postValidateStore()
{

    $requestValidation = $this->validateStore();

    if($requestValidation !== true){

       die($requestValidation);
    }

    die(json_encode(['success' => 1]));

}

/**
 * @return mixed
 */
public function postStore()
{

    $requestValidation = $this->validateStore();

    if($requestValidation === true){

        // create new user in DB
        $this->createPostFromParams($this->formParams);

        Session::put('success', 'Successfully created a post.');

    } else {

        Session::put('failure', 'Error creating post.');
    }

    return redirect('posts');
}

/**
 * @return bool|false|string
 */
private function validateStore()
{

    $parameters = $this->formParams;
    $validationRules = [
        'title'     => 'required|alnum',
        'content'   => 'required',
    ];

    // if validation fails return back with error messages
    if ($this->validatorFails($parameters, $validationRules)) {

        return json_encode(['errors' => $this->getValidatorErrors($validationRules)]);
    }

    return true;
}

function isValid() {

var formIsValid = false;
var fields = jQuery.param({
title: $('#post-title').val(),
content: $('#post-content').val()
});

$.ajax({
    async: false,
    type: "POST",
    url: "/posts/ValidateStore",
    data: fields,
    dataType: 'json',
    success: function(result){

        if(typeof result.success == "undefined"){

            var messages = [];

            $.each(result.errors, function( index, value ) {
                messages.push('
' + value);
            });

            bootbox.alert("" + messages + "");

        } else {

            formIsValid = true;
        }

    }

});

return formIsValid;
}


Automating a set a of weekly reports, including graphs and delivery of reports

I got this done by making a second dictionary, which takes locations as keys and values as list of sublocations
dfs = dict(tuple(data.groupby('location')))
dfss = dict(tuple(data.groupby('sublocation')))

dd = {}

for key, value in dfs.items(): #dictionary is made of groupby object, key is
                               #location, value is datafram
    a = []
    dee={}
    for i in value['sublocation']:
        if i in a:
            pass
        else:
            a.append(str(i))
    dee = {key:a}
    dd.update(dee)
for key, value in dfss.items():
    try:
        for k, v in dd.items():
            if key in v:
                dur=str(k)
            else:
                pass
    except:
        pass

Then in the next cell,
for key, value in dfss.items():
    try:
        for k, v in dd.items():
            if key in v:
                dur=str(k)
            else:
                pass
        #tmp = value[value['sublocation']==i]
        sns.set(style='white', palette=sns.palplot(sns.color_palette(ui)), font='sans-serif')

I think I can make the overall script run even faster by employing more regex expressions for filtering the dataframe in various steps.
This set-up works because I can save the files according to the key's from the two dictionaries. It allows me to save the nearly 375 files automatically. I use another script to move the files to their respective folders.
plt.savefig("path/{0}/{1} @ {2}.pdf".format(dur,dur,key), bbox_inches = 'tight')

Having a slightly different case, take three data sets and make mini data sets based on some column such as location
oct_dict = dict(tuple(oct.groupby('location')))
oct2_dict = dict(tuple(oct2.groupby('location')))
for k, v in oct_dict.items():
    for k2, v2 in stu_dict.items(): #replace with v2 = stu_dict[k] if you know for sure it exits
        for k3, v3 in oct2_dict.items(): #replace with v3 = oct2_dict[k] if you know for sure it exits
            if k == k2 and k == k3: #can delete this if not needed
                plt.close('all')
                with PdfPages(r'path\{}.pdf'.format(k)) as pdf:


Randomly generate spelling mistake in string

Break it down into one function that randomly repeats a character, and another function which randomly executes that function 50% of the time:

function repeatRandomChar(str) {
  var i = Math.floor(Math.random() * str.length);
  return str.slice(0, i+1) + str.slice(i);
}

function randomTypo(str) {
  return Math.random() > 0.5 ? repeatRandomChar(str) : str;
}

Now you can just call randomTypo('Stack Overflow') 10 times to reproduce your sample data.

Note also that the original code has needless multiplication, in that

 Math.random() > 0.5

is equivalent to:

 (Math.random() * 10) >= 5


Below I've written up an implementation of a recursive bubble sort that addresses the main concerns you mentioned. The areas your code can be improved matches what you instinctively pointed out in your bullet points.

Whenever you use a List or MutableList in Scala remember that it is in fact a linked list and so accessing an element takes linear time. This could add a significant number of operations to an implementation of bubble sort that utilizes a List. As a substitute I used an Array which offers constant time access to elements. It is also worth mentioning that the Array container is mutable in Scala even if it is declared as a val.

We can kill two birds with one stone by rewriting the while loop as a recursive procedure. The two birds are while and var and our trusty stone is recursion.

def bubbleSort(arr: Array[Int]): Array[Int] = {

  val hasSwaps =
    for {
      i <- (1 until arr.length)
    } yield {
      if (arr(i - 1) > arr(i)) {
        val tmp    = arr(i)
        arr(i)     = arr(i - 1)
        arr(i - 1) = tmp
        true
      }
      else false
    }

  if (hasSwaps.reduce(_ || _)) bubbleSort(arr)
  else arr
}


PHP is not my area of expretise, so just some generic notes:

The function create a new MySQL connection on every call which could be a bottleneck in your application. You could use persistent connections with a p: prefix but others usually suggest PDO as a better alternative of database handling.
The $the prefix on most of the variables seem redundant (it doesn't add too much to them), I'd avoid it.
If you intended to return the original value when its not text, long, int etc. you should make it explicit with a default case inside the switch statement. If not, throw an exception in the default case and sign the error. (The Pragmatic Programmer: From Journeyman to Master by Andrew Hunt and David Thomas: Dead Programs Tell No Lies.)
case "text" and case "date" contains the same logic, you could use fall through there too.


Providing a consistent interface for inRange function over modded values

If you really need to present the boolean parameters in your client API I would do that as follows

private boolean inRangeBothInclusive(long start, long end) {
    if (start == end) {
        return this.value == start;
    }
    else if (start < end) {
        return start <= this.value &&
               this.value <= end;
    }
    return !(end <= this.value &&
             this.value <= start);
}

public boolean inRange(long start, long end, boolean startInclusive, boolean endInclusive) {
    start = startInclusive ? start : start + 1;
    end = endInclusive ? end : end - 1;
    return inRangeBothInclusive(start, end);
}


Splitting a string by spaces without space-splitting elements in double-quotes

The best way to do what you want with the standard library would be shlex.split():

>>> import shlex
>>> s = r'  "C:\Program Files (x86)\myeditor" "$FILEPATH" -n$LINENO "c:\Program Files" -f$FILENAME -aArg2'
>>> shlex.split(s)
['C:\\Program Files (x86)\\myeditor', '$FILEPATH', '-n$LINENO', 'c:\\Program Files', '-f$FILENAME', '-aArg2']

Note that the quotes are not retained.


The splitting / partitioning makes this very complicated and hard to follow. Instead of splitting and then putting the pieces back together, it would be vastly simpler to replace with a regex, for example:

import re

def set_mode(mode, iface, interfaces):
    """
    Set the mode for the specified interface
    :param mode: 'dhcp' or 'static'
    :param iface: name of the interface, for example eth1, eth2, ...
    :param interfaces: content of /etc/network/interfaces
    :return: updated content, to be saved in /etc/network/interfaces
    """
    iface_prefix = 'iface {} inet '.format(iface)
    iface_entry = iface_prefix + mode
    if iface_prefix in interfaces:
        interfaces = re.sub(iface_prefix + r'.*', iface_entry, interfaces)
    else:
        interfaces += '\n' + iface_entry
    return interfaces

For your sample file, the following gives me the same output with the original method and this new one:

with open('./interfaces') as fh:
    content = fh.read()
    print set_mode('static', 'eth8', content)
    print '---'
    print set_mode('dhcp', 'eth8', content)
    print '---'
    print set_mode('dhcp', 'eth1', content)

Coding style

The original code has several issues that violate PEP8, the official coding style guide of Python:

Use snake_case for function and variable names (that's why I renamed setMode to set_mode
Put spaces around operators: a=something instead of a = something
A docstring is strongly recommended for the set_mode function


As usual, a few points to complete what has already been said:

An std::ifstream is implicitly constructed with std::ios_base::in. No need to explicitly pass it to the constructor.
You don't need to explicitly call file.close(): since you are not using it again before the end of the scope where it has been declared, it will automagically be closed when destructed. That's the power of RAII! :D
You have two functions supposed to be reusable in other projects, mean and stdDev. The fixed size defined outside of the functions will prevent them from being reusable. You could use std::array instead and have this signature for mean:

template<std::size_t N>
double mean(const std::array<double, N>& arr);

You could even templatize the type so that you can work with something else than double. Morevoer, using std::array would allow you to use a clean range-based for loop:

template<typename T, std::size_t N>
auto mean(const std::array<T, N>& arr)
    -> T
{
    T sum{}; // generally performs zero-initialization
    for (auto&& val: arr)
    {
        sum += val;
    }
    return sum / N;
}

Alternatively, you could use the function above and compute the sum with std::accumulate:

template<typename T, std::size_t N>
auto mean(const std::array<T, N>& arr)
    -> T
{
    return std::accumulate(std::begin(arr), std::end(arr), T{}) / N;
}

This one is more subtle and I like to bother people with it, but return is not a function, so don't put parenthesis around what you return. In your case (in most cases actually), it will work as expected, but if your return type is decltype(auto), then you may have surprises. Consider the following example:

auto foo()
    -> decltype(auto)
{
    int res = 0;
    // do stuff with res
    return (res);
}

Int this particular case, the compiler will deduce the return type int& because you returned a parenthesized identifier and so you will be returning a reference to a temporary, which isn't what you want (and which is really bad). Had you dropped the parenthesis around the return expression, then the deduced would have been the expected int. Bottom line: don't put parenthesis around the returned expression if you want to avoid surprises.


Query Rails 3 Active Record Fetch associated model based on conditions

User.joins(:addresses).where(["addresses.city like ? OR addresses.address_line like ?", '%jap%', '%jap%'])

or

a = Address.arel_table
User.joins(:addresses).where(a[:city].matches('%jap%').or(a[:address_line].matches('%jap%')))


Want to check if I am using PDO correctly

Your code is fine. Really. However, it does show some lack of understanding the true benefits and power of prepared statements.
I'm also not convinced you fully understand how the PDOStatement::bindParam method works. Allow me to explain:

A prepared statement is sent to the DB server as a string, with the placeholders that will be replaced with the query values. This query string is already parsed, compiled and optimized at this point, in case it is possible, the result is already being stored in a temp-table, too.
At this point, you have a resource handle to this prepared statement, assigned to the variable $stmt. The really neat thing is that this statement can be used as much as you like, each times specifying new parameters, for example:

$stmt = $pdo->prepare('SELECT age, sex, nationality FROM people WHERE name = :name');
$names = array(
    'Frank',
    'Lisa',
    'John',
    'Jane'
);
$bind = array(
    ':name' => null
);
$personalia = array();
foreach ($names as $name)
{
    $bind[':name'] = $name;
    $stmt->execute($bind);
    $personalia[$name] = $stmt->fetch(PDO::FETCH_ASSOC);
}

As you can see, I only call prepare once, but execute 4 distinct queries. The advantage then, is simple: the query only has to be parsed, compiled and optimized once, and in some cases, the result set can be pre-fetched in such a way that you'd never need to search through the entire tbl.
Bottom line: prepared statements not only provide security against injection, it often outperforms regular queries, too.

You may have noticed how I used execute(array), and not bindParam, like your code does. Though sometimes I do use bindParam, I find it best to avoid this method when I can, in favour of execute(array), or if needs must PDOStatement::bindValue. As to why, we need to look at the method's signature:

public bool PDOStatement::bindParam ( mixed $parameter , mixed &$variable [, int $data_type = PDO::PARAM_STR [, int $length [, mixed $driver_options ]]] )

The $parameter argument is the Parameter identifier, or placeholder. In this case, the string :name.
The $variable argument is not the value that will be used in the query but if you look closely, the parameter is passed by reference: &$variable <-- that's what the & operator is for. Using it yourself is, arguably, bad practice, but no matter how you look at it, it does make your code harder to read and maintain. Imagine I did this, for example:

$stmt->bindParam(':name', $name);
while($name = array_pop($names))
{
    $stmt->execute();
}

This should work just fine, but what if $names changes, or someone re-assignes $name at some point as the while loop becomes more complex? You end up with quite error-prone code.

The advantage of this method, then, is the third parameter: $data_type. It allows you to specify the data-type you want to pass to the query. using the PDOStatement::execute(array) method, all parameters will follow the default behaviour, which means they'll be passed as strings. MySQL is capable to cast those string values to the appropriate types most of the time. As always, a cast implies some overhead, but it's highly unlikely that this will be a bottleneck and most of the time, this'll do just fine. It's an old quote, but keep in mind that premature optimization still is the root of all evil. Be that as it may, when dealing with values like NULL or booleans, it can sometimes come in handy to pass specific types.
Still, for those cases, PDOStatement::bindParam shouldn't be the default method to turn to. As you can see from the method's signature, it's powerful, but complex. Bugs and complexity go hand in hand, so let's look at another method, that does allow you to specify specific types: PDOStatement::bindValue. This method does the same thing as PDOStatement::bindParam, but does not use references (that's one less source of woes you don't have to think about), and doesn't take as many arguments:

public bool PDOStatement::bindValue ( mixed $parameter , mixed $value [, int $data_type = PDO::PARAM_STR ] )

If all you need is to specify a specific type, then this method is to be preferred: it allows you to specify all the types, but without the added risk of passing references around.

To recap: Unless you're looking to optimize your code to save every millisecond you can, or you need to pass some driver-specific options, I'd use bindValue rather than bindParam. Which, again, makes your code less error-prone and generally easier to maintain.

In short, then, and applied to your specific code, I'd recommend you write something like:

$stmt = $pdo->prepare(
    'SELECT * FROM DB.GameReg WHERE hash = :user'
);
$stmt->execute(
    array(
        ':user' => $_COOKIE['Logged']
    )
);
$gameReg = $stmt->fetch(PDO::FETCH_ASSOC);

Which gives you spacious, easy to read and maintain code.
If you want to be able to specify the type, and need nothing more, then use bindValue.

If you want to call a stored procedure, that uses an INOUT argument, then you have to resort to `PDOStatement::bindParam:

$stmt = $pdo->prepare(
    'CALL your_sp(:io)'
);
$was = $io = 'hello';
$stmt->bindParam(
    ':io',
    $io,
    PDO::PARAM_STR | PDO::PARAM_INPUT_OUTPUT,//string, inout argument
    6
);
//example:
$stmt->execute();
echo 'Argument was: ', $was, PHP_EOL, 'Now is: ', $io;

Could echo something like:

  Argument was: hello
  Now is: world


Output

It would be nice if the usernames were clickable.  You can achieve that using the magic [User Link] column.  It might make the query fail to complete on a large site like Stack Overflow, though.

It's weird that you cast(VotesPerDay as int) and cast(LastAccessDate as date) for sorting.  Why not sort by VotesPerDay (without rounding) and LastAccessDate directly?

Implementation

The names of your CTEs, sub and agg, don't mean anything to me.

select distinct should be replaced with a smarter join wherever possible.  If you look at the execution plan, you'll see that it estimates that there are 3 million rows, when there are actually just 26740 Code Review users.  The estimated subtree cost is 1048.  In comparison, my query below has an estimated subtree cost of 5.7 and 27580 rows for Code Review, and those numbers scale depending on the size of the site.

Your agg CTE has a TotalVotes > 0 as a WHERE condition.  It would probably be more efficient to test for (UpVotes > 0 OR DownVotes > 0), because that has a possibility to take advantage of an index (though we don't know whether the Users table actually has such an index in SEDE).

Suggested solution

WITH FilteredUsers AS (
    SELECT *
         , DATEDIFF(day, CAST(CreationDate AS DATE), CAST(LastAccessDate AS DATE)) AS MembershipDays
        FROM Users
        WHERE
            Id > 0 AND
            (UpVotes > 0 OR DownVotes > 0)
), PostCounts AS (
    SELECT OwnerUserId
         , COUNT(*) AS PostCount
        FROM Posts
        GROUP BY OwnerUserId
)
SELECT Id
     , DisplayName
     , CreationDate
     , LastAccessDate
     , CASE WHEN MembershipDays = 0 THEN 1 ELSE 0 END AS IsOneTimer
     , MembershipDays
     , ROUND((UpVotes + DownVotes) / CASE WHEN MembershipDays = 0 THEN 1 ELSE CAST(MembershipDays AS DECIMAL) END, 3) AS VotesPerDay
     , COALESCE(PostCount, 0) AS PostCount
     , Reputation
     , UpVotes + DownVotes AS TotalVotes
     , UpVotes
     , DownVotes
    FROM FilteredUsers
        LEFT OUTER JOIN PostCounts
            ON FilteredUsers.Id = PostCounts.OwnerUserId
    ORDER BY PostCount
           , VotesPerDay DESC
           , LastAccessDate DESC
           , TotalVotes DESC
           , Reputation
           , IsOneTimer
           , CreationDate;


Instead of searching for the value that belongs at Queue[i] to swap it there, just swap the value that is there to where that belongs:
def MinimumSwaps(Queue):
    MinSwaps = 0
    for i in range(len(Queue) - 1):
        while Queue[i] != i + 1:
            j = Queue[i] - 1
            Queue[i], Queue[j] = Queue[j], Queue[i]
            MinSwaps += 1
    return MinSwaps

This improves the performance to \$O(1)\$ for using a value instead of the \$O(n)\$ for searching. And thus total performance to \$O(n)\$ instead of your original \$O(n^2)\$. Still using only O(1) extra space.


I have couple suggestions:

Separate Logic

I would separate lookup and modify logic. Add a function to remove element and call it from this one leaving in this one only logic to lookup an item.

public void remove(Node<T> data) {
    if (!data) {
        throw new NoSuchElementException();
    }

    // Removing logic here
    ...
}

public void remove(T data) {
    return remove(search(data));
}

public Node<T> search(T data) {
    for (Node<T> current = this.head; current != null; current = current.getNext()) {
        if (current.getData().equals(data)) {
            return current;
        }
    }

    return null;
}

Simplify Checks

I think this should work and cover all your cases, no?

// If this is head of the list
if (previous == null) {
    this.head = next;
}
else {
    previous.setNext(next);
}

// If this is tail of the list
if (next == null) {
    this.tail = previous;
}
else {
    next.setPrevious(previous);
}


PHP & MySQLi Login Script - Is it safe from Injection?

There's no need for the $user variable (it's already in $myusername) so don't query for it either.

Please, deal with the $previous = $_SERVER['HTTP_REFERER']; now. You don't want to allow a malicious user to edit the HTTP headers you send.

What do you plan to do if any of the database calls fail? You don't seem to be checking for nor handling that. Also, it's best to have the exact same behavior on "invalid username" as well as "password supplied does not match". I'm not sure if your code does that or not.

I didn't think people usually put spaces around the -> method call operator, but at least be consistent with your spacing.


JavaScript / Express error handling w/ promises

There's a big problem here.  getUserByEmail() can either return a promise or throw synchronously which is a bad design and very unfriendly for the caller.  Instead, you want any synchronous errors to be returned as a rejected promise.

The beginning of your code should be changed from this:

// SERVICE / MODEL LOGIC
getUserByEmail() {
  if (!this._model.email) {
    throw new VError('Missing email.');
  }

to this:

// SERVICE / MODEL LOGIC
getUserByEmail() {
  if (!this._model.email) {
    return Promise.reject(new VError('Missing email.'));
  }

The other throw statements are what you do from a .then() handler to turn the promise chain into a rejected promise.  You could also do return Promise.reject(...), but throw works just as well.


You end two functions like this -
End Function`

Which might be a typo, but it causes errors.

Readability
Indentation
Indenting your code makes it a lot easier to follow and maintain
Sub findLast2()
    '<snip>
    Dim i As Integer
    Dim arr() As Variant
    Set ws = Sheet1
    LC = lColCount(ws)
    i = 1
    ReDim arr(1 To LC)
    Do While i <> LC + 1
        LR = lRowCount(ws, i)
        arr(i) = LR
        i = i + 1
    Loop
    LR = Application.WorksheetFunction.Max(arr())
    Dim Res As Variant
    For Each Res In arr()
        Debug.Print Res
    Next Res
    '<snip>
End Sub

Comments
"code tell you how, comments tell you why". The code should speak for itself, if it needs a comment, it might need to be made more clear. If not, the comment should describe why you're doing something rather than how you're doing it. Here are a few reasons to avoid comments all together.
Naming
Variable names - give your variables meaningful names.
What is LC? lastColumn. LR? lastRow What is vArr() an array of?
Additionally, Standard VBA naming conventions have camelCase for local variables and PascalCase for other variables and names.
Structure
If possible, you should pass argument ByVal rather than ByRef.
You also declare all of your subs and functions as Public by default, so call them public or private to ensure it's clear
Public Sub FindLastRow()
Private Function ReturnColumnLetter(ByVal columnNumber As Long) As String

and so on.


I have a few issues with in your code:

Consistency in naming - use either camelCase or not_camel_case but don't
mix
consistency in braces.  The opening brace for a function goes in the first
column.
word_start_index and word_end_index should take a const parameter
word_start_index is the same as strspn(string, " "); or if you are also
looking for punctuation, strspn(string, " \t\n.,;:");
word_end_index - as for word_start_index but use strcspn (note the
'c')
word_end_index as a function (ie not in your context) fails for an empty
string or a string starting with a space  (it returns the char before the
string starts).
variable test in main() is misnamed. I would prefer something that shows it
is a string.
the test while (test != '\0') in main() is wrong - should be *test !=
'\0'.
Your loop always exits from the break
no return or parameters in main()

Also, arguably the position of the stars in your pointers is wrong.  I prefer char* p to be written char *p, which makes it clear that it is p that takes the star. Consider code such as char* a, b;. This is bad because it gives the impression that b is a pointer.


public static string ToHtml(this string s, bool nofollow)
{
    s = HttpUtility.HtmlEncode(s);
    string[] paragraphs = s.Split(new string[]{"\r\n\r\n"}, StringSplitOptions.None);
    StringBuilder sb = new StringBuilder();
    foreach (string par in paragraphs) {
        sb.AppendLine("
");
        string p = par.Replace(Environment.NewLine, "
\r\n");
        if (nofollow) {
            p = Regex.Replace(p, @"\[\[(.+)\]\[(.+)\]\]", "$1");
            p = Regex.Replace(p, @"\[\[(.+)\]\]", "$1");
        } else {
            p = Regex.Replace(p, @"\[\[(.+)\]\[(.+)\]\]", "$1");
            p = Regex.Replace(p, @"\[\[(.+)\]\]", "$1");
            sb.AppendLine(p);
        }
        sb.AppendLine("
");
    }
    return sb.ToString();
}

In general, if you find yourself with a variable that you pass around through a bunch of static methods (like nofollow), it may be time to make those methods not static.


Making a script file to perform maintenance

This is awesome:

Option Explicit

By doing that you've forced yourself to declare every variable you use; making a typo in a variable's name will stop the code from being executable, which is a very good thing. Well done!

This is less awesome:

Dim retVal

Declaring variables you're not using is, well, useless. Use them or kill 'em.

Then there's this:

On Error Resume Next

It basically says "look, I don't care what happens, just run every single executable statement you see and whatever happens happens" - so if any command raises an error, you completely ignore it and move on: if CCleaner.exe doesn't exist or the /AUTO option isn't valid for that command, your script will never even know.

You could log it in a text file that you can consult and clean up when you check out mom's computer, or simply output a message that contains the description of the error, for example:

On Error GoTo ErrHandler

'...script...

WScript.Quit

ErrHandler:
WScript.Echo "Unexpected error: " & Err.Description
Resume Next

This is minimal error handling - it does pretty much exactly the same thing (it just keeps going), except if there's an error it will output an error message before resuming with the next instruction.

That "jumping around" isn't ideal though - when there's an error with a command, execution jumps to ErrHandler, prints the error, and the jumps back to the instruction immediately following the line that raised the error. There's a better way.

Make yourself a Function. The advantage of a function is that it makes the shell object short-lived (it's scoped to the function), and it can handle an error that not only could happen when passing the command string to the shell object's Run method, but also if Run returns a non-zero error code - if all goes well the function itself returns a success message, and if anything goes wrong it returns an error message. That level of abstraction also makes the actual script much less cluttered.

With this function, your entire script could look like this:

<job>
<script language="VBScript">
    Option Explicit

    Function Execute(command)
        On Error GoTo CleanFail

        Dim shell
        Set shell = CreateObject("WScript.Shell")

        Dim code
        code = shell.Run(command)

        Dim result
        If code <> 0 Then
            result = "Non-zero exit code: " & CStr(code)
        Else
            result = "Command '" & command & "' completed successfully."
        End If

    CleanExit:
        Execute = result
        Exit Function
    CleanFail:
        result = "Unexpected error #" & CStr(Err.Number) & ": " & Err.Description
        Resume CleanExit
    End Function

    WScript.Echo Execute("CCleaner.exe /AUTO")
    WScript.Echo Execute("WiseRegCleaner.exe /AUTO")
    WScript.Echo Execute("Cleanmgr /sagerun:1")
    WScript.Echo Execute("Defrag volume c:")
    WScript.Echo Execute("WiseDiskCleaner.exe /AUTO")
    WScript.Echo Execute("mbam.exe /fullscanterminate")

    WScript.Echo "Completed."
</script>
</job>

Notice there's no need to declare any script-level ("global") variables, handle errors at script-level, or to explicitly Quit anything - it simply runs to completion and lets the script host deal with termination.

If all goes well then your output should look like this:

Command 'CCleaner.exe /AUTO' completed successfully.
Command 'WiseRegCleaner.exe /AUTO' completed successfully.
Command 'Cleanmgr /sagerun:1' completed successfully.
Command 'Defrag volume c:' completed successfully.
Command 'WiseDiskCleaner.exe /AUTO' completed successfully.
Command 'mbam.exe /fullscanterminate' completed successfully.
Completed.


There are a few style changes in Python.
The main one is Python uses 4 spaces, not 2, as it's standard indent size.
This is important as indent size matters in Python.
Also most variables are snake_case.
So my code examples may have small changes.

I would recommend splitting the displaying and formatting into separate functions.
This is as then you can manipulate the output. Which can be nice.

This means that you would have to change your returns.

Changing this allows you to remove the two empty lines at the beginning,
for having to explicitly call print.
And you can print both files and targets at the same time:

print("\n\n".join([
    col_print("Files",
        [...]
    ),
    col_print("Targets",
        [...]
    )
]))

You could pass termwidth and padsize as default values.
This allows you to change them if you wish at a later point.

def col_print(title, array, pad_size=1, term_width=150):
    ...

You may want to change maxitemwidth so there is only one len.
It makes the code slightly easier to understand.
This is as I originally was a bit confused when I saw the len(max(...)).

max_item_width = max(map(len, array))

Division changed in Python3.

Rather than doing int(a / b) you can do a // b.
Python2 division can be nice at times, and so they kept it in.

Python3 division automatically casts a and b to floats.

In short this means that you don't have to do things like a / float(int(b / c)).
Instead you can do a / (b // c). Which is much more readable.

At this point the code looks quite nice:

def col_print(title, array, term_width=150, pad_size=1):
    indent = " " * 4
    pad = " " * pad_size
    title += "\n"

    if not array:
        return title + indent + "<None>"

    max_item_width = max(map(len, array))
    num_rows = int(math.ceil(len(array) / ((term_width + pad_size) // (max_item_width + pad_size))))

    return title + "\n".join(
        indent + pad.join(item.ljust(max_item_width) for item in array[index::num_rows])
        for index in range(num_rows)
    )


It is about inject initial value when you give Hash.new(0)
and call c[w] += 1 in block it is expanded to c[w] = c[w] + 1 as we said
to Hash initializer if it has no key then key will set to 0 when
first appeared.
c here is an accumulator and instance of inject initial value.
accumulator value will be set to return value of the block after
every turn. we are returning c because of this. it can be type of
any object. (1..10).inject(0) {|a,x| a + x } for example it is
Fixnum here.


Game where two players take turns picking numbers until a target sum

Prelude

Firstly, you might want to ask on Math Stack Exchange if there is any analysis. This game looks a lot like Nim and a variant of the subtraction game (mentioned later in the article). The subtraction game in particular has a really nice and cheesy solution. The major difference is that you prevent taking any number away twice.

On to the code!

Default values

When you start a game, the first player to go is, well, the first player. I don't think a user really wants to waste their time typing it. A similar argument goes for current_sum. You shouldn't really need to specify it. Hide it make the default value 0. so:

def try_best_win(numbers, flags, expected_sum, current_sum=0, is_first_player=True):

Is something you should probably do.

You don't really need flags.

You have a list of numbers (which btw, is a generalization of your problem statement, why?). Each one of these numbers represents a move you cannot play again. So in the recursive call:

Apply the move
Remove the move from numbers
Recurse on the new set of numbers.

This is equivalent to what you are doing and removes the flag variable entirely.

Bugs

There are bugs in your program. @Mathias provides an example as to why your code is wrong. You should consider @vnp's comment. The typical game tree traversal involves a reduction phase of some sort. As another hint, you should really review slide 27/39 of these slides. (Ask yourself, what does your code do differently than what is on that slide!)

Abstraction (and more hints)

You can actually abstract a lot of this. See my question here for a general framework on solving these games. A general framework declutters a lot of code. However, as mentioned in the prelude, a mathematical analysis may (or may not) provide a better solution than the general framework.


The first thing I would do is split up the while loop into 3 parts:
- handling both not empty
- add all remaining from left
- add all remaining from right

No wait, the first thing I did is paste the code in IntelliJ and have it autoformat to comply with the java coding conventions.
Since it's just some minor points like spacing I'm not going to list them here, overall your code looks decent already.

I also renamed a_iter and b_iter to leftIndex and rightIndex. Both because a variable shouldn't have an _ in it's name and because it better conveys what the variable is. Same for renaming a and b to leftElement and rightElement.

Now back to splitting up the while loop. I changed the || in the while condition to an &&, removed the "when xxx exhausted" parts and added the 2 new while loops after. This is the result:

int leftIndex = 0;
int rightIndex = 0;
while (leftIndex < left.size() && rightIndex < right.size()) {
    T leftElement = left.get(leftIndex);
    T rightElement = right.get(rightIndex);
    if (leftElement.compareTo(rightElement) < 0) {
        combined.add(leftElement);
        leftIndex++;
    } else {
        combined.add(rightElement);
        rightIndex++;
    }
}

// At least one of the sub lists is empty at this point.
// Just add all remaining elements from the other sub list.
while(leftIndex < left.size()){
    combined.add(left.get(leftIndex++));
}
while(rightIndex < right.size()){
    combined.add(right.get(rightIndex++));
}

Or if you want, replace the last while loops with an addAll

combined.addAll(left.subList(leftIndex, left.size()));
combined.addAll(right.subList(rightIndex, right.size()));

The biggest problem with this implementation is that it creates a lot of temporary lists. Taking a quick glance at how the built in list sort in java is implemented shows that they turn it into an array first, sort the array and then update the given list:

 public static <T extends Comparable<? super T>> void sort(List<T> list) {
     Object[] a = list.toArray();
     Arrays.sort(a);
     ListIterator<T> i = list.listIterator();
     for (int j=0; j<a.length; j++) {
         i.next();
         i.set((T)a[j]);
     }
 }

Note that this doesn't return the list. It actually sorts the list you pass into it.

If you're looking for more improvements to the merge algorithm itself you could look up how it's implemented in java. (Although recently it's changed into a Tim sort which is a combination of merge sort and insertion sort).

As a final note: if your intention was to actually use your code in a project other than studying how merge sort is implemented or practicing your java skills I would advise against it. Just use the built-in functions if available.


I think that conceptually you're fine. There are some details that need attention.

Hide the implementation

Your creation syntax:

CWindow window = std::make_unique<CWindowWrap>("title", 0, 0, 140, 100, 0)

requires the user to know that CWindow is a unique_ptr<CWindowWrap> this isn't ideal. I believe that it's a good idea to hide the implementation class.

You should put your CWindowWrap class in an implementation namespace:

namespace detail{
    class CWindowWrap{
        ...
    };
}
using CWindow = std::unique_ptr<detail::CWindowWrap>;

Then you should provide a creator function like this:

CWindow make_window(const char* title, int xpos, int ypos, int width, int height, Uint32 flags){
     return std::make_unique<detail::CWindowWrap>(title, xpos, ypos, width, height, flags);
}

Don't use virtual if you don't need it

CWindowWrap doesn't need a virtual destructor as far as I can tell and I can't imagine why you would inherit from this. So simply remove virtual.

Wrapper classes should match types exactly

You're not matching the types properly for the constructor of CWindowWrap (flags should be Uint32 see here).

Move assignment/construction

As you have already initialized ptr_window in the in-class declaration, you do not need : ptr_window(nullptr) in your move constructor.

Your move assignment operator is missing a return statement.

That said, as you are not supposed to instantiate CWindowWrap directly you could simply = delete the move assignment operator and constructor. They won't be used.

Same comments goes for the other wrapper.


Concatenating an array of optional NSAttributedStrings

The second and third approach combine two tasks into one:

Extract the non-nil elements from the given array of optional
attributed strings, and
concatenate these with a given separator.

My suggestion is to separate these concerns. This rules out #2 and #3
and leaves us with your #1 approach, the extension method on SequenceType.

Another disadvantage of the extension _ArrayType  is that it uses an internal type,
so that might break in a future version of Swift.

The flatMap() method from the Swift standard library already provides a method for the first task:

let attributedStrings = optionalAttributedStrings.flatMap { $0 }

and this can be combined with your extension method by the caller:

let joined = optionalAttributedStrings.flatMap { $0 }.join(withSeparator: separator)

A user might also want to concatenate non-optional strings, which
works with the extension method:

let joined = attributedStrings.join(withSeparator: separator)

but not with the other two approaches.

Another argument for approach #1 is that it resembles
the existing method to join strings:

extension SequenceType where Generator.Element == String {
    public func joinWithSeparator(separator: String) -> String
}

The method itself can be improved. The reduce() method creates a new
NSMutableAttributedString in each iteration. Better create only one
and append all elements (similar as on your join() function):

extension SequenceType where Generator.Element: NSAttributedString {

    func join(withSeparator separator: NSAttributedString) -> NSAttributedString {
        let finalString = NSMutableAttributedString()
        for (index, string) in enumerate() {
            if index > 0 {
                finalString.appendAttributedString(separator)
            }
            finalString.appendAttributedString(string)
        }
        return finalString
    }
}

Update: The Swift language changes constantly. For the convenience
of future readers, here is an update to Swift 4 of the above code:

extension Sequence where Element: NSAttributedString {

    func join(withSeparator separator: NSAttributedString) -> NSAttributedString {
        let finalString = NSMutableAttributedString()
        for (index, string) in enumerated() {
            if index > 0 {
                finalString.append(separator)
            }
            finalString.append(string)
        }
        return finalString
    }
}

Also flatMap has been renamed to compactMap:

let attributedStrings = optionalAttributedStrings.compactMap { $0 }


As vnp points out, your code is incorrect because a thread may read REFERENCE after IS_CREATED is set but before REFERENCE is set. Here are a couple alternatives:

use double-checked locking:

private static volatile T reference;
public static T get() {
    if (reference == null)
        synchronized(ThisClass.class) {
            if (reference == null)
                reference = new MyObject();
        }
    return reference;
}

use static class initialization:

private static class Lazy {
    private static final T reference = new MyObject();
}
public static T get() {
    return Lazy.reference;
}

use optimistic creation with CAS (this might create multiple instances but only one instance will be returned):

private static final AtomicReference<T> reference = new AtomicReference<>();
public static T get() {
    if (reference.get() == null)
        reference.compareAndSet(null, new MyObject());
    return reference.get();
}


Horizontally concatenating the entries of two matrices, and padding with NaNs

I see two major way to simplify and speed this up.  First, rather than copying a to c at every step of the loop, you can define c to include a from the beginning.  Second, you can find all the nonzero, non-NaN values in a vectorized manner at the very beginning  This reduces the time for me be about 1/2 for a large (~10000 row) random data set.

function c = catnonzero_2(a, b)
    c=[a, NaN(size(b))];
    agood = a~=0;
    bgood = b~=0;
    for ii=1:size(a,1)
        ailast=find(agood(ii,:), 1, 'last');
        if isempty(ailast)
            ailast = 0;
        end
        bilast=find(bgood(ii,:), 1, 'last');
        if ~isempty(bilast)
            c(ii, ailast+1:ailast+bilast) = b(ii, 1:bilast);
        else
            c(ii, ailast+1:end) = NaN;
        end
    end
end

This can be improved even more by separating out the rows that can be vectorized from those that can't.

I find all the rows of a and b with some non-null values ("good" rows).  Rows that aren't good are then filled with NaN.
I find all the rows of a and b where the last value is non-null ("perfect" rows).
For rows that are good but not perfect ("imperfect" rows):

For b I can loop over them an put the NaN values at the end.  This allows me to treat all b rows as either "perfect" or "bad", since the "imperfect" rows already have the NaN values at the end and thus can be used in the entirety.
For a, I can loop over the rows where a are imperfect and b are not good and put NaN at the end of those.  Where b is good, b will be ovewriting those anyway so it isn't necessary as long as b is at least as long as a.

I make c like in the previous example.
In cases where a is perfect and b is good, I can just write b to c at the point where a ends.
In the cases where a is bad and b is food, I can just write b from the start of c.
In the remaining cases, I have to calculate where b starts, and then write b.
 3.

This reduces the time for me by about another 1/4:

function c = catnonzero_3(a, b)
    alen = size(a, 2);
    blen = size(b, 2);

    agood = a~=0;
    bgood = b~=0;

    agoodrows = any(agood, 2);
    bgoodrows = any(bgood, 2);

    aperfectrows = agood(:,end);
    bperfectrows = bgood(:,end);
    aimperfectrows = agoodrows & ~aperfectrows;

    a(~agoodrows, :) = NaN;
    b(~bgoodrows, :) = NaN;

    if alen <= blen
       apadtarg = aimperfectrows & ~bgoodrows;
    else
       apadtarg = aimperfectrows;
    end

    for ii=find(apadtarg)'
        a(ii, ailast(ii)+1:end) = NaN;
    end
    for ii=find(bgoodrows & ~bperfectrows)'
        b(ii, bilast(ii)+1:end) = NaN;
    end

    c=[a, NaN(size(b))];

    ailast = @(ii) find(agood(ii,:), 1, 'last');
    bilast = @(ii) find(bgood(ii,:), 1, 'last');

    aperfbgood = aperfectrows & bgoodrows;
    c(aperfbgood, size(a, 2)+1:end) = b(aperfbgood, :);

    abadbgood = ~agoodrows & bgoodrows;
    c(abadbgood, 1:blen) = b(abadbgood, :);

    for ii=find(aimperfectrows & bgoodrows)'
        ajj = ailast(ii);
        c(ii, ajj+1:ajj+blen) = b(ii, :);
    end
end

And here is the data set I used to test (your version is catnonzero_1:

a=randi([-11, 10], 100000,80);
b=randi([-11, 10], 100000,100);

a(a==-11) = NaN;
b(b==-11) = NaN;

timeit(@() catnonzero_1(a, b))
timeit(@() catnonzero_2(a, b))
timeit(@() catnonzero_3(a, b))

And the result:

>> run_w_time

ans =

    0.889284394000000

ans =

    0.411362394000000

ans =

    0.102184394000000

ans =

    1

ans =

    1

c1 = catnonzero_1(a, b);
c2 = catnonzero_2(a, b);
c3 = catnonzero_3(a, b);

all(all(c1(~isnan(c1))==c2(~isnan(c2))))
all(all(c1(~isnan(c1))==c3(~isnan(c3))))


Position update loop and checking collision

You can reduce some of the indent by checking for the negative condition and bailing out early. E.g.:

TouchPanelCapabilities touchCap = TouchPanel.GetCapabilities();
if (!touchCap.IsConnected) { return; }

TouchCollection touches = TouchPanel.GetState();
if (touches.Count == 0) { return; }

... your other code goes here ...

PositionTouch: Standard naming convention for local variables is camelCase. Also the names reads slightly weird - touchPosition would be better.
On every iteration through your ListDragObj method you check if (touches[touches.Count - 1].State == TouchLocationState.Released). You can store that in a local variable before the loop:

var touchReleased = touches[touches.Count - 1].State == TouchLocationState.Released;

for (...)
{
    ...
    if (touchReleased)

You don't actually use the index in this loop: for (int i = 0; i < ListDragObj.Count(); i++). A more idiomatic C# way would be to use a foreach in this case:

foreach (var dragObject in ListDragObj)
{
    ...
}

And replace all uses of ListDragObj[i] with dragObject.
This:

for (int i = 0; i < ListDragObj.Count(); i++)
{
    if (ListDragObj[i].Shape.Contains((int)PositionTouch.X, (int)PositionTouch.Y))
    {
        //Permit to avoid several Obj to moove in the same time
        if (!OnlyOneSelected(ListDragObj))

looks suspiciously like an O(n^2) algorithm - assuming that OnlyOneSelected iterates over the list and counts how many are selected. You should consider keeping track of how many items are selected in your class. This could be achieved by adding two methods:

void SelectedObject(DragObj dragObject) { ... }
void DeselectObject(DragObj dragObject) { ... }

which modify the selected property and adjust the selected count.
This

if (gm.Check_Tile((int)(PositionTouch.X / 10), (int)(PositionTouch.Y / 10)))

looks like it computes a tile index from the position - assuming tiles are 10x10. If this assumption is correct then you should change Check_Tile to accept a position. It should then calculate the appropriate tile index by itself. Otherwise what happens if you ever want to change your tile size from 10x10 to something else? You would need to find every place in your code where you make this implicit assumption.