Pushing an array into an object with an undefined/non-existing property

The overall approach looks fine - check if the property exists on the object, and then either create the collection or append the data to the existing collection. While there are other methods than yours that achieve the same thing, none of them is clearly smoother or more semantically appropriate - the tools to do this more concisely just don't exist in vanilla JS yet (though there are libraries like Lodash and Underscore that implement the same sort of logic under the hood).
But, your current code has a bug: if the property already exists on the object, the data will be pushed to the existing array as a subarray, rather than pushing all elements of data to the existing array:

const result = {
  helloworld: [{
    alreadyExistingProp: 'alreadyExistingVal'
  }]
};
const data = [{
    name: "John Doe"
},
{
    name: "Doe John"
}];

const key = "helloworld";

if(result.hasOwnProperty(key)) {
  result[key].push(data);
} else {
  Object.assign(result, {
    [key]: data
  });
}

console.log(result);

You want a flat structure instead. Change
result[key].push(data);

to
result[key].push(...data);

A couple other pointers:
hasOwnProperty? Since it sounds like the values of the object will always be truthy, you can consider making a truthy test instead of using hasOwnProperty:
if (result[key]) {

Object.assign is unnecessary when setting just a single property This:
Object.assign(result, {
  [key]: data
});

can be
result[key] = data;

Mutation worries? Note that the approach used so far will mutate the result object and the data array. Mutation may cause unexpected behavior and bugs elsewhere if other parts of the script have a reference to the object that gets modified. If this is something to worry about, either clone the data before assigning it, or immutably update the result variable (like how state is updated in React).
For a short contrived example of how accidental mutation might result in a bug:

const result = {};
const addData = (data) => {
  const key = "helloworld";
  if(result.hasOwnProperty(key)) {
    result[key].push(...data);
  } else {
    result[key] = data;
  }
};

const dataFromUser = [{
    name: "John Doe"
},
{
    name: "Doe John"
}];
addData(dataFromUser);
addData([{ name: 'Default Name' }]);

// now the `result` object contains all the data
// but the dataFromUser now contains an extra object, which may be a mistake:
for (const item of dataFromUser) {
  console.log('Name from dataFromUser:', item.name);
}

This may well not be a problem for your situation, but variable contents changing unexpectedly due to mutation by code elsewhere is quite a common source of bugs in my experience.
Of course, if you understand well how references to objects work, and have no problem with (or like) the mutation that will occur, feel free to use it.


Overall, this looks pretty nice. There are few minor things that can be improved though, about this part:

int x = 0;

for (const auto& i : words)
{
    if (x++ == 0)
    {
        std::cout << "\nThe most repeated element is: " << i->first << "\n\n";

        std::cout << " Word\tRepeated Times";

        std::cout << '\n' << std::setfill('-') << std::setw(23) << '\n';
    }

    // ...
}

i is customary for loop variables that are simple counters.
In this case it is a word (well, sort of),
so it would be better to name it as such.

The variable x is a bit confusing:

its name tells nothing of its purpose
it's important for the first iteration of the loop
... but it keeps counting during all iterations

It would be clearer and better this way:

bool first = true;

for (const auto& word : words)
{
    if (first)
    {
        std::cout << "\nThe most repeated element is: " << word->first << "\n\n";

        std::cout << " Word\tRepeated Times";

        std::cout << '\n' << std::setfill('-') << std::setw(23) << '\n';

        first = false;
    }

    // ...
}


var displayValue : Double {
    get {
        return (display.text as NSString!).doubleValue
    }
    set {
    }
}

This empty setter is very disingenuous.

If we don't want to let the user set the display's text property by passing a double, then we should make this property readonly by eliminating the set:

var displayValue : Double {
    get {
        return (display.text as NSString!).doubleValue
    }
}

But I actually don't necessarily see a reason why this can't be readwrite:

var displayValue : Double {
    get {
        return (display.text as NSString!).doubleValue
    }
    set {
        display.text = String(format: "%f", newValue)
    }
}

Of course, we can use our format string to specify number of decimal places to show and such.

The biggest thing is, we need to do something with the empty set for our computed property.  If we don't want an end-user setting the value this way, then don't let them and don't let them think they can.  By removing the set method as I've done in the first example, trying to set the property will result in a compiler error.

There's another area we want to start using the compiler to our advantage--with our operations.  You're using a simple String type to track what sort of math we should be doing.  Swift is all about explicit types, so let's make an enum to handle our operations:

enum MathematicalOperation: String {
    case Addition = "+"
    case Subtraction = "-"
    case Multiplication = "x"
    case Division = "÷"
}

Now let's just our currentOperation and nextOperation to have the MathematicalOperation type:

var currentOperation : MathematicalOperation?
var nextOperation : MathematicalOperation?

We can still make use of the button's title text if we really want:

self.nextOperation = MathematicalOperation(rawValue:sender.currentTitle)

And now, let's fix up that switch:

if (currentOperation != nil) {
    switch currentOperation! {
    case "+": display.text = "\(currentResult + operand)"
    case "-": display.text = "\(currentResult - operand)"
    case "×": display.text = "\(currentResult * operand)"
    case "÷": display.text = "\(currentResult / operand)"
    default: break
    }
}

Let's get rid of the unnecessary ! operation (which when abused leads to some bad code--here is fine, but let's not get in the habbit), and let's not rely on string comparisons for the switch:

if let op = currentOperation {
    switch op {
        case .Addition: display.text = "\(currentResult + operand)"
        case .Subtraction: display.text = "\(currentResult - operand)"
        case .Multiplication: display.text = "\(currentResult * operand)"
        case .Division: display.text = "\(currentResult / operand)"
    }
}


Spike gave a nice answer already. I just wanted to point out one thing: This is a good use case for rjust, aka "right-justify". With that, you can skip the string-multiplication when you pad the numbers.

def print_multiplication_table(max)
  padding = (max * max).to_s.length + 1
  sequence = (1..max).to_a
  puts sequence.product(sequence)
    .map { |a, b| (a * b).to_s.rjust(padding) }
    .each_slice(max)
    .map(&:join)
    .join("\n")
end

This one only uses 1 space between columns, but 2 spaces can be had by replacing .map(&:join) with .map { |row| row.join(" ") }.


Welcome to Code Review! You've made a very good start at learning VBA and how to put together clean code. Many helpful folks will give you supportive comments and I'll jump in with mine...

Starting with your MergeCells routine:

