The first thing I would do with this code is wrap the entire code in an IIFE.  This will create your own private scope and not pollute the global namespace.  Also, since you are using jQuery, you can pass in the jQuery object as $ to ensure that it is correctly mapped.

(function( $ ) {
  //your code here
})( jQuery );

Next, you have each droppable in its own document.ready call.  That is unnecessary.  You only need one call. We will add that in at the end of the code.

Since most of your code is actually in the event handler and it is almost entirely the same for each instance, we can DRY out your code. Just pass in a string that contains the one difference between each function and cache some of the variables.

function dropHandler( item ) {
  $('.ui-selected.' + item).each( function() {
    var $curr = $('#' + item), val = $curr.val(), html = $(this).html();
    $curr.val( ( val === "" ) ? html : val + ", " + html;
  });
}

With this in place, we just need a to loop over all of your items.  So add each input name into an array and loop over it creating the droppables.

var fields = ['dest_city','dest_state','car']

function init() {
  var len = fields.length;
  for( var i = 0; i < len; i++ ) {
    $('#' + fields[i] ).droppable({
      drop : function(event, ui) {
        dropHandler( this.id );
      }
    });
  }
}

Last just add a call to the init function on document.ready.

$(function(){
  init();
});

After these changes, here is the updated code:

(function( $ ){

  var fields = ['dest_city','dest_state','car'];

  function dropHandler( item ) {
    $('.ui-selected.' + item).each( function() {
      var $curr = $('#' + item), val = $curr.val(), html = $(this).html();
      $curr.val( ( val === "" ) ? html : val + ", " + html;
    });
  }

  function init() {
    var len = fields.length;
    for( var i = 0; i < len; i++ ) {
      $('#' + fields[i] ).droppable({
        drop : function(event, ui) {
          dropHandler( this.id );
        }
      });
    }
  }

  $(function(){
    init();
  });

})( jQuery );

Let me know if you have any questions or comments.


Instead Of Preface

My answer is split into three main parts.
The first two explain how to make the small-ish code changes to improve readability and decrease fragility.
The third part covers more of a design aspect which you may find important.

A. Tactical Improvements

1. TypeScript is about Types

Use explicit types wherever possible. This will:

Enable compile time errors (very helpful for nasty typo detection);
Help a lot during the code refactor (especially when it comes to signature changes). However, don't get too confident -- certain things are not being caught by the compiler.

In the code provided below, notice that all the signatures declare parameter types and return type.

1.1. Little Type Hint Trick

Often, frameworks or libraries return objects of type any. When this happens, the compiler loses the narrow type information making the code less reliable. As an example, we can see that response.json() in our Observables' map part is doing exactly that. Since we know, what object the remote service API is supposed to return us back, we can immediately cast that expression to the specific type and make the compiler our helper again: <ContactGroup>response.json().

It's important to understand though, that in runtime there is no guarantee that the return object is actually of the same type as the type we cast to. In other words, this cast is practically helpful, but is sometimes misleading and should be used carefully.

2. Master JavaScript and TypeScript idioms

TypeScript is a superset of JavaScript, i.e. whatever is syntactically correct in JS is also correct in TS.

Therefore, instead of looping through the items and writing them to console one by one, you can use the spread operator console.log('Contact id list', ...response.contacts), where response.contacts is an array.
Another thing is the var/let/const. As a rule, I start with const and switch to let only when feel it necessary or pragmatic. This approach forces me to think in a way more functional programming way which I find less error prone compared to imperative style. A thing (variable) does not have to be a constant in physical, mathematical, or business-logic sense of this word like Pi, Epsilon, Gravitational constant, etc. to be declared as const. It's just an instruction to the compiler the you don't want this thing to be reassigned down the road. This practice prevents accidental assignments (source of bugs) and pushes towards cleaner code.

I am very new to JavaScript myself, therefore it is hard for me to notice any other non-idiomatic pieces of code.

B. Slightly Different Code

Please notice that this is not a refactoring since I don't know what your models exactly look like.

    private contacts: Contact[] = [];
    private contactGroups: ContactGroup[] = [];

    loadContactsAndContactGroupsTogether(): void {
      Observable
        .forkJoin([
          this.http.get('Contacts/').map(response => response.json()),
          this.http.get('ContactGroups/').map(response => response.json())
        ])
        .subscribe(
          results => {
            const contactsListResponse = <ContactsListResponse>results[0];
            const contactGroupsListResponse = <ContactGroupsListResponse>results[1];

            this.loadContacts(contactsListResponse.contacts);
            this.loadGroups(contactGroupsListResponse.contactgroups);
          },
          error => console.error(error));
    }

    loadContacts(contactIdList: string[]): void {
      Observable
        .forkJoin(
          contactIdList.map(
            contactId => this.http.get(`Contacts/${contactId}`).map(response => <Contact>response.json())
          )
        ).subscribe(
          data => this.contacts = data,
          error => console.error(error)
        );
    }

    loadGroups(groupIdList: string[]): void {
      Observable
        .forkJoin(
          groupIdList.map(
            groupId => this.http.get(`ContactGroups/${groupId}`).map(response => <ContactGroup>response.json())
          )
        ).subscribe(
          data => this.contactGroups = data,
          error => console.error(error)
        );
    }

  }

Here's the assumed structure of your models

class ContactsListResponse {
  contacts: string[];
}
class ContactGroupsListResponse {
  contactgroups: string[];
}
class Contact { }
class ContactGroup { }

C. Strategic Improvements

One question you may want to ask yourself whenever assessing a system or its part is: Does it scale [well]?

There's an issue with the way we load data. If Contacts/, ContactGroups/, Contacts/{id}, or ContactGroups/{id} API or their combination return(s) enormous amount of data, our single page application (SPA) is very likely going to screw up:

The application user experience cay suffer if we load too many records (scrolling through more than a few dozens of records is rarely enjoyable).
The application responsiveness cay be at risk if we load even more data. The numbers vary a lot, but I've seen SPAs that show noticeable lags while displaying "just 300 rows of data". That was the result of many things including heavy client-side calculation, sub-optimal code, and other...
The application can become unstable (may freeze or even crash the browser). If the contact/contactGroups API(s) does not limit the response at all, and returns many megabytes of data, SPA will attempt to consume whatever memory is needed to accommodate all the records.

All of these scenarios are failures from the business perspective which only vary in scale. Here are a few techniques you may want to consider as countermeasures (you can search for more).

Client-side filtering or Infinite scrolling be helpful for keeping the UX enjoyable. The infinite scrolling may be not very easy to implement very efficiently. Also, both techniques are unlikely to help with the responsiveness and stability issues in worst cases.

Server-side filtering ("search") and Pagination are a couple of effective ways to guarantee that the amount of data given to the client has a controllable limit. These things require either the API changes or client-side changes or both.

Disclaimer

I apologize in advance if my answer is too broad -- your question does not include a concrete set of aspects you'd like to get covered in review and I tried to point out some small and some bigger things.


Find out whether string A can be shifted to get string B

You can check if the String is empty with !str instead of strA.length === 0,

console.log(''); // false

i think haveSameLength and isSame are extras, you can write srtA.length === strB.length and it would still be readable,

you can get the first letter with a simpler strA[0] instead of strA.substring(0, 1);

  Which one is more readable and easier to understand for you?

a loop is easier to read and understand than a recursive function,

But the hole approach seems like it can be simpler using a for loop, Array.some() , here's what i would suggest :

You can generate an array of combinations moving the letters one index at a time,
for a string abc you would have ['abc, bca', 'cba'], see if one of the resulting array entries euqals the second string :

const isSameAfterShifting = (str1, str2) => {
  // check if the strings are empty or has different lengths
  if (!str1 || !str2 || str1.length !== str2.length) return false;

  // check if the strings are the same
  if (str1 === str2) return true;

  // generate the array
  let combos = [];
  for (let i = 0; i < str1.length; i++) {
    let c = str1.slice(i) + str1.slice(0, i);
    combos.push(c);
  }

  // for a string 'abc'
  // combos = ['abc', bca', 'cab']

  // check if the array has one of its entries equal to the second string
  return combos.some(s => s === str2);
}

console.log( isSameAfterShifting('abc', 'cab') );
console.log( isSameAfterShifting('abc', 'cabaaa') );
console.log( isSameAfterShifting('abc', 'bac') );

you can replace the for loop with Array.from()

const isSameAfterShifting = (str1, str2) => {
  // check if the strings are empty or has different lengths
  if (!str1 || !str2 || str1.length !== str2.length) return false;

  // check if the strings are the same
  if (str1 === str2) return true;

  // generate the array
  let combos = Array.from({
    length: str1.length
  }, (_, i) => str1.slice(i) + str1.slice(0, i));

  // for a string 'abc'
  // combos = ['abc', bca', 'cab']

  // check if the array has one of its entries equal to the second string
  return combos.some(s => s === str2);
};

console.log(isSameAfterShifting("abc", "cab"));
console.log(isSameAfterShifting("abc", "cabaaa"));
console.log(isSameAfterShifting("abc", "bac"));


Yes, u can do like this. But some scenario doesn't work.

Scenario 1: If controller has 5 parallel services, at that time loader will get ended after any response received in out of 5.

Scenario 2: We don't need to show loader to some of the services, internally we will call based on the click or any action. At that time it will fail.

Instead of using interceptor better use that flag in respective controller itself or u have to pass additional flag in the header to hide and show loader via interceptor. My suggestion is handle that in respective controller itself.


Find the next empty column on a chessboard

Manually listing the numbers from 0 to 7 is a bad sign; I would definitely consider your first method more readable.

Have you considered using an array(-like) of booleans instead of a set, though?

// given array<bool, 8> used;
auto const it = std::find(used.cbegin() + col, used.cend(), false);

if (it == used.cend())
    return false;

col = std::distance(used.cbegin(), it);

It should be faster, too, with no downside that I can think of (since your set and array capacity will be the same).

Then there’s the possibility that the overall code can be structured so you only need an iterator and never an index (except to produce results)…

Alternatively, it still makes the first method simpler.

for (; col < 8; ++col)
    if (!used[col])
        break;

if (col == 8)
    return false;

or

while (used[col])
    if (++col == 8)
        return false;


I don't program in C and I don't know the exact input strings that you're expecting, but I can offer a couple of regex suggestions based on reasonable assumptions.

Your regex:

@"Host: (((?<hostName>.+?):(?<port>\d+?))|(?<hostName>.+?))\s+"

Your pattern looks for a hostname followed by a colon then a port number then whitespace characters OR a hostname followed by whitespace characters.

Since you are not capturing the whitespace and merely using the whitespace as an end point, the pattern can be reconfigured.
Since the colon-port substring is optional, the zero or one quantifier ? can be used to eliminate the redundant named capture group (which was causing trouble at regex101.com).
+? calls for "lazy" matching.  If you want your pattern to execute quickly, rewrite your pattern to use greedy quantifiers.

New pattern:

@"Host: (?<hostName>[^:\s]+)(:(?<port>\d+))?"

Here is a cheap and cheerful demo: https://regex101.com/r/NqSJ8L/1/

Note, my above pattern could be massaged a few different ways.  For instance, you might use ^ and an m pattern modifier to anchor the pattern to the start of the line of text.  Again, I don't program in C, so I don't know if there are incapatabilities with certain pattern entities.

Or instead of a negated character class, you can list the valid character for a hostname:

@"Host: (?<hostName>[\w.-]+)(:(?<port>\d+))?"

P.s. It just occurred to me that my optional pattern will not always deliver a named capture group for the port, so if you don't want to write code to check that the port capture group is generated, here is OhMyGoodness's commented pattern without the trailing whitespace matching.  (?<= ) is a lookbehind. (?: ) is a non-capturing group.

Host: (?<hostName>[\w.-]+):?(?<port>(?:(?<=:)\d+)?)


Optimal way to Compare two arrays that are widely different

Sure, you can always write your own method for everything but if you are lazy you could just use LINQ with ToLookup + All + Count

var arr1 = new[] { 1, 2, 3, 4, 3, 2 };
var arr2 = new[] { 6, 7, 3, 4, 1, 2, 2, 3 };

var lookup1 = arr1.ToLookup(x => x);
var lookup2 = arr2.ToLookup(x => x);

var isFullyContained = lookup1.All(x => lookup2[x.Key].Count() == x.Count());

false - means arr1 is fully contained in arr2

The good thing about lookup is that you don't need the ContainsKey method because if the key does not exist it'll return an empty collection.

Review

You create a dictionary only for the first array but you need one for the second array too or otherwise you need to loop over it each time which is unnecessary. Just count the items and compare their counts.


Is this a good approach?

Sadly, nope.

  Or is there a better way to accomplish this task?

Yes.

Instead of manually sifting through pages and copying source code, use wget's site mirroring functionality to download the entire site. There are a lot of ways to do this with the various options wget has. HTTrack is also an option if you want the tool to mangle the structure, names, etc. But we only need to download the pages so wget is fine.

Next, instead of having a page that parses the page source for content, consider writing a Node.js script instead*. Use glob to grab the paths of all HTML files, cheerio to traverse and grab content from the HTML like jQuery, and Node's very own fs to read and write to files. Also, regular expressions are the worst tools to parse through HTML. That's a known fact, don't even go there.

In summary, you run wget to download the entire site, and the Node.js script to parse all the HTML that was downloaded. You'll probably spend half a day to a day tops to build this script and the next day you'll have parsed content in seconds.  You just saved 2 months worth of work right there.

With the answer above, the rest becomes irrelevant.

*Any language would actually do (Python, Ruby, PHP, etc). But since you wrote in JS, Node.js would probably make more sense.


readable validation with python regex and simple logic

When to use is not
Your usage of is not is incorrect. You want to use == when you're testing equality, like when you check if s doesn't equal a '0'. You want to use is not when checking for identity, like when you're ensuring two variables are of the same object.
def is_leading_zeros(s: str) -> bool:
    if s != '0':
        return s[0] != '0'
    return True

Clearer comparisons
Python has a syntax that allows you to do this:
def is_in_bounds(s: str) -> int:
    return 0 <= int(s) <= 255

Type Hints
You should add types hints to your functions, which display what types are accepted and returned from your functions. See above for an example of this.


Star imports are discouraged. It's preferable to specify what classes you're importing in most cases.

getR is a very poor method name unless R is well defined inside the domain you're operating in. It's preferable to clearly express, without abbreviations, what the method will be doing. get is also misleading because it implies a simple local operation to retrieve a value from a class, not a remote call.

When variables will not be reassigned, it's preferable to mark them as final. This expresses design intent and tells the reader they don't have to worry about the value of the variable changing.

Minimizes scope wherever possible. getR should probably be either private or public. Package-private seems unlikely to be correct.

startTime is never used and can be removed. Rather than creating a Calendar instance, System.currentTimeMillis() would be preferable to find the current time.

If getR needs a URL, it should probably take it as a parameter, rather than accepting a String. In particular, your error handling of a bad URL is highly dubious. The caller gets no notification of any type that the URL string was incorrect. Make them build a correct URL and handle the case where they can't before the getR call.

There's an argument to be made that setDoInput(true) is noise, and one to be made that it makes things clearer.

The only exception your method throws is if the error stream can't be closed. It's unclear what you expect the caller to be able to do about that.

Use try-with-resources where possible to leverage automatic closing of resources. Otherwise you need to always close resources in finally blocks or you risk exceptions preventing you from closing them.

Always use curly braces, even if they're not required. You prevent an annoying and difficult-to-find class of error, and you enhance readability in most cases.

In idiomatic java, catch belongs on the same line as }.

