The regular expression for email that matches 100% accurately would be a sight to see.  One answer to this related question claims to do that.  It certainly is horrendous, so I won't complain that yours isn't completely accurate.  While a phone-number is relatively simple, the possibilities are more than you might think.  For example, not all countries require ten digits.  The ITU has defined the maximum number of digits to be 15.  You can then take into account that the country code might not have a plus sign (+) before it.  It might be something like 1-800-123-4567.  The number of possibilities grows the more one thinks about it, so I won't complain.  I'm merely pointing it out.

I would use re.finditer() instead of re.findall().  That means that instead of getting a list of tuples, you get an iterator of matches.  With that, it becomes:

for email in emailmo:
    print(email.group())

and similar for the phone numbers.

There are two ways that I see to do the list comprehension (with re.finditer()):

[print(pn.group()) for pn in phonemo]
print('\n'.join([pn.group() for pn in phonemo]))

The first is positively sickening.  It creates a list as long as the number of phone numbers or email addresses, and that list isn't even used.  The second is a little more to my liking, but I do believe that the explicit for loop is better.  For your curiosity, the old code in similar comprehensions could be horrendous:

[print(''.join(pn)) for pn in phonemo]

or ... horrendous:

print('\n'.join([''.join(pn) for pn in phonemo]))


For just Mass, I would define some constants.

public final static Mass kg = new Mass(1);
public final static Mass lb = new Mass(1/2.2, kg);
public final static Mass oz = new Mass(1/16.0, lb);

And define your conversions with the “to” (and “from”) units passed in.

public double in(Mass unit) {
    return mass / unit.mass;
}

public static double convert(double quantity, Mass from, Mass to) {
    return quantity * from.mass / to.mass;
}

Of course, you’d need to remove the “set” members, and make the Mass a constant value class.

private final double mass;

public Mass(double kg) {
    mass =  kg;
}

public Mass(double quantity, Mass unit) {
    mass = quantity * unit.mass;
}

New units just mean defining new class constants.

Mass weight = new Mass( 100, Mass.kg );
double pounds = weight.in( Mass.lb );
double ounces = weight.in( Mass.oz );

As described in the comments, you could expand this to a complete unit calculator, if you tracked the power of each unit dimension in the quantity class.


I think you're on the right track with this, but that there are some improvements you could make.
A Better Abstraction
The way you have it now, a user of this linked list type has to do a bunch of work to create and maintain the list. You could make it a lot easier on a user to define a list type separate from the node type. Something like this:
typedef struct IntNode {
    int value;
    struct IntNode *next;
} IntNode;

and
typedef struct IntList {
    IntNode *head;
    IntNode *tail;
} IntList;

What this allows you to do is quickly insert at the head and tail, which are 2 common operations. It also means that a user of this type doesn't have to make all the links between the nodes manually.
You could add a function to create a new empty list, a function to insert an int into the list at the tail, and another to remove an int from the list. Once you have the creation and insertion functions, you don't need to put memory allocation code into the add() function. You would simply create the list at the start of the add() function, then as you go through the 2 input lists, generate the new int containing the sum, and insert it into the list. It might look something like this:
SinglyLinkedListInt *add_two_numbers(SinglyLinkedListInt *l1, SinglyLinkedListInt *l2) {
  SinglyLinkedListInt *result = create_new_list();
  if (result == NULL)
  {
    return NULL;
  }

  int carry = 0;
  while (l1 || l2 || carry) {
    int a = l1 ? l1->value : 0;
    int b = l2 ? l2->value : 0;
    int value = carry + a + b;

    append(result, value % 10);

    carry = value / 10;
    l1 = l1 ? l1->next : NULL;
    l2 = l2 ? l2->next : NULL;
  }

  return result;
}

Here you'd write the create_new_list() function and the append() function that would add the new value to the end of the list. Now you don't have allocation code in a math function, and you don't need to keep track of the current node and keep incrementing it. (As pointed out by @chux, you will need some way to tell whether append() successfully allocated memory or not. I would probably have it return a boolean indicating success or failure and make sure to check it after calling.)
Memory Management
You are correct that not calling free() on something that you've created with malloc() is a problem. In the code you currently have, you should be freeing result and every node in the list after you're done using them. Note that that's one more thing a user of this code has to keep track of: some lists are created on the stack and some are created on the heap, and it's even possible that some nodes in the same list could be created in different places and need to be handled differently for freeing them.
If they were always created on the heap, it would simplify using the type by having a free_list() function that did it for you. If you used my above suggestion about creating a separate IntList type, it might look something like this:
void free_list(IntList *list)
{
    if (list == NULL)
    {
        return;
    }

    IntNode* current_node = list->head;
    IntNode* next_node = NULL;
    while (current_node != NULL)
    {
        next_node = current_node->next;
        free(current_node);
        current_node = next_node;
    }
    list->head = NULL;
    list->tail = NULL;
    free(list);
}

Then your call sequence becomes:
IntList* list = create_new_list();
// ... Add some nodes
list->append(...);
list->append(...);
//... do whatever else with the list
free_list(list);


Saving player name throughout script-launches

I'm not sure why you are reading all of the file and checking for istitle(). Here I make the assumption that if the file exists, it will always include the player name on the first line.

if os.path.isfile('names.json'):
  with open('names.json') as f:
    player_name = f.readline()
else:
  player_name = console.input_alert('What is your name? ').title()

with open('names.json', 'w') as f:
    f.write(player_name)

If you want to read the entire file and check for istitle():

player_name = None
if os.path.isfile('names.json'):
  with open('names.json') as f:
      for line in f.readlines():
          if line.istitle():
              player_name = line

with open('names.json', 'w') as f:
    if player_name is None:
      player_name = console.input_alert('What is your name? ').title()
    f.write(player_name)

You may notice that I do not close the files in either case. That is because the with statement takes care of that for us. See Understanding Python's "with" statement.


Yes, I think it is fine. erase() will get rid of the <key,value> pair indexed by the id.

A tiny optimization here would be calling erase() with the iterator it instead of the id string. This should avoid a second lookup, since the iterator already contains the relevant information map need to remove the item. You can see here that erase() operates on keys or iterators.

Also, pass your id string by const reference, since the method does not need a copy of the string. E.g.:

void TextureManager::freeTexture(const std::string & id) { /* ... */ }
                                 ^^^^^             ^

This is a very long and error prone line:

std::map<std::string, SDL_Texture*>::iterator

You should typedef the map type or use auto if targeting C++11.

Typedefing map somewhere:

// In the header file somewhere...
typedef std::map<std::string, SDL_Texture*> TextureMap;

// Then it is a little simpler to use:
TextureMap::iterator it = map.find(...);

Or just use auto if you can:

auto it = map.find(...);


Pythonic way to convert XML attribute to float, or else get None

It's a bit difficult to get None without writing an explicit conditional.  The next best option may be to go with float('nan') instead of -1 to make it harder to accidentally use it as a value.

self.radius = float(etree_elem.attrib.get('radius', 'nan'))

You can use math.isfinite() to test the existence of a value.  The self.radius >= 0 test would also continue to work.


Take all the bits in a number and shift them to the left end

It appears the correct results are given, which is good.  I do see some miscellaneous things, though.

The naming and execution in main() seem confusing.  Try something like this:

int main()
{
    // the name "bit" is misleading; you're using an integer
    // name it something more accurate (this is just an idea)
    int original = 11;

    // why not return the final (shifted) integer?
    // sticking set_bit() into print_bit() is hard to read
    int final = set_bits(original);

    // print both integers
    print_bit(original);
    print_bit(final);
}

This:

if((bit & i) != 0)
std::cout << "1";
else std::cout << "0";

could become a single-line ternary statement:

// read as: (statement is true?) ? (if so, do this) : (if not, do this)
std::cout << ((bit & i) != 0) ? "1" : "0";

This:

if((bit & i) == 0)
    lefted <<= 1;

could have curly braces (to allow any additional code for the body):

if ((bit & i) == 0)
{
    lefted <<= 1;
}

I'd probably make your "magic numbers" (such as 0x80) constants.  This could help provide more context for your code, especially when there's no relevant documentation.
std::cout << std::endl; doesn't need to be in print_bit().  The display function should only print the values; that's what the user expects.  If you want a newline with the displaying, put it around the calling code.  That way, the displaying will be easier to adjust.


Measure website home page total network size in bytes

You're using the wrong shebang. According to this StackOverflow answer:

  Correct usage for Python 3 scripts is:

#!/usr/bin/env python3

  This defaults to version 3.latest. For Python 2.7.latest use python2 in place of python3.

Don't use #!/usr/bin/python. From the Tutor mailing list:

  Consider the possiblities that in a different machine, python may be installed at /usr/bin/python or /bin/python in those cases, the above #! will fail.
  For those cases, we get to call the env executable with argument which will determine the arguments path by searching in the $PATH and use it correctly.

I'd move command line argument handling to the bottom, possibly in a main(). The rest of the code could be separated into function 'units'.
Certain variables and literals could be replaced by constants. From what I can tell:

logging_prefs could be a constant;
Waiting times could be constants;
Exit codes could be constants.

Catching Exception is bad practice.
These parentheses:

d = (datetime.today()).strftime("%d-%m-%y-%H-%M")

are superfluous.
This cast:

filename = 'results_{}.txt'.format(str(d))

is pointless.
Don't mix single and double quotes.
Don't assign multiple variables on a single line.
The same driver will be instantiated, regardless of the 'datacentre' argument. Therefore, the if-statement can be left out altogether.
Error messages should be written to stderr, not stdout.
Imports should be placed at the top of a file, and rarely in a function.

Here's my take on it (untested):

#!/usr/bin/env python3

""" This script will simply check the download page size (bytes) of a Home page."""

from __future__ import print_function

import argparse
from datetime import datetime
import re
import sys

from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

LOGGING_PREFS = {"performance": "INFO"}

WAITING_TIME = 30
TIMEOUT = 30

DATA_LENGTH_REGEX = r"encodedDataLength\":(.*?),"

EXIT_OK = 0
EXIT_WARNING = 1
EXIT_FAILURE = 2

def get_driver(local):
    if local:
        caps = DesiredCapabilities.CHROME.copy()
        caps["loggingPrefs"] = LOGGING_PREFS
        return webdriver.Chrome(desired_capabilities=caps)
    else:
        profile = webdriver.FirefoxProfile()
        profile.set_preference("plugin.state.flash", 0)
        profile.set_preference("webdriver_enable_native_events", False)
        profile.update_preferences()

        caps = DesiredCapabilities.FIREFOX.copy()
        caps["loggingPrefs"] = LOGGING_PREFS
        caps["acceptSslCerts"] = False

        return webdriver.Remote(
            command_executor="http://selenium/hub",
            desired_capabilities=caps,
            browser_profile=profile
        )