The name MergeCells is already a method of the Range object. Naming your routine with this same name can be confusing, so I stronly recommend a different name such as MergeAdjacentNonEmptyCellsInColumn. It may seem overly long, but it's descriptive and makes your code an easy read.
You might consider using an array of columns as an input parameter to this Sub. That would give you the flexibility to reuse the Sub in the future on a different set of columns.
I have many bruises and scars from writing code the says Cells(... or Rows.Count without explicitly attaching those references to a specific worksheet. In your case, your Sub will only work on the currently active worksheet. If you create an input parameter for the target worksheet, that will make sure the routine works on the sheet you want for sure. To make it easier to read, just wrap your loop sections in a With clause.
Go ahead and declare your variables closer to their first use. It saves you from having to jump back and forth between their declaration and the executable code.
Please break up long lines such as your Array initialization. It makes it much easier to read. The typical column to wrap a long line is column 80, but you can choose your own as long as you're consistent.
I'm in favor of somewhat longer, more descriptive variable names. It makes your code read more like sentences that can (hopefully) clearly convey what that code is doing. So I use lastRowInColumn and similar names.

So:

Option Explicit

Sub test()
    Dim columnsToMerge() As Variant
    columnsToMerge = Array("A", "B", "C", "D", "E", "F", "G", "H", "I", _
                           "J", "K", "L", "M", "N", "O", "P", "Q", "R", _
                           "S", "T", "U", "AA", "AB", "AC", "AD", "AE", _
                           "AF", "AG", "AH", "AI", "AJ", "AK")

    MergeAdjacentNonEmptyCellsInColumn Sheet1, columnsToMerge
End Sub

Public Sub MergeAdjacentNonEmptyCellsInColumn(ByRef targetWS As Worksheet, _
                                              ByRef colArray() As Variant)
    Application.DisplayAlerts = False
    'Application.ScreenUpdating = false
    With targetWS
        Dim lastRowInColumn As Long
        Dim c As Long
        For c = LBound(colArray) To UBound(colArray)
            lastRowInColumn = .Cells(.rows.count, colArray(c)).End(xlUp).Row
            Dim i As Long
            For i = lastRowInColumn - 1 To 2 Step -1
                If .Cells(i, colArray(c)).value = .Cells(i, colArray(c)).Offset(1, 0).value And _
                   Not IsEmpty(.Cells(i, colArray(c))) Then
                    .Cells(i, colArray(c)).Resize(2, 1).Merge
                    .Cells(i, colArray(c)).HorizontalAlignment = xlCenter
                    .Cells(i, colArray(c)).VerticalAlignment = xlCenter
                End If
            Next i
        Next c
    End With
    Application.DisplayAlerts = True
    'Application.ScreenUpdating = True
End Sub

For your next Sub, you've named it fixMergedCells, but that is identical to the next sub. So I think this sub should be renamed to something like unmergeAndCenter.

A generally followed convention is to begin variable names with lower case and Sub/Function names with an uppercase letter. That would make your sub UnmergeAndCenter.
The variable m is a Range. But as I mentioned earlier, I see a single-letter variable as a looping index. So I'd rather see this named allMergedCells because that's what you get when you perform the Intersect action.

And so:

Sub test1()
    UnmergeAndCenter RawData
End Sub

Sub UnmergeAndCenter(sh As Worksheet)
    'replace merged cells by Center Across Selection
    'high perf version using a hack: https://stackoverflow.com/a/9452164/78522
    Dim constFla As Variant
    constFla = Array(xlConstants, xlFormulas)

    Dim usedArea As Range
    Set usedArea = sh.UsedRange

    Dim i As Long
    For i = 0 To 1                               '1 run for constants, 1 for formulas
        Err.Clear
        On Error Resume Next
        Dim allMergedCells As Range
        Set allMergedCells = Intersect(usedArea.Cells.SpecialCells(constFla(i)), _
                                       usedArea.Cells.SpecialCells(xlBlanks))
        On Error GoTo 0
        If Not allMergedCells Is Nothing Then
            Dim c As Range
            For Each c In allMergedCells.Cells
                If c.MergeCells Then
                    With c.MergeArea
                        'Debug.Print .Address
                        .UnMerge
                        .HorizontalAlignment = xlCenterAcrossSelection
                    End With
                End If
            Next c
        End If
    Next i
End Sub

Capitalize the first letter of your last Sub.
It's another long habit of mine (create your own style and habit) that I almost never write a compound statement (like an If) on one line. It may be tedious, but it makes my code more consistent to always use multiple lines. Makes it easier to maintain in the future (IMHO).

Finally:

Sub FixMergedCells(Optional sh As Variant)
    If IsMissing(sh) Then
        Set sh = ActiveSheet
    End If
    sh.Cells.UnMerge
End Sub


The big thing I can see is that you don't seem to know why to use a mutable structure in Haskell. They're not automatically faster. In fact, they have some GC-related overhead that exceeds that of immutable structures in GHC. Mutable structures in GHC are only a win if they can actually reduce the amount of allocation, and this implementation looks like it allocates a lot.

When you consider using a mutable structure, you need to examine how mutability will reduce total allocation. If it doesn't reduce allocation (and usually by an asymptotic factor) it's unlikely that mutability alone is going to help performance.


Overall, it gets the job done, but your code (especially the area I'd refer to as "pyramid code"), could use a little more organization and clarity.

Your if statement could be a little more concise, and, at the same time, more canonical about what it's actually there for:

if (!('REDDIT_USERAGENT' in process.env)) {
  ...
}

You can write concise code without using cryptic variable names. Change r to something more meaningful like robot or even just bot.

One way to resolve pyramid code is to look for places where your logic can be decoupled or flattened. While it's possible to continue to use the async dependency in order to achieve this, it's probably much easier to just use async/await since you're already using promises anyway. This will also give you an opportunity to get rid of your global variable lastChecked:

function matchesRequirements (post) {
  return post.domain === 'gfycat.com' && /(\/[a-z][a-z])?\/gifs\/detail/g.test(post.url)
}

async function tryReply (post) {
  const { comments, subreddit, title, url } = await post.fetch()
  const participants = comments.map(comment => comment.author.name)

  if (!participants.includes(process.env.REDDIT_USERNAME)) {
    console.log(chalk.red(`${chalk.bold('Found new post:')} ${title} [/r/${subreddit.display_name}]`))

    const proper = url.replace(/(\/[a-z][a-z])?\/gifs\/detail/g, '')
    const reason = 'https://gist.github.com/ImJustToNy/cb3457e36f22123eb93864f0af639da3'
    const source = 'https://github.com/ImJustToNy/GfycatDetailsConvert'

    const text = `[Proper Gfycat URL](${proper}) \n\n^^I'm ^^just ^^a ^^bot, ^^bleep, ^^bloop. [^^[Why?]](${reason}) [^^[Source ^^code]](${source})`

    return post.reply(text)
  }
}

async function pollNewPosts () {
  let lastChecked

  while (true) {
    const posts = await bot.getNew('all', {
      before: lastChecked,
      show: 'all',
      amount: 1000
    })

    if (posts.length > 0) {
      lastChecked = posts[0].name
    }

    await Promise.all(posts
      .filter(matchesRequirements)
      .map(tryReply)
    )

    await new Promise(resolve => setTimeout(resolve, 5000))
  }
}

pollNewPosts()

One of the things in this rewrite to flatten your pyramid code, I changed the order in which .fetch() is called, because the way your code accessed the comments property relied on the usage of a proxy get trap in order to work properly, which is both unnecessary and inefficient.

Lastly, I cleaned up your generated text to break it up into a few lines, otherwise it's quite unreadable. You might consider storing that text to an external template file using a minimal template engine (possibly written yourself just for this specific case) in order to avoid hard-coding it in here.


Get a number from a class of a HTML element

You might use something like the snippet below, that is:

sure a bit shorter
probably faster, because:

using find() rather than filter() makes the loop stop as soon as the desired result is got
looking for the involved class-prefix and extracting the number are both processed in the same statement

and browser agnostic, while includes() is not recognized by IE

function get_gallery_columns($el) {
  var matches, result = false;
  $el.attr('class').split(/\s+/).find(function (className) {
    if (matches = className.match(/^gallery-columns-(\d+)$/)) {
      result = +matches[1];
      return true;
    }
  });
  return result;
}

console.log(get_gallery_columns($('#gallery-1')));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="gallery-1" class="gallery galleryid-555 gallery-columns-3 gallery-size-thumbnail">
    ...
</div>


Creation of playlist to fake-split a full-album video

Instead of using print() you can add a newline character \n at the end of the previous printed string:

print('with the same name as the album file.\n')
print('The playlist will be saved in current directory.')

When you ask for a filename, you don't do any input validation. What if they enter an empty string? What if their path isn't real? I'm not familar with pathlib, and also not sure what you'd want to do. You could create an infinite loop that will only break when the user enters a valid/existing path. Alternatively you could end the program if an invalid path appears. You definitely shouldn't ignore errors or leave it to Python to raise whatever errors it sees fit. You should make explicit choices about what happens.

When you're appending the string to playlist_entries, it's quite hard to read. You would do better to define an ENTRY_TEMPLATE string at the top of the file which you just use and format when appending.

Python truthiness can be very useful, but in this case if i is liable to confuse people. I would suggest either an explicit statement like i != 0 or a comment.

    if i:  # Not the first entry


Checking for Internet connectivity on Android

I am not familiar enough with Java to know what inside your try block could throw an exception or what sort of exceptions you might expect, however, simply printing the stack trace surely can't really be all that helpful.

First of all, any end user isn't going to see this information.  Second of all, no developer will see this testing outside of the development environment.

Again, I'm not that familiar with Java, so I don't know what options are available, but you need to do one of a few things.

Show the exception to the user (or some information about it anyway).  This is probably completely unnecessary.  The network connection is either available or not, right?
Rethrow the exception and let the caller handle it.  It can be useful to know there was an exception and we should retry the network connection later.
Log the exception in a way that the developer can access even when it happens in production.  Error logs should be uploaded somewhere.
Just do nothing, and don't waste execution time printing the stack trace.  If you chose this option, you probably want to find a way to leave the print stack trace in for development environments, but for production builds, you shouldn't be executing this code.

Now.... our code also has some magic numbers in it.  I realize this isn't entirely your fault.  I've visited the official documentation.  I see, that somehow, this method simply takes an int and the documentation doesn't seem to clarify what the legitimate values are very well... but they are all defined as constants:

ConnectivityManager.TYPE_BLUETOOTH
ConnectivityManager.TYPE_DUMMY
ConnectivityManager.TYPE_ETHERNET
ConnectivityManager.TYPE_MOBILE
ConnectivityManager.TYPE_MOBILE_DUN
ConnectivityManager.TYPE_MOBILE_HIPRI
ConnectivityManager.TYPE_MOBILE_MMS
ConnectivityManager.TYPE_MOBILE_SUPL
ConnectivityManager.TYPE_VPN
ConnectivityManager.TYPE_WIFI
ConnectivityManager.TYPE_WIMAX

These are the constants we should be passing in when checking for a connection.  Using these constants makes things a bit more readable.  But moreover, I might modify our method to be more flexible.  You're only checking for WIFI or MOBILE (I don't know enough about Android to know if this is excluding anything important).  But we can write our function in such a way that we can check for whatever types the user needs.

public static boolean isNetworkAvailable(Context context, int[] networkTypes) {
    try {
        ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
        for (int networkType : networkTypes) {
            NetworkInfo netInfo = cm.getNetworkInfo(networkType);
            if (netInfo != null && netInfo.getState() == NetworkInfo.State.CONNECTED) {
                return true;
            }
        }
    } catch (Exception e) {
        return false;
    }
    return false;
}

Now our method is duplicating less code and its flexible enough to check for what ever types of networks the user happens to specify.  If we want a method that doesn't require passing in networks and still does what your original implementation does, we can just write a wrapper method that passes mobile/wifi in to this method.


Thanks for sharing your code.
This looks pretty good for a novices code since you managed to remove some code duplication by using parameterized methods.
here is what I would change:
Naming
Finding good names is the hardest part in programming, so always take your time to think about the names of your identifiers.
Naming Conventions
Please read (and follow) the
Java Naming Conventions.
eg .: variables of type  boolean (like gameOver) or methods returning a  boolean should start with *is, has, can or alike.
Don't surprise your readers
Your method askForTurn() does nor only acquire user input, it actually does the turn. So it should better be named doTurn().
Magic numbers
replace the literal numbers by constants with expressive names.
Separation of Concerns
askForTurn() does more than one thing:

it acquires user input,
validates the user input
translates the input into a field position
checks the end condition

each of this actions should live in a method of its own.
hidden recursion/implicit error handling
In case of an invalid input you do a recursive call to askForTurn().
Beside that this also belongs in the Don't surprise your readers category it is a potential memory leak.
Use of the static key word
The only method that should be static in your code should be main.
For the rest of your code you should avoid the static key word unless you have a good reason to use it.
In your case it would be quiet easy to do:
move the while loop from main into a new (non static) method and call it on an instance of the class:
public static void main(String[] args) {
    new TicTacToe().runTheGame();
}

This would safe you from all the statics in your program.


Regarding testing:  Yes, it's in the standard library.  There are of course more libraries to help out more, but that's where you should likely start your journey.

For error reporting, well, it's a bit inconsistent at the moment?  There's both returning a value ([NOT CONTENT]...) as well as fmt.Println and panic too, all of which are not very appropriate for production usage.

The first of which can lead to serious debugging nightmares:  How do you know the file didn't contain that exact string for one?  This is always a problem if the valid values are mixed with error values (like how in most C APIs there are int return values with -1 for errors, while everything \$>= 0\$ are the "actual" return values in the non-error case)!  It's much better to keep them separate, which in Go could be done with separate types, or separate return values (which is what's done for errors).

The second one is perhaps less bad, but again, the error situation is just hidden, not actually dealt with.

The third one can be done, however it's usually reserved for programming errors, since not catching a panic call will simply abort the program (which is rarely what you want).

If in doubt, return an error in addition to any values: func getContent(string) (string, error) and writeContent/appendContent(string, string) error would be fine.  Maybe also see this blog post and this newer one for 1.13.

The defer to close files is pretty much required in my opinion.  Unless you can prove that nothing else between the opening of the file and the Close call can raise a panic, you pretty much have to use defer ...Close(), otherwise you risk leaking resources (open file handles).

For the comments, please have a look here:  Instead of comments simply add proper docstrings to the functions, that is good practice anyway and would certainly be appreciated by colleagues on bigger projects.

Maybe as a last note:  The permissions 0777 and 0600 are okay if those are the ones you want.  However, that might not be true in general.  Exactly how ioutil.WriteFile lets you specify them would be likely what you want in general.  If not, consider creating constants so that you don't have magic numbers inline with the code (e.g. const defaultFilePermissions = 0777 or something similar).


Your method isEmpty is not needed at all. First, none of your code uses it. Second, if you were to keep it, you should turn it's logic around and rename it to __bool__, this way, if heap automatically works and is True if the heap is not empty. But third, if no __bool__ method exists, Python already calls len(obj) != 0 to determine an object's truthiness, so it is already supplied by defining __len__.

As a second point, you should not mix naming conventions. You currently use both lower_case and camelCase for your method names. PEP8, Python's official style-guide, recommends using lower_case.

You don't need the line-continuation in here, the line is already shorter than 80 characters:

    def _swap(self, i, j):
        self._data[i], self._data[j] = self._data[j], self._data[i]

Some docstrings describing what your methods do and what they expect as inputs/what they return, would also be really good.

I would rename your method del_min to pop_min, because it returns the removed element and not just deletes it.


Speed up Crawling Every File C:\ and hashing using Java 8

The main drawbacks of the solution you are trying to apply are:

The I/O streams are never closed: resources are leaking severely.
The InputStream reads data per byte and updates the MessageDigest with a single byte, but it would be more efficient when using a buffer.
The main logic body is using older File API, but there are newer tools since Java 7.
md5 instance is created for each file, but it can be reused by calling md5.reset().

Here what I can suggest to improve this solution.

The main call will be ridiculously short:

public void crawl2(String path) throws IOException {
  Files.walkFileTree(Paths.get(path), new HashingFileCrawler());
}

Files.walkFileTree needs an instance of FileVisitor and it executes all the boilerplate of traversing the file hierarchy, we need only to implement our logic. Let's call our implementor HashingFileCrawler:

public class HashingFileCrawler extends SimpleFileVisitor<Path> {

  private final MessageDigest md5; // only one instance

  public HashingFileCrawler() {
    try {
      this.md5 = MessageDigest.getInstance("MD5");
    } catch (NoSuchAlgorithmException ex) {
      // if we enter this catch block, there is definitely something wrong with the running JVM. "MD5" algo should exist by default.
      throw new IllegalStateException(ex);
    }
  }

  @Override
  public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
    System.out.println("Dir: " + dir.toString());
    return FileVisitResult.CONTINUE;
  }

  @Override
  public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
    System.out.println("File: " + file.toString());
    final byte[] buffer = new byte[2048];
    try (InputStream fis = Files.newInputStream(file);
         BufferedInputStream bis = new BufferedInputStream(fis)) {
      int nbRead = bis.read(buffer); // read file data into the buffer for exchange with md5
      while (nbRead > -1) {
        md5.update(buffer, 0, nbRead);
        nbRead = bis.read(buffer);
      }
      System.out.println("Hash:" + Arrays.toString(md5.digest()));
      md5.reset();  // reset MD for reuse for next file
      return FileVisitResult.CONTINUE;
    }
  }
}