Always catch the most specific type of exception possible. Catching Exception may silently swallow current or future exceptions you didn't intend to handle.

Using assert to ensure invariants in non-production environments is a good practice, but note that assertions must be engaged at both compile time and run time to function. Most production environments won't (and shouldn't) have assertions enabled. Many development environments and compilations also won't have assertions enabled, so make sure that they're correctly activated if you intend to use them.

It's unclear to me why you're explicitly closing the error stream in that fashion, since you never need or use it otherwise. If you must close it, put it in a try-with-resources block.

You should almost certainly log the exception you're handling for debugging later.

Early returns can clarify the code. The only one return location paradigm is a holdover from when it was not possible to embed returns in the middle of a block of code. A helper method could do the replacements for you.

In idiomatic java, variables start with a lowercase letter. return would be preferable to Return.

Turning the if check into a guard clause would reduce indentation and simplify the logic.

As of Java 9, I believe (but you should confirm) that string concatenation is actually faster than using a StringBuilder in the simple case of appending strings to one another. I think the readability is a wash.

If you were to make all these changes, your code might look more like:

private static String getR(
        final String xml,
        final URL requestUrl,
        final int retryWaitTime,
        final int socketTimeOut) {

    final StringBuilder xmlString = new StringBuilder();
    HttpURLConnection connection = null;

    try {
        connection = (HttpURLConnection) requestUrl.openConnection();
        connection.setConnectTimeout(retryWaitTime);
        connection.setReadTimeout(socketTimeOut);
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Accept", "application/xml");
        connection.setRequestProperty("Content-Type", "application/xml; charset=UTF-8");

        try (final OutputStreamWriter writer =
                new OutputStreamWriter(connection.getOutputStream(), StandardCharsets.UTF_8)) {
            writer.write(xml);
        }

        final int statusCode = connection.getResponseCode();
        if (statusCode != HttpURLConnection.HTTP_OK) {
            return sanitize(statusCode + "^" + xml);
        }

        try (final BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
            String line;
            while ((line = br.readLine()) != null) {
                xmlString.append(line);
            }
        }
        return sanitize(xmlString.toString());

    } catch (final IOException e) {
        e.printStackTrace();
        return sanitize("X^" + xml);
    }
}

private static String sanitize(final String string) {
    return string.replace("\n", "").replace("\r", "");
}


Randomly selecting an adjective and noun, combining them into a message

Everything looks pretty straight-forward, there are just some idiomatic changes to be made.

The function documentation, especially the argument and return value documentation, is mostly useless. In a statically typed language, the types provide a large amount of implicit documentation. Variable and method names tell another large chunk. Don't repeat all that compiler-checked documentation in your prose. Maybe even think about introducing new types for documentation purposes!
The type is also encoded in the name in certain places, which risks being redundant. — file_path: &Path.
Instead of requiring &Path, use AsRef<Path> to accept more types and improve the ergonomics at the call site.
It's inefficient to evaluate the path's display before it's needed. Since it's only used for error cases, only evaluate it in error cases. This is another way of saying to scope variables as tightly as possible.
There's no reason to create a variable to return it in the next statement; just return it directly — match {...} instead of let foo = match {...}; foo.
Call trait methods directly when possible, instead of using the Universal Function Call Syntax (UFCS) — foo.description() instead of Error::description(&foo).
read_to_string doesn't return an Ok(content), it returns the number of bytes read. This variable name is misleading.
If only one branch of a match statement is used, it's better to use an if let statement.
Functions shouldn't take a String if they just reading from it, it's better to take a &str as it is more accepting.
Functions shouldn't take a Vec<T> if they just reading from it, it's better to take a &[T] as it is more accepting.
Use expect instead on unwrap as it will help you find logic errors much easier when they happen. They may also help end users figure out problems on their own.
There's no need to specify the item type when collecting into a collection like a vector. You can use the placeholder _ instead — Vec<_>.
selfcare is confusingly named.
It's better to get the random number generator just once and reuse it.
When writing the sentence to the output, the code doesn't care if it's a string, just that it's printable. Accept a generic type that is printable instead.

extern crate rand;

use rand::Rng;
use std::env;
use std::error::Error;
use std::fs::File;
use std::io::prelude::*;
use std::path::Path;

fn read_lines<P>(file_path: P) -> Vec<String>
    where P: AsRef<Path>
{
    let content = read_file(file_path);
    split_lines(&content)
}

fn open_file<P>(file_path: P) -> File
    where P: AsRef<Path>
{
    let file_path = file_path.as_ref();
    match File::open(file_path) {
        Err(why) => panic!("Couldn't open file {}: {}", file_path.display(), why.description()),
        Ok(file) => file,
    }
}

fn read_file<P>(file_path: P) -> String
    where P: AsRef<Path>
{
    let file_path = file_path.as_ref();
    let mut file = open_file(file_path);
    let mut content = String::new();
    if let Err(why) = file.read_to_string(&mut content) {
        panic!("Couldn't read file {}: {}", file_path.display(), why.description());
    }
    content
}

fn split_lines(string: &str) -> Vec<String> {
    string
        .lines()
        .map(ToOwned::to_owned) // Nice
        .collect()
}