def get_homepage_size(driver, website):
    driver.implicitly_wait(WAITING_TIME)
    driver.set_page_load_timeout(TIMEOUT)
    url = "http://" + website + "/"
    driver.get(url)
    total_bytes = []

    try:
        for entry in driver.get_log("performance"):
            entry = str(entry)
            if "Network.dataReceived" in entry:
                r = re.search(DATA_LENGTH_REGEX, entry)
                total_bytes.append(int(r.group(1)))
    except Exception:
        # TODO Find a more specific exception.
        # What could fail?
        driver.close()
        print("Failed to get data size for {}".format(website), file=sys.stderr)
        sys.exit(EXIT_FAILURE)

    if total_bytes is not None:
        return round((float(sum(total_bytes) / 1000) / 1000), 2)

def write_results_to_file(website, size_in_mb):
    date = datetime.today().strftime("%d-%m-%y-%H-%M")
    filename = "results_{}.txt".format(date)
    with open(filename, "a") as f:
        f.write("{}, {}\n".format(website, size_in_mb))

def display_results(website, size_in_mb):
    if size_in_mb < 2.0:
        print("OK. Total Network Data Received size for {}: {}MB".format(
            website, size_in_mb)
        )
        sys.exit(EXIT_OK)
    elif size_in_mb >= 2.0 and size_in_mb < 4.0:
        print("Warning. Total Network Data Received size for {}: {}MB".format(
            website, size_in_mb
        )
        sys.exit(EXIT_WARNING)
    elif size_in_mb >= 4.0:
        print("CRITICAL. Total Network Data Received size for {}: {}MB".format(
            website, size_in_mb)
        )
        sys.exit(EXIT_WARNING)

def main():
    parser = argparse.ArgumentParser(description="This script will measure size of a home page.")
    parser.add_argument("--site", default="somewebsite.com", required=True)
    parser.add_argument("--local", action="store_true", default=False)
    parser.add_argument("--datacentre", choices=["dc1", "dc2"])
    args = parser.parse_args()

    driver = get_driver(args.local)
    size_in_mb = get_homepage_size(driver=driver, website=args.site)
    if args.local:
        write_results_to_file(args.site, size_in_mb=size_in_mb)
    display_results(args.site, size_in_mb=size_in_mb)

if __name__ == "__main__":
    main()


So I thought I'd try this out with a test enumerable.

public class NumberValues : IEnumerable<int>
{
    public NumberValues(int startValue, int endValue)
    {
        _endValue = endValue;
        _startValue = startValue;
        counter = 0;
    }
    public NumberValues(int endValue) : this(0, 10) { }

    public int counter { get; set; }

    public IEnumerator<int> GetEnumerator()
    {

        var iterator = _startValue;
        while (iterator < _endValue)
        {
            Trace.Write(iterator + ",");
            iterator++;
            counter++;
            yield return iterator;
        }

    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
}

followed closely by

    [TestCase(0,5)]
    [TestCase(1,5)]
    [TestCase(0,6)]
    [TestCase(1,6)]
    [TestCase(0,10)]
    [TestCase(1,10)]
    public void TestSkipBeforeIf(int start, int end)
    {
        var numberValue = new NumberValues(start,end);
        numberValue.SplitBeforeIf(i => i%2 == 0).ToList();
    }

which results in the following output.

0,5 > 0,0,1,0,1,2,0,1,2,3,0,1,2,3,4,0,1,2,3,4,0,1,2,3,4,  - 25
1,5 > 1,1,1,2,1,2,3,1,2,3,4,1,2,3,4,1,2,3,4,  - 19
0,6 > 0,0,1,0,1,2,0,1,2,3,0,1,2,3,4,0,1,2,3,4,5,0,1,2,3,4,5,  - 27
1,6 > 1,1,1,2,1,2,3,1,2,3,4,1,2,3,4,5,1,2,3,4,5,  - 21
0,10 > 0,0,1,0,1,2,0,1,2,3,0,1,2,3,4,0,1,2,3,4,5,0,1,2,3,4,5,6,0,1,2,3,4,5,6,7,0,1,2,3,4,5,6,7,8,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,  - 65
1,10 >     1,1,1,2,1,2,3,1,2,3,4,1,2,3,4,5,1,2,3,4,5,6,1,2,3,4,5,6,7,1,2,3,4,5,6,7,8,1,2,3,,4,5,6,7,8,9,1,2,3,4,5,6,7,8,9,  - 55

0,20 > 230
0,40 > 860
0,100 > 5150

But why?

        while (input.Any())
        {
            var temp = input.TakeWhile(v => !pred(v));
            if (predSatis == null || predSatis.Equals(default(T)))
                yield return temp;
            else
                yield return (new List<T> { predSatis }).Concat(temp);

            input = input.SkipWhile(v => !pred(v));
            predSatis = input.FirstOrDefault();
            input = input.Skip(1);
        }

if you evaluate your 2 lines

input = input.SkipWhile(v => !pred(v));
predSatis = input.FirstOrDefault();

over iterations of your while loop, it is necessary to expand the input variable for each iteration.

input.SkipWhile(pred).FirstOrDefault
input.SkipWhile(pred).SkipWhile(pred).FirstOrDefault
input.SkipWhile(pred).SkipWhile(pred).SkipWhile(pred).FirstOrDefault
input.SkipWhile(pred).SkipWhile(pred).SkipWhile(pred).SkipWhile(pred).FirstOrDefault

having seen this, we now consider the evaluation of input.SkipWhile(!pred)

so over 100 iterations

pred = x => x % 2 == 0 : 5150
pred = x => x % 3 == 0 : 3600
pred = x => x % 4 == 0 : 2625
pred = x => x % 5 == 0 : 2120
pred = x => x % 6 == 0 : 1849
pred = x => x % 15 == 0 : 837
pred = x => x % 20 == 0 : 605
pred = x => x % 25 == 0 : 504
pred = x => x % 30 == 0 : 564
pred = x => x % 30 == 0 : 413

Your functions behaviour is therefore dependent not just on the size of your data, but on the form of your predicate.

For your own analysis, this is what I used for evaluating the predicate

   [TestCase(1,5000,10)]
   public void TestSkipBeforeIf(int start, int end, int mod)
   {
        var numberValue = new NumberValues(start,end);
        numberValue.SplitBeforeIf(i => i%mod == 0).ToList();
   }

I'm not clear what you meant by stateful predicate or IEnumerable, however in terms of the IEnumerable I have maintained a count as state. Similarly I could maintain a count for the pred, or add some bizarre checking behaviour.

Func<object, int, bool> predStateful = (y,x) =>
{
    if (x == y.Check(x))
    {
        return false;
    }
    return x%mod == 0;
};
Func<int, bool> pred = x => predStateful(MyCheckingObject,x);
numberValue.SplitBeforeIf(pred).ToList();

Thanks for the interesting question.

EDIT: Modified Chunk function using a predicate.
original

    public static IEnumerable<IEnumerable<TValue>> Chunk<TValue>(
                    this IEnumerable<TValue> values,
                    Func<TValue,bool> pred)
    {
        using (var enumerator = values.GetEnumerator())
        {
            while (enumerator.MoveNext())
            {
                yield return GetChunk(enumerator, pred).ToList();
            }
        }
    }
    private static IEnumerable<T> GetChunk<T>(
                     IEnumerator<T> enumerator,
                     Func<T,bool> pred)
    {
        do
        {
            yield return enumerator.Current;
        } while (!pred(enumerator.Current) && enumerator.MoveNext());
    }


JUnit test case to check that an exception of type javax.mail.MessagingException is not thrown

JUnit will fail anyway if an (unexpected) exception is thrown, by creating an Error (instead of a simple failure). As you do not catch any other exceptions (which means every exception fails your test anyway), you can simply remove the try-catch block, as your test case will still fail then if the MessagingException is thrown.


Kadane's Algorithm for 2D array with known boundaries

Input can be simplified using destructuring assignment and NumPy:

N, M, max_rows, max_cols = map(int, raw_input().split())
table = np.genfromtxt(sys.stdin)

By the PEP 8 standard, variable and function names should be written using lowercase_with_underscores.  The comment block for each function should be a docstring instead.

The kadane2DwithBounds() function should return its result instead of printing it.

The use of global variables N, M, table, and temp within the two functions is disconcerting.  table and temp should be passed explicitly.  N and M can be inferred by inspecting the table itself, and therefore don't need to be passed to the kadane functions.


The CharacterFactory class is created so that I'll be able to handle Orc and Human classes in a more abstract way or so.

You try to stay DRY which is very good, but this idea would be better represented with inheritance.

You could create a class Character() and let both Human and Orc, inherit from the super class like so:

class Character():
    def __init__(self, health, attack_damage, name):
        self.attack_damage = attack_damage
        self.health = health
        self.name = name

    def attack(self, target):
        target.health -= self.attack_damage

    def __str__(self):
        return f"Name: {self.name}\nDamage: {self.attack_damage}\nHealth: {self.health}\n"

class Human(Character):
    def __init__(self, name, health=105, attack_damage=45):
        super().__init__(health, attack_damage, name)

class Orc(Character):
    def __init__(self, name, health=100, attack_damage=50):
        super().__init__(health, attack_damage, name)

def main():
    orc = Orc("Karcsi")
    human = Human("Nojbejtoo")

    print(orc)
    print(human)

    orc.attack(human)
    print(human)

if __name__ == "__main__":
    main()

Things I changed:

Instead of an inspect function, I override the magic function __str__ so you can directly print(human) or print(orc)
The use of the if __name__ == '__main__'
And the snake_case functions main instead of Main
In the attack function body, see how a = a - b equals a -= b

I have omitted the GameState part, maybe someone else will pick that up.

Good luck with your game!


I don't understand why you need GNU tr for this task. The macOs tr should work equally well.

For passwords, you should use /dev/random instead of urandom.

It's a funny password policy if it really requires the password to be 99 characters long. At that length, it doesn't matter anymore whether the password contains a digit or not because such a long password, if generated by a strong random generator, cannot be guessed.

The code in itself is fine. I would indent it differently, though, lining up all four calls to tr. Writing a function to eliminate the code duplication is probably overkill.


Registering various kinds of blocks in Minecraft

Your updated version is pretty darn good.  As in, "You're basically done, no need to make any further changes." (See note at the bottom).

The only thing I did differently (aside from creating non-normal registration methods as well that do all sorts of things) was to take two classes I already had and give them the register function: ClientProxy and CommonProxy.

My setup is such that ClientProxy.register calls super (which calls GameRegistry.register for the block as well as creating and registering the itemblock) and then calls ModelLoader.setCustomModelResourceLocation for the item (or registerItemVariants for block-variant items, or other methods for other pathways).

I later moved this code over into a library package I already had (centralizing the gains and avoiding duplication), added some static methods (in the Common) as helper redirects and ended up with this class which can be boiled down to these two methods for the basic no-nonsense blocks:

public void _registerBlockWithItem(Block block, String registryname) {
    super._registerBlockWithItem(block, registryname);
    _registerBlockResources(block);
}

private void _registerBlockResources(Block block) {
    Item item = Item.getItemFromBlock(block);
    ModelLoader.setCustomModelResourceLocation(item, 0, new ModelResourceLocation(block.getRegistryName(),"normal"));
}

The first method being equivalent to your register method which self-calls your registerClient only on the client side, which then allows us to merge init and initClient.

This made my ModBlocks (well, main mod class in my case) very slim when it comes to registering blocks and items. Looks almost 1.7ish!

There are still some minor improvements which could be made, but at two-three lines per block it's a vast improvement over your original thirteen lines per block.

Note: you should also mark registerClient as @SideOnly(Side.CLIENT) as well: that method is still refers to a class that doesn't exist on the server (ModelLoader) and may crash the dedicated server when the JVM tries to load your ModBlocks class.


I'm not sure where you got xlInputReference from, or 16. According to the MSDN page you linked, the correct type for a reference input is 8.

I'm not sure I like your approach. You only need this for range inputs. Personally, I would handle this (prompting for range inputs) by asking for a cell reference (as text) then converting that text into a range object separately (with appropriate error handling).

But, to take your current approach:

As it stands, I've got very little that I can see improvements for.

You shouldn't use Integer. It is completely deprecated. Use Long instead.

Your method name isn't great and breaks convention (that Metohd names use PascalCase). I would use something like HandleInputBox.

Since yes, you can have compound return types but obviously, trying to return some combination of object + text + number is going to fail, you probably want to check for it:

If dataType Mod 16 >= 8 Then
    If dataType <> 8 Then
    '/ Compound of 8 with other values
        '/ Error handling
    Else
        On Error GoTo InputCancelled
        Set mjInputBox = Application.InputBox(prompt:=prompt, Title:=Title, Default:=Default, Type:=dataType)
        On Error GoTo 0
    End If
Else
    mjInputBox = Application.InputBox(prompt:=prompt, Title:=Title, Default:=Default, Type:=dataType)
End If

You should probably implement all the other optional arguments for Application.InputBox() as well since you only have to pass them through.

Other than that, I have nothing to critique. The code is good.


An echo program, mostly in C and completely from scratch

Is my program's behavior fully compliant with the standard for echo?

Code does not process the string as in the OPERANDS section.  In particular:

Code does not support \c: "Suppress the <newline> that otherwise follows the final argument in the output. ..."

  Am I making any unwarranted assumptions that could make my code not work on a future release of Linux (or compiler)? In particular, are popping argc and the way I'm overwriting null terminators in argv values okay?

I see no trouble with argc.

Overwriting the null terminators in argv may/may not be OK, but is not needed.  I could foresee future restrictions.  Alternative: write the argv[i] and then the separator.

  Other issues

No comment.


Finding the smallest positive number evenly divisible by a range of numbers

There are two parts to my initial assessment of your code.

Firstly, often the 'best' way to solve a problem where you are tempted to have a found = true type situation is to call a seperate method for that part of the work, and to simply 'return value' when you find the value... for example, your code:

     for (int i = 1; i <= n; i++) {
         //for 1 to int that was passed divide the current number and see if its divisible
            if (number % i != 0) {
             break;

         } else if (i == n)
             found = true;

     }

would be easily written as:

private static final boolean checkValue(final int value, int n) {
    while (n > 1) {
        if (value % n != 0) {
            return false;
        }
        n--;
    }
    return true;
}

then your main loop becomes:

int number = n;

while (!checkValue(number, n)) {
     number++;
}
System.out.printf("Number %d is divisible by all positive values up to %d\n", number, n);

The second issue I have is for performance..... you should not be using number++, you will save a lot of time if you only check the multiples of the largest number, so:

number += n; // instead of number++;

EDIT

If you look at the math, you will see that, we can do much better than number += n, and can determine that if we find a value that is a multiple of both n and n - 1 that the final result will be a multiple of that value. If we can use that value as the 'step' then we will go faster than just using n. Similarly, if we can find a multiple of all n, n - 1, and n - 2 then that would be a good step too.

So, consider the following:

private static final int checkValue(final long value, int n) {
    while (n > 1) {
        if (value % n != 0) {
            return n;
        }
        n--;
    }
    return 1;
}

This loop now returns the value at which the expression fails....

and we can use that in our main loop as follows:

    final int n = 23;

    long number = n;

    long step = n;
    int fact = n;
    int bestfact = fac;
    while (number > 0 && (fact = checkValue(number, n)) > 1) {
        if (bestfac > fact) {
            bestfac = fact;
            step = number;
        }
        number += step;
    }

    if (number < 0) {
        System.out.println("No values were found (overflow) divisible by all " + n + " factors");
    }

On my computer, the difference between this optimization and a naieve step, is 0.022ms vs 4961.271ms  (or 225000 times faster!!!!!!!)


Note: I would take everything I say with a grain of salt.  It's been a few years since I used C on a regular basis, and even at my peak with C, I was never very familiar with the standard or certain best practices.

Your function is responsible for cleaning up memory, yet when you bail in your NULL returns, you don't do that.

In particular, if a realloc fails, the memory already allocated stays, and if allocating the second dimension-ed array fails, you still need to free what you have already allocated before returning.

A review of a few code points:

I would highly consider abstracting away the memory stuff, but if you don't, I would consider doubling the array size instead of adding ten.

Consider a fairly long string being split on space.  Assume it ends up being 1000 split strings.  This means 100 allocations, and allocating is fairly slow.  If you were to double, it would be 10 allocations.

Doubling wastes, at most, sizeof(type) * n/2 bytes, but has at most, lg n allocations (note: very rough math)
Doubling using more memory but is typically faster

size should be an unsigned type (I would use size_t)
As previously mentioned, you have potential memory leaks
As your code exists, there's really no advantage over strtok

strtok doesn't very well allow storing into an array, but your function requires fairly manual memory management anyway

The malloc/strncpy combination could be changed to use strndup and be a lot simpler (I think strndup is standard?)
You could actually use strtok inside of your function to avoid doing the index calculations

Part of your code is recreating strtok
The other part of your code is taking that strtok functionality and using it to push things into an array
What you have now will (probably) perform better than strtok

I'm not familiar enough with standard practices of C to know what the expected way would be, but something about the the memory handling feels odd to me:

const char[] str = "Hello World";
int size = 0;
char** str_parts = my_split(str, ' ', &size);
if (str_parts != NULL) {
    //Let's do something with the parts
    for (int i = 0; i < size; ++i) {
        printf("Part %d: '%s'\n", size, str_parts[i]);
    }
    //Now we have to clean up (could technically be in the printing loop)
    for (int i = 0; i < size; ++i) {
        free(str_parts[i]);
    }
    free(str_parts);
}

I might consider abstracting the memory away to a generalized vector or a specialized string vector.

That could bring your API to something like:

const char[] str = "Hello World";
cvector parts;
//A vector of char*'s that will call free() on each element before destructing
cvector_init(&parts, sizeof(char*), free);
if (my_split(&parts, ' ')) {
    for (size_t i = 0; i < parts.size; ++i) {
        //I'm a bit rusty on C, so I'm not sure if the char* cast is needed or not
        printf("Part %d: '%s'\n", size, (char*) cvector_get(&parts, i));
    }
}
cvector_destory(&parts);

The downside to this would be that you'd be tying your other code to a specific API (though bastardizing the vector into a char** would actually be fairly easy if you wrote the cvector API in a particular way -- though then you'd be depending on implementation details, which is usually a bad idea), and this vector would perform worse than a plain 2d array.  (Though if you wrote a string specialized vector, the performance could be very similar and, depending on design, you could even use it as a char** without worrying much about the implications.)


Searching in a lock-free ordered single-linked list

Lockless list not threadsafe
I was able to break your list with a simple program:
LF_List list = {0};

void *threadFunc(void *arg)
{
    uint64_t key = (uintptr_t) arg;
    int i;

    for (i=0;i<100000;i++) {
        lf_list_put_if_absent(&list, key, (void *) 1);
        if (lf_list_remove(&list, key) == 0) {
            printf("ERROR\n");
            exit(1);
        }
    }
    return NULL;
}

int main(void)
{
    pthread_t t1, t2;
    pthread_create(&t1, 0, threadFunc, (void *) 9);
    pthread_create(&t2, 0, threadFunc, (void *) 8);
    pthread_join(t1, NULL);
    pthread_join(t2, NULL);
}

When I ran this program, one of three things happened:

The program terminated (no errors).
The program printed ERROR, meaning that something went wrong with a put or remove.
The program never terminated, indicating a cycle in the list was created.

I was also able to cause a segmentation violation by modifying lf_list_remove() to write 0xffffffff to the next pointer of a node just before freeing it:
    if (CAS(prev, cur, PTR_OF(cur)->next) == cur) {
        // Once a pointer is freed, its memory could be trashed.
        // Simulate this by writing an invalid address to cur->next.
        PTR_OF(cur)->next = 0xffffffff;
        free(PTR_OF(cur));
        INCR(&table->size, -1);
        return 1;
    } else {
        continue;
    }

I was also able to cause the program to crash by specifically adding some strategic sleep() calls to cause two threads to perform a specific sequence of events, but that code is too lengthy to list here unless you really want to see it.
Basically, what it all boils down to is that when one thread is freeing a node, the other thread can access the freed node because there is nothing to stop it from doing so.  The original code in the research paper used marking bits to prevent this from happening, but those marking bits have been removed from this implementation.


There are no docstrings. What do homogeneous_type and binSearch do?
In Python we rarely need to insist that lists be homogeneous. It often makes sense to have heterogeneous lists, provided that all elements support the required operations, for example it can be reasonable to have a list containing a mixture of int and float.
Checking that the list is homogeneous requires looking at every value to check that it is the required type. But if you are going to look at every value, you don't gain anything by doing a binary search, you might as well just call list1.index(value).
Similarly, sorting the list requires looking at every element, so again, there is no point in sorting and then doing a binary search. Skipping the sort and calling list1.index(value) would be faster.
The binary search code maintains a closed interval left <= i <= right that contains the index of the value being searched for. But maintaining a closed interval requires some complexity when computing the middle index:

midIndex, mod = divmod(left + right, 2)
midIndex = midIndex + 1 if mod else midIndex

It would be simpler to maintain a half-open interval left <= i < right by starting with right = len(list1). Then the computation of the midpoint is simple:

midIndex = (left + right) // 2

(In the half-open version of the code the loop condition needs to be left < right rather than left <= right, and you need to assign right = midIndex rather than right = midIndex - 1.)
On each iteration of the binary search loop there are three comparisons:

list1[midIndex] == value:
list1[midIndex] < value:
list1[midIndex] > value:

This can be reduced to one comparison per iteration, like this:

left, right = 0, len(list1)
while left < right:
    mid = (left + right) // 2
    if value < list1[mid]:
        right = mid
    else:
        left = mid + 1
if left < len(list1) and value == list1[left]:
    return left
else:
    raise ValueError("not found")

Note that this version of the code works fine even if list1 is the empty list, allowing you to remove the special case for if not list:.
Binary search is built into Python: see the bisect module.


Ubuntu-Nginx lightweight server environment setup

Good

Tying together related commands with && is a good error-avoidance strategy.

Trouble

The code is not re-entrant because the aliases will keep getting appended every time.  This is bad because you can only run or "enter" the code once safely.  You could touch file if the aliases are added and use that as a flag.  I would create the aliases in file and add a sourceing line to bashrc.  If you add the source line before creating the aliases file the aliases file could serve as your flag file for whether to add that line or not.
Running source on anything that doesn't have some side effect at the end of your script is pointless.  The source is causing the aliases you added to get read into the current shell.  But since you're at the end of your script there's no command that will use the aliases so it was a waste of effort to read them in.  Maybe you intend to do more with these later in the script, but it seems they are intended for the interactive user.  So sourceing the new aliases in an interactive shell would make them available to the interactive user sooner than logging out and logging back in would.
Some comments might save you from rethinking what you did someday.

Maybe trouble

Did you leave out a single quote in the pma alias?
Can you have more than one version of php-fpm installed?  If so your * in the command will expand in a weird way.  Maybe you can put the version you expect in a variable or use packaging commands to the find the version that is installed.
No sanity checking.  It might be good to error out if the files you are looking for turn out to not be around.
I hope you're storing your code in git somewhere.  The lack of a github link makes me wonder about this.


What you've done here is listed all possible checks, but you've compiled it into a single method. Ideally, you should split this up into separate tasks, as there are three categories of similar checks:

Horizontal checks
Vertical checks
Diagonal checks

Maybe the current example is just simple enough to not fully warrant it, but especially if you had had many different win conditions (e.g. another rule that states making a 2x2 square also counts as a win), you'd understand why you need to break your validation into smaller (logically coherent) parts.

The method

public bool WhoWon(Cell cell)

I agree with the other answers here. The name of the method does not match its return type. WhoWon should return a player. HasWon should return a boolean.

I'm also not a fan of the "cell" name. Looking at the code, cell seems to contain the player's letter (X or O).  That is not immediately apparent by calling it a cell, a cell would be a box on the board.

E.g. board[1,1] is a cell, as it represents a box on the board. But I would call the value of board[1,1] a token, i.e. the symbol that is contained within (if it's not empty).

You haven't shared the how Cell is defined. This may already be close to what I'd prefer to use. Based on this, let me suggest an improvement:

public enum Token { X, O, Empty }

public Token[,] _board = new Token[3,3];

public bool HasWon(Token token)
{
    // ...
}

Notice that you could also implement WhoWon() based on HasWon():

public Token WhoWon()
{
    if(HasWon(Token.X))
        return Token.X;

    if(HasWon(Token.O))
        return Token.O;

    return Token.Empty;
}

The method body

I suggest splitting this up, as it will dramatically simplify the validation logic and make it easier to parse.

public enum Token { X, O, Empty }
public Token[,] _board = new Token[3,3];

public bool HasWon(Token token)
{
    return
        IsHorizontalVictory(token)
        || IsVerticalVictory(token)
        || IsDiagonalVictory(token);

}

private bool IsHorizontalVictory(Token token)
{
    for(int y = 0; y <= 2; y++)
    {
        if(_board[0,y] == token && _board[1,y] == token && _board[2,y] == token)
            return true;
    }

    //No victory condition hit = no victory.
    return false;
}

private bool IsVerticalVictory(Token token)
{
    for(int x = 0; x <= 2; x++)
    {
        if(_board[x,0] == token && _board[x,1] == token && _board[x,2] == token)
            return true;
    }

    //No victory condition hit = no victory.
    return false;
}

private bool IsDiagonalVictory(Token token)
{
    if(_board[0,0] == token && _board[1,1] == token && _board[2,2] == token)
        return true;

    if(_board[0,2] == token && _board[1,1] == token && _board[2,0] == token)
        return true;

    //No victory condition hit = no victory.
    return false;
}

Comments:

You could further abstract this, e.g. by making the dimensions of the board variable. However, TicTacToe is always played on a 3x3 board, so this seems unnecessary at the moment.
Instead of using a multidimensional array, you could create a full OO representation of the board with its cells. This is going to cost some effort to put together, but it will make board operations (such as checking for victory) nicer to read. Index-based retrieval is nice when simple, but can become horrendously complex to follow if the logic gets to be too big.
Some things could have been rewritten, e.g. the IsDiagonalVictory() method could have merged the two checks (+ the false return value) into one boolean: return (logic_for_diag_1) || (logic_for_diag_2). However, this would've storngly affected the readability of the code. As the performance difference is negligible, I therefore chose the most readable option.

This was a headscratcher

for (int i = 0; i < 3; i++)  //A
{
    for (int j = 0; j < 3; j++)   //B
    {
        //A
        if (_board[i, 0] == cell && _board[i, 1] == cell && _board[i, 2] == cell)
        {
            return true;
        }

        //B
        else if (_board[0, j] == cell && _board[1, j] == cell && _board[2, j] == cell)
        {
            return true;
        }
    }
}

It took me a while to understand what your intention was here. You've combined two completely separate for-loops, and have for some reason decided to intwine them.

I marked them A and B in the code, because these two are completely separate pieces of logic. Splitting them up:

for (int i = 0; i < 3; i++)  //A
{
    if (_board[i, 0] == cell && _board[i, 1] == cell && _board[i, 2] == cell)
    {
        return true;
    }
}

for (int j = 0; j < 3; j++)   //B
{
    if (_board[0, j] == cell && _board[1, j] == cell && _board[2, j] == cell)
    {
        return true;
    }
}

You may be wondering, does it matter?

Yes, it does. First of all, splitting them dramatically enhances the readability of the code.

Secondly, you're going to end up doing less loops.

Nested for-loops are multiplicative. 3 loops for A times 3 loops for B = 9 loops. Furthermore, each of the 9 loops is doing two checks, thus resulting in 18 checks occurring.
Separate for-loops are additive. 3 loops for A plus 3 loops for B = 6 loops. Each loop only does one check, thus resulting in 6 checks occuring.

Your nested loops were performing every unique check three separate times (18 / 6 = 3), which serves no functional purpose.

Let's look at only the vertical check:

if (_board[i, 0] == cell && _board[i, 1] == cell && _board[i, 2] == cell)

This was being executed for every pair of i,j, while you only needed to test for every value of i.

This is a comparison of the pairs (i,j) and what the vertical check actually did:

(0,0)   =>   Checks vertical column 0
(0,1)   =>   Checks vertical column 1
(0,2)   =>   Checks vertical column 2
(1,0)   =>   Checks vertical column 0
(1,1)   =>   Checks vertical column 1
(1,2)   =>   Checks vertical column 2
(2,0)   =>   Checks vertical column 0
(2,1)   =>   Checks vertical column 1
(2,2)   =>   Checks vertical column 2

Notice how it repeats the same thing for every value of j (0,1,2), even though the value of j has no impact on the outcome of the result.

This is a comparison of the values of i and what the vertical check actually did:

(0)   =>   Checks vertical column 0
(1)   =>   Checks vertical column 1
(2)   =>   Checks vertical column 2

By not observing the value of j, we haven't repeated the same check for every distinct value of j.


Compile with all warnings

If you compile this code with all warnings enabled (e.g. -Wall -Wextra -pedantic) the compiler will tell you that your initialization is out of order.
This simply means you initialize your members in a different order than they have been declared in. In your example this is not bad but if you have members that depend on others being initialized before them this can lead to problems.

& is part of the type in C++

While this is not an error it can look like bitwise AND at a glance and be a potential source of confusion. Prefer to write foo& bar instead of foo & bar.

User defined types

Also just a minor nitpick but usually user defined types start with an uppercase letter i.e. ClickableRect.
Since you inherit from Shape I think it would make more sense to name your class ClickableShape but this is just personal preference.

Design

You expose window to your class only to get access to the mouse coordinates. Unless you plan to use window in a different matter in the future it'd be better to hide this info from your class.
A simple approach to testing for a click within your shape could be:

class ClickableShape : public sf::RectangleShape {
public:
    bool click(const sf::Vector2i& mouse_pos) const {
        return getGlobalBounds().contains(mouse_pos.x, mouse_pos.y);
    }
};

Which can then be called as:

ClickableShape cs{};
cs.setSize(sf::Vector2f(50, 50));
cs.setFillColor(sf::Color(0xffffffff));

And finally in your event loop:

case sf::Event::MouseButtonPressed:
    cs.click(sf::Mouse::getPosition(window));
    break;

This way you avoid exposing unnecessary data to your class and can still check if the shape was clicked.

Approach #2:

I'm not sure what you're planning to do with this in the future but another approach to this would be to keep the inheritance short and have the rectangle as a member.

class MyButton : public sf::Drawable {
public:
    MyButton() {
        shape.setSize(sf::Vector2f(50, 50));
        shape.setFillColor(sf::Color(0xffffffff));
    }

    bool click(const sf::Event& event) const {
        return shape.getGlobalBounds().contains(event.mouseButton.x, event.mouseButton.y);
    }

    void draw(sf::RenderTarget& target, sf::RenderStates states) const {
        target.draw(shape);
    }

private:
    sf::RectangleShape shape;
};


Show User that Page is Loading using dots (...)

$(document).ready(function(){

    var interval;

    function startIndicator(){
        stopIndicator();

        dotCount = 1;

        interval = setInterval(function(){

            $("#dots").text('.'.repeat(dotCount));

            dotCount++;
            if(dotCount > 3){
                dotCount = 0;
            }

        },1000);
    }

    function stopIndicator(){
        clearInterval(interval);
        dotCount = 0;
        $("#dots").text('');
    }

    $("#run").click(startIndicator);

    $("#stop").click(stopIndicator);

});

Authenticating

<button id="run">
    Run It
</button>
<button id="stop">
    Stop
</button>

This improves:

Original code allowed multiple timers set causing issues
String "Authenticating" not repeated and confined to HTML
Slightly cleaner conditions
Renamed countdown to indicator because it's not really a countdown
WARNING: .repeat maybe only works in quite modern browsers

Note: If you want to hide the "Authentication" text as well, just add CSS to hide the .progress div where appropriate.

One alternative approach that will probably give less and simpler code, at the cost of user's CPU, is to make the dots update all the time and simply toggle the visibility of #dots or .progress.


Selecting/ Deselecting All from Checkbox

I see what looks like a bug. The x variable (which should probably be renamed to something more informative - maybe user?) is a object (with selected and StudentScheduleUsrID properties) which you remove from the array in the upper code with

} else {
    angular.forEach($scope.selectedUserListOP, (el, idx) => {
        if(el.StudentScheduleUsrID === $scope.scheduleUsers.lstOnlineProctoring[k].StudentScheduleUsrID) {
            $scope.selectedUserListOP.splice(idx, 1);
        }
    });
}

splice's first argument should be the index of the element you want to start deleting from. That's fine. But in the lower code, the first argument you pass to splice is the object x, not the index:

$scope.scheduleUsers.lstOnlineProctoring.forEach(x => {
  // ...
  } else if(!checked){
      if($scope.selectedUserListOP.filter(m => m.StudentScheduleUsrID == x.StudentScheduleUsrID).length > 0)
          $scope.selectedUserListOP.splice(x, 1);
  }

That won't work, because the first argument is not a number. If you want to remove this x from the array there, find its index in the array with findIndex, then pass that number to splice.

const selectedUserIndex = $scope.selectedUserListOP.findIndex(
  selectedUser => selectedUser.StudentScheduleUsrID === user.StudentScheduleUsrID
);
if (selectedUserIndex !== -1) {
  $scope.selectedUserListOP.splice(selectedUserIndex, 1);
}

On a different note: Errors should not arise in synchronous code in most cases. If you have code that sometimes results in an unexpected error, you should fix the code so that the error doesn't ever occur (as far as you can tell). If you've tested the code in various situations (which you should be doing anyway, as a developer) and you can't think of any which might cause an error to occur, there shouldn't be any reason to use try/catch, since it'll just clutter up the code - and besides, you aren't doing anything with the error other than logging it to the console, but the error will be logged to the console anyway. So, feel free to remove the try/catch.

It can be reasonable to have a try/catch if any of the following are true and you can do something useful with the error (such as send it to your server logs for examination, or gracefully degrade functionality for the user):

You're awaiting an asynchronous operation that might throw (eg, due to a network problem - very common)
Synchronous code you're calling and don't have control over may throw (pretty unusual)
Despite implementing your own tests, the logic is extremely complicated and you're not sure if there lingering issues (pretty unusual)
You need to break out of a deeply nested function with throw and yield control flow back to a much higher calling function (pretty unusual and somewhat of a code smell - better to test values and return when invalid)

None of the above are going on here.

Instead of filtering inside the loop to check to see if any of the elements in the selectedUserListOP have a matching StudentScheduleUsrID, it would be more elegant and less computationally complex to construct a Set of all the StudentScheduleUsrIDs in the selectedUserListOP beforehand. Then, all you need to do inside the loop is check whether that set .has it:

$scope.selectAllProctoringUser = function(checked) {
  const selectedUserStudentIds = new Set(
    $scope.selectedUserListOP.map(
      user => user.StudentScheduleUsrID
    )
  );
  $scope.scheduleUsers.lstOnlineProctoring.forEach(user => {
    user.selected = checked;
    if (checked) {
      if (!selectedUserStudentIds.has(user.StudentScheduleUsrID)) {
        $scope.selectedUserListOP.push(x);
      }
    } else {
      const selectedUserIndex = $scope.selectedUserListOP.findIndex(
        selectedUser => selectedUser.StudentScheduleUsrID === user.StudentScheduleUsrID
      );
      if (selectedUserIndex !== -1) {
        $scope.selectedUserListOP.splice(selectedUserIndex, 1);
      }
    }
  });
}

If you did have to iterate over the array there, instead of if (someArr.filter(...).length == 0), it would be better to

Use strict equality with ===, not loose equality (consider using a linter)
To check whether every items in an array passes a test (or doesn't pass a test), use .every or .some - don't use .filter to construct a new array only to check its length. Eg:

if ($scope.selectedUserListOP.every(m => m.StudentScheduleUsrID !== x.StudentScheduleUsrID))


Review

Adhere PEP8

functions and variable should be snake_case
Avoid multiple statements on one line

if len(a) == 0: return -1

Indentation matters, and an indentation of 4 spaces is the standard

You don't need all these guard clauses

if len(a) == 0: return -1
if len(a) == 1: return -1
if len(a) == 2 and a[0] == a[1]: return a[0]

The else: does nothing here, only adds an extra indentation level
When you need both the index and the item it is better to enumerate!

for x in (range(len(b)-1)):

For timing, see the Time complexity for python

You use some expensive operations while this can be done is a single loop

.sort() O(n log n)
.index() is O(n)

Note: Look for example at vnp's solution


Refactor two jQuery filter functions into one function

You'll have the following two inputs in your HTML.

<input id="filterInput1" />
<input id="filterInput2" />

Then you can wire them both up together, or split it into separate assignments:

$('#filterInput1, #filterInput2').each(function () {
    $(this).keyup(function () {
        filter(this);
    });
});

Finally, check the ID of the element that triggered the function call to see what list you should be trying to highlight:

function filter(element) {
    var value = $(element).val(),
        selector;

    if (element.id === 'filterInput1') {
        selector = '.pdfList';
    } else if (element.id === 'filterInput2') {
        selector = '.pdfList2';
    } else {
        return; // Or throw an error, whatever you feel is more appropriate.
    }

    // Now the dropdown selector is stored in the variable, and will change which
    // it is looking at depending on who called it.
    $(selector + " > li").each(function (){
        if ($(this).text().indexOf(value) > -1) {
                $(this).show();
        } else {
            $(this).hide();
        }
    });
}


API calls organization in Ionic (Angular) application

Your approach is already pretty good.

What I would do to improve your code is the following:

Use a config/constants.ts file for your constants.
Generate two providers (using ionic g provider <providername>).
In the first provider put all the route related code (I allways call it server-communication.ts).
In the second provider put all the logic (I allways call it app-data.ts).
Import the second provider in all the pages where it is needed.

Here is short example:

constants.ts:

/*
 * SERVER
 */
export const AUTH = "Authorization",
  TOKEN_PREFIX = "Token ",
  SERVER_ADDRESS = "https://myserver.com/api/";
/*
 * ROUTES
 */
export const ROUTE_LOGIN = "login/",
  ROUTE_FACEBOOK = "social/facebook/",
  ROUTE_REGISTER = "register/";
// Go on with all the other constants you might need.

server-communication.ts:

import { Injectable } from "@angular/core";
import { Http, Headers, RequestOptions } from "@angular/http";
import "rxjs/add/operator/map";

import {
  SERVER_ADDRESS,
  TOKEN_PREFIX,
  ROUTE_LOGIN,
  ROUTE_FACEBOOK,
  ROUTE_REGISTER
} from "../../config/constants";

@Injectable()
export class ServerCommunicationProvider {
  constructor(private http: Http) {}

authenticate(credentials) {
    return this.http
      .post(SERVER_ADDRESS + ROUTE_LOGIN, credentials)
      .map(res => res.json());
  }

  registerUser(credentials) {
    return this.http
      .post(SERVER_ADDRESS + ROUTE_REGISTER, credentials)
      .map(res => res.json());
  }
  // Go on with your other routes.

  // If you need to specify more data about the request do it like this:
  getObject(objectID: number): Promise<any> {
    return new Promise((resolve, reject) => {
      this.http
        .get(SERVER_ADDRESS + ROUTE_OBJECT + objectId, this.getHttpHeader())
        .subscribe(
          data => {
            resolve(data.json());
          },
          err => {
            console.log(err);
            reject(err);
          }
        );
    });
  }

  //Getting the correct format for the authorization header
  getHttpHeader(): RequestOptions {
    return new RequestOptions({
      headers: new Headers({
        Authorization: TOKEN_PREFIX + this.storageProv.userToken,
        "content-Type": "application/json",
        Accept: "application/json"
      })
    });
  }

And then utilize those appdata.ts:

import { Injectable } from "@angular/core";
import { ServerCommunicationProvider } from "../server-communication/server-communication";

@Injectable()
export class AppDataProvider {
  constructor(
    private serverProv: ServerCommunicationProvider
  ) {}

login(email: string, password: string): void {
    this.loadingProv.authLoading();
    let credentials = {
      username: email,
      password: password
    };
    this.serverProv.authenticate(credentials).subscribe(
      res => {
      // Your login logic here
      },
      err => {
      // What happens when user can't log in here.
      }
    );
  }
  // More functions with logic for your routes.


Hacker Rank Challenge : Find count of substrings which are special palindrome

This

#include <bits/stdc++.h>
using namespace std;

is given by the submission template from HackerRank (so it is not your fault),
but note that both lines are generally considered as bad practice.
See for example

Why should I not #include <bits/stdc++.h>?
Why is “using namespace std” considered bad practice?

on Stack Overflow.

With respect to your

long substrCount(int n, string s)

function:

The outer while loop could be made a for loop as well – why should it
be different from the inner for(long int ...) loop?
The proper data type for string lengths and indices is string::size_type
aka size_t.

One step to increase the efficiency would be to avoid the creation (and reversal)
of the additional strings sub and rev_sub. All tests can be done directly on
the original string s. As an example,

if (sub[j] != c || rev_sub[j] != c)

is equivalent to

if (s[i + j] != c || s[i + length_sub - 1 - j] != c)

Your method checks all \$ n (n-1)/2 \$ substrings of length 2 or more if
it is a “special palindromic string.”. The following approach seems more
efficient to me:

The number of substrings with all identical characters (e.g. "aaa")
can be determined with a single traversal of the string. All sequences
of \$ k \$ contiguous identical characters contain \$ k(k+1)/2 \$
substrings with identical characters.
To determine the number of substrings where characters except the middle one
are the same (e.g. "aadaa") traverse the string, and check for each character
(e.g. "d") how many identical characters exist to the left and to the right
of this character.

Example: The string "mnonopoo" has the following sequences of contiguous
identical characters

m n o n o p oo

which gives a total

1+1+1+1+1+1+3 = 9

substrings with all identical characters. The number of substrings where
all characters except the middle one are the same around each character are

m n o n o p o o
0+0+1+1+0+1+0+0 = 3


For operations that don't support cancellation themselves, You can combine Task.WhenAny() with Task.Delay():

Async Function TryAwait(Of T)(target As Task(Of T), delay as Integer) As Task(Of T)
    Dim completed = Await Task.WhenAny(target, Task.Delay(delay))
    If completed Is target Then
        Return Await target
    End If

    Throw New TimeoutException()
End Function

Usage:

Dim nextCommand = Await TryAwait(reader.ReadLineAsync(), 2000)


Pandas replace rare values in a pipeline

You could use scikit-learn's TransformerMixin which provides an implementation of fit_transform for you (its implementation is available here for interest).

I'd consider renaming RemoveScarceValuesFeatureEngineer to something that fits a bit more with other classes in scikit-learn. How about RareValueTransformer instead?

What do you want to happen if an unseen value is transformed? Take, for example

sample_test = pd.DataFrame([{"a": 1, "s": "a"}, {"a": 2, "s": "b"}])
print(sample_test)
print(rssfe.transform(sample_test))

This raises a KeyError, which isn't what I expected. I'd either rework your code to ignore unseen values, or return a nicer error if this is what you want to happen. To me, ignoring seems more reasonable, but it's up to you! Making some unit tests would give you more confidence in cases like this, too.
A pedantic aside: you have a typo of 'occurrence' in min_occurences, which is easily amended.


You should realize that if \$i\$ is a divisor of \$a\$, then so is \$a / i\$. This way you get two divisors per found divisor.

In the same vein, you only need to search up to \$\sqrt{n}\$, because all factors above that have already been found as the second divisor.

So your code would become:

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

int main(){
        int a,i;
        scanf("%d",&a);
        int bound = ceil(sqrt(a));
        for(i=1; i <= bound; i++) {
                if(a%i==0) {
                        printf("%d\n",i);
                        if(a/i != i) printf("%d\n", a/i);
                }
        }
        printf("%d\n",a);
        return 0;
}


Given two strings, determine if one is a permutation of the other

This code is broken.

// This creates an array with size elements all set to zero.
// But your string (in the examples) are not more than 4 long.
// So the largest vector is 4 elements long.
vector<int> s1_set(s1.size());

// Here x is char.
for (const auto& x : s1) {
// It is undefined if char is signed or unsigned.
// so the range of values for x is
//       0 -> 255
// or -127 -> 128
//
// Either way the range is well beyond the size of
// the array defined above.


You may run into a problem if a track has more than one artist.

You'd have to enter the track for each artist again, or you'd have to only use the first artist, or you'd have to create a new "combined" artist.

Why not omit the artist→track hierarchy?

<collection>
  <track>
    <title>Thriller</title>
    <artist>Michael Jackson</artist>
  </track>
  <track>
    <title>Hey Jude</title>
    <artist>The Beatles</artist>
  </track>
</collection>

Benefits:

You can add more metadata for tracks (composer, album, etc.)
You can add tracks without title and/or artist

If different artists may have the same name, you'd need a way to differentiate the artist elements; e.g. by using id with an ID of an artist database.


I think the nicest thing to do is to create a function which separates the counting of the elements of an array from the array itself.  For example, right now you have a "counting procedure", which basically looks like this:

public static boolean count(int[] values) {

   int count = 0;
   int currentElement = values[0];
   for(int i = 0; i < values.length; i++) {
     if (currentElement == values[i])
       count++;
     currentElement = values[i];
   }
   return (count >= 4);
}

Once you've separated this out, counting the rows is as simple as

int rows = values.length
int cols = values[0].length
for (int i = 0;i < rows; i++)
  if (count(values[i]))
    return true;

Counting the columns like this is a little trickier.  I think the cleanest way to do this is to actually allocate a temporary array and fill it with the correct values.  Note that this isn't faster than what you've recommended -- it's only prettier.

int[] tmpArray = new int[rows];
for (int j = 0; j < cols; i++) {
  for (int i = 0; i < rows; i++)
    tmpArray[i] = values[i][j];
  if (count(tmpArray))
    return true;
}

It's not actually clear to me at all if your diagonal counting code works, but now we have a nice tool to write it intuitively.  What's tricky is I cannot see the four distinct diagonals you're counting, and what parts of the code handle each one.  With the following approach, we do each one individually:

int diagonal_length = min(rows, cols)
tmpArray = new int[diagonal_length];

//first major diagonal
for(int i = 0; i < diagonal_length;i++)
  tmpArray[i] = values[i][i];
if (count(tmpArray))
  return true;

//second major diagonal
for(int i = 0; i < diagonal_length;i++)
  tmpArray[i] = values[i][cols - 1 - i];
if (count(tmpArray))
  return true;

//first minor diagonal
for(int i = 0; i < diagonal_length;i++)
  tmpArray[i] = values[rows - 1 - i][i];
if (count(tmpArray))
  return true;

//second minor diagonal
for(int i = 0; i < diagonal_length;i++)
  tmpArray[i] = values[rows - 1 - i][cols - 1 - i];
if (count(tmpArray))
  return true;

return false;

The big advantage of this proposed rewrite is not in speed or algorithms, simply a matter of code clarity.  It's easier to test and examine this code; e.g. the count function can be tested separately.  You can also easily print out the tmpArray variable to check that the right thing is being counted at the beginning of count(), and this is a must if you want to be sure this code is working properly.

Important note:: I haven't tested any of this code yet!!  Errors are fairly likely, but the idea should work either way.


Loading articles dynamically on page change

One big step to opimize your code is to cache your jQuery objects.

var $layer = $('#layer');

You can also chain your method calls

$layer.css({ height: '30px' }).fadeIn(300).append('hi');

Also, make use of context

var $layerLoading = $('.layerLoading');
$layerLoading.fadeOut("slow",function(){
  //$(".layerloading").remove();
    // instead do - this refers to the context which is '.layerloading' in this case
  $(this).remove();
});


Populate dropdown B on selection in dropdown A

Don't use a <table> element to "hide" extra data in your markup. It's a terribly complex way of doing things, and it's pretty hacky to have large, hidden elements like that (and not a good semantic use of a table either).
Be consistent with your naming; Sublist is capitalized, but choices is lowercase.
Alphabetize the city names :)

With regard the JS: It's ok given the context, but the use of the table is the real culprit. Still there's at least 1 thing you should change:

Don't call the populate* before the page has loaded (you wait before adding the change handler, because the #ParentList element might not have loaded yet; that same timing issue would cause the populateParentlist function to fail)

Now, ideally, the city list should be available as JSON or something (loaded from the server for instance), but if you're going to store it in the HTML, you might as well use a select and subdivide it using optgroup elements:

<select id="cities">
  <optgroup label="Poland">
    <option selected>Krakow</option>
    <option>Warszawa</option>
  </optgroup>
  ...

As a bonus, the list will work even without javascript. And you can set the initially-selected city in the HTML.

It also contains all the option elements you'll need for the city dropdown; we just need to convert the optgroups into options for a 2nd dropdown:

$(function () { // wait for page to load
    var cityDropdown = $("#cities"),
        countryDropdown = $('<select></select>'), // create a country dropdown
        countries = []; // ordered list of countries

    // parse the nested dropdown
    cityDropdown.children().each(function () {
        var group = $(this),
            countryName = group.attr('label'),
            option;

        // create an option for the country
        option = $('<option></option>').text(countryName);

        // store the associated city options
        option.data('cities', group.children());

        // check if the country should be selected
        if( group.find(':selected').length > 0 ) {
            option.prop('selected', true);
        }

        // add the country to the dropdown
        countryDropdown.append(option);
    });

    // add the country dropdown to the page
    cityDropdown.before(countryDropdown);

    // this function updates the city dropdown based on the selected country
    function updateCities() {
        var country = countryDropdown.find(':selected');
        cityDropdown.empty().append(country.data('cities'));
    }

    // call the function to set the initial cities
    updateCities();

    // and add the change handler
    countryDropdown.on('change', updateCities);
});

Here's a demo


Is there a performance difference using AS keyword in SQL?

I wouldn't expect much if any noticeable overhead as all that is doing is aliasing the name of the column in the result set.

The question I would ask however, is why it's being done in the first place? All I can think of is to prevent the code which uses the query breaking if a column is renamed (as long as the alias isn't changed).


Yes, both methods seem to work correctly, your code definately implements
mergesort :).

Your code, however, seems like somewhat direct translation of C implementation, as it hardly
uses Ruby idioms, what hurts readability.
Ruby Arrays know they size (#length, #empty? etc.), so you don't need to keep track of it.
So, splitting the array could very well be done like:

# _sort now only accepts one argument, values
mid = values.length / 2
left = _sort(values[0...mid])

Such approach would of course require you to rewrite #merge, but it would
be worth it, as it is more readable to work on actual arrays than criptic numbers. This would also probably eliminate need for Validator module to exist (and Comparator doesn't seem to be used anyways). You should always aim at using idiomatic Ruby, because reader of your code seeing something C-like will waste much time thinking "why didn't <insert idiom> suffice here?" to analyze your code.

If someone passes wierd value to your #sort (like, a Fixnum), it will raise cryptic errors
like NoMethodError: undefined method 'empty?'. You should handle such errors by rescueing them
and raising more descriptive ones (in this case, ArgumentError probably) so they are easier
to analyze. #merge should be handled separately, as NoMethodError there likely means
something else.

def invalid_to_sort?(values)
  # I don't think nil deserves special treatment here though, it should
  #   raise ArgumentError like all non-arrays. This seems to come from
  #   C where arrays are pointers and NULL is pointer too, so they are
  #   hard to distinguish without direct check
  values.nil? || values.empty? || values.one?
rescue NoMethodError
  raise ArgumentError, "some descriptive message"
end

Your current code structure introduces somewhat odd (non-Ruby) interface.

sorter = Merge::Sort.new
sorted = sorter.sort(array)

Following example of standard library, Rubyish thing to do would be something like:

array.merge_sort! # destructive
# and
sorted = array.merge_sort # safe

This is easily achieved by making safe variant work on a duplicate:

class Array
  def merge_sort!
    # ... code code code ...
  end

  def merge_sort
    dup.merge_sort!
  end
end

Of course, patching standard classes is dangerous, but as various examples (most notably Rails)
prove, also extremely usefull. If you are concerned, you could use refinements
, but those are somewhat experimental. However, as you are adding new functionality (and not replacing existing one)
only real danger is conflicting with some other patch, so I'd say go for it.

In any case, there is no need to introduce a class, more so one that you need to instantiate.
If you want external sorting method (to avoid patching Array), just make it part of a module
to keep things simple, i.e:

module Sort
  def self.merge_sort(values)
    # ... code code code ...
  end
end

sorted = Sort.merge_sort(array)

Now I know from your previous question that you come from Java, so you like to instantiate alot ;)
but in Ruby we work somewhat differently, here a module/class is proper object that works like anything else,
not some sort ofmetadata-thingy, so it's easy to use them with dependency injection and what-not,
usually there is no need to create instances just to call some code :)


You are right.  You have way too much duplication there.  And you are on the right track with your refactored version but I don't think it goes far enough.

Right now if you want to add a new color you have to do the following.

Add a new div to the color buttons with a unique id.
Add style rules (background) to that div with the color.
Add a button click rule that selects the button by id.
Change the brush color making sure it matches the background done in #2.

With your refactoring you would change this to:

Add a new div to the color buttons with a unique id.
Add style rules (background) to that div with the color.
Add a value to the div button.
Add the id to the button click function.

So you might have made the code shorter but didn't really make it much easier to maintain.

So, how can we get this shorter.  Well, we can select elements by class name.  So instead of using the id we just use class names.

    ...

And your script becomes:

$('#colors .brush-selector').click(function() {
    brush.setColor(this.data('val'));
});

Now to add a new color you have the following steps:

Add a new div to the color buttons with a unique id.
Add style rules (background) to that div with the color.
Add a value to the div button that matches the color.

Better, but we are still duplicating info.  The background color and data-val fields are the same.  And if we accidentally type one wrong then we have incorrect behavior.  So why don't we just use the background-color of the div.

    ...

$('#colors .brush-selector').click(function() {
    brush.setColor(this.css('background-color'));
});

That takes our steps down to:

Add a new div to the color buttons.
Add style rules (background) to that div with the color.

Which is pretty good.  Basically one step to adjust colors.  Just adjust the divs.

There are further steps you could take that I won't go into detail but leave to you.

If you knew the only divs in the #colors elements were brush selectors you could remove the class altogether and just select the divs within #colors $(#colors div).

You could also create a javascript array of allowed colors.  Then create the buttons using the array.  Then the only step you would need would be to adjust the colors in that array.  This would also allow you to select colors dynamically since that array could come from anywhere.


Max-Heap arraylist based priority queue written in Java

Don't override with the default behavior

    private ArrayList<Pair<String, Integer>> heapArray;

    public FPPriorityQueue(){
        super();
        heapArray = new ArrayList<Pair<String, Integer>>();
    }

This could be simply

    private List<Pair<String, Integer>> heap = new ArrayList<>();

You don't need a custom constructor.  This will declare and initialize it.

I prefer the name heap to heapArray.  It's simpler and more accurate.

In the latest Java, you don't have to specify Pair<String, Integer> twice.  It's smart enough to figure it out if you just say <>.

In general, it is preferable to use interfaces as types rather than implementations.  Among other reasons, it allows you to change implementations easily.

Huh?

public boolean empty(){
    return true;
}

What's this do?  If it was called isEmpty, I'd think it was returning whether or not the heap was empty.  As is, I would expect empty to do something, perhaps clear the heap.

Whatever it's supposed to do, it doesn't seem to be doing it.

Don't rely on your inputs

private void shiftUp(int index){

    int parentIndex;

    if(index != 1){
        parentIndex = index/2;
        int childData = heapArray.get(index).getValue();
        int parentData = getParentData(index);

        if(parentData < childData){
            swap(parentIndex,index);
            shiftUp(parentIndex);
        }
    }
}

What if index is less than 1?

private void shiftUp(int index) {
    if (index > 1) {
        int parentIndex = index / 2;
        int parentData = heap.get(parentIndex).getValue();
        int childData = heap.get(index).getValue();

        if (parentData < childData) {
            swap(parentIndex, index);
            shiftUp(parentIndex);
        }
    }
}

Changing != to > handles index values less than 1.  And it's free.  We're already doing a comparison.  Why not do the better one?

We don't need getParentData.  We have to calculate parentIndex anyway, so we can just fetch directly.

I added some extra whitespace, because I find code easier to read that way.

Don't do unnecessary work

public void insert(String key, Integer value){

    Pair<String, Integer> element = new Pair<String, Integer>(key,value);
    Pair<String, Integer> nullElement = new Pair<String, Integer>("NULL",0);
    //add the element to the last position in the list
    if(heapArray.isEmpty()){
        heapArray.add(0,nullElement);
        heapArray.add(1,element);
    }
    else{
        heapArray.add(heapArray.size(), element);
        shiftUp(heapArray.size()-1);
    }

}

We don't need nullElement every time.  Consider

public void insert(String key, Integer value) {
    Pair<String, Integer> element = new Pair<>(key,value);

    //add the element to the last position in the list
    if (heapArray.isEmpty()) {
        heap.add(new Pair<String, Integer>("NULL", 0));
        heap.add(element);
    } else {
        heap.add(element);
        shiftUp(heap.size()-1);
    }
}

We don't have to explicitly say that we want to put things in the last position.  That's how the single argument add works already.

I personally am not crazy about the half-cuddled else {, and it's not the Java standard.  So I fully cuddled:  } else {.

We only create nullElement in the one edge case now.  The rest of the time, we don't bother.  But we can actually do better.  Consider

public FPPriorityQueue() {
    heap.add(new Pair<String, Integer>("NULL", 0));
}

This will create the null element the one time you need it, at the beginning.  And this is the kind of thing that you do in a constructor.

You don't need the explicit super().  Java's smart enough to do that for you when you're just calling the default constructor.

Now we can just say

    public void insert(String key, Integer value) {
       //add the element to the last position in the list
        heap.add(new Pair<String, Integer>(key, value));
        shiftUp(heap.size() - 1);
    }

It adds to the end of the list.

And because we previously changed shiftUp to handle the empty case, we don't need to prevent calling shiftUp in that case.

I'm not sure that we need the null element.  The math is a little more complex without it but still doable.

Don't Repeat Yourself

private void shiftDown(int index){

    if(heapArray.size()> (index*2)+1) {
        int leftChildValue = heapArray.get(index * 2).getValue();
        int rightChildValue = heapArray.get((index * 2) + 1).getValue();

        int indexValue = heapArray.get(index).getValue();

        if(indexValue < leftChildValue || indexValue < rightChildValue)
        {
            if(leftChildValue > rightChildValue){
                int leftChildIndex = index*2;
                swap(index,leftChildIndex);
                shiftDown(leftChildIndex);
            }
            else{
                int rightChildIndex = (index*2)+1;
                swap(index,rightChildIndex);
                shiftDown(rightChildIndex);
            }
        }
    }

}

Consider

private void shiftDown(int index) {
    int left = index * 2;
    int right = left + 1;
    if (heap.size() > right) {
        int leftChildValue = heap.get(left).getValue();
        int rightChildValue = heap.get(right).getValue();

        int indexValue = heap.get(index).getValue();

        if (indexValue < leftChildValue || indexValue < rightChildValue) {
            if (leftChildValue > rightChildValue) {
                swap(index, left);
                shiftDown(left);
            } else {
                swap(index, right);
                shiftDown(right);
            }
        }
    }
}

This way we set left and right before using them.  So we can't accidentally pick the wrong value one place.

Don't reinvent the wheel

If this is an exercise to improve your understanding of how a heap works, that's fine.  There's a reinvent-the-wheel tag that you can use to let us know.  But if you just needed to solve the problem, an easier way is to use a PriorityQueue with a custom Comparator or a custom type that extends Comparable.  Then Java will handle all the fiddly bits of managing the heap.

public class PairComparator implements Comparator<Pair<String, Integer>> {

    public int compare(Pair<String, Integer> a, Pair<String, Integer> b) {
        return b.getValue().compareTo(a.getValue());
    }

}

If the order is backwards, switch a and b in the return line.

I forget if you have to implement equals as well.

You'd use this like

        PriorityQueue<Pair<String, Integer>> queue = new PriorityQueue<>(new PairComparator());

Then you can call queue.add and queue.poll to insert and remove items.

You don't provide test code, so I haven't tried to compile and test any of this.  Beware of typos, etc.


How many of a particular item of clothing do I need?

For a beginner to go your program is good. You have obviously read up on flag handling, and you've got a grasp on the pointers. I have come to like the flag processing in go (though having previously learned/understood getopt and written my own library in Java, I feel like go should allow more powerful commandline handling).

Flags

So, having said you have a good grasp on those concepts, I am going to recommend that you change the flag handling (and as a consequence, you remove the pointers).

In addition, you should be putting in the number of days to simulate, and perhaps the starting date, as flags too.

So, flag functions include both ...Ptr and ...Var variants. I recommend using the ...Var variants where you can. Your code:

numberOftshirtsPtr := flag.Int("shirts", 9, "a int number of tshirts")
thursdayPtr := flag.Bool("thursday", true, "a bool use Thursday")
dryingPtr := flag.Bool("drying", true, "a bool use drying")
flag.Parse()

I would write like:

numberOftshirts := 9
doThursdays := true
doDrying := true

flag.IntVar(&numberOftshirts, "shirts", numberOftshirts, "the number of tshirts")
flag.BoolVar(&doThursdays, "thursday", doThursdays, "use Thursday")
flag.BoolVar(&doDrying, "drying", doDrying, "use drying")
flag.Parse()

By taking the address of the var and giving it to flag, we can then use the variables as-is later without having to keep the pointer handling at all, so code like:

var clean, minClean = *numberOftshirtsPtr, *numberOftshirtsPtr

becomes:

var clean, minClean = numberOftshirts, numberOftshirts

Note that, by convention, using hungarian notation in go is not good code-style. You should not suffix pointer variables with Ptr. A pointer to an int containing the number of T-Shirts is still numberOftshirts and not numberOftshirtsPtr

OK, so the above code changes the flag handling to be Var-based, and it reads easier, and removes all pointer references later.

I would also add flags for the starting date, and number of days to simulate.

Washing Day

Your washingday function is a good idea, but you are doing string processing in places where the time library has better options to offer. Note that time has constantes for the days-of-week, and those constants are declared as a Weekday type, and that type has a String() function available: https://golang.org/pkg/time/#Weekday - what this means is that you can avoid the string-conversions in the function. I personally would probably use the String() option too to print the days. Actually, I would remove the println from the function because it is making the function do too much - (computation and presentation). I would have your function as:

func isWashingDay(today time.Time, doThursday bool) bool {

    if today.Weekday() == time.Monday {
        //fmt.Printf("%v!\n", time.Monday)
        return true
    }

    if doThursday && today.Weekday() == time.Thursday {
        _, week := today.ISOWeek()
        if even(week) {
            //fmt.Printf("%v!\n", time.Thursday)
            return true
        }
    }

    return false
}

Note that I no longer have any raw text in there (it's all time variables, etc), and also note that I no longer have if ... else ... statements. When the if part of a condition always has a return in it, there's no need for the else at all.

Main

Your program is essentially contained inside the main-method. This makes the main method bulky, and the code is not reusable. Even in example progams and learning exercises, you should try to break your code in to functions that can be run, and tested independently. Go has a strong toolset related to unit-tests and benchmarks, and you should get in the habit of creating small, independent functions that are easy to process in the testing systems too.

One way to improve the bulkiness of the main method is to declare a struct to contain the state of a given day. You can get clever with some function processing too. I would create a state struct, and use it for a bunch of the logic....

type ClothesState struct {
    day     time.Time
    clean   int
    dirty   int
    washing int
    drying  int
}

In addition, to separate out your printing of the state, I would create a bit of a string helper function... I'll explain it later, but show you here, now:

func format(day, clean, dirty, washing, drying interface{}) string {
    return fmt.Sprintf("%-11v| %-2v| %-2v| %-2v| %2-v", day, clean, dirty, washing, drying)
}

With this function, we can add a String() method to our state too that uses it:

func (cs ClothesState) String() string {
    return format(cs.day.Format("2006-01-02"), cs.clean, cs.dirty, cs.washing, cs.drying)
}

Now we can use the %v (or %s) style fmt to print the state:

fmt.Printf("%v\n", state)

Further, I would take the state-tansition logic and make it a method on the struct too:

func (cs ClothesState) Advance(doDrying, doThursdays bool) ClothesState {
    tomorrow := cs.day.AddDate(0, 0, 1)

    clean := cs.clean
    clean += cs.drying

    drying := cs.washing
    if !doDrying {
        // take all the drying directly in to clean
        clean += drying
        drying = 0
    }

    washing := 0
    dirty := cs.dirty
    if isWashingDay(tomorrow, doThursdays) {
        washing = dirty
        dirty = 0
    }

    clean--
    dirty++

    return ClothesState{
        day:     tomorrow,
        clean:   clean,
        dirty:   dirty,
        washing: washing,
        drying:  drying,
    }

}

Now you have an immutable state struct that you can then advance through the daily logic. Each advance returns a new state.

Conclusion

You've made a great start in to Go. I encourage the use of structs to localize logic, the use of smaller, single-purpose functions, and separating the presentation code (printlns) from the calculation code.

I have taken your code and re-worked it in a way I would consider an improvement, and I have tweaked the starting state to match your logic (and also kept the println statements in the isWashingDay so that it matches the output of your program.

Have a look, and see how the logic is separated, how the flags are used, and so on: https://play.golang.org/p/B62HmIoxNc

package main

import (
    "flag"
    "fmt"
    "time"
)

func even(number int) bool {
    return number%2 == 0
}

func isWashingDay(today time.Time, doThursday bool) bool {

    if today.Weekday() == time.Monday {
        fmt.Printf("%v!\n", time.Monday)
        return true
    }

    if doThursday && today.Weekday() == time.Thursday {
        _, week := today.ISOWeek()
        if even(week) {
            fmt.Printf("%v!\n", time.Thursday)
            return true
        }
    }

    return false
}

func format(day, clean, dirty, washing, drying interface{}) string {
    return fmt.Sprintf("%-11v| %-2v| %-2v| %-2v| %-2v", day, clean, dirty, washing, drying)
}

type ClothesState struct {
    day     time.Time
    clean   int
    dirty   int
    washing int
    drying  int
}

func (cs ClothesState) String() string {
    return format(cs.day.Format("2006-01-02"), cs.clean, cs.dirty, cs.washing, cs.drying)
}

func (cs ClothesState) Advance(doDrying, doThursdays bool) ClothesState {
    tomorrow := cs.day.AddDate(0, 0, 1)

    clean := cs.clean
    clean += cs.drying

    drying := cs.washing
    if !doDrying {
        // take all the drying directly in to clean
        clean += drying
        drying = 0
    }

    washing := 0
    dirty := cs.dirty
    if isWashingDay(tomorrow, doThursdays) {
        washing = dirty
        dirty = 0
    }

    clean--
    dirty++

    return ClothesState{
        day:     tomorrow,
        clean:   clean,
        dirty:   dirty,
        washing: washing,
        drying:  drying,
    }

}

func main() {
    numberOftshirts := 9
    doThursdays := true
    doDrying := true

    flag.IntVar(&numberOftshirts, "shirts", numberOftshirts, "the number of tshirts")
    flag.BoolVar(&doThursdays, "thursday", doThursdays, "use Thursday")
    flag.BoolVar(&doDrying, "drying", doDrying, "use drying")
    flag.Parse()

    today, _ := time.Parse(time.RFC3339, "2017-02-06T00:00:00+00:00")

    // Set the state with 1 dirty shirt to match OP logic
    state := ClothesState{
        day:   today,
        clean: numberOftshirts - 1,
        dirty: 1,
    }

    minClean := state.clean

    fmt.Println(format("Date", "C", "D", "W", "Y"))
    fmt.Printf("%v\n", state)

    testDays := 365
    for i := 0; i < testDays; i++ {
        state = state.Advance(doDrying, doThursdays)
        fmt.Printf("%v\n", state)

        if state.clean < minClean {
            minClean = state.clean
        }

    }

    fmt.Println("Total days:", testDays)
    fmt.Println("Minimum clean shirts:", minClean)
}


Unwinding shortened URLs with Python, SQLite, and multithreading

__

There is liitle need for the __. A single _ should suffice to make people clear it's a private attribute. If they really want to use it, __ won't stop the access

Linelength

Especially the lines with queries are too long. Can't you make those queries multiline?

From:

def updateUnwoundUrl(self, url_starting, url_unwound):
    self.__cursor.execute(
        'UPDATE url SET url_unwound = ? WHERE url_starting = ?', (url_unwound, url_starting))
    self.__conn.commit()
    return self.__cursor

to:

def updateUnwoundUrl(self, url_starting, url_unwound):
    self.__cursor.execute(
        '''UPDATE url
           SET url_unwound = ?
           WHERE url_starting = ?
        '''
        , (url_unwound, url_starting)
    )
    self.__conn.commit()
    return self.__cursor

Hoist the IO

If ever you want to change the db format to something else, you will need to change the internals of the code and how the my_db_path is made.

To change this, I would follow the tips from this talk.

Database path

def unwindUrls(workers=100, request_timeout=10):
    relative_path = os.path.dirname(__file__)
    my_db_path = os.path.join(relative_path, 'database', 'my.db')

First, I would use my_db_path to handle filepaths.

Secondly I would add relative_path as an an argument, with Path('.') as default argument, this way you can specify the path.

def unwindUrls(workers=100, request_timeout=10):
    relative_path = os.path.dirname(__file__)
    my_db_path = os.path.join(relative_path, 'database', 'my.db')
    with MyDatabase(my_db_path) as my_db:

...
if __name__ == '__main__':
    unwindUrls()

To:

def unwindUrls(my_db, workers=100, request_timeout=10):

...
if __name__ == '__main__':
    my_db_path = pathlib.Path('.') / 'database' / 'my.db'
    with MyDatabase(my_db_path) as my_db:
        unwindUrls(my_db)

chunk_iter

def chunk_iter(iterable, chunk_size):
    it = iter(iterable)
    while True:
        chunk = tuple(next(it) for _ in range(chunk_size))
        if not chunk:
            break
        yield chunk

raises a Warning in Python 3.6

  C:\miniconda3\envs\test_env\lib\site-packages\ipykernel_launcher.py:4:
  DeprecationWarning: generator 'chunk_iter..' raised
  StopIteration   after removing the cwd from sys.path.

Better to use itertools.islice

def chunk_iter(iterable, chunk_size):
    it = iter(iterable)
    while True:
        chunk = tuple(islice(it, chunk_size))
        if not chunk:
            return
        yield chunk

Exception

a few time you use except Exception. This is way too broad. You should specify which Exceptions you want to catch


Determine numeric month based on actual moth

Just use an array.

var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];

var m = months.indexOf('May');  // 4


Which Java string value is preferred to return: blank or null?

The general question you ask "Which is better, "" or null?" is off-topic for CodeReview, but your code snippet has a number of reviewable items....

Regex Usage

Compiled Pattern performance

  String regex = "http://(.*)/consolidate";
  Pattern pattern = Pattern.compile(regex);
  Matcher matcher = pattern.matcher(uri);
  if(matcher.find()){
      result = matcher.group(1);
  }

This snippet makes it look like you know what you are doing, with the Pattern compile, etc. But, there is no performance benefit in the way you have done this. Compiled Java Pattern instances are thread-safe, and compiling them for one-time-use is not useful. It is common practice to make the Pattern a static-final field:

private static final Pattern MYPATTERN = Pattern.compile("http://(.*)/consolidate");

Then you can re-use that compiled pattern as much as you like, in any method, in any thread, like:

  Matcher matcher = MYPATTERN.matcher(uri);
  if(matcher.find()){
      result = matcher.group(1);
  }

find vs. matches

Now, matcher.find() and matcher.matches() are different methods.

find() will scan the input looking for any point inside the input where the pattern will match....
matches() does just one scan, and it matches the entire input string against the entire pattern.

With the input junkhttp://a/consolidate/junk:

find() will find your pattern
matches() will not find your pattern

The pattern

Now, as for the actual Regex... it appears that you want your pattern to match the HTTP 'host' against which you have the 'consolidate' path.... but, your pattern will match a lot of things which I would consider to be unexpected... for example, your pattern will return the following:

http://myhost/consolidate   from  http://http://myhost/consolidate/consolidate
myhost/consolidate          from  http://myhost/consolidate/consolidate
myhost:8080                 from  http://myhost:8080/consolidate
                            from  http:///consolidate

Each of the above input values will produce unexpected results.

Correct Regex

There is not a correct regex for matching URL's.... even if a regex appears that it will match, it is still not the correct solution ;-)

Solution

Use the java.net.URI class to validate your input. I have an example here, where I choose to return null if there is no configured URI, or throw an exception if there is a configured URI and that URI is not a valid value. This would be 'sensible' for many configurations, I expect.

public String getInfo() {
      String urival = clientConfiguration.getUri();
      if (urival == null || urival.isEmpty()) {
          return null;
      }
      try {
          URI uri = new URI(urival);
          return uri.getHost();
      } catch (URISyntaxException e) {
          throw new IllegalStateException("The configured URI is not valid: " + e.getMessage(), e);
      }
}


I find !! and once-used definitions smelly.

A passed around environment like roads might as well open a scope that spans all uses of it.

efficientRoadNetwork roads n = and
  [ edge i j || any (\k -> edge i k && edge k j) [0..n-1]
  | i <- [0..n-1], j <- [0..i-1]
  ] where edge i j = elem [i,j] roads || elem [j,i] roads