preVisitDirectory is called before crawling the files in a directory: it corresponds to the original code under condition if (f.isDirectory()).

visitFile wraps the main logic of producing a hash for a file, under else in the original code.

The size of the byte buffer (2048 here) can be adjusted: try to play with different values to see whether the perfs change.


Consistency and correct syntax would be a start:  The last function call
is improperly closed, so technically that's broken.  Also my JavaScript
mode marks all missing semicolons, so I inserted them too.  The naming
convention is unusual in the sense that it's mixing camel case and
underscores, doesn't loook the greatest.  The comments mostly state what
the code already says - I'd leave them out unless they add significant
insights.

Now to the actual code.  WebAlert can be simplified since it always
returns false.

The name callback implies the parameter being a function, which it's
not, a better name could be inCallback or so?

The whole adding/removing nodes just for an alert seems messy.  I'd say
that you should always have the div for WebAlert_Area in the
website, then toggle its visibility with CSS unless there's a pressing
reason to do it this way.

In any case, removing the div just to recreate it immediately
doesn't strike me as a good way.  Can't it just stay there and be filled
with new content (.html(msg)) instead of
Remove_WebAlert(); Create_WebAlert?

Of course it is untested, but I think splitting it like below makes more
sense and is less convoluted:

(function($){
    $.fn.WebAlert = function(msg) {
        if (!$('.WebAlert_Area').length) {
            $(this).Create_WebAlert();
        }
        $(this).Set_WebAlert(msg);
        return false;
    };

    $.fn.Create_WebAlert = function(msg) {
        $('body').append('

');
    };

    $.fn.Set_WebAlert = function(msg) {
        $('.WebAlert_Area .Text_Area').html(msg);
    };

    $.fn.Remove_WebAlert = function() {
        $('.WebAlert_Area').hide(1000, function() {
            $(this).remove();
        });
    };
})(jQuery);

$(document).ready(function() {
    $('body').WebAlert('Welcome To My Web');
});


Javascript. Reverse order of words in string, but not special characters

The current implementation of isAlpha ...
let isAlpha = (char) => {
  // match any alphabetic character.
  let pat = /[a-zA-z]/igm;

  if(char.match(pat)){
    return true;
  } else {
    return false;
  }
};

... can be refactored into something as short as this ...
function isAlpha(char) {
  return (/[a-zA-z]/).test(char);
};

... or maybe even that ...
function isAlpha(char) {
  // \w matches any word character
  // and is equal to [a-zA-Z0-9_]
  return (/\w/).test(char);
};

Why is that?
isAlpha gets invoked from within reverse always by providing a single character. Thus the regex can be simplified from /[a-zA-z]/igm to /[a-zA-z]/. Since isAlpha is supposed to return a boolean value do not use match and do no not return either true or false separately but use RegExp.prototype.test instead which already provides the correct return value.
Thats all so far but I will continue looking through the code, since as of now I don't understand why one wants to test a string stepwise character by character.
There is an answer of mine, regarding your question at StackOverflow. Maybe you get some inspiration from an alternative approach.


Instantiating objects with many attributes

Martin Fowler's bible book Refactoring does identify a smell called "Long Parameter List" (p78) and proposes the following refactorings:

Replace Parameter with Method (p292)
Introduce Parameter Object (295)
Preserve Whole Object (298)

Of these I think that "Introduce Parameter Object" would best suit:

You'd wrap the attributes up in their own object and pass that to the constructor.  You may face the same issue with the new object if you choose to bundle all the values directly into its' constructor, though you could use setters instead of parameters in that object.

To illustrate (sorry, my PHP-fu is weak):

$params = new OpenIDParams();
$params->setSomething( $imgPath . $name . $ext );
$params->setSomethingElse( 'openid_highlight' );

$params->setName( $name );

$op = new OpenIdProvider( $params );

This is a little more verbose but it addresses your concern about not being clear about the attributes' purpose / meaning.  Also it'll be a little less painful to add extra attributes into the equation later.


Determine all prime, palindrome string integers within a range

One suggestion: That sqrt is expensive, and you can eliminate it in a lot of common cases. For example: if any number except 2 is even, then it's not prime. Every second time you call check_prime, you're passing an even number.

So you can check n%2 before the loop, and eliminate that sqrt on half of your calls. You can extend this to check the first few primes explicitly, before starting your loop:

def check_prime(n):
    if n<2:
        return False
    if n%2==0:
        return n==2
    if n%3==0:
        return n==3
    if n%5==0:
        return n==5
    for i in range(7, int(sqrt(n))+1, 2):
        if n%i == 0:
            return False
    return True

You get diminishing returns by adding more checks. I benchmarked the above at about 2x as fast as your original code.


Product of corresponding elements in 2 arrays

This is effectively a convolution problem. Theoretically, this can (potentially) be done faster by a conversion to the frequency domain, that is, using a fast Fourier transform (FFT) convolution.

Writing a high-performance FFT convolution isn't something I'd want to reproduce here (even if I could reproduce it, which to be perfectly honest, I couldn't). Thankfully, I don't have to: libraries like numpy and scipy provide this functionality: see scipy.signal.fftconvolve.

The only thing that we have to be careful with is that convolution reverses the second array, so we must provide that in a reversed form:

import numpy
from scipy.signal import fftconvolve

x = numpy.array([2,3,4,5])
y = numpy.array([1,3])
maximum = numpy.max(fftconvolve(x, y[::-1], mode='valid')) # reversed view of y

For small arrays, this is likely to be slower than the naïve O(n2) convolution, due to the overhead of conversions (and multiplying complex numbers). If you are in this case, then you should try scipy.signal.convolve.

For an in-depth writeup of computational complexity comparisons between the naïve convolution and the fast Fourier transform, see here.


Trie data structure in C++ with add and search

This is a pretty good implementation from what I see. It's easy to read and looks very straightforward. Nice work!
Naming
For the most part your naming is good. There are a few small things I would change. For example, the get_leaf() method. When I read the name I thought it was going to retrieve a leaf node, but I couldn't see how it could determine which one. In reality, it returns a bool that tells whether it is a leaf or not. I would rename it to is_leaf() to avoid confusion.
I also don't like the word value as it's fairly meaningless. It represents a letter in the set of words formed by that branch of the trie. I would name it character or letter.
Organization
For the default constructor for a Node, in C++11 and later, you don't need to write it out by hand. In the header, you can just declare it as:
Node() = default;

In trie.cpp you have the implementation of 3 classes. I usually break them out into a separate source file per class. Given how small these are, it's not a huge deal to put it all in one file. I would, however, keep all methods for a class together. You have several methods of Node, then 2 methods of NodePointerComp, then more methods of Node. It makes it a little hard to find things when examining the source. So I'd move all methods from a single class together into 1 section. You might also want to add either a comment break between them (just something like //----NodePointerComp methods----) or, if your compiler supports it, something like a #pragma mark NodePointerComp. In my IDE, when the editor sees #pragma mark <Name>, it adds <Name> to the pop-up menu with all the functions in it. That makes it really easy to navigate to those methods quickly.
Simplify
It looks like you're using the convention of a negative value representing whether a node is the end of a word or not. I originally thought that you were trying to define the last node in a branch, but I see from the comments I was mistaken. That's a good indication that the name is too confusing and the implementation too complex.
I'm not an expert on the C++ spec, but I thought that whether char was signed or not (when not explicitly specified) was implementation-dependent. Even if it's not, that's a tenuous way to determine the end of a word. I recommend a bool that says it's the end of a word. It would simplify the get_leaf() and set_leaf methods(). Also they should be renamed to is_word_end() and set_word_end().
Encapsulation
I'm a little uncomfortable with Node::children being public. That's an implementation detail, and I think it would be a good idea to hide that detail from users of the class. It would make the logic in Trie slightly less straightforward, but I think the tradeoff would be worth it in the long run. Right now, Trie can modify that variable and Node won't necessarily be aware of it. It also makes it more difficult to use in a multithreaded environment, should you need to do that. If it were private, you could ensure that it was never accessed outside of some sort of lock (or mutex, whatever) inside the class.


Function that returns another function, for a programming task

The name function_generator could be improved. What this function does is to evaluate the polynomial at the given value x. So a name like evaluate would be better.
The body of function_generator can be simplified. First, it's simpler to iterate over L in reversed order, because then you can start with k = 0 rather than k = len(L) - 1:

def evaluate(L, x):
    k = 0
    sum = 0
    for number in reversed(L):
        sum += number * x ** k
        k += 1
    return sum

Now that k goes upwards, you can use enumerate to generate the values for k:

def evaluate(L, x):
    sum = 0
    for k, a in enumerate(reversed(L)):
        sum += a * x ** k
    return sum

And now that the body of the loop is a single expression, you can use the built-in sum function to do the addition:

def evaluate(L, x):
    return sum(a * x ** k for k, a in enumerate(reversed(L)))

Another approach to polynomial evaluation is to generate the power series in \$x\$ separately:

def power_series(x):
    "Generate power series 1, x, x**2, ..."
    y = 1
    while True:
        yield y
        y *= x

and then combine it with the coefficients using zip:

def evaluate(L, x):
    "Evaluate the polynomial with coefficients in L at the point x."
    return sum(a * y for a, y in zip(reversed(L), power_series(x)))

This is more efficient for large polynomials because each step in power_series is a multiplication by x, which is cheaper to compute than the exponentiation x ** k.

Finally, you could take advantage of this transformation: $$a_k x^k + a_{k-1} x^{k-1} + \dots + a_1x + a_0 = (\cdots ((0 + a_k)x + a_{k-1})x + \cdots + a_1)x + a_0$$ and write:

def evaluate(L, x):
    "Evaluate the polynomial with coefficients in L at the point x."
    r = 0
    for a in L:
        r = r * x + a
    return r

(This is Horner's method.)
There's no need for function, because it's fine for the body of function_generator to refer to nonlocal variables like L. So you can write:

def general_poly(L):
    "Return function evaluating the polynomial with coefficients in L."
    def evaluate(x):
        r = 0
        for a in L:
            r = r * x + a
        return r
    return evaluate

An alternative approach is to use functools.partial:

from functools import partial

def evaluate(L, x):
    "Evaluate the polynomial with coefficients in L at the point x."
    r = 0
    for a in L:
        r = r * x + a
    return r

def general_poly(L):
    "Return function evaluating the polynomial with coefficients in L."
    return partial(evaluate, L)

This would be useful if you sometimes wanted to call evaluate directly (instead of via general_poly).


Code Style

Whitespace and Braces

Be consistent in your usage of whitespace and braces. for and if statments should have a space between the keyword, parentheses, and opening brace (if using K&R style braces). Also, don't omit braces in an if, then include them in the else. For example:

if( *internal_it == *pat_it)
    pat_it++;
else{ // ...

Becomes:

if(*internal_it == *pat_it) {
    pat_it++;
} else { // ...

Reduce Variable Scope

it and internal_it are both declared outside their respective for statement, but are not referenced outside of it. Declaring them inside the for statement limits their scope to within the for loop, reducing opportunities for them to be misused. You can also use auto for type deduction, saving you the necessity of typing long iterator type names.

Reduce Nesting

Your code contains many nested if and for statements. This can make the code hard to read. If you have an if statement wrapping the entire loop body, you can reduce the level of nesting by inverting the condition and breaking early:

if(*it == *pat_it){
    // loop body
}

Becomes:

if (*it != *pat_it) {
    continue;
}
// loop body

Simplify, Simplify

Your inner for loop has almost exactly the same bounds as the outer loop. This can be simplified to a single loop over text and pattern each:

bool simplePatternMatch(const std::string &text, const std::string &pattern)
{
    // handle empty-string case
    if (pattern.empty() || text.empty())
    {
        return pattern.empty() && text.empty();
    }

    for(auto it = text.begin(); it != text.end(); it++) {
        auto pat_it = pattern.begin();
        while (pat_it != pattern.end() && *it == *pat_it) {
            ++it;
            ++pat_it;
        }
        if (pat_it == pattern.end()) {
            return true;
        }
    }

    //if we reach here there was no match
    return false;
}

You could change the while to a for and increment it and pat_it in the increment statement, but I find this more readable. Writing it this way also makes it explicit that there is a loop over each of your string arguments, which makes analyzing complexity much easier.

But wait! All that iterator comparison is complicated. Wouldn't it be nice if there was another way? Turns out, there is std::mismatch(), which is essentially what the inner loop does. Then the loop can be simplified:

for (auto it = text.begin(); it != text.end(); ++it) {
    const auto mismatches = std::mismatch(pattern.begin(), pattern.end(), it);
    if (mismatches.first == pattern.end()) {
        return true;
    }
}

Algorithm

Now that your function has been simplified a bit, it is easier to see that you have written a naive pattern match, which has complexity \$\mathcal{O}(mn)\$, where m is your pattern length, and n is the string length. You can improve upon this by implementing one of the well-known pattern-matching algorithms, like Boyer-Moore or Knuth-Morris-Pratt. I leave this as an exercise to you, both because it would make this answer too long, and it would be a good candidate for another question on Code Review.


Does this code fall into a design pattern?

The initialise reminds me a factory but it's not exactly a factory. It's fine if you don't use the same if-elseif structure in your code elsewhere. If you do pull out it to a factory class.

Just some idea:

1, Consider using an enum instead of the integer typeCode (eliminate magic numbers).

2, Maybe you should throw an IllegalStateException in the end of the initialise method with a message "Invalid typecode".

3, The same is true for the setTypeCode() method. Or set explicitly typeCode to 0 in the last line of the method if 0 is a valid value. (This is the implicit default value of the private int typeCode field.)

4, I'd rename the setTypeCode() to calculateTypeCode() which would return a TypeCode enum. Now it's more or less temporal coupling.

5, You should create a new getNextScreen() method in the CustomDialog class with the first four line of the displayDialog() method. Then call the getNextScreen() from the displayDialog() methods. It would remove some code duplication.

// CustomDialog class code
public Dialog createNextScreen() {
    DialogType dialogType = new DialogType();
    DialogBuilder dialogBuilder = new DialogBuilder();
    AbstractDialogFactory abstractDialogFactory =
        dialogType.getDialogType(DialogEnum.EXCLAMATION_DIALOG);
    Dialog nextScreen = dialogBuilder.buildDialog(abstractDialogFactory, text);
    return nextScreen;
}

// OkExclamationDialog, ExclamationDialog class code
public void displayDialog() {
    Dialog nextScreen = getNextScreen();
    ...
    ScreenController.displayNextScreenFadeTransition(nextScreen);
}


Inserting an entire form into MySQL database

Don't take shortcuts. Build a proper insert statement using a parameterized query and validate each of the form inputs that they're also of the proper type (ie., not sending a string into an integer field).

Do this to protect the integrity of your data, both from improper types and from malicious (or even unintended) attacks.

See this and other related questions on SO for constructing proper parameterized queries with MySql.

More than that, you don't want your class that deals with data inserts to also interact with your UI. These concerns should be seperated. Seperate your UI code from your business logic code from your data access code. Don't let these things mingle, because your UI could change, your logic could change, and your data strategy could change, and they could change independently.


The other answers have great hints that you should definitely follow.

However, since we are talking about passwords here, a little bit of extra security might not hurt. Especially if it's readily available in the secrets module in Python 3. secrets uses a cryptograhically strong random number generator (in contrast to the pseudo random number generator in the normal random module). There is a special warning in that regard in the docs of random. If you want to stick to random, at least use an instance of random.SystemRandom(), which is basically what secrets does. An example:

RNG = random.SystemRandom()

def password_generator(...):
    ...
    # The remaining values to fill
    type_ = list(types.keys())
    for rem in range(length - num_chars):
        char_list.append(RNG.choice(type_))
        # alternatively
        char_list.append(secrets.choice(type_))
    ...

random.choice uses what is called a pseudo-random number generator, i.e. an algorithm that generates a deterministic "randomly looking" sequence of bytes starting from a given seed. secrets.choice uses a randomness source implemented in the OS, which likely takes electrical noise and other things into consideration to generate non-deterministic random data. random.org has a comprehensive article on the differences at https://www.random.org/randomness/. And of course, there is also the obligatory Wikipedia page about Randomness.


Picking 10 distinct words 'randomly' from List of unique words

First off, don't make a new Random instance every iteration.

Secondly your approach is ineffective for larger numbers, and especially if the number of words to choose is closer to the number of words available. The odds that a word is not already among the chosen words can become so small it can take a long time for your code to complete. Imagine picking 1.000.000 words in random order from a list of 1.000.000, getting the last word is a 1 in a million chance to get right.

A simple but more efficient approach is to shuffle the words and then just take the head of the list :

List<String> words = new ArrayList<String>();
/* code to add 20 words */

Collections.shuffle(words);

System.out.println("word10 List: " + words.subList(0, 10));

Obviously you don't need to shuffle the entire list. You can write your own partial Fisher-Yates shuffle (basically swap your choices to the head of the list), that stops once enough of the list is shuffled. This is definitely a good choice if you're going to do this for large collections of words with only a small list to choose.


Is pattern matching within a unit test a code smell?

I don't think so. When a tested method returns a discriminated union, then using pattern matching in the unit test is natural.

  Do I really need to throw an exception just for my test to fail if the function under test receives invalid arguments (i.e. not Succeeded case value)?

Yes, I think you should. The reason for that is that if the function incorrectly returns something other than Succeeded, your test needs to fail. And throwing an exception is how you do that.

Also, if you're a fan of terseness, you can write the List.exists predicate as e.g. ((=) (0,4)), instead of using fun:

let northWestAvailable = coordinates |> List.exists ((=) (0,4))

Or, even better, use should contain:

coordinates |> should contain (0,4)

This is shorter, clearer and will also lead to clearer test failures.


Having models which inherit from one base model

I'm aware that composition is always considered a best practice.

I wouldn't say that it's always the best choice. Though I guess that's not what you're saying, since you chose inheritance anyway.

In general, best practices are just guidelines to keep in mind when designing and implementing your code.

In this specific case, I think that inheritance is the right solution.

#region Properties

I don't see the need to have these kinds of #regions all over your code. Your classes aren't humongous so normal code folding will work just fine.

InitMembers();

Why is this code in a separate method? Unless you have a good reason for that, just put it directly into the constructor.

public BaseServiceResponse(Guid patientId)
{
    this.PatientId = patientId;
}

This means that the other members aren't going to be initialized. You should probably delegate from one constructor to the other using : this() to fix this.

this.PatientId = Guid.Empty;
this.PracticeId = Guid.Empty;
this.Status = 0;
this.Message = string.Empty;
this.ReturnUrl = string.Empty;

The empty GUID and 0 are the default values for Guid and an enum, respectively, so you don't need to initialize them to that. Though it might make sense to do it anyway for clarity.

Initializing the string properties to empty string makes it less clear that the value is uninitialized and could potentially hide bugs.

public List<string> ReportNames;
public string SomeOtherProp;

These should be properties too, not public fields. And when you make ReportNames a field, consider making the setter private.

public FullReportResponse(Guid patientId, List<string> reportNames)
{
    this.PatientId = patientId;
    this.ReportNames = reportNames;
}

Consider making a copy of reportNames here. Otherwise, it's easy to write buggy code that passes the list to FullReportResponse and then reuses it for other purposes, which will change the FullReportResponse.

Also, consider accepting IEnumerable<string> to be more flexible.


functions

This is 1 long script. Partition the code in logical blocks. This could be like this

get the raw data
summarize the data
split the test- and train data
get the result from the regression
plot the results

magical values

there are some magical values in your code, for example 4 as the column, datetime(2013, 1, 1) as the threshold to split the data. Define them as variables (or parameters for the functions)

dummy data

to illustrate this, I use this dummy data

def generate_dummy_data(
    x_label="x",
    date_label="date",
    size=100,
    seed=0,
    start="20120101",
    freq="7d",
):
    np.random.seed(seed)

    return pd.DataFrame(
        {
            "Close": np.random.randint(100, 200, size=size),
            x_label: np.random.randint(1000, 2000, size=size),
            date_label: pd.DatetimeIndex(start=start, freq=freq, periods=size),
        }
    )

summarize

The rolling mean and std you do can be done with builtin pandas functionality

You also change the raw data. It would be better to make this summary a different DataFrame, and not alter the original data.

def summarize(df, date_label, x_label, y_label="Close"):
    return pd.DataFrame(
        {
            y_label: df[y_label],
            date_label: df[date_label],
            "day_5": df[x_label].rolling(5).mean(),
            "std_5": df[x_label].rolling(5).std(),
            "day_30": df[x_label].rolling(30).mean(),
        }
    ).dropna()

regression

here I followed pep-8, and renamed X_cols to x_cols

def regression(train, test, x_cols, y_col):
    lr = LinearRegression()
    lr.fit(train[x_cols], train[y_col])
    yhat = lr.predict(test[x_cols])
    mse = mean_squared_error(yhat, test[y_col])
    rmse = mse/len(yhat)
    score = lr.score(test[x_cols], test[y_col])

    return yhat, rmse, score

main guard

If you put the calling code behind if __name__ == "__main__":, you can import this script in other code without running the analysis, and reuse the functions

if __name__ == "__main__":

    x_label = "x"
    date_label = "date"
    y_label = "Close"
    data = generate_dummy_data(
        x_label=x_label, date_label=date_label, y_label=y_label
    )

    summary = summarize(
        data, date_label=date_label, x_label=x_label, y_label=y_label
    )

    threshold = "20130101"

    train = summary.loc[summary[date_label] < threshold]
    test = summary.loc[summary[date_label] >= threshold]

    x_cols = ["day_5", "std_5", "day_30"]

    yhat, rmse, score = regression(train, test, x_cols, y_col)

    print(x_cols, rmse, score)

    plt.scatter(yhat, test[y_col], c="k", s=1)
    plt.plot(
        [0.95 * yhat.min(), 1.05 * yhat.max()],
        [0.95 * yhat.min(), 1.05 * yhat.max()],
        c="r",
    )
    plt.show()

If you want to compare what each of the 3 metrics do individually, you'll have to do something like this:

for x_label in x_cols:
    yhat, rmse, score = regression(train, test, [x_label], y_col)

    print(x_label, rmse, score)

    plt.scatter(yhat, test[y_col], c="k", s=1)
    plt.plot([.95*yhat.min(), 1.05*yhat.max()], [.95*yhat.min(), 1.05*yhat.max()], c="r")
    plt.show()


What is $option in run_rsync?

option is read in the global scope to decide if user wants a full ingest or continue a partial ingest. In that loop that reads the prompt, the meaning of option is understandable.

Referring to $option in run_rsync is just too far away. It's not clear anymore where it comes from and what it means. It would be better if the prompt loop passed the decision to run_rsync as a parameter, to make it perfectly clear. For example:

while true
do
    read -r -p $'Enter [1] to start an ingest or [2] to complete a partial ingest.\n' option
    case $option in
        1 )
            make_directory
            run_rsync full
            break;;
        2 )
            run_rsync partial
            break;;
        * )
            echo $'Please enter a valid option!\n';;
    esac
done

And then in run_rsync:

run_rsync() {
    local ingestType=$1

    echo $'Follow the prompt to complete the rsync command.\n'

    prompt_user $'Path to source media?\n' source_path

    if [[ "$ingestType" = "partial" ]]; then
        prompt_user $'Target directory?\n' target_directory
        destination_path=$target_directory
    fi

    # ...

Inconsistent terminology

In make_directory, the term "target directory" refers to the base directory in which a timestamped sub-directory will be created, with brand name, project name, and so on, also in the name.

In run_rsync, in case of partial ingest the user is prompted for "target directory", but here it will mean the full destination path. If would be better to name it as such.

Inconsistent formatting

The code uses inconsistent indentation.
For example the content of prompt_user is over-indented, compared to other functions.
The body of the while loop in the global scope is over-indented,
and also haphazardly indented.
It would be easier to read if indenting was consistent throughout.

Unnecessary comments

Most comments in the program state the obvious.
They are just noise,
and it would be better to remove them.


dup f swap g is a common idiom, so Factor has bi.

: mult3or5? ( x -- ? ) [ mult3? ] [ mult5? ] bi or ;


Formatting

Now let's talk about formatting. Your code is hard to read. Format it. Done.

Actually, if you want some tips:

import java.util.*;
public class MergeTwoSortedLists {
    public static void main(String[] args)
    {

These lines of code have a couple of problems:

Line 1-2: Space between import statements and class declaration

Line 2-3: Space between class declaration and first line of code inside class

Line 3-4: Java conventions require that braces are on the same line as declaration

Result:

import java.util.*;

public class MergeTwoSortedLists {

    public static void main(String[] args) {

This code:

 java.util.Scanner input = new java.util.Scanner(System.in);

 // Enter values for list1
 System.out.println("Enter the amount of numbers in the first list:");
 // Assign user defined length to the array
 int lengthOfArray = input.nextInt();
 int[] list1 = new int[lengthOfArray];

 // i increments and the user values are assigned to the array until the length is exceeded
 System.out.println("Enter " + list1.length + " values: ");
 for (int i = 0; i < list1.length; i++) // line 11
  list1[i] = input.nextInt();

 // Enter values for list2
 System.out.println("Enter the amount of numbers in the second list:");
 // Assign user defined length to the array
 int lengthOfArray2 = input.nextInt();
 int[] list2 = new int[lengthOfArray2];

 // i increments and the user values are assigned to the array until the length is exceeded
 System.out.println("Enter " + list2.length + " values: ");
 for (int i = 0; i < list2.length; i++) // line 23
  list2[i] = input.nextInt();

 // Lists one and two are merged into one list
 int[] list3 = merge(list1, list2);
 // Sorts the lists in numerical order
 Arrays.sort(list3);
 // This accesses the actual user defined integers and not their locations, printing them in an assorted array
 System.out.println("The merged list is: " +Arrays.toString(list3));

all share a problem. That problem is that you are indenting it by only 1 space, Java conventions recommend 4-space tabs, or just 4 spaces.

Some other things:

Line 11 (as marked by comment): ALWAYS put braces to group if, else, while, do-while, for, and similar statements. Here is why.

Line 13 or 14: Two empty lines won't improve readability. Remove one.

Line 23 (as marked by a comment): Same thing as Line 11

Last line: Space before and after +

Result:

    java.util.Scanner input = new java.util.Scanner(System.in);

    // Enter values for list1
    System.out.println("Enter the amount of numbers in the first list:");
    // Assign user defined length to the array
    int lengthOfArray = input.nextInt();
    int[] list1 = new int[lengthOfArray];

    // i increments and the user values are assigned to the array until the length is exceeded
    System.out.println("Enter " + list1.length + " values: ");
    for (int i = 0; i < list1.length; i++) {
        list1[i] = input.nextInt();
    }

    // Enter values for list2
    System.out.println("Enter the amount of numbers in the second list:");
    // Assign user defined length to the array
    int lengthOfArray2 = input.nextInt();
    int[] list2 = new int[lengthOfArray2];

    // i increments and the user values are assigned to the array until the length is exceeded
    System.out.println("Enter " + list2.length + " values: ");
    for (int i = 0; i < list2.length; i++) {
        list2[i] = input.nextInt();
    }

    // Lists one and two are merged into one list
    int[] list3 = merge(list1, list2);
    // Sorts the lists in numerical order
    Arrays.sort(list3);
    // This accesses the actual user defined integers and not their locations, printing them in an assorted array
    System.out.println("The merged list is: " + Arrays.toString(list3));

Here:

public static int[] merge(int[] list1, int[] list2)
{
    int[] list3 = new int[list1.length + list2.length];
    // Both p and i increment, and list 3 is assigned the user defined integers from both list 1 and 2
    for (int i = 0, p=0 ; i < list1.length || i < list2.length ; i++) {
        if (i < list1.length) {
            list3[p++] = list1[i];
        }
        if (i < list2.length) {
            list3[p++] = list2[i];
        }
    }
    return list3;
    // line 15
}

Looks pretty good, but some points:

Line 1: Space between methods

Line 1-2: Java conventions require that braces are on the same line as declaration

Line 4: Space before and after =
Line 4: Usually no space is required before ;

Line 15: Extra newline at the end of the method is not necessary

Result:

public static int[] merge(int[] list1, int[] list2) {
    int[] list3 = new int[list1.length + list2.length];
    // Both p and i increment, and list 3 is assigned the user defined integers from both list 1 and 2
    for (int i = 0, p = 0; i < list1.length || i < list2.length; i++) {
        if (i < list1.length) {
            list3[p++] = list1[i];
        }
        if (i < list2.length) {
            list3[p++] = list2[i];
        }
    }
    return list3;
}

Review

import java.util.*;

Never import an entire package, even if you are using a lot of the package. In this case, all you need is `Scanner, so that's even worse.

import java.util.Scanner;

is what you should do.

java.util.Scanner input = new java.util.Scanner(System.in);

Why are you using the full name when you just imported it?

Scanner input = new Scanner(System.in);

Now, to your merge method:

The method should be private
Since you are sorting the array anyways, it is more efficient to sort the arrays, then merge them, like the final step of merge sort:

private static int[] merge(int[] array1, int[] array2) {
    int length1 = array1.length;
    int length2 = array2.length;

    int[] array = new int[length1 + length2];

    int index1 = 0;
    int index2 = 0;

    while (index1 < length1 && index2 < length2) {
        array[index1 + index2] = array1[index1] < array2[index2]
                ? array1[index1++]
                : array2[index2++];
    }
    while (index1 < length1) {
        array[index1 + index2] = array1[index1++];
    }
    while (index2 < length2) {
        array[index1 + index2] = array2[index2++];
    }
    return array;
}

Final Code:

import java.util.Scanner;

public class MergeTwoSortedLists {

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

        // Enter values for list1
        System.out.println("Enter the amount of numbers in the first list:");
        // Assign user defined length to the array
        int lengthOfArray = input.nextInt();
        int[] list1 = new int[lengthOfArray];

        // i increments and the user values are assigned to the array until the length is exceeded
        System.out.println("Enter " + list1.length + " values: ");
        for (int i = 0; i < list1.length; i++) {
            list1[i] = input.nextInt();
        }

        // Enter values for list2
        System.out.println("Enter the amount of numbers in the second list:");
        // Assign user defined length to the array
        int lengthOfArray2 = input.nextInt();
        int[] list2 = new int[lengthOfArray2];

        // i increments and the user values are assigned to the array until the length is exceeded
        System.out.println("Enter " + list2.length + " values: ");
        for (int i = 0; i < list2.length; i++) {
            list2[i] = input.nextInt();
        }
        // Sorts the lists in numerical order
        Arrays.sort(list1);
        Arrays.sort(list2);

        // Lists one and two are merged into one list
        int[] list3 = merge(list1, list2);
        // This accesses the actual user defined integers and not their locations, printing them in an assorted array
        System.out.println("The merged list is: " + Arrays.toString(list3));
    }

    private static int[] merge(int[] array1, int[] array2) {
        int length1 = array1.length;
        int length2 = array2.length;

        int[] array = new int[length1 + length2];

        int index1 = 0;
        int index2 = 0;

        while (index1 < length1 && index2 < length2) {
            array[index1 + index2] = array1[index1] < array2[index2]
                    ? array1[index1++]
                    : array2[index2++];
        }
        while (index1 < length1) {
            array[index1 + index2] = array1[index1++];
        }
        while (index2 < length2) {
            array[index1 + index2] = array2[index2++];
        }
        return array;
    }

}


I usually make some simple helper functions to simplify and shorten the code building html. (As your programme gets more complicated you can expand these to suit your needs, or if you prefer, switch to a library like jquery.) In the version below I have also added a few lines to add a total row to the table. However, think about whether you need to rewrite the entire table each time it changes, or could simply add or delete individual rows. If the latter, you would want something like addRow, deleteRow and updateTotal methods.

function build(parent, type, innerHTML) {
    // Make a new element, optionally fill it with html, append it to the parent,
    // and return it.
    var el = document.createElement(type);
    if (innerHTML) {
        el.innerHTML = innerHTML;
    }
    parent.appendChild(el);
    return el;
}

function E(id) {
    // This function has no purpose except to save typing
    return document.getElementById(id);
}

function ShoppingList() {
    var totalCell;
    this.items = [];
    this.setItem = function (product, price) {
        var item = new Item(product, price);
        this.items.push(item);
    };
    this.render = function () {
        E('shoppingList').innerHTML = "";
        E('message').innerHTML = "";
        var tr = build(E('shoppingList'), 'tr');
        tr.id = 'header';
        build(tr, 'th', 'Product');
        build(tr, 'th', 'Prijs');
        build(tr, 'th', 'Verwijder');
        var totalPrice = 0;
        for (var i = 0; i < this.items.length; i++) {
            tr = build(E('shoppingList'), 'tr');
            tr.id = i;
            build(tr, 'td', this.items[i].product);
            build(tr, 'td', this.items[i].price);
            build(tr, 'td', 'Verwijder').addEventListener('click', delItem, false);
            totalPrice += this.items[i].price;
        }
        tr = build(E('shoppingList'), 'tr');
        build(tr, 'td', 'Total');
        totalCell = build(tr, 'td', totalPrice);
        build(tr, 'td', '');
    };
}


"Guess my Number" game in Python (2.7.9)

Magic numbers

1, 10, and 5 are so-called magic numbers in the code: they are duplicated in many places. The numbers themselves don't carry a meaning, but they are special to the program. If you wanted to change the maximum number of tries, you would have to manually search and replace all occurrences of 5. If the number 5 is used for other than the purpose of maximum number of tries, then the change will be especially difficult, as you would have to review each occurrence to verify its purpose.

The solution is simple: give the magic numbers meaningful names, for example:

lower_limit = 1
upper_limit = 10
max_tries = 5

You might even want to make these constants by uppercasing the names.

Copy-paste coding

This piece of code appears multiple times:

remaining = 5 - tries
print("\nYou have " + str(remaining) + " guesses left.\n")

Most probably you copy-pasted it every time you needed.
Try to avoid pressing ControlV while programming.
Try solution is almost always to create a new function, for example:

def print_remaining_guesses(tries):
    remaining = max_tries - tries
    print("\nYou have " + str(remaining) + " guesses left.\n")

Use "{}".format(...) for formatting

Instead of:

print("\nYou have " + str(remaining) + " guesses left.\n")

The recommended way is:

print("\nYou have {} guesses left.\n".format(remaining))

This is a kind of templating. By removing + varname + from the middle of strings, the text becomes a bit easier to read. Another benefit is that you can drop the str(...) wrapper, format will automatically take care of that for you.

Pull common operations up

Looking at this code:

if guess > 10:
    tries += 1
    print("\nWay too high! Try a number 10 or lower.")
else:
    tries += 1
    print("\nTry something lower.")

The value of tries will be increment no matter what. So you can pull it up, out of the if-else:

tries += 1
if guess > 10:
    print("\nWay too high! Try a number 10 or lower.")
else:
    print("\nTry something lower.")

Keep try blocks small

You have a very large try block here:

try:
    guess = int(guess)

    # ... many lines ...

# Input not an integer
except ValueError:
    # ...

Since the only place where you expect something to go wrong is the guess = int(guess) line, it would be better to wrap only that in the try-except.

Comparison with boolean values

Don't use == or != with boolean values. Instead of:

while correct == False:

The recommended way is:

while not correct:

Pointless comments

The comments on these lines really don't tell anything new:

if guess == number:  # Correct answer
    # ...

elif guess > number:  # Guess too high

Let the code speak for itself. Then you really don't need comments at all.

Formatting

The space between print and ( is redundant, you should remove it:

print ("I'm thinking of a number between 1 and 10.")

Python has an official style guide called PEP8, I suggest to review it and follow it.


Determining whether two two-digit numbers share a digit in common

You can simplify the boolean parts of your method.

public boolean shareDigit(int a, int b) {
    int lefta = a / 10;
    int righta = a % 10;
    int leftb = b / 10;
    int rightb = b % 10;
    return lefta == leftb || lefta == rightb || righta == leftb
            || righta == rightb;
}


User registration and authentication using hashed passwords

Nope, it is not safe. You can refer to the following article thet explains why you shouldn't use SHA-family hashing and required to use password_hash() instead. Beside other things, it means that salt field should be removed, and password field should be varchar(255).

To soften the pill, I've got the reference code to check the hashed passsword.

There is one more issue which is connected to security: wherever an error occurs, you are echoing it right in the hands of a potential hacker, revealing a lot of sensitive information about your software, database structure, etc. You should never ever be doing things like  echo "Error: " . $e->getMessage();! For more info refer to my article on the basics of PHP error reporting

Everything else is rather good, save for peculiar code formatting and unnecessary WHILE statement. When you expect just a single row, there is no need to run a while loop. Just fetch your row right away.

Also, it does no good to duplicate the database connection code. Store it in a file and just include wherever needed.

So the refactored version would be like

db.php:

<?php

$servername = "localhost";
$username = "whatever";
$password = "whatever";
$dbname = "whatever";
$charset = 'utf8mb4';

$options = [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_EMULATE_PREPARES   => false,
];
$dsn = "mysql:host=$servername;dbname=$dbname;charset=$charset";
try {
     $db = new PDO($dsn, $username, $password, $options);
} catch (\PDOException $e) {
     throw new \PDOException($e->getMessage(), (int)$e->getCode());
}

register.php

require 'db.php';
$hashpsw = password_hash($_POST["providedpass"],);

$stmt = $db->prepare("INSERT INTO users (username, password, level) VALUES (?,?,?)");
$stmt->execute(array($_POST["usrnm"], $hashpsw, 1));
echo "USER CREATED";

auth.php:

require 'db.php';
$stmt = $db->prepare("SELECT * FROM users WHERE username = ?");
$stmt->execute([$_POST['usrnm']]);
$user = $stmt->fetch();

if ($user && password_verify($_POST['providedpass'], $user['password']))
{
    echo "FOUND USER";
}


Three functions for computing simple arithmetic

There's a bit to say about this code, so I'll try to take it from the top and work my way down:

Declare main() after your functions so you don't have to declare those function prototypes at the beginning of your source code.
You shouldn't be printing anything from the functions other than main() here.  You should be returning the values to main() and handle them there.
You are restricting yourself by only accepting int parameters into your getsum() function.  I would use intmax_t from <stdint.h> instead.
You don't protect yourself from integer overflow within any of your functions. Take a look at this question and answer for an idea of how to implement that protection using the latest standards.
Why does your doDiv() function accept float values, and then return a double value?  Inconsistent and not what a programmer would expect.  Either return a float, or accept doubles as parameters.
Always declare what parameters your function takes in, even if nothing.

int main(void)

You might wonder why we have to do this.  Imagine we have the function foo() declared as such:

int foo()

In C, this is known as an identifier list and means that it "can take any number of parameters of unknown types".  We can actually pass values to the function even though we don't mean to or intend to.  If the caller calls the function giving it some argument, the behavior is undefined. The stack could become corrupted for example, because the called function expects a different layout when it gains control.

Using identifier lists in function parameters is depreciated.  It is much better to do something like:

int foo(void)

In C, this is known as a parameter type list and defines that the function takes zero arguments (and also communicates that when reading it) - like with all cases where the function is declared using a parameter type list, which is called a prototype.   If the caller calls the function and gives it some argument, that is an error and the compiler spits out an appropriate error.

The second way of declaring a function has plenty of benefits. One of course is that amount and types of parameters are checked. Another difference is that because the compiler knows the parameter types, it can apply implicit conversions of the arguments to the type of the parameters. If no parameter type list is present, that can't be done, and arguments are converted to promoted types (that is called the default argument promotion). char will become int, for example, while float will become double.
Use %g when printing float values.  It also allows you to print double if you decide to "upgrade" the type later.
You don't have to return 0 at the end of main(), just like you wouldn't bother putting return; at the end of a void-returning function. The C standard  knows how frequently this is used, and lets you not bother.

  C99 & C11 §5.1.2.2(3)

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

You asked me to comment on your formatting and documentation.  I find leading by example is a good way to learn something, so look at how I do it in this question of mine. Also, I use doxygen for my documentation generation.  I think it is a good habit that you should get into as well.


Regarding improving the code, here are some suggestions:

Reduce the number of conditions/loops. The whole method is doable in a single while loop. See below for an example.
Prefer nouns for names of variables and verbs for functions/methods. For instance, instead of calling the return value ReturnCheck, call it ReturnValue.
Refactor the code to handle the connection getting closed before getting all of the expected bytes. According to a Microsoft Winsock web page for the recv call, "If the connection has been gracefully closed, the return value is zero". At which point I believe your code will try again and get SOCKET_ERROR (with an error code of WSAENOTCONN). And then return false even though it may have missed only say the last byte expected.
Recognize values that are constant with the C++ const type qualifier (or constexpr as you've done for compile-time constants).
Seeing as how you used constexpr (available since C++11), go ahead and also prefer using auto.
Consider making the RecvAllBytes method a method of a class that the client can use too (I don't demonstrate this though).

Here's how this could look (I didn't compile and test this code but hopefully it works):

int Server::RecvAllBytes(std::shared_ptr<Connection> connection, char * data, int bytesExpected)
{
    WSASetLastError(0);

    auto bytesReceived = decltype(bytesExpected){0};
    while (bytesExpected > 0)
    {
        const auto bytesRequested = (bytesExpected > maxBufferSize)? maxBufferSize: bytesExpected;
        const auto returnValue = recv(connection->socket, data + bytesReceived, bytesRequested);
        if (returnValue == -1 || returnValue == 0)
        {
            return bytesReceived;
        }
        bytesReceived += returnValue;
        bytesExpected -= returnValue;
    }
    return bytesReceived;
}

And how it could be used:

const auto bytesReceived = server.RecvAllBytes(connection, bigBuffer, bigSize);
if (bytesReceived < bigSize)
{
    if (WSAGetLastError() != 0)
    {
        // handle error.
    }
    else
    {
        // handle connection closed before all bytes received.
    }
}


Map array of objects and apply condition

If you are not returning a new set of values from map just modifying the element, then you should just use each


Your fmap function is overly complicated. Array x is a Functor and Length and Pointer are obviously preserved by fmap, so:

instance Functor FixedLengthQueue where
  fmap f (FLQ a b x) =  FLQ a b $ fmap f x

There is listArray :: Ix i => (i, i) -> [e] -> Array i e, so you don't need zipping.

foldl' inc 0 xs is just length xs:

fromList :: [a] -> Maybe (FixedLengthQueue a)
fromList [] = Nothing -- Nonsensical empty fixed length queue
fromList xs
  = Just
  . FLQ len 0
  . listArray (0, len-1)
  $ xs
  where
    len = Prelude.length xs

Note the qualified use of Prelude.length. You can use

import Prelude hiding (foldl,foldl1,foldr,foldr1);
import qualified Prelude (length)

if you want length to always mean FixedLenghtQueue.length. Prelude.length will still be available.

Since all your internal arrays are 0-based, there is no need to store Length separately, it can be always retrieved by snd . bounds or rangeSize . bounds

Your FixedLengthQueue can be thought as a special array or a special list. So you can just construct the list or the array explicitly and use existing foldMap implementations. Here is code using innerArray approach:

instance Foldable FixedLengthQueue where
    foldMap f = foldMap f . innerArray where
        innerArray (FLQ l p a) = ixmap (bounds a) (mapIdx l p) a
        mapIdx l p i = (i + l - p) `mod` l

As for performance, you should benchmark your full application before optimization. Compositional style is not necessary worse performing so you should strive to write at as high level as possible before trying optimizations.

Also there is Data.Sequence which I think will perform better than Array while keeping you away from ST monad.

A useful typeclass instance to implement is Traversable. It is also cumbersome to implement as innerArray approach will work poorly:

instance Traversable FixedLengthQueue where
    traverse f = fmap fromArray . traverse f . innerArray where
        fromArray a = FLQ (rangeSize $ bounds a) 0 a

Interestingly, Prelude uses "innerList" approach - it converts an array to a list and back:

instance Ix i => Traversable (Array i) where
        traverse f arr = listArray (bounds arr) `fmap` traverse f (elems arr)

So I think the best we can do with Traversable is to use "innerList" approach too:

instance Traversable FixedLengthQueue where
    traverse f = fmap (fromJust . fromList) . traverse f . toList

Here is an Eq instance:

instance (Eq a) => Eq (FixedLengthQueue a) where
    (FLQ l1 _ _) == (FLQ l2 _ _) | l1 /= l2 = False
    q1 == q2 = toList q1 == toList q2

Here is another approach to implement toList:

indexList p l = range (p, l - 1) ++ range (0, p - 1)

toList' (FLQ l p a) = map (a !) $ indexList p l

I'm not sure that it's much better though, but the idea can be used everywhere:

eq (FLQ l1 p1 a1) (FLQ l2 p2 a2) = l1 == l2 && comp where
    r1 = indexList p1 l1
    r2 = indexList p2 l2
    comp = Prelude.all (\(i1, i2) -> (a1 ! i1) == (a2 ! i2)) $ zip r1 r2


"import translate" in a way that works with Python 2 and 3

No that's not the best way to import in both Python2 and Python3, if you have to support Python 2.5.0a1 and above.
This is as you can use:

from __future__ import absolute_import
from .core import translate

As documented in the __future__ module.


I find $.ajax().promise().then(fn) to be a little more confusing when looking at the code than it would have been if you instead used $.ajax().complete(fn) (or success if that is what you meant).
I would throttle the ajax post so that it doesn't happen on every keyup
if you are using the latest syntax already for $.ajax, I think it makes sense to use the .on method instead of .bind
some of the $() calls can be cached at various levels

So far the resulting code looks something like this (completely untested):

(function($, window){
    $.fn.extend({
        enableSearch:function(opts,callback){
            var timeout;
            var $t = this;
            return $t
                .on({
                    focus: function(){
                        $(this.form.elements).val(''); // clears all search inputs
                        $t.trigger('keyup'); // triggers the search on an empty input element
                    }, // END focus bind
                    keyup: function(){
                        var t = this;
                        if (timeout) { window.clearTimeout(timeout); }
                        timeout = window.setTimeout(function() {
                            var searchData = $.extend({}, {
                                source:t.form.id,
                                column:$t.attr('id'),
                                value:$t.val()
                            }, opts);

                            $.ajax({
                                url:opts.URL,
                                type:'post',
                                data:searchData,
                                dataType:'json'
                            }).complete(function(returndata){
                                callback(returndata);
                            }); // END ajax call
                        }, $.fn.enableSearch.throttle); //END setTimeout
                    } //END keyup
                }); //END on
        } //END fn enableSearch
    });
    $.fn.enableSearch.throttle = 150; //$.ajax will not happen until 150 ms delay happens between keystrokes
}(jQuery, window));

This code is still very specific to your particular case and isn't very reusable elsewhere. The only reasons I would even be making it into a plugin are testability and reuse. I suppose you may be able to reuse this on your application so that isn't much of a deal, but I feel like it requires too much knowledge of your specific implementation to be testable.


An implementation that uses the random module has the benefit of being platform independent. This code isn't going to run so well if you try it on Windows.

There is also another alternative. os.urandom() will use the underlying os to provide the random values.

  On a UNIX-like system this will query /dev/urandom, and on Windows it
  will use CryptGenRandom().

You can also use random.SystemRandom() if you still want the OS source, but want to use the interface provided by random.

This answer provides an implementation of chunks() that iterates instead of constructing a list of all the chunks.

I would also lean towards an implementation that opens the output file first, then writes to it as it iterates over the chunks. This way, you won't need to build a huge string in memory before writing it to disk. Similarly, I would generate the random values as needed.


Style, simplification and modularization for unit converter

Do you think your code is optimal?  You should be the first reviewer (along with the compiler).

Did you notice that you had to copy the
same code four times, once for each unit type.  Duplication of code is
generally bad and you should spot it yourself.  Your four input cases, meters,
cm, inches and feet all do the same thing:

convert to meters
push into vector
set low/high variables

Here's what the loop might look without the duplication:

double low = DBL_MAX;
double high = DBL_MIN;
...

while (cin >> num >> unit) {
    if (unit == "m") {
        meters = num;
    } else if (unit == "cm") {
        meters = num * cm_to_m;
    } else if (unit == "in") {
        meters = num * in_to_m;
    } else if (unit == "ft") {
        meters = num * ft_to_m;
    } else {
        cout << "Incorrect Unit Entered! Please try again..." << endl;
        continue;
    }
    input.push_back(meters);

    if (meters < low) {
        low = meters;
        low_unit = unit;
    } else if (meters > high) {
        high = meters;
        high_unit = unit;
    }
}

This is a lot simpler than your original code, having removed all of the
duplication.  Your tests for count == 0 are unnecessary if you set the
low/high variables to the limits of the range for double (all double values
are going to be less than or equal to DBL_MAX etc).   This leaves a continue
which many people would consider bad form and some coding standards outlaw.
To avoid this we could put the conversion into a function:

static bool convert_to_meters(double num, double &meters, const string& unit)
{
    const double cm_to_m = 0.01;
    const double in_to_m = 2.54 * 0.01;
    const double ft_to_m = 12 * 2.54 * 0.01;
    if (unit == "m") {
        meters = num;
    } else if (unit == "cm") {
        meters = num * cm_to_m;
    } else if (unit == "in") {
        meters = num * in_to_m;
    } else if (unit == "ft") {
        meters = num * ft_to_m;
    } else {
        return false;
    }
    return true;
}

And call it from the main loop:

while (cin >> num >> unit) {
    if (!convert_to_meters(num, meters, unit)) {
        cout << "Incorrect Unit Entered! Please try again..." << endl;
    }
    else {
        input.push_back(meters);

        if (meters < low) {
            low = meters;
            low_unit = unit;
        } else if (meters > high) {
            high = meters;
            high_unit = unit;
        }
    }
}

You then have another set of unit conversions done twice which could be
extracted to a function:

static double convert_from_meters(double meters, const string& unit)
{
    const double m_to_cm = 100;
    const double m_to_in = 100 * (1.0/2.54);
    const double m_to_ft = 100 * (1.0/2.54) * (1.0/12.0);
    double num = meters;
    if (unit == "cm") {
        num *= m_to_cm;
    } else if (unit == "in") {
        num *= m_to_in;
    } else if (unit == "ft") {
        num *= m_to_ft;
    }
    return num;
}

and called with:

low  = convert_from_meters(low, low_unit);
high = convert_from_meters(high, high_unit);

You finish with a loop to add all of the values in the vector.  There is a standard
algorith for this:

double sum = std::accumulate(input.begin(), input.end(), 0.0);

Note that your sorting of the vector seems to be unnecessary. However you
could determine the low/high values (without units) by looking at the first
and last items in the vector after sorting.  And if you gave up the
requirement to print the low/high values in their original units you would
need neither to save low/high and low_unit/high_unit every time round the
loop, nor to convert from meters back to original units.  The code then becomes
much simpler.

This might seem like cheating and in an exercise where the
requirements are set for you, it is.  But in the real world, simplifying the
requirements (which can often be fairly arbitrary and many times are
determined by you) can make a huge difference to the complexity and cost of
code.  Clearly the customer has to agree to any changes that affect the end
product.


Here are a number of things that may help you improve your code.

Use the required #includes

The code uses std::vector which means that it should #include <vector>.  It was not difficult to infer, but it helps reviewers if the code is complete.  This code appears to require the following:

#include <vector>
#include <sstream>
#include <string>
#include <iostream>

Provide complete code to reviewers

This is not so much a change to the code as a change in how you present it to other people.  Without the full context of the code and an example of how to use it, it takes more effort for other people to understand your code.  This affects not only code reviews, but also maintenance of the code in the future, by you or by others.  One good way to address that is by the use of comments.  Another good technique is to include test code showing how your code is intended to be used and the expected results.  The code, as posted, is just a program fragment, so I turned it into a function for testing:

std::vector<std::string> fetch_names(const std::string &text_content, const std::string &ext) {
    std::vector<std::string> attachment_names;
    std::istringstream words(text_content);
    std::string word;
    while (words >> word) {
        auto extension_found = word.find(ext);
        if (extension_found != word.npos) {
            auto name_start = word.find("'") + 1;
            std::string attachment_name = word.substr(name_start, (extension_found + 3) - name_start + 1);
            attachment_names.push_back(attachment_name);
        }
    }
    return attachment_names;
}

Fix the bugs

As posted, the extension was named pst_extension but was used as abc_extension so it wouldn't compile without some alteration.  More serious, however, is that the matching appears to be flawed.  It purports to look for a filename surrounded by single quotes but that's not what it actually does.  I wrote a small test program:

int main(int argc, char *argv[]) {
    if (argc != 2) {
        std::cout << "Usage: getfile filename\n";
        return 0;
    }
    std::ifstream in{argv[1]};
    for (std::string fn; std::getline(in, fn); ) {
        auto names = fetch_names(fn, ".abc");
        unsigned i=0;
        for (const auto &file : names) {
            std::cout << ++i << "\t[" << file << "]\n";
        }
    }
}

I then used it with this file:

file = "one.abc"
file='two.abc"
file   == three.abcd
file=four.ab
file='five.abcd'  file2='six.abcd'
file='seven.abc' file='eight.abc'

I would expect the output to be this:

1   [seven.abc]
2   [eight.abc]

But what it actually reported was this:

1   ["one.abc]
1   [two.abc]
1   [three.abc]
1   [five.abc]
2   [six.abc]
1   [seven.abc]
2   [eight.abc]

Consider regular expressions

First, it appears that the "file=" portion of the line is ignored.  The code actually acts on any matchine string within single quotes.  Assuming that's intentional, we can use regular expressions very easily for this:

#include <regex>
#include <iterator>

std::vector<std::string> fetch_names(const std::string &text_content,
            const std::string &ext) {
    std::vector<std::string> file;
    std::regex file_regex{"'(\\S+"+ext+")'"};
    auto begin = std::sregex_iterator{text_content.begin(),
              text_content.end(), file_regex};
    auto end = std::sregex_iterator{};
    for (auto it = begin; it != end; ++it) {
        file.push_back((*it)[1]);
    }
    return file;
}

This works with a fairly simple regular expression that looks for opening and closing single quote characters and assumes the filename is made of non-whitespace characters only.  If that's not the case for your program (e.g. if you wish to accept spaces within the file name), then you can adjust the regex accordingly.  For example, if you wish to allow either single or double quotes (but they must match) and the filename can include alphanumeric plus spaces and underscores, we can use this:

std::regex file_regex{"('|\")([ _[:alnum:]]+"+ext+")\\1"};

In this case, the actual filename portion is in the second grouping, so we would account for that by changing the loop:

for (auto it = begin; it != end; ++it) {
    file.push_back((*it)[2]);
}

If you want the code to explicitly look for the "file = " portion of the line as well, it's as simple as changing the regex to this:

std::regex file_regex{"file\\s*=\\s*('|\")([ _[:alnum:]]+"+ext+")\\1"};

Note that using a regex is often slower than alternatives, such as writing your own state machine, but is often fast enough and is extremely flexible.  Note for example, that we actually construct the regex at runtime from a passed parameter.  This is both very flexible and potentially dangerous, so any user input should be sanitized before use.


I don't think its really SQL-injection, but $hostname is not taken from server but from DNS.

Theoretically i can add some kind of malicious domain name and affect your query. But from other hand, domain syntax is really limited. I don't think you can use it to do some serious thing.

Though i would recommend some error protection to avoid SQL-errors.

And correct mysql-escaping can never be bad ))


A proxy replacement for getters and setters

It's always going to be ugly
Getters and setters are never going to be as pretty in C++ as in some other languages that natively support them. Maybe something nice will be possible in a future C++ standard, but certainly not if you are stuck with C++11.
If you are going to use this to proxy member variables of a class, then the best syntax I can come up with is:
class foo {
    int x{123};
    static int getter(foo *self) { return self->x; }
    static void setter(foo *self, int val) { self->x = val; }
public:
    auto datum() { return make_proxy(this, getter, setter); }
};

The above allows the getter and setter access to the whole class, in case it wants to update multiple variables, or if the getter returns some function of multiple member variables. But unless you can reuse getters and setters, there is really not much point to it in my opinion.
The main reason is that either you have to write my_foo.datum() = 456, which has the added parentheses that make it not look like you are setting a regular member variable, or you have to declare datum like so:
class foo {
    ...
public:
    proxy<foo *, decltype(getter), decltype(setter)> datum{this, getter, setter};
};

That will allow you to write my_foo.datum = 456.
The former doesn't even work with C++11, since auto return type deduction doesn't work in that situation. You could add a trailing return type, but it will be ugly and repetetive. The latter has the overhead of storing three pointers for each proxy variable in your class.
It doesn't handle const instances
Your proxy class doesn't work if you create a const instance of a class that uses proxy member variables, for example:
const foo my_foo;
return my_foo.datum();

You could probably create a class const_proxy that only has a getter, and which ensures const is used in the right places, and then overload the proxy member like so:
class foo {
    ...
public:
     auto datum() { return make_proxy(this, getter, setter); }
     auto datum() const { return make_const_proxy(this, getter); }
};

But that adds even more noise.