/// Chooses random adjective and noun from file, combines into message.
///
/// This function does not return the message, but prints it to stdout.
/// The message is in the format "You are a <adjective> <noun>."
fn selfcare<S>(adj: &[S], nouns: &[S])
    where S: std::fmt::Display
{
    let mut rng = rand::thread_rng();
    let adjective = rng.choose(adj).expect("No adjective found");
    let noun = rng.choose(nouns).expect("No noun found");
    println!("You are a {} {}", adjective, noun)
}

/// Print random inspiring message in format "You are a <adjective> <noun>".
///
/// Takes command line args `adj_file` and `noun_file`, respectively the paths
/// to the file containing the adjectives and the containing the nouns.
fn main() {
    let mut args: Vec<_> = env::args().collect();
    if args.len() == 1 {
        args.push("adjectives.txt".to_string());
        args.push("nouns.txt".to_string());
    }
    let adj = read_lines(&args[1]);
    let nouns = read_lines(&args[2]);
    selfcare(&adj, &nouns);
}

I'd also probably roll all the file stuff into one method:

fn read_lines<P>(file_path: P) -> Vec<String>
    where P: AsRef<Path>
{
    let file_path = file_path.as_ref();

    let file = match File::open(file_path) {
        Err(why) => panic!("Couldn't open file {}: {}", file_path.display(), why.description()),
        Ok(file) => file,
    };

    let buf = BufReader::new(file);

    buf.lines().map(|line| {
        match line {
            Ok(l) => l,
            Err(why) => panic!("Couldn't read file {}: {}", file_path.display(), why.description()),
        }
    }).collect()
}

Note that this also allows me to use BufRead::lines, which is probably more efficient than reading the entire file into memory and then splitting it.

I'm also not the biggest fan of burying print statements in my code. You even have comments warning the caller about that! Instead, check out this exciting change:

/// Chooses a random adjective and noun.
fn selfcare<A, N, F, T>(adj: &[A], nouns: &[N], f: F) -> T
    where F: FnOnce(&A, &N) -> T
{
    let mut rng = rand::thread_rng();
    let adjective = rng.choose(adj).expect("No adjective found");
    let noun = rng.choose(nouns).expect("No noun found");
    f(adjective, noun)
}

// ...

selfcare(&adj, &nouns, |adjective, noun| println!("You are a {} {}", adjective, noun));

This pushes the printing to the outermost layers of your program, where it belongs :-) It also opens a new name for selfcare - random_adjective_and_noun, thus allowing you to delete the comment. Note that the requirement for being able to print the value disappears, and I took the opportunity to allow the adjective and noun to be different types (which is a bit of YAGNI).

Thinking about your main method, it seems a little strange to push into the args vector to provide default values. Instead, I might combine Vec::get and Option::map_or to provide defaults:

let args: Vec<_> = env::args().collect();
let adj_filename = args.get(1).map_or("adjectives.txt", |f| &**f);
let noun_filename = args.get(2).map_or("nouns.txt", |f| &**f);
let adj = read_lines(adj_filename);
let nouns = read_lines(noun_filename);

This has the benefit of not needing to allocate the fallback filenames, and it handles the case of providing the first filename and not the second. In fact, you don't have to even collect the arguments anymore, you could just use the args iterator directly. However, putting them into a vector is pretty standard.


Passing variable pointer as string to another function

There is not much to be reviewed here.

Function IsObject does it's job correctly and there is not much to be said there.

What would have to be reviewed is the real code that would need IsObject and memory management technique you have shown in your demo. Since your demo is just a demo it doesn't show real life issue you are trying to resolve, and therefore it is impossible to give you any tips and advice on how to improve it.

All I can say is don't ever manage memory like that, and if you really, really feel the need to do so, then post such code here for review. Unless you have some real corner case there, I am quite sure that such code can be thoroughly reviewed and refactored.

So, your code is perfectly fine except you should not be using it anywhere :)


I was wondering if this is good

Well, are you just looking to prevent the normal user from messing up during registration? I think it would be fine for that.

I'll see if I can point out flaws in your validation...

First, you check to see if length is 0. If it is, you warn them. Cool. But right after, you check to see if it's greater than 0. This is redundant? It would have to be longer than 0 characters to pass the first conditional!
Now you check length < 7. But what if my email is a@a.ca? Eeek! But I was lucky and set up my domain www.a.ca with email support and registered with my first initial!
Why can't the username be longer than 30 characters? Is your database not capable of such long strings? If it truly just cannot handle those awfully long names, fine. If it can, I'd suggest you support long names! Besides, I'd hate to find a new username if I've always used my most favorite 32 characters username!
Why can't my password be longer than 50 characters either? I might be one of those users who has funky passwords that are always has 9 words in their passwords.
What exactly is passwordCombination()? If I'm one of those funky users I mentioned in point 4, I'd be upset with this rule.
Use <input type="email" /> to validate emails on the client-side, not emailValidate(). Then check it again on the server with something such as PHP's filter_var().
":(" should really be "):" to be consistant with eye placement in "D:".

There's some critique on your validation. So maybe it would be best to find an established validation library and make slight alterations to suit you! Google has some validation standards, and W3C also has some tips and tricks up their sleeve!

But always remember:

  Servers should not rely on client-side validation. Client-side validation can be intentionally bypassed by hostile users, and unintentionally bypassed by users of older user agents

Now I'm not JavaScript maniac, but I might be able to help a little!

I believe you could generalize $(this).find(".input-field") into something such as $(this).find("input[type=text], input[type=password]"). This way you don't rely on having that class.
You just check if error_field is empty, so why not make it simpler and turn it into a counter.  Each error increments it. In the end, if it's value is equal to 0, it's all good!


This is a small program, so some of the problems are not likely that big. If this were part of the API, problems may stack up and then make an actual difference.

There are several points which you should work on:

opendir leak: opendir opens a file descriptor. You open 2 directories, none of which are closed. Make sure to call closedir. If this is part of an API, those memory leaks will stack up. Otherwise, this might not be a problem, since when the process ends, the descriptors should be cleared automatically.
Error checks: If I were to run this code a lot of times, some of which are intended to end in errors, there would be some clatter due to the positioning of your error checks. Checks like does src exist or can dst dir be accessed, should be done first. This will eliminate the need for some operations. Generally, it is always best to perform error checks first.
Finding the name: A big part of the code is dedicated to finding the name of the src, and copying it to dst. You might improve it by using built-in functions instead. Use strrchr to find the last / and strcpy to copy the name.

Maybe there are other possible changes, but that should be the gist of it. Most of those problems have a small effect. This is a small program, so you won't notice must performance changes (unless this is an API).


You currently have:

i, j, k = 0, 0, 0 #i= left counter, j= right counter, k= master counter

Don't write minified code. Use variable names.

left_counter, right_counter, master_counter = 0, 0, 0


PHP 7.3.9: Check if uploaded file is an image (I don't care about the format)

The method in question does not use $this therefore you might consider making it static.

Further it is a private method, i dont know of which class, but consider making it a public method of its own class.

The method accepts UploadedFile but it is only interested in the real path. As long as you keep it private it could be ok and simpler to call, but if you ever make it public (as suggested above), you should let it accept string path instead, that way it will be more flexible.

There are 18 constants for the image types, but you are using hardcoded numbers. What If another type is added in the future? Do you want to have to modify your code? Check the exif_ imagetype return value doc. It will never return int that is not one of the constants. return is_int($result); is absolutely enough.


Export an Excel file using Laravel-Excel

The code looks OK. You may want to move the query outside of the foreach loop and group the results afterwards. But the foreach loop is limited to the number of days in a month, so I don't think that will do very much. That may cause the application to use more memory.

Therefore, I advise testing if the performance is indeed an issue. If so you might want to delegate creating the export to a queue. Queues in Laravel are not hard to implement (surprise!)

Laravel Queues Documentation 7.x


Well, the obvious method would be to use the itertools module which has exactly what you want. Here are the docs, just in case you'll need to look up for something else.

from itertools import permutations

def generate_permutations():
    return list(permutations([1,2,3]))

The above will return:

  [(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]

Below, you can find the algorith of this module:

def permutations(iterable, r=None):
    pool = tuple(iterable)
    n = len(pool)
    r = n if r is None else r
    if r > n:
        return
    indices = range(n)
    cycles = range(n, n-r, -1)
    yield tuple(pool[i] for i in indices[:r])
    while n:
        for i in reversed(range(r)):
            cycles[i] -= 1
            if cycles[i] == 0:
                indices[i:] = indices[i+1:] + indices[i:i+1]
                cycles[i] = n - i
            else:
                j = cycles[i]
                indices[i], indices[-j] = indices[-j], indices[i]
                yield tuple(pool[i] for i in indices[:r])
                break
        else:
            return

As you can see, this is using just a while loop do do what you did in 3 separate for loops. For this kind of operations, I strongly recommend using the itertools module.


Conditionally eliminating one of two colliding bodies

IMHO this is perfectly fine.

if (!isPlayer(bodyA) || !isPlayer(bodyB)) {
    return;
}

This is an early return, saving you one indentation level.

    if (save(bodyB)) return;
    markForDestroy(bodyB);

This is not as good. Here, I'd go for

    if (!save(bodyB)) markForDestroy(bodyB);

Note that braces should be used around single statements as well, i.e.,

    if (!save(bodyB)) {
        markForDestroy(bodyB);
    }

  But doing maybe this practice reduces the code readability.

No, used wisely it helps readability. When reading top down, you know that both bodies are players. In an if-block you know this too, but the indentation may get excessive. Moreover, using the early return makes clear that only players are dealt with.

As stated in the comments, processContact would be a much better name. A method called processContactBetweenPlayers could be extracted (not needed now as it's rather short). Such a method should use something like

checkArgument(isPlayer(bodyA) && isPlayer(bodyB));

in case it's public, otherwise I'd recommend

assert isPlayer(bodyA) && isPlayer(bodyB);

While asserts are often frowned upon, this is exactly what they're good for.


Preventing duplicate key errors in EF-Core InMemory provider through locking

A lock works here, and it's functional, but it does come with some drawbacks in this case.

If you and I both submit the request at the same time, one of them will be delayed even though there wasn't actually a reason. Now you've introduced a potentially hazardous situation, what happens if a lot of distinct persons submit requests at once?

The best option here, is to block only those who violated the key sanity. The easiest way to do this is actually to catch the appropriate exception.

There's a nice question about this on Stack Overflow, which I would like to borrow some information from: Duplicate key exception from Entity Framework?

There is an answer that looks promising, which looks like:

try
{
    await db.SaveChangesAsync();
}
catch (DbUpdateException ex)
{
    SqlException innerException = ex.InnerException.InnerException as SqlException;
    if (innerException != null && (innerException.Number == 2627 || innerException.Number == 2601))
    {
        //your handling stuff
    }
    else
    {
        throw;
    }
}

Based on the research I could suss-out in a short bit, this looks like it's appropriate for EF-Core, whereas the accepted answer looks more like EF on standard. I can't test it, so I leave it to you, but I would go more towards this route than a shared lock.

Of course, it's up to you, but I wouldn't even try to re-save the LastWrite on a duplicate key violation, because we know it's going to be right now, so why do the extra work? I'd just catch and swallow in this case, with a clear comment as to why:

try
{
    context.SaveChanges();
}
catch (DbUpdateException ex)
{
    SqlException innerException = ex.InnerException.InnerException as SqlException;
    if (innerException != null && (innerException.Number == 2627 || innerException.Number == 2601))
    {
        // Swallow the exception, as the only thing we're updating is the `LastWrite`, which will be the current date/time so there's not point in doing additional queries;
    }
    else
    {
        throw;
    }
}

Depending on the logic, I may also even recommend tracking that further up the stack, and only call to this function if it needs updated. (Rather than for every update.)


Displaying orders and customers in a table, filtering out duplicates

There are several major problems.

You've mixed presentation with logic.
You have some error/exception handling but not enough.
Where is your PDOErrors.txt being written to? It looks like it's being written to your web directory. This allows someone to visit http://yoursite.com/PDOErrors.txt and view information that may allow them to compromise your site.
You read from variables without ensuring they've been initialized. Even though php does not require variables to be initialized, I've found that this is a great place for bugs to live.
The way you are iterating over query results and creating arrays makes no sense. I know you've mentioned there are duplicates to remove but your solution is not the way to handle that situation. As others have mentioned, you either have problems with your schema that should be corrected, or you should use sql to return the proper result set.
You should not display unlimited result sets. The app might seem like it works now but, when your data grows the app will eventually crash due to either time or memory exhaustion. Result sets should be paginated with sane limits.
Your code is vulnerable to cross site scripting (or at least broken html). Whenever you do echo $foo, you should instead do echo htmlspecialchars($foo).

I know you've stated you are new to programming so I understand and sympathize with wanting to write code this way. You get quick results and from your perspective and I'm sure it seems like it works. But, as your app grows, you will find that this style is completely un-maintainable. Even you, the author will not be able to follow or understand it (not to mention the poor sap who comes after you).

Additionally, you have introduced some major security vulnerabilities without even realizing it. My advice is that you should immediately abandon this script and look to one of the many excellent frameworks for php (symfony or zend to name a few). These kinds of frameworks already contain what you need to write secure and organized applications. Although it would take time to learn how to use a framework, it is far less time than you would spend maintaining scripts written this way and dealing with the security problems.


The findIndex seems un-Haskelly and the fmap on the result of findIndex feels just wrong.

There's nothing wrong with fmap.

One thing I would advise is replacing (\x -> x - 1) with (minus 1). Also, [ls | ls <- lss, p ls] is probably best rewritten to use filter.

If you format your code more nicely, I think you'd find it reasonably appealing:

g = findIndex . (==)

p l r ls = g l ls <= g r ls

sLeftOf l r lss = filter (p l r) lss

sDirectLeftOf l r lss = filter (p l r) $ fmap (minus 1) (g ls)

  The first leftOf is immediately to left of and the second is somewhere to the left of; but this won't work for a single list.

Seems like a fairly contrived solution. elem and zip are still \$O(n)\$ so I don't think this accomplishes what you intended. If you're concerned about performance, I'd suggest using a keyed map so that lookups become \$O(\log n)\$ - searching an array will be \$O(n)\$ just like searching a list.

Also, you define

leftOf' x xs y ys = guard $ (x,y) `elem` (aux xs (tail ys))
aux a b@(_:ys) = (zip a b) ++ aux a ys
aux _ []       = []

which is not used anywhere. Passing the -Wall option to GHC will warn you any time you do something like this.


You could use a list comprehension in get_num:

def get_num(string):
    """this function takes a string as input and outputs a list with all the integers in the string"""
    # get the numbers from string
    numbers = ''.join(x if x.isdigit() else ' ' for x in string).split()

    # change to list of ints instead of strings
    return [int(number) for number in numbers]
    # return map(int, numbers)  # Alternative

Also note that join can take a generator expression, so no need to convert to a list first. I also chose more descriptive variable names here.

You should also give your functions (and classes) a docstring (by putting a triple-""" delimited string as the first line of the funciton body, as I did above), which you can access interactively via help(function_name) and which is used by many documentation building tools.

It also seems a bit too manual to have to know which method to call depending on the url. Your crawler could decide that on its own:

class Crawler(object):
    sites = {"hackthissite.org": ('.blight-td', 1, 0),
             "certifiedsecure.com": ('.level_progress_details', 0, 1)}

    def __init__(self, url):
        self.url = url
        self.options = self.get_sites_options(Crawler.sites)

    def get_sites_options(self, sites):
        for site, options in sites.items():
            if self.url in site:
                return options

    def get_site_data(self, user):
        """retrieve data from site and"""
        request = requests.get(self.url + user)
        return bs4.BeautifulSoup(request.text, 'lxml')

    def get_experience(self, user):
        select_str, index, out_index = self.options
        experience = self.get_site_data(user).select(select_str)[index].getText()
        return get_num(experience)[out_index]


There are two obvious optimisations.

The first is to remove the line

    $file_dest = Get-ChildItem -PATH $COMP_DEST -name

since $file_dest is unused. I assume that it was previously used instead of

Get-ChildItem -PATH $COMP_DEST -name -Include $file_ori[$i]

The second is to do the remote hashing remotely. Rather than fetch 500 files (of unknown size) across the network in order to calculate their MD5 sums, use remote PowerShell to calculate their MD5 sums and just return the filenames and the hashes. You might even be able to manage to get the two computers to calculate the hashes in parallel, giving a two-fold speedup.


Select Queries From Parent-Child Tables Model

Select *
Generally, it is advised against using SELECT *. The answers to this stackoverflow question explain why SELECT * is considered harmful.
Your queries might return different values
The first query takes the transaction record with the latest CRTime, the second uses the highest ID. These are likely returning the same rows right now, but I would use the CRTime. The rows might not have been inserted in time order, so the most recent time and the highest ID might not result in the same record.
I would recommend the first query
I would recommend the first query because it avoids that second join that the second query has. Other than changing the SELECT *s to list all the columns and making sure the tables are properly indexed, I don't think there is much you can do to improve it. That's a pretty nice query.
Select * and Indexing
One of the problems pointed out in the linked SO question is that fact that using SELECT * can cause the query to not use indexing properly as it brings back more columns than you need.
Checking runtimes
I found this stackoverflow question had some good answers regarding comparing SQL runtimes/performance.


Project Euler # 44 Pentagon numbers in Python

This is an answer focused primarily about styling

Your parameter names can be renamed to be more specific, like generate_pentagons(n) can be rewritten to generate_pentagons(number_of_pentagons). This change can also be implemented in the get_pentagons method. While this may seem useless in this program, since n can be easily interpreted as the number of pentagons to generate, it's a good practice to follow when you start writing large programs that require more specific parameter names.
Parameter constants should be UPPERCASE.
You don't use i in your loop in generate_pentagons method. To avoid generating an unused variable, you can use an underscore. The _ immediately signals the reader that the value is not important.

Final Code

from time import time

def generate_pentagons(number_of_pentagons):
    """generates next n pentagons"""
    pentagons = (num * (3 * num - 1) // 2 for num in range(1, number_of_pentagons))
    for _ in range(number_of_pentagons - 1):
        yield next(pentagons)

def get_pentagons(number_of_pentagons):
    """Assumes n is a range > 0. Generates pentagons that obey to the + - rules."""
    pentagons = set(generate_pentagons(number_of_pentagons))
    for pentagon1 in pentagons:
        for pentagon2 in pentagons:
            if pentagon1 + pentagon2 in pentagons and abs(pentagon1 - pentagon2) in pentagons:
                return pentagon1, pentagon2

if __name__ == '__main__':
    START_TIME = time()
    PENTAGON_1, PENTAGON_2 = get_pentagons(10000)
    print(abs(PENTAGON_1 - PENTAGON_2))
    print(f"Time: {time() - START_TIME} seconds.")


Basic graphical R code draws an ellipse instead of a circle

A vectorized solution using outer (Outer Product of Arrays):

edge <- 100
magicradius <- .81
magicmargin <- .01
width <- (2*edge) + 1

x <- -edge:edge
y <- -edge:edge

mat <- outer(x, y, function(x,y) sqrt(x^2 + y^2))
ind <- mat > ((magicradius-magicmargin)*edge) &
       mat < ((magicradius+magicmargin)*edge)
image(ind, asp=1)

The aspect ratio in image() can be set with the asp argument (see the Details section in ?plot.window)


The code looks perfect, except for the variable name numbers. This variable only holds a single number, therefore its name must be number instead.
Since the variable is only used in a very small scope, the names n or i may be acceptable as well. (Subject to personal preference.)


This is a pretty good brute-force way to find these numbers. It will obviously be slow because of it's brute-force, but it's easy to read and understand, which is always a plus! Here are some ways you could improve it.
Don't Try All Combinations
Once you've calculated a factorial, it's pretty easy to add 1 to it and determine if it's a perfect square. I would write a function called is_perfect_square() that looks like this:
bool is_perfect_square(const int x)
{
    double square = static_cast<double>(x);
    double root = sqrt(square);
    return root == std::round(root);
}

Now you can simply do this:
void print_brown_numbers(int limit)
{
    for (unsigned int i = 2; i <= limit; ++i)
    {
        unsigned int fact = factorial(i);
        if (is_perfect_square (fact + 1))
        {
            std::cout << sqrt(fact + 1) << " " << i << " are brown numbers\n";
        }
    }
}

Note that in my version, the limit is the limit of the factorial, not the square, so it works slightly differently.
Error Handling
Most compilers will use 32-bits for an int or an unsigned int these days. Factorials can get very large very quickly. 12! is the largest factorial a 32-bit int or unsigned int can hold. You should check your inputs to make sure you won't get an overflow and let the user enter a different one if it would.
Types
You're mixing signed and unsigned types. While there's nothing wrong with your math, you're leaving 1 bit (so half the range - 2 billion values) on the table for the square. It will never be negative, so you should just make it unsigned to begin with. (Or make the factorial signed. Either way is fine given the maximum values.)


Get rid of SoldierRankLibrary

GetSoldierRank() belongs in the Soldier class. That's what Rank { get; set; } is for.
the Dictionary will be replaced by an enum (see below). An enum does not need be inside of any class. You can use boolean operators on enums ("<", "==", ...)

Use Enum instead of Dictionary

Your dictionary is mimicking an Enum. In other words and Enum
inherently associates a number with a name. And in general using Enum
is preferred over strings.
Make separate OfficerRank and EnlistedRank enums if that works
better.
I like @Nik's answer with "unknown". But I'd make it "0" instead of
"-1". The natural default value of an enum variable is zero.
If the underlying int values matter elsewhere in code just make sure you put the ranks in the desired order.

Soldier Class

Rank and Title appear to be the same thing. Do you really need to refer to the soldier's rank by its underlying (integer) value?
Explicitly set variables in the constructor. We all know default values for .NET types, but you want to convey intent and meaning.
Exhaustively set the entire state in the constructor. Again, intent and meaning.
Rankup() - change name to Promote(). Don't pass in an integer, pass in something that has meaning. We're going to utilize Rank enum so this fills the bill.
RefreshTitle() - obsolete. Rank/Title is the same thing. The Rank enum keeps us from having to deal with a string and an int.
Property mis-use. It makes no sense to have a private Title set and
a public RefreshTitle(). Think of a Property as a method. A lot of existing code goes away simply by using the public get properties.
Override ToString(). Now PrintSoldierInfo() disappears.

New Code

public enum Rank {undefined, BuckPrivate, Sergeant, Lieutenant, Captain}

public class Soldier {
    public string   Name { get; protected set; }
    public Rank     Rank { get; protected set; }

    public Soldier (string name) {
        Name = name ?? "No Name";       // null coalescing.
        Rank = Rank.undefined;   // maybe private if enlisted or lieutenant if officer
    }

    public void Promote (Rank newRank) {
        if ((int)this.Rank < (int)newRank ) this.Rank = newRank;
        // we don't allow Demotion in this method.
    }

   public override string ToString() {
       Stringbuilder me = new Stringbuilder();  // need to import System.Text to use Stringbuilder

// C# string formatting avoids clumsy string concatination; clearer and less error prone
       me.AppendLine("Name: {0}  Rank: {1}", Name,Rank);

       return me.ToString();  // Stringbuilder must be converted to a string.
   }
}

Using Soldier

Soldier grunt = new Soldier("Sad Sack");
grunt.Promote(Rank.Sergeant);
Console.WriteLine (grunt); // ToString() is automagically called.


Counting the number of words in a string

I personally would use the built-in way of reading words.

std::stringstream wordStream("A list of words");

std::string       word;
int               count = 0;
while(wordStream >> word)
{
    ++count;   // We read one space separated words
}              // from the stream.

Of course the default does not handle punctuation correctly (as the words are divided by space. But we can handle that.

So how do we make things look like a space.
All you need to do is tell the stream what characters are spaces. To do this you need to create a ctype facet and implant it into the stream.

#include <locale>
#include <string>
#include <sstream>
#include <iostream>

// This is my facet that will treat the ,.- as space characters and thus ignore them.
class WordSplitterFacet: public std::ctype<char>
{
    public:
        typedef std::ctype<char>    base;
        typedef base::char_type     char_type;

        WordSplitterFacet(std::locale const& l)
            : base(table)
        {
            std::ctype<char> const&  defaultCType  = std::use_facet<std::ctype<char> >(l);

            // Copy the default value from the provided locale
            static  char data[256];
            for(int loop = 0;loop < 256;++loop) { data[loop] = loop;}
            defaultCType.is(data, data+256, table);

            // Modifications to default to include extra space types.
            table[',']  |= base::space;
            table['.']  |= base::space;
            table['!']  |= base::space;
            table['?']  |= base::space;
            table['(']  |= base::space;
            table[')']  |= base::space;
        }
    private:
        base::mask  table[256];
};

Now you just have to add it to a stream.

int main()
{
    std::stringstream   wordsAndPunt("word1 ,,, word2");
    wordsAndPunt.imbue(std::locale(std::locale(), new WordSplitterFacet(std::locale()));

    // Now apply the count.
    std::string word;
    int         count = 0;
    while(wordsAndPunt >> word)
    {
        ++count;   // We read one space separated words
    }              // from the stream.
    std::cout << count << "\n";
}

Now we have the basics in place you don't even need the loop. You can replace it with standard algorithms.

int main()
{
    std::stringstream   wordsAndPunt("word1 ,,, word2");
    wordsAndPunt.imbue(std::locale(std::locale(), new WordSplitterFacet(std::locale()));

    // Now apply the count.
    int  count = std::distance(std::istream_iterator<std::string>(wordsAndPunt),
                               std::istream_iterator<std::string>());
    std::cout << count << "\n";

}


Determining coefficient in geometric progression

In the if statement inside the while loop,
since the method returns when the condition is true,
you can drop the else.

In the condition of the while, you have pointless parentheses.

When printing stuff without variables,
I prefer puts instead of printf because it's shorter.

scanf_s doesn't compile with my compiler gcc.
I don't know what it is, but replacing with scanf seems to work fine for me.

Notice in your question that the syntax highlighter made Num have a different color from other variables.
It's because CamelCase is usually used for class names,
and camelCase for variable names.
So I'd rename this to num, or thisNum (to sort of harmonize with prevNum).

Pay attention to formatting. It makes the code more readable. For example:

You didn't indent the main body, then after the while loop you indented.
There are pointless blank lines in the while loop that just look strange.

With the above suggestions applied:

#include <stdio.h>
#include <math.h>

int main() {
    int prevNum;
    scanf("%i", &prevNum);
    int thisNum;
    scanf("%i", &thisNum);
    int r = thisNum / prevNum;
    prevNum = thisNum;
    while (scanf("%i", &thisNum) != EOF)
    {
        if (thisNum / prevNum != r)
        {
            puts("No progression");
            return 0;
        }
        prevNum = thisNum;
    }
    printf("Progression with r=%i \n", r);
    return 0;
}


Partial Answer This does not cover all aspects of your code, so feel free to wait for other responses.

In OOP, it is important to identify the scope of an object. In your case, you have two input matrices and possibly a result matrix for the operation that the user selects. The key point is, that each matrix should be a distinguished instance of your matrix class. What you have is something like a matrix manager, that contains multiple matrices in a single instance.

When you re-design your matrix class to contain a single matrix, you should possibly externalize your user input logic. Also, the sum, diff and transpose functions could be external functions that take two matrices as parameters and return a resulting matrix. However, I guess it would also be ok to have them as member function that only takes the second matrix as parameter.

Consider the following class definition:

#include <vector>

class matrix {
private:
    // matrix with m columns and n rows
    int _m, _n;
    // values, organized as an outer vector of rows
    // and an inner vector of columns
    std::vector<std::vector<int>> _values;

public:
    // initialize matrix by its size
    matrix(int m, int n)
        : _m(m), _n(n)
    {
        // initialize the matrix size
        _values.resize(n);
        for (int i = 0; i < n; ++i)
        {
            _values[i].resize(m);
        }
    }

    // TODO:
    // - other constructors
    // - copy operator
    // - other desired functions
    // - assessors to the matrix elements
};

Maybe you can start from there.


Finding products of all other members of an array

This could be done with two consecutive loops (instead of nested loops), making it O(N) instead of O(N^2).

In the first loop you calculate the total product of all non-zero elements (and the number of zeros).

If there are more than one zero, return result as is, since all elements already default to zero.

In the second you either set the result element to zero or to total product divided by the current element depending on the number of zeros in the data and the value of the current element.

BTW, There are a lot of blog posts and even some research written about the pointlessness of this kind of interview questions.


I like your code. It is easy to understand and pretty straight-forward.

Regarding your question of the measuring units: yes, every variable should have them since you are not operating exclusively on SI units. You have calories (instead of joule) and years and minutes (instead of seconds).

I would just change some of the smaller details, from top to bottom:

The doc comment for main is wrong. That function not only initializes the program, it is the whole program, including computation and output.
Rename get_person_attributes to read_person_attributes or input_person_attributes. Functions called get_* usually don't have side-effects and are usually not complicated.
The gender prompt could be more specific: 'Your gender (male, female): '
The official spelling for kilogram is kg, not Kg. Although kilo is a large multiplier, it is the only one with a lowercase letter.
The prompt for the heart rate could include in bpm.
The Your your is a typo.
In make_person, the proper a person of proper gender sounds wrong (though I'm not a native English speaker).
You compute gender.lower() twice, which is unnecessary.
Do you prefer burned or burnt? Choose one and use it everywhere.

Having each of the complicated formulas in a single line is very good. One might be attempted to split it into several small formulae or extract the factors to a separate class CaloriesCalculatorFactors, but that would make the code harder to understand.


I suggest using this declaration:

typedef struct _node {
  int val;
  struct _node *next;
} node;

After that, you can declare node *t instead of struct node *t. Also, you'll use sizeof(node) instead of sizeof(struct node).

Your delete is buggy. I'll quote just a bit:

struct node *deleteNode(struct node *first, int num)
{
  struct node *prev=NULL;
  struct node *root = first;
  while (root != NULL)
  {
    if (root->val == num)
    {
      ...
      else if (prev == NULL) //first element
      {
        free(first);
        first = root->next;
        root = root->next;
      }
      ...
    }
    ...
  }
  return first;
}

So, you have root = first, then you free the memory of first, and then you access root->next which is the same as first->next, which is a value contained in the already freed memory.

I'd write it in two parts:

Delete all there is to be deleted from the list start.
Delete all there is to be deleted, but is not at the list start.

Like this:

node *deleteNodes(node *first, int num) {
  node *prev, *active;

  while (first && first->val == num) {
    node *tmp = first;
    first = first->next;
    free(tmp);
  }

  if (!first) return NULL;

  prev = first;
  active = first->next;

  while (active)
    if (active->val == num) {
      prev->next = active->next;
      free(active);
      active = prev->next;
    } else {
      prev = active;
      active = active->next;
    }

  return first;
}

I have changed the name of the function because you seem to want to remove all the nodes containing the value num.

A matter of personal choice: I prefer to transverse through a list the same way I do with arrays -- by using a for loop.

void printList(node *root) {
  node *t;
  for (t = root; t; t = t->next)
    printf("Value: %d\n", t->val);
}

If you really want to reuse root, you can, but one or few additional variables (like my t (stands for "temporary") in the above code) can make your code much more readable.

It may be useful to finish void functions with return;, as it helps you detect certain problems in code (i.e., if you change the return value to something else, such return will result in error and warn you to fix it).

This

node *current = malloc(sizeof(node));

can be written like this like this:

node *current = (node*)malloc(sizeof(node));

Read about using such a cast here and decide for yourself. I prefer to use it.

You should always release all your memory (i.e., delete the remaining list) when you program ends, instead of relying on the OS to do it properly.


remove_prefix and remove_suffix functions

Firstly I would say turn your print statements into a test. That way you can change the implementation with confidence that you have not broken anything.

Here is what those debug prints are as a test:

class TestRemove(unittest.TestCase):

    def test_remove_prefix(self):
        hello = 'Hello, World'
        value = remove_prefix(hello, 'Hello, ')
        self.assertEqual(value, 'World')
        value = remove_prefix(hello, 'Hello, Hello', raise_if_no_match=False)
        self.assertEqual(value, hello)
        self.assertRaises(ValueError, remove_prefix, hello, 'Hello, Hello')

    def test_remove_suffix(self):
        singing = 'I am singing in the rain'
        value = remove_suffix(singing, ' in the rain')
        self.assertEqual(value, 'I am singing')
        value = remove_suffix(singing, 'swinging in the rain', raise_if_no_match=False)
        self.assertEqual(value, singing)
        self.assertRaises(ValueError, remove_suffix, singing, 'swinging in the rain')

I think you should be using the the built in string operations which can be found here. Namely startswith(), endswith(), spilt() and rsplit().

You can also reassign variable names to give a more clear flow through the function. Here is my version of remove_prefix().

def remove_prefix(text, prefix, raise_if_no_match=True):
    if (text.startswith(prefix)):
        text = text.split(prefix, 1)[1]
    else:
        if (raise_if_no_match):
            msg_fmt = 'Text "{}" does not end with a prefix "{}".'
            raise ValueError(msg_fmt.format(text, prefix))
    return text

From that I'm sure you can change remove_suffix().

Also I would add docstrings to the functions so the arguments and exceptions raised are documented.


The proper way of doing this is to use the tools the language already gave you.

IPv4 usually are stored as big endian numbers, and Go already have an IP type:

func int2ip(num int) net.IP {
    var b [4]byte
    binary.BigEndian.PutUint32(b[:], uint32(num))
    return net.IPv4(b[0], b[1], b[2], b[3])
}

//or if you don't care about returning net.IP
func int2ipstr(num int) string {
    var b [4]byte
    binary.BigEndian.PutUint32(b[:], uint32(num))
    return fmt.Sprintf("%d.%d.%d.%d", b[0], b[1], b[2], b[3])
}

playground

//edit adding more details following @Schism's advice

Using Sprintf is usually fine and they worked on optimizing it fairly well, if you want to squeeze every drop of performance out of it, you could use a more "buffered" alternative like :

func int2ipb(num int) string {
    b, buf := [4]byte{}, make([]byte, 0, 15) //15 = max number of bytes in an ip
    binary.BigEndian.PutUint32(b[:], uint32(num))
    for _, n := range b {
        buf = append(buf, '.')
        buf = append(buf, strconv.Itoa(int(n))[:]...)
    }
    return string(buf[1:])
}


Main loop for a text-based Blackjack game

It's "Pythonic" to iterate through items, so assuming that len(joueurs) == nb, your main for loop can be:
    for a, joueur in enumerate(joueurs):

which means all your joueurs[a] become joueur. I'm quite surprised that onze, askoui and perdu functions take the whole joueurs list, not just the current player. How does that work?
I'd guess that the check for possible onze action, which I take it is converting an ace down from 11 points to 1, could more comfortably fit within the askoui function when our current player gets another card, non? Then this main routine could just check against 21, or perhaps even better the askoui function could return a status value.
Difficult to be more specific without getting into some of these auxiliary functions. Here's my best guess at a reduced code that I think should do the same  as you presently have, plus some outstanding issues:
while t:
    input("Appuyez sur entrer pour continuer...")
    for ix, jr in enumerate(joueurs):
        jID = ix+1
        while sum(jr) < 21:
            time.sleep(0.5)
            print("main du joueur", jID, ":", jr, "Total :", sum(jr))
            ask = input("Joueur {} voulez vous une carte ?(oui/non)".format(jID))
            if ask == "oui":
                askoui(joueurs) # why all joueurs?
                if sum(jr) > 21 and 11 in jr:
                    onze(joueurs) # why all joueurs?
            else:
                asknon()
                t = False # immediate halt to play for all players?
                break
        if sum(jr) == 21:
            print("joueur", jID, "a BLACKJACK")
            time.sleep(1) # then play continues
        elif sum(jr) > 21:
            perdu(joueurs) # why all joueurs?
            t = False
        # play continues without message if sum(jr)<21 ?


The solution should look like (pseudocode, I know little F# too ;) ):

String
  |> ChunksOf 2
  |> Map Reverse
  |> Flatten

An example explains clearly

"abcd" -> ["ab", "cd"] -> ["ba", "dc"] -> "badc"

The key of effective Functional Programming is making good use of the built-in functions and carefully combining them.


Best practices to do complex forms with javascript?

For a single form, this is the exact reason Knockout.js was created - tutorials here: http://learn.knockoutjs.com/#/?tutorial=intro

Angular is more of a full blown "SPA" framework, Knockout is data-binding for JavaScript with things like this: http://knockoutjs.com/documentation/if-binding.html


Quicksort using uniform_int_distribution to select the pivot

Because you are creating a generator in each iteration with the same seed, the value you get from your distribution will be the same.

So no, this is not the correct way to use the new random subsystem in C++11.

You need to pass in a distribution by reference to quicksort(iteratorm,iterator).

Also personally I don't feel that random numbers should be a part of a sorting algorithm because performance becomes non-deterministic. I would suggest you use one of the other pivot selection strategies.

Also your algorithm requires the use of random access iterators. Might be worth noting.


"Ringing in the New Year (2011→ 2012)" puzzle

I wrote this solution that runs in 0.2 seconds on my computer when compiled. It also does a BFS with memoisation. However, it uses two heuristics: Don't divide by two unless the denominator is 1 and don't go above 10000. A more elegant way would be to use a priority queue that prioritises "states" like these. However, using these heuristics does not guarantee an optimal solution.

As a side note, this question might be better for code review than Stack Overflow.

import Data.Ratio
import Data.Map (Map)
import qualified Data.Map as M
import Data.Sequence hiding (reverse)

-- Left, Middle, or Right
data Pos = L | M | R
 deriving (Eq,Ord,Show)

-- Up/Down Left/Right
data Lbl = UL | UR | DL | DR
 deriving (Eq,Ord,Show)

-- The operators in the labels
op :: Lbl -> Rational -> Rational
op UL = (+7)
op UR = (*3)
op DL = (/2)
op DR = (subtract 5)

-- Gives the possible candidates for a position
candidates :: Pos -> [(Pos,Lbl)]
candidates = \p -> case p of M -> map (L,) left ++ map (R,) right
                             L -> map (M,) left
                             R -> map (M,) right
  where right = [UR,DR]
        left  = [UL,DL]

-- The state is the value, position and the last label (cannot revisit it)
type St = (Rational,Pos,Lbl)

-- The memo map, remembers if a state has been visited before and
-- which was the previos state
type Memo = Map St St

-- Is this a solved state?
solved :: St -> Bool
solved (2012,R,_) = True
solved _          = False

-- The initial state
initSt :: St
initSt = (2011,L,DR)  -- ugly hack, say the last label was DR ;)

-- Solve, with a queue of states to visit and a memo map
solve :: Seq St -> Memo -> [St]
solve (viewl -> top@(v,p,l) :< rest) memo
  | solved top = reverse (retrievePath memo top)
  | otherwise  =
     let new = [ (st,top)
               | (p',l') <- candidates p
               -- ^ Get the candidate locations from here
               , l /= l'
               -- ^ Don't go through the same label twice
               , let st@(v',_,_) = (op l' v,p',l')
               -- ^ Calculate the new state
               -- Two heuristics:
               , not (l == DL && denominator v' /= 1)
               -- ^ 1) don't divide by two unless the denominator is 1
               , v' < 10000
               -- ^ 2) don't go above 10000
               , st `M.notMember` memo
               -- ^ Don't revisit a state
               ]
     in  solve (rest >< fromList (map fst new))
               -- ^ Enqueue the new states
               (memo `M.union` M.fromList new)
               -- ^ Add these to the memoization

-- Retrieve the path from the memo map
retrievePath :: Memo -> St -> [St]
retrievePath memo st@(v,p,l)
  | st == initSt = [initSt]
  | otherwise    = st : retrievePath memo (memo M.! st)

-- This is the problem with 2011 and 2012
problem = solve (singleton initSt) (M.singleton initSt initSt)

main = print problem


You've got students and their scores here. I assume that student without scores is meaningless, as well as scores without students. It would be nice to combine that data into single object:
public class StudentScores {

    // Auto-property guarantees that student name defined once in constructor
    // and will not accidentally change.
    public string Name { get; }

    // Scores count can be different for different students.
    // Private field guarantees that scores will not be messed up by other classes.
    // Otherwise some student could access scores and change them,
    // which would lead to errors.
    private readonly List<int> scores = new List<int>();

    public StudentScores(string name) {
        Name = name;
    }

    // We still need a method to add scores to our encapsulated list.
    // We could implement Clear() or RemoveAt() public methods later.
    public void AddScore(int score) {
        scores.Add(score);
    }

    public double Average() {
        if (scores.Count > 0)
            return scores.Average();
        else
            return 0;

        // Or simple: return scores.Count > 0 ? scores.Average() : 0;
    }

    // Nicer way to print data: student name and all scores separated by empty space.
    public override string ToString() {
        return $"{Name} {string.Join(" ", scores)}";
    }
}

Without comments it's only 20 lines long:
public class StudentScores
{
    public string Student { get; }

    private readonly List<int> scores = new List<int>();

    public StudentScores(string student)
        => Student = student;

    public void AddScore(int score)
        => scores.Add(score);

    public double Average()
        => scores.Count > 0 ? scores.Average() : 0;

    public override string ToString()
        => $"{Student} {string.Join(" ", scores)}";
}

Now your syntax in Main is much nicer:
static void Main(string[] args) {

    string[] names = {"Morgan", "Bowie", "Ananya"};

    var morgan = new StudentScores(names[0]);

    // Determine how much scores has student.
    Console.WriteLine("Enter number of test scores for " + names[0]);
    int count = int.Parse(Console.ReadLine());

    for (int i = 0; i < count; i++) {
       morgan.AddScore(int.Parse(Console.ReadLine()));
    }

    var bowie = new StudentScores(names[1]);
    // ...

    var ananya = new StudentScores(names[2]);
    // ...

    Console.WriteLine(morgan.ToString() + " Average score: {0:N2}", morgan.Average());
    Console.WriteLine(bowie.ToString() + " Average score: {0:N2}", bowie.Average());
    Console.WriteLine(ananya.ToString() + " Average score: {0:N2}", ananya.Average());
}

You could improve your Main() further creating single loop for all students:
static void Main(string[] args) {

    string[] names = {"Morgan", "Bowie", "Ananya"};
    List<StudentScores> scores = new List<StudentScores>();

    foreach(var name in names)
    {
        var student = new StudentScores(name);
        Console.WriteLine($"Enter number of test scores for {name}");
        int count = int.Parse(Console.ReadLine());
        for (int i = 0; i < count; i++)
           student.AddScore(int.Parse(Console.ReadLine()));
        scores.Add(student);
    }

    foreach(var score in scores)
        Console.WriteLine($"{score.ToString()}, Average score: {score.Average():N2}");

You could remove Average() method and move calculations directly to ToString(), but I think it's nice to have methods for such things.


Exercism: Class representation of a matrix in Python

I would make a few suggestions, rather than just saving the input string it would be better, as you suggest, to save the output of the get_rows function in memory, so you don't have to recreate it every time.
Similarly when you want an individual row or column, it seems inefficient to gather all the rows, (and then all the columns) just to reject all but one of them.
Your comments say produces i-th (column/row)... but the variable is referred to as index
Minor points:
You don't need to save rows as a variable in _get_columns, you can just use [list(row) for row in zip(*self._get_rows())]
you could reduce _get_rows to one line : [[int(char) for char in row_string.split()] for row_string in self.matrix_string.split('\n')]
I'm assuming that you don't need to check if the input is invalid, because that isn't part of the testing suite. However you may want to do it anyway if you plan on using this class again.
In terms of style the code is good. The first comment under class Matrix doesn't really say anything and there are more newlines than are necessary, but other than that everything looks good.
You could try something like:
class Matrix:
    """Class representation of an integer matrix indexed from 1
    ...

    Attributes
    ----------
    rows: List[List(int)]
        A list of the rows of values in the matrix.

    Methods
    -------
    row(self, i)
        returns the i-th row.

    column(self, i)
        returns the i-th column.
    """

    def __init__(self, matrix_string):
        """Save a list of rows from the input string.
        - matrix_string: A space and new line seperated string of values
        in the matrix.
        """
        self.rows = self._get_rows(matrix_string)

    def _get_rows(self, matrix_string):
        """Produce a list of rows of the matrix.
        - matrix_string: A space and new line seperated string of values
        in the matrix.
        """
        rows = []
        for row_string in matrix_string.split('\n'):
            rows.append([int(char) for char in row_string.split()])
        return rows

    def _get_columns(self):
        """Produce a list of columns of the matrix."""
        return [list(row) for row in zip(*self.rows)]

    def row(self, i):
        """Produce i-th row of the matrix with first index being 1."""
        return self.rows[i - 1]

    def column(self, i):
        """Produce i-th column of the matrix with first index being 1."""
        return [row[i - 1] for row in self.rows]

or you could drop the _get_rows and change the __init__ to:
    def __init__(self, matrix_string):
        """Save a list of rows from the input string.
        - matrix_string: A space and new line seperated string of values
        in the matrix.
        """
        self.rows = [[int(x) for x in row.split()] for row in matrix_string.split("\n")]

In terms of performance:
using cProfile and the following script:
if __name__ == "__main__":
    for _ in range(100000):
        matrix = Matrix("1 2 3 4\n5 6 7 8\n9 8 7 6\n1000 2000 3000 4000")
        for i in range(1, 5):
            matrix.column(i)
            matrix.row(i)

Produces for the old matrix definition:
12900228 function calls (12900222 primitive calls) in 10.239 seconds
For the my definition:
1900228 function calls (1900222 primitive calls) in 1.359 seconds


There are several improvements to this that involve various algorithms that are more cryptographically secure than sha1 (such as sha256 or higher, blowfish, whirlpool, etc.), using strict comparison (to avoid that gotcha with very long hashes loosely comparing when not equal), and including a CSPRNG salting function in the class, that takes over when a user does not supply a salt.

However, CRYPT_BLOWFISH is still very usable in PHP < 5.3. In fact, It's usable in PHP 3.0.18 and over, with the use of PHPass, by the same security company who make John the Ripper (which you should be using to test your class. Try and get the UNIQPASS wordlist. It's really effective!). An alternative to JtR is hashcat. There are several defcon talks about correct usage of password crackers to test strength (by the feds), among other uses (by the non-feds).

If you really must roll your own, then consider implementing blowfish manually.


Well, strictly speaking your code has UB because getChildren(...) tries to create iterators to both child-nodes, even if they are beyond the end-iterator.
Some iterators and containers are more forgiving than others, as are implementations generally...

You forgot the include for std::swap and std::iter_swap: <algorithm>.
Also for std::is_same: <type_traits>.
Both obviously happen to be included by your current includes.

You might want to use std::iter_swap consistently, look in swapLargestValueWithRoot.


Creating API clients that are "async agnostic"

The code is admirably clear.
Nice annotations.
With these classes,
Chuck Norris wouldn't need a debugger,
he could just stare down the bug until the code confesses.

class Request(NamedTuple):
    method: str

Maybe list method 2nd, and allow defaulting to 'GET'?

    response = yield Request('GET', URL_TEMPLATE.format(id=id))

    try:

        if response.status != 200:

Ok, nit-picky observation: there's more than one success code,
so one might bury the test in an is_success() helper function.
(I use an API that routinely returns 204 success.)
But this is for pedagogic purposes, and the 200 test is perfect, don't change it.

Broader observation: showing that "stuff which can go wrong after GET" happens
within the try is pretty interesting.
There is a small amount of "ceremony" to access the result.
If this were a production library, rather than pedagogic, I'd be wondering
if we could maybe save clients from looking for 200 status at all,
and just raise appropriate errors if client is asking for bad data.

This would probably need an url_prefix_to_api_name registry map,
so we could identify a given url as being a Joke url,
and could look for a class with the conventional name JokeApiError.
(Clearly the registry would never contain Norris, because:
No statement can catch the ChuckNorrisException.)

The next few lines have boilerplate checks that maybe could be defaulted,
and / or moved into some JokeApi method a user could choose to supply.

The raise in this line:

    raise Return(data['value']['joke'])

is, ummm, slightly surprising.
I'm sure you have your technical reasons for it.
But maybe it could be a return, or a yield, or simply a method call with side effects?
Or a .close()-style cleanup handler of a with resource manager?
Or simply buried in library code that developers typically won't view?
The raise is just a little jarring, given that this is the success case.

I encourage you to keep pushing on this.
Two ways to win:

Write something a little bigger than just joke access, maybe do some CRUD.
Convince one other developer to use your stuff.

Both will push your code in the direction of increased maturity,
increased readiness for a 1.0 release.


Three buttons with click listeners that pop up a quick toast

Anonymous classes and final keyword
It's good that you realize that you have redundancy in your code.  I think what is holding you back from refactoring the code yourself is that you aren't sure how to set the same onClickListener for each button because each button has a slightly different toast to pop up.
What you need to do is use final variables.  A final variable declared outside an anonymous class instantiation can be used within the anonymous class (i.e. your View.OnClickListener).  So in your case, you could do this:
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    setToastForButton(R.id.button1, "This button will launch button1 App!");
    setToastForButton(R.id.button2, "This button will launch button2 App!");
    setToastForButton(R.id.button3, "This button will launch button3 App!");
}

// Notice the final keyword here.  It allows the variable "text" to
// be used in the onClick() method below.
void setToastForButton(int btnId, final CharSequence text)
{
    Button button = (Button) findViewById(btnId);

    button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Context context = getApplicationContext();
            int duration = Toast.LENGTH_SHORT;

            Toast toast = Toast.makeText(context, text, duration);
            toast.show();
        }
    });
}

You can learn more about anonymous classes here.


Efficiency

the biggest improvement will be to not open the config file each time you log something, but only once when instantiating the logger.
you could also open the log file only once, but it might not be a good idea to have it open for the whole lifetime of the program.
create only one instance of the two SimpleDateFormat objects and store it in a class level field instead of creating them each time.
also create your messages array only once as a field.

Robustness

use an enum instead of string for your warning levels
you are never closing your propFile stream.

Readability

follow the standard Java indent style: curly brackets go on the same line as the opening statement.
use more spaces (around <=, =, etc). This point and the previous one can be fixed by any IDE.
don't do this: timeStamp+id+++"|".
use camelCase for all variable names, don't mix it with snake_case except for final static fields.
use JavaDoc style comments.
remove variables that are only used in one place.
use try with resources to save the close statement.
choose better variable names. app would be clearer as shortDateFormat, format as extendedDateFormat, dateApp as logFileName, appendValue as appendToFile, logLevel as maximalLogLevel (should this maybe be minimal?), logType as logLevel.

There are probably more improvements, but with this your code already looks a bit nicer:

public class FunctionLogging {

    private String path;
    private boolean appendToFile = false;
    private int logLevel;
    private String[] messages = new String[] {"FATAL", "WARNING", "NOTICE", "DEBUG"};

    private SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy|HH:mm:ss:SSSSSS|");
    private SimpleDateFormat app = new SimpleDateFormat("dd-MM-yyyy");

    /**
     *
     * @param filePath used as a placeholder variable for the output path. Can be hard-coded but is preferredly configurable from properties file
     * @param logLevel set as true when called in each class used in. true appends line to the end of the file, false overwrites file contents
     * @param append_value TODO
     */
    public FunctionLogging(String filePath, int logLevel, boolean appendValue) throws IOException {
        path = filePath;
        appendToFile = appendValue;

        loadConfig();
    }

    private void loadConfig() throws IOException {
        try (FileInputStream propFile = new FileInputStream("config.ini")) {
            Properties config = new Properties(System.getProperties());
            config.load(propFile);
            logLevel = Integer.parseInt(config.getProperty("loggingLevel"));
        }
    }

    public void writeToFile(int logType, String textLine) throws IOException {
        if (logType <= logLevel) {
            Date date = new Date();
            String timeStamp = format.format(date);
            String dateApp = app.format(date);

            FileWriter logWriter = new FileWriter(path + dateApp + ".log", appendToFile);
            try (PrintWriter loggerLines = new PrintWriter(logWriter)) {
                loggerLines.println(timeStamp + "1|" + messages[logType] + "|" + textLine);
            }
        }
    }
}

Or with enums:

public class FunctionLogging {

    public enum Level {

        FATAL("FATAL", 1),
        WARNING("WARNING", 2),
        NOTICE("NOTICE", 3),
        DEBUG("DEBUG", 4);

        private final String message;
        private final int level;

        private Level(String message, int level) {
            this.message = message;
            this.level = level;
        }

        @Override
        public String toString() {
            return message;
        }

        public int getLevel() {
            return level;
        }
    }

    // [...]

    public void writeToFile(Level level, String textLine) throws IOException {
        if (level.getLevel() <= logLevel) {
            // [...]
            try (PrintWriter loggerLines = new PrintWriter(logWriter)) {
                loggerLines.println(timeStamp + "1|" + level.toString() + "|" + textLine);
            }
        }
    }

    // [...]

// usage:

writeToFile(FunctionLogging.Level.DEBUG, "something happened");


There are actually several bugs in your code. Your list is also not very easy to use because it can't be iterated.

Bugs

static fields are shared among class instances. So if you create multiple Linkedlist instances, they will all use the same headnode and nodecount. That is obviously not what you want. Those fields should not be static.
AddatNthPosition doesn't add anything if you pass 0 or 1 as index. Also, it throws a NullReferenceException when given an index that is too large. Throwing an ArgumentOutOfRangeException would be better if the index is too small (negative) or too large.
Only Addatfirst takes into account that the list can be empty. The other add methods fail with a NullReferenceException when called on an empty list.

Problems

Your list cannot be iterated because it does not implement IEnumerable. That makes it difficult to use: instead of using foreach or Linq, calling code is forced to manually walk through its nodes. While you're at it, implementing ICollection (count) and IList (indexing, adding, inserting, removing) may also be useful.
public fields can be modified by other code. That means that some other code could replace the head node of a linked list, or adjust its count. That can easily cause bugs or other unexpected behavior. Classes should hide their internal state and implementation details.
Print may be useful for debugging, but it should not be part of your (final) list class. Classes should (ideally) have only a single responsibility, and 'storing items' and 'displaying things' are different things as far as I'm concerned.
Why is there a current field? It looks like that should be a local variable in some of your methods.

Improvements

Consider making your class generic. This improves type safety and makes your list easier to work with.
Try sticking to the official naming conventions to make your code easier to read. C# code uses PascalCase for class and method names: LinkedList instead of Linkedlist, AddToStart instead of AddtoStart, and so on. camelCase is used for field names: headNode instead of headnode, nodeCount instead of nodecount, and so on.
Try using more descriptive names. value instead of d, newNode instead of dummy, and so on. Also, Nodes is plural, but it represents a single node, so it should be named Node instead.
Look at the collections in the standard library. They often use particular names for their methods, and that's what other programmers will be familiar with. Using different names makes your code harder to use. Consider renaming AddatLast to Add, and combining Addatfirst and AddatNthPosition into a single Insert method (where its first argument is the index, conform the IList interface). Also rename nodecount to Count and make it a get-only property, so it can't be modified by other code.
A Remove and/or RemoveAt method would make your list more useful.
If adding items at the end is important, consider adding a lastNode field to improve performance for that case.
Inconsistent indentation makes code harder to read, and it looks a little sloppy.


C and C++ are different languages.

They have a common syntax in places. But how you use them is completely different. What you have written is C NOT C++.

C++ has its own set of header files for C functionality.

#include<stdio.h>
#include<stdlib.h>

Drop the ".h" and add a "c" prefix for the C++ version of these files.

#include<cstdio>
#include<cstdlib>

This puts all the functions in the namespace std.

Don't use using namespace std;

using namespace std;

Yes we know all tutorials and books do this. But they have a motive they are trying to save space on printed material. In any program larger than 10 lines this is going to cause a problem.

The reason the standard libraries are in the std namespace is so that it is not a huge burden to include the prefix in the name.

More details can be found here: Why is “using namespace std;” considered bad practice? and the best answer.

Use OO and classes

Sure OO is not perfect for everything. But a tree and its node is the perfect place to use OO concepts.

The may it is written is very C like and not C++ like. The constructor is not part of the class. There is no destructor to clean up memory there is no definition of ownership semantics so it is unclear who should be cleaning up memory and thus it is going to leak like a sieve.

struct node{
    int data;
    struct node *left;    // Don't need struct in C++
    struct node *right;   // unlike C structs don't have their own namespace.
};
///////////////////////////////
struct node *newnode(int value)
{
    // Abslutely never use C memory management functions in C++
    // The Heap and Free Store need not map to the same memory.
    // Also this does not invoke the constructure to initialize
    // the object.
    struct node *temp=(struct node *)malloc(sizeof(struct node));

    // Also you C code is broken.
    // malloc() can return `NULL` and you don't check for that.
    temp->data=value;
    temp->left=NULL;
    temp->right=NULL;
    return (temp);
}

This should look like this:

class Tree
{
     // Private class to store the nodes in the tree.
     struct Node
     {
         int   data;
         Node* left;
         Node* right;

         Node(int d) : data(d), left(nullptr), right(nullptr) {}
         Node(int d, Node* l, Node* r) : data(d), left(l), right(r) {}

         ~Node()
         {
              delete left;
              delete right;
         }
     };

     Node*  root;
     Tree()
         : root(nullptr)
     {}
     ~Tree()
     {
         delete root;
     }
     // Remove copy semantics (because I am lazy)
     // If you want add your own
     Tree(Tree const&)            = delete;
     Tree& operator=(Tree const&) = delete;

     void addData(int data) {
        // Ill leave you to implement this
     }
};

These should be a member of the Tree object (Note the Node)

void inorder_rec(struct node *temp)
void preorder_rec(struct node *temp)
void postorder_rec(struct node *temp)

Why are you using printf when you import iostream?

    printf("%d",temp->data);
    printf("%d",temp->data);

Your main just leaks memory. For every call to new there should be a call to delete.  But in reality there should be zero calls to new. That should be done internal to the owning class and most objects should be automatic objects (construct on declaration and destruct when they go out of scope).


Argument parser for a word count and/or line count program

Do you notice something fishy on this line?

print "Words in a file: {}" .format(print_words(args.filename))

If I highlight just the fishy part:

print print_words(...)

The fishy part is printing something returned by print_words.
The name of print_words suggests that it prints something.
And printing functions typically don't return a value.
So this is all very confusing.

My guess is that print_words doesn't actually print words,
but returns a word count. So a name like get_word_count would be less confusing.
The same goes for print_lines.

With these suggested renames, now we can introduce some real printing functions, and make the code more DRY:

if args.words:
    print_words(args.filename)

elif args.lines:
    print_lines(args.filename)

else:
    print_words(args.filename)
    print_lines(args.filename)

It won't get much DRY-er than this, and I don't think it needs to.


Leaflet map distance from the onclick marker

A short review;

selPts.length = 0; //Reset the array if selecting new points always resets the array, even if no points will be added, also selPts = [] is more idiomatic
Seems like xy is not declared there, and it probably should be. Nor is selPts
I feel center describes more accurately the purpose of xy
Idiomatic JavaScript uses lowerCamelCase, so layer_lat_long -> layerLatLong etc.
In the end I went with layerLatLng since you get it from a function called getLatLng
I only knew selPts was selectedPoints due to comments, I think you should spell it out completely
You can extract the common logic into a function and pass that function to .eachLayer()

Obligatory rewrite:

function SelectPoints(latitude, longitude) {
  var dist = document.getElementById("miles").value,
    theRadius = parseInt(dist, 10) * 1609.34; //1609.34 meters in a mile

  center = [latitude, longitude]; //center point of circle
  selectedPoints.length = []; //Reset the array if selecting new points

  function updateSelectedPoints(layer){
    // Lat, long of current point as it loops through.
    layerLatLng = layer.getLatLng();
    // Distance from our circle marker To current point in meters
    distanceFromCenter = layerLatLng.distanceTo(center);
    // See if meters is within radius, add the to array
    if (distanceFromCenter <= theRadius){
      selectedPoints.push(layer.feature);
    }
  }

  if($('#cf').is(":checked")){
    job.eachLayer(updateSelectedPoints);
  }
  if($('#vm').is(":checked")){
    job2.eachLayer(updateSelectedPoints);
  }
  if($('#bt').is(":checked")){
    job3.eachLayer(updateSelectedPoints);
  }
}


Initializing a std::array from a recursive template computation

I think your code is fine for the most part. I don't like the inheritance from std::array, seeing as you can do the same thing with a static array data member, which would make the code easier to maintain (less coupling).

If you're well-and-truly in C++14 land, I think the code is clearer if you use constexpr functions rather than functions-disguised-as-structs:

#include <iostream>
#include <utility>
#include <array>

constexpr size_t factorial(size_t t) {
    return t == 0 ? 1 : t * factorial(t - 1);
}

template<size_t... i>
constexpr auto factorial_array(std::index_sequence<i...>) {
    return std::array<size_t, sizeof...(i)>{{factorial(i)...}};
}

template<size_t size>
constexpr auto factorial_array() {
    return factorial_array(std::make_index_sequence<size>{});
}

int main() {
  constexpr auto f = factorial_array<15>();
  for (size_t i = 0; i < f.size(); i++) {
    std::cout << i << "! = " << f[i] << '\n';
  }
  return 0;